text
stringlengths
2
1.04M
meta
dict
package algorithms.imageProcessing; import algorithms.util.ResourceFinder; import algorithms.util.PairIntArray; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import junit.framework.TestCase; /** * * @author nichole */ public class CornersTest extends TestCase { private Logger log = Logger.getLogger(this.getClass().getName()); public CornersTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testProcess() throws Exception { /* objectives: (1) all true corners should be detected (2) no false corners should be detected. (3) corner points should be well localized (4) corner detectors should be robust with respect to noise (5) corner detectors should be efficient */ String fileName = "lena.jpg"; String outFileName = "lena.png"; //fileName = "valve_gaussian.png"; //outFileName = fileName; String filePath = ResourceFinder.findFileInTestResources(fileName); GreyscaleImage img = ImageIOHelper.readImageAsGrayScaleG(filePath); CurvatureScaleSpaceCornerDetector detector = new CurvatureScaleSpaceCornerDetector(img); detector.findCorners(); Image image = ImageIOHelper.readImageAsGrayScale(filePath); List<PairIntArray> edges = detector.getEdgesInOriginalReferenceFrame(); PairIntArray corners = detector.getCornersInOriginalReferenceFrame(); ImageIOHelper.addAlternatingColorCurvesToImage(edges, image); ImageIOHelper.addCurveToImage(corners, image, 2, 2550, 0, 0); String dirPath = ResourceFinder.findDirectory("bin"); String sep = System.getProperty("file.separator"); ImageIOHelper.writeOutputImage(dirPath + sep + "corners_" + outFileName, image); } public static void main(String[] args) { try { CornersTest test = new CornersTest("CornersTest"); test.testProcess(); } catch (Exception e) { System.err.println("ERROR: " + e.getMessage()); } } }
{ "content_hash": "98312de26294d74fbdd11e16d97f5db9", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 81, "avg_line_length": 31.376623376623378, "alnum_prop": 0.6324503311258278, "repo_name": "dukson/curvature-scale-space-corners-and-transformations", "id": "634a07a04b98c21f79b6a921fa15dbbf7717290a", "size": "2416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/algorithms/imageProcessing/CornersTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "36527" }, { "name": "DTrace", "bytes": "10469" }, { "name": "HTML", "bytes": "178627" }, { "name": "Java", "bytes": "1437979" }, { "name": "Shell", "bytes": "1889" } ], "symlink_target": "" }
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **filter** | [**\AnketologClient\Model\SurveyFilter**](SurveyFilter.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "content_hash": "413d647f2e289a62972806bd0f8a2728", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 161, "avg_line_length": 48.285714285714285, "alnum_prop": 0.5621301775147929, "repo_name": "anketolog/AnketologClient-php", "id": "653ab27afc3b0ba57240189e68df7df6ef354229", "size": "380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Model/SurveyReportFilterCustom.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "4908889" }, { "name": "Shell", "bytes": "1663" } ], "symlink_target": "" }
FROM gcr.io/k8s-testimages/kubekins-e2e:latest-master RUN apt-get update && apt-get install -y \ git && \ rm -rf /var/lib/apt/lists/* # Build latest kubemci from HEAD. RUN cd /${GOPATH}/src && \ mkdir -p github.com/GoogleCloudPlatform && \ cd github.com/GoogleCloudPlatform && \ git clone --depth 1 https://github.com/GoogleCloudPlatform/k8s-multicluster-ingress.git && \ cd k8s-multicluster-ingress && \ make build && \ cp kubemci /bin && \ rm -rf /${GOPATH}/src/github.com/GoogleCloudPlatform/k8s-multicluster-ingress
{ "content_hash": "ab96ac5c83dbecfd2447434987d75033", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 96, "avg_line_length": 37.2, "alnum_prop": 0.6792114695340502, "repo_name": "pwittrock/test-infra", "id": "55cf1e690d29550163665561551034a247464b82", "size": "1146", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "images/kubemci/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "26680" }, { "name": "Go", "bytes": "3777108" }, { "name": "HTML", "bytes": "73415" }, { "name": "JavaScript", "bytes": "209470" }, { "name": "Makefile", "bytes": "62520" }, { "name": "Python", "bytes": "993471" }, { "name": "Roff", "bytes": "5462" }, { "name": "Shell", "bytes": "99694" }, { "name": "Smarty", "bytes": "516" } ], "symlink_target": "" }
package team import ( "errors" "sync" "koding/kites/kloud/stack" "koding/kites/kloud/team" "koding/klientctl/ctlcli" "koding/klientctl/endpoint/kloud" ) var DefaultClient = &Client{} // ListOptions are options available for `team list` command. type ListOptions struct { Slug string // Limit to a specific team with a given name. } type Team struct { Name string `json:"name"` } func (t *Team) Valid() error { if t.Name == "" { return errors.New("invalid empty team name") } return nil } type Client struct { Kloud *kloud.Client once sync.Once // for c.init() used Team } func (c *Client) Use(team *Team) { c.init() c.used = *team } func (c *Client) Used() *Team { c.init() return &c.used } // List returns the list of user's teams. func (c *Client) List(opts *ListOptions) ([]*team.Team, error) { c.init() req := &stack.TeamListRequest{} if opts != nil { req.Slug = opts.Slug } resp := stack.TeamListResponse{} if err := c.kloud().Call("team.list", req, &resp); err != nil { return nil, err } return resp.Teams, nil } func (c *Client) Close() (err error) { if c.used.Valid() == nil { err = c.kloud().Cache().SetValue("team.used", &c.used) } return err } func (c *Client) init() { c.once.Do(c.readCache) } func (c *Client) readCache() { // Ignoring read error, if it's non-nil then empty cache is going to // be used instead. _ = c.kloud().Cache().GetValue("team.used", &c.used) // Flush cache on exit. ctlcli.CloseOnExit(c) } func (c *Client) kloud() *kloud.Client { if c.Kloud != nil { return c.Kloud } return kloud.DefaultClient } func Use(team *Team) { DefaultClient.Use(team) } func Used() *Team { return DefaultClient.Used() } func List(opts *ListOptions) ([]*team.Team, error) { return DefaultClient.List(opts) }
{ "content_hash": "000224e8a97dd3befbaa6c660e9fcec1", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 86, "avg_line_length": 19.11340206185567, "alnum_prop": 0.6326860841423948, "repo_name": "kwagdy/koding-1", "id": "267d00bdb4f4adc59c3cb41ab3b91c3b6dc17737", "size": "1854", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "go/src/koding/klientctl/endpoint/team/team.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "743802" }, { "name": "CoffeeScript", "bytes": "4668756" }, { "name": "Go", "bytes": "6240707" }, { "name": "HTML", "bytes": "107319" }, { "name": "JavaScript", "bytes": "2205890" }, { "name": "Makefile", "bytes": "6772" }, { "name": "PHP", "bytes": "1570" }, { "name": "PLpgSQL", "bytes": "12770" }, { "name": "Perl", "bytes": "1612" }, { "name": "Python", "bytes": "27895" }, { "name": "Ruby", "bytes": "1763" }, { "name": "SQLPL", "bytes": "5187" }, { "name": "Shell", "bytes": "115346" } ], "symlink_target": "" }
package org.kie.remote.client.documentation.jms; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jms.ConnectionFactory; import javax.jms.Queue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.TaskService; import org.kie.api.task.model.Task; import org.kie.api.task.model.TaskSummary; import org.kie.remote.client.api.RemoteRuntimeEngineFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JmsJavaApiExamples { /** * 1: the names of these objects may be different depending on your application server * 2: Here we add the connection factory and queue instances * 3: if we are not using SSL, then we have to explictly do that. SSL is necessary * for security reasons (plain-text password in message) when doing task operations * via the remote Java API. */ // @formatter:off // tag::connFactoryJmsBuilderExample[] private static final String CONNECTION_FACTORY_NAME = "jms/RemoteConnectionFactory"; // <1> private static final String KSESSION_QUEUE_NAME = "jms/queue/KIE.SESSION"; private static final String TASK_QUEUE_NAME = "jms/queue/KIE.TASK"; private static final String RESPONSE_QUEUE_NAME = "jms/queue/KIE.RESPONSE"; public void startProcessViaJmsRemoteJavaAPI(String hostname, int jmsConnPort, String deploymentId, String user, String password, String processId) throws NamingException { InitialContext remoteInitialContext = getRemoteInitialContext(); String queueName = KSESSION_QUEUE_NAME; Queue sessionQueue = (Queue) remoteInitialContext.lookup(queueName); queueName = TASK_QUEUE_NAME; Queue taskQueue = (Queue) remoteInitialContext.lookup(queueName); queueName = RESPONSE_QUEUE_NAME; Queue responseQueue = (Queue) remoteInitialContext.lookup(queueName); String connFactoryName = CONNECTION_FACTORY_NAME; ConnectionFactory connFact = (ConnectionFactory) remoteInitialContext.lookup(connFactoryName); RuntimeEngine engine = RemoteRuntimeEngineFactory.newJmsBuilder() .addDeploymentId(deploymentId) .addConnectionFactory(connFact) // <2> .addKieSessionQueue(sessionQueue) .addTaskServiceQueue(taskQueue) .addResponseQueue(responseQueue) .addUserName(user) .addPassword(password) .addHostName(hostname) .addJmsConnectorPort(jmsConnPort) .disableTaskSecurity() // <3> .build(); // Create KieSession instances and use them KieSession ksession = engine.getKieSession(); // Each operation on a KieSession, TaskService or AuditLogService (client) instance // sends a request for the operation to the server side and waits for the response // If something goes wrong on the server side, the client will throw an exception. ProcessInstance processInstance = ksession.startProcess(processId); long procId = processInstance.getId(); } // end::connFactoryJmsBuilderExample[] // tag::initContextJmsBuilderExample[] public void startProcessViaJmsRemoteJavaAPIInitialContext(String hostname, int jmsConnPort, String deploymentId, String user, String password, String processId) { // See your application server documentation for how to initialize // a remote InitialContext instance for your server instance InitialContext remoteInitialContext = getRemoteInitialContext(); RuntimeEngine engine = RemoteRuntimeEngineFactory.newJmsBuilder() .addDeploymentId(deploymentId) .addRemoteInitialContext(remoteInitialContext) .addUserName(user) .addPassword(password) .build(); // Create KieSession instances and use them KieSession ksession = engine.getKieSession(); // Each operation on a KieSession, TaskService or AuditLogService (client) instance // sends a request for the operation to the server side and waits for the response // If something goes wrong on the server side, the client will throw an exception. ProcessInstance processInstance = ksession.startProcess(processId); long procId = processInstance.getId(); } // end::initContextJmsBuilderExample[] // @formatter:on // @formatter:off // tag::jbossHostNameJmsBuilderExample[] public void startProcessViaJmsRemoteJavaAPI(String hostNameOrIpAdress, String deploymentId, String user, String password, String processId) { // this requires that you also have the following dependencies // - org.jboss.as:jboss-naming artifact appropriate to the EAP version you're using RuntimeEngine engine = RemoteRuntimeEngineFactory.newJmsBuilder() .addJbossServerHostName(hostNameOrIpAdress) .addDeploymentId(deploymentId) .addUserName(user) .addPassword(password) .build(); } // end::jbossHostNameJmsBuilderExample[] // @formatter:on private static InitialContext getRemoteInitialContext() { return null; } private static Logger logger = LoggerFactory.getLogger(JmsJavaApiExamples.class); // @formatter:off // tag::sslJmsBuilderExample[] public void startProcessAndHandleTaskViaJmsRemoteJavaAPISsl(String hostNameOrIpAdress, int jmsSslConnectorPort, String deploymentId, String user, String password, String keyTrustStoreLocation, String keyTrustStorePassword, String processId) { InitialContext remoteInitialContext = getRemoteInitialContext(); RuntimeEngine engine = RemoteRuntimeEngineFactory.newJmsBuilder() .addDeploymentId(deploymentId) .addRemoteInitialContext(remoteInitialContext) .addUserName(user) .addPassword(password) .addHostName(hostNameOrIpAdress) .addJmsConnectorPort(jmsSslConnectorPort) .useKeystoreAsTruststore() .addKeystoreLocation(keyTrustStoreLocation) .addKeystorePassword(keyTrustStorePassword) .build(); // create JMS request KieSession ksession = engine.getKieSession(); ProcessInstance processInstance = ksession.startProcess(processId); long procInstId = processInstance.getId(); logger.debug("Started process instance: " + procInstId ); TaskService taskService = engine.getTaskService(); List<TaskSummary> taskSumList = taskService.getTasksAssignedAsPotentialOwner(user, "en-UK"); TaskSummary taskSum = null; for( TaskSummary taskSumElem : taskSumList ) { if( taskSumElem.getProcessInstanceId().equals(procInstId) ) { taskSum = taskSumElem; } } long taskId = taskSum.getId(); logger.debug("Found task " + taskId); // get other info from task if you want to Task task = taskService.getTaskById(taskId); logger.debug("Retrieved task " + taskId ); taskService.start(taskId, user); Map<String, Object> resultData = new HashMap<String, Object>(); // insert results for task in resultData taskService.complete(taskId, user, resultData); logger.debug("Completed task " + taskId ); } // end::sslJmsBuilderExample[] // @formatter:on }
{ "content_hash": "d6a55f6658b49fcc2af9fc9e2dd37495", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 115, "avg_line_length": 42.98913043478261, "alnum_prop": 0.6730720606826801, "repo_name": "porcelli/kie-wb-common-server-ui-test", "id": "9a2f3df9c0971bec4c27bcb6d680af7a7a3f2ea6", "size": "7910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kie-wb-distributions/kie-docs/kie-docs-code/src/main/java/org/kie/remote/client/documentation/jms/JmsJavaApiExamples.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "515" }, { "name": "CSS", "bytes": "42685" }, { "name": "HTML", "bytes": "38266" }, { "name": "Java", "bytes": "509318" }, { "name": "JavaScript", "bytes": "14829" }, { "name": "Shell", "bytes": "2338" }, { "name": "XSLT", "bytes": "17143" } ], "symlink_target": "" }
import typescript from 'rollup-plugin-typescript'; import commonjs from 'rollup-plugin-commonjs'; import nodeResolve from 'rollup-plugin-node-resolve'; export default { entry: './lib/index.ts', treeshake: true, moduleName: 'matejs', plugins: [ typescript({ typescript: require('typescript') }), nodeResolve({ jsnext: true, main: true }), commonjs() ], targets: [ { dest: 'dist/index.cjs.js', format: 'cjs' }, { dest: 'dist/index.js', format: 'umd' }, { dest: 'dist/index.es.js', format: 'es' }, ] }
{ "content_hash": "9cbf71d5fcde3866f5acb47c39a232e8", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 53, "avg_line_length": 26.047619047619047, "alnum_prop": 0.6307129798903108, "repo_name": "psastras/mate.js", "id": "775bbd1e71a605ac94691790509cb5a5fbbd26e7", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rollup.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "144" }, { "name": "JavaScript", "bytes": "567" }, { "name": "Shell", "bytes": "358" }, { "name": "TypeScript", "bytes": "88220" } ], "symlink_target": "" }
<?php namespace N1215\Jugoya; use Psr\Http\Server\RequestHandlerInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Psr\Http\Message\ServerRequestInterface; use Laminas\Diactoros\Response\TextResponse; use Laminas\Diactoros\ServerRequest; class RequestHandlerBuilderTest extends TestCase { /** * @param RequestHandlerInterface|callable $coreHandler * @dataProvider dataProviderCoreHandler */ public function testCreate($coreHandler) { /** @var ContainerInterface|MockObject $container */ $container = $this->createMock(ContainerInterface::class); $container->expects($this->any()) ->method('get') ->will( $this->returnValueMap([ [FakeMiddleware::class, new FakeMiddleware('dependency')], [FakeHandler::class, new FakeHandler('handler')] ]) ); $builder = RequestHandlerBuilder::fromContainer($container); $app = $builder->build($coreHandler, [ function(ServerRequestInterface $request, RequestHandlerInterface $handler) { $response = $handler->handle($request); $body = $response->getBody(); $body->seek($body->getSize()); $body->write(PHP_EOL . 'callable'); return $response; }, new FakeMiddleware('object'), FakeMiddleware::class, ]); $this->assertInstanceOf(DelegateHandler::class, $app); $request = new ServerRequest(); $response = $app->handle($request); $expected = join(PHP_EOL, ['handler', 'dependency', 'object', 'callable']); $this->assertEquals($expected, $response->getBody()->__toString()); } public function dataProviderCoreHandler() { return [ [new FakeHandler('handler')], [function(ServerRequestInterface $request) { return new TextResponse('handler'); }], [FakeHandler::class], ]; } public function testFromContainer() { /** @var ContainerInterface $container */ $container = $this->createMock(ContainerInterface::class); $builder = RequestHandlerBuilder::fromContainer($container); $this->assertInstanceOf(RequestHandlerBuilder::class, $builder); } }
{ "content_hash": "d47ed589fdfde590baf7499889563d82", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 89, "avg_line_length": 31.844155844155843, "alnum_prop": 0.6056280587275693, "repo_name": "n1215/jugoya", "id": "25149786d490eccff4f3ceaeb9fe1cdee0b08b5e", "size": "2452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/RequestHandlerBuilderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "43269" } ], "symlink_target": "" }
/*global defineSuite*/ defineSuite([ 'Scene/Moon', 'Core/Cartesian3', 'Core/defined', 'Core/Ellipsoid', 'Core/Matrix3', 'Core/Simon1994PlanetaryPositions', 'Core/Transforms', 'Specs/createCamera', 'Specs/createFrameState', 'Specs/createScene', 'Specs/destroyScene' ], function( Moon, Cartesian3, defined, Ellipsoid, Matrix3, Simon1994PlanetaryPositions, Transforms, createCamera, createFrameState, createScene, destroyScene) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/ var scene; beforeAll(function() { scene = createScene(); }); afterAll(function() { destroyScene(scene); }); function lookAtMoon(camera, date) { var icrfToFixed = new Matrix3(); if (!defined(Transforms.computeIcrfToFixedMatrix(date, icrfToFixed))) { Transforms.computeTemeToPseudoFixedMatrix(date, icrfToFixed); } var moonPosition = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(date); Matrix3.multiplyByVector(icrfToFixed, moonPosition, moonPosition); var cameraPosition = Cartesian3.multiplyByScalar(Cartesian3.normalize(moonPosition, new Cartesian3()), 1e7, new Cartesian3()); camera.lookAt(moonPosition, cameraPosition, Cartesian3.UNIT_Z); } it('default constructs the moon', function() { var moon = new Moon(); expect(moon.show).toEqual(true); expect(moon.textureUrl).toContain('Assets/Textures/moonSmall.jpg'); expect(moon.ellipsoid).toBe(Ellipsoid.MOON); expect(moon.onlySunLighting).toEqual(true); }); it('draws in 3D', function() { scene.moon = new Moon(); scene.initializeFrame(); scene.render(); var date = scene.frameState.time; var camera = scene.camera; lookAtMoon(camera, date); scene.initializeFrame(); scene.render(); expect(scene.context.readPixels()).toNotEqual([0, 0, 0, 0]); }); it('does not render when show is false', function() { var moon = new Moon(); moon.show = false; var frameState = createFrameState(createCamera({ near : 1.0, far : 1.0e10 })); var context = scene.context; var us = context.uniformState; us.update(context, frameState); lookAtMoon(scene.camera, frameState.time); us.update(context, frameState); var commandList = []; moon.update(context, frameState, commandList); expect(commandList.length).toEqual(0); moon.destroy(); }); it('isDestroyed', function() { var moon = new Moon(); expect(moon.isDestroyed()).toEqual(false); moon.destroy(); expect(moon.isDestroyed()).toEqual(true); }); }, 'WebGL');
{ "content_hash": "4f3679860f7f1e5edffa83a84b71f73f", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 134, "avg_line_length": 29.54368932038835, "alnum_prop": 0.6069668090699967, "repo_name": "uhef/Oskari-Routing-frontend", "id": "0e2b1ca7f28273207f1a2ee6e4df50067ecf58ad", "size": "3043", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "libraries/cesium/cesium-b30/Specs/Scene/MoonSpec.js", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "141360" }, { "name": "CSS", "bytes": "3199762" }, { "name": "Clojure", "bytes": "605" }, { "name": "JavaScript", "bytes": "62160191" }, { "name": "Makefile", "bytes": "685" }, { "name": "PHP", "bytes": "145405" }, { "name": "Perl", "bytes": "32074" }, { "name": "Prolog", "bytes": "49" }, { "name": "Python", "bytes": "3530" }, { "name": "Shell", "bytes": "74328" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6971026443b245974ce222637c662547", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "5784fa43ae160d04d044a80753b291191f235aad", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Dolichos/Dolichos mutabilis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * EmployeeTax * * PHP version 5 * * @category Class * @package XeroAPI\XeroPHP * @author OpenAPI Generator team * @link https://openapi-generator.tech */ /** * Xero Payroll UK * * This is the Xero Payroll API for orgs in the UK region. * * Contact: [email protected] * Generated by: https://openapi-generator.tech * OpenAPI Generator version: 4.3.1 */ /** * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ namespace XeroAPI\XeroPHP\Models\PayrollUk; use \ArrayAccess; use \XeroAPI\XeroPHP\PayrollUkObjectSerializer; use \XeroAPI\XeroPHP\StringUtil; /** * EmployeeTax Class Doc Comment * * @category Class * @package XeroAPI\XeroPHP * @author OpenAPI Generator team * @link https://openapi-generator.tech */ class EmployeeTax implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $openAPIModelName = 'EmployeeTax'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $openAPITypes = [ 'starter_type' => 'string', 'starter_declaration' => 'string', 'tax_code' => 'string', 'w1_m1' => 'bool', 'previous_taxable_pay' => 'double', 'previous_tax_paid' => 'double', 'student_loan_deduction' => 'string', 'has_post_graduate_loans' => 'bool', 'is_director' => 'bool', 'directorship_start_date' => '\DateTime', 'nic_calculation_method' => 'string' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $openAPIFormats = [ 'starter_type' => null, 'starter_declaration' => null, 'tax_code' => null, 'w1_m1' => null, 'previous_taxable_pay' => 'double', 'previous_tax_paid' => 'double', 'student_loan_deduction' => null, 'has_post_graduate_loans' => null, 'is_director' => null, 'directorship_start_date' => 'date', 'nic_calculation_method' => null ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function openAPITypes() { return self::$openAPITypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function openAPIFormats() { return self::$openAPIFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'starter_type' => 'starterType', 'starter_declaration' => 'starterDeclaration', 'tax_code' => 'taxCode', 'w1_m1' => 'w1M1', 'previous_taxable_pay' => 'previousTaxablePay', 'previous_tax_paid' => 'previousTaxPaid', 'student_loan_deduction' => 'studentLoanDeduction', 'has_post_graduate_loans' => 'hasPostGraduateLoans', 'is_director' => 'isDirector', 'directorship_start_date' => 'directorshipStartDate', 'nic_calculation_method' => 'nicCalculationMethod' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'starter_type' => 'setStarterType', 'starter_declaration' => 'setStarterDeclaration', 'tax_code' => 'setTaxCode', 'w1_m1' => 'setW1M1', 'previous_taxable_pay' => 'setPreviousTaxablePay', 'previous_tax_paid' => 'setPreviousTaxPaid', 'student_loan_deduction' => 'setStudentLoanDeduction', 'has_post_graduate_loans' => 'setHasPostGraduateLoans', 'is_director' => 'setIsDirector', 'directorship_start_date' => 'setDirectorshipStartDate', 'nic_calculation_method' => 'setNicCalculationMethod' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'starter_type' => 'getStarterType', 'starter_declaration' => 'getStarterDeclaration', 'tax_code' => 'getTaxCode', 'w1_m1' => 'getW1M1', 'previous_taxable_pay' => 'getPreviousTaxablePay', 'previous_tax_paid' => 'getPreviousTaxPaid', 'student_loan_deduction' => 'getStudentLoanDeduction', 'has_post_graduate_loans' => 'getHasPostGraduateLoans', 'is_director' => 'getIsDirector', 'directorship_start_date' => 'getDirectorshipStartDate', 'nic_calculation_method' => 'getNicCalculationMethod' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$openAPIModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['starter_type'] = isset($data['starter_type']) ? $data['starter_type'] : null; $this->container['starter_declaration'] = isset($data['starter_declaration']) ? $data['starter_declaration'] : null; $this->container['tax_code'] = isset($data['tax_code']) ? $data['tax_code'] : null; $this->container['w1_m1'] = isset($data['w1_m1']) ? $data['w1_m1'] : null; $this->container['previous_taxable_pay'] = isset($data['previous_taxable_pay']) ? $data['previous_taxable_pay'] : null; $this->container['previous_tax_paid'] = isset($data['previous_tax_paid']) ? $data['previous_tax_paid'] : null; $this->container['student_loan_deduction'] = isset($data['student_loan_deduction']) ? $data['student_loan_deduction'] : null; $this->container['has_post_graduate_loans'] = isset($data['has_post_graduate_loans']) ? $data['has_post_graduate_loans'] : null; $this->container['is_director'] = isset($data['is_director']) ? $data['is_director'] : null; $this->container['directorship_start_date'] = isset($data['directorship_start_date']) ? $data['directorship_start_date'] : null; $this->container['nic_calculation_method'] = isset($data['nic_calculation_method']) ? $data['nic_calculation_method'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets starter_type * * @return string|null */ public function getStarterType() { return $this->container['starter_type']; } /** * Sets starter_type * * @param string|null $starter_type The Starter type. * * @return $this */ public function setStarterType($starter_type) { $this->container['starter_type'] = $starter_type; return $this; } /** * Gets starter_declaration * * @return string|null */ public function getStarterDeclaration() { return $this->container['starter_declaration']; } /** * Sets starter_declaration * * @param string|null $starter_declaration Starter declaration. * * @return $this */ public function setStarterDeclaration($starter_declaration) { $this->container['starter_declaration'] = $starter_declaration; return $this; } /** * Gets tax_code * * @return string|null */ public function getTaxCode() { return $this->container['tax_code']; } /** * Sets tax_code * * @param string|null $tax_code The Tax code. * * @return $this */ public function setTaxCode($tax_code) { $this->container['tax_code'] = $tax_code; return $this; } /** * Gets w1_m1 * * @return bool|null */ public function getW1M1() { return $this->container['w1_m1']; } /** * Sets w1_m1 * * @param bool|null $w1_m1 Describes whether the tax settings is W1M1 * * @return $this */ public function setW1M1($w1_m1) { $this->container['w1_m1'] = $w1_m1; return $this; } /** * Gets previous_taxable_pay * * @return double|null */ public function getPreviousTaxablePay() { return $this->container['previous_taxable_pay']; } /** * Sets previous_taxable_pay * * @param double|null $previous_taxable_pay The previous taxable pay * * @return $this */ public function setPreviousTaxablePay($previous_taxable_pay) { $this->container['previous_taxable_pay'] = $previous_taxable_pay; return $this; } /** * Gets previous_tax_paid * * @return double|null */ public function getPreviousTaxPaid() { return $this->container['previous_tax_paid']; } /** * Sets previous_tax_paid * * @param double|null $previous_tax_paid The tax amount previously paid * * @return $this */ public function setPreviousTaxPaid($previous_tax_paid) { $this->container['previous_tax_paid'] = $previous_tax_paid; return $this; } /** * Gets student_loan_deduction * * @return string|null */ public function getStudentLoanDeduction() { return $this->container['student_loan_deduction']; } /** * Sets student_loan_deduction * * @param string|null $student_loan_deduction The employee's student loan deduction type * * @return $this */ public function setStudentLoanDeduction($student_loan_deduction) { $this->container['student_loan_deduction'] = $student_loan_deduction; return $this; } /** * Gets has_post_graduate_loans * * @return bool|null */ public function getHasPostGraduateLoans() { return $this->container['has_post_graduate_loans']; } /** * Sets has_post_graduate_loans * * @param bool|null $has_post_graduate_loans Describes whether the employee has post graduate loans * * @return $this */ public function setHasPostGraduateLoans($has_post_graduate_loans) { $this->container['has_post_graduate_loans'] = $has_post_graduate_loans; return $this; } /** * Gets is_director * * @return bool|null */ public function getIsDirector() { return $this->container['is_director']; } /** * Sets is_director * * @param bool|null $is_director Describes whether the employee is director * * @return $this */ public function setIsDirector($is_director) { $this->container['is_director'] = $is_director; return $this; } /** * Gets directorship_start_date * * @return \DateTime|null */ public function getDirectorshipStartDate() { return $this->container['directorship_start_date']; } /** * Sets directorship_start_date * * @param \DateTime|null $directorship_start_date The directorship start date * * @return $this */ public function setDirectorshipStartDate($directorship_start_date) { $this->container['directorship_start_date'] = $directorship_start_date; return $this; } /** * Gets nic_calculation_method * * @return string|null */ public function getNicCalculationMethod() { return $this->container['nic_calculation_method']; } /** * Sets nic_calculation_method * * @param string|null $nic_calculation_method NICs calculation method * * @return $this */ public function setNicCalculationMethod($nic_calculation_method) { $this->container['nic_calculation_method'] = $nic_calculation_method; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { return json_encode( PayrollUkObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } }
{ "content_hash": "0df5eb43260ce0e4d758d8acc9715ea6", "timestamp": "", "source": "github", "line_count": 629, "max_line_length": 136, "avg_line_length": 23.62162162162162, "alnum_prop": 0.5745726208103379, "repo_name": "unaio/una", "id": "bcb1496892ea420d47107dfd6fd8c88d0dc3e8ae", "size": "14858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/boonex/xero/plugins/xeroapi/xero-php-oauth2/lib/Models/PayrollUk/EmployeeTax.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9522763" }, { "name": "Dockerfile", "bytes": "2367" }, { "name": "HTML", "bytes": "6194660" }, { "name": "JavaScript", "bytes": "24733694" }, { "name": "Less", "bytes": "3020615" }, { "name": "Makefile", "bytes": "1196" }, { "name": "PHP", "bytes": "158741504" }, { "name": "Ruby", "bytes": "210" }, { "name": "Shell", "bytes": "3327" }, { "name": "Smarty", "bytes": "3461" } ], "symlink_target": "" }
var GameObject = (function() { var GameObject = function(x, y, width, height) { this.x = x || 0; this.y = y || 0; this.width = width || 0; this.height = height || 0; }; GameObject.prototype.distanceTo = function(pos) { var dx = this.x - pos.x; var dy = this.y - pos.y; return Math.sqrt(dx * dx + dy * dy); }; GameObject.prototype.angleTo = function(pos) { var dx = this.x - pos.x; var dy = this.y - pos.y; return Math.atan2(dy, dx); }; return GameObject; })(); var Bullet = (function() { var Bullet = function(x, y, angle, owner) { GameObject.apply(this, [x, y, 3, 3]); this.vx = 5 * cos(angle); this.vy = 5 * sin(angle); this.owner = owner; }; Bullet.prototype = new GameObject(); return Bullet; })();
{ "content_hash": "c3419115fb9c422aa8351ed813f8987c", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 50, "avg_line_length": 21.34285714285714, "alnum_prop": 0.5943775100401606, "repo_name": "AngleVisions/GulpSamples", "id": "2468760ffe1178cb8163291487d3c308668b0521", "size": "747", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "concat/src/a.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "76891" }, { "name": "JavaScript", "bytes": "12248" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black"> <android.support.v7.widget.RecyclerView android:id="@+id/userfeeds_links_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent"/> <ProgressBar android:id="@+id/userfeeds_links_loader" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> <TextView android:id="@+id/userfeeds_links_empty_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/userfeeds_link_background" android:gravity="center" android:textColor="@color/userfeeds_link_text_color" android:visibility="gone"/> </FrameLayout>
{ "content_hash": "7df758fd38e8e1ba3a6270187df39eb0", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 64, "avg_line_length": 35.75, "alnum_prop": 0.6743256743256744, "repo_name": "Userfeeds/android-ads-sdk", "id": "982d6a4de7d78e472752545ef17b3683a99f612d", "size": "1001", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/res/layout/userfeeds_links_recycler_view.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Kotlin", "bytes": "24019" } ], "symlink_target": "" }
namespace base { // TimeDelta ------------------------------------------------------------------ int TimeDelta::InDays() const { return static_cast<int>(delta_ / Time::kMicrosecondsPerDay); } int TimeDelta::InHours() const { return static_cast<int>(delta_ / Time::kMicrosecondsPerHour); } int TimeDelta::InMinutes() const { return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute); } double TimeDelta::InSecondsF() const { return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond; } int64 TimeDelta::InSeconds() const { return delta_ / Time::kMicrosecondsPerSecond; } double TimeDelta::InMillisecondsF() const { return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond; } int64 TimeDelta::InMilliseconds() const { return delta_ / Time::kMicrosecondsPerMillisecond; } int64 TimeDelta::InMicroseconds() const { return delta_; } // Time ----------------------------------------------------------------------- // static Time Time::FromTimeT(time_t tt) { if (tt == 0) return Time(); // Preserve 0 so we can tell it doesn't exist. return (tt * kMicrosecondsPerSecond) + kTimeTToMicrosecondsOffset; } time_t Time::ToTimeT() const { if (us_ == 0) return 0; // Preserve 0 so we can tell it doesn't exist. return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond; } // static Time Time::FromDoubleT(double dt) { return (dt * static_cast<double>(kMicrosecondsPerSecond)) + kTimeTToMicrosecondsOffset; } double Time::ToDoubleT() const { if (us_ == 0) return 0; // Preserve 0 so we can tell it doesn't exist. return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) / static_cast<double>(kMicrosecondsPerSecond)); } Time Time::LocalMidnight() const { Exploded exploded; LocalExplode(&exploded); exploded.hour = 0; exploded.minute = 0; exploded.second = 0; exploded.millisecond = 0; return FromLocalExploded(exploded); } // static bool Time::FromString(const wchar_t* time_string, Time* parsed_time) { DCHECK((time_string != NULL) && (parsed_time != NULL)); std::string ascii_time_string = SysWideToUTF8(time_string); if (ascii_time_string.length() == 0) return false; PRTime result_time = 0; PRStatus result = PR_ParseTimeString(ascii_time_string.c_str(), PR_FALSE, &result_time); if (PR_SUCCESS != result) return false; result_time += kTimeTToMicrosecondsOffset; *parsed_time = Time(result_time); return true; } } // namespace base
{ "content_hash": "2c20659a09c17dc1eddde4b64d5a5dc7", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 79, "avg_line_length": 27.714285714285715, "alnum_prop": 0.6534496431403648, "repo_name": "kuiche/chromium", "id": "992e256ba285ff959340c4f3bc72502ebb25c3c3", "size": "2861", "binary": false, "copies": "3", "ref": "refs/heads/trunk", "path": "base/time.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.gabstudios.validate; /** * This is a byte validator. After this class is created, call the testXXXX() * methods to perform tests when the validate() method is called. * * Validate.defineByte(byte).testNotNull().validate(); * * If the throwValidationExceptionOnFail() method has been called and if the validate fails * then a ValidateException will be thrown. * * Validate.defineByte(byte).testEquals(expectedByte) * .throwValidationExceptionOnFail().validate(); * * If no test method is called, validate() returns a false. * * @author Gregory Brown (sysdevone) * */ public class ByteValidator extends NumberValidator<Byte> { /** * Protected constructor. Use Validate static method to create validator. * * @param value * The value that will be validated. */ protected ByteValidator(final byte value) { super( value, Byte.MIN_VALUE, Byte.MAX_VALUE); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format( "ByteValidator [_isTestMaxValue=%s, _isTestMinValue=%s, _maxValue=%s, _minValue=%s, _isValidationExceptionThrownOnFail=%s, _equalsValue=%s, _isTestEquals=%s, _isTestNotNull=%s, _isTested=%s, _value=%s]", _isTestMaxValue, _isTestMinValue, _maxValue, _minValue, _isValidationExceptionThrownOnFail, _equalsValue, _isTestEquals, _isTestNotNull, _isTested, _value); } }
{ "content_hash": "df6b2e31fc95d5c1752fffdf3e59caae", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 207, "avg_line_length": 30.875, "alnum_prop": 0.6821862348178138, "repo_name": "sysdevone/gab-dev", "id": "819dc5a3a028590b8d84ef75882d02002e83d027", "size": "2281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/gabstudios/validate/ByteValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "126748" } ], "symlink_target": "" }
package org.tcsaroundtheworld.submit.client.verify; import org.tcsaroundtheworld.common.shared.verify.SubmissionValueVerifier; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; public class TextFieldVerifier extends LabelFieldVerifier { public TextFieldVerifier(final String itemName, final boolean mandatory, final SubmissionValueVerifier verifier, final Label errorLabel, final TextBox field) { super(itemName, mandatory, verifier, errorLabel, field); field.addChangeHandler(new ChangeHandler() { public void onChange(final ChangeEvent event) { checkField(); } }); } }
{ "content_hash": "5b06a36a1922ec5ad0e4c0029d0eefe3", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 160, "avg_line_length": 36.142857142857146, "alnum_prop": 0.7799736495388669, "repo_name": "drweaver/tcsaroundtheworld", "id": "ca1c04a491bd91346b30cff14d0c49ca568f2a1d", "size": "759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/submit/org/tcsaroundtheworld/submit/client/verify/TextFieldVerifier.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "336" }, { "name": "HTML", "bytes": "5733" }, { "name": "Java", "bytes": "284065" }, { "name": "JavaScript", "bytes": "157049" } ], "symlink_target": "" }
layout: post title: GSoC First Week --- ![Logo](https://summerofcode.withgoogle.com/static/img/summer-of-code-logo.svg) Previously, I was working on the [PR](https://github.com/symengine/symengine/pull/942) for `FiniteSet` implementation. I managed to get it merged this week. So, now we have `UniversalSet`, `EmptySet`, `Interval` and `FiniteSet` implementation in SymEngine. Where in `FiniteSet` we have a `set_basic` which can contain any `Basic` object. That is apart from `Number` objects we can have `Symbol` objects as well, and even an `Expression`.<br/> Then I started working on implementing `FiniteField`. I have sent this [PR](https://github.com/symengine/symengine/pull/955). Initially I was using `std::map<unsigned, int>` as the `type` for `dict_` and `int` type for `modulo_`, but I realized that there are already `inverse` function written for `integer_class`/`mpz`, so I changed the `dict_` to `std::map<unsigned, integer_class>` and `modulo_` to `integer_class`. While implementing this, I thought of writing tests after doing the whole implementation. And when I wrote the tests, I realized how badly I had done the implementation, like missing corner cases and all. It is always a better practice to write tests parallely with your implementation.<br/> So, As of now I have implemented the following functions: * `gf_add_ground(const integer_class a)` * `gf_sub_ground(const integer_class a)` * `gf_mul_ground(const integer_class a)` * `gf_quo_ground(const integer_class a)` * `gf_add(const RCP<const GaloisField> &o)` * `gf_sub(const RCP<const GaloisField> &o)` * `gf_mul(const RCP<const GaloisField> &o)` Where `gf_*_ground` does the operation represented by `*` by the integer `a` to the polynomaial in the given field. And `gf_add`, `gf_sub`, `gf_mul` do their respective operation with another polynomial in the finite field. <br/> I will be implementing `gf_div` this weekend.
{ "content_hash": "07ad40e58f33d8c10b03b61d0440c7ce", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 419, "avg_line_length": 70.77777777777777, "alnum_prop": 0.7451596023024595, "repo_name": "nishnik/nishnik.github.io", "id": "4e050bf0643bd2e69e46b1ed4c0403611952709b", "size": "1915", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-5-27-GSoC-First-Week.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "62905" }, { "name": "HTML", "bytes": "6266" } ], "symlink_target": "" }
require 'watir' module Crashlytics class InvalidCredentials < StandardError end Crawler = Struct.new(:email, :password) do LOGIN_URL = "https://www.crashlytics.com/login" def statistics_page login browser.goto 'https://www.crashlytics.com/seeking-alpha/ios/apps/com.seekingalpha.ipadportfolio/issues?build=all&status=open&event_type=all&time=last-twenty-four-hours' browser.html end private def login browser.goto LOGIN_URL browser.text_field(id: 'form-email').set email browser.text_field(id: 'form-password').set password browser.button(id: 'sign_in_email').click end def browser @browser ||= Watir::Browser.new :chrome end end end
{ "content_hash": "8ac52bf1457550b8550b960b71cf5228", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 174, "avg_line_length": 23.580645161290324, "alnum_prop": 0.6839945280437757, "repo_name": "seekingalpha/crashlytics", "id": "07d0d735bc0b7c8971e7a0500d8a2cae9950f012", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/crashlytics/crawler.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4375" } ], "symlink_target": "" }
package com.pivovarit.function; import org.junit.jupiter.api.Test; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; import java.util.stream.Stream; import static com.pivovarit.function.TestCommons.givenThrowingFunction; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class ThrowingFunctionTest { @Test void shouldReturnOptional() { // given ThrowingFunction<Integer, Integer, Exception> f1 = i -> i; // when Optional<Integer> result = f1.lift().apply(42); // then assertThat(result.isPresent()).isTrue(); } @Test void shouldReturnEmptyOptional() { // given ThrowingFunction<Integer, Integer, Exception> f1 = givenThrowingFunction(); // when Optional<Integer> result = f1.lift().apply(42); // then assertThat(result.isPresent()).isFalse(); } @Test void shouldThrowEx() { ThrowingFunction<Integer, Integer, Exception> f1 = givenThrowingFunction("custom exception message"); assertThatThrownBy(() -> f1.apply(42)) .isInstanceOf(Exception.class) .hasMessage("custom exception message"); } @Test void shouldWrapInRuntimeExWhenUsingUnchecked() { assertThatThrownBy(() -> Stream.of(". .") .map(ThrowingFunction.unchecked(URI::new)) .collect(toList())) .isInstanceOf(RuntimeException.class) .hasMessage("Illegal character in path at index 1: . .") .hasCauseInstanceOf(URISyntaxException.class); } @Test void shouldWrapInOptionalWhenUsingStandardUtilsFunctions() { // when Long result = Stream.of(". .") .map(ThrowingFunction.lifted(URI::new)) .filter(Optional::isPresent) .count(); //then assertThat(result).isZero(); } }
{ "content_hash": "2924a3c989e73b2ef87e7c513dccc6d9", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 109, "avg_line_length": 27.819444444444443, "alnum_prop": 0.6490264603095357, "repo_name": "TouK/ThrowingFunction", "id": "ad64b0fb6a558689463518d14f5f6bf1e41f590d", "size": "2003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/pivovarit/function/ThrowingFunctionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "61113" } ], "symlink_target": "" }
package util import java.util.stream.Collectors import org.jsoup.nodes.Element import org.jsoup.select.Elements /** * <pre> * Created on 6/3/15. * </pre> * @author K.Sakamoto */ object JsoupHelper { implicit def elementsToElements4Scala(elements: Elements): Elements4Scala = { new Elements4Scala(elements) } } class Elements4Scala(that: Elements) { def toElementArray: Array[Element] = { val list: java.util.List[Element] = that.stream.collect(Collectors.toList[Element]) list.toArray(new Array[Element](list.size())) } }
{ "content_hash": "e32e0c2aa054628bf493883017d3b0cd", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 87, "avg_line_length": 22, "alnum_prop": 0.72, "repo_name": "ktr-skmt/FelisCatusZero", "id": "74c13ae61a06ee0c3edb8fd5f0110519ff3b6fd7", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/util/JsoupHelper.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "8466" }, { "name": "Java", "bytes": "314997" }, { "name": "Jupyter Notebook", "bytes": "36377" }, { "name": "Scala", "bytes": "518961" }, { "name": "Shell", "bytes": "101" } ], "symlink_target": "" }
var vows = require('vows'); var assert = require('assert'); var passport = require('passport'); var util = require('util'); var Passport = require('passport').Passport; vows.describe('passport').addBatch({ 'module': { 'should report a version': function (x) { assert.isString(passport.version); }, }, 'passport': { topic: function() { return new Passport(); }, 'should create initialization middleware': function (passport) { var initialize = passport.initialize(); assert.isFunction(initialize); assert.lengthOf(initialize, 3); }, 'should create session restoration middleware': function (passport) { var session = passport.session(); assert.isFunction(session); assert.lengthOf(session, 3); }, 'should create authentication middleware': function (passport) { var authenticate = passport.authenticate(); assert.isFunction(authenticate); assert.lengthOf(authenticate, 3); }, }, 'passport with strategies': { topic: function() { return new Passport(); }, 'should add strategies': function (passport) { var strategy = {}; strategy.name = 'default'; passport.use(strategy); assert.isObject(passport._strategies['default']); passport._strategies = {}; }, 'should add strategies with specified name': function (passport) { var strategy = {}; passport.use('foo', strategy); assert.isObject(passport._strategies['foo']); passport._strategies = {}; }, 'should add strategies that have a name with overrride name': function (passport) { var strategy = {}; strategy.name = 'foo'; passport.use('my-foo', strategy); assert.isObject(passport._strategies['my-foo']); assert.isUndefined(passport._strategies['foo']); passport._strategies = {}; }, 'should throw an error when adding strategies without a name' : function(passport) { var strategy = {}; assert.throws(function() { passport.use(strategy); }); }, }, 'passport with strategies to unuse': { topic: function() { return new Passport(); }, 'should unuse strategies': function (passport) { var strategyOne = {}; strategyOne.name = 'one'; passport.use(strategyOne); var strategyTwo = {}; strategyTwo.name = 'two'; passport.use(strategyTwo); // session is implicitly used assert.lengthOf(Object.keys(passport._strategies), 3); assert.isObject(passport._strategies['one']); assert.isObject(passport._strategies['two']); passport.unuse('one'); assert.lengthOf(Object.keys(passport._strategies), 2); assert.isUndefined(passport._strategies['one']); assert.isObject(passport._strategies['two']); }, }, 'passport with no serializers': { topic: function() { var self = this; var passport = new Passport(); function serialized(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.serializeUser({ id: '1', username: 'jared' }, serialized); }); }, 'should fail to serialize user': function (err, obj) { assert.instanceOf(err, Error); assert.isUndefined(obj); }, }, 'passport with one serializer': { topic: function() { var self = this; var passport = new Passport(); passport.serializeUser(function(user, done) { done(null, user.id); }); function serialized(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.serializeUser({ id: '1', username: 'jared' }, serialized); }); }, 'should serialize user': function (err, obj) { assert.isNull(err); assert.equal(obj, '1'); }, }, 'passport with multiple serializers': { topic: function() { var self = this; var passport = new Passport(); passport.serializeUser(function(user, done) { done('pass'); }); passport.serializeUser(function(user, done) { done(null, 'second-serializer'); }); passport.serializeUser(function(user, done) { done(null, 'should-not-execute'); }); function serialized(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.serializeUser({ id: '1', username: 'jared' }, serialized); }); }, 'should serialize user': function (err, obj) { assert.isNull(err); assert.equal(obj, 'second-serializer'); }, }, 'passport with a serializer that throws an error': { topic: function() { var self = this; var passport = new Passport(); passport.serializeUser(function(user, done) { // throws ReferenceError: wtf is not defined wtf }); function serialized(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.serializeUser({ id: '1', username: 'jared' }, serialized); }); }, 'should fail to serialize user': function (err, obj) { assert.instanceOf(err, Error); assert.isUndefined(obj); }, }, 'passport with no deserializers': { topic: function() { var self = this; var passport = new Passport(); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should fail to deserialize user': function (err, user) { assert.instanceOf(err, Error); assert.isUndefined(user); }, }, 'passport with one deserializer': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done(null, obj.username); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should deserialize user': function (err, user) { assert.isNull(err); assert.equal(user, 'jared'); }, }, 'passport with multiple deserializers': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done('pass'); }); passport.deserializeUser(function(obj, done) { done(null, 'second-deserializer'); }); passport.deserializeUser(function(obj, done) { done(null, 'should-not-execute'); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should deserialize user': function (err, user) { assert.isNull(err); assert.equal(user, 'second-deserializer'); }, }, 'passport with one deserializer that sets user to null': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done(null, null); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should invalidate user': function (err, user) { assert.isNull(err); assert.strictEqual(user, false); }, }, 'passport with one deserializer that sets user to false': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done(null, false); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should invalidate user': function (err, user) { assert.isNull(err); assert.strictEqual(user, false); }, }, 'passport with multiple deserializers, the second of which sets user to null': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done('pass'); }); passport.deserializeUser(function(obj, done) { done(null, null); }); passport.deserializeUser(function(obj, done) { done(null, 'should-not-execute'); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should invalidate user': function (err, user) { assert.isNull(err); assert.strictEqual(user, false); }, }, 'passport with multiple deserializers, the second of which sets user to false': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { done('pass'); }); passport.deserializeUser(function(obj, done) { done(null, false); }); passport.deserializeUser(function(obj, done) { done(null, 'should-not-execute'); }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should invalidate user': function (err, user) { assert.isNull(err); assert.strictEqual(user, false); }, }, 'passport with a deserializer that throws an error': { topic: function() { var self = this; var passport = new Passport(); passport.deserializeUser(function(obj, done) { // throws ReferenceError: wtf is not defined wtf }); function deserialized(err, user) { self.callback(err, user); } process.nextTick(function () { passport.deserializeUser({ id: '1', username: 'jared' }, deserialized); }); }, 'should fail to deserialize user': function (err, obj) { assert.instanceOf(err, Error); assert.isUndefined(obj); }, }, 'passport with no auth info transformers': { topic: function() { var self = this; var passport = new Passport(); function transformed(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.transformAuthInfo({ clientId: '1', scope: 'write' }, transformed); }); }, 'should leave info untransformed': function (err, obj) { assert.isNull(err); assert.equal(obj.clientId, '1'); assert.equal(obj.scope, 'write'); }, }, 'passport with one auth info transformer': { topic: function() { var self = this; var passport = new Passport(); passport.transformAuthInfo(function(info, done) { done(null, { clientId: info.clientId, client: { name: 'foo' }}); }); function transformed(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.transformAuthInfo({ clientId: '1', scope: 'write' }, transformed); }); }, 'should transform info': function (err, obj) { assert.isNull(err); assert.equal(obj.clientId, '1'); assert.equal(obj.client.name, 'foo'); assert.isUndefined(obj.scope); }, }, 'passport with multiple auth info transformers': { topic: function() { var self = this; var passport = new Passport(); passport.transformAuthInfo(function(info, done) { done('pass'); }); passport.transformAuthInfo(function(info, done) { done(null, { clientId: info.clientId, client: { name: 'bar' }}); }); passport.transformAuthInfo(function(info, done) { done(null, { clientId: info.clientId, client: { name: 'not-bar' }}); }); function transformed(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.transformAuthInfo({ clientId: '1', scope: 'write' }, transformed); }); }, 'should transform info': function (err, obj) { assert.isNull(err); assert.equal(obj.clientId, '1'); assert.equal(obj.client.name, 'bar'); assert.isUndefined(obj.scope); }, }, 'passport with an auth info transformer that throws an error': { topic: function() { var self = this; var passport = new Passport(); passport.transformAuthInfo(function(user, done) { // throws ReferenceError: wtf is not defined wtf }); function transformed(err, obj) { self.callback(err, obj); } process.nextTick(function () { passport.serializeUser({ clientId: '1', scope: 'write' }, transformed); }); }, 'should fail to transform info': function (err, obj) { assert.instanceOf(err, Error); assert.isUndefined(obj); }, }, }).export(module);
{ "content_hash": "0255811c869728827299a6fb6e7833e9", "timestamp": "", "source": "github", "line_count": 465, "max_line_length": 88, "avg_line_length": 28.86021505376344, "alnum_prop": 0.5814456035767511, "repo_name": "xippi/passport", "id": "f84c3bee4cc390ef8e677685471e8ba5a4a891f4", "size": "13420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/index-test.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import re from EmeraldAI.Logic.Modules import Global from EmeraldAI.Config.Config import Config if(Config().Get("Database", "NLPDatabaseType").lower() == "sqlite"): from EmeraldAI.Logic.Database.SQlite3 import SQlite3 as db elif(Config().Get("Database", "NLPDatabaseType").lower() == "mysql"): from EmeraldAI.Logic.Database.MySQL import MySQL as db # This is just to distinguish between german and english def DetectLanguage(input): # 207 most common words in germen + hallo = 208 words_DE = Global.ReadDataFile("Commonwords", "de.txt") # 207 most common words in english + hello = 208 words_EN = Global.ReadDataFile("Commonwords", "en.txt") exactMatch_DE = re.compile(r'\b%s\b' % '\\b|\\b'.join( words_DE), flags=re.IGNORECASE | re.UNICODE) count_DE = len(exactMatch_DE.findall(input)) exactMatch_EN = re.compile(r'\b%s\b' % '\\b|\\b'.join( words_EN), flags=re.IGNORECASE | re.UNICODE) count_EN = len(exactMatch_EN.findall(input)) if(count_EN > count_DE): return "en" return "de" def WordSegmentation(input, extended=False): if input.startswith("TRIGGER_"): return [input] if not extended: segmentationRegex = re.compile( r"((?:\b[^\s]+\b)(?:(?<=\.\w).)?)", flags=re.UNICODE) else: segmentationRegex = re.compile( r"((?:\{)?(?:\b[^\s]+\b)(?:(?<=\.\w).)?(?:\})?)", flags=re.UNICODE) return segmentationRegex.findall(input) def GetStopwords(language): return Global.ReadDataFile("Stopwords", "{0}.txt".format(language.lower())) def RemoveStopwords(wordlist, language): stopwords = GetStopwords(language) return [x for x in wordlist if x not in stopwords] def IsStopword(word, language): stopwords = GetStopwords(language) return word in stopwords def Normalize(input, language): normalizedInput = input.lower() if(language.lower() == "all" or language.lower() == "de"): normalizedInput = normalizedInput.replace('ä', 'ae') normalizedInput = normalizedInput.replace('ü', 'ue') normalizedInput = normalizedInput.replace('ö', 'oe') normalizedInput = normalizedInput.replace('ß', 'ss') return normalizedInput def IsFirstname(input): normalizedInput = Normalize(input, "all") result = db().Fetchall("SELECT * FROM NLP_Firstname WHERE Firstname = '{0}'".format(normalizedInput.title())) return len(result) > 0 def IsLastname(input): normalizedInput = Normalize(input, "all") result = db().Fetchall("SELECT * FROM NLP_Lastname WHERE Lastname = '{0}'".format(normalizedInput.title())) return len(result) > 0 def TrimBasewords(PipelineArgs): inputString = PipelineArgs.Normalized sentence = PipelineArgs.SentenceList[PipelineArgs.ResponseID] for word in sentence.BasewordList: inputString = inputString.replace(word, "") return inputString.strip() def TrimStopwords(input, language): stopwords = GetStopwords(language) inputwords = input.split() resultwords = [word for word in inputwords if word.lower() not in stopwords] result = ' '.join(resultwords) return result
{ "content_hash": "7f5cb5e9aeb4ad192cc1825fdea929aa", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 113, "avg_line_length": 35.37078651685393, "alnum_prop": 0.6699491740787802, "repo_name": "MaxMorgenstern/EmeraldAI", "id": "ba494e705455f3d95e90605e0aa21b8ecd0f1b2b", "size": "3194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EmeraldAI/Logic/NLP/NLP.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "133" }, { "name": "C", "bytes": "34040" }, { "name": "C++", "bytes": "238832" }, { "name": "Java", "bytes": "69620" }, { "name": "Python", "bytes": "287448" }, { "name": "Shell", "bytes": "11298" } ], "symlink_target": "" }
package gui; import javafx.animation.AnimationTimer; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; import java.awt.*; /** * Created by Robin on 28-6-2015. */ public class Launcher extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { final double[] x = {0}; final double[] y = {0}; Pane root = new Pane(); Scene scene = new Scene(root,1920, 1080); Color color = Color.BLACK; CornerRadii corner = new CornerRadii(0); Insets inset = new Insets(0); BackgroundFill fill = new BackgroundFill(color, corner, inset); Background black = new Background(fill); root.setBackground(black); Text location = new Text(); location.setLayoutX(100); location.setLayoutY(50); location.setFill(Color.WHITE); Circle circle = new Circle(100,Color.BLUE); AnimationTimer timer = new AnimationTimer() { @Override public void handle(long now) { TranslateTransition tt = new TranslateTransition(Duration.millis(250), circle); Point mouse = MouseInfo.getPointerInfo().getLocation(); x[0] = mouse.getX(); y[0] = mouse.getY(); location.setText(x[0] + ", " + y[0]); tt.setToX(x[0]); tt.setToY(y[0]); tt.play(); } }; timer.start(); root.getChildren().addAll(circle, location); primaryStage.setFullScreenExitHint(""); primaryStage.setScene(scene); primaryStage.setFullScreen(true); primaryStage.show(); } }
{ "content_hash": "5acb371f8c28e91929ef6e1d38a1b515", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 95, "avg_line_length": 26.8875, "alnum_prop": 0.6211064621106462, "repo_name": "thervh70/Agar.io-Java-Clone", "id": "47894fc83d1b054dcbe0043c69f162e3aebfddbe", "size": "2151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gui/Launcher.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "11155" } ], "symlink_target": "" }
package com.github.prokod.gradle.crossbuild.model; /** * UpdateEvent type */ public enum EventType { SCALA_VERSIONS_UPDATE, EXT_UPDATE, ARCHIVE_APPENDIX_PATTERN_UPDATE }
{ "content_hash": "6e9cd764623773dc76274c256732c582", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 50, "avg_line_length": 16.818181818181817, "alnum_prop": 0.7189189189189189, "repo_name": "prokod/gradle-crossbuild-scala", "id": "9fb8febe3bb2936c00652f7eea24730af30876b4", "size": "804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/groovy/com/github/prokod/gradle/crossbuild/model/EventType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "405687" }, { "name": "Java", "bytes": "804" } ], "symlink_target": "" }
function assemble_report(data_path, requested_range, Author) % Uses the pregenerated images resulting from the wake, eigenmode and s % parameter analysis and generates the appropriate latex code to turn them % into a useable report. % % Example: assemble_report(ppi, wake_data, eigenmode_data, 'Alun Morgan', output_path) arc_names = GdfidL_find_selected_models(data_path, requested_range); for jse = 1:length(arc_names) old_path = pwd; arc_name = arc_names{jse}; % Load up the original model input parameters. % FIXME need to deal better with different solvers % this may dissapear with the refactoring of the graphs. load([data_path, '/', arc_name, '/wake/run_inputs.mat']) % Load up the data extracted from the run log. load([data_path, '/', arc_name,'/data_from_run_logs.mat']) % Load up post processing inputs load([data_path, '/', arc_name,'/pp_inputs.mat']) % Load up the post precessed data. load([data_path, '/', arc_name,'/data_postprocessed.mat']) % Setting up the latex headers etc. [param_list, param_vals] = extract_parameters(mi, run_logs); param_list = regexprep(param_list,'_',' '); report_input.author = Author; report_input.doc_num = ppi.rep_num; report_input.param_list = param_list; report_input.param_vals = param_vals; report_input.model_name = regexprep(ppi.model_name,'_',' '); report_input.doc_root = ppi.output_path; if isfield(run_logs, 'wake') report_input.date = run_logs.wake.dte; % This makes the preamble for the latex file. preamble = latex_add_preamble(report_input); % This adds in the pictures of the geometry. pics = insert_geometry_pics([data_path, '/', arc_name,'/wake/']); combined = cat(1,preamble, '\clearpage', '\chapter{Geometry}',pics); wake_ltx = generate_latex_for_wake_analysis(... pp_data.wake_data.raw_data.port.alpha,... pp_data.wake_data.raw_data.port.beta,... pp_data.wake_data.raw_data.port.frequency_cutoffs_all, ... pp_data.wake_data.raw_data.port.labels_table); combined = cat(1,combined, '\clearpage', wake_ltx); % This adds the input file to the document as an appendix. gdf_name = regexprep(ppi.model_name, 'GdfidL_',''); if exist(['pp_link/wake/', gdf_name, '.gdf'],'file') gdf_data = add_gdf_file_to_report(['pp_link/wake/', gdf_name, '.gdf']); combined = cat(1,combined,'\clearpage','\chapter{Input file}',gdf_data); end % Finish the latex document. combined = cat(1,combined,'\end{document}' ); cd([data_path, '/', arc_name,'/wake']) latex_write_file('Wake_report',combined); process_tex('.', 'Wake_report') elseif isfield(run_logs, 's_parameter') report_input.date = run_logs.s_parameter.dte; % This makes the preamble for the latex file. preamble = latex_add_preamble(report_input); % This adds in the pictures of the geometry. pics = insert_geometry_pics('pp_link/s_parameter/'); combined = cat(1,preamble, '\clearpage', '\chapter{Geometry}',pics); if exist('pp_link/s_parameter/all_sparameters.eps','file') == 2 s_ltx = generate_latex_for_s_parameter_analysis; combined = cat(1,combined, '\clearpage', s_ltx); end % This adds the input file to the document as an appendix. gdf_name = regexprep(ppi.model_name, 'GdfidL_',''); if exist(['pp_link/s_parameter/', gdf_name, '.gdf'],'file') gdf_data = add_gdf_file_to_report(['pp_link/s_parameter/', gdf_name, '.gdf']); combined = cat(1,combined,'\clearpage','\chapter{Input file}',gdf_data); end % Finish the latex document. combined = cat(1,combined,'\end{document}' ); cd('pp_link/s_parameter') latex_write_file('S_parameter_report',combined); process_tex('.', 'S_parameter_report') elseif isfield(run_logs, 'eigenmode') report_input.date = run_logs.eigenmode.dte; % This makes the preamble for the latex file. preamble = latex_add_preamble(report_input); % This adds in the pictures of the geometry. pics = insert_geometry_pics('pp_link/eigenmode/'); combined = cat(1,preamble, '\clearpage', '\chapter{Geometry}',pics); if isstruct(pp_data.eigenmode_data) eigen_lossy_ltx = generate_latex_for_eigenmode_analysis(pp_data.eigenmode_data); combined = cat(1,combined, '\clearpage', eigen_lossy_ltx); end % This adds the input file to the document as an appendix. gdf_name = regexprep(ppi.model_name, 'GdfidL_',''); if exist(['pp_link/eigenmode/', gdf_name, '.gdf'],'file') gdf_data = add_gdf_file_to_report(['pp_link/eigenmode/', gdf_name, '.gdf']); combined = cat(1,combined,'\clearpage','\chapter{Input file}',gdf_data); end % Finish the latex document. combined = cat(1,combined,'\end{document}' ); cd('pp_link/eigenmode') latex_write_file('Eigenmode_report',combined); process_tex('.', 'Eigenmode_report') elseif isfield(run_logs, 'eigenmode_lossy') report_input.date = run_logs.eigenmode_lossy.dte; % This makes the preamble for the latex file. preamble = latex_add_preamble(report_input); % This adds in the pictures of the geometry. pics = insert_geometry_pics('pp_link/lossy_eigenmode/'); combined = cat(1,preamble, '\clearpage', '\chapter{Geometry}',pics); if isstruct(pp_data.eigenmode_lossy_data) eigen_lossy_ltx = generate_latex_for_eigenmode_analysis(pp_data.eigenmode_lossy_data); combined = cat(1,combined, '\clearpage', eigen_lossy_ltx); end % This adds the input file to the document as an appendix. gdf_name = regexprep(ppi.model_name, 'GdfidL_',''); if exist(['pp_link/lossy_eigenmode/', gdf_name, '.gdf'],'file') gdf_data = add_gdf_file_to_report(['pp_link/lossy_eigenmode/', gdf_name, '.gdf']); combined = cat(1,combined,'\clearpage','\chapter{Input file}',gdf_data); end % Finish the latex document. combined = cat(1,combined,'\end{document}' ); cd('pp_link/lossy_eigenmode') latex_write_file('Lossy_eigenmode_report',combined); process_tex('.', 'Lossy_eigenmode_report') end clear run_logs ppi pp_data mi cd(old_path) end
{ "content_hash": "a3cd29bc5dbf950f90d3726578e08bb1", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 98, "avg_line_length": 49.350746268656714, "alnum_prop": 0.6165129290790866, "repo_name": "alunmorgan/EM-modellling-framework", "id": "49d731544abd48384b4c8d900ecdbdd85fa64523", "size": "6613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Report_generation/assemble_report.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Matlab", "bytes": "554480" } ], "symlink_target": "" }
<?php namespace NilPortugues\SchemaOrg\Classes; use NilPortugues\SchemaOrg\SchemaClass; /** * METHODSTART. * * @method static \NilPortugues\SchemaOrg\Properties\SupersededByProperty supersededBy() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty additionalType() * @method static \NilPortugues\SchemaOrg\Properties\AlternateNameProperty alternateName() * @method static \NilPortugues\SchemaOrg\Properties\DescriptionProperty description() * @method static \NilPortugues\SchemaOrg\Properties\ImageProperty image() * @method static \NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty mainEntityOfPage() * @method static \NilPortugues\SchemaOrg\Properties\NameProperty name() * @method static \NilPortugues\SchemaOrg\Properties\SameAsProperty sameAs() * @method static \NilPortugues\SchemaOrg\Properties\UrlProperty url() * @method static \NilPortugues\SchemaOrg\Properties\PotentialActionProperty potentialAction() * METHODEND. * * The business function specifies the type of activity or access (i.e., the bundle of rights) offered by the organization or business person through the offer. Typical are sell, rental or lease, maintenance or repair, manufacture / produce, recycle / dispose, engineering / construction, or installation. Proprietary specifications of access rights are also instances of this class. */ class BusinessFunction extends SchemaClass { /** * @var string */ protected static $schemaUrl = 'http://schema.org/BusinessFunction'; /** * @var array */ protected static $supportedMethods = [ 'additionalType' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'alternateName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlternateNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'description' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DescriptionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'image' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ImageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'mainEntityOfPage' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'name' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'potentialAction' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PotentialActionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'sameAs' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SameAsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'supersededBy' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SupersededByProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Enumeration', ], 'url' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\UrlProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], ]; }
{ "content_hash": "37c94d87802643144449ddbd6ca29ee7", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 383, "avg_line_length": 46.246753246753244, "alnum_prop": 0.6781802864363943, "repo_name": "nilportugues/schema.org-mapping", "id": "6b459867de2f524c970293c50a5e8fe224f1c914", "size": "3797", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Classes/BusinessFunction.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "13275991" } ], "symlink_target": "" }
namespace rapid { namespace core { class EventLoop { public: EventLoop(); RAPID_DISABLE_COPY(EventLoop) void start(); void stop(); void waitForEnd(); void updateChannel(Channel *channel); void removeChannel(Channel *channel); void wakeup(); private: std::atomic<bool> quit_; std::thread thread_; EPollPoller poller_; Channel wakeupChannel_; std::vector<Channel*> activeChannels_; std::shared_ptr<spdlog::logger> logger_; }; } } #endif // RAPID_CORE_EVENTLOOP_H
{ "content_hash": "7bf0f6bdff1346e368a158c56224138e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 44, "avg_line_length": 16.5, "alnum_prop": 0.6515151515151515, "repo_name": "billlin0904/librapid", "id": "39fe2aeff308670c5dddb9c0596824529d3dad62", "size": "1155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/rapid/core/eventloop.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "89051" }, { "name": "QMake", "bytes": "1690" } ], "symlink_target": "" }
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/screens/user_selection_screen.h" #include <stddef.h> #include <memory> #include <utility> #include "ash/components/arc/arc_util.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" #include "ash/constants/ash_switches.h" #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/ash/login/demo_mode/demo_session.h" #include "chrome/browser/ash/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/ash/login/helper.h" #include "chrome/browser/ash/login/lock/screen_locker.h" #include "chrome/browser/ash/login/lock_screen_utils.h" #include "chrome/browser/ash/login/quick_unlock/fingerprint_utils.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_factory.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_storage.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_utils.h" #include "chrome/browser/ash/login/reauth_stats.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/ui/views/user_board_view.h" #include "chrome/browser/ash/login/users/chrome_user_manager.h" #include "chrome/browser/ash/login/users/default_user_image/default_user_images.h" #include "chrome/browser/ash/login/users/multi_profile_user_controller.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/ash/system/system_clock.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/ui/ash/login_screen_client_impl.h" #include "chrome/browser/ui/webui/ash/login/l10n_util.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "chromeos/ash/components/cryptohome/cryptohome_parameters.h" #include "chromeos/ash/components/dbus/dbus_thread_manager.h" #include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h" #include "chromeos/ash/components/proximity_auth/screenlock_bridge.h" #include "chromeos/ash/components/proximity_auth/smart_lock_metrics_recorder.h" #include "chromeos/ash/components/settings/cros_settings_names.h" #include "chromeos/dbus/tpm_manager/tpm_manager.pb.h" #include "chromeos/dbus/tpm_manager/tpm_manager_client.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_service.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "content/public/browser/device_service.h" #include "google_apis/gaia/gaia_auth_util.h" #include "services/device/public/mojom/wake_lock.mojom.h" #include "services/device/public/mojom/wake_lock_provider.mojom.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" // Enable VLOG level 1. #undef ENABLED_VLOG_LEVEL #define ENABLED_VLOG_LEVEL 1 namespace ash { namespace { const char kWakeLockReason[] = "TPMLockedIssue"; const int kWaitingOvertimeInSeconds = 1; // Max number of users to show. // Please keep synced with one in signin_userlist_unittest.cc. const size_t kMaxUsers = 50; // Returns true if we have enterprise domain information. // `out_manager`: Output value of the manager of the device's domain. Can be // either a domain (foo.com) or an email address ([email protected]) bool GetDeviceManager(std::string* out_manager) { policy::BrowserPolicyConnectorAsh* policy_connector = g_browser_process->platform_part()->browser_policy_connector_ash(); if (policy_connector->IsCloudManaged()) { *out_manager = policy_connector->GetEnterpriseDomainManager(); return true; } return false; } // Get locales information of public account user. // Returns a list of available locales. // `public_session_recommended_locales`: This can be nullptr if we don't have // recommended locales. // `out_selected_locale`: Output value of the initially selected locale. // `out_multiple_locales`: Output value indicates whether we have multiple // recommended locales. base::Value::List GetPublicSessionLocales( const std::vector<std::string>* public_session_recommended_locales, std::string* out_selected_locale, bool* out_multiple_locales) { std::vector<std::string> kEmptyRecommendedLocales; const std::vector<std::string>& recommended_locales = public_session_recommended_locales ? *public_session_recommended_locales : kEmptyRecommendedLocales; // Construct the list of available locales. This list consists of the // recommended locales, followed by all others. auto available_locales = GetUILanguageList(&recommended_locales, std::string(), input_method::InputMethodManager::Get()); // Select the the first recommended locale that is actually available or the // current UI locale if none of them are available. *out_selected_locale = FindMostRelevantLocale(recommended_locales, available_locales, g_browser_process->GetApplicationLocale()); *out_multiple_locales = recommended_locales.size() >= 2; return available_locales; } // Returns true if dircrypto migration check should be performed. // TODO(achuith): Get rid of this function altogether. bool ShouldCheckNeedDircryptoMigration() { return arc::IsArcAvailable(); } // Returns true if the user can run ARC based on the user type. bool IsUserAllowedForARC(const AccountId& account_id) { return user_manager::UserManager::IsInitialized() && arc::IsArcAllowedForUser( user_manager::UserManager::Get()->FindUser(account_id)); } AccountId GetOwnerAccountId() { std::string owner_email; CrosSettings::Get()->GetString(kDeviceOwner, &owner_email); user_manager::KnownUser known_user(g_browser_process->local_state()); const AccountId owner = known_user.GetAccountId( owner_email, std::string() /* id */, AccountType::UNKNOWN); return owner; } bool IsDeviceEnterpriseManaged() { policy::BrowserPolicyConnectorAsh* connector = g_browser_process->platform_part()->browser_policy_connector_ash(); return connector->IsDeviceEnterpriseManaged(); } bool IsSigninToAdd() { return LoginDisplayHost::default_host() && user_manager::UserManager::Get()->IsUserLoggedIn(); } bool CanRemoveUser(const user_manager::User* user) { const bool is_single_user = user_manager::UserManager::Get()->GetUsers().size() == 1; // Single user check here is necessary because owner info might not be // available when running into login screen on first boot. // See http://crosbug.com/12723 if (is_single_user && !IsDeviceEnterpriseManaged()) return false; if (!user->GetAccountId().is_valid()) return false; if (user->GetAccountId() == GetOwnerAccountId()) return false; if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT || user->is_logged_in() || IsSigninToAdd()) return false; return true; } void GetMultiProfilePolicy(const user_manager::User* user, bool* out_is_allowed, MultiProfileUserBehavior* out_policy) { const std::string& user_id = user->GetAccountId().GetUserEmail(); MultiProfileUserController* multi_profile_user_controller = ChromeUserManager::Get()->GetMultiProfileUserController(); MultiProfileUserController::UserAllowedInSessionReason is_user_allowed_reason; *out_is_allowed = multi_profile_user_controller->IsUserAllowedInSession( user_id, &is_user_allowed_reason); std::string policy; if (is_user_allowed_reason == MultiProfileUserController::NOT_ALLOWED_OWNER_AS_SECONDARY) { policy = MultiProfileUserController::kBehaviorOwnerPrimaryOnly; } else { policy = multi_profile_user_controller->GetCachedValue(user_id); } *out_policy = MultiProfileUserController::UserBehaviorStringToEnum(policy); } } // namespace // Helper class to call cryptohome to check whether a user needs dircrypto // migration. The check results are cached to limit calls to cryptohome. class UserSelectionScreen::DircryptoMigrationChecker { public: explicit DircryptoMigrationChecker(UserSelectionScreen* owner) : owner_(owner) {} DircryptoMigrationChecker(const DircryptoMigrationChecker&) = delete; DircryptoMigrationChecker& operator=(const DircryptoMigrationChecker&) = delete; ~DircryptoMigrationChecker() = default; // Start to check whether the given user needs dircrypto migration. void Check(const AccountId& account_id) { focused_user_ = account_id; // If the user may be enterprise-managed, don't display the banner, because // migration may be blocked by user policy (and user policy is not available // at this time yet). if (!policy::BrowserPolicyConnector::IsNonEnterpriseUser( account_id.GetUserEmail())) { UpdateUI(account_id, false); return; } auto it = needs_dircrypto_migration_cache_.find(account_id); if (it != needs_dircrypto_migration_cache_.end()) { UpdateUI(account_id, it->second); return; } // No banner if the user is not allowed for ARC. if (!IsUserAllowedForARC(account_id)) { UpdateUI(account_id, false); return; } UserDataAuthClient::Get()->WaitForServiceToBeAvailable( base::BindOnce(&DircryptoMigrationChecker::RunCryptohomeCheck, weak_ptr_factory_.GetWeakPtr(), account_id)); } private: // WaitForServiceToBeAvailable callback to invoke NeedsDircryptoMigration when // cryptohome service is available. void RunCryptohomeCheck(const AccountId& account_id, bool service_is_ready) { if (!service_is_ready) { LOG(ERROR) << "Cryptohome is not available."; return; } user_data_auth::NeedsDircryptoMigrationRequest request; *request.mutable_account_id() = cryptohome::CreateAccountIdentifierFromAccountId(account_id); UserDataAuthClient::Get()->NeedsDircryptoMigration( request, base::BindOnce(&DircryptoMigrationChecker:: OnCryptohomeNeedsDircryptoMigrationCallback, weak_ptr_factory_.GetWeakPtr(), account_id)); } // Callback invoked when NeedsDircryptoMigration call is finished. void OnCryptohomeNeedsDircryptoMigrationCallback( const AccountId& account_id, absl::optional<user_data_auth::NeedsDircryptoMigrationReply> reply) { if (!reply.has_value()) { LOG(ERROR) << "Failed to call cryptohome NeedsDircryptoMigration."; // Hide the banner to avoid confusion in http://crbug.com/721948. // Cache is not updated so that cryptohome call will still be attempted. UpdateUI(account_id, false); return; } bool needs_migration = reply->needs_dircrypto_migration(); UMA_HISTOGRAM_BOOLEAN("Ash.Login.Login.MigrationBanner", needs_migration); needs_dircrypto_migration_cache_[account_id] = needs_migration; UpdateUI(account_id, needs_migration); } // Update UI for the given user when the check result is available. void UpdateUI(const AccountId& account_id, bool needs_migration) { // Bail if the user is not the currently focused. if (account_id != focused_user_) return; owner_->ShowBannerMessage( needs_migration ? l10n_util::GetStringUTF16( IDS_LOGIN_NEEDS_DIRCRYPTO_MIGRATION_BANNER) : std::u16string(), needs_migration); } UserSelectionScreen* const owner_; AccountId focused_user_ = EmptyAccountId(); // Cached result of NeedsDircryptoMigration cryptohome check. Key is the // account id of users. True value means the user needs dircrypto migration // and false means dircrypto migration is done. std::map<AccountId, bool> needs_dircrypto_migration_cache_; base::WeakPtrFactory<DircryptoMigrationChecker> weak_ptr_factory_{this}; }; // Helper class to check whether tpm is locked and update UI with time left to // unlocking. class UserSelectionScreen::TpmLockedChecker { public: explicit TpmLockedChecker(UserSelectionScreen* owner) : owner_(owner) {} TpmLockedChecker(const TpmLockedChecker&) = delete; TpmLockedChecker& operator=(const TpmLockedChecker&) = delete; ~TpmLockedChecker() = default; void Check() { UserDataAuthClient::Get()->WaitForServiceToBeAvailable(base::BindOnce( &TpmLockedChecker::RunCryptohomeCheck, weak_ptr_factory_.GetWeakPtr())); } private: void RunCryptohomeCheck(bool service_is_ready) { if (!service_is_ready) { LOG(ERROR) << "Cryptohome is not available."; return; } // Though this function sends D-Bus call to tpm manager, it makes sense to // still wait for cryptohome because the the side effect of the lock has to // be propagated to cryptohome to cause the known issue of interest. chromeos::TpmManagerClient::Get()->GetDictionaryAttackInfo( ::tpm_manager::GetDictionaryAttackInfoRequest(), base::BindOnce(&TpmLockedChecker::OnGetDictionaryAttackInfo, weak_ptr_factory_.GetWeakPtr())); } // Callback invoked when GetDictionaryAttackInfo call is finished. void OnGetDictionaryAttackInfo( const ::tpm_manager::GetDictionaryAttackInfoReply& reply) { check_finised_ = base::TimeTicks::Now(); if (reply.status() != ::tpm_manager::STATUS_SUCCESS) return; if (reply.dictionary_attack_lockout_in_effect()) { // Add `kWaitingOvertimeInSeconds` for safetiness, i.e hiding UI and // releasing `wake_lock_` happens after TPM becomes unlocked. dictionary_attack_lockout_time_remaining_ = base::Seconds(reply.dictionary_attack_lockout_seconds_remaining() + kWaitingOvertimeInSeconds); OnTpmIsLocked(); } else { TpmIsUnlocked(); } } void OnTpmIsLocked() { AcquireWakeLock(); clock_ticking_animator_.Start(FROM_HERE, base::Seconds(1), this, &TpmLockedChecker::UpdateUI); tpm_recheck_.Start(FROM_HERE, base::Minutes(1), this, &TpmLockedChecker::Check); } void UpdateUI() { const base::TimeDelta time_spent = base::TimeTicks::Now() - check_finised_; if (time_spent > dictionary_attack_lockout_time_remaining_) { Check(); } else { owner_->SetTpmLockedState( true, dictionary_attack_lockout_time_remaining_ - time_spent); } } void TpmIsUnlocked() { clock_ticking_animator_.Stop(); tpm_recheck_.Stop(); owner_->SetTpmLockedState(false, base::TimeDelta()); } void AcquireWakeLock() { if (!wake_lock_) { mojo::Remote<device::mojom::WakeLockProvider> provider; content::GetDeviceService().BindWakeLockProvider( provider.BindNewPipeAndPassReceiver()); provider->GetWakeLockWithoutContext( device::mojom::WakeLockType::kPreventDisplaySleep, device::mojom::WakeLockReason::kOther, kWakeLockReason, wake_lock_.BindNewPipeAndPassReceiver()); } // The `wake_lock_` is released once TpmLockedChecker is destroyed. // It happens after successful login. wake_lock_->RequestWakeLock(); } UserSelectionScreen* const owner_; base::TimeTicks check_finised_; base::TimeDelta dictionary_attack_lockout_time_remaining_; base::RepeatingTimer clock_ticking_animator_; base::RepeatingTimer tpm_recheck_; mojo::Remote<device::mojom::WakeLock> wake_lock_; base::WeakPtrFactory<TpmLockedChecker> weak_ptr_factory_{this}; }; UserSelectionScreen::UserSelectionScreen(DisplayedScreen display_type) : display_type_(display_type) { session_manager::SessionManager::Get()->AddObserver(this); if (display_type_ != DisplayedScreen::SIGN_IN_SCREEN) return; allowed_input_methods_subscription_ = CrosSettings::Get()->AddSettingsObserver( kDeviceLoginScreenInputMethods, base::BindRepeating( &UserSelectionScreen::OnAllowedInputMethodsChanged, base::Unretained(this))); OnAllowedInputMethodsChanged(); } UserSelectionScreen::~UserSelectionScreen() { proximity_auth::ScreenlockBridge::Get()->SetLockHandler(nullptr); session_manager::SessionManager::Get()->RemoveObserver(this); } void UserSelectionScreen::InitEasyUnlock() { proximity_auth::ScreenlockBridge::Get()->SetLockHandler(this); } void UserSelectionScreen::SetTpmLockedState(bool is_locked, base::TimeDelta time_left) { for (user_manager::User* user : users_) { view_->SetTpmLockedState(user->GetAccountId(), is_locked, time_left); } } // static bool UserSelectionScreen::ShouldForceOnlineSignIn( const user_manager::User* user) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSkipForceOnlineSignInForTesting)) { return false; } // Public sessions are always allowed to log in offline. // Deprecated supervised users are always allowed to log in offline. // For all other users, force online sign in if: // * The flag to force online sign-in is set for the user. // * The user's OAuth token is invalid or unknown. if (user->is_logged_in()) return false; const user_manager::User::OAuthTokenStatus token_status = user->oauth_token_status(); const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool has_gaia_account = user->HasGaiaAccount(); if (is_public_session) return false; // At this point the reason for invalid token should be already set. If not, // this might be a leftover from an old version. if (has_gaia_account && token_status == user_manager::User::OAUTH2_TOKEN_STATUS_INVALID) RecordReauthReason(user->GetAccountId(), ReauthReason::kOther); // We need to force an online signin if the user is marked as requiring it or // if there's an invalid OAUTH token that needs to be refreshed. if (user->force_online_signin()) { VLOG(1) << "Online login forced by user flag"; return true; } if (has_gaia_account && (token_status == user_manager::User::OAUTH2_TOKEN_STATUS_INVALID || token_status == user_manager::User::OAUTH_TOKEN_STATUS_UNKNOWN)) { VLOG(1) << "Online login forced due to invalid OAuth2 token status: " << token_status; return true; } user_manager::KnownUser known_user(g_browser_process->local_state()); const absl::optional<base::TimeDelta> offline_signin_time_limit = known_user.GetOfflineSigninLimit(user->GetAccountId()); if (!offline_signin_time_limit) return false; const base::Time last_gaia_signin_time = known_user.GetLastOnlineSignin(user->GetAccountId()); if (last_gaia_signin_time == base::Time()) return false; const base::Time now = base::DefaultClock::GetInstance()->Now(); const base::TimeDelta time_since_last_gaia_signin = now - last_gaia_signin_time; if (time_since_last_gaia_signin >= offline_signin_time_limit) return true; return false; } // static UserAvatar UserSelectionScreen::BuildAshUserAvatarForUser( const user_manager::User& user) { UserAvatar avatar; avatar.image = user.GetImage(); if (avatar.image.isNull()) { avatar.image = *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_LOGIN_DEFAULT_USER); } // TODO(jdufault): Unify image handling between this code and // user_image_source::GetUserImageInternal. auto load_image_from_resource = [&avatar](int resource_id) { auto& rb = ui::ResourceBundle::GetSharedInstance(); base::StringPiece avatar_data = rb.GetRawDataResourceForScale( resource_id, rb.GetMaxResourceScaleFactor()); avatar.bytes.assign(avatar_data.begin(), avatar_data.end()); }; // After the avatar cloud migration, remove the second if case. if (user.has_image_bytes()) { avatar.bytes.assign( user.image_bytes()->front(), user.image_bytes()->front() + user.image_bytes()->size()); } else if (user.HasDefaultImage()) { int resource_id = default_user_image::GetDefaultImageResourceId(user.image_index()); load_image_from_resource(resource_id); } else if (user.image_is_stub()) { load_image_from_resource(IDR_LOGIN_DEFAULT_USER); } return avatar; } void UserSelectionScreen::SetView(UserBoardView* view) { view_ = view; } void UserSelectionScreen::Init(const user_manager::UserList& users) { users_ = users; if (!ime_state_.get()) ime_state_ = input_method::InputMethodManager::Get()->GetActiveIMEState(); // Resets observed object in case of re-Init, no-op otherwise. scoped_observation_.Reset(); // Login screen-only logic to send users through the online re-auth. // In-session (including the lock screen) is handled by // InSessionPasswordSyncManager. if (users.size() > 0 && display_type_ == DisplayedScreen::SIGN_IN_SCREEN) { online_signin_notifier_ = std::make_unique<UserOnlineSigninNotifier>(users); scoped_observation_.Observe(online_signin_notifier_.get()); online_signin_notifier_->CheckForPolicyEnforcedOnlineSignin(); sync_token_checkers_ = std::make_unique<PasswordSyncTokenCheckersCollection>(); sync_token_checkers_->StartPasswordSyncCheckers(users, this); } else { sync_token_checkers_.reset(); } if (tpm_locked_checker_) return; tpm_locked_checker_ = std::make_unique<TpmLockedChecker>(this); tpm_locked_checker_->Check(); } // static const user_manager::UserList UserSelectionScreen::PrepareUserListForSending( const user_manager::UserList& users, const AccountId& owner, bool is_signin_to_add) { user_manager::UserList users_to_send; bool has_owner = owner.is_valid(); size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers; size_t non_owner_count = 0; for (user_manager::User* user : users) { bool is_owner = user->GetAccountId() == owner; bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; if ((is_public_account && !is_signin_to_add) || is_owner || (!is_public_account && non_owner_count < max_non_owner_users)) { if (!is_owner) ++non_owner_count; if (is_owner && users_to_send.size() > kMaxUsers) { // Owner is always in the list. users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), user); while (users_to_send.size() > kMaxUsers) users_to_send.erase(users_to_send.begin() + kMaxUsers); } else if (users_to_send.size() < kMaxUsers) { users_to_send.push_back(user); } } } return users_to_send; } void UserSelectionScreen::CheckUserStatus(const AccountId& account_id) { // No checks on the multi-profiles signin or locker screen. if (user_manager::UserManager::Get()->IsUserLoggedIn()) return; if (!token_handle_util_.get()) { token_handle_util_ = std::make_unique<TokenHandleUtil>(); } if (token_handle_util_->HasToken(account_id)) { token_handle_util_->CheckToken( account_id, ProfileHelper::Get()->GetSigninProfile()->GetURLLoaderFactory(), base::BindOnce(&UserSelectionScreen::OnUserStatusChecked, weak_factory_.GetWeakPtr())); } // Run dircrypto migration check only on the login screen when necessary. if (display_type_ == DisplayedScreen::SIGN_IN_SCREEN && ShouldCheckNeedDircryptoMigration()) { if (!dircrypto_migration_checker_) { dircrypto_migration_checker_ = std::make_unique<DircryptoMigrationChecker>(this); } dircrypto_migration_checker_->Check(account_id); } } void UserSelectionScreen::HandleFocusPod(const AccountId& account_id) { DCHECK(!pending_focused_account_id_.has_value()); const session_manager::SessionState session_state = session_manager::SessionManager::Get()->session_state(); if (session_state == session_manager::SessionState::ACTIVE) { // Wait for the session state change before actual work. pending_focused_account_id_ = account_id; return; } proximity_auth::ScreenlockBridge::Get()->SetFocusedUser(account_id); if (focused_pod_account_id_ == account_id) return; CheckUserStatus(account_id); lock_screen_utils::SetUserInputMethod( account_id, ime_state_.get(), display_type_ == DisplayedScreen::SIGN_IN_SCREEN /* honor_device_policy */); lock_screen_utils::SetKeyboardSettings(account_id); user_manager::KnownUser known_user(g_browser_process->local_state()); absl::optional<bool> use_24hour_clock = known_user.FindBoolPath(account_id, ::prefs::kUse24HourClock); if (!use_24hour_clock.has_value()) { focused_user_clock_type_.reset(); } else { base::HourClockType clock_type = use_24hour_clock.value() ? base::k24HourClock : base::k12HourClock; if (focused_user_clock_type_.has_value()) { focused_user_clock_type_->UpdateClockType(clock_type); } else { focused_user_clock_type_ = g_browser_process->platform_part() ->GetSystemClock() ->CreateScopedHourClockType(clock_type); } } focused_pod_account_id_ = account_id; } void UserSelectionScreen::HandleNoPodFocused() { focused_pod_account_id_ = EmptyAccountId(); focused_user_clock_type_.reset(); if (display_type_ == DisplayedScreen::SIGN_IN_SCREEN) lock_screen_utils::EnforceDevicePolicyInputMethods(std::string()); } void UserSelectionScreen::OnAllowedInputMethodsChanged() { DCHECK_EQ(display_type_, DisplayedScreen::SIGN_IN_SCREEN); if (focused_pod_account_id_.is_valid()) { std::string user_input_method_id = lock_screen_utils::GetUserLastInputMethodId(focused_pod_account_id_); lock_screen_utils::EnforceDevicePolicyInputMethods(user_input_method_id); } else { lock_screen_utils::EnforceDevicePolicyInputMethods(std::string()); } } void UserSelectionScreen::OnBeforeShow() { input_method::InputMethodManager::Get()->SetState(ime_state_); } void UserSelectionScreen::OnUserStatusChecked( const AccountId& account_id, TokenHandleUtil::TokenHandleStatus status) { if (status == TokenHandleUtil::INVALID) { RecordReauthReason(account_id, ReauthReason::kInvalidTokenHandle); SetAuthType(account_id, proximity_auth::mojom::AuthType::ONLINE_SIGN_IN, std::u16string()); } } // EasyUnlock stuff void UserSelectionScreen::SetAuthType(const AccountId& account_id, proximity_auth::mojom::AuthType auth_type, const std::u16string& initial_value) { if (GetAuthType(account_id) == proximity_auth::mojom::AuthType::FORCE_OFFLINE_PASSWORD) { return; } DCHECK(GetAuthType(account_id) != proximity_auth::mojom::AuthType::FORCE_OFFLINE_PASSWORD || auth_type == proximity_auth::mojom::AuthType::FORCE_OFFLINE_PASSWORD); user_auth_type_map_[account_id] = auth_type; view_->SetAuthType(account_id, auth_type, initial_value); } proximity_auth::mojom::AuthType UserSelectionScreen::GetAuthType( const AccountId& account_id) const { if (user_auth_type_map_.find(account_id) == user_auth_type_map_.end()) return proximity_auth::mojom::AuthType::OFFLINE_PASSWORD; return user_auth_type_map_.find(account_id)->second; } proximity_auth::ScreenlockBridge::LockHandler::ScreenType UserSelectionScreen::GetScreenType() const { switch (display_type_) { case DisplayedScreen::LOCK_SCREEN: return ScreenType::LOCK_SCREEN; case DisplayedScreen::SIGN_IN_SCREEN: return ScreenType::SIGNIN_SCREEN; default: return ScreenType::OTHER_SCREEN; } } void UserSelectionScreen::ShowBannerMessage(const std::u16string& message, bool is_warning) { view_->ShowBannerMessage(message, is_warning); } void UserSelectionScreen::ShowUserPodCustomIcon( const AccountId& account_id, const proximity_auth::ScreenlockBridge::UserPodCustomIconInfo& icon_info) { if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) return; view_->ShowUserPodCustomIcon(account_id, icon_info); } void UserSelectionScreen::HideUserPodCustomIcon(const AccountId& account_id) { if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) return; view_->HideUserPodCustomIcon(account_id); } void UserSelectionScreen::SetSmartLockState(const AccountId& account_id, SmartLockState state) { if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) { view_->SetSmartLockState(account_id, state); } } void UserSelectionScreen::NotifySmartLockAuthResult(const AccountId& account_id, bool success) { if (base::FeatureList::IsEnabled(features::kSmartLockUIRevamp)) { view_->NotifySmartLockAuthResult(account_id, success); } } void UserSelectionScreen::EnableInput() { // If Easy Unlock fails to unlock the screen, re-enable the password input. // This is only necessary on the lock screen, because the error handling for // the sign-in screen uses a different code path. if (ScreenLocker::default_screen_locker()) ScreenLocker::default_screen_locker()->EnableInput(); } void UserSelectionScreen::Unlock(const AccountId& account_id) { DCHECK_EQ(GetScreenType(), LOCK_SCREEN); ScreenLocker::Hide(); } void UserSelectionScreen::AttemptEasySignin(const AccountId& account_id, const std::string& secret, const std::string& key_label) { DCHECK_EQ(GetScreenType(), SIGNIN_SCREEN); const user_manager::User* const user = user_manager::UserManager::Get()->FindUser(account_id); DCHECK(user); UserContext user_context(*user); user_context.SetAuthFlow(UserContext::AUTH_FLOW_EASY_UNLOCK); user_context.SetKey(Key(secret)); user_context.GetKey()->SetLabel(key_label); // LoginDisplayHost does not exist in views-based lock screen. if (LoginDisplayHost::default_host()) { LoginDisplayHost::default_host()->GetLoginDisplay()->delegate()->Login( user_context, SigninSpecifics()); } else { SmartLockMetricsRecorder::RecordAuthResultSignInFailure( SmartLockMetricsRecorder::SmartLockAuthResultFailureReason:: kLoginDisplayHostDoesNotExist); } } void UserSelectionScreen::OnSessionStateChanged() { if (!pending_focused_account_id_.has_value()) return; DCHECK(session_manager::SessionManager::Get()->IsUserSessionBlocked()); AccountId focused_pod(pending_focused_account_id_.value()); pending_focused_account_id_.reset(); HandleFocusPod(focused_pod); } void UserSelectionScreen::OnInvalidSyncToken(const AccountId& account_id) { RecordReauthReason(account_id, ReauthReason::kSamlPasswordSyncTokenValidationFailed); SetAuthType(account_id, proximity_auth::mojom::AuthType::ONLINE_SIGN_IN, std::u16string()); } void UserSelectionScreen::OnOnlineSigninEnforced(const AccountId& account_id) { SetAuthType(account_id, proximity_auth::mojom::AuthType::ONLINE_SIGN_IN, std::u16string()); } void UserSelectionScreen::HardLockPod(const AccountId& account_id) { view_->SetAuthType(account_id, proximity_auth::mojom::AuthType::OFFLINE_PASSWORD, std::u16string()); EasyUnlockService* service = GetEasyUnlockServiceForUser(account_id); if (!service) return; service->SetHardlockState(SmartLockStateHandler::USER_HARDLOCK); } void UserSelectionScreen::AttemptEasyUnlock(const AccountId& account_id) { EasyUnlockService* service = GetEasyUnlockServiceForUser(account_id); if (!service) return; service->AttemptAuth(account_id); } std::vector<LoginUserInfo> UserSelectionScreen::UpdateAndReturnUserListForAsh() { std::vector<LoginUserInfo> user_info_list; const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (const user_manager::User* user : users_to_send_) { const AccountId& account_id = user->GetAccountId(); bool is_owner = owner == account_id; const bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(user) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; LoginUserInfo user_info; user_info.basic_user_info.type = user->GetType(); user_info.basic_user_info.account_id = user->GetAccountId(); user_manager::KnownUser known_user(g_browser_process->local_state()); user_info.use_24hour_clock = known_user.FindBoolPath(account_id, ::prefs::kUse24HourClock) .value_or(base::GetHourClockType() == base::k24HourClock); user_info.basic_user_info.display_name = base::UTF16ToUTF8(user->GetDisplayName()); user_info.basic_user_info.display_email = user->display_email(); user_info.basic_user_info.avatar = BuildAshUserAvatarForUser(*user); user_info.auth_type = initial_auth_type; user_info.is_signed_in = user->is_logged_in(); user_info.is_device_owner = is_owner; user_info.can_remove = CanRemoveUser(user); user_info.fingerprint_state = quick_unlock::GetFingerprintStateForUser( user, quick_unlock::Purpose::kUnlock); auto* easy_unlock_service = GetEasyUnlockServiceForUser(account_id); if (easy_unlock_service) { user_info.smart_lock_state = easy_unlock_service->GetInitialSmartLockState(); } user_info.show_pin_pad_for_password = false; if (known_user.GetIsEnterpriseManaged(user->GetAccountId()) && user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) { if (const std::string* account_manager = known_user.GetAccountManager(user->GetAccountId())) { user_info.user_account_manager = *account_manager; } else { user_info.user_account_manager = gaia::ExtractDomainName(user->display_email()); } } CrosSettings::Get()->GetBoolean(kDeviceShowNumericKeyboardForPassword, &user_info.show_pin_pad_for_password); if (absl::optional<bool> show_display_password_button = known_user.FindBoolPath( user->GetAccountId(), prefs::kLoginDisplayPasswordButtonEnabled)) { user_info.show_display_password_button = show_display_password_button.value(); } // Fill multi-profile data. if (!is_signin_to_add) { user_info.is_multiprofile_allowed = true; } else { GetMultiProfilePolicy(user, &user_info.is_multiprofile_allowed, &user_info.multiprofile_policy); } // Fill public session data. if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { std::string manager; user_info.public_account_info.emplace(); if (GetDeviceManager(&manager)) user_info.public_account_info->device_enterprise_manager = manager; user_info.public_account_info->using_saml = user->using_saml(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; std::string selected_locale; bool has_multiple_locales; auto available_locales = GetPublicSessionLocales(public_session_recommended_locales, &selected_locale, &has_multiple_locales); user_info.public_account_info->available_locales = lock_screen_utils::FromListValueToLocaleItem( std::move(available_locales)); user_info.public_account_info->default_locale = selected_locale; user_info.public_account_info->show_advanced_view = has_multiple_locales; // Do not show expanded view when in demo mode. user_info.public_account_info->show_expanded_view = !DemoSession::IsDeviceInDemoMode(); } user_info.can_remove = CanRemoveUser(user); // Send a request to get keyboard layouts for default locale. if (is_public_account && LoginScreenClientImpl::HasInstance()) { LoginScreenClientImpl::Get()->RequestPublicSessionKeyboardLayouts( account_id, user_info.public_account_info->default_locale); } user_info_list.push_back(std::move(user_info)); } return user_info_list; } void UserSelectionScreen::SetUsersLoaded(bool loaded) { users_loaded_ = loaded; } EasyUnlockService* UserSelectionScreen::GetEasyUnlockServiceForUser( const AccountId& account_id) const { if (GetScreenType() == OTHER_SCREEN) return nullptr; const user_manager::User* unlock_user = nullptr; for (const user_manager::User* user : users_) { if (user->GetAccountId() == account_id) { unlock_user = user; break; } } if (!unlock_user) return nullptr; ProfileHelper* profile_helper = ProfileHelper::Get(); Profile* profile = profile_helper->GetProfileByUser(unlock_user); // If the active screen is the lock screen, a Profile must exist that is // associated with |unlock_user|. This does not apply vice-versa: there are // some valid scenarios where |profile| exists but the active screen is not // the lock screen. if (GetScreenType() == LOCK_SCREEN) { DCHECK(profile); } if (!profile) profile = profile_helper->GetSigninProfile(); return EasyUnlockService::Get(profile); } } // namespace ash
{ "content_hash": "83554082a5c690a19302a91c59c55c3c", "timestamp": "", "source": "github", "line_count": 1013, "max_line_length": 82, "avg_line_length": 38.133267522211256, "alnum_prop": 0.6966527738227757, "repo_name": "chromium/chromium", "id": "2373610af302b3a8f597def4b67ca6be9a4cbbb2", "size": "38629", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "chrome/browser/ash/login/screens/user_selection_screen.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.strategy; public class Test { public static void main(String[] args) { //mozemo dodeliti bilo koju strateguju da uradi sortiranje int[] var = {1, 2, 3, 4, 5 }; Context ctx = new Context(new BubbleSort()); ctx.arrange(var); //mozemo promeniti strategiju bez potrebe da menjamo Context klasu ctx = new Context(new QuickSort()); ctx.arrange(var); } }
{ "content_hash": "a81cb427791635ff5b5f9b57fbef0ddb", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 74, "avg_line_length": 23.88888888888889, "alnum_prop": 0.6116279069767442, "repo_name": "stapetro/mnk_javabasic", "id": "41fef5ed1e72582068b283d71959dcb5c4518598", "size": "430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/strategy/Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "23723" } ], "symlink_target": "" }
<html><head><META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet" href="css/jquery.mobile-1.2.0.css" /><style type="text/css">.content-primary {text-align: left;}#header h3 {text-align: left;}</style><script src="js/jquery.js"></script><script src="js/jquery.mobile-1.2.0.js"></script></head><body><div id="page1" data-role="page"><div id="header" data-position="fixed" data-role="header" data-theme="e"><h3><strong>ALÝ BÝN ÞÝHAB </strong></h3><a class="ui-btn-right" href="../index.html" data-role="button" data-icon="home">Geri</a></div><div data-role="content" align = "center"><div class="content-primary">Mýsýr evliyâsýndan. Doðum târihi belli deðildir. Nesebi dördüncü dedede Tilmsan sultâný Ebû Abdullah'a, sonra da Seyyid Muhammed bin Hanefiyye'ye ulaþýr. Büyük âlim Ýmâm-ý Þa'rânî'nin dedesidir. Ali bin Þihâb küçük yaþta babasýný kaybetti. Annesinin terbiyesi ile büyüdü. Ücretle köylülerin hayvanlarýný otlatýrdý, nafakasýný çobanlýktan saðlardý. Hayvan güderken, bir yandan da Kur'ân-ý kerîmi ezberlerdi. Bir gün, oradan geçmekte olan bir derviþ, onun yanýna gelip; "Yavrum, beni iyi dinle! Annene danýþ, Kâhire'ye git, orada ilim öðren." dedi. Ali bin Þihâb akþam eve gidince durumu annesine anlattý. Annesi, ilim tahsîl etmesini uygun görerek yanýna dört ay kadar yetecek azýk hazýrladý. Kâhire'ye giden Ali bin Þihâb, El-Minhâc, Eþ-Þâtibiyye, El-Minhâ adlý eserleri okudu. Âdeti üzere annesi ona devamlý þekerli ve tahinli ekmek getirir veya gönderirdi. Bu onun gýdâsý idi. Annesi onun çamaþýrlarýný yýkamak istedi. Oðlunun bülûð çaðýna geldiðini anlayýnca; "Yavrum! Bu belde ehlinden sana zarar gelmesinden korkarým. Gel seni kendi memleketinden birisi ile evlendireyim." dedi. Annesine çok itâatkâr olduðu için, emrini dinledi. Ali bin Þihâb; "Ben, ilmi ve ahlâký anamdan öðrendim." buyururdu. Ali bin Þihâb, verâ sâhibi idi. Þüphelilerden çok sakýnýrdý. Deðirmene gittiðinde, kendisinden önce un öðütülmüþ ise, taþý kaldýrýr, baþkalarýnýn un kalýntýlarýný temizler, bunlarý toplayýp hamur yapar, sonra hayvanlara verirdi. Daha sonra kendi buðdayýný öðütürdü. Baþkalarýna âit tarlanýn otundan ve ekininden beslenmiþ olmalarý ihtimâliyle, vefâtýna kadar, ekini ve otu bol olan yerlerde otlayan hayvanlarýn etinden yemedi. Çok verâ sâhibi olmasý sebebiyle, arýnýn yaptýðý balý da yemezdi. Sebebini soranlara; "Bahçe sâhiplerini, bahçelerindeki þeftâli, zerdâli v.s. aðaçlarýndan arýlarý kovarken gördüm. Onlarýn çiçeklerinden alýp yemelerine müsâade etmiyorlar. Allahü teâlâ, baþkalarýnýn rýzâsý olmadan, onlarýn arâzisinde, inek otlatmayý haram kýldý. Hem rýzâlarý dýþýnda ineði otlatacaksýn, hem de sütünü saðýp içeceksin, böyle þey olmaz." buyurdu. Kendisine getirilen hediyeleri dul ve yetimlere daðýtýrdý Ali bin Þihâb, birine bir þey satýp da alacaðý parada þüpheye düþtüðünde, o parayý almaz, müþterinin istediði þeyi ona verir, ihtiyâcýný karþýlar; "Al, dilediðin gibi kullan, bizden yana helâl olsun." derdi. Müþteri malý alýr, bunu kendisini sevdiði için yapýyor zannederdi. Ali bin Þihâb, zâlimlere yardýmcý olduklarýný tahmîn ettiði kimselerin hiçbir þeyini alýp yemezdi. Bir gün kendisine, birisi yemek getirdi. Getirilen yemeði yemedi. Getiren kiþi; "Efendim bu helâldir. Alnýmýn teri ile kazandým." deyince; "Ben terâzisini tutanýn, hangi tarafýn aðýr bastýðýný ihlâsla gözetmeyenin yemeðini yemem!" buyurdu. Ali bin Þihâb, vefâtýna kadar hiçbir kimsenin gýybetini yapmadý. Bundan uzak durdu. Ömrü boyunca boþ durmadý ve lüzûmsuz bir iþle meþgûl olmadý. Ýbâdet ve insanlara faydalý iþlerle meþgûl oldu. Geceleyin biraz uyur, sonra kalkar abdest alýr, namaz kýlardý. Daha sonra büyükçe bir kap alýr, su doldurulmasý gereken yerleri doldurur, bir taraftan da Kur'ân-ý kerîm okurdu. Bu hâli, sabah namazýna kadar devâm ederdi. Çok kere, bu zaman zarfýnda Kur'ân-ý kerîmin yarýsýný okumuþ olurdu.Dergâh, câmi ve o civârdaki yolculara âit sebilleri su ile doldururdu. Hattâ hayvanlara âit su içme yerlerine de su koyardý. Sonra câmideki abdest alma yerlerinin suyunu doldururdu. Temizlenmesi gereken yerlerin temizliðini yapardý. Bütün iþleri bitirdikten sonra, dergâhýn damýna çýkar, Allahü teâlâdan af diler, tesbîh okurdu. Sonra sabah ezânýný okur, iner câmiye girerdi. Sabah namazýnýn sünnetini kýldýktan sonra talebeleri ile birlikte kýrâatine uygun Kur'ân-ý kerîm okurdu. Bunu bitirince, cemâate namaz kýldýrýrdý. Namaz bittikten sonra, güneþ doðuncaya kadar tekrar Kur'ân-ý kerîm okurdu. Bu vakitte mektep çocuklarý gelirdi. Onlara, ikindi vaktine kadar ders okuturdu. Sonra tekrar abdest alma yerlerinin suyunu doldururdu. Bu iþten sonra, dergâh kapýsýnýn yanýndaki dükkâný açar, zeytinyaðý, bal, pirinç, biber gibi þeyler satar, halkýn bu tür ihtiyâcýný da karþýlar, gün batmadan evvel iþini bitirirdi. Sonra da ezân okur, cemâate akþam namazýný kýldýrýrdý. Namazdan sonra, yatsý namazýna kadar Kur'ân-ý kerîm okurdu. Yatsý namazýný kýldýktan sonra, Ali bin Þihâb evine gider, bir miktar istirahat ederdi. Sonra tekrar ayný iþleri yapmaya baþlardý. Hanýmý onun bu hâline acýyýp; "Efendi, bir gece olsun kendine dinlenecek bir zaman ayýrmaz mýsýn?" diye sorunca; "Biz buraya dinlenmek için gelmedik." buyururdu. "Hac dönüþü, insanlar kendisini karþýlamaya çýktýlar. Ýkindi vakti idi. O, hemen dergâhýn damýna çýkýp ezân-ý Muhammedîyi okudu. Sonra inip, namaz kýldýrdý. Namazdan sonra da etrâfý temizlemeye, abdest alma yerlerinin sularýný doldurmaya baþladý. Daha evine gitmeden, bu iþlerini yapýp bitirdi. O geceden îtibâren, önceki âdeti üzere, hiç aksatmadan sebilleri doldurmaya devâm etti. Baþkalarýnýn hac dönüþü günlerce dinlendiði, boþ durduðu gibi yapmadý. "Vakit, keskin bir kýlýçtýr." buyururdu. Hacdan döndükten sonra, aðlamasý ve hüznü daha da fazlalaþtý. Vefâtýna kadar hep bu hâl üzere yaþadý." Berhami denilen bâzý kimseler, ateþ yemek, ateþe girmek, dil üzerinde kýlýç gezdirmek gibi iþler yaparlardý. Bunlar Ali bin Þihâb'ýn beldesine gelince, o bunlara mâni olup; "Yaptýðýnýz bu iþlerin dînimizdeki yerini gösterin ve Hocam Ýbrâhim ed-Düsûkî'den böyle bir haber söyleyin." dedi. Onlar cevap veremediler. O gece Berhamiler, rüyâda Ýbrâhim ed-Düsûkî'yi gördüler. Onlara; "Hepiniz Ali bin Þihâb'ýn sözünü dinleyiniz. Ben, dört büyük halîfe olan Hulefâ-i râþidînin ve müctehid imâmlarýn çizdiði hidâyet yoluna aykýrý her iþe karþýyým." dedi. Sabah olunca, hepsi yaptýklarýna piþmân oldular ve tövbe ettiler. Ali bin Þihâb da onlara; "Eðer hocam Ýbrâhim ed-Düsûkî'nin bu iþte rýzâsý olduðunu bilseydim, sizden önce ben yapardým." dedi. Ali bin Þihâb, bir yere oturup, oyun ve boþþeylerle vakit geçiren köylüleri görünce; "Yavrularým, ömür çok kýsadýr. Oyun ve eðlence zamaný deðildir. Yakýnda yaptýklarýnýza piþman olursunuz." diye nasîhat ederdi. Ali bin Þihâb, seyyid idi. Resûlullah efendimizin soyundan olduðunu açýklamazdý ve; "Neseble öðünmek doðru deðildir. Kiþi, iyi amel sâhibi olmalýdýr.Önceleri bir köle olan Selmân-ý Fârisî ve Bilâl-i Habeþî (r.anhümâ) Resûlullah'ýn emrine girince, O'nun sohbetinde þanlarý ne kadar üstün oldu." buyurdu. Ali bin Þihâb vefâtý yaklaþtýðýnda Abdülazîz ed-Dîrînî'nin Tehâret-ül-Kulûb kitabýnda yazýlý zâtlarýn vefât ediþ hâllerinin okunmasýný istedi. Bir müddet dinledikten sonra derin ve hüzünlü nefes aldý ve; "Onlar, kâfileler hâlinde atlarla geçip gittiler. Biz ise, topal bir merkep ile onlarý tâkibe çalýþýyoruz." buyurdu. Bir aralýk dilinde bâzý kabarcýklar çýktý. Ev halkýndan birisinin; "Vallahi bu dil bu hâle gelmemeli idi. Zîrâ o, geceler boyu Kur'ân-ý kerîm okudu, hatim indirdi." dediðini duyunca; "Onun sözlerini duymamýþ olayým. Eðer o, hesab verme husûsunda benim bildiðimi bilseydi, öyle söylemezdi." buyurdu." Vefâtýndan az önce; "Kabrimi belli etmek için bir niþan koymayýnýz. Beni, þu kubbeli yerin arkasýna defnediniz." diye vasiyette bulundu. Ali bin Þihâb 1486 (H.891) senesinde vefât etti. Ali bin Þihâb; "Helâl lokma ile beslenen bedeni toprak çürütmez." buyururdu. Onun bu sözüne bâzýlarý îtirâz edip, bu durumun Peygamberlere ve þehîdlere mahsus olduðunu söylediler. Vefâtýndan yirmi bir sene sonra Ali bin Þihâb'ýn söylediði söze yine îtirâz edenler oldu. Sözünün doðru olup olmadýðýný anlamak için, gidip kabrini açtýlar. Onu, ilk gün koyduklarý gibi bembeyaz bir kefen içinde buldular. Ýnkârcýlar tövbe ve istiðfâr edip, Allahü teâlâdan af dilediler." Ali el-Iyâþî, Ebü'l-Abbâs'ýn talebelerinden idi. Bir gece Ali bin Þihâb'ýn dergâhýnda geceledi. O gece Ali bin Þihâb'ý, kabrinde Kur'ân-ý kerîm okurken gördü. Meryem sûresinden baþlayýp, Rahmân sûresine kadar okudu. Sabah, tan yeri aðarýrken okumayý býraktý. Ali el-Iyâþî, durumu orada bulunanlara anlattý. Onlar da; "Evet! O, Ali bin Þihâb'dýr." dediler. Ali bin Þihâb buyururdu ki: "Ben, birinin çok ibâdetine deðil, Allahü teâlâdan korkusunun çokluðuna ve bir de nefsi ile olan mücâdelede onu hesâba çekiþine bakarým." HESÂBINI TUTTU Muhammed bin Abdürrahmân, bir bahar mevsiminde Ali bin Þihâb'ýn bulunduðu bölgeye gelip zirâatle meþgûl oldu. Anbarlar yaptýrdý ve oldukça fazla masraf yaptý. Oradan ayrýlacaðýnda, iþini yürütecek ve anbarlarý teslim alacak emin birisini aradý. Ýþini bu þekilde yürütecekti. Köylüler, Ali bin Þihâb'dan daha emin birinin olmadýðýný söylediler. Muhammed bin Abdürrahmân gidip, iþini kendisine havale etmek istediðini Ali bin Þihâb'a söyledi. Fakat o kabûl etmedi. Muhammed bin Abdürrahmân da çok ýsrâr ederek, iþlerini ve anahtarlarý ona teslim etti. Ali bin Þihâb bu ýsrâr üzerine onu kýrmayýp, iþlerini teslim aldý. Bir zaman sonra, tarladaki kavun ve karpuzlar oldu. Onlarý topladý ve bir yere koydu. Zamaný biraz geçince, telef olmasýn diye satmak istedi. Tellâl tutup îlân etti. Alan olmadý. Telef olan bu mallarý kendi hesâbýna yazdý. Sonra hayvanlara verilen otlarýn daðýlýþýný günü gününe bir yere yazdý. Hangisine ne kadar yem verildiðini ve neler verileceðini tesbit etti. Hasta olanlarý da yazdý. Birçok iþi yapýp, hesâbýný tuttu. Nihâyet mallarýn sâhibi olan Muhammed bin Abdurrahmân geri döndü. Yapýlan iþleri, tutulan hesaplarý görünce, Ali bin Þihâb'ýn ayaklarýna kapandý ve; "Efendim, af buyurunuz. Sizin gibi bir zâtý kendime vekil yapýp iþimde çalýþtýrdým." deyip, özür diledi. ÝNSANIN ÞEREFÝ Ali ibni Þihâb ki, evlâd-ý Resûl'dendir, Hem o devrin en büyük, din âlimlerindendir. Geçirirdi vaktini, hizmet ve ibâdetle, Vakar sâhibi olup, heybetliydi gâyetle. Ne vakit namaz için, çýkýp da hânesinden, Câmiye gitse idi, insanlarýn içinden, Heybetinden insanlar, her iþi terk ederek, Câmiye koþarlardý, onu tâkib ederek. Boþ duran insanlarý, görse idi o eðer, Derdi ki: "Ey insanlar, çok kýsadýr ömürler, Boþa geçirmeyin ki, vaktinizi siz þu an, Yoksa mahþer gününde, olursunuz çok piþman." Sülâle-i Resûl'den, olduðu halde bile, Derdi: "Doðru deðildir, öðünmek nesebiyle. Ýnsana þeref veren, ilim ve edebidir, Bir de ameli olup, neseb ve mal deðildir. Bilâl-i Habeþî'yle ve Selmân-ý Fârisî, Îmân etmeden önce, köle idi ikisi. Lâkin Resûlullah'ýn, bir an durup yanýnda, Mânevî sultanlýða, yükseldiler ânýnda." Derdi ki: "Mühim olan, deðildir çok ibâdet, Günahlardan sakýnmak, mühimdir daha elbet. Hak teâlâ indinde, kýymetli olmak için, Haramlardan kaçmasý, lâzýmdýr her kiþinin." Ömrünün sonlarýnda, Hacca gitti bir sene, Dönüp hiç dinlenmeden, baþladý hizmetine. Dediler ki: "Efendim uzak yoldan geldiniz, Hiç olmazsa birkaç gün, evde dinlenseydiniz." Buyurdu: "Dinlenmeðe, gelmedik bu dünyâya, Bizlere çalýþmaðý, emretti Hak teâlâ. Vakit keskin bir kýlýç, gibidir ey insanlar, Ýyi kullanýlýrsa, insana fayda saðlar." Hacdan sonra çoðaldý, aðlamasý ve hüznü, Gözünden akan yaþlar, ýslatýrdý yüzünü Vasiyyet eyledi ki, vefâtýndan az önce: "Kabrim için bir niþan, koymayýn ben ölünce." Hayâtýndan bahsedip, önceki velîlerin, Sonra bir nefes aldý, çok hüzünlü ve derin. Dedi: "Onlar gittiler, atlý kâfilelerle, Biz onlarý izleriz, topal bir merkep ile. Biz tâkib ediyoruz, o büyüklerimizi, Onlarýn yollarýndan, ayýrma yâ Rab bizi." Oðlu naklediyor ki; Babam Ali bin Þihâb, Derdi ki: "Hep helâlden, yememiz eder îcab, Helâlle beslenirse, bir beden tam olarak, Ölürse, o bedeni, çürütemez bu toprak." Buna, bâzý kimseler, îtirâz ederlerdi, Peygamber ve Sýddýklar, hiç çürümez derlerdi. Babamýn vefâtýndan, geçince yirmi sene, Halk içinde bu mevzû, gündeme geldi yine. Bunun doðruluðunu, görmek için âþikâr, Babamýn mezârýný, bir gün gidip açtýlar. Hiç çürümemiþ görüp, düþtüler bir hayrete, O zaman inandýlar, bu açýk hakîkate. 1) Tabakât-ül-Kübrâ; c.2, s.109 2) Ýslâm Âlimleri Ansiklopedisi; c.11, s.272 <br></div></body></html>
{ "content_hash": "8d962296e2a06827afd940a84f8786e9", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 557, "avg_line_length": 63.58706467661692, "alnum_prop": 0.7932869102574134, "repo_name": "relmas/velaye", "id": "40360b8fd3a22f5fbe0d5f03456185edec579e84", "size": "12781", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/sayfalar/305.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "227452" }, { "name": "JavaScript", "bytes": "296010" } ], "symlink_target": "" }
package com.jojo.flippy.app; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class SignUpOptionsActivity extends FragmentActivity { @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_signup_activity); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, new FacebookSignInFragment()) .commit(); } } }
{ "content_hash": "0b459138ac184268d96348abd8e983a8", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 76, "avg_line_length": 28.47826086956522, "alnum_prop": 0.6595419847328244, "repo_name": "jessejohnson/flippy", "id": "cf65138492f33be146e2ad766ea2066060464e7f", "size": "655", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "Flippy/app/src/main/java/com/jojo/flippy/app/SignUpOptionsActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1991" }, { "name": "Java", "bytes": "408885" }, { "name": "Shell", "bytes": "6" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import com.sun.lwuit.Button; import com.sun.lwuit.Command; import com.sun.lwuit.Container; import com.sun.lwuit.Display; import com.sun.lwuit.Form; import com.sun.lwuit.Label; import com.sun.lwuit.TextArea; import com.sun.lwuit.TextField; import com.sun.lwuit.events.ActionEvent; import com.sun.lwuit.events.ActionListener; import com.sun.lwuit.layouts.BorderLayout; import com.sun.lwuit.layouts.BoxLayout; import com.sun.lwuit.plaf.UIManager; import com.sun.lwuit.util.Resources; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.midlet.*; /** * @author RODGEE */ public class adminpolice extends MIDlet implements ActionListener { Form current, frmLogin, frmMenu, frmRegister, frmUpdatesR, frmDl, frmInsurance, frmOffences, frmSummary, frmUpdates, frmAddOffences; TextField txtRegNo, txtRegNoR, txtFirstNameR, txtLastNameR, txtIDNoR; TextArea txtaUpdateR, txtaDl, txtaInsurance, txtaOffences, txtaSummary, txtaUpdates, txtaAddOffences; Button btnLogin, btnRegister, btnSummary, btnDL, btnInsuaranceDetails, btnOffences, btnUpdates, btnRegisterR, btnUpdatesR, btnSubmit, btnOffencesR, btnAdd; Command cmdExit, cmdBack; String updates; public void startApp() { Display.init(this); try { //access the theme created in the resource editor Resources res = Resources.open("/adminpolice.res"); UIManager.getInstance().setThemeProps(res.getTheme("adminpolice")); } catch (IOException ex) { System.out.println("Unable to get theme" + ex.getMessage()); } frmLogin = new Form("Login"); cmdExit = new Command("Exit", 0); frmLogin.setLayout(new BoxLayout(BoxLayout.Y_AXIS)); txtRegNo = new TextField("", 20); btnLogin = new Button("Login"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowMenu(); } }); btnRegister = new Button("Register"); btnRegister.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowRegister(); } }); btnUpdatesR = new Button("Updates"); btnUpdatesR.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowUpdatesR(); } }); frmLogin.addComponent(new Label("Registration Number")); frmLogin.addComponent(txtRegNo); frmLogin.addComponent(btnLogin); frmLogin.addComponent(btnRegister); frmLogin.addComponent(btnUpdatesR); frmLogin.addCommand(cmdExit); frmLogin.addCommandListener(this); frmLogin.show(); } public void ShowMenu() { frmMenu = new Form("MENU"); frmMenu.setLayout(new BoxLayout(BoxLayout.Y_AXIS)); btnSummary = new Button("Summary"); btnSummary.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowSummary(); } }); btnDL = new Button("Driving License"); btnDL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Label title = new Label(detailNews.getTitle()); // form2.setTitleComponent(title); // String Description = detailNews.getDescription(); // System.out.println("Description" + Description);//Here i am able to get different Description values Related to myList Screen but in text area it is displaying First one always // big = new TextArea(); // // big.setEditable(false); // big.setText(Description); // // form2.addComponent(pubDate); // form2.addComponent(big); // form2.show(); ShowDL(); } }); btnInsuaranceDetails = new Button("Insuarance Details"); btnInsuaranceDetails.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowInsuaranceDetails(); } }); btnOffences = new Button("Offences"); btnOffences.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowOffences(); } }); btnUpdates = new Button("Updates"); btnUpdates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowUpdates(); } }); frmMenu.addComponent(btnSummary); frmMenu.addComponent(btnDL); frmMenu.addComponent(btnInsuaranceDetails); frmMenu.addComponent(btnOffences); frmMenu.addComponent(btnUpdates); cmdBack = new Command("Back", 0); frmMenu.addCommand(cmdBack); frmMenu.addCommandListener(this); frmMenu.show(); } private void ShowRegister() { frmRegister = new Form("Register"); frmRegister.setLayout(new BorderLayout()); txtRegNoR = new TextField("", 20); txtFirstNameR = new TextField("", 20); txtLastNameR = new TextField("", 20); btnRegisterR = new Button("Register"); btnRegisterR.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frmLogin.show(); } }); Container conRegister = new Container(new BoxLayout(BoxLayout.Y_AXIS)); conRegister.addComponent(new Label("Registration Number")); conRegister.addComponent(txtRegNoR); conRegister.addComponent(new Label("First Name")); conRegister.addComponent(txtFirstNameR); conRegister.addComponent(new Label("Last Name")); conRegister.addComponent(txtLastNameR); conRegister.addComponent(btnRegisterR); //add the container to the form frmRegister.addComponent(BorderLayout.CENTER, conRegister); cmdBack = new Command("Back", 0); frmRegister.addCommand(cmdBack); frmRegister.addCommandListener(this); frmRegister.show(); } private void ShowUpdatesR() { frmUpdatesR = new Form("Register Updates"); txtaUpdateR = new TextArea(10, 20, TextArea.ANY); txtaUpdateR.setEditable(true); btnSubmit = new Button("Update"); btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { updates = txtaUpdateR.getText().trim(); //check if password match //send to database String updateURL = "http://localhost/project/register2.php?email_address="+updates; //call the dbfunction method String updateResponse = dbfunction(updateURL); int resp = Integer.parseInt(updateResponse); if (resp == 1) { //send the user to login form // txtaValidate.setText("you've registered successfully"); // validate.setTimeout(1000); // validate.show(70,70,10,10,true); frmLogin.show(); } else { //alert "registration failed" //System.out.println("Failed"); } } }); frmUpdatesR.addComponent(txtaUpdateR); frmUpdatesR.addComponent(btnSubmit); cmdBack = new Command("Back", 0); frmUpdatesR.addCommand(cmdBack); frmUpdatesR.addCommandListener(this); frmUpdatesR.show(); } private void ShowSummary() { frmSummary = new Form("Summary"); txtaSummary = new TextArea(10, 20, TextArea.UNEDITABLE); txtaSummary.setEditable(false); frmSummary.addComponent(txtaSummary); cmdBack = new Command("Back"); frmSummary.addCommand(cmdBack); frmSummary.addCommandListener(this); frmSummary.show(); } private void ShowDL() { String drivingLicenseURL = "http://localhost/mbank/services.php"; String ServicesResponse = dbfunction(drivingLicenseURL); String[] ServicesArray = split(ServicesResponse, '#'); frmDl = new Form("Driving License"); txtaDl = new TextArea(10, 20, TextArea.UNEDITABLE); txtaDl.setEditable(false); frmDl.addComponent(txtaDl); cmdBack = new Command("Back"); frmDl.addCommand(cmdBack); frmDl.addCommandListener(this); frmDl.show(); } private void ShowInsuaranceDetails() { frmInsurance = new Form("Insurance Details"); txtaInsurance = new TextArea(10, 20, TextArea.UNEDITABLE); txtaInsurance.setEditable(false); frmInsurance.addComponent(txtaInsurance); cmdBack = new Command("Back"); frmInsurance.addCommand(cmdBack); frmInsurance.addCommandListener(this); frmInsurance.show(); } private void ShowOffences() { frmOffences = new Form("Offences"); txtaOffences = new TextArea(10, 20, TextArea.UNEDITABLE); txtaOffences.setEditable(false); btnAdd = new Button("Add"); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowAddOffences(); } }); frmOffences.addComponent(txtaOffences); frmOffences.addComponent(btnAdd); cmdBack = new Command("Back"); frmOffences.addCommand(cmdBack); frmOffences.addCommandListener(this); frmOffences.show(); } private void ShowUpdates() { frmUpdates = new Form("Updates"); txtaUpdates = new TextArea(10, 20, TextArea.UNEDITABLE); txtaUpdates.setEditable(false); frmUpdates.addComponent(txtaUpdates); cmdBack = new Command("Back"); frmUpdates.addCommand(cmdBack); frmUpdates.addCommandListener(this); frmUpdates.show(); } private void ShowAddOffences() { frmAddOffences = new Form("Add Offences"); txtaAddOffences = new TextArea(10, 20, TextArea.ANY); txtaAddOffences.setEditable(true); btnOffencesR = new Button("Submit"); btnOffencesR.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { ShowOffences(); } }); frmAddOffences.addComponent(txtaAddOffences); frmAddOffences.addComponent(btnOffencesR); cmdBack = new Command("Back"); frmAddOffences.addCommand(cmdBack); frmAddOffences.addCommandListener(this); frmAddOffences.show(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void actionPerformed(ActionEvent ae) { current = Display.getInstance().getCurrent(); if (ae.getSource() == cmdExit) { destroyApp(true); notifyDestroyed(); } else if (ae.getSource() == btnLogin && current == frmLogin) { frmLogin.show(); } else if (ae.getSource() == btnRegister && current == frmLogin) { frmRegister.show(); } else if (ae.getSource() == cmdBack && current == frmMenu) { frmLogin.show(); } else if (ae.getSource() == cmdBack && current == frmRegister) { frmLogin.show(); }else if (ae.getSource() == cmdBack && current == frmUpdatesR) { frmLogin.show(); }else if (ae.getSource() == cmdBack && current == frmDl) { ShowMenu(); } else if (ae.getSource() == cmdBack && current == frmSummary) { ShowMenu(); } else if (ae.getSource() == cmdBack && current == frmInsurance) { ShowMenu(); }else if (ae.getSource() == cmdBack && current == frmUpdates) { ShowMenu(); }else if (ae.getSource() == cmdBack && current == frmOffences) { ShowMenu(); }else if (ae.getSource() == cmdBack && current == frmAddOffences) { ShowOffences(); } } private String dbfunction(String createaccountURL) { String response = null; InputStream is = null; StringBuffer sb = null; HttpConnection http = null; String url; try { // encode the url url = encodeURL(createaccountURL); // establish a HTTP connection http = (HttpConnection) Connector.open(url); // set the request method to GET http.setRequestMethod(HttpConnection.GET); // get server response if (http.getResponseCode() == HttpConnection.HTTP_OK) { sb = new StringBuffer(); int ch; is = http.openInputStream(); while ((ch = is.read()) != -1) { sb.append((char) ch); } response = sb.toString(); } else { // showDialog("Network Error", "Please try again"); System.out.println("Network Error: Please try again"); } } catch (Exception ex) { // showDialog("Network Error", ex.getMessage()); System.out.println("Network Error" + ex.getMessage()); } finally { try { if (is != null) { is.close(); } if (sb != null) { response = sb.toString(); } else { // showDialog("Network Error", "Please try again"); System.out.println("Network Error: Please try again"); } if (http != null) { http.close(); } } catch (IOException ex) { } } return response; } private String getResponse(HttpConnection http, InputStream iStrm) throws IOException { String response = ""; if (http.getResponseCode() == HttpConnection.HTTP_OK) { int length = (int) http.getLength(); String str = null; if (length != -1) { byte servletData[] = new byte[length]; iStrm.read(servletData); str = new String(servletData); } else { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) { bStrm.write(ch); } str = new String(bStrm.toByteArray()); bStrm.close(); } response = str; } else { response = new String(http.getResponseMessage()); } return response; } private String encodeURL(String url) { url = replace(url, 'à', "%E0"); url = replace(url, 'è', "%E8"); url = replace(url, 'é', "%E9"); url = replace(url, 'ì', "%EC"); url = replace(url, 'ò', "%F2"); url = replace(url, 'ù', "%F9"); url = replace(url, '$', "%24"); url = replace(url, '#', "%23"); url = replace(url, '£', "%A3"); url = replace(url, '@', "%40"); url = replace(url, '\'', "%27"); url = replace(url, ' ', "%20"); return url; } //split public static String[] split(String s, char separator) { Vector v = new Vector(); for (int ini = 0, end = 0; ini < s.length(); ini = end + 1) { end = s.indexOf(separator, ini); if (end == -1) { end = s.length(); } String st = s.substring(ini, end).trim(); if (st.length() > 0) { v.addElement(st); } else { v.addElement("null"); } } String temp[] = new String[v.size()]; v.copyInto(temp); return temp; } private String replace(String source, char oldChar, String dest) { String str = ""; for (int i = 0; i < source.length(); i++) { if (source.charAt(i) != oldChar) { str += source.charAt(i); } else { str += dest; } } return str; } }
{ "content_hash": "b0771fd32fd6ec9a8465ac41ca59e07d", "timestamp": "", "source": "github", "line_count": 480, "max_line_length": 194, "avg_line_length": 35.25, "alnum_prop": 0.565839243498818, "repo_name": "modomodo/J2ME-Coursework", "id": "abacd81f7b849c0d0289d296cd4f7ccb3e212fa8", "size": "16927", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "adminpolice/src/adminpolice.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "37377" }, { "name": "PHP", "bytes": "2589" } ], "symlink_target": "" }
#ifndef __PLAT_PRIVATE_H__ #define __PLAT_PRIVATE_H__ #ifndef __ASSEMBLY__ #include <mmio.h> #include <psci.h> #include <stdint.h> #include <xlat_tables.h> #define __sramdata __attribute__((section(".sram.data"))) #define __sramconst __attribute__((section(".sram.rodata"))) #define __sramfunc __attribute__((section(".sram.text"))) #define __pmusramdata __attribute__((section(".pmusram.data"))) #define __pmusramconst __attribute__((section(".pmusram.rodata"))) #define __pmusramfunc __attribute__((section(".pmusram.text"))) extern uint32_t __bl31_sram_text_start, __bl31_sram_text_end; extern uint32_t __bl31_sram_data_start, __bl31_sram_data_end; extern uint32_t __bl31_sram_stack_start, __bl31_sram_stack_end; extern uint32_t __bl31_sram_text_real_end, __bl31_sram_data_real_end; extern uint32_t __sram_incbin_start, __sram_incbin_end; extern uint32_t __sram_incbin_real_end; /****************************************************************************** * The register have write-mask bits, it is mean, if you want to set the bits, * you needs set the write-mask bits at the same time, * The write-mask bits is in high 16-bits. * The fllowing macro definition helps access write-mask bits reg efficient! ******************************************************************************/ #define REG_MSK_SHIFT 16 #ifndef WMSK_BIT #define WMSK_BIT(nr) BIT((nr) + REG_MSK_SHIFT) #endif /* set one bit with write mask */ #ifndef BIT_WITH_WMSK #define BIT_WITH_WMSK(nr) (BIT(nr) | WMSK_BIT(nr)) #endif #ifndef BITS_SHIFT #define BITS_SHIFT(bits, shift) (bits << (shift)) #endif #ifndef BITS_WITH_WMASK #define BITS_WITH_WMASK(bits, msk, shift)\ (BITS_SHIFT(bits, shift) | BITS_SHIFT(msk, (shift + REG_MSK_SHIFT))) #endif /****************************************************************************** * Function and variable prototypes *****************************************************************************/ void plat_configure_mmu_el3(unsigned long total_base, unsigned long total_size, unsigned long, unsigned long, unsigned long, unsigned long); void plat_cci_init(void); void plat_cci_enable(void); void plat_cci_disable(void); void plat_delay_timer_init(void); void params_early_setup(void *plat_params_from_bl2); void plat_rockchip_gic_driver_init(void); void plat_rockchip_gic_init(void); void plat_rockchip_gic_cpuif_enable(void); void plat_rockchip_gic_cpuif_disable(void); void plat_rockchip_gic_pcpu_init(void); void plat_rockchip_pmu_init(void); void plat_rockchip_soc_init(void); uintptr_t plat_get_sec_entrypoint(void); void platform_cpu_warmboot(void); struct gpio_info *plat_get_rockchip_gpio_reset(void); struct gpio_info *plat_get_rockchip_gpio_poweroff(void); struct gpio_info *plat_get_rockchip_suspend_gpio(uint32_t *count); struct apio_info *plat_get_rockchip_suspend_apio(void); void plat_rockchip_gpio_init(void); void plat_rockchip_save_gpio(void); void plat_rockchip_restore_gpio(void); int rockchip_soc_cores_pwr_dm_on(unsigned long mpidr, uint64_t entrypoint); int rockchip_soc_hlvl_pwr_dm_off(uint32_t lvl, plat_local_state_t lvl_state); int rockchip_soc_cores_pwr_dm_off(void); int rockchip_soc_sys_pwr_dm_suspend(void); int rockchip_soc_cores_pwr_dm_suspend(void); int rockchip_soc_hlvl_pwr_dm_suspend(uint32_t lvl, plat_local_state_t lvl_state); int rockchip_soc_hlvl_pwr_dm_on_finish(uint32_t lvl, plat_local_state_t lvl_state); int rockchip_soc_cores_pwr_dm_on_finish(void); int rockchip_soc_sys_pwr_dm_resume(void); int rockchip_soc_hlvl_pwr_dm_resume(uint32_t lvl, plat_local_state_t lvl_state); int rockchip_soc_cores_pwr_dm_resume(void); void __dead2 rockchip_soc_soft_reset(void); void __dead2 rockchip_soc_system_off(void); void __dead2 rockchip_soc_cores_pd_pwr_dn_wfi( const psci_power_state_t *target_state); void __dead2 rockchip_soc_sys_pd_pwr_dn_wfi(void); extern const unsigned char rockchip_power_domain_tree_desc[]; extern void *pmu_cpuson_entrypoint; extern uint64_t cpuson_entry_point[PLATFORM_CORE_COUNT]; extern uint32_t cpuson_flags[PLATFORM_CORE_COUNT]; extern const mmap_region_t plat_rk_mmap[]; void rockchip_plat_mmu_el3(void); #endif /* __ASSEMBLY__ */ /****************************************************************************** * cpu up status * The bits of macro value is not more than 12 bits for cmp instruction! ******************************************************************************/ #define PMU_CPU_HOTPLUG 0xf00 #define PMU_CPU_AUTO_PWRDN 0xf0 #define PMU_CLST_RET 0xa5 #endif /* __PLAT_PRIVATE_H__ */
{ "content_hash": "5d235550b7a300199d23221e5105785a", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 80, "avg_line_length": 34.33582089552239, "alnum_prop": 0.6489893501412737, "repo_name": "lsigithub/arm-trusted-firmware_public", "id": "545677352f099ba64417bcb6ae2f03d84aeab7c2", "size": "4730", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "plat/rockchip/common/include/plat_private.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "322275" }, { "name": "C", "bytes": "1656636" }, { "name": "C++", "bytes": "21215" }, { "name": "Makefile", "bytes": "108712" }, { "name": "Objective-C", "bytes": "2280" } ], "symlink_target": "" }
package com.pixnfit; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class CreateAccount extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_account); } }
{ "content_hash": "bc66d86bae15caf4fb6e8dcc1d9dad4e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 57, "avg_line_length": 25.76923076923077, "alnum_prop": 0.7582089552238805, "repo_name": "fabier/pixnfit-android", "id": "2f2ac5359ccd61339f272b4dccb061529fd2bec4", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/pixnfit/CreateAccount.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "92366" } ], "symlink_target": "" }
module Editor::Controllers::Document class SendFile include Editor::Action # http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpRuby.html def send_document @object_name = "#{@document.identifier}.txt" puts "document id = #{@document.id}" @url = Noteshare::AWS.put_string(@document.content, "#{@document.identifier}.txt", 'test' ) end def call(params) id = params[:id] @document = DocumentRepository.find id if @document send_document self.body = "OK: contents of #{@document.title} uploaded to #{@object_name} " else self.body = "ERROR: file (id = #{id}) not found" end end end end
{ "content_hash": "361e8e0024254f3f356ef1501fc0de9a", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 97, "avg_line_length": 27.96, "alnum_prop": 0.6251788268955651, "repo_name": "jxxcarlson/noteshare", "id": "0041e7f9233ae8f1350e9e186efab98ba437f068", "size": "699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/editor/controllers/document/send_file.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "250265" }, { "name": "HTML", "bytes": "193134" }, { "name": "JavaScript", "bytes": "306977" }, { "name": "Ruby", "bytes": "600473" }, { "name": "Shell", "bytes": "922" } ], "symlink_target": "" }
using System; using Google.GData.Client; using Google.GData.Documents; using Google.GData.Spreadsheets; namespace GDataDB.Impl { public class Database : IDatabase { private readonly IDatabaseClient client; private readonly AtomEntry entry; public Database(IDatabaseClient client, AtomEntry entry) { this.client = client; this.entry = entry; } public ITable<T> CreateTable<T>(string name) { var link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null); var wsFeed = (WorksheetFeed) client.SpreadsheetService.Query(new WorksheetQuery(link.HRef.ToString())); var length = typeof (T).GetProperties().Length; var ws = wsFeed.Insert(new WorksheetEntry(1, (uint) length, name)); var cellLink = new AtomLink(ws.CellFeedLink); var cFeed = client.SpreadsheetService.Query(new CellQuery(cellLink.HRef.ToString())); { uint c = 0; foreach (var p in typeof (T).GetProperties()) { var entry1 = new CellEntry(1, ++c, p.Name); cFeed.Insert(entry1); } } return new Table<T>(client.SpreadsheetService, ws); } public ITable<T> GetTable<T>(string name) { var link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null); var wsFeed = (WorksheetFeed) client.SpreadsheetService.Query(new WorksheetQuery(link.HRef.ToString()) {Title = name, Exact = true}); if (wsFeed.Entries.Count == 0) return null; return new Table<T>(client.SpreadsheetService, (WorksheetEntry) wsFeed.Entries[0]); } public WorksheetEntry GetWorksheetEntry(string name) { var link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null); var wsFeed = (WorksheetFeed) client.SpreadsheetService.Query(new WorksheetQuery(link.HRef.ToString()) {Title = name, Exact = true}); if (wsFeed.Entries.Count == 0) return null; return (WorksheetEntry)wsFeed.Entries [0]; /* WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries [0]; // Fetch the cell feed of the worksheet. CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); CellFeed cellFeed = client.SpreadsheetService.Query(cellQuery); // Iterate through each cell, printing its value. foreach (CellEntry cell in cellFeed.Entries) { // Print the cell's address in A1 notation Console.WriteLine(cell.Title.Text); // Print the cell's address in R1C1 notation Console.WriteLine(cell.Id.Uri.Content.Substring(cell.Id.Uri.Content.LastIndexOf("/") + 1)); // Print the cell's formula or text value Console.WriteLine(cell.InputValue); // Print the cell's calculated value if the cell's value is numeric // Prints empty string if cell's value is not numeric Console.WriteLine(cell.NumericValue); // Print the cell's displayed value (useful if the cell has a formula) Console.WriteLine(cell.Value); } */ } public void Delete() { // cannot call "entry.Delete()" directly after modification as the EditUri is invalid var feed = client.DocumentService.Query(new DocumentsListQuery(entry.SelfUri.ToString())); feed.Entries[0].Delete(); } } }
{ "content_hash": "2b061704686fdd73cb713af4bcf616d0", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 144, "avg_line_length": 41.353658536585364, "alnum_prop": 0.6579180182836921, "repo_name": "neon77/Unity-QuickSheet", "id": "8f9fdff60e06a6813b56414c30db7f881c520e61", "size": "3391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/Database.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "137309" } ], "symlink_target": "" }
"""Example of overwriting auto-generated argparse options with custom ones. """ from dataclasses import dataclass from typing import List from simple_parsing import ArgumentParser, field from simple_parsing.helpers import list_field def parse(cls, args: str = ""): """Removes some boilerplate code from the examples.""" parser = ArgumentParser() # Create an argument parser parser.add_arguments(cls, "example") # add arguments for the dataclass ns = parser.parse_args(args.split()) # parse the given `args` return ns.example # return the dataclass instance # Example 1: List of Choices: @dataclass class Example1: # A list of animals to take on a walk. (can only be passed 'cat' or 'dog') pets_to_walk: List[str] = list_field(default=["dog"], choices=["cat", "dog"]) # passing no arguments uses the default values: assert parse(Example1, "") == Example1(pets_to_walk=["dog"]) assert parse(Example1, "--pets_to_walk") == Example1(pets_to_walk=[]) assert parse(Example1, "--pets_to_walk cat") == Example1(pets_to_walk=["cat"]) assert parse(Example1, "--pets_to_walk dog dog cat") == Example1(pets_to_walk=["dog", "dog", "cat"]) # # Passing a value not in 'choices' produces an error: # with pytest.raises(SystemExit): # example = parse(Example1, "--pets_to_walk racoon") # expected = """ # usage: custom_args_example.py [-h] [--pets_to_walk [{cat,dog,horse} [{cat,dog} ...]]] # custom_args_example.py: error: argument --pets_to_walk: invalid choice: 'racoon' (choose from 'cat', 'dog') # """ # Example 2: Additional Option Strings @dataclass class Example2: # (This argument can be passed either as "-i" or "--input_dir") input_dir: str = field("./in", alias="-i") # (This argument can be passed either as "-o", "--out", or "--output_dir") output_dir: str = field("./out", alias=["-o", "--out"]) assert parse(Example2, "-i tmp/data") == Example2(input_dir="tmp/data") assert parse(Example2, "-o tmp/data") == Example2(output_dir="tmp/data") assert parse(Example2, "--out louise") == Example2(output_dir="louise") assert parse(Example2, "--input_dir louise") == Example2(input_dir="louise") assert parse(Example2, "--output_dir joe/annie") == Example2(output_dir="joe/annie") assert parse(Example2, "-i input -o output") == Example2(input_dir="input", output_dir="output") # Example 3: Using other actions (store_true, store_false, store_const, etc.) @dataclass class Example3: """Examples with other actions.""" b: bool = False debug: bool = field(alias="-d", action="store_true") verbose: bool = field(alias="-v", action="store_true") cache: bool = False # cache: bool = field(default=True, "--no_cache", "store_false") # no_cache: bool = field(dest=cache, action="store_false") parser = ArgumentParser() parser.add_arguments(Example3, "example") args = parser.parse_args() example = args.example print(example) delattr(args, "example") assert not vars(args)
{ "content_hash": "09529352f54681706e7f3673ae20cb50", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 113, "avg_line_length": 35.09411764705882, "alnum_prop": 0.6724773717733825, "repo_name": "lebrice/SimpleParsing", "id": "7f0680e47435e23ed7ff19da7b60e5a18c700afa", "size": "2983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/custom_args/custom_args_example.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "607221" } ], "symlink_target": "" }
namespace Microsoft.WindowsAzure.Management.HDInsight { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Hadoop.Client; using Microsoft.Hadoop.Client.WebHCatRest; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.ClusterManager; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.LocationFinder; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.IaasClusters; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.PaasClusters; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.ResourceTypeFinder; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.RestClient; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.VersionFinder; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.WebRequest; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Retries; using Microsoft.WindowsAzure.Management.HDInsight.Framework.ServiceLocation; using Microsoft.WindowsAzure.Management.HDInsight.Logging; /// <inheritdoc /> [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "DisposableObject implements IDisposable correctly, the implementation of IDisposable in the interfaces is necessary for the design.")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This complexity is needed to handle all the operations.")] public sealed class HDInsightClient : ClientBase, IHDInsightClient { private readonly Lazy<bool> canUseClustersContract; private Lazy<List<string>> capabilities; /// <summary> /// Default HDInsight version. /// </summary> internal const string DEFAULTHDINSIGHTVERSION = "default"; internal const string ClustersContractCapabilityVersion1 = "CAPABILITY_FEATURE_CLUSTERS_CONTRACT_1_SDK"; internal static string ClustersContractCapabilityVersion2 = "CAPABILITY_FEATURE_CLUSTERS_CONTRACT_2_SDK"; internal static string IaasClustersCapability = "CAPABILITY_FEATURE_IAAS_DEPLOYMENTS"; internal const string ClusterAlreadyExistsError = "The condition specified by the ETag is not satisfied."; private IHDInsightSubscriptionCredentials credentials; private ClusterDetails currentDetails; private const string DefaultSchemaVersion = "1.0"; private TimeSpan defaultResizeTimeout = TimeSpan.FromHours(1); /// <summary> /// Gets the connection credential. /// </summary> public IHDInsightSubscriptionCredentials Credentials { get { return this.credentials; } } /// <inheritdoc /> public TimeSpan PollingInterval { get; set; } /// <inheritdoc /> internal static TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(30); /// <summary> /// Initializes a new instance of the HDInsightClient class. /// </summary> /// <param name="credentials">The credential to use when operating against the service.</param> /// <param name="httpOperationTimeout">The HTTP operation timeout.</param> /// <param name="policy">The retry policy.</param> /// <exception cref="System.InvalidOperationException">Unable to connect to the HDInsight subscription with the supplied type of credential.</exception> internal HDInsightClient(IHDInsightSubscriptionCredentials credentials, TimeSpan? httpOperationTimeout = null, IRetryPolicy policy = null) : base(httpOperationTimeout, policy) { var asCertificateCredentials = credentials; if (asCertificateCredentials.IsNull()) { throw new InvalidOperationException("Unable to connect to the HDInsight subscription with the supplied type of credential"); } this.credentials = ServiceLocator.Instance.Locate<IHDInsightSubscriptionCredentialsFactory>().Create(asCertificateCredentials); this.capabilities = new Lazy<List<string>>(this.GetCapabilities); this.canUseClustersContract = new Lazy<bool>(this.CanUseClustersContract); this.PollingInterval = DefaultPollingInterval; } /// <summary> /// Connects to an HDInsight subscription. /// </summary> /// <param name="credentials"> /// The credential used to connect to the subscription. /// </param> /// <returns> /// A new HDInsight client. /// </returns> public static IHDInsightClient Connect(IHDInsightSubscriptionCredentials credentials) { return ServiceLocator.Instance.Locate<IHDInsightClientFactory>().Create(credentials); } /// <summary> /// Connects the specified credentials. /// </summary> /// <param name="credentials">The credential used to connect to the subscription.</param> /// <param name="httpOperationTimeout">The HTTP operation timeout.</param> /// <param name="policy">The retry policy to use for operations on this client.</param> /// <returns> /// A new HDInsight client. /// </returns> public static IHDInsightClient Connect(IHDInsightSubscriptionCredentials credentials, TimeSpan httpOperationTimeout, IRetryPolicy policy) { return ServiceLocator.Instance.Locate<IHDInsightClientFactory>().Create(credentials, httpOperationTimeout, policy); } /// <inheritdoc /> public event EventHandler<ClusterProvisioningStatusEventArgs> ClusterProvisioning; /// <inheritdoc /> public async Task<Collection<string>> ListAvailableLocationsAsync() { return await ListAvailableLocationsAsync(OSType.Windows); } /// <inheritdoc /> public async Task<Collection<string>> ListAvailableLocationsAsync(OSType osType) { var client = ServiceLocator.Instance.Locate<ILocationFinderClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); switch (osType) { case OSType.Windows: return await client.ListAvailableLocations(); case OSType.Linux: return await client.ListAvailableIaasLocations(); default: throw new InvalidProgramException(String.Format("Encountered unhandled value for OSType: {0}", osType)); } } /// <inheritdoc /> public async Task<IEnumerable<KeyValuePair<string, string>>> ListResourceProviderPropertiesAsync() { var client = ServiceLocator.Instance.Locate<IRdfeServiceRestClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); return await client.GetResourceProviderProperties(); } /// <inheritdoc /> public async Task<Collection<HDInsightVersion>> ListAvailableVersionsAsync() { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); return await overrideHandlers.VersionFinder.ListAvailableVersions(); } /// <inheritdoc /> public async Task<ICollection<ClusterDetails>> ListClustersAsync() { ICollection<ClusterDetails> allClusters; // List all clusters using the containers client using (var client = this.CreateContainersPocoClient()) { allClusters = await client.ListContainers(); } // List all clusters using the clusters client if (this.canUseClustersContract.Value) { using (var client = this.CreateClustersPocoClient(this.capabilities.Value)) { var clusters = await client.ListContainers(); allClusters = clusters.Concat(allClusters).ToList(); } } // List all clusters using the iaas clusters client if (this.HasIaasCapability()) { using (var client = this.CreateIaasClustersPocoClient(this.capabilities.Value)) { var iaasClusters = await client.ListContainers(); allClusters = iaasClusters.Concat(allClusters).ToList(); } } return allClusters; } /// <inheritdoc /> public async Task<ClusterDetails> GetClusterAsync(string name) { if (name == null) { throw new ArgumentNullException("name"); } try { using (var client = this.CreatePocoClientForDnsName(name)) { return await client.ListContainer(name); } } catch (HDInsightClusterDoesNotExistException) { //The semantics of this method is that if a cluster doesn't exist we return null return null; } } /// <inheritdoc /> public async Task<ClusterDetails> GetClusterAsync(string name, string location) { if (name == null) { throw new ArgumentNullException("name"); } if (location == null) { throw new ArgumentNullException("location"); } try { using (var client = this.CreatePocoClientForDnsName(name)) { return await client.ListContainer(name, location); } } catch (HDInsightClusterDoesNotExistException) { //The semantics of this method is that if a cluster doesn't exist we return null return null; } } public async Task<ClusterDetails> CreateClusterAsync(ClusterCreateParameters clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } var createParamsV2 = new ClusterCreateParametersV2(clusterCreateParameters); return await CreateClusterAsync(createParamsV2); } /// <inheritdoc /> public async Task<ClusterDetails> CreateClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters.OSType == OSType.Linux) { return await this.CreateIaasClusterAsync(clusterCreateParameters); } else { return await this.CreatePaasClusterAsync(clusterCreateParameters); } } private async Task<ClusterDetails> CreatePaasClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } IHDInsightManagementPocoClient client = null; if (!this.canUseClustersContract.Value) { client = this.CreateContainersPocoClient(); } else { client = this.CreateClustersPocoClient(this.capabilities.Value); } this.LogMessage("Validating Cluster Versions", Severity.Informational, Verbosity.Detailed); await this.ValidateClusterVersion(clusterCreateParameters); // listen to cluster provisioning events on the POCO client. client.ClusterProvisioning += this.RaiseClusterProvisioningEvent; Exception requestException = null; // Creates a cluster and waits for it to complete try { this.LogMessage("Sending Cluster Create Request", Severity.Informational, Verbosity.Detailed); await client.CreateContainer(clusterCreateParameters); } catch (Exception ex) { ex = ex.GetFirstException(); var hlex = ex as HttpLayerException; var httpEx = ex as HttpRequestException; var webex = ex as WebException; if (hlex.IsNotNull() || httpEx.IsNotNull() || webex.IsNotNull()) { requestException = ex; if (hlex.IsNotNull()) { HandleCreateHttpLayerException(clusterCreateParameters, hlex); } } else { throw; } } await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, clusterCreateParameters.Name, clusterCreateParameters.Location, clusterCreateParameters.CreateTimeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); // Validates that cluster didn't get on error state var result = this.currentDetails; if (result == null) { if (requestException != null) { throw requestException; } throw new HDInsightClusterCreateException("Attempting to return the newly created cluster returned no cluster. The cluster could not be found."); } if (result.Error != null) { throw new HDInsightClusterCreateException(result); } return result; } private async Task<ClusterDetails> CreateIaasClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } // Validate cluster creation parameters clusterCreateParameters.ValidateClusterCreateParameters(); this.LogMessage("Validating Cluster Versions", Severity.Informational, Verbosity.Detailed); await this.ValidateClusterVersion(clusterCreateParameters); IHDInsightManagementPocoClient client = this.CreateIaasClustersPocoClient(this.capabilities.Value); // listen to cluster provisioning events on the POCO client. client.ClusterProvisioning += this.RaiseClusterProvisioningEvent; Exception requestException = null; // Creates a cluster and waits for it to complete try { this.LogMessage("Sending Cluster Create Request", Severity.Informational, Verbosity.Detailed); await client.CreateContainer(clusterCreateParameters); } catch (Exception ex) { ex = ex.GetFirstException(); var hlex = ex as HttpLayerException; var httpEx = ex as HttpRequestException; var webex = ex as WebException; if (hlex.IsNotNull() || httpEx.IsNotNull() || webex.IsNotNull()) { requestException = ex; if (hlex.IsNotNull()) { HandleCreateHttpLayerException(clusterCreateParameters, hlex); } } else { throw; } } await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, clusterCreateParameters.Name, clusterCreateParameters.Location, clusterCreateParameters.CreateTimeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); // Validates that cluster didn't get on error state var result = this.currentDetails; if (result == null) { if (requestException != null) { throw requestException; } throw new HDInsightClusterCreateException("Attempting to return the newly created cluster returned no cluster. The cluster could not be found."); } if (result.Error != null) { throw new HDInsightClusterCreateException(result); } return result; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private bool CanUseClustersContract() { string clustersCapability; SchemaVersionUtils.SupportedSchemaVersions.TryGetValue(1, out clustersCapability); bool retval = this.capabilities.Value.Contains(clustersCapability); this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Clusters resource type is enabled '{0}'", retval), Severity.Critical, Verbosity.Detailed); return retval; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private bool HasIaasCapability() { bool retval = this.capabilities.Value.Contains(IaasClustersCapability); this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Iaas Clusters resource type is enabled '{0}'", retval), Severity.Critical, Verbosity.Detailed); return retval; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private List<string> GetCapabilities() { this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Fetching resource provider properties for subscription '{0}'.", this.credentials.SubscriptionId), Severity.Critical, Verbosity.Detailed); List<KeyValuePair<string, string>> props = this.ListResourceProviderProperties().ToList(); return props.Select(p => p.Key).ToList(); } private IHDInsightManagementPocoClient CreateClustersPocoClient(List<string> capabilities) { return new PaasClustersPocoClient(this.credentials, this.IgnoreSslErrors, this.Context, capabilities); } private IHDInsightManagementPocoClient CreateIaasClustersPocoClient(List<string> capabilities) { return new IaasClustersPocoClient(this.credentials, this.IgnoreSslErrors, this.Context, capabilities); } private IHDInsightManagementPocoClient CreateContainersPocoClient() { return ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); } private IHDInsightManagementPocoClient CreatePocoClientForDnsName(string dnsName) { if (this.canUseClustersContract.Value) { var rdfeResourceTypeFinder = ServiceLocator.Instance.Locate<IRdfeResourceTypeFinderFactory>() .Create(this.credentials, this.Context, this.IgnoreSslErrors, DefaultSchemaVersion); var rdfeResourceType = rdfeResourceTypeFinder.GetResourceTypeForCluster(dnsName).Result; switch (rdfeResourceType) { case RdfeResourceType.Clusters: return this.CreateClustersPocoClient(this.capabilities.Value); case RdfeResourceType.Containers: return this.CreateContainersPocoClient(); case RdfeResourceType.IaasClusters: return this.CreateIaasClustersPocoClient(this.capabilities.Value); default: throw new HDInsightClusterDoesNotExistException(dnsName); } } return this.CreateContainersPocoClient(); } private static void HandleCreateHttpLayerException(ClusterCreateParametersV2 clusterCreateParameters, HttpLayerException e) { if (e.RequestContent.Contains(ClusterAlreadyExistsError) && e.RequestStatusCode == HttpStatusCode.BadRequest) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cluster {0} already exists.", clusterCreateParameters.Name)); } } /// <summary> /// Raises the cluster provisioning event. /// </summary> /// <param name="sender">The IHDInsightManagementPocoClient instance.</param> /// <param name="e">EventArgs for the event.</param> public void RaiseClusterProvisioningEvent(object sender, ClusterProvisioningStatusEventArgs e) { var handler = this.ClusterProvisioning; if (handler.IsNotNull()) { handler(sender, e); } } /// <summary> /// Used to handle the notification events during waiting. /// </summary> /// <param name="cluster"> /// The cluster in its current state. /// </param> public void HandleClusterWaitNotifyEvent(ClusterDetails cluster) { if (cluster.IsNotNull()) { this.currentDetails = cluster; this.RaiseClusterProvisioningEvent(this, new ClusterProvisioningStatusEventArgs(cluster, cluster.State)); } } /// <inheritdoc /> public async Task DeleteClusterAsync(string name) { if (name == null) { throw new ArgumentNullException("name"); } var client = this.CreatePocoClientForDnsName(name); await client.DeleteContainer(name); await client.WaitForClusterNull(name, TimeSpan.FromMinutes(30), this.PollingInterval, this.Context.CancellationToken); } /// <inheritdoc /> public async Task DeleteClusterAsync(string name, string location) { if (name == null) { throw new ArgumentNullException("name"); } if (location == null) { throw new ArgumentNullException("location"); } var client = this.CreatePocoClientForDnsName(name); await client.DeleteContainer(name, location); await client.WaitForClusterNull(name, location, TimeSpan.FromMinutes(30), this.Context.CancellationToken); } /// <inheritdoc /> public async Task EnableHttpAsync(string dnsName, string location, string httpUserName, string httpPassword) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); httpUserName.ArgumentNotNullOrEmpty("httpUserName"); httpPassword.ArgumentNotNullOrEmpty("httpPassword"); using (var client = this.CreatePocoClientForDnsName(dnsName)) { await this.AssertClusterVersionSupported(dnsName); var operationId = await client.EnableHttp(dnsName, location, httpUserName, httpPassword); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, TimeSpan.FromHours(1), this.Context.CancellationToken); } } /// <inheritdoc /> public void DisableHttp(string dnsName, string location) { this.DisableHttpAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public void EnableHttp(string dnsName, string location, string httpUserName, string httpPassword) { this.EnableHttpAsync(dnsName, location, httpUserName, httpPassword).WaitForResult(); } /// <inheritdoc /> public async Task DisableHttpAsync(string dnsName, string location) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); using (var client = this.CreatePocoClientForDnsName(dnsName)) { await this.AssertClusterVersionSupported(dnsName); var operationId = await client.DisableHttp(dnsName, location); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, TimeSpan.FromHours(1), this.Context.CancellationToken); } } /// <inheritdoc /> public Collection<string> ListAvailableLocations() { return this.ListAvailableLocationsAsync().WaitForResult(); } /// <inheritdoc /> public Collection<string> ListAvailableLocations(OSType osType) { return this.ListAvailableLocationsAsync(osType).WaitForResult(); } /// <inheritdoc /> public IEnumerable<KeyValuePair<string, string>> ListResourceProviderProperties() { var client = ServiceLocator.Instance.Locate<IRdfeServiceRestClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); return client.GetResourceProviderProperties().WaitForResult(); } /// <inheritdoc /> public Collection<HDInsightVersion> ListAvailableVersions() { return this.ListAvailableVersionsAsync().WaitForResult(); } /// <inheritdoc /> public ICollection<ClusterDetails> ListClusters() { return this.ListClustersAsync().WaitForResult(); } /// <inheritdoc /> public ClusterDetails GetCluster(string dnsName) { return this.GetClusterAsync(dnsName).WaitForResult(); } /// <inheritdoc /> public ClusterDetails GetCluster(string dnsName, string location) { return this.GetClusterAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public ClusterDetails CreateCluster(ClusterCreateParameters cluster) { return this.CreateClusterAsync(new ClusterCreateParametersV2(cluster)).WaitForResult(); } /// <inheritdoc /> public ClusterDetails CreateCluster(ClusterCreateParameters cluster, TimeSpan timeout) { return this.CreateClusterAsync(new ClusterCreateParametersV2(cluster)).WaitForResult(timeout); } public ClusterDetails CreateCluster(ClusterCreateParametersV2 cluster) { return this.CreateClusterAsync(cluster).WaitForResult(); } public ClusterDetails CreateCluster(ClusterCreateParametersV2 cluster, TimeSpan timeout) { return this.CreateClusterAsync(cluster).WaitForResult(timeout); } /// <inheritdoc /> public ClusterDetails ChangeClusterSize(string dnsName, string location, int newSize) { return this.ChangeClusterSizeAsync(dnsName, location, newSize).WaitForResult(); } /// <inheritdoc /> public ClusterDetails ChangeClusterSize(string dnsName, string location, int newSize, TimeSpan timeout) { return this.ChangeClusterSizeAsync(dnsName, location, newSize, timeout).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <inheritdoc /> public async Task<ClusterDetails> ChangeClusterSizeAsync(string dnsName, string location, int newSize) { return await ChangeClusterSizeAsync(dnsName, location, newSize, this.defaultResizeTimeout); } /// <inheritdoc /> public async Task<ClusterDetails> ChangeClusterSizeAsync(string dnsName, string location, int newSize, TimeSpan timeout) { dnsName.ArgumentNotNullOrEmpty("dnsName"); newSize.ArgumentNotNull("newSize"); location.ArgumentNotNull("location"); SchemaVersionUtils.EnsureSchemaVersionSupportsResize(this.capabilities.Value); var client = this.CreateClustersPocoClient(this.capabilities.Value); var operationId = Guid.Empty; try { this.LogMessage("Sending Change Cluster Size request.", Severity.Informational, Verbosity.Detailed); operationId = await client.ChangeClusterSize(dnsName, location, newSize); } catch (Exception ex) { this.LogMessage(ex.GetFirstException().Message, Severity.Error, Verbosity.Detailed); throw ex.GetFirstException(); } if (operationId == Guid.Empty) { return await client.ListContainer(dnsName); } await client.WaitForOperationCompleteOrError(dnsName, location, operationId, timeout, this.Context.CancellationToken); await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, dnsName, location, timeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); this.LogMessage("Validating that the cluster didn't go into an error state.", Severity.Informational, Verbosity.Detailed); var result = await client.ListContainer(dnsName); if (result == null) { throw new Exception(string.Format("Cluster {0} could not be found.", dnsName)); } if (result.Error != null) { this.LogMessage(result.Error.Message, Severity.Informational, Verbosity.Detailed); throw new Exception(result.Error.Message); } return result; } /// <inheritdoc /> public void DeleteCluster(string dnsName) { this.DeleteClusterAsync(dnsName).WaitForResult(); } /// <inheritdoc /> public void DeleteCluster(string dnsName, TimeSpan timeout) { this.DeleteClusterAsync(dnsName).WaitForResult(timeout); } /// <inheritdoc /> public void DeleteCluster(string dnsName, string location) { this.DeleteClusterAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public void DeleteCluster(string dnsName, string location, TimeSpan timeout) { this.DeleteClusterAsync(dnsName, location).WaitForResult(timeout); } /// <summary> /// Encrypt payload string into a base 64-encoded string using the certificate. /// This is suitable for encrypting storage account keys for later use as a job argument. /// </summary> /// <param name="cert"> /// Certificate used to encrypt the payload. /// </param> /// <param name="payload"> /// Value to encrypt. /// </param> /// <returns> /// Encrypted payload. /// </returns> public static string EncryptAsBase64String(X509Certificate2 cert, string payload) { var ci = new ContentInfo(Encoding.UTF8.GetBytes(payload)); var env = new EnvelopedCms(ci); env.Encrypt(new CmsRecipient(cert)); return Convert.ToBase64String(env.Encode()); } // This method is used by the NonPublic SDK. Be aware of breaking changes to that project when you alter it. private async Task AssertClusterVersionSupported(string dnsName) { var cluster = await this.GetClusterAsync(dnsName); if (cluster == null) { throw new HDInsightClusterDoesNotExistException(dnsName); } if (cluster.State == ClusterState.Error) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cluster '{0}' is an error state. Performing operations other than delete are not possible.", dnsName)); } this.AssertSupportedVersion(cluster.VersionNumber); } private async Task ValidateClusterVersion(ClusterCreateParametersV2 cluster) { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); // Validates the version for cluster creation if (!string.IsNullOrEmpty(cluster.Version) && !string.Equals(cluster.Version, DEFAULTHDINSIGHTVERSION, StringComparison.OrdinalIgnoreCase)) { this.AssertSupportedVersion(overrideHandlers.PayloadConverter.ConvertStringToVersion(cluster.Version)); var availableVersions = await overrideHandlers.VersionFinder.ListAvailableVersions(); if (availableVersions.All(hdinsightVersion => hdinsightVersion.Version != cluster.Version)) { throw new InvalidOperationException( string.Format( "Cannot create a cluster with version '{0}'. Available Versions for your subscription are: {1}", cluster.Version, string.Join(",", availableVersions))); } // Clusters with OSType.Linux only supported from version 3.2 onwards var version = new Version(cluster.Version); if (cluster.OSType == OSType.Linux && version.CompareTo(new Version("3.2")) < 0) { throw new NotSupportedException(string.Format("Clusters with OSType {0} are only supported from version 3.2", cluster.OSType)); } // HBase cluster only supported after version 3.0 if (version.CompareTo(new Version("3.0")) < 0 && cluster.ClusterType == ClusterType.HBase) { throw new InvalidOperationException( string.Format("Cannot create a HBase cluster with version '{0}'. HBase cluster only supported after version 3.0", cluster.Version)); } // Cluster customization only supported after version 3.0 if (version.CompareTo(new Version("3.0")) < 0 && cluster.ConfigActions != null && cluster.ConfigActions.Count > 0) { throw new InvalidOperationException( string.Format("Cannot create a customized cluster with version '{0}'. Customized clusters only supported after version 3.0", cluster.Version)); } // Various VM sizes only supported starting with version 3.1 if (version.CompareTo(new Version("3.1")) < 0 && createHasNewVMSizesSpecified(cluster)) { throw new InvalidOperationException( string.Format( "Cannot use various VM sizes with cluster version '{0}'. Custom VM sizes are only supported for cluster versions 3.1 and above.", cluster.Version)); } // Spark cluster only supported after version 3.2 if (version.CompareTo(new Version("3.2")) < 0 && cluster.ClusterType == ClusterType.Spark) { throw new InvalidOperationException( string.Format("Cannot create a Spark cluster with version '{0}'. Spark cluster only supported after version 3.2", cluster.Version)); } } else { cluster.Version = DEFAULTHDINSIGHTVERSION; } } private void AssertSupportedVersion(Version hdinsightClusterVersion) { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); switch (overrideHandlers.VersionFinder.GetVersionStatus(hdinsightClusterVersion)) { case VersionStatus.Obsolete: throw new NotSupportedException( string.Format( CultureInfo.CurrentCulture, HDInsightConstants.ClusterVersionTooLowForClusterOperations, hdinsightClusterVersion.ToString(), HDInsightSDKSupportedVersions.MinVersion, HDInsightSDKSupportedVersions.MaxVersion)); case VersionStatus.ToolsUpgradeRequired: throw new NotSupportedException( string.Format( CultureInfo.CurrentCulture, HDInsightConstants.ClusterVersionTooHighForClusterOperations, hdinsightClusterVersion.ToString(), HDInsightSDKSupportedVersions.MinVersion, HDInsightSDKSupportedVersions.MaxVersion)); } } private bool createHasNewVMSizesSpecified(ClusterCreateParametersV2 clusterCreateParameters) { const string ExtraLarge = "ExtraLarge"; const string Large = "Large"; if (!new[] {Large, ExtraLarge}.Contains(clusterCreateParameters.HeadNodeSize, StringComparer.OrdinalIgnoreCase)) { return true; } if (!clusterCreateParameters.DataNodeSize.Equals(Large)) { return true; } return clusterCreateParameters.ZookeeperNodeSize != null; } } }
{ "content_hash": "f6995ef46c0cb47e68b91756ac30585b", "timestamp": "", "source": "github", "line_count": 898, "max_line_length": 315, "avg_line_length": 45.49777282850779, "alnum_prop": 0.6063098122720709, "repo_name": "shixiaoyu/azure-sdk-for-net", "id": "b9b92fdb4cd57b9afcda851daa1c46bb2c45ae44", "size": "41542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/HDInsight/Microsoft.WindowsAzure.Management.HDInsight/HDInsightClient.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "26396861" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
MADDisc ======= ## Project Description This project had been published on App Store in 2011 and lasted for few months. This project created a carousal and a pointer that helps people to make a decision right away. People can set up different conditions and even those are without any relationship between each other. Then, use the finger tip to make pointer spinning around on the carousal. ## Future Work MADDisc is still an non-ARC project. I will not change it to ARC because it reminds me that **Don't forget the basic and don't leave the memory management away**. I am still refactoring it. This project is open sourced for everyone to discover something useful. ## Milestone MADDisc was in the top 20 of newly apps recommendation on App Store in 2011. ![screenshot](https://s3.amazonaws.com/f.cl.ly/items/1V1H142w3B03003G0917/%E7%98%8B%E7%8B%82%E8%BD%89%E7%9B%A4_%E5%9C%A8Entertainment%E9%A0%AD%E6%A2%9D.png)
{ "content_hash": "40384ed5cd282d0b85b30363c3db0790", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 352, "avg_line_length": 54.64705882352941, "alnum_prop": 0.7685683530678149, "repo_name": "derekli66/MADDisc", "id": "edbc5a33069e89617a122ab21caf5de9f1f4b5da", "size": "929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "326" }, { "name": "Objective-C", "bytes": "174396" } ], "symlink_target": "" }
 #include <aws/eks/model/CreateNodegroupRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::EKS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateNodegroupRequest::CreateNodegroupRequest() : m_clusterNameHasBeenSet(false), m_nodegroupNameHasBeenSet(false), m_scalingConfigHasBeenSet(false), m_diskSize(0), m_diskSizeHasBeenSet(false), m_subnetsHasBeenSet(false), m_instanceTypesHasBeenSet(false), m_amiType(AMITypes::NOT_SET), m_amiTypeHasBeenSet(false), m_remoteAccessHasBeenSet(false), m_nodeRoleHasBeenSet(false), m_labelsHasBeenSet(false), m_tagsHasBeenSet(false), m_clientRequestToken(Aws::Utils::UUID::RandomUUID()), m_clientRequestTokenHasBeenSet(true), m_launchTemplateHasBeenSet(false), m_capacityType(CapacityTypes::NOT_SET), m_capacityTypeHasBeenSet(false), m_versionHasBeenSet(false), m_releaseVersionHasBeenSet(false) { } Aws::String CreateNodegroupRequest::SerializePayload() const { JsonValue payload; if(m_nodegroupNameHasBeenSet) { payload.WithString("nodegroupName", m_nodegroupName); } if(m_scalingConfigHasBeenSet) { payload.WithObject("scalingConfig", m_scalingConfig.Jsonize()); } if(m_diskSizeHasBeenSet) { payload.WithInteger("diskSize", m_diskSize); } if(m_subnetsHasBeenSet) { Array<JsonValue> subnetsJsonList(m_subnets.size()); for(unsigned subnetsIndex = 0; subnetsIndex < subnetsJsonList.GetLength(); ++subnetsIndex) { subnetsJsonList[subnetsIndex].AsString(m_subnets[subnetsIndex]); } payload.WithArray("subnets", std::move(subnetsJsonList)); } if(m_instanceTypesHasBeenSet) { Array<JsonValue> instanceTypesJsonList(m_instanceTypes.size()); for(unsigned instanceTypesIndex = 0; instanceTypesIndex < instanceTypesJsonList.GetLength(); ++instanceTypesIndex) { instanceTypesJsonList[instanceTypesIndex].AsString(m_instanceTypes[instanceTypesIndex]); } payload.WithArray("instanceTypes", std::move(instanceTypesJsonList)); } if(m_amiTypeHasBeenSet) { payload.WithString("amiType", AMITypesMapper::GetNameForAMITypes(m_amiType)); } if(m_remoteAccessHasBeenSet) { payload.WithObject("remoteAccess", m_remoteAccess.Jsonize()); } if(m_nodeRoleHasBeenSet) { payload.WithString("nodeRole", m_nodeRole); } if(m_labelsHasBeenSet) { JsonValue labelsJsonMap; for(auto& labelsItem : m_labels) { labelsJsonMap.WithString(labelsItem.first, labelsItem.second); } payload.WithObject("labels", std::move(labelsJsonMap)); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("tags", std::move(tagsJsonMap)); } if(m_clientRequestTokenHasBeenSet) { payload.WithString("clientRequestToken", m_clientRequestToken); } if(m_launchTemplateHasBeenSet) { payload.WithObject("launchTemplate", m_launchTemplate.Jsonize()); } if(m_capacityTypeHasBeenSet) { payload.WithString("capacityType", CapacityTypesMapper::GetNameForCapacityTypes(m_capacityType)); } if(m_versionHasBeenSet) { payload.WithString("version", m_version); } if(m_releaseVersionHasBeenSet) { payload.WithString("releaseVersion", m_releaseVersion); } return payload.View().WriteReadable(); }
{ "content_hash": "5e0aad772835223f3159b11595881f7d", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 117, "avg_line_length": 22.61437908496732, "alnum_prop": 0.7225433526011561, "repo_name": "jt70471/aws-sdk-cpp", "id": "bc8763de04e0427092ace649f8c05b2784c0780b", "size": "3579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-eks/source/model/CreateNodegroupRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
import mock import pkg_resources as pkg from sahara.plugins import exceptions as ex from sahara.plugins.hdp import clusterspec as cs from sahara.plugins.hdp.versions.version_2_0_6 import services as s2 from sahara.plugins import provisioning from sahara.tests.unit import base as sahara_base import sahara.tests.unit.plugins.hdp.hdp_test_base as base from sahara.topology import topology_helper as th from sahara import version class TestCONF(object): def __init__(self, enable_data_locality, enable_hypervisor_awareness): self.enable_data_locality = enable_data_locality self.enable_hypervisor_awareness = enable_hypervisor_awareness @mock.patch("sahara.utils.openstack.nova.get_instance_info", base.get_instance_info) @mock.patch('sahara.plugins.hdp.versions.version_2_0_6.services.HdfsService.' '_get_swift_properties', return_value=[]) class ClusterSpecTestForHDP2(sahara_base.SaharaTestCase): service_validators = {} def setUp(self): super(ClusterSpecTestForHDP2, self).setUp() self.service_validators['YARN'] = self._assert_yarn self.service_validators['HDFS'] = self._assert_hdfs self.service_validators['MAPREDUCE2'] = self._assert_mrv2 self.service_validators['GANGLIA'] = self._assert_ganglia self.service_validators['NAGIOS'] = self._assert_nagios self.service_validators['AMBARI'] = self._assert_ambari self.service_validators['PIG'] = self._assert_pig self.service_validators['HIVE'] = self._assert_hive self.service_validators['HCATALOG'] = self._assert_hcatalog self.service_validators['ZOOKEEPER'] = self._assert_zookeeper self.service_validators['WEBHCAT'] = self._assert_webhcat self.service_validators['OOZIE'] = self._assert_oozie self.service_validators['SQOOP'] = self._assert_sqoop self.service_validators['HBASE'] = self._assert_hbase self.service_validators['HUE'] = self._assert_hue def test_parse_default_with_cluster(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "AMBARI_AGENT", "ZOOKEEPER_SERVER"]) node_group2 = TestNodeGroup('slave', [server2], ['NODEMANAGER', 'DATANODE']) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, []) self._assert_services(cluster_config.services) self._assert_configurations(cluster_config.configurations) node_groups = cluster_config.node_groups self.assertEqual(2, len(node_groups)) self.assertIn('master', node_groups) self.assertIn('slave', node_groups) master_node_group = node_groups['master'] self.assertEqual('master', master_node_group.name) self.assertEqual(13, len(master_node_group.components)) self.assertIn('NAMENODE', master_node_group.components) self.assertIn('RESOURCEMANAGER', master_node_group.components) self.assertIn('HISTORYSERVER', master_node_group.components) self.assertIn('SECONDARY_NAMENODE', master_node_group.components) self.assertIn('GANGLIA_SERVER', master_node_group.components) self.assertIn('GANGLIA_MONITOR', master_node_group.components) self.assertIn('NAGIOS_SERVER', master_node_group.components) self.assertIn('AMBARI_SERVER', master_node_group.components) self.assertIn('AMBARI_AGENT', master_node_group.components) self.assertIn('YARN_CLIENT', master_node_group.components) self.assertIn('ZOOKEEPER_SERVER', master_node_group.components) slave_node_group = node_groups['slave'] self.assertEqual('slave', slave_node_group.name) self.assertIn('NODEMANAGER', slave_node_group.components) return cluster_config def test_determine_component_hosts(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') server1 = base.TestServer('ambari_machine', 'master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'slave', '11111', 3, '222.22.2222', '333.22.2222') server3 = base.TestServer('host3', 'slave', '11111', 3, '222.22.2223', '333.22.2223') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) node_group2 = TestNodeGroup( 'slave', [server2], ["DATANODE", "NODEMANAGER", "HDFS_CLIENT", "MAPREDUCE2_CLIENT"]) node_group3 = TestNodeGroup( 'slave2', [server3], ["DATANODE", "NODEMANAGER", "HDFS_CLIENT", "MAPREDUCE2_CLIENT"]) cluster = base.TestCluster([node_group1, node_group2, node_group3]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, []) hosts = cluster_config.determine_component_hosts('AMBARI_SERVER') self.assertEqual(1, len(hosts)) self.assertEqual('ambari_machine', hosts.pop().fqdn()) hosts = cluster_config.determine_component_hosts('DATANODE') self.assertEqual(2, len(hosts)) datanodes = set([server2.fqdn(), server3.fqdn()]) host_fqdn = set([hosts.pop().fqdn(), hosts.pop().fqdn()]) # test intersection is both servers self.assertEqual(datanodes, host_fqdn & datanodes) def test_finalize_configuration(self, patched): patched.return_value = [{'name': 'swift.prop1', 'value': 'swift_prop_value'}, {'name': 'swift.prop2', 'value': 'swift_prop_value2'}] cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') master_host = base.TestServer( 'master.novalocal', 'master', '11111', 3, '111.11.1111', '222.11.1111') jt_host = base.TestServer( 'jt_host.novalocal', 'jt', '11111', 3, '111.11.2222', '222.11.2222') nn_host = base.TestServer( 'nn_host.novalocal', 'nn', '11111', 3, '111.11.3333', '222.11.3333') snn_host = base.TestServer( 'snn_host.novalocal', 'jt', '11111', 3, '111.11.4444', '222.11.4444') hive_host = base.TestServer( 'hive_host.novalocal', 'hive', '11111', 3, '111.11.5555', '222.11.5555') hive_ms_host = base.TestServer( 'hive_ms_host.novalocal', 'hive_ms', '11111', 3, '111.11.6666', '222.11.6666') hive_mysql_host = base.TestServer( 'hive_mysql_host.novalocal', 'hive_mysql', '11111', 3, '111.11.7777', '222.11.7777') hcat_host = base.TestServer( 'hcat_host.novalocal', 'hcat', '11111', 3, '111.11.8888', '222.11.8888') zk1_host = base.TestServer( 'zk1_host.novalocal', 'zk1', '11111', 3, '111.11.9999', '222.11.9999') zk2_host = base.TestServer( 'zk2_host.novalocal', 'zk2', '11112', 3, '111.11.9990', '222.11.9990') oozie_host = base.TestServer( 'oozie_host.novalocal', 'oozie', '11111', 3, '111.11.9999', '222.11.9999') slave_host = base.TestServer( 'slave1.novalocal', 'slave', '11111', 3, '222.22.6666', '333.22.6666') master_ng = TestNodeGroup( 'master', [master_host], ["GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOIS_SERVER", "AMBARI_SERVER", "AMBARI_AGENT"]) jt_ng = TestNodeGroup( 'jt', [jt_host], ["RESOURCEMANAGER", "GANGLIA_MONITOR", "HISTORYSERVER", "AMBARI_AGENT"]) nn_ng = TestNodeGroup( 'nn', [nn_host], ["NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) snn_ng = TestNodeGroup( 'snn', [snn_host], ["SECONDARY_NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_ng = TestNodeGroup( 'hive', [hive_host], ["HIVE_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_ms_ng = TestNodeGroup( 'meta', [hive_ms_host], ["HIVE_METASTORE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_mysql_ng = TestNodeGroup( 'mysql', [hive_mysql_host], ["MYSQL_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hcat_ng = TestNodeGroup( 'hcat', [hcat_host], ["WEBHCAT_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) zk1_ng = TestNodeGroup( 'zk1', [zk1_host], ["ZOOKEEPER_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) zk2_ng = TestNodeGroup( 'zk2', [zk2_host], ["ZOOKEEPER_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) oozie_ng = TestNodeGroup( 'oozie', [oozie_host], ["OOZIE_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) slave_ng = TestNodeGroup( 'slave', [slave_host], ["DATANODE", "NODEMANAGER", "GANGLIA_MONITOR", "HDFS_CLIENT", "MAPREDUCE2_CLIENT", "OOZIE_CLIENT", "AMBARI_AGENT"]) user_input_config = TestUserInputConfig( 'core-site', 'cluster', 'fs.defaultFS') user_input = provisioning.UserInput( user_input_config, 'hdfs://nn_dif_host.novalocal:8020') cluster = base.TestCluster([master_ng, jt_ng, nn_ng, snn_ng, hive_ng, hive_ms_ng, hive_mysql_ng, hcat_ng, zk1_ng, zk2_ng, oozie_ng, slave_ng]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) config = cluster_config.configurations # for this value, validating that user inputs override configured # values, whether they are processed by runtime or not self.assertEqual(config['core-site']['fs.defaultFS'], 'hdfs://nn_dif_host.novalocal:8020') self.assertEqual(config['mapred-site'] ['mapreduce.jobhistory.webapp.address'], 'jt_host.novalocal:19888') self.assertEqual(config['hdfs-site']['dfs.namenode.http-address'], 'nn_host.novalocal:50070') self.assertEqual(config['hdfs-site'] ['dfs.namenode.secondary.http-address'], 'snn_host.novalocal:50090') self.assertEqual(config['hdfs-site']['dfs.namenode.https-address'], 'nn_host.novalocal:50470') self.assertEqual(config['global']['hive_hostname'], 'hive_host.novalocal') self.assertEqual(config['core-site']['hadoop.proxyuser.hive.hosts'], 'hive_host.novalocal') self.assertEqual(config['hive-site'] ['javax.jdo.option.ConnectionURL'], 'jdbc:mysql://hive_mysql_host.novalocal/hive?' 'createDatabaseIfNotExist=true') self.assertEqual(config['hive-site']['hive.metastore.uris'], 'thrift://hive_ms_host.novalocal:9083') self.assertTrue( 'hive.metastore.uris=thrift://hive_ms_host.novalocal:9083' in config['webhcat-site']['templeton.hive.properties']) self.assertEqual(config['core-site']['hadoop.proxyuser.hcat.hosts'], 'hcat_host.novalocal') self.assertEqual(set( config['webhcat-site']['templeton.zookeeper.hosts'].split(',')), set(['zk1_host.novalocal:2181', 'zk2_host.novalocal:2181'])) self.assertEqual(config['oozie-site']['oozie.base.url'], 'http://oozie_host.novalocal:11000/oozie') self.assertEqual(config['global']['oozie_hostname'], 'oozie_host.novalocal') self.assertEqual(config['core-site']['hadoop.proxyuser.oozie.hosts'], 'oozie_host.novalocal,222.11.9999,111.11.9999') # test swift properties self.assertEqual('swift_prop_value', config['core-site']['swift.prop1']) self.assertEqual('swift_prop_value2', config['core-site']['swift.prop2']) def test_finalize_configuration_with_hue(self, patched): patched.return_value = [{'name': 'swift.prop1', 'value': 'swift_prop_value'}, {'name': 'swift.prop2', 'value': 'swift_prop_value2'}] cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') master_host = base.TestServer( 'master.novalocal', 'master', '11111', 3, '111.11.1111', '222.11.1111') jt_host = base.TestServer( 'jt_host.novalocal', 'jt', '11111', 3, '111.11.2222', '222.11.2222') nn_host = base.TestServer( 'nn_host.novalocal', 'nn', '11111', 3, '111.11.3333', '222.11.3333') snn_host = base.TestServer( 'snn_host.novalocal', 'jt', '11111', 3, '111.11.4444', '222.11.4444') hive_host = base.TestServer( 'hive_host.novalocal', 'hive', '11111', 3, '111.11.5555', '222.11.5555') hive_ms_host = base.TestServer( 'hive_ms_host.novalocal', 'hive_ms', '11111', 3, '111.11.6666', '222.11.6666') hive_mysql_host = base.TestServer( 'hive_mysql_host.novalocal', 'hive_mysql', '11111', 3, '111.11.7777', '222.11.7777') hcat_host = base.TestServer( 'hcat_host.novalocal', 'hcat', '11111', 3, '111.11.8888', '222.11.8888') zk1_host = base.TestServer( 'zk1_host.novalocal', 'zk1', '11111', 3, '111.11.9999', '222.11.9999') zk2_host = base.TestServer( 'zk2_host.novalocal', 'zk2', '11112', 3, '111.11.9990', '222.11.9990') oozie_host = base.TestServer( 'oozie_host.novalocal', 'oozie', '11111', 3, '111.11.9999', '222.11.9999') slave_host = base.TestServer( 'slave1.novalocal', 'slave', '11111', 3, '222.22.6666', '333.22.6666') master_ng = TestNodeGroup( 'master', [master_host], ["GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOIS_SERVER", "AMBARI_SERVER", "AMBARI_AGENT"]) jt_ng = TestNodeGroup( 'jt', [jt_host], ["RESOURCEMANAGER", "GANGLIA_MONITOR", "HISTORYSERVER", "AMBARI_AGENT"]) nn_ng = TestNodeGroup( 'nn', [nn_host], ["NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) snn_ng = TestNodeGroup( 'snn', [snn_host], ["SECONDARY_NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_ng = TestNodeGroup( 'hive', [hive_host], ["HIVE_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_ms_ng = TestNodeGroup( 'meta', [hive_ms_host], ["HIVE_METASTORE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hive_mysql_ng = TestNodeGroup( 'mysql', [hive_mysql_host], ["MYSQL_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) hcat_ng = TestNodeGroup( 'hcat', [hcat_host], ["WEBHCAT_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) zk1_ng = TestNodeGroup( 'zk1', [zk1_host], ["ZOOKEEPER_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) zk2_ng = TestNodeGroup( 'zk2', [zk2_host], ["ZOOKEEPER_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) oozie_ng = TestNodeGroup( 'oozie', [oozie_host], ["OOZIE_SERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) slave_ng = TestNodeGroup( 'slave', [slave_host], ["DATANODE", "NODEMANAGER", "GANGLIA_MONITOR", "HDFS_CLIENT", "MAPREDUCE2_CLIENT", "OOZIE_CLIENT", "AMBARI_AGENT", "HUE"]) user_input_config = TestUserInputConfig( 'core-site', 'cluster', 'fs.defaultFS') user_input = provisioning.UserInput( user_input_config, 'hdfs://nn_dif_host.novalocal:8020') cluster = base.TestCluster([master_ng, jt_ng, nn_ng, snn_ng, hive_ng, hive_ms_ng, hive_mysql_ng, hcat_ng, zk1_ng, zk2_ng, oozie_ng, slave_ng]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) config = cluster_config.configurations # for this value, validating that user inputs override configured # values, whether they are processed by runtime or not self.assertEqual(config['core-site']['fs.defaultFS'], 'hdfs://nn_dif_host.novalocal:8020') self.assertEqual(config['mapred-site'] ['mapreduce.jobhistory.webapp.address'], 'jt_host.novalocal:19888') self.assertEqual(config['hdfs-site']['dfs.namenode.http-address'], 'nn_host.novalocal:50070') self.assertEqual(config['hdfs-site'] ['dfs.namenode.secondary.http-address'], 'snn_host.novalocal:50090') self.assertEqual(config['hdfs-site']['dfs.namenode.https-address'], 'nn_host.novalocal:50470') self.assertEqual(config['hdfs-site']['dfs.support.broken.append'], 'true') self.assertEqual(config['hdfs-site']['dfs.webhdfs.enabled'], 'true') self.assertEqual(config['global']['hive_hostname'], 'hive_host.novalocal') self.assertEqual(config['core-site']['hadoop.proxyuser.hive.hosts'], 'hive_host.novalocal') self.assertEqual(config['hive-site'] ['javax.jdo.option.ConnectionURL'], 'jdbc:mysql://hive_mysql_host.novalocal/hive?' 'createDatabaseIfNotExist=true') self.assertEqual(config['hive-site']['hive.metastore.uris'], 'thrift://hive_ms_host.novalocal:9083') self.assertTrue( 'hive.metastore.uris=thrift://hive_ms_host.novalocal:9083' in config['webhcat-site']['templeton.hive.properties']) self.assertEqual(config['core-site']['hadoop.proxyuser.hcat.hosts'], '*') self.assertEqual(config['core-site']['hadoop.proxyuser.hcat.groups'], '*') self.assertEqual(config['core-site']['hadoop.proxyuser.hue.hosts'], '*') self.assertEqual(config['core-site']['hadoop.proxyuser.hue.groups'], '*') self.assertEqual(set( config['webhcat-site']['templeton.zookeeper.hosts'].split(',')), set(['zk1_host.novalocal:2181', 'zk2_host.novalocal:2181'])) self.assertEqual(config['webhcat-site']['webhcat.proxyuser.hue.hosts'], '*') self.assertEqual(config['webhcat-site'] ['webhcat.proxyuser.hue.groups'], '*') self.assertEqual(config['oozie-site']['oozie.base.url'], 'http://oozie_host.novalocal:11000/oozie') self.assertEqual(config['oozie-site'] ['oozie.service.ProxyUserService.proxyuser.hue.' 'groups'], '*') self.assertEqual(config['oozie-site'] ['oozie.service.ProxyUserService.proxyuser.hue.' 'hosts'], '*') self.assertEqual(config['global']['oozie_hostname'], 'oozie_host.novalocal') self.assertEqual(config['core-site']['hadoop.proxyuser.oozie.hosts'], 'oozie_host.novalocal,222.11.9999,111.11.9999') # test swift properties self.assertEqual('swift_prop_value', config['core-site']['swift.prop1']) self.assertEqual('swift_prop_value2', config['core-site']['swift.prop2']) def test__determine_deployed_services(self, nova_mock): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') master_host = base.TestServer( 'master.novalocal', 'master', '11111', 3, '111.11.1111', '222.11.1111') jt_host = base.TestServer( 'jt_host.novalocal', 'jt', '11111', 3, '111.11.2222', '222.11.2222') nn_host = base.TestServer( 'nn_host.novalocal', 'nn', '11111', 3, '111.11.3333', '222.11.3333') snn_host = base.TestServer( 'snn_host.novalocal', 'jt', '11111', 3, '111.11.4444', '222.11.4444') slave_host = base.TestServer( 'slave1.novalocal', 'slave', '11111', 3, '222.22.6666', '333.22.6666') master_ng = TestNodeGroup( 'master', [master_host], ['GANGLIA_SERVER', 'GANGLIA_MONITOR', 'NAGIOS_SERVER', 'AMBARI_SERVER', 'AMBARI_AGENT', 'ZOOKEEPER_SERVER']) jt_ng = TestNodeGroup('jt', [jt_host], ["RESOURCEMANAGER", "HISTORYSERVER", "GANGLIA_MONITOR", "AMBARI_AGENT"]) nn_ng = TestNodeGroup('nn', [nn_host], ["NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) snn_ng = TestNodeGroup('snn', [snn_host], ["SECONDARY_NAMENODE", "GANGLIA_MONITOR", "AMBARI_AGENT"]) slave_ng = TestNodeGroup( 'slave', [slave_host], ["DATANODE", "NODEMANAGER", "GANGLIA_MONITOR", "HDFS_CLIENT", "MAPREDUCE2_CLIENT", "AMBARI_AGENT"]) cluster = base.TestCluster([master_ng, jt_ng, nn_ng, snn_ng, slave_ng]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, []) services = cluster_config.services for service in services: if service.name in ['YARN', 'HDFS', 'MAPREDUCE2', 'GANGLIA', 'AMBARI', 'NAGIOS', 'ZOOKEEPER']: self.assertTrue(service.deployed) else: self.assertFalse(service.deployed) def test_ambari_rpm_path(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') cluster_spec = cs.ClusterSpec(cluster_config_file, version='2.0.6') ambari_config = cluster_spec.configurations['ambari'] rpm = ambari_config.get('rpm', None) self.assertEqual('http://s3.amazonaws.com/' 'public-repo-1.hortonworks.com/ambari/centos6/' '1.x/updates/1.6.0/ambari.repo', rpm) def test_fs_umask(self, patched): s_conf = s2.CONF try: s2.CONF = TestCONF(False, False) cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "AMBARI_AGENT", "HISTORYSERVER", "ZOOKEEPER_SERVER"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, '2.0.6') cluster_config.create_operational_config(cluster, []) # core-site self.assertEqual( '022', cluster_config.configurations['hdfs-site'] ['fs.permissions.umask-mode']) finally: s2.CONF = s_conf def test_parse_default(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') self._assert_services(cluster_config.services) self._assert_configurations(cluster_config.configurations) node_groups = cluster_config.node_groups self.assertEqual(2, len(node_groups)) master_node_group = node_groups['master'] self.assertEqual('master', master_node_group.name) self.assertIsNone(master_node_group.predicate) self.assertEqual('1', master_node_group.cardinality) self.assertEqual(8, len(master_node_group.components)) self.assertIn('NAMENODE', master_node_group.components) self.assertIn('RESOURCEMANAGER', master_node_group.components) self.assertIn('HISTORYSERVER', master_node_group.components) self.assertIn('SECONDARY_NAMENODE', master_node_group.components) self.assertIn('GANGLIA_SERVER', master_node_group.components) self.assertIn('NAGIOS_SERVER', master_node_group.components) self.assertIn('AMBARI_SERVER', master_node_group.components) self.assertIn('ZOOKEEPER_SERVER', master_node_group.components) slave_node_group = node_groups['slave'] self.assertEqual('slave', slave_node_group.name) self.assertIsNone(slave_node_group.predicate) self.assertEqual('1+', slave_node_group.cardinality) self.assertEqual(5, len(slave_node_group.components)) self.assertIn('DATANODE', slave_node_group.components) self.assertIn('NODEMANAGER', slave_node_group.components) self.assertIn('HDFS_CLIENT', slave_node_group.components) self.assertIn('YARN_CLIENT', slave_node_group.components) self.assertIn('MAPREDUCE2_CLIENT', slave_node_group.components) return cluster_config def test_ambari_rpm(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') self._assert_configurations(cluster_config.configurations) ambari_config = cluster_config.configurations['ambari'] self.assertIsNotNone('no rpm uri found', ambari_config.get('rpm', None)) def test_normalize(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster = cluster_config.normalize() configs = cluster.cluster_configs contains_dfs_datanode_http_address = False contains_staging_dir = False contains_mapred_user = False for entry in configs: config = entry.config # assert some random configurations across targets if config.name == 'dfs.datanode.http.address': contains_dfs_datanode_http_address = True self.assertEqual('string', config.type) self.assertEqual('0.0.0.0:50075', config.default_value) self.assertEqual('HDFS', config.applicable_target) if config.name == 'yarn.app.mapreduce.am.staging-dir': contains_staging_dir = True self.assertEqual('string', config.type) self.assertEqual( '/user', config.default_value) self.assertEqual('MAPREDUCE2', config.applicable_target) if config.name == 'mapred_user': contains_mapred_user = True self.assertEqual('string', config.type) self.assertEqual('mapred', config.default_value) self.assertEqual('MAPREDUCE2', config.applicable_target) # print 'Config: name: {0}, type:{1}, # default value:{2}, target:{3}, Value:{4}'.format( # config.name, config.type, # config.default_value, # config.applicable_target, entry.value) self.assertTrue(contains_dfs_datanode_http_address) self.assertTrue(contains_staging_dir) self.assertTrue(contains_mapred_user) node_groups = cluster.node_groups self.assertEqual(2, len(node_groups)) contains_master_group = False contains_slave_group = False for i in range(2): node_group = node_groups[i] components = node_group.node_processes if node_group.name == "master": contains_master_group = True self.assertEqual(8, len(components)) self.assertIn('NAMENODE', components) self.assertIn('RESOURCEMANAGER', components) self.assertIn('HISTORYSERVER', components) self.assertIn('SECONDARY_NAMENODE', components) self.assertIn('GANGLIA_SERVER', components) self.assertIn('NAGIOS_SERVER', components) self.assertIn('AMBARI_SERVER', components) self.assertIn('ZOOKEEPER_SERVER', components) # TODO(jspeidel): node configs # TODO(jspeidel): vm_requirements elif node_group.name == 'slave': contains_slave_group = True self.assertEqual(5, len(components)) self.assertIn('DATANODE', components) self.assertIn('NODEMANAGER', components) self.assertIn('HDFS_CLIENT', components) self.assertIn('YARN_CLIENT', components) self.assertIn('MAPREDUCE2_CLIENT', components) # TODO(jspeidel): node configs # TODO(jspeidel): vm requirements else: self.fail('Unexpected node group: {0}'.format(node_group.name)) self.assertTrue(contains_master_group) self.assertTrue(contains_slave_group) def test_existing_config_item_in_top_level_within_blueprint(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') user_input_config = TestUserInputConfig( 'global', 'OOZIE', 'oozie_log_dir') user_input = provisioning.UserInput(user_input_config, '/some/new/path') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) self.assertEqual('/some/new/path', cluster_config.configurations ['global']['oozie_log_dir']) def test_new_config_item_in_top_level_within_blueprint(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') user_input_config = TestUserInputConfig( 'global', 'general', 'new_property') user_input = provisioning.UserInput(user_input_config, 'foo') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) self.assertEqual( 'foo', cluster_config.configurations['global']['new_property']) def test_topology_configuration_no_hypervisor(self, patched): s_conf = s2.CONF th_conf = th.CONF try: s2.CONF = TestCONF(True, False) th.CONF = TestCONF(True, False) cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, []) # core-site self.assertEqual( 'org.apache.hadoop.net.NetworkTopology', cluster_config.configurations['core-site'] ['net.topology.impl']) self.assertEqual( 'true', cluster_config.configurations['core-site'] ['net.topology.nodegroup.aware']) self.assertEqual( 'org.apache.hadoop.hdfs.server.namenode.' 'BlockPlacementPolicyWithNodeGroup', cluster_config.configurations['core-site'] ['dfs.block.replicator.classname']) self.assertEqual( 'true', cluster_config.configurations['core-site'] ['fs.swift.service.sahara.location-aware']) self.assertEqual( 'org.apache.hadoop.net.ScriptBasedMapping', cluster_config.configurations['core-site'] ['net.topology.node.switch.mapping.impl']) self.assertEqual( '/etc/hadoop/conf/topology.sh', cluster_config.configurations['core-site'] ['net.topology.script.file.name']) # mapred-site self.assertEqual( 'true', cluster_config.configurations['mapred-site'] ['mapred.jobtracker.nodegroup.aware']) self.assertEqual( '3', cluster_config.configurations['mapred-site'] ['mapred.task.cache.levels']) self.assertEqual( 'org.apache.hadoop.mapred.JobSchedulableWithNodeGroup', cluster_config.configurations['mapred-site'] ['mapred.jobtracker.jobSchedulable']) finally: s2.CONF = s_conf th.CONF = th_conf def test_topology_configuration_with_hypervisor(self, patched): s_conf = s2.CONF try: s2.CONF = TestCONF(True, True) cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, []) # core-site self.assertEqual( 'org.apache.hadoop.net.NetworkTopologyWithNodeGroup', cluster_config.configurations['core-site'] ['net.topology.impl']) finally: s2.CONF = s_conf def test_update_ambari_admin_user(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') user_input_config = TestUserInputConfig('ambari-stack', 'AMBARI', 'ambari.admin.user') user_input = provisioning.UserInput(user_input_config, 'new-user') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) ambari_service = next(service for service in cluster_config.services if service.name == 'AMBARI') users = ambari_service.users self.assertEqual(1, len(users)) self.assertEqual('new-user', users[0].name) def test_update_ambari_admin_password(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') user_input_config = TestUserInputConfig('ambari-stack', 'AMBARI', 'ambari.admin.password') user_input = provisioning.UserInput(user_input_config, 'new-pwd') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'master', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'slave', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config(cluster, [user_input]) ambari_service = next(service for service in cluster_config.services if service.name == 'AMBARI') users = ambari_service.users self.assertEqual(1, len(users)) self.assertEqual('new-pwd', users[0].password) def test_update_ambari_admin_user_and_password(self, patched): cluster_config_file = pkg.resource_string( version.version_info.package, 'plugins/hdp/versions/version_2_0_6/resources/' 'default-cluster.template') user_user_input_config = TestUserInputConfig('ambari-stack', 'AMBARI', 'ambari.admin.user') pwd_user_input_config = TestUserInputConfig('ambari-stack', 'AMBARI', 'ambari.admin.password') user_user_input = provisioning.UserInput(user_user_input_config, 'new-admin_user') pwd_user_input = provisioning.UserInput(pwd_user_input_config, 'new-admin_pwd') server1 = base.TestServer('host1', 'test-master', '11111', 3, '111.11.1111', '222.11.1111') server2 = base.TestServer('host2', 'test-slave', '11111', 3, '222.22.2222', '333.22.2222') node_group1 = TestNodeGroup( 'one', [server1], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "SECONDARY_NAMENODE", "GANGLIA_SERVER", "GANGLIA_MONITOR", "NAGIOS_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'two', [server2], ["NODEMANAGER", "DATANODE", "AMBARI_AGENT", "GANGLIA_MONITOR"]) cluster = base.TestCluster([node_group1, node_group2]) cluster_config = cs.ClusterSpec(cluster_config_file, version='2.0.6') cluster_config.create_operational_config( cluster, [user_user_input, pwd_user_input]) ambari_service = next(service for service in cluster_config.services if service.name == 'AMBARI') users = ambari_service.users self.assertEqual(1, len(users)) self.assertEqual('new-admin_user', users[0].name) self.assertEqual('new-admin_pwd', users[0].password) def test_validate_missing_hdfs(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["NODEMANAGER", "MAPREDUCE2_CLIENT", "HISTORYSERVER"]) node_group2 = TestNodeGroup( 'master', [server2], ["RESOURCEMANAGER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing hdfs service try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.RequiredServiceMissingException: # expected pass def test_validate_missing_mr2(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing mr service try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.RequiredServiceMissingException: # expected pass def test_validate_missing_ambari(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["NAMENODE", "RESOURCEMANAGER", "ZOOKEEPER_SERVER"]) node_group2 = TestNodeGroup( 'master', [server2], ["DATANODE", "NODEMANAGER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing ambari service try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.RequiredServiceMissingException: # expected pass # TODO(jspeidel): move validate_* to test_services when validate # is called independently of cluspterspec def test_validate_hdfs(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "HDFS_CLIENT", "MAPREDUCE2_CLIENT"], 1) node_group2 = TestNodeGroup( 'master', [server2], ["RESOURCEMANAGER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing NN try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "ZOOKEEPER_SERVER", "AMBARI_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 NN node_group3 = TestNodeGroup( 'master2', [server2], ["NAMENODE"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_yarn(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "HDFS_CLIENT", "MAPREDUCE2_CLIENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing JT try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 JT node_group3 = TestNodeGroup( 'master', [server2], ["RESOURCEMANAGER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass # should cause validation exception due to 2 NN node_group3 = TestNodeGroup( 'master', [server2], ["NAMENODE"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass # should fail due to no nodemanager node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "HDFS_CLIENT", "MAPREDUCE2_CLIENT"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing JT try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_hive(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "HIVE_CLIENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing hive_server try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HIVE_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 HIVE_SERVER node_group3 = TestNodeGroup( 'master', [server2], ["HIVE_SERVER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_zk(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') server3 = base.TestServer('host3', 'master', '11113', 3, '111.11.1113', '222.22.2224') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "ZOOKEEPER_CLIENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "AMBARI_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing ZOOKEEPER_SERVER try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "ZOOKEEPER_SERVER", "AMBARI_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should allow multiple ZOOKEEPER_SERVER processes node_group3 = TestNodeGroup( 'zkserver', [server3], ["ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') cluster_config.create_operational_config(cluster, []) def test_validate_oozie(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "OOZIE_CLIENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing OOZIE_SERVER try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "OOZIE_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 OOZIE_SERVER node_group3 = TestNodeGroup( 'master', [server2], ["OOZIE_SERVER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_ganglia(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "GANGLIA_MONITOR"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing GANGLIA_SERVER try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "GANGLIA_SERVER", "AMBARI_SERVER", "HISTORYSERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 GANGLIA_SERVER node_group3 = TestNodeGroup( 'master2', [server2], ["GANGLIA_SERVER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_ambari(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing AMBARI_SERVER try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should cause validation exception due to 2 AMBARI_SERVER node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) node_group3 = TestNodeGroup( 'master', [server2], ["AMBARI_SERVER"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') try: cluster_config.create_operational_config(cluster, []) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_validate_hue(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "HUE"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing hive_server, oozie_server and # webhchat_server which is required by hue self.assertRaises(ex.RequiredServiceMissingException, cluster_config.create_operational_config, cluster, []) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HIVE_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing oozie_server and webhchat_server, which # is required by hue self.assertRaises(ex.RequiredServiceMissingException, cluster_config.create_operational_config, cluster, []) node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "OOZIE_CLIENT", "HUE"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HIVE_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER", "OOZIE_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should fail due to missing webhchat_server, which is required by hue self.assertRaises(ex.RequiredServiceMissingException, cluster_config.create_operational_config, cluster, []) node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "OOZIE_CLIENT", "HUE"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HIVE_SERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER", "OOZIE_SERVER", "WEBHCAT_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # should validate successfully now cluster_config.create_operational_config(cluster, []) # should have automatically added a HIVE_CLIENT to "slave" node group hue_ngs = cluster_config.get_node_groups_containing_component("HUE") self.assertEqual(1, len(hue_ngs)) self.assertIn("HIVE_CLIENT", hue_ngs.pop().components) # should cause validation exception due to 2 hue instances node_group3 = TestNodeGroup( 'master', [server2], ["HUE"]) cluster = base.TestCluster([node_group, node_group2, node_group3]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') self.assertRaises(ex.InvalidComponentCountException, cluster_config.create_operational_config, cluster, []) def test_validate_scaling_existing_ng(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # sanity check that original config validates cluster_config.create_operational_config(cluster, []) cluster_config = base.create_clusterspec(hdp_version='2.0.6') scaled_groups = {'master': 2} # should fail due to 2 JT try: cluster_config.create_operational_config( cluster, [], scaled_groups) self.fail('Validation should have thrown an exception') except ex.InvalidComponentCountException: # expected pass def test_scale(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER", "AMBARI_AGENT"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "ZOOKEEPER_SERVER", "AMBARI_SERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # sanity check that original config validates cluster_config.create_operational_config(cluster, []) slave_ng = cluster_config.node_groups['slave'] self.assertEqual(1, slave_ng.count) cluster_config.scale({'slave': 2}) self.assertEqual(2, slave_ng.count) def test_get_deployed_configurations(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') node_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER"]) node_group2 = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "AMBARI_SERVER", "ZOOKEEPER_SERVER", "HISTORYSERVER"]) cluster = base.TestCluster([node_group, node_group2]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') # sanity check that original config validates cluster_config.create_operational_config(cluster, []) configs = cluster_config.get_deployed_configurations() expected_configs = set(['mapred-site', 'ambari', 'hdfs-site', 'global', 'core-site', 'yarn-site']) self.assertEqual(expected_configs, expected_configs & configs) def test_get_deployed_node_group_count(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') slave_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER"]) slave2_group = TestNodeGroup( 'slave2', [server], ["DATANODE", "NODEMANAGER"]) master_group = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([master_group, slave_group, slave2_group]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') cluster_config.create_operational_config(cluster, []) self.assertEqual(2, cluster_config.get_deployed_node_group_count( 'DATANODE')) self.assertEqual(1, cluster_config.get_deployed_node_group_count( 'AMBARI_SERVER')) def test_get_node_groups_containing_component(self, patched): server = base.TestServer('host1', 'slave', '11111', 3, '111.11.1111', '222.22.2222') server2 = base.TestServer('host2', 'master', '11112', 3, '111.11.1112', '222.22.2223') slave_group = TestNodeGroup( 'slave', [server], ["DATANODE", "NODEMANAGER"]) slave2_group = TestNodeGroup( 'slave2', [server], ["DATANODE", "NODEMANAGER"]) master_group = TestNodeGroup( 'master', [server2], ["NAMENODE", "RESOURCEMANAGER", "HISTORYSERVER", "AMBARI_SERVER", "ZOOKEEPER_SERVER"]) cluster = base.TestCluster([master_group, slave_group, slave2_group]) cluster_config = base.create_clusterspec(hdp_version='2.0.6') cluster_config.create_operational_config(cluster, []) datanode_ngs = cluster_config.get_node_groups_containing_component( 'DATANODE') self.assertEqual(2, len(datanode_ngs)) ng_names = set([datanode_ngs[0].name, datanode_ngs[1].name]) self.assertIn('slave', ng_names) self.assertIn('slave2', ng_names) def test_get_components_for_type(self, patched): cluster_config = base.create_clusterspec(hdp_version='2.0.6') clients = cluster_config.get_components_for_type('CLIENT') slaves = cluster_config.get_components_for_type('SLAVE') masters = cluster_config.get_components_for_type('MASTER') expected_clients = set(['HCAT', 'ZOOKEEPER_CLIENT', 'MAPREDUCE2_CLIENT', 'HIVE_CLIENT', 'HDFS_CLIENT', 'PIG', 'YARN_CLIENT', 'HUE']) self.assertEqual(expected_clients, expected_clients & set(clients)) expected_slaves = set(['AMBARI_AGENT', 'NODEMANAGER', 'DATANODE', 'GANGLIA_MONITOR']) self.assertEqual(expected_slaves, expected_slaves & set(slaves)) expected_masters = set(['SECONDARY_NAMENODE', 'HIVE_METASTORE', 'AMBARI_SERVER', 'RESOURCEMANAGER', 'WEBHCAT_SERVER', 'NAGIOS_SERVER', 'MYSQL_SERVER', 'ZOOKEEPER_SERVER', 'NAMENODE', 'HIVE_SERVER', 'GANGLIA_SERVER']) self.assertEqual(expected_masters, expected_masters & set(masters)) def _assert_services(self, services): found_services = [] for service in services: name = service.name found_services.append(name) self.service_validators[name](service) self.assertEqual(15, len(found_services)) self.assertIn('HDFS', found_services) self.assertIn('MAPREDUCE2', found_services) self.assertIn('GANGLIA', found_services) self.assertIn('NAGIOS', found_services) self.assertIn('AMBARI', found_services) self.assertIn('PIG', found_services) self.assertIn('HIVE', found_services) self.assertIn('HCATALOG', found_services) self.assertIn('ZOOKEEPER', found_services) self.assertIn('WEBHCAT', found_services) self.assertIn('OOZIE', found_services) self.assertIn('SQOOP', found_services) self.assertIn('HBASE', found_services) self.assertIn('HUE', found_services) def _assert_hdfs(self, service): self.assertEqual('HDFS', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(4, len(found_components)) self._assert_component('NAMENODE', 'MASTER', "1", found_components['NAMENODE']) self._assert_component('DATANODE', 'SLAVE', "1+", found_components['DATANODE']) self._assert_component('SECONDARY_NAMENODE', 'MASTER', "1", found_components['SECONDARY_NAMENODE']) self._assert_component('HDFS_CLIENT', 'CLIENT', "1+", found_components['HDFS_CLIENT']) # TODO(jspeidel) config def _assert_mrv2(self, service): self.assertEqual('MAPREDUCE2', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(2, len(found_components)) self._assert_component('HISTORYSERVER', 'MASTER', "1", found_components['HISTORYSERVER']) self._assert_component('MAPREDUCE2_CLIENT', 'CLIENT', "1+", found_components['MAPREDUCE2_CLIENT']) def _assert_yarn(self, service): self.assertEqual('YARN', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(3, len(found_components)) self._assert_component('RESOURCEMANAGER', 'MASTER', "1", found_components['RESOURCEMANAGER']) self._assert_component('NODEMANAGER', 'SLAVE', "1+", found_components['NODEMANAGER']) self._assert_component('YARN_CLIENT', 'CLIENT', "1+", found_components['YARN_CLIENT']) def _assert_nagios(self, service): self.assertEqual('NAGIOS', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(1, len(found_components)) self._assert_component('NAGIOS_SERVER', 'MASTER', "1", found_components['NAGIOS_SERVER']) def _assert_ganglia(self, service): self.assertEqual('GANGLIA', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(2, len(found_components)) self._assert_component('GANGLIA_SERVER', 'MASTER', "1", found_components['GANGLIA_SERVER']) self._assert_component('GANGLIA_MONITOR', 'SLAVE', "1+", found_components['GANGLIA_MONITOR']) def _assert_ambari(self, service): self.assertEqual('AMBARI', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(2, len(found_components)) self._assert_component('AMBARI_SERVER', 'MASTER', "1", found_components['AMBARI_SERVER']) self._assert_component('AMBARI_AGENT', 'SLAVE', "1+", found_components['AMBARI_AGENT']) self.assertEqual(1, len(service.users)) user = service.users[0] self.assertEqual('admin', user.name) self.assertEqual('admin', user.password) groups = user.groups self.assertEqual(1, len(groups)) self.assertIn('admin', groups) def _assert_pig(self, service): self.assertEqual('PIG', service.name) self.assertEqual(1, len(service.components)) self.assertEqual('PIG', service.components[0].name) def _assert_hive(self, service): self.assertEqual('HIVE', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(4, len(found_components)) self._assert_component('HIVE_SERVER', 'MASTER', "1", found_components['HIVE_SERVER']) self._assert_component('HIVE_METASTORE', 'MASTER', "1", found_components['HIVE_METASTORE']) self._assert_component('MYSQL_SERVER', 'MASTER', "1", found_components['MYSQL_SERVER']) self._assert_component('HIVE_CLIENT', 'CLIENT', "1+", found_components['HIVE_CLIENT']) def _assert_hcatalog(self, service): self.assertEqual('HCATALOG', service.name) self.assertEqual(1, len(service.components)) self.assertEqual('HCAT', service.components[0].name) def _assert_zookeeper(self, service): self.assertEqual('ZOOKEEPER', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(2, len(found_components)) self._assert_component('ZOOKEEPER_SERVER', 'MASTER', "1+", found_components['ZOOKEEPER_SERVER']) self._assert_component('ZOOKEEPER_CLIENT', 'CLIENT', "1+", found_components['ZOOKEEPER_CLIENT']) def _assert_webhcat(self, service): self.assertEqual('WEBHCAT', service.name) self.assertEqual(1, len(service.components)) self.assertEqual('WEBHCAT_SERVER', service.components[0].name) def _assert_oozie(self, service): self.assertEqual('OOZIE', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(2, len(found_components)) self._assert_component('OOZIE_SERVER', 'MASTER', "1", found_components['OOZIE_SERVER']) self._assert_component('OOZIE_CLIENT', 'CLIENT', "1+", found_components['OOZIE_CLIENT']) def _assert_sqoop(self, service): self.assertEqual('SQOOP', service.name) self.assertEqual(1, len(service.components)) self.assertEqual('SQOOP', service.components[0].name) def _assert_hbase(self, service): self.assertEqual('HBASE', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(3, len(found_components)) self._assert_component('HBASE_MASTER', 'MASTER', "1", found_components['HBASE_MASTER']) self._assert_component('HBASE_REGIONSERVER', 'SLAVE', "1+", found_components['HBASE_REGIONSERVER']) self._assert_component('HBASE_CLIENT', 'CLIENT', "1+", found_components['HBASE_CLIENT']) def _assert_hue(self, service): self.assertEqual('HUE', service.name) found_components = {} for component in service.components: found_components[component.name] = component self.assertEqual(1, len(found_components)) self._assert_component('HUE', 'CLIENT', "1", found_components['HUE']) def _assert_component(self, name, comp_type, cardinality, component): self.assertEqual(name, component.name) self.assertEqual(comp_type, component.type) self.assertEqual(cardinality, component.cardinality) def _assert_configurations(self, configurations): self.assertEqual(16, len(configurations)) self.assertIn('global', configurations) self.assertIn('core-site', configurations) self.assertIn('yarn-site', configurations) self.assertIn('mapred-site', configurations) self.assertIn('hdfs-site', configurations) self.assertIn('ambari', configurations) self.assertIn('webhcat-site', configurations) self.assertIn('hive-site', configurations) self.assertIn('oozie-site', configurations) self.assertIn('hbase-site', configurations) self.assertIn('capacity-scheduler', configurations) self.assertIn('hue-ini', configurations) self.assertIn('hue-core-site', configurations) self.assertIn('hue-hdfs-site', configurations) self.assertIn('hue-webhcat-site', configurations) self.assertIn('hue-oozie-site', configurations) class TestNodeGroup(object): def __init__(self, name, instances, node_processes, count=1): self.name = name self.instances = instances for i in instances: i.node_group = self self.node_processes = node_processes self.count = count self.id = name def storage_paths(self): return [''] class TestUserInputConfig(object): def __init__(self, tag, target, name): self.tag = tag self.applicable_target = target self.name = name
{ "content_hash": "f9fcffe6dda67f7f027f9b596b24cad5", "timestamp": "", "source": "github", "line_count": 1924, "max_line_length": 79, "avg_line_length": 45.816008316008315, "alnum_prop": 0.5488145207033466, "repo_name": "xme1226/sahara", "id": "e00462e534e35b786d634a1b526da8e67d11c179", "size": "88737", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sahara/tests/unit/plugins/hdp/test_clusterspec_hdp2.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3609" }, { "name": "PigLatin", "bytes": "161" }, { "name": "Python", "bytes": "2064261" }, { "name": "Shell", "bytes": "16736" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>微糖</title> <meta name="description" content=""> <link rel="stylesheet" href="/semantic/packaged/css/semantic.css"> <link rel="stylesheet" href="/css/common.css"> <link rel="stylesheet" type="text/css" href="/css/ask.css"> <!-- Le fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/icon/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/icon/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/icon/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="/icon/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="/icon/favicon.ico"> <script src="/lib/jquery.js"></script> <script src="/semantic/packaged/javascript/semantic.js"></script> </head> <body> <% include ./inc_topmenu.html %> <% include ./inc_sidebar.html %> <div class="ui page grid mainpage"> <div class="eleven wide column"> <h4 class="ui dividing header"> <i class="inbox icon"></i>提出新问题 </h4> <div class="ui form"> <div class="field"> <input type="text" class="title" placeholder="标题,用一句话说清你的问题"> </div> <div class="field" style="margin-bottom: 5px;"> <div class="ui icon buttons"> <div class="ui button" title="撤销"><i class="reply mail icon"></i></div> <div class="ui button" title="重做"><i class="forward mail icon"></i></div> </div> <div class="ui icon buttons"> <div class="ui button"><i class="bold icon"></i></div> <div class="ui button"><i class="italic icon"></i></div> </div> <div class="ui icon buttons"> <div class="ui button"><i class="url icon"></i></div> <div class="ui button"><i class="quote left icon"></i></div> <div class="ui button"><i class="code icon"></i></div> <div class="ui button"><i class="photo icon"></i></div> </div> <div class="ui icon buttons"> <div class="ui button"><i class="ordered list icon"></i></div> <div class="ui button"><i class="unordered list icon"></i></div> <div class="ui button"><i class="fullscreen icon"></i></div> </div> <div class="ui icon buttons" style="float: right;"> <div class="ui icon button"> <i class="question icon"></i> </div> </div> </div> <div class="field"> <textarea class="content" style="height:288px;"></textarea> </div> </div> </div> <div class="five wide column"> <h5 class="ui small header"> 提问指南 </h5> <div class="ui bulleted list"> <div class="item">良好的排版,正确使用Markdown语法</div> <div class="item">内容与技术相关,有明确的答案,有代码贴代码,附上已尝试过的解决方案</div> </div> <div class="ui divider"></div> <h5 class="ui header">问题标签(至少1个)</h5> <div class="ui small labels hasAddedList"> </div> <div class="ui small fluid icon input"> <input type="text" placeholder="如: NodeJS"> <i class="inverted blue add icon"></i> </div> <div class="ui segment"> <div class="ui small labels hotTopics"> <div class="ui label">JavaScript</div> <div class="ui label">css</div> <div class="ui label">前端开发</div> <div class="ui label">css</div> <div class="ui label">JavaScript</div> <div class="ui label">JavaScript</div> <div class="ui label">css</div> <div class="ui label">前端开发</div> <div class="ui label">JavaScript</div> <div class="ui label">JavaScript</div> <div class="ui label">css</div> <div class="ui label">前端开发</div> <div class="ui label">JavaScript</div> <div class="ui label">css</div> </div> </div> <div class="ui fluid red button add"> 提交问题 </div> </div> </div> <% include ./inc_gotop.html %> <% include ./inc_footer.html %> <script src="/seajs/sea.js" data-config="/js/config" data-main="/js/ask" ></script> </body> </html>
{ "content_hash": "ded81dbf4ac491666b879c649e42ac15", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 111, "avg_line_length": 40.323076923076925, "alnum_prop": 0.4828309805417779, "repo_name": "silianlinyi/weitang", "id": "d5936b831f2c50ccd2e79cbba6717e6b51f6f8e8", "size": "5440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/ask.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1074024" }, { "name": "JavaScript", "bytes": "1795064" } ], "symlink_target": "" }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dfp.axis.v201505.creativeservice; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.common.lib.utils.Media; import com.google.api.ads.dfp.axis.factory.DfpServices; import com.google.api.ads.dfp.axis.v201505.Creative; import com.google.api.ads.dfp.axis.v201505.CreativeAsset; import com.google.api.ads.dfp.axis.v201505.CreativeServiceInterface; import com.google.api.ads.dfp.axis.v201505.ImageCreative; import com.google.api.ads.dfp.axis.v201505.ImageRedirectCreative; import com.google.api.ads.dfp.axis.v201505.Size; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import java.util.Random; /** * This example creates new creatives. To determine which creatives exist, run * GetAllCreatives.java. * * Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. */ public class CreateCreatives { // Set the ID of the advertiser (company) that all creatives will be assigned // to. private static final String ADVERTISER_ID = "INSERT_ADVERTISER_COMPANY_ID_HERE"; public static void runExample(DfpServices dfpServices, DfpSession session, long advertiserId) throws Exception { // Get the CreativeService. CreativeServiceInterface creativeService = dfpServices.get(session, CreativeServiceInterface.class); // Create creative size. Size size = new Size(); size.setWidth(300); size.setHeight(250); size.setIsAspectRatio(false); // Create an image creative. ImageCreative imageCreative = new ImageCreative(); imageCreative.setName("Image creative #" + new Random().nextInt(Integer.MAX_VALUE)); imageCreative.setAdvertiserId(advertiserId); imageCreative.setDestinationUrl("http://google.com"); imageCreative.setSize(size); // Create image asset. CreativeAsset creativeAsset = new CreativeAsset(); creativeAsset.setFileName("image.jpg"); creativeAsset.setAssetByteArray(Media.getMediaDataFromUrl( "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg")); creativeAsset.setSize(size); imageCreative.setPrimaryImageAsset(creativeAsset); // Create an image redirect creative. ImageRedirectCreative imageRedirectCreative = new ImageRedirectCreative(); imageRedirectCreative.setName( "Image redirect creative #" + new Random().nextInt(Integer.MAX_VALUE)); imageRedirectCreative.setAdvertiserId(advertiserId); imageRedirectCreative.setDestinationUrl("http://google.com"); imageRedirectCreative.setImageUrl( "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg"); imageRedirectCreative.setSize(size); // Create the creatives on the server. Creative[] creatives = creativeService.createCreatives(new Creative[] {imageCreative, imageRedirectCreative}); for (Creative createdCreative : creatives) { System.out.printf("A creative with ID %d, name '%s', and type '%s'" + " was created and can be previewed at: %s%n", createdCreative.getId(), createdCreative.getName(), createdCreative.getClass().getSimpleName(), createdCreative.getPreviewUrl()); } } public static void main(String[] args) throws Exception { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.DFP) .fromFile() .build() .generateCredential(); // Construct a DfpSession. DfpSession session = new DfpSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build(); DfpServices dfpServices = new DfpServices(); runExample(dfpServices, session, Long.parseLong(ADVERTISER_ID)); } }
{ "content_hash": "7251e777a5f537a9be68ab6750a5e380", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 95, "avg_line_length": 40.17857142857143, "alnum_prop": 0.7366666666666667, "repo_name": "gawkermedia/googleads-java-lib", "id": "a450867bbef179e6355cc4c6f5e2a6196a2d90c5", "size": "4500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/dfp_axis/src/main/java/dfp/axis/v201505/creativeservice/CreateCreatives.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "107468648" } ], "symlink_target": "" }
autoclosing... <script type="text/javascript"> var retval="$val"; //alert("set val"); var ope = this.window.opener; //alert(ope); var elem = ope.document.getElementById("$var"); //alert("var: $var ; elem:"+elem); if (elem) { elem.value=retval; // set original form dirty and close window var origFormId = elem.form.getAttribute("id"); ope.setFormDirty(origFormId); } this.window.close(); // close first, safari bug will not close window otherwhise </script>
{ "content_hash": "607545caebb957ff0672d6d6a0c29c9e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 29.75, "alnum_prop": 0.6827731092436975, "repo_name": "srinivasiyerb/Scholst", "id": "a201857933624598d6d6391320afcb348571547f", "size": "476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target/Scholastic/WEB-INF/classes/org/olat/course/groupsandrights/ui/_content/closing.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2300074" }, { "name": "Java", "bytes": "20346154" }, { "name": "JavaScript", "bytes": "33958863" }, { "name": "Perl", "bytes": "4117" }, { "name": "Shell", "bytes": "42399" }, { "name": "XSLT", "bytes": "172058" } ], "symlink_target": "" }
class Nghttp2 < Formula desc "HTTP/2 C Library" homepage "https://nghttp2.org/" url "https://github.com/nghttp2/nghttp2/releases/download/v1.15.0/nghttp2-1.15.0.tar.xz" sha256 "317afbef79eec624577d006ea7111cf978d2c88e999a6f336c83b99f924b5e4a" bottle do sha256 "a6e7ef94226b0f2a52657f1713b95df76979f3d72e569b23bb487a4919811776" => :sierra sha256 "e9ff28814a9c850c3d0a7c58a5d1738eb82d57716230aacb0b3c455f84ea5b1e" => :el_capitan sha256 "a734d9eb510f1c73fda1ec2396915a9e7c68ac5fde7a7e7753fe33364092d7a9" => :yosemite end head do url "https://github.com/nghttp2/nghttp2.git" depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build end option "with-examples", "Compile and install example programs" option "without-docs", "Don't build man pages" option "with-python3", "Build python3 bindings" depends_on :python3 => :optional depends_on "sphinx-doc" => :build if build.with? "docs" depends_on "libxml2" if MacOS.version <= :lion depends_on "pkg-config" => :build depends_on "cunit" => :build depends_on "libev" depends_on "openssl" depends_on "libevent" depends_on "jansson" depends_on "boost" depends_on "spdylay" depends_on "jemalloc" => :recommended resource "Cython" do url "https://pypi.python.org/packages/c6/fe/97319581905de40f1be7015a0ea1bd336a756f6249914b148a17eefa75dc/Cython-0.24.1.tar.gz" sha256 "84808fda00508757928e1feadcf41c9f78e9a9b7167b6649ab0933b76f75e7b9" end # https://github.com/tatsuhiro-t/nghttp2/issues/125 # Upstream requested the issue closed and for users to use gcc instead. # Given this will actually build with Clang with cxx11, just use that. needs :cxx11 def install ENV.cxx11 args = %W[ --prefix=#{prefix} --disable-silent-rules --enable-app --with-boost=#{Formula["boost"].opt_prefix} --enable-asio-lib --with-spdylay --disable-python-bindings ] args << "--enable-examples" if build.with? "examples" args << "--with-xml-prefix=/usr" if MacOS.version > :lion args << "--without-jemalloc" if build.without? "jemalloc" system "autoreconf", "-ivf" if build.head? system "./configure", *args system "make" system "make", "check" # Currently this is not installed by the make install stage. if build.with? "docs" system "make", "html" doc.install Dir["doc/manual/html/*"] end system "make", "install" libexec.install "examples" if build.with? "examples" if build.with? "python3" pyver = Language::Python.major_minor_version "python3" ENV["PYTHONPATH"] = cythonpath = buildpath/"cython/lib/python#{pyver}/site-packages" cythonpath.mkpath ENV.prepend_create_path "PYTHONPATH", lib/"python#{pyver}/site-packages" resource("Cython").stage do system "python3", *Language::Python.setup_install_args(buildpath/"cython") end cd "python" do system buildpath/"cython/bin/cython", "nghttp2.pyx" system "python3", *Language::Python.setup_install_args(prefix) end end end test do system bin/"nghttp", "-nv", "https://nghttp2.org" end end
{ "content_hash": "d0e99abde3fc60336912743f90aca168", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 130, "avg_line_length": 32.37373737373738, "alnum_prop": 0.6895475819032761, "repo_name": "lasote/homebrew-core", "id": "94a1a0047779081b46bd6a89f9615f62ef19c1e6", "size": "3205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Formula/nghttp2.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Perl", "bytes": "628" }, { "name": "Ruby", "bytes": "5834139" } ], "symlink_target": "" }
@implementation MSContentListCell @synthesize isTitleTableViewCell; @synthesize indexPath; - (void)update:(id<MSCellModel>)cellModel indexPath:(NSIndexPath *)aIndexPath { self.indexPath = aIndexPath; } - (void)update:(id<MSCellModel>)cellModel { } - (void)awakeFromNib { // Initialization code [super awakeFromNib]; self.isTitleTableViewCell = NO; UIView *bgView = [[UIView alloc] initWithFrame:self.bounds]; bgView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth; bgView.backgroundColor = RGB(0xff, 0xff, 0xff); self.backgroundView = bgView; UIView *view = [[UIView alloc] initWithFrame:self.bounds]; view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; view.backgroundColor = RGB(0xfa, 0xfa, 0xfa); self.selectedBackgroundView = view; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { if(self.selected == selected) return; [super setSelected:selected animated:animated]; [[NSNotificationCenter defaultCenter] postNotificationName:MSScrollableListCellSelectedNotification object:self]; } - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { if(self.highlighted == highlighted) return; [super setHighlighted:highlighted animated:animated]; [[NSNotificationCenter defaultCenter] postNotificationName:MSScrollableListCellHighlightedNotification object:self]; } @end
{ "content_hash": "0f1b84e7670780113d668956ae93bc07", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 120, "avg_line_length": 30.102040816326532, "alnum_prop": 0.7566101694915254, "repo_name": "EmoneyCN/EMSpeed", "id": "67fc5ad21396549844c063857668ed965aa2fd0b", "size": "1665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UI/src/scrollableListController/view/MSContentListCell.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "23965" }, { "name": "Objective-C", "bytes": "1260288" }, { "name": "Ruby", "bytes": "6656" } ], "symlink_target": "" }
<?php namespace iriki_tests\engine\database\mongodb; class otherTest extends \PHPUnit\Framework\TestCase { public function test_isMongoId_failure() { $false_mongo_id = 'false mongo id'; $status = \iriki\engine\mongodb::isMongoId($false_mongo_id); //assert $this->assertNotEquals(true, $status); } public function test_isMongoId_success() { $true_mongo_id = '596cbd52565bb550080041b8'; $status = \iriki\engine\mongodb::isMongoId($true_mongo_id); //assert $this->assertEquals(true, $status); } public function test_doInitialise_failure() { $status = \iriki\engine\mongodb::doInitialise( null ); //assert $this->assertEquals(null, $status); } //session token check: auth, remember, ip? //enforce ids //de enforce } ?>
{ "content_hash": "bf8fc0b622ceef6aa349c1380322dd8b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 68, "avg_line_length": 19.666666666666668, "alnum_prop": 0.5988700564971752, "repo_name": "stigwue/iriki", "id": "80db17b798fa7b58788f63b339ad86e190c98f75", "size": "885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/tests/iriki/database/mongodb/otherTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "369368" } ], "symlink_target": "" }
# [](#EasyIcon) *(Easy)*: Change Calculator Write A function that takes an amount of money, rounds it to the nearest penny and then tells you the *minimum* number of coins needed to equal that amount of money. For Example: "4.17" would print out: Quarters: 16 Dimes: 1 Nickels: 1 Pennies: 2 *Author: nanermaner* # Formal Inputs & Outputs ## Input Description Your Function should accept a decimal number (which may or may not have an actual decimal, in which you can assume it is an integer representing dollars, not cents). Your function should round this number to the nearest hundredth. ## Output Description Print the minimum number of coins needed. The four coins used should be 25 cent, 10 cent, 5 cent and 1 cent. It should be in the following format: Quarters: <integer> Dimes: <integer> Nickels: <integer> Pennies: <integer> # Sample Inputs & Outputs ## Sample Input 1.23 ## Sample Output Quarters: 4 Dimes: 2 Nickels: 0 Pennies: 3 # Challenge Input 10.24 0.99 5 00.06 ## Challenge Input Solution Not yet posted # Note This program may be different for international users, my examples used quarters, nickels, dimes and pennies. Feel free to use generic terms like "10 cent coins" or any other unit of currency you are more familiar with. * Bonus: Only print coins that are used at least once in the solution.
{ "content_hash": "191b2ed7f317e0787a1fc069993665a8", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 230, "avg_line_length": 33.41860465116279, "alnum_prop": 0.7021572720946416, "repo_name": "FreddieV4/DailyProgrammerChallenges", "id": "9a96e737a1db000ff13b1734c9df2e5c60802c7f", "size": "1437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Easy Challenges/Challenge 0119 Easy - Change Calculator/challenge_text.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "184826" }, { "name": "C++", "bytes": "20049" }, { "name": "Common Lisp", "bytes": "567" }, { "name": "Crystal", "bytes": "81" }, { "name": "D", "bytes": "2372" }, { "name": "Elixir", "bytes": "621" }, { "name": "Go", "bytes": "1799" }, { "name": "Java", "bytes": "49443" }, { "name": "JavaScript", "bytes": "20193" }, { "name": "Matlab", "bytes": "2612" }, { "name": "Perl", "bytes": "6698" }, { "name": "Python", "bytes": "76412" }, { "name": "R", "bytes": "1011" }, { "name": "Ruby", "bytes": "7239" }, { "name": "Rust", "bytes": "3580" }, { "name": "Tcl", "bytes": "977" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\views_ui\Tests\OverrideDisplaysTest. */ namespace Drupal\views_ui\Tests; /** * Tests that displays can be correctly overridden via the user interface. */ class OverrideDisplaysTest extends UITestBase { public static function getInfo() { return array( 'name' => 'Overridden displays functionality', 'description' => 'Test that displays can be correctly overridden via the user interface.', 'group' => 'Views UI', ); } /** * Tests that displays can be overridden via the UI. */ function testOverrideDisplays() { // Create a basic view that shows all content, with a page and a block // display. $view['label'] = $this->randomName(16); $view['id'] = strtolower($this->randomName(16)); $view['page[create]'] = 1; $view['page[path]'] = $this->randomName(16); $view['block[create]'] = 1; $view_path = $view['page[path]']; $this->drupalPost('admin/structure/views/add', $view, t('Save and edit')); // Configure its title. Since the page and block both started off with the // same (empty) title in the views wizard, we expect the wizard to have set // things up so that they both inherit from the default display, and we // therefore only need to change that to have it take effect for both. $edit = array(); $edit['title'] = $original_title = $this->randomName(16); $edit['override[dropdown]'] = 'default'; $this->drupalPost("admin/structure/views/nojs/display/{$view['id']}/page_1/title", $edit, t('Apply')); $this->drupalPost("admin/structure/views/view/{$view['id']}/edit/page_1", array(), t('Save')); // Add a node that will appear in the view, so that the block will actually // be displayed. $this->drupalCreateNode(); // Make sure the title appears in the page. $this->drupalGet($view_path); $this->assertResponse(200); $this->assertText($original_title); // Confirm that the view block is available in the block administration UI. $this->drupalGet('admin/structure/block/list/' . \Drupal::config('system.theme')->get('default')); $this->assertText('View: ' . $view['label']); // Place the block. $this->drupalPlaceBlock("views_block:{$view['id']}-block_1"); // Make sure the title appears in the block. $this->drupalGet(''); $this->assertText($original_title); // Change the title for the page display only, and make sure that the // original title still appears on the page. $edit = array(); $edit['title'] = $new_title = $this->randomName(16); $edit['override[dropdown]'] = 'page_1'; $this->drupalPost("admin/structure/views/nojs/display/{$view['id']}/page_1/title", $edit, t('Apply')); $this->drupalPost("admin/structure/views/view/{$view['id']}/edit/page_1", array(), t('Save')); $this->drupalGet($view_path); $this->assertResponse(200); $this->assertText($new_title); $this->assertText($original_title); } /** * Tests that the wizard correctly sets up default and overridden displays. */ function testWizardMixedDefaultOverriddenDisplays() { // Create a basic view with a page, block, and feed. Give the page and feed // identical titles, but give the block a different one, so we expect the // page and feed to inherit their titles from the default display, but the // block to override it. $view['label'] = $this->randomName(16); $view['id'] = strtolower($this->randomName(16)); $view['page[create]'] = 1; $view['page[title]'] = $this->randomName(16); $view['page[path]'] = $this->randomName(16); $view['page[feed]'] = 1; $view['page[feed_properties][path]'] = $this->randomName(16); $view['block[create]'] = 1; $view['block[title]'] = $this->randomName(16); $this->drupalPost('admin/structure/views/add', $view, t('Save and edit')); // Add a node that will appear in the view, so that the block will actually // be displayed. $this->drupalCreateNode(); // Make sure that the feed, page and block all start off with the correct // titles. $this->drupalGet($view['page[path]']); $this->assertResponse(200); $this->assertText($view['page[title]']); $this->assertNoText($view['block[title]']); $this->drupalGet($view['page[feed_properties][path]']); $this->assertResponse(200); $this->assertText($view['page[title]']); $this->assertNoText($view['block[title]']); // Confirm that the block is available in the block administration UI. $this->drupalGet('admin/structure/block/list/' . \Drupal::config('system.theme')->get('default')); $this->assertText('View: ' . $view['label']); // Put the block into the first sidebar region, and make sure it will not // display on the view's page display (since we will be searching for the // presence/absence of the view's title in both the page and the block). $this->drupalPlaceBlock("views_block:{$view['id']}-block_1", array( 'visibility' => array( 'path' => array( 'visibility' => BLOCK_VISIBILITY_NOTLISTED, 'pages' => $view['page[path]'], ), ), )); $this->drupalGet(''); $this->assertText($view['block[title]']); $this->assertNoText($view['page[title]']); // Edit the page and change the title. This should automatically change // the feed's title also, but not the block. $edit = array(); $edit['title'] = $new_default_title = $this->randomName(16); $this->drupalPost("admin/structure/views/nojs/display/{$view['id']}/page_1/title", $edit, t('Apply')); $this->drupalPost("admin/structure/views/view/{$view['id']}/edit/page_1", array(), t('Save')); $this->drupalGet($view['page[path]']); $this->assertResponse(200); $this->assertText($new_default_title); $this->assertNoText($view['page[title]']); $this->assertNoText($view['block[title]']); $this->drupalGet($view['page[feed_properties][path]']); $this->assertResponse(200); $this->assertText($new_default_title); $this->assertNoText($view['page[title]']); $this->assertNoText($view['block[title]']); $this->drupalGet(''); $this->assertNoText($new_default_title); $this->assertNoText($view['page[title]']); $this->assertText($view['block[title]']); // Edit the block and change the title. This should automatically change // the block title only, and leave the defaults alone. $edit = array(); $edit['title'] = $new_block_title = $this->randomName(16); $this->drupalPost("admin/structure/views/nojs/display/{$view['id']}/block_1/title", $edit, t('Apply')); $this->drupalPost("admin/structure/views/view/{$view['id']}/edit/block_1", array(), t('Save')); $this->drupalGet($view['page[path]']); $this->assertResponse(200); $this->assertText($new_default_title); $this->drupalGet($view['page[feed_properties][path]']); $this->assertResponse(200); $this->assertText($new_default_title); $this->assertNoText($new_block_title); $this->drupalGet(''); $this->assertText($new_block_title); $this->assertNoText($view['block[title]']); } /** * Tests that the revert to all displays select-option works as expected. */ function testRevertAllDisplays() { // Create a basic view with a page, block. // Because there is both a title on page and block we expect the title on // the block be overriden. $view['label'] = $this->randomName(16); $view['id'] = strtolower($this->randomName(16)); $view['page[create]'] = 1; $view['page[title]'] = $this->randomName(16); $view['page[path]'] = $this->randomName(16); $view['block[create]'] = 1; $view['block[title]'] = $this->randomName(16); $this->drupalPost('admin/structure/views/add', $view, t('Save and edit')); // Revert the title of the block back to the default ones, but submit some // new values to be sure that the new value is not stored. $edit = array(); $edit['title'] = $new_block_title = $this->randomName(); $edit['override[dropdown]'] = 'default_revert'; $this->drupalPost("admin/structure/views/nojs/display/{$view['id']}/block_1/title", $edit, t('Apply')); $this->drupalPost("admin/structure/views/view/{$view['id']}/edit/block_1", array(), t('Save')); $this->assertText($view['page[title]']); } }
{ "content_hash": "ebde70eff51db57e005f5aa7d143d3a3", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 107, "avg_line_length": 41.865, "alnum_prop": 0.6380031052191568, "repo_name": "nickopris/musicapp", "id": "ee265060ec25ef189375676e0df75b4f347d674d", "size": "8373", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/core/modules/views_ui/lib/Drupal/views_ui/Tests/OverrideDisplaysTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "263467" }, { "name": "JavaScript", "bytes": "665433" }, { "name": "PHP", "bytes": "14580545" }, { "name": "Shell", "bytes": "61500" } ], "symlink_target": "" }
layout: page title: About Me excerpt: #"So Simple is a responsive Jekyll theme for your words and images." modified: 2016-11-15 image: feature: #so-simple-sample-image-7.jpg credit: #WeGraphics creditlink: #http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/ --- Welcome! My name is Andrea Everett, and I am a data scientist and political scientist. I use this blog to present results and discussion of my data science projects. Please enjoy!
{ "content_hash": "8f954c812b11d3255febf6951bca5178", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 182, "avg_line_length": 42.90909090909091, "alnum_prop": 0.7669491525423728, "repo_name": "andreaeverett/andreaeverett.github.io", "id": "f6067f0e0b1a6b68555f4ccfef2ac875b73bb924", "size": "476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about/index.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "50701" }, { "name": "HTML", "bytes": "18924" }, { "name": "JavaScript", "bytes": "78211" } ], "symlink_target": "" }
""" This file provides fallback data for info attributes that are required for building OTFs. There are two main functions that are important: * :func:`~getAttrWithFallback` * :func:`~preflightInfo` There are a set of other functions that are used internally for synthesizing values for specific attributes. These can be used externally as well. """ import time import unicodedata from fontTools.misc.textTools import binary2num from fontTools.misc.arrayTools import unionRect import ufoLib try: set except NameError: from sets import Set as set # ----------------- # Special Fallbacks # ----------------- # generic def styleMapFamilyNameFallback(info): """ Fallback to *openTypeNamePreferredFamilyName openTypeNamePreferredSubfamilyName*. """ familyName = getAttrWithFallback(info, "openTypeNamePreferredFamilyName") styleName = getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName") if styleName is None: styleName = u"" return (familyName + u" " + styleName).strip() # head def dateStringForNow(): year, month, day, hour, minute, second, weekDay, yearDay, isDST = time.localtime() year = str(year) month = str(month).zfill(2) day = str(day).zfill(2) hour = str(hour).zfill(2) minute = str(minute).zfill(2) second = str(second).zfill(2) return "%s/%s/%s %s:%s:%s" % (year, month, day, hour, minute, second) def openTypeHeadCreatedFallback(info): """ Fallback to now. """ return dateStringForNow() # hhea def openTypeHheaAscenderFallback(info): """ Fallback to *unitsPerEm + descender*. """ return info.unitsPerEm + info.descender def openTypeHheaDescenderFallback(info): """ Fallback to *descender*. """ return info.descender # name def openTypeNameVersionFallback(info): """ Fallback to *versionMajor.versionMinor* in the form 0.000. """ versionMajor = getAttrWithFallback(info, "versionMajor") versionMinor = getAttrWithFallback(info, "versionMinor") return "%d.%s" % (versionMajor, str(versionMinor).zfill(3)) def openTypeNameUniqueIDFallback(info): """ Fallback to *openTypeNameVersion;openTypeOS2VendorID;styleMapFamilyName styleMapStyleName*. """ version = getAttrWithFallback(info, "openTypeNameVersion") vendor = getAttrWithFallback(info, "openTypeOS2VendorID") familyName = getAttrWithFallback(info, "styleMapFamilyName") styleName = getAttrWithFallback(info, "styleMapStyleName").title() return u"%s;%s;%s %s" % (version, vendor, familyName, styleName) def openTypeNamePreferredFamilyNameFallback(info): """ Fallback to *familyName*. """ return info.familyName def openTypeNamePreferredSubfamilyNameFallback(info): """ Fallback to *styleName*. """ return info.styleName def openTypeNameCompatibleFullNameFallback(info): """ Fallback to *styleMapFamilyName styleMapStyleName*. If *styleMapStyleName* is *regular* this will not add the style name. """ familyName = getAttrWithFallback(info, "styleMapFamilyName") styleMapStyleName = getAttrWithFallback(info, "styleMapStyleName") if styleMapStyleName != "regular": familyName += " " + styleMapStyleName.title() return familyName def openTypeNameWWSFamilyNameFallback(info): # not yet supported return None def openTypeNameWWSSubfamilyNameFallback(info): # not yet supported return None # OS/2 def openTypeOS2TypoAscenderFallback(info): """ Fallback to *unitsPerEm + descender*. """ return info.unitsPerEm + info.descender def openTypeOS2TypoDescenderFallback(info): """ Fallback to *descender*. """ return info.descender def openTypeOS2WinAscentFallback(info): """ Fallback to the maximum y value of the font's bounding box. If that is not available, fallback to *ascender*. If the maximum y value is negative, fallback to 0 (zero). """ font = info.getParent() if font is None: yMax = getAttrWithFallback(info, "ascender") else: bounds = getFontBounds(font) xMin, yMin, xMax, yMax = bounds if yMax < 0: return 0 return yMax def openTypeOS2WinDescentFallback(info): """ Fallback to the minimum y value of the font's bounding box. If that is not available, fallback to *descender*. If the mininum y value is positive, fallback to 0 (zero). """ font = info.getParent() if font is None: return abs(getAttrWithFallback(info, "descender")) bounds = getFontBounds(font) if bounds is None: return abs(getAttrWithFallback(info, "descender")) xMin, yMin, xMax, yMax = bounds if yMin > 0: return 0 return abs(yMin) # postscript _postscriptFontNameExceptions = set("[](){}<>/%") _postscriptFontNameAllowed = set([unichr(i) for i in xrange(33, 137)]) def normalizeStringForPostscript(s, allowSpaces=True): s = unicode(s) normalized = [] for c in s: if c == " " and not allowSpaces: continue if c in _postscriptFontNameExceptions: continue if c not in _postscriptFontNameAllowed: c = unicodedata.normalize("NFKD", c).encode("ascii", "ignore") normalized.append(c) return "".join(normalized) def normalizeNameForPostscript(name): return normalizeStringForPostscript(name, allowSpaces=False) def postscriptFontNameFallback(info): """ Fallback to a string containing only valid characters as defined in the specification. This will draw from *openTypeNamePreferredFamilyName* and *openTypeNamePreferredSubfamilyName*. """ name = u"%s-%s" % (getAttrWithFallback(info, "openTypeNamePreferredFamilyName"), getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName")) return normalizeNameForPostscript(name) def postscriptFullNameFallback(info): """ Fallback to *openTypeNamePreferredFamilyName openTypeNamePreferredSubfamilyName*. """ name = u"%s %s" % (getAttrWithFallback(info, "openTypeNamePreferredFamilyName"), getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName")) return normalizeNameForPostscript(name) def postscriptSlantAngleFallback(info): """ Fallback to *italicAngle*. """ return getAttrWithFallback(info, "italicAngle") _postscriptWeightNameOptions = { 100 : "Thin", 200 : "Extra-light", 300 : "Light", 400 : "Normal", 500 : "Medium", 600 : "Semi-bold", 700 : "Bold", 800 : "Extra-bold", 900 : "Black" } def postscriptWeightNameFallback(info): """ Fallback to the closest match of the *openTypeOS2WeightClass* in this table: === =========== 100 Thin 200 Extra-light 300 Light 400 Normal 500 Medium 600 Semi-bold 700 Bold 800 Extra-bold 900 Black === =========== """ value = getAttrWithFallback(info, "openTypeOS2WeightClass") value = int(round(value * .01) * 100) if value < 100: value = 100 elif value > 900: value = 900 name = _postscriptWeightNameOptions[value] return name def postscriptBlueScaleFallback(info): """ Fallback to a calculated value: 3/(4 * *maxZoneHeight*) where *maxZoneHeight* is the tallest zone from *postscriptBlueValues* and *postscriptOtherBlues*. If zones are not set, return 0.039625. """ blues = getAttrWithFallback(info, "postscriptBlueValues") otherBlues = getAttrWithFallback(info, "postscriptOtherBlues") maxZoneHeight = 0 blueScale = 0.039625 if blues: assert len(blues) % 2 == 0 for x, y in zip(blues[:-1:2], blues[1::2]): maxZoneHeight = max(maxZoneHeight, abs(y-x)) if otherBlues: assert len(otherBlues) % 2 == 0 for x, y in zip(otherBlues[:-1:2], otherBlues[1::2]): maxZoneHeight = max(maxZoneHeight, abs(y-x)) if maxZoneHeight != 0: blueScale = 3/(4*maxZoneHeight) return blueScale # -------------- # Attribute Maps # -------------- staticFallbackData = dict( styleMapStyleName="regular", versionMajor=0, versionMinor=0, copyright=None, trademark=None, italicAngle=0, # not needed year=None, note=None, openTypeHeadLowestRecPPEM=6, openTypeHeadFlags=[0, 1], openTypeHheaLineGap=200, openTypeHheaCaretSlopeRise=1, openTypeHheaCaretSlopeRun=0, openTypeHheaCaretOffset=0, openTypeNameDesigner=None, openTypeNameDesignerURL=None, openTypeNameManufacturer=None, openTypeNameManufacturerURL=None, openTypeNameLicense=None, openTypeNameLicenseURL=None, openTypeNameDescription=None, openTypeNameSampleText=None, openTypeOS2WidthClass=5, openTypeOS2WeightClass=400, openTypeOS2Selection=[], openTypeOS2VendorID="NONE", openTypeOS2Panose=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], openTypeOS2FamilyClass=[0, 0], openTypeOS2UnicodeRanges=[], openTypeOS2CodePageRanges=[], openTypeOS2TypoLineGap=200, openTypeOS2Type=[2], # let the FDK fallback on these openTypeOS2SubscriptXSize=None, openTypeOS2SubscriptYSize=None, openTypeOS2SubscriptXOffset=None, openTypeOS2SubscriptYOffset=None, openTypeOS2SuperscriptXSize=None, openTypeOS2SuperscriptYSize=None, openTypeOS2SuperscriptXOffset=None, openTypeOS2SuperscriptYOffset=None, openTypeOS2StrikeoutSize=None, openTypeOS2StrikeoutPosition=None, # fallback to None on these # as the user should be in # complete control openTypeVheaVertTypoAscender=None, openTypeVheaVertTypoDescender=None, openTypeVheaVertTypoLineGap=None, openTypeVheaCaretSlopeRise=None, openTypeVheaCaretSlopeRun=None, openTypeVheaCaretOffset=None, postscriptUniqueID=None, postscriptUnderlineThickness=None, postscriptUnderlinePosition=None, postscriptIsFixedPitch=False, postscriptBlueValues=[], postscriptOtherBlues=[], postscriptFamilyBlues=[], postscriptFamilyOtherBlues=[], postscriptStemSnapH=[], postscriptStemSnapV=[], postscriptBlueFuzz=0, postscriptBlueShift=7, postscriptForceBold=False, postscriptDefaultWidthX=200, postscriptNominalWidthX=0, # not used in OTF postscriptDefaultCharacter=None, postscriptWindowsCharacterSet=None, # not used in OTF macintoshFONDFamilyID=None, macintoshFONDName=None ) specialFallbacks = dict( styleMapFamilyName=styleMapFamilyNameFallback, openTypeHeadCreated=openTypeHeadCreatedFallback, openTypeHheaAscender=openTypeHheaAscenderFallback, openTypeHheaDescender=openTypeHheaDescenderFallback, openTypeNameVersion=openTypeNameVersionFallback, openTypeNameUniqueID=openTypeNameUniqueIDFallback, openTypeNamePreferredFamilyName=openTypeNamePreferredFamilyNameFallback, openTypeNamePreferredSubfamilyName=openTypeNamePreferredSubfamilyNameFallback, openTypeNameCompatibleFullName=openTypeNameCompatibleFullNameFallback, openTypeNameWWSFamilyName=openTypeNameWWSFamilyNameFallback, openTypeNameWWSSubfamilyName=openTypeNameWWSSubfamilyNameFallback, openTypeOS2TypoAscender=openTypeOS2TypoAscenderFallback, openTypeOS2TypoDescender=openTypeOS2TypoDescenderFallback, openTypeOS2WinAscent=openTypeOS2WinAscentFallback, openTypeOS2WinDescent=openTypeOS2WinDescentFallback, postscriptFontName=postscriptFontNameFallback, postscriptFullName=postscriptFullNameFallback, postscriptSlantAngle=postscriptSlantAngleFallback, postscriptWeightName=postscriptWeightNameFallback, postscriptBlueScale=postscriptBlueScaleFallback ) requiredAttributes = set(ufoLib.fontInfoAttributesVersion2) - (set(staticFallbackData.keys()) | set(specialFallbacks.keys())) recommendedAttributes = set([ "styleMapFamilyName", "versionMajor", "versionMinor", "copyright", "trademark", "openTypeHeadCreated", "openTypeNameDesigner", "openTypeNameDesignerURL", "openTypeNameManufacturer", "openTypeNameManufacturerURL", "openTypeNameLicense", "openTypeNameLicenseURL", "openTypeNameDescription", "openTypeNameSampleText", "openTypeOS2WidthClass", "openTypeOS2WeightClass", "openTypeOS2VendorID", "openTypeOS2Panose", "openTypeOS2FamilyClass", "openTypeOS2UnicodeRanges", "openTypeOS2CodePageRanges", "openTypeOS2TypoLineGap", "openTypeOS2Type", "postscriptBlueValues", "postscriptOtherBlues", "postscriptFamilyBlues", "postscriptFamilyOtherBlues", "postscriptStemSnapH", "postscriptStemSnapV" ]) # ------------ # Main Methods # ------------ def getAttrWithFallback(info, attr): """ Get the value for *attr* from the *info* object. If the object does not have the attribute or the value for the atribute is None, this will either get a value from a predefined set of attributes or it will synthesize a value from the available data. """ if hasattr(info, attr) and getattr(info, attr) is not None: value = getattr(info, attr) else: if attr in specialFallbacks: value = specialFallbacks[attr](info) else: value = staticFallbackData[attr] return value def preflightInfo(info): """ Returns a dict containing two items. The value for each item will be a list of info attribute names. ================== === missingRequired Required data that is missing. missingRecommended Recommended data that is missing. ================== === """ missingRequired = set() missingRecommended = set() for attr in requiredAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRequired.add(attr) for attr in recommendedAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRecommended.add(attr) return dict(missingRequired=missingRequired, missingRecommended=missingRecommended) def getFontBounds(font): """ Get a tuple of (xMin, yMin, xMax, yMax) for all glyphs in the given *font*. """ rect = None # defcon if hasattr(font, "bounds"): rect = font.bounds # others else: for glyph in font: # robofab if hasattr(glyph,"box"): bounds = glyph.box # others else: bounds = glyph.bounds if rect is None: rect = bounds continue if rect is not None and bounds is not None: rect = unionRect(rect, bounds) if rect is None: rect = (0, 0, 0, 0) return rect # ----------------- # Low Level Support # ----------------- # these should not be used outside of this package def intListToNum(intList, start, length): all = [] bin = "" for i in range(start, start+length): if i in intList: b = "1" else: b = "0" bin = b + bin if not (i + 1) % 8: all.append(bin) bin = "" if bin: all.append(bin) all.reverse() all = " ".join(all) return binary2num(all) def dateStringToTimeValue(date): try: t = time.strptime(date, "%Y/%m/%d %H:%M:%S") return long(time.mktime(t)) except OverflowError: return 0L # ---- # Test # ---- class _TestInfoObject(object): def __init__(self): self.familyName = "Family Name" self.styleName = "Style Name" self.unitsPerEm = 1000 self.descender = -250 self.xHeight = 450 self.capHeight = 600 self.ascender = 650 self.bounds = (0, -225, 100, 755) def getParent(self): return self def _test(): """ >>> info = _TestInfoObject() >>> getAttrWithFallback(info, "familyName") 'Family Name' >>> getAttrWithFallback(info, "styleName") 'Style Name' >>> getAttrWithFallback(info, "styleMapFamilyName") u'Family Name Style Name' >>> info.styleMapFamilyName = "Style Map Family Name" >>> getAttrWithFallback(info, "styleMapFamilyName") 'Style Map Family Name' >>> getAttrWithFallback(info, "openTypeNamePreferredFamilyName") 'Family Name' >>> getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName") 'Style Name' >>> getAttrWithFallback(info, "openTypeNameCompatibleFullName") 'Style Map Family Name' >>> getAttrWithFallback(info, "openTypeHheaAscender") 750 >>> getAttrWithFallback(info, "openTypeHheaDescender") -250 >>> getAttrWithFallback(info, "openTypeNameVersion") '0.000' >>> info.versionMinor = 1 >>> info.versionMajor = 1 >>> getAttrWithFallback(info, "openTypeNameVersion") '1.001' >>> getAttrWithFallback(info, "openTypeNameUniqueID") u'1.001;NONE;Style Map Family Name Regular' >>> getAttrWithFallback(info, "openTypeOS2TypoAscender") 750 >>> getAttrWithFallback(info, "openTypeOS2TypoDescender") -250 >>> getAttrWithFallback(info, "openTypeOS2WinAscent") 755 >>> getAttrWithFallback(info, "openTypeOS2WinDescent") 225 >>> getAttrWithFallback(info, "postscriptSlantAngle") 0 >>> getAttrWithFallback(info, "postscriptWeightName") 'Normal' """ if __name__ == "__main__": import doctest doctest.testmod()
{ "content_hash": "6c27f5965b358c978b2e4c688e70de27", "timestamp": "", "source": "github", "line_count": 593, "max_line_length": 149, "avg_line_length": 29.325463743676224, "alnum_prop": 0.6803910293271995, "repo_name": "benkiel/ufo2fdk", "id": "88032ba1d96418db8f215f1c0382709596d82765", "size": "17390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lib/ufo2fdk/fontInfoData.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "128530" } ], "symlink_target": "" }
{extend name="public/content" /} {block name="myBeforeStyle"} <link href="__ROOT__/public/static/admin/css/plugins/iCheck/custom.css" rel="stylesheet"> <link href="__ROOT__/public/static/admin/css/other.css" rel="stylesheet"> {/block} {block name="content"} <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>区域添加 <small></small></h5> </div> <div class="ibox-content"> <form method="post" class="form-horizontal" action="{:url('insert')}"> <div class="form-group"> <label class="col-sm-2 control-label">标题 *</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" required> <span class="help-block m-b-none"></span> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">选择地区 *</label> <div class="col-sm-10 list_range"> <fieldset class="city_china_val"> <select class="province other" name="province" data-first-title="选择省"> <option value="">请选择</option> </select> <select class="city" name="city" data-first-title="选择市"> <option value="">请选择</option> </select> <select class="area" name="area" data-first-title="选择地区"> <option value="">请选择</option> </select> </fieldset> <button class="btn btn-info add_range" type="button"><i class="fa fa-plus"></i> 添加范围</button> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">备注</label> <div class="col-sm-10"> <input type="text" class="form-control" name="remark"> <span class="help-block m-b-none"></span> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-2"> <input type="hidden" name="provinceVal" value=""> <input type="hidden" name="cityVal" value=""> <input type="hidden" name="areaVal" value=""> <button class="btn btn-primary" type="submit">保存内容</button>&nbsp;&nbsp; <button class="btn btn-warning" type="reset">重置内容</button>&nbsp;&nbsp; <button class="btn btn-primary btn_url" type="button" data-url="{:url('index')}"> <i class="fa fa-level-up"></i>&nbsp;&nbsp;<span class="bold">返回上一层</span> </button> </div> </div> </form> </div> </div> </div> </div> </div> {/block} {block name="myAfterScript"} <!-- Peity --> <script src="__ROOT__/public/static/admin/js/plugins/peity/jquery.peity.min.js"></script> <!-- 自定义js --> <script src="__ROOT__/public/static/admin/js/content.js?v=1.0.0"></script> <!-- iCheck --> <script src="__ROOT__/public/static/admin/js/plugins/iCheck/icheck.min.js"></script> <!-- Peity --> <script src="__ROOT__/public/static/admin/js/demo/peity-demo.js"></script> <script src="__ROOT__/public/static/admin/js/plugins/cxSelect/jquery.cxselect.js"></script> <script> $(document).ready(function () { $('.i-checks').iCheck({ checkboxClass: 'icheckbox_square-green', radioClass: 'iradio_square-green', }); }); $('.city_china_val').cxSelect({ url: "__ROOT__/public/static/admin/js/plugins/cxSelect/cityData.min.json", // 如果服务器不支持 .json 类型文件,请将文件改为 .js 文件 selects: ['province', 'city', 'area'], // 数组,请注意顺序 // emptyStyle: 'none' }); $(".add_range").on('click', function(){ var rangeHTML = '<fieldset class="city_china_val">'+ '<select class="province other" name="province" data-first-title="选择省">'+ '<option value="">请选择</option>'+ '</select>'+ '<select class="city select_left" name="city" data-first-title="选择市">'+ '<option value="">请选择</option>'+ '</select>'+ '<select class="area select_left" name="area" data-first-title="选择地区">'+ '<option value="">请选择</option>'+ '</select>'+ '<button class="btn btn-warning delete_range select_left" type="button"><i class="fa fa-minus"></i> 删除区域</button>'+ '</fieldset>'; $(".city_china_val:last").after(rangeHTML); $('.city_china_val').cxSelect({ url: "__ROOT__/public/static/admin/js/plugins/cxSelect/cityData.min.json", // 如果服务器不支持 .json 类型文件,请将文件改为 .js 文件 selects: ['province', 'city', 'area'], // 数组,请注意顺序 // emptyStyle: 'none' }); }); $(".list_range").on('click', '.delete_range', function(){ $(this).parent().remove(); }); $(".btn-primary").on('click', function(){ var provinceData = ''; var cityData = ''; var areaData = ''; var provinceInfo = []; $(".province").each(function(){ var provinceVal = $(this).val(); provinceInfo.push(provinceVal); }); provinceData = provinceInfo.join('|'); $("input[name='provinceVal']").val(provinceData); var cityInfo = []; $(".city").each(function(){ var cityVal = $(this).val(); cityInfo.push(cityVal); }); cityData = cityInfo.join('|'); $("input[name='cityVal']").val(cityData); var areaInfo = []; $(".area").each(function(){ var areaVal = $(this).val(); areaInfo.push(areaVal); }); areaData = areaInfo.join('|'); $("input[name='areaVal']").val(areaData); $("form").submit(); }); </script> {/block}
{ "content_hash": "73528b10a632d300cf28c2bcfb0329a0", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 192, "avg_line_length": 43.308176100628934, "alnum_prop": 0.45991867557362764, "repo_name": "hanhang/mf315", "id": "ee552a31fc1f0c198799423fd060e46cb5b46285", "size": "7150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "admin/view/district/add.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "13" }, { "name": "HTML", "bytes": "269855" }, { "name": "PHP", "bytes": "312622" } ], "symlink_target": "" }
package com.github.sethereum.evm import com.github.sethereum.evm.EvmWord.ImplicitConversions._ import scala.util.Try trait EvmMemoryOps[T <: EvmMemoryOps[T]] { this: T => def memSize: EvmWord def memLoad(offset: Int): Try[(EvmWord, T)] def memSlice(begin: Int, end: Int): Try[(Seq[Byte], T)] def memStore(offset: Int, value: EvmWord): Try[T] def memStore(offset: Int, value: Byte): Try[T] def memStore(offset: Int, value: Seq[Byte]): Try[T] } /** * Simple auto sizing memory implementation backed by a single contiguous byte array. * * Implementation via byte array has the following consequences: * 1. Does NOT satisfy immutable state semantics given the underlying array * 2. It is not optimized for sparse memory access * 3. Addressable memory is limited to the size of an Int */ case class EvmMemory private (bytes: Seq[Byte] = Seq.empty, max: Int = 0) extends EvmMemoryOps[EvmMemory] { // Round size up to 32 byte boundary def memSize(size: Int): Int = (size + EvmWord.BYTES - 1) / EvmWord.BYTES * EvmWord.BYTES override def memSize: EvmWord = memSize(max) override def memLoad(offset: Int): Try[(EvmWord, EvmMemory)] = { val begin = offset: Int val end = begin + EvmWord.BYTES if (begin >= bytes.size) { Try((EvmWord.Zero, copy(max = Math.max(this.max, end)))) } else if (end <= bytes.size) { Try((EvmWord(bytes.slice(begin, end)), this)) } else { Try((EvmWord.leftAlign(bytes.slice(begin, bytes.size)), copy(max = end))) } } override def memSlice(begin: Int, end: Int): Try[(Seq[Byte], EvmMemory)] = { if (begin >= bytes.size) { Try((Seq.fill(end - begin)(0.toByte), copy(max = end))) } else if (end <= bytes.size) { Try((bytes.slice(begin, end), this)) } else { Try((bytes.slice(begin, end).padTo(end - begin, 0.toByte), copy(max = end))) } } override def memStore(offset: Int, value: EvmWord): Try[EvmMemory] = { val end = offset + EvmWord.BYTES val to: Array[Byte] = atLeastMem(end) value.padLeft.bytes.copyToArray(to, offset) Try(EvmMemory(to, Math.max(this.max, end))) } override def memStore(offset: Int, value: Byte): Try[EvmMemory] = { val end = offset + 1 val to: Array[Byte] = atLeastMem(end) to(offset) = value Try(EvmMemory(to, Math.max(this.max, end))) } override def memStore(offset: Int, value: Seq[Byte]): Try[EvmMemory] = { val end = offset + value.size val to: Array[Byte] = atLeastMem(end) value.copyToArray(to, offset) Try(EvmMemory(to, Math.max(this.max, end))) } // Ensure that internal memory array is at least the given size // Allocation size, if needed, is rounded up to 32 byte boundary private def atLeastMem(size: Int): Array[Byte] = { if (size > bytes.size) { val bytes = Array.ofDim[Byte](memSize(size)) this.bytes.copyToArray(bytes) bytes } else { this.bytes.toArray } } } object EvmMemory { def apply(): EvmMemory = new EvmMemory() def apply(bytes: Seq[Byte]): EvmMemory = new EvmMemory(bytes, bytes.size) } //// Sparse Map-based memory implementation //case class EvmMemory private (memory: Map[EvmWord, EvmWord] = Map.empty.withDefault(_ => EvmWord.ZERO), end: BigInteger = BigInteger.ZERO) extends EvmMemoryOps[EvmMemory] { // import EvmMemory._ // // // Size in bytes // override def size: EvmWord = end.add(EvmWordBytes).divide(EvmWordBytes).multiply(EvmWordBytes) // // override def memLoad(offset: EvmWord): Try[(EvmWord, EvmMemory)] = { // val begin = (offset: BigInteger) // val end = begin.add(EvmWordBytes) // val rem = begin.mod(EvmWordBytes) // val isAligned = rem == BigInteger.ZERO // // // Shortcut word aligned memory access // if (isAligned) { // Try((memory(begin.padLeft), if (end > this.end) copy(end = end) else this)) // } else { // val aligned = begin.subtract(rem) // val first = memory(aligned.padLeft) // val second = memory(aligned.add(EvmWordBytes).padLeft) // // val len = rem.intValue() // val bytes = Array.ofDim[Byte](EvmWord.BYTES) // first.bytes.copyToArray(bytes, 0, len) // second.bytes.copyToArray(bytes, len, EvmWord.BYTES - len) // // Try((EvmWord(bytes), if (end > this.end) copy(end = end) else this)) // } // } // // override def memStore(begin: EvmWord, value: EvmWord): Try[EvmMemory] = ??? // // override def memStore(begin: EvmWord, value: Byte): Try[EvmMemory] = ??? //} // //object EvmMemory { // val EvmWordBytes: BigInteger = BigInteger.valueOf(EvmWord.BYTES) //}
{ "content_hash": "006f1d7dc3a95f5f77cdbc667cb168f9", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 174, "avg_line_length": 34.082089552238806, "alnum_prop": 0.6562294723012919, "repo_name": "sethereum/scodec-rlp", "id": "f3c0286d90b5d7a7a7a0fc9ec2eb93ff998394a7", "size": "4567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/github/sethereum/evm/EvmMemory.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "89396" } ], "symlink_target": "" }
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GruntLauncher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Bjornej")] [assembly: AssemblyProduct("GruntLauncher")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0")] [assembly: AssemblyFileVersion("1.1.0")]
{ "content_hash": "35def8fba6cb63b36594ce8b47a266d2", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 84, "avg_line_length": 34.8125, "alnum_prop": 0.7477558348294434, "repo_name": "Bjornej/GruntLauncher", "id": "344c9ab73b21a200f9d49cb4fa334fb4a44841e5", "size": "1116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GruntLauncher/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "37741" } ], "symlink_target": "" }
import Ember from 'ember'; export function rangeGen(params/*, hash*/) { return params; } export default Ember.HTMLBars.makeBoundHelper(function(values) { var start = values[0]; var count = values[1]; var ret = []; for(var i = 0; i < count; i++) { ret.push(i+start); } return ret; });
{ "content_hash": "7e4b6e02ae79964f1afcf59ec1753b39", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 64, "avg_line_length": 19.0625, "alnum_prop": 0.6295081967213115, "repo_name": "v3sper/cv", "id": "99c5f1e11d832e4dcf707d2fdb55796ad4c1391c", "size": "305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/helpers/range-gen.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4559" }, { "name": "HTML", "bytes": "6512" }, { "name": "JavaScript", "bytes": "17608" } ], "symlink_target": "" }
<!doctype html> <html> <head> <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon"> <title>renderer.js (Closure Library API Documentation - JavaScript)</title> <link rel="stylesheet" href="static/css/base.css"> <link rel="stylesheet" href="static/css/doc.css"> <link rel="stylesheet" href="static/css/sidetree.css"> <link rel="stylesheet" href="static/css/prettify.css"> <script> var _staticFilePath = "static/"; </script> <script src="static/js/doc.js"> </script> <meta charset="utf8"> </head> <body onload="prettyPrint()"> <div id="header"> <div class="g-section g-tpl-50-50 g-split"> <div class="g-unit g-first"> <a id="logo" href="index.html">Closure Library API Documentation</a> </div> <div class="g-unit"> <div class="g-c"> <strong>Go to class or file:</strong> <input type="text" id="ac"> </div> </div> </div> </div> <div class="colmask rightmenu"> <div class="colleft"> <div class="col1"> <!-- Column 1 start --> <div id="title"> <span class="fn">renderer.js</span> </div> <div class="g-section g-tpl-75-25"> <div class="g-unit g-first" id="description"> Class for rendering the results of an auto complete and allow the user to select an row. </div> <div class="g-unit" id="useful-links"> <div class="title">Useful links</div> <ol> <li><a href="closure_goog_ui_autocomplete_renderer.js.source.html"><span class='source-code-link'>Source Code</span></a></li> </ol> </div> </div> <h2 class="g-first">File Location</h2> <div class="g-section g-tpl-20-80"> <div class="g-unit g-first"> <div class="g-c-cell code-label">ui/autocomplete/renderer.js</div> </div> </div> <hr/> <h2>Classes</h2> <div class="fn-constructor"> <a href="class_goog_ui_AutoComplete_Renderer.html"> goog.ui.AutoComplete.Renderer</a><br/> <div class="class-details">Class for rendering the results of an auto-complete in a drop down list.</div> </div> <div class="fn-constructor"> <a href="class_goog_ui_AutoComplete_Renderer_CustomRenderer.html"> goog.ui.AutoComplete.Renderer.CustomRenderer</a><br/> <div class="class-details">Class allowing different implementations to custom render the autocomplete. Extending classes should override the render function.</div> </div> <br/> <div class="legend"> <span class="key publickey"></span><span>Public</span> <span class="key protectedkey"></span><span>Protected</span> <span class="key privatekey"></span><span>Private</span> </div> <h2>Global Properties</h2> <div class="section"> <table class="horiz-rule"> <tr class="even entry public"> <td class="access"></td> <a name="goog.ui.AutoComplete.Renderer.DELAY_BEFORE_MOUSEOVER"></a> <td> <div class="arg"> <img align="left" src="static/images/blank.gif"> <span class="entryNamespace">goog.ui.AutoComplete.Renderer.</span><span class="entryName">DELAY_BEFORE_MOUSEOVER</span> : <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div> </div> <div class="entryOverview"> The delay before mouseover events are registered, in milliseconds </div> </td> <td class="view-code"> <a href="closure_goog_ui_autocomplete_renderer.js.source.html#line217">Code &raquo;</a> </td> </tr> <tr class="odd entry private"> <td class="access"></td> <a name="goog.ui.AutoComplete.Renderer.nextId_"></a> <td> <div class="arg"> <img align="left" src="static/images/blank.gif"> <span class="entryNamespace">goog.ui.AutoComplete.Renderer.</span><span class="entryName">nextId_</span> : <div class="fullType"><span class="type"><a href="http://www.google.com/url?sa=D&q=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number">number</a></span></div> </div> <div class="entryOverview"> Next unique instance ID of a renderer. </div> </td> <td class="view-code"> <a href="closure_goog_ui_autocomplete_renderer.js.source.html#line210">Code &raquo;</a> </td> </tr> </table> </div> <!-- Column 1 end --> </div> <div class="col2"> <!-- Column 2 start --> <div class="col2-c"> <h2 id="ref-head">Directory autocomplete</h2> <div id="localView"></div> </div> <div class="col2-c"> <h2 id="ref-head">File Reference</h2> <div id="sideFileIndex" rootPath="closure/goog" current="ui/autocomplete/renderer.js"></div> </div> <!-- Column 2 end --> </div> </div> </div> </body> </html>
{ "content_hash": "841c85c622d72a5d5d00c0dcdf178ce5", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 202, "avg_line_length": 24.43349753694581, "alnum_prop": 0.6108870967741935, "repo_name": "yesudeep/puppy", "id": "361af2f677a8b907cfba79096e36b09ab9b92e8c", "size": "4960", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/google-closure-library/closure/goog/docs/closure_goog_ui_autocomplete_renderer.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7979495" }, { "name": "Python", "bytes": "117877" }, { "name": "Ruby", "bytes": "592" } ], "symlink_target": "" }
cask "deadbeef-nightly" do version :latest sha256 :no_check url "https://downloads.sourceforge.net/deadbeef/travis/macOS/master/deadbeef-devel-macos-universal.zip", verified: "downloads.sourceforge.net/deadbeef/" name "DeaDBeeF" desc "Modular audio player" homepage "https://deadbeef.sourceforge.io/" app "DeaDBeeF.app" zap trash: [ "~/Library/Preferences/com.deadbeef.deadbeef.plist", "~/Library/Preferences/deadbeef", "~/Library/Saved Application State/com.deadbeef.deadbeef.savedState", ] end
{ "content_hash": "128a19d65d2e603e44956a4aebe07f3d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 106, "avg_line_length": 29.72222222222222, "alnum_prop": 0.7289719626168224, "repo_name": "mahori/homebrew-cask-versions", "id": "f4b4f9fca4113ce04ebbe113ac846f0e40ded224", "size": "535", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/deadbeef-nightly.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "277510" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.xtuml.bp</groupId> <artifactId>org.xtuml.bp.releng.parent.tests</artifactId> <version>7.0.0-SNAPSHOT</version> <relativePath>../../releng/org.xtuml.bp.releng.parent.tests/</relativePath> </parent> <groupId>org.xtuml.bp</groupId> <artifactId>org.xtuml.bp.ui.text.test</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>eclipse-test-plugin</packaging> <build> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>generate-ant</id> <phase>generate-sources</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <property name="compile_classpath" refid="maven.compile.classpath" /> <property name="runtime_classpath" refid="maven.runtime.classpath" /> <property name="test_classpath" refid="maven.test.classpath" /> <property name="plugin_classpath" refid="maven.plugin.classpath" /> <property name="outputDir" value="${project.build.outputDirectory}" /> <property name="sourceDir" value="${project.build.sourceDirectory}" /> <property name="ant.home" value="${ant-home-path}" /> <property name="eclipse.home" value="${eclipse-home-path}" /> <ant antfile="${basedir}/generate.xml" target="nb_all" /> </tasks> </configuration> </execution> <execution> <id>clean-ant</id> <phase>clean</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <property name="compile_classpath" refid="maven.compile.classpath" /> <property name="runtime_classpath" refid="maven.runtime.classpath" /> <property name="test_classpath" refid="maven.test.classpath" /> <property name="plugin_classpath" refid="maven.plugin.classpath" /> <property name="outputDir" value="${project.build.outputDirectory}" /> <property name="sourceDir" value="${project.build.sourceDirectory}" /> <property name="ant.home" value="${ant-home-path}" /> <property name="eclipse.home" value="${eclipse-home-path}" /> <ant antfile="${basedir}/generate.xml" target="clean_all" /> </tasks> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-surefire-plugin</artifactId> <version>${tycho-version}</version> <configuration> <includes> <include>**/UITextGlobalsSuite.java</include> <include>**/OpenDeclarationsTestsTestSuite.java</include> </includes> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "c8363bd45f0d5ed257b0118a386b6a5a", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 99, "avg_line_length": 38.26923076923077, "alnum_prop": 0.6432160804020101, "repo_name": "keithbrown/bptest", "id": "e31a7d0cc9642b219a190d03ac82f448787aa292", "size": "2985", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org.xtuml.bp.ui.text.test/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arc", "bytes": "305800" }, { "name": "HTML", "bytes": "98111" }, { "name": "Java", "bytes": "8457508" }, { "name": "PLpgSQL", "bytes": "977715" }, { "name": "Perl", "bytes": "41856" }, { "name": "TSQL", "bytes": "16094547" } ], "symlink_target": "" }
package uk.ac.susx.mlcl.lib.io; import com.google.common.base.CharMatcher; import com.google.common.io.Closeables; import com.google.common.io.Flushables; import org.junit.*; import uk.ac.susx.mlcl.TestConstants; import uk.ac.susx.mlcl.lib.io.Lexer.Type; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Random; import static org.junit.Assert.assertEquals; /** * @author Hamish I A Morgan &lt;[email protected]&gt; */ public class LexerTest { private static final String CFB = "come friendly bombs\nand fall on slough."; private static final int[] CFB_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; private static final Type[] CFB_types = {Type.Value, Type.Whitespace, Type.Value, Type.Whitespace, Type.Value, Type.Whitespace, Type.Value, Type.Whitespace, Type.Value, Type.Whitespace, Type.Value, Type.Whitespace, Type.Value, Type.Delimiter}; private static final int[] CFB_starts = {0, 4, 5, 13, 14, 19, 20, 23, 24, 28, 29, 31, 32, 38}; private static final int[] CFB_ends = {4, 5, 13, 14, 19, 20, 23, 24, 28, 29, 31, 32, 38, 39}; private static final String[] CFB_values = new String[]{"come", " ", "friendly", " ", "bombs", "\n", "and", " ", "fall", " ", "on", " ", "slough", "."}; private static final int[] CFB_lines = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}; private static final int[] CFB_columns = {0, 4, 5, 13, 14, 19, 0, 3, 4, 8, 9, 11, 12, 18}; private static final char[] CFB_charAt0 = {'c', ' ', 'f', ' ', 'b', '\n', 'a', ' ', 'f', ' ', 'o', ' ', 's', '.'}; public LexerTest() { } private File makeTmpData(String str, Charset charset) throws IOException { File tmp = File.createTempFile(this.getClass().getName() + ".", ""); tmp.deleteOnExit(); OutputStream out = null; try { out = new FileOutputStream(tmp); out.write(str.getBytes(charset)); } finally { if (out != null) { Flushables.flushQuietly(out); Closeables.closeQuietly(out); } } return tmp; } @Test public void basicTest() throws IOException { System.out.println("basicTest"); Charset charset = Files.DEFAULT_CHARSET; File tmp = makeTmpData(CFB, charset); Lexer lexer = new Lexer(tmp, charset); lexer.setDelimiterMatcher(CharMatcher.is('.')); int i = 0; while (lexer.hasNext()) { lexer.advance(); assertEquals("type", CFB_types[i], lexer.type()); assertEquals("start", CFB_starts[i], lexer.start()); assertEquals("end", CFB_ends[i], lexer.end()); assertEquals("value", CFB_values[i], lexer.value().toString()); assertEquals("charAt0", CFB_charAt0[i], lexer.charAt(0)); i++; } assertEquals("numbers length", i, CFB_numbers.length); assertEquals("types length", i, CFB_types.length); assertEquals("starts length", i, CFB_starts.length); assertEquals("ends length", i, CFB_ends.length); assertEquals("values length", i, CFB_values.length); assertEquals("lines length", i, CFB_lines.length); assertEquals("columns length", i, CFB_columns.length); assertEquals("charAt0 length", i, CFB_charAt0.length); } @Test public void seekTest() throws IOException { System.out.println("seekTest"); Charset charset = Files.DEFAULT_CHARSET; File tmp = makeTmpData(CFB, charset); Lexer lexer = new Lexer(tmp, charset); lexer.setDelimiterMatcher(CharMatcher.is('.')); // Iterator of the whole string, storing the tell offsets for every // lexeme in a list Tell[] tells = new Tell[CFB_numbers.length]; int i = 0; while (lexer.hasNext()) { lexer.advance(); tells[i] = lexer.position(); i++; } // Now randomly seek into the lexer at various offsets, and check that // they are what they are supposed to be Random rand = new Random(1); for (int j = 0; j < 500; j++) { i = rand.nextInt(CFB_numbers.length); lexer.position(tells[i]); assertEquals("type[" + i + "]", CFB_types[i], lexer.type()); assertEquals("value[" + i + "]", CFB_values[i], lexer.value(). toString()); assertEquals("charAt0[" + i + "]", CFB_charAt0[i], lexer.charAt(0)); } } @Test public void seekTestFruitEntries() throws IOException { seekTest(TestConstants.TEST_FRUIT_ENTRIES); } @Test public void seekTestFruitFeatures() throws IOException { seekTest(TestConstants.TEST_FRUIT_FEATURES); } @Test public void seekTestFruitEvents() throws IOException { seekTest(TestConstants.TEST_FRUIT_EVENTS); } @Test public void seekTestFruitInput() throws IOException { seekTest(TestConstants.TEST_FRUIT_INPUT); } @Test public void seekTestFruitSims() throws IOException { seekTest(TestConstants.TEST_FRUIT_SIMS); } void seekTest(File file) throws IOException { System.out.println("Test Lexer seek with " + file.toString() + ""); Charset charset = Files.DEFAULT_CHARSET; Lexer lexer = new Lexer(file, charset); List<Tell> tells = new ArrayList<Tell>(); List<String> values = new ArrayList<String>(); while (lexer.hasNext()) { lexer.advance(); tells.add(lexer.position()); values.add(lexer.value().toString()); } // check a bunch random seeks Random rand = new Random(0); for (int j = 0; j < 500; j++) { final int i = rand.nextInt(tells.size()); lexer.position(tells.get(i)); assertEquals(values.get(i), lexer.value().toString()); assertEquals(tells.get(i), lexer.position()); } // Check the edge cases for (int i : new int[]{tells.size() - 1, 0, tells.size() - 2, 1}) { lexer.position(tells.get(i)); assertEquals(values.get(i), lexer.value().toString()); assertEquals(tells.get(i), lexer.position()); } } }
{ "content_hash": "b3b96bf57e1ed3390da2b73c2d6ec39a", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 81, "avg_line_length": 32.61306532663317, "alnum_prop": 0.5721109399075501, "repo_name": "MLCL/Byblo", "id": "bc6f7a48eb7da55367d035840b1f828fbcb85f6c", "size": "8090", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/uk/ac/susx/mlcl/lib/io/LexerTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "4659" }, { "name": "Java", "bytes": "2232485" }, { "name": "Perl6", "bytes": "4" }, { "name": "Shell", "bytes": "47440" } ], "symlink_target": "" }
export * from './container-control.component'; export * from './control.component'; export * from './navigation-control.component';
{ "content_hash": "7d3daf81ae72325a15cf8b0dde02559e", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 47, "avg_line_length": 44, "alnum_prop": 0.7348484848484849, "repo_name": "aarmour/mapquest-ng2", "id": "e06faf9335b8798be161cede6dcccff60eb87fa1", "size": "132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/mapbox/control/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3905" }, { "name": "HTML", "bytes": "516" }, { "name": "JavaScript", "bytes": "2803" }, { "name": "TypeScript", "bytes": "47407" } ], "symlink_target": "" }
typedef int my_t; // data type for [inItem], [valueItem] and [outItem]. #include "producer_consumer.h" // The "producer" step gets an inItem, and produces a valueItem. int Producer::execute(const int & t, ProdCons_context & c ) const { // Get the inItem my_t in; c.inItem.get(t, in); // Compute the valueItem my_t value = in * 10; // i is some function of my_tag_in int i = (int)t ; // Put the valueItem c.valueItem.put(i, value); return CnC::CNC_Success; } // The "consumer" step gets an valueItem, and produces an outItem. int Consumer::execute(const int & t, ProdCons_context & c ) const { // i is some function of my_tag_in int i = (int)t ; // Get the valueItem my_t value; c.valueItem.get(i, value); // Compute the outItem my_t out = value + 3; // Put the outItem c.outItem.put(t, out); return CnC::CNC_Success; } int main( int argc, char* argv[]) { // Create an instance of the context class which defines the graph ProdCons_context c; // User input for the number of instances of (producer) and (consumer) // to be executed. It can be any positive integer. const unsigned int N = 10; // Put all inItem instances and all prodConsTag instances. // Each prodConsTag instance prescribes a "producer" step instance // and a "consumer" step instance. for (unsigned int i = 0; i < N; ++i){ c.inItem.put(i, my_t(i*10)); c.prodConsTag.put(i); } // Wait for all steps to finish c.wait(); // Execution of the graph has finished. // Print the outItem instances. CnC::item_collection<int, my_t>::const_iterator cii; for (cii = c.outItem.begin(); cii != c.outItem.end(); cii++) { int tag = cii->first; my_t outVal = *(cii->second); std::cout << "outItem" << tag << " is " << outVal << std::endl; } }
{ "content_hash": "17a60b85d05bc254888031369cda9a82", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 74, "avg_line_length": 26.52777777777778, "alnum_prop": 0.6078534031413613, "repo_name": "fschlimb/icnc", "id": "db5d54c685569c421bcf237c3980431e8c5d356c", "size": "4072", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "samples/producer_consumer/producer_consumer/producer_consumer.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "853303" }, { "name": "CMake", "bytes": "28429" }, { "name": "Dockerfile", "bytes": "1271" }, { "name": "Makefile", "bytes": "3057" }, { "name": "PHP", "bytes": "5576" }, { "name": "Python", "bytes": "15228" }, { "name": "Shell", "bytes": "13848" } ], "symlink_target": "" }
/*------------------------------------------------------------*/ // <summary>GameCanvas for Unity</summary> // <author>Seibe TAKAHASHI</author> // <remarks> // (c) 2015-2022 Smart Device Programming. // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // </remarks> /*------------------------------------------------------------*/ #nullable enable using System.Runtime.CompilerServices; using Unity.Mathematics; namespace GameCanvas { public static class GcMath { //---------------------------------------------------------- #region 変数 //---------------------------------------------------------- public static Random s_Random; #endregion //---------------------------------------------------------- #region 公開関数 //---------------------------------------------------------- /// <summary> /// 絶対値 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(in float value) => math.abs(value); /// <summary> /// 絶対値 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Abs(in int value) => math.abs(value); /// <summary> /// 計算誤差を考慮した同値判定 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AlmostSame(in float a, in float b) => (a == b) || UnityEngine.Mathf.Approximately(a, b); /// <summary> /// 計算誤差を考慮した同値判定 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AlmostSame(in float2 a, in float2 b) => AlmostSame(a.x, b.x) && AlmostSame(a.y, b.y); /// <summary> /// 計算誤差を考慮したゼロ判定 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AlmostZero(in float value) => (value >= -math.EPSILON && value <= math.EPSILON); /// <summary> /// ベクトルの角度 /// </summary> /// <param name="v">ベクトル</param> /// <returns>ベクトルの角度(度数法)</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Atan2(in float2 v) => math.degrees(math.atan2(v.y, v.x)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp(in float value, in float min, in float max) => math.clamp(value, min, max); /// <summary> /// コサイン /// </summary> /// <param name="degree">角度(度数法)</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(in float degree) => math.cos(math.radians(degree)); /// <summary> /// ベクトルの外積 /// </summary> /// <param name="a">ベクトルA</param> /// <param name="b">ベクトルB</param> /// <returns>外積</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cross(in float2 a, in float2 b) => a.x * b.y - a.y * b.x; /// <summary> /// ベクトルの内積 /// </summary> /// <param name="a">ベクトルA</param> /// <param name="b">ベクトルB</param> /// <returns>内積</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(in float2 a, in float2 b) => a.x * b.x + a.y * b.y; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Max(in float a, in float b) => math.max(a, b); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Min(in float a, in float b) => math.min(a, b); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Random(in int min, in int max) => s_Random.NextInt(min, max + 1); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Random(in float min, in float max) => s_Random.NextFloat(min, max); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Random() => s_Random.NextFloat(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Repeat(in float value, in float max) => UnityEngine.Mathf.Repeat(value, max); /// <summary> /// ベクトルの転回 /// </summary> /// <param name="v">回転前のベクトル</param> /// <param name="degree">回転量(度数法)</param> /// <returns>回転後のベクトル</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float2 RotateVector(in float2 v, in float degree) => GcAffine.FromRotate(math.radians(degree)).Mul(v); /// <summary> /// 四捨五入 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Round(in double value) => (int)System.Math.Round(value); /// <summary> /// 乱数の種の設定 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetRandomSeed(in uint seed) => s_Random.InitState(seed); /// <summary> /// サイン /// </summary> /// <param name="degree">角度(度数法)</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(in float degree) => math.sin(math.radians(degree)); /// <summary> /// 平方根 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(in float value) => math.sqrt(value); #endregion //---------------------------------------------------------- #region 内部関数 //---------------------------------------------------------- static GcMath() { s_Random = new Random(0x6E624EB7u); } #endregion } }
{ "content_hash": "dedc6934039f626fb85c5a29c89fffc6", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 95, "avg_line_length": 35.31927710843374, "alnum_prop": 0.5353914378304622, "repo_name": "sfc-sdp/GameCanvas-Unity", "id": "4763580a6cb9317e886748b4e231400647cefc70", "size": "6219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Packages/GameCanvas/Runtime/Scripts/Utility/GcMath.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "667666" }, { "name": "ShaderLab", "bytes": "3587" } ], "symlink_target": "" }
from modeltranslation.translator import translator, TranslationOptions from mezzanine.core.translation import TranslatedRichText from mezzanine.forms.models import Form, Field class TranslatedForm(TranslatedRichText): fields = ('button_text', 'response', 'email_subject', 'email_message',) class TranslatedField(TranslationOptions): fields = ('label', 'choices', 'default', 'placeholder_text', 'help_text',) translator.register(Form, TranslatedForm) translator.register(Field, TranslatedField)
{ "content_hash": "21f71cb904c7eb726b53dfde8dd67461", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 78, "avg_line_length": 36.142857142857146, "alnum_prop": 0.7905138339920948, "repo_name": "dekomote/mezzanine-modeltranslation-backport", "id": "8b7630f5d45fd3fe5d89787a42591b85a0dae3c0", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/translation_in_3.1.10", "path": "mezzanine/forms/translation.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "104823" }, { "name": "HTML", "bytes": "88707" }, { "name": "JavaScript", "bytes": "249888" }, { "name": "Nginx", "bytes": "2261" }, { "name": "Python", "bytes": "640391" } ], "symlink_target": "" }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { EditStoreComponent } from './edit-store.component'; describe('EditStoreComponent', () => { let component: EditStoreComponent; let fixture: ComponentFixture<EditStoreComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ EditStoreComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EditStoreComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "dec94446e745bef0dd9d42260626c485", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 73, "avg_line_length": 28, "alnum_prop": 0.6862244897959183, "repo_name": "KonstantinKirchev/Women-Market", "id": "59a61518e437b4829a62f4e296c0c9eaa45da67a", "size": "784", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/edit-store/edit-store.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12184" }, { "name": "HTML", "bytes": "57081" }, { "name": "JavaScript", "bytes": "1884" }, { "name": "TypeScript", "bytes": "79375" } ], "symlink_target": "" }
package com.dscid.filesystemanalyzer; public interface AnalyzerStorage { }
{ "content_hash": "a61e71ff27e8ab60a2132fcc019962b1", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 15.4, "alnum_prop": 0.8181818181818182, "repo_name": "fxarte/FileSystemAnalyzer", "id": "1b92d97667c4908fd2d99bbd58300c4469667239", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/dscid/filesystemanalyzer/AnalyzerStorage.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "103063" } ], "symlink_target": "" }
namespace Tenh { // interface for everything in basic mode that has operator overloads template <typename Derived_, Uint32 FREE_INDEX_COUNT_> struct ExpressionOperand_i { static_assert((!TypesAreEqual_f<Derived_,NullType>::V), "Derived type for ExpressionOperand_i must not be NullType."); static_assert(FREE_INDEX_COUNT_ <= 2, "ExpressionOperand_i must have more than one free index."); typedef Derived_ Derived; static Uint32 const FREE_INDEX_COUNT = FREE_INDEX_COUNT_; // for accessing this as the Derived type Derived const &as_derived () const { return *static_cast<Derived const *>(this); } Derived &as_derived () { return *static_cast<Derived *>(this); } }; } // end of namespace Tenh #endif // TENH_BASIC_EXPRESSIONOPERAND_HPP_
{ "content_hash": "d4a1f4686e5e94e5eda28e5641df8c2e", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 122, "avg_line_length": 35.04545454545455, "alnum_prop": 0.7159533073929961, "repo_name": "leapmotion/tensorheaven", "id": "f32d13b8498cab686fee5258700b8f115df28121", "size": "1142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/tenh/basic/expressionoperand.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1715954" }, { "name": "CMake", "bytes": "8916" }, { "name": "Perl", "bytes": "1898" }, { "name": "Shell", "bytes": "2688" } ], "symlink_target": "" }
<?php use SimpleValidator\Validators\Range; class RangeValidatorTest extends PHPUnit_Framework_TestCase { public function testValidator() { $message = 'field must be between 1 and 3.14'; $v = new Range('toto', $message, -1, 3.14); $this->assertEquals($message, $v->getErrorMessage()); $this->assertTrue($v->execute(array('toto' => ''))); $this->assertTrue($v->execute(array('toto' => null))); $this->assertFalse($v->execute(array('toto' => 'ddgg'))); $this->assertFalse($v->execute(array('toto' => '123.4'))); $this->assertFalse($v->execute(array('toto' => 123.4))); $this->assertFalse($v->execute(array('toto' => -2))); $this->assertTrue($v->execute(array())); $this->assertTrue($v->execute(array('toto' => 3.14))); $this->assertTrue($v->execute(array('toto' => 1))); $this->assertTrue($v->execute(array('toto' => '1.25'))); $this->assertTrue($v->execute(array('toto' => '-0.5'))); $this->assertTrue($v->execute(array('toto' => 0))); $this->assertTrue($v->execute(array('toto' => -1))); $this->assertTrue($v->execute(array('toto' => '0'))); } }
{ "content_hash": "237df7ddc6e6867390c51ee72de5c9b9", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 66, "avg_line_length": 38.70967741935484, "alnum_prop": 0.5625, "repo_name": "mat-mo/miniflux_ynh", "id": "c536a9b1a5ee89a48ffb8d0f08fbf9d0eb256a71", "size": "1200", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sources/vendor/fguillot/simple-validator/tests/RangeValidatorTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "544" }, { "name": "CSS", "bytes": "194188" }, { "name": "JavaScript", "bytes": "28673" }, { "name": "Nginx", "bytes": "602" }, { "name": "PHP", "bytes": "412214" }, { "name": "Ruby", "bytes": "876" }, { "name": "Shell", "bytes": "4201" } ], "symlink_target": "" }
package com.demem.barcodescanner.utils; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; public class GPSTracker extends Service implements LocationListener { private final Context mContext; boolean isGPSEnabled = false; boolean isNetworkEnabled = false; boolean canGetLocation = false; Location location; double latitude; double longitude; private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } return latitude; } public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } return longitude; } public boolean canGetLocation() { return this.canGetLocation; } public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); alertDialog.setTitle("GPS is settings"); alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } }
{ "content_hash": "f7731107220273524bc8d14fad58a9c1", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 90, "avg_line_length": 32.38607594936709, "alnum_prop": 0.5589212429157709, "repo_name": "khartash/dememscanner", "id": "8890d8ea0ee5965a3b9ea0efd3e3a7ea39649428", "size": "5117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/demem/barcodescanner/utils/GPSTracker.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "340" }, { "name": "Java", "bytes": "396116" } ], "symlink_target": "" }
/** */ /* * Created on 16.11.2004 * */ package org.apache.harmony.test.func.networking.java.net.URL.Init06; import java.io.IOException; import java.net.*; import org.apache.harmony.test.func.networking.java.net.share.URLTestFramework; /** * */ public class init06 extends URLTestFramework { public int test () { URL url = null; String urlFile = getValidFile(); String urlContextStr = "ftp://user:[email protected]/pub"; URLConnection con = null; URL urlContext = null; try { urlContext = new URL (urlContextStr); } catch (MalformedURLException e) { return (fail("can't create URL " + e.getMessage())); } try { url = new URL (urlContext, urlFile); } catch (MalformedURLException e) { return (fail("can't create URL " + e.getMessage())); } try { con = url.openConnection(); } catch (IOException e) { return fail("Can't create URLConnection: " + e.getMessage()); } String result = con.getURL().toString(); String rightResult = urlFile.equals("") ? urlContextStr : "ftp://user:[email protected]".concat(urlFile); if (result.equals(rightResult)) { return (pass("File: " + urlFile + "; Context: " + urlContext.toString() + "; URL: " + result)); } else { return fail ("Result: " + result + ", should be: " + rightResult); } } public static void main (String[] args) { System.exit(new init06().test(args)); } }
{ "content_hash": "72e34ff80d898458c6ba10df68782d79", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 117, "avg_line_length": 27.672131147540984, "alnum_prop": 0.5385071090047393, "repo_name": "freeVM/freeVM", "id": "32362d5fd53d518c8555401bebd7329545c70960", "size": "2500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/networking/java/net/URL/Init06/init06.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "116828" }, { "name": "C", "bytes": "17860389" }, { "name": "C++", "bytes": "19007206" }, { "name": "CSS", "bytes": "217777" }, { "name": "Java", "bytes": "152108632" }, { "name": "Objective-C", "bytes": "106412" }, { "name": "Objective-J", "bytes": "11029421" }, { "name": "Perl", "bytes": "305690" }, { "name": "Scilab", "bytes": "34" }, { "name": "Shell", "bytes": "153821" }, { "name": "XSLT", "bytes": "152859" } ], "symlink_target": "" }
package com.citraining.ws; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.1.5-b03- * Generated source version: 2.1 * */ @WebService(name = "GlobalWeatherSoap", targetNamespace = "http://www.webserviceX.NET") @XmlSeeAlso({ ObjectFactory.class }) public interface GlobalWeatherSoap { /** * Get weather report for all major cities around the world. * * @param cityName * @param countryName * @return * returns java.lang.String */ @WebMethod(operationName = "GetWeather", action = "http://www.webserviceX.NET/GetWeather") @WebResult(name = "GetWeatherResult", targetNamespace = "http://www.webserviceX.NET") @RequestWrapper(localName = "GetWeather", targetNamespace = "http://www.webserviceX.NET", className = "com.citraining.ws.GetWeather") @ResponseWrapper(localName = "GetWeatherResponse", targetNamespace = "http://www.webserviceX.NET", className = "com.citraining.ws.GetWeatherResponse") public String getWeather( @WebParam(name = "CityName", targetNamespace = "http://www.webserviceX.NET") String cityName, @WebParam(name = "CountryName", targetNamespace = "http://www.webserviceX.NET") String countryName); /** * Get all major cities by country name(full / part). * * @param countryName * @return * returns java.lang.String */ @WebMethod(operationName = "GetCitiesByCountry", action = "http://www.webserviceX.NET/GetCitiesByCountry") @WebResult(name = "GetCitiesByCountryResult", targetNamespace = "http://www.webserviceX.NET") @RequestWrapper(localName = "GetCitiesByCountry", targetNamespace = "http://www.webserviceX.NET", className = "com.citraining.ws.GetCitiesByCountry") @ResponseWrapper(localName = "GetCitiesByCountryResponse", targetNamespace = "http://www.webserviceX.NET", className = "com.citraining.ws.GetCitiesByCountryResponse") public String getCitiesByCountry( @WebParam(name = "CountryName", targetNamespace = "http://www.webserviceX.NET") String countryName); }
{ "content_hash": "ccaf3d1f8c2d4410fa10aaadedfaa864", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 170, "avg_line_length": 40.32203389830509, "alnum_prop": 0.6885245901639344, "repo_name": "phoolhbti/AEM", "id": "fe8da762055bfb9d6bad609f8a67ac40e4e034f3", "size": "2379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "citraining/soap-weater/src/main/java/com/citraining/ws/GlobalWeatherSoap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "68363" }, { "name": "HTML", "bytes": "155389" }, { "name": "Java", "bytes": "275564" }, { "name": "JavaScript", "bytes": "560238" }, { "name": "Less", "bytes": "51104" }, { "name": "PureBasic", "bytes": "5805" } ], "symlink_target": "" }
<script src="http://code.highcharts.com/maps/highmaps.js"></script> <script src="http://code.highcharts.com/maps/modules/exporting.js"></script> <script src="http://code.highcharts.com/mapdata/countries/ir/ir-all.js"></script> <div id="container"></div>
{ "content_hash": "f8401e420d94fd162799148300d0bff4", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 81, "avg_line_length": 51, "alnum_prop": 0.7294117647058823, "repo_name": "hcharts/data", "id": "90b98f078ef8f51396d61f532db961f3fd960c6d", "size": "255", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "datas/mapdata/countries/ir/ir-all/demo.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "81346" }, { "name": "HTML", "bytes": "325033" }, { "name": "JavaScript", "bytes": "3492201" }, { "name": "PHP", "bytes": "12087" } ], "symlink_target": "" }
package org.apache.activemq.artemis.core.server.cluster; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal; import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal; import org.apache.activemq.artemis.core.client.impl.Topology; import org.apache.activemq.artemis.core.config.ClusterConnectionConfiguration; import org.apache.activemq.artemis.core.protocol.core.Channel; import org.apache.activemq.artemis.core.protocol.core.ChannelHandler; import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterConnectMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterConnectReplyMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.NodeAnnounceMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.QuorumVoteMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.QuorumVoteReplyMessage; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ScaleDownAnnounceMessage; import org.apache.activemq.artemis.core.server.ActiveMQComponent; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumManager; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteHandler; import org.apache.activemq.artemis.core.server.cluster.qourum.Vote; import org.apache.activemq.artemis.core.server.impl.Activation; import org.apache.activemq.artemis.spi.core.remoting.Acceptor; import org.jboss.logging.Logger; /** * used for creating and managing cluster control connections for each cluster connection and the replication connection */ public class ClusterController implements ActiveMQComponent { private static final Logger logger = Logger.getLogger(ClusterController.class); private final QuorumManager quorumManager; private final ActiveMQServer server; private final Map<SimpleString, ServerLocatorInternal> locators = new HashMap<>(); private SimpleString defaultClusterConnectionName; private ServerLocator defaultLocator; private ServerLocator replicationLocator; private final Executor executor; private CountDownLatch replicationClusterConnectedLatch; private boolean started; private SimpleString replicatedClusterName; public ClusterController(ActiveMQServer server, ScheduledExecutorService scheduledExecutor) { this.server = server; executor = server.getExecutorFactory().getExecutor(); quorumManager = new QuorumManager(scheduledExecutor, this); } @Override public void start() throws Exception { if (started) return; //set the default locator that will be used to connecting to the default cluster. defaultLocator = locators.get(defaultClusterConnectionName); //create a locator for replication, either the default or the specified if not set if (replicatedClusterName != null && !replicatedClusterName.equals(defaultClusterConnectionName)) { replicationLocator = locators.get(replicatedClusterName); if (replicationLocator == null) { ActiveMQServerLogger.LOGGER.noClusterConnectionForReplicationCluster(); replicationLocator = defaultLocator; } } else { replicationLocator = defaultLocator; } //latch so we know once we are connected replicationClusterConnectedLatch = new CountDownLatch(1); //and add the quorum manager as a topology listener defaultLocator.addClusterTopologyListener(quorumManager); //start the quorum manager quorumManager.start(); started = true; //connect all the locators in a separate thread for (ServerLocatorInternal serverLocatorInternal : locators.values()) { if (serverLocatorInternal.isConnectable()) { executor.execute(new ConnectRunnable(serverLocatorInternal)); } } } @Override public void stop() throws Exception { //close all the locators for (ServerLocatorInternal serverLocatorInternal : locators.values()) { serverLocatorInternal.close(); } //stop the quorum manager quorumManager.stop(); started = false; } @Override public boolean isStarted() { return started; } public QuorumManager getQuorumManager() { return quorumManager; } //set the default cluster connections name public void setDefaultClusterConnectionName(SimpleString defaultClusterConnection) { this.defaultClusterConnectionName = defaultClusterConnection; } /** * add a locator for a cluster connection. * * @param name the cluster connection name * @param dg the discovery group to use * @param config the cluster connection config */ public void addClusterConnection(SimpleString name, DiscoveryGroupConfiguration dg, ClusterConnectionConfiguration config) { ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(dg); configAndAdd(name, serverLocator, config); } /** * add a locator for a cluster connection. * * @param name the cluster connection name * @param tcConfigs the transport configurations to use */ public void addClusterConnection(SimpleString name, TransportConfiguration[] tcConfigs, ClusterConnectionConfiguration config) { ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(tcConfigs); configAndAdd(name, serverLocator, config); } private void configAndAdd(SimpleString name, ServerLocatorInternal serverLocator, ClusterConnectionConfiguration config) { serverLocator.setConnectionTTL(config.getConnectionTTL()); serverLocator.setClientFailureCheckPeriod(config.getClientFailureCheckPeriod()); //if the cluster isn't available we want to hang around until it is serverLocator.setReconnectAttempts(-1); serverLocator.setInitialConnectAttempts(-1); //this is used for replication so need to use the server packet decoder serverLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(serverLocator)); locators.put(name, serverLocator); } /** * add a cluster listener * * @param listener */ public void addClusterTopologyListenerForReplication(ClusterTopologyListener listener) { replicationLocator.addClusterTopologyListener(listener); } /** * add an interceptor * * @param interceptor */ public void addIncomingInterceptorForReplication(Interceptor interceptor) { replicationLocator.addIncomingInterceptor(interceptor); } /** * connect to a specific node in the cluster used for replication * * @param transportConfiguration the configuration of the node to connect to. * @return the Cluster Control * @throws Exception */ public ClusterControl connectToNode(TransportConfiguration transportConfiguration) throws Exception { ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) defaultLocator.createSessionFactory(transportConfiguration, 0, false); return connectToNodeInCluster(sessionFactory); } /** * connect to a specific node in the cluster used for replication * * @param transportConfiguration the configuration of the node to connect to. * @return the Cluster Control * @throws Exception */ public ClusterControl connectToNodeInReplicatedCluster(TransportConfiguration transportConfiguration) throws Exception { ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) replicationLocator.createSessionFactory(transportConfiguration, 0, false); return connectToNodeInCluster(sessionFactory); } /** * connect to an already defined node in the cluster * * @param sf the session factory * @return the Cluster Control */ public ClusterControl connectToNodeInCluster(ClientSessionFactoryInternal sf) { sf.getServerLocator().setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(sf.getServerLocator())); return new ClusterControl(sf, server); } /** * retry interval for connecting to the cluster * * @return the retry interval */ public long getRetryIntervalForReplicatedCluster() { return replicationLocator.getRetryInterval(); } /** * wait until we have connected to the cluster. * * @throws InterruptedException */ public void awaitConnectionToReplicationCluster() throws InterruptedException { replicationClusterConnectedLatch.await(); } /** * used to set a channel handler on the connection that can be used by the cluster control * * @param channel the channel to set the handler * @param acceptorUsed the acceptor used for connection * @param remotingConnection the connection itself * @param activation */ public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, Activation activation) { channel.setHandler(new ClusterControllerChannelHandler(channel, acceptorUsed, remotingConnection, activation.getActivationChannelHandler(channel, acceptorUsed))); } public int getDefaultClusterSize() { return defaultLocator.getTopology().getMembers().size(); } public Topology getDefaultClusterTopology() { return defaultLocator.getTopology(); } public SimpleString getNodeID() { return server.getNodeID(); } public String getIdentity() { return server.getIdentity(); } public void setReplicatedClusterName(String replicatedClusterName) { this.replicatedClusterName = new SimpleString(replicatedClusterName); } /** * a handler for handling packets sent between the cluster. */ private final class ClusterControllerChannelHandler implements ChannelHandler { private final Channel clusterChannel; private final Acceptor acceptorUsed; private final CoreRemotingConnection remotingConnection; private final ChannelHandler channelHandler; boolean authorized = false; private ClusterControllerChannelHandler(Channel clusterChannel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, ChannelHandler channelHandler) { this.clusterChannel = clusterChannel; this.acceptorUsed = acceptorUsed; this.remotingConnection = remotingConnection; this.channelHandler = channelHandler; } @Override public void handlePacket(Packet packet) { if (!isStarted()) { if (channelHandler != null) { channelHandler.handlePacket(packet); } return; } if (!authorized) { if (packet.getType() == PacketImpl.CLUSTER_CONNECT) { ClusterConnection clusterConnection = acceptorUsed.getClusterConnection(); //if this acceptor isn't associated with a cluster connection use the default if (clusterConnection == null) { clusterConnection = server.getClusterManager().getDefaultConnection(null); } ClusterConnectMessage msg = (ClusterConnectMessage) packet; if (server.getConfiguration().isSecurityEnabled() && !clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword())) { clusterChannel.send(new ClusterConnectReplyMessage(false)); } else { authorized = true; clusterChannel.send(new ClusterConnectReplyMessage(true)); } } } else { if (packet.getType() == PacketImpl.NODE_ANNOUNCE) { NodeAnnounceMessage msg = (NodeAnnounceMessage) packet; Pair<TransportConfiguration, TransportConfiguration> pair; if (msg.isBackup()) { pair = new Pair<>(null, msg.getConnector()); } else { pair = new Pair<>(msg.getConnector(), msg.getBackupConnector()); } if (logger.isTraceEnabled()) { logger.trace("Server " + server + " receiving nodeUp from NodeID=" + msg.getNodeID() + ", pair=" + pair); } if (acceptorUsed != null) { ClusterConnection clusterConn = acceptorUsed.getClusterConnection(); if (clusterConn != null) { String scaleDownGroupName = msg.getScaleDownGroupName(); clusterConn.nodeAnnounced(msg.getCurrentEventID(), msg.getNodeID(), msg.getBackupGroupName(), scaleDownGroupName, pair, msg.isBackup()); } else { logger.debug("Cluster connection is null on acceptor = " + acceptorUsed); } } else { logger.debug("there is no acceptor used configured at the CoreProtocolManager " + this); } } else if (packet.getType() == PacketImpl.QUORUM_VOTE) { QuorumVoteMessage quorumVoteMessage = (QuorumVoteMessage) packet; QuorumVoteHandler voteHandler = quorumManager.getVoteHandler(quorumVoteMessage.getHandler()); quorumVoteMessage.decode(voteHandler); Vote vote = quorumManager.vote(quorumVoteMessage.getHandler(), quorumVoteMessage.getVote()); clusterChannel.send(new QuorumVoteReplyMessage(quorumVoteMessage.getHandler(), vote)); } else if (packet.getType() == PacketImpl.SCALEDOWN_ANNOUNCEMENT) { ScaleDownAnnounceMessage message = (ScaleDownAnnounceMessage) packet; //we don't really need to check as it should always be true if (server.getNodeID().equals(message.getTargetNodeId())) { server.addScaledDownNode(message.getScaledDownNodeId()); } } else if (channelHandler != null) { channelHandler.handlePacket(packet); } } } } /** * used for making the initial connection in the cluster */ private final class ConnectRunnable implements Runnable { private final ServerLocatorInternal serverLocator; private ConnectRunnable(ServerLocatorInternal serverLocator) { this.serverLocator = serverLocator; } @Override public void run() { try { serverLocator.connect(); if (serverLocator == replicationLocator) { replicationClusterConnectedLatch.countDown(); } } catch (ActiveMQException e) { if (!started) { return; } server.getScheduledPool().schedule(this, serverLocator.getRetryInterval(), TimeUnit.MILLISECONDS); } } } public ServerLocator getReplicationLocator() { return this.replicationLocator; } }
{ "content_hash": "cd6330c383d887e015339c24a59b3990", "timestamp": "", "source": "github", "line_count": 406, "max_line_length": 168, "avg_line_length": 41.09605911330049, "alnum_prop": 0.6941564279292778, "repo_name": "rh-messaging/jboss-activemq-artemis", "id": "ca99b23fee43badf0402f6c976d6bd55b1d972db", "size": "17484", "binary": false, "copies": "2", "ref": "refs/heads/jboss-1.5.5-x", "path": "artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7193" }, { "name": "C", "bytes": "26484" }, { "name": "C++", "bytes": "1197" }, { "name": "CMake", "bytes": "4260" }, { "name": "CSS", "bytes": "11732" }, { "name": "HTML", "bytes": "19329" }, { "name": "Java", "bytes": "24217754" }, { "name": "Shell", "bytes": "29773" } ], "symlink_target": "" }
namespace RobotsFactory.Reports.Models { using System; using System.Linq; public class ExcelReportEntry { public int ProductId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public decimal Sum { get; set; } } }
{ "content_hash": "5afb9be65abab4b20ba1d8b1d6b67105", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 19.1875, "alnum_prop": 0.6026058631921825, "repo_name": "Team-Zealot-Databases/Databases-Teamwork-2014", "id": "cae5f8e36c62dca8bd717a0bd0629d5291a6a299", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RobotsFactory/RobotsFactory.Reports.Models/ExcelReportEntry.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "105650" } ], "symlink_target": "" }
<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> <inspection_tool class="AndroidLintRecycle" enabled="false" level="WARNING" enabled_by_default="false" /> <inspection_tool class="InfiniteLoopStatement" enabled="false" level="WARNING" enabled_by_default="false" /> <inspection_tool class="LoggerInitializedWithForeignClass" enabled="false" level="WARNING" enabled_by_default="false"> <option name="loggerClassName" value="org.apache.log4j.Logger,org.slf4j.LoggerFactory,org.apache.commons.logging.LogFactory,java.util.logging.Logger" /> <option name="loggerFactoryMethodName" value="getLogger,getLogger,getLog,getLogger" /> </inspection_tool> </profile> </component>
{ "content_hash": "99d565445ada99f22c0bd3173f1cc010", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 158, "avg_line_length": 70.54545454545455, "alnum_prop": 0.7538659793814433, "repo_name": "a750183047/whereismytreasure", "id": "1f97d1aae17fff2ecc0357411ff14d317a9057e5", "size": "776", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/inspectionProfiles/Project_Default.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "86331" } ], "symlink_target": "" }
// ========================================================================== // Greenhouse.SimpleButton // ========================================================================== /*globals Greenhouse*/ /*jslint evil: true */ /** @class This view come from SCUI.SimpleButton Mixin to allow for simple button actions... This Mixin comes from SCUI: http://github.com/etgryphon/sproutcore-ui and is avaliable under the MIT license @author Evin Grano @version 0.1 @since 0.1 */ Greenhouse.SimpleButton = { /* SimpleButton Mixin */ target: null, action: null, hasState: NO, hasHover: NO, inState: NO, _hover: NO, stateClass: 'state', hoverClass: 'hover', activeClass: 'active', // Used to show the button as being active (pressed) _isMouseDown: NO, displayProperties: ['inState'], /** @private On mouse down, set active only if enabled. */ mouseDown: function(evt) { //console.log('SimpleButton#mouseDown()...'); if (!this.get('isEnabledInPane')) return YES ; // handled event, but do nothing //this.set('isActive', YES); this._isMouseDown = YES; this.displayDidChange(); return YES ; }, /** @private Remove the active class on mouseExited if mouse is down. */ mouseExited: function(evt) { //console.log('SimpleButton#mouseExited()...'); if ( this.get('hasHover') ){ this._hover = NO; this.displayDidChange(); } //if (this._isMouseDown) this.set('isActive', NO); return YES; }, /** @private If mouse was down and we renter the button area, set the active state again. */ mouseEntered: function(evt) { //console.log('SimpleButton#mouseEntered()...'); if ( this.get('hasHover') ){ this._hover = YES; this.displayDidChange(); } //this.set('isActive', this._isMouseDown); return YES; }, /** @private ON mouse up, trigger the action only if we are enabled and the mouse was released inside of the view. */ mouseUp: function(evt) { if (!this.get('isEnabledInPane')) return YES; //console.log('SimpleButton#mouseUp()...'); //if (this._isMouseDown) this.set('isActive', NO); // track independently in case isEnabled has changed this._isMouseDown = false; // Trigger the action var target = this.get('target') || null; var action = this.get('action'); // Support inline functions if (this._hasLegacyActionHandler()) { // old school... this._triggerLegacyActionHandler(evt); } else { // newer action method + optional target syntax... this.getPath('pane.rootResponder').sendAction(action, target, this, this.get('pane')); } if (this.get('hasState')) { this.set('inState', !this.get('inState')); } this.displayDidChange(); return YES; }, renderMixin: function(context, firstTime) { if (this.get('hasHover')) { var hoverClass = this.get('hoverClass'); context.setClass(hoverClass, this._hover && !this._isMouseDown); // addClass if YES, removeClass if NO } if (this.get('hasState')) { var stateClass = this.get('stateClass'); context.setClass(stateClass, this.inState); // addClass if YES, removeClass if NO } var activeClass = this.get('activeClass'); context.setClass(activeClass, this._isMouseDown); // If there is a toolTip set, grab it and localize if necessary. var toolTip = this.get('toolTip') ; if (SC.typeOf(toolTip) === SC.T_STRING) { if (this.get('localize')) toolTip = toolTip.loc(); context.attr('title', toolTip); context.attr('alt', toolTip); } }, /** @private From ButtonView Support inline function definitions */ _hasLegacyActionHandler: function(){ var action = this.get('action'); if (action && (SC.typeOf(action) === SC.T_FUNCTION)) return true; if (action && (SC.typeOf(action) === SC.T_STRING) && (action.indexOf('.') !== -1)) return true; return false; }, /** @private */ _triggerLegacyActionHandler: function(evt){ var target = this.get('target'); var action = this.get('action'); // TODO: [MB/EG] Review: MH added the else if so that the action executes // in the scope of the target, if it is specified. if (target === undefined && SC.typeOf(action) === SC.T_FUNCTION) { this.action(evt); } else if (target !== undefined && SC.typeOf(action) === SC.T_FUNCTION) { action.apply(target, [evt]); } if (SC.typeOf(action) === SC.T_STRING) { eval("this.action = function(e) { return "+ action +"(this, e); };"); this.action(evt); } } };
{ "content_hash": "117906763f8e0b593ea5f96eb081d9af", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 108, "avg_line_length": 29.828025477707005, "alnum_prop": 0.5966260943839419, "repo_name": "Eloqua/sproutcore", "id": "63d47d7c38ae376a14ee1ac6002668bc85c838e6", "size": "4683", "binary": false, "copies": "4", "ref": "refs/heads/ad/462", "path": "apps/greenhouse/views/simple_button.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "122698" }, { "name": "HTML", "bytes": "18077" }, { "name": "JavaScript", "bytes": "4898992" }, { "name": "Ruby", "bytes": "3484" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <testsuite tests="3" failures="0" name="forum.test.UtilisatorServiceTest" time="0" errors="0" skipped="0"> <properties> <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/> <property name="sun.boot.library.path" value="C:\Program Files\Java\jdk1.8.0_60\jre\bin"/> <property name="java.vm.version" value="25.60-b23"/> <property name="java.vm.vendor" value="Oracle Corporation"/> <property name="java.vendor.url" value="http://java.oracle.com/"/> <property name="path.separator" value=";"/> <property name="guice.disable.misplaced.annotation.check" value="true"/> <property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/> <property name="file.encoding.pkg" value="sun.io"/> <property name="user.script" value=""/> <property name="user.country" value="FR"/> <property name="sun.java.launcher" value="SUN_STANDARD"/> <property name="sun.os.patch.level" value="Service Pack 1"/> <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/> <property name="user.dir" value="C:\Users\ETY\Desktop\Projets Formation\J2E\ForumSpring"/> <property name="java.runtime.version" value="1.8.0_60-b27"/> <property name="java.awt.graphicsenv" value="sun.awt.Win32GraphicsEnvironment"/> <property name="java.endorsed.dirs" value="C:\Program Files\Java\jdk1.8.0_60\jre\lib\endorsed"/> <property name="os.arch" value="amd64"/> <property name="java.io.tmpdir" value="C:\Users\ETY\AppData\Local\Temp\"/> <property name="line.separator" value=" "/> <property name="java.vm.specification.vendor" value="Oracle Corporation"/> <property name="user.variant" value=""/> <property name="os.name" value="Windows 7"/> <property name="maven.ext.class.path" value="C:\Program Files\NetBeans 8.0.2\java\maven-nblib\netbeans-eventspy.jar"/> <property name="classworlds.conf" value="C:\Program Files\NetBeans 8.0.2\java\maven\bin\m2.conf"/> <property name="sun.jnu.encoding" value="Cp1252"/> <property name="java.library.path" value="C:\Program Files\Java\jdk1.8.0_60\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Tools\Maven\apache-maven-3.2.5\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Cassandra\bin;C:\Python27;C:\Program Files\MongoDB\Server\3.0/bin;C:\Users\ETY\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Program Files\Java\jdk1.8.0_60\bin;C:\Users\ETY\Desktop\Projets Formation\Java\TP\apache-maven-3.3.3-bin\apache-maven-3.3.3\bin;."/> <property name="java.specification.name" value="Java Platform API Specification"/> <property name="java.class.version" value="52.0"/> <property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/> <property name="os.version" value="6.1"/> <property name="user.home" value="C:\Users\ETY"/> <property name="user.timezone" value="Europe/Paris"/> <property name="java.awt.printerjob" value="sun.awt.windows.WPrinterJob"/> <property name="java.specification.version" value="1.8"/> <property name="file.encoding" value="UTF-8"/> <property name="user.name" value="ETY"/> <property name="java.class.path" value="C:\Program Files\NetBeans 8.0.2\java\maven\boot\plexus-classworlds-2.4.jar"/> <property name="java.vm.specification.version" value="1.8"/> <property name="sun.arch.data.model" value="64"/> <property name="java.home" value="C:\Program Files\Java\jdk1.8.0_60\jre"/> <property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher -Dmaven.ext.class.path=C:\Program Files\NetBeans 8.0.2\java\maven-nblib\netbeans-eventspy.jar -Dfile.encoding=UTF-8 clean install"/> <property name="java.specification.vendor" value="Oracle Corporation"/> <property name="user.language" value="fr"/> <property name="awt.toolkit" value="sun.awt.windows.WToolkit"/> <property name="java.vm.info" value="mixed mode"/> <property name="java.version" value="1.8.0_60"/> <property name="java.ext.dirs" value="C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext;C:\Windows\Sun\Java\lib\ext"/> <property name="sun.boot.class.path" value="C:\Program Files\Java\jdk1.8.0_60\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_60\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_60\jre\classes"/> <property name="java.vendor" value="Oracle Corporation"/> <property name="maven.home" value="C:\Program Files\NetBeans 8.0.2\java\maven"/> <property name="file.separator" value="\"/> <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/> <property name="sun.cpu.endian" value="little"/> <property name="sun.io.unicode.encoding" value="UnicodeLittle"/> <property name="sun.desktop" value="windows"/> <property name="sun.cpu.isalist" value="amd64"/> </properties> <testcase classname="forum.test.UtilisatorServiceTest" name="testTroisUsers" time="0"/> <testcase classname="forum.test.UtilisatorServiceTest" name="ajoutMessageTest" time="0"/> <testcase classname="forum.test.UtilisatorServiceTest" name="lectureMessageTest" time="0"/> </testsuite>
{ "content_hash": "826fbe22a66ec424eeb4044dcd25b69a", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 995, "avg_line_length": 88.61194029850746, "alnum_prop": 0.7168603671888159, "repo_name": "MHayet/ForumSpring", "id": "46bc5302351781562222d3e6ed15a6e3721f8d87", "size": "5937", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target/surefire-reports/TEST-forum.test.UtilisatorServiceTest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "37387" } ], "symlink_target": "" }
.. _l-1a-classe-heritage: Classes, héritages ================== Ces notebooks sont prévus pour une durée de quatre heures (2 séances). .. toctree:: :maxdepth: 2 td1a_cenonce_session5 td1a_correction_session5 td1a_cenonce_session6 td1a_correction_session6 2022_classes
{ "content_hash": "cef19a94a187a296f1b55e35a2974ef8", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 70, "avg_line_length": 19.733333333333334, "alnum_prop": 0.668918918918919, "repo_name": "sdpython/ensae_teaching_cs", "id": "f03e530373188c719838e76af09c7f5f401b58af", "size": "301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_doc/sphinxdoc/source/notebooks/_gs1a_5_classes.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "382" }, { "name": "C#", "bytes": "26850" }, { "name": "CSS", "bytes": "220769" }, { "name": "HTML", "bytes": "44390" }, { "name": "JavaScript", "bytes": "31077" }, { "name": "Jupyter Notebook", "bytes": "45255629" }, { "name": "PostScript", "bytes": "169142" }, { "name": "Python", "bytes": "1770141" }, { "name": "R", "bytes": "339" }, { "name": "Shell", "bytes": "3675" }, { "name": "TeX", "bytes": "593824" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../includes/main.css" type="text/css"> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"> <title>Apache CloudStack | The Power Behind Your Cloud</title> </head> <body> <div id="insidetopbg"> <div id="inside_wrapper"> <div class="uppermenu_panel"> <div class="uppermenu_box"></div> </div> <div id="main_controller"> <div id="inside_header"> <div class="header_top"> <a class="cloud_logo" href="http://cloudstack.org"></a> <div class="mainemenu_panel"></div> </div> </div> <div id="main_content"> <div class="inside_apileftpanel"> <div class="inside_contentpanel" style="width:930px;"> <div class="api_titlebox"> <div class="api_titlebox_left"> <span> Apache CloudStack 4.17.0.0 Root Admin API Reference </span> <p></p> <h1>removeCertFromLoadBalancer</h1> <p>Removes a certificate from a load balancer rule</p> </div> <div class="api_titlebox_right"> <a class="api_backbutton" href="../index.html"></a> </div> </div> <div class="api_tablepanel"> <h2>Request parameters</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td> </tr> <tr> <td style="width:200px;"><strong>lbruleid</strong></td><td style="width:500px;"><strong>the ID of the load balancer rule</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> </table> </div> <div class="api_tablepanel"> <h2>Response Tags</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td> </tr> <tr> <td style="width:200px;"><strong>displaytext</strong></td><td style="width:500px;">any text associated with the success or failure</td> </tr> <tr> <td style="width:200px;"><strong>success</strong></td><td style="width:500px;">true if operation is executed successfully</td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> <div id="comments_thread"> <script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script> <noscript> <iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&amp;page=4.2.0/rootadmin"></iframe> </noscript> </div> <div id="footer_maincontroller"> <p> Copyright &copy; 2015 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a> <br> Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation. </p> </div> </div> </div> </div> </body> </html>
{ "content_hash": "f26fff5d4f0fd97785b38c5797ca0943", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 229, "avg_line_length": 59.3448275862069, "alnum_prop": 0.39879914778229714, "repo_name": "apache/cloudstack-www", "id": "1b22891f0ecbca11dc1e71ff7ec718bdbdc61276", "size": "5163", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "content/api/apidocs-4.17/apis/removeCertFromLoadBalancer.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "568290" }, { "name": "HTML", "bytes": "222229805" }, { "name": "JavaScript", "bytes": "61116" }, { "name": "Python", "bytes": "3284" }, { "name": "Ruby", "bytes": "1973" }, { "name": "Shell", "bytes": "873" } ], "symlink_target": "" }
namespace edb { class CalcImageArea : public ICommand { public: CalcImageArea() {} // // interface ICommand // virtual std::string Command() const override; virtual std::string Description() const override; virtual std::string Usage() const override; virtual int Run(int argc, char *argv[]) override; static ICommand* Create() { return new CalcImageArea(); } private: void Run(const std::string& dir) const; }; // CalcImageArea } #endif // _EASYDB_CALC_IMAGE_AREA_H_
{ "content_hash": "f90591538540c06bb79dcad74ce400a9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 58, "avg_line_length": 18.576923076923077, "alnum_prop": 0.7080745341614907, "repo_name": "xzrunner/easyeditor", "id": "a06ed4fbd596cf2ad6e9e54b751f28bbcb92d47e", "size": "577", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "easydb/src/libdb/CalcImageArea.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "118661" }, { "name": "C++", "bytes": "5152354" }, { "name": "GLSL", "bytes": "10503" }, { "name": "Lua", "bytes": "127544" }, { "name": "Makefile", "bytes": "210" } ], "symlink_target": "" }
using System; using System.IO; using System.Text; using System.Collections; using NUnit.Framework; using NUnit.Core; using NUnit.TestData.ConsoleRunnerTest; using NUnit.Tests.Assemblies; namespace NUnit.ConsoleRunner.Tests { [TestFixture] public class ConsoleRunnerTest { private static readonly string failureMsg = string.Format( "Errors: {0}, Failures: {1}", MockAssembly.Errors, MockAssembly.Failures ); private static readonly string xmlFile = Path.Combine(Path.GetTempPath(), "console-test.xml"); private StringBuilder output; TextWriter saveOut; [SetUp] public void Init() { output = new StringBuilder(); Console.Out.Flush(); saveOut = Console.Out; Console.SetOut( new StringWriter( output ) ); } [TearDown] public void CleanUp() { Console.SetOut( saveOut ); FileInfo file = new FileInfo(xmlFile); if(file.Exists) file.Delete(); file = new FileInfo( "TestResult.xml" ); if(file.Exists) file.Delete(); } [Test] public void FailureFixture() { int resultCode = runFixture(typeof(FailureTest), "-noxml"); Assert.AreEqual(1, resultCode); } [Test] public void MultiFailureFixture() { int resultCode = runFixture(typeof(MultiFailureTest), "-noxml"); Assert.AreEqual(3, resultCode); } [Test] public void SuccessFixture() { int resultCode = runFixture(typeof(SuccessTest), "-noxml"); Assert.AreEqual(0, resultCode); } [Test] public void XmlResult() { FileInfo info = new FileInfo(xmlFile); info.Delete(); int resultCode = runFixture(typeof(SuccessTest), "-xml:" + xmlFile); Assert.AreEqual(0, resultCode); Assert.AreEqual(true, info.Exists); } [Test] public void InvalidFixture() { int resultCode = executeConsole( new string[] { MockAssembly.AssemblyPath, "-fixture:NUnit.Tests.BogusTest", "-noxml" }); Assert.AreEqual(ConsoleUi.FIXTURE_NOT_FOUND, resultCode); } [Test] public void AssemblyNotFound() { int resultCode = executeConsole(new string[] { "badassembly.dll", "-noxml" }); Assert.AreEqual(ConsoleUi.FILE_NOT_FOUND, resultCode); } [Test] public void OneOfTwoAssembliesNotFound() { int resultCode = executeConsole(new string[] { GetType().Module.Name, "badassembly.dll", "-noxml" }); Assert.AreEqual(ConsoleUi.FILE_NOT_FOUND, resultCode); } [Test] public void XmlToConsole() { int resultCode = runFixture( typeof(SuccessTest), "-xmlconsole", "-nologo" ); Assert.AreEqual(0, resultCode); StringAssert.Contains( @"<?xml version=""1.0""", output.ToString(), "Only XML should be displayed in xmlconsole mode"); } [Test] public void Bug1073539Test() { int resultCode = runFixture( typeof( Bug1073539Fixture ), "-noxml" ); Assert.AreEqual( 1, resultCode ); } [Test] public void Bug1311644Test() { int resultCode = runFixture( typeof( Bug1311644Fixture ), "-noxml" ); Assert.AreEqual( 1, resultCode ); } [Test] public void CanRunWithoutTestDomain() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, "-domain:None", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } [Test] public void CanRunWithSingleTestDomain() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, "-domain:Single", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } [Test] public void CanRunWithMultipleTestDomains() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, NoNamespaceTestFixture.AssemblyPath, "-domain:Multiple", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } [Test] public void CanRunWithoutTestDomain_NoThread() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, "-domain:None", "-nothread", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } [Test] public void CanRunWithSingleTestDomain_NoThread() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, "-domain:Single", "-nothread", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } [Test] public void CanRunWithMultipleTestDomains_NoThread() { Assert.AreEqual(MockAssembly.ErrorsAndFailures, executeConsole(MockAssembly.AssemblyPath, NoNamespaceTestFixture.AssemblyPath, "-domain:Multiple", "-nothread", "-noxml")); StringAssert.Contains( failureMsg, output.ToString() ); } private int runFixture( Type type ) { return executeConsole(new string[] { AssemblyHelper.GetAssemblyPath(type), "-fixture:" + type.FullName, "-noxml" }); } private int runFixture( Type type, params string[] arguments ) { string[] args = new string[arguments.Length+2]; int n = 0; args[n++] = AssemblyHelper.GetAssemblyPath(type); args[n++] = "-fixture:" + type.FullName; foreach( string arg in arguments ) args[n++] = arg; return executeConsole( args ); } // Run test in process using console. For test purposes, // avoid use of another process and turn trace off. private int executeConsole( params string[] arguments ) { int n = 0; #if CLR_2_0 || CLR_4_0 string[] args = new string[arguments.Length + 2]; args[n++] = "-process:single"; #else string[] args = new string[arguments.Length + 1]; #endif args[n++] = "-trace:Off"; foreach (string arg in arguments) args[n++] = arg; return NUnit.ConsoleRunner.Runner.Main( args ); } } }
{ "content_hash": "2c8560a893fe896c1f82558df46d2bf5", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 183, "avg_line_length": 29.75862068965517, "alnum_prop": 0.6427743751034597, "repo_name": "acken/AutoTest.Net", "id": "2dd828b7f1e6479efdf921ff19c1e3359d7895cc", "size": "6358", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/NUnit/src/NUnit-2.6.0.12051/src/ConsoleRunner/tests/ConsoleRunnerTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "150" }, { "name": "C#", "bytes": "9855924" }, { "name": "C++", "bytes": "57796" }, { "name": "CSS", "bytes": "22906" }, { "name": "JavaScript", "bytes": "10141" }, { "name": "Pascal", "bytes": "215" }, { "name": "PowerShell", "bytes": "156" }, { "name": "Ruby", "bytes": "3593661" }, { "name": "Shell", "bytes": "21129" }, { "name": "Visual Basic", "bytes": "97606" }, { "name": "XSLT", "bytes": "164747" } ], "symlink_target": "" }
An [Evil-icons](https://github.com/outpunk/evil-icons) loader for [webpack](https://github.com/webpack/webpack). ## Install `npm install evil-icons-loader --save-dev` ## Usage With jade-loader ```js module: { loaders: [{ test: /\.css/, loader: 'evil-icons-loader!jade-loader' }] } ``` With ejs-loader ```js module: { loaders: [{ test: /\.css/, loader: 'ejs-loader!evil-icons-loader' }] } ``` ## Options ### `className` Specify a icon class. ```js module: { loaders: [{ test: /\.css/, loader: 'evil-icons?className=myClass!jade' }] } ``` ## License Licensed under the MIT license.
{ "content_hash": "ebdbdd09bc589c3a5939a84dde2a263d", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 112, "avg_line_length": 13.630434782608695, "alnum_prop": 0.6124401913875598, "repo_name": "valerybugakov/evil-icons-loader", "id": "a22fc1545d78b9297d839020d0b7c09e33c3cf56", "size": "647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1828" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace Functional.Maybe { /// <summary> /// Integration with Enumerable's LINQ (such as .FirstMaybe()) and all kinds of cross-use of IEnumerables and Maybes /// </summary> public static class MaybeEnumerable { /// <summary> /// First item or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Maybe<T> FirstMaybe<T>(this IEnumerable<T> items) { Contract.Requires(items != null); return FirstMaybe(items, arg => true); } /// <summary> /// First item matching <paramref name="predicate"/> or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Maybe<T> FirstMaybe<T>(this IEnumerable<T> items, Func<T, bool> predicate) { Contract.Requires(items != null); Contract.Requires(predicate != null); var filtered = items.Where(predicate).ToArray(); return filtered.Any().Then(filtered.First); } /// <summary> /// Single item or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Maybe<T> SingleMaybe<T>(this IEnumerable<T> items) { Contract.Requires(items != null); return SingleMaybe(items, arg => true); } /// <summary> /// Single item matching <paramref name="predicate"/> or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Maybe<T> SingleMaybe<T>(this IEnumerable<T> items, Func<T, bool> predicate) { Contract.Requires(items != null); Contract.Requires(predicate != null); var all = items.ToArray(); return (all.Count(predicate) == 1).Then(() => all.Single(predicate)); } /// <summary> /// Last item or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Maybe<T> LastMaybe<T>(this IEnumerable<T> items) { Contract.Requires(items != null); return LastMaybe(items, arg => true); } /// <summary> /// Last item matching <paramref name="predicate"/> or Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Maybe<T> LastMaybe<T>(this IEnumerable<T> items, Func<T, bool> predicate) { Contract.Requires(items != null); Contract.Requires(predicate != null); var filtered = items.Where(predicate).ToArray(); return filtered.Any().Then(filtered.Last); } /// <summary> /// Returns the value of <paramref name="maybeCollection"/> if exists orlse an empty collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="maybeCollection"></param> /// <returns></returns> public static IEnumerable<T> FromMaybe<T>(this Maybe<IEnumerable<T>> maybeCollection) { return maybeCollection.HasValue ? maybeCollection.Value : Enumerable.Empty<T>(); } /// <summary> /// For each items that has value, applies <paramref name="selector"/> to it and wraps back as Maybe, for each otherwise remains Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="maybes"></param> /// <param name="selector"></param> /// <returns></returns> public static IEnumerable<Maybe<TResult>> Select<T, TResult>(this IEnumerable<Maybe<T>> maybes, Func<T, TResult> selector) { Contract.Requires(maybes != null); return maybes.Select(maybe => maybe.Select(selector)); } /// <summary> /// If all the items have value, unwraps all and returns the whole sequence of <typeparamref name="T"/>, wrapping the whole as Maybe, otherwise returns Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="maybes"></param> /// <returns></returns> public static Maybe<IEnumerable<T>> WholeSequenceOfValues<T>(this IEnumerable<Maybe<T>> maybes) { Contract.Requires(maybes != null); var forced = maybes.ToArray(); // there has got to be a better way to do this if (forced.AnyNothing()) return Maybe<IEnumerable<T>>.Nothing; return forced.Select(m => m.Value).ToMaybe(); } /// <summary> /// Filters out all the Nothings, unwrapping the rest to just type <typeparamref name="T"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="maybes"></param> /// <returns></returns> public static IEnumerable<T> WhereValueExist<T>(this IEnumerable<Maybe<T>> maybes) { Contract.Requires(maybes != null); return SelectWhereValueExist(maybes, m => m); } /// <summary> /// Filters out all the Nothings, unwrapping the rest to just type <typeparamref name="T"/> and then applies <paramref name="fn"/> to each /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="maybes"></param> /// <param name="fn"></param> /// <returns></returns> public static IEnumerable<TResult> SelectWhereValueExist<T, TResult>(this IEnumerable<Maybe<T>> maybes, Func<T, TResult> fn) { Contract.Requires(maybes != null); return from maybe in maybes where maybe.HasValue select fn(maybe.Value); } /// <summary> /// Checks if any item is Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="maybes"></param> /// <returns></returns> public static bool AnyNothing<T>(this IEnumerable<Maybe<T>> maybes) { Contract.Requires(maybes != null); return maybes.Any(m => !m.HasValue); } /// <summary> /// If ALL calls to <paramref name="pred"/> returned a value, filters out the <paramref name="xs"/> based on that values, otherwise returns Nothing /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xs"></param> /// <param name="pred"></param> /// <returns></returns> public static Maybe<IEnumerable<T>> WhereAll<T>(this IEnumerable<T> xs, Func<T, Maybe<bool>> pred) { Contract.Requires(xs != null); var l = new List<T>(); foreach (var x in xs) { var r = pred(x); if (!r.HasValue) return Maybe<IEnumerable<T>>.Nothing; if (r.Value) l.Add(x); } return new Maybe<IEnumerable<T>>(l); } /// <summary> /// Filters out <paramref name="xs"/> based on <paramref name="pred"/> resuls; Nothing considered as False /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xs"></param> /// <param name="pred"></param> /// <returns></returns> public static IEnumerable<T> Where<T>(this IEnumerable<T> xs, Func<T, Maybe<bool>> pred) { Contract.Requires(xs != null); return from x in xs let b = pred(x) where b.HasValue && b.Value select x; } } }
{ "content_hash": "22629ff8ceba230c1d981fb911361712", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 162, "avg_line_length": 32.38709677419355, "alnum_prop": 0.6402959590210586, "repo_name": "InspiredIdealist/Functional.Maybe", "id": "529532a5bba231e7822bebd0611d401fcadbd211", "size": "7030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MaybeEnumerable.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "28084" } ], "symlink_target": "" }
package codingbat.recursion1; /** * http://codingbat.com/prob/p183394 */ public final class AllStar { public String allStar(String str) { if (str == null || str.isEmpty()) { return ""; } if (str.length() < 2) { return str.substring(0, 1); } return str.substring(0, 1) + "*" + allStar(str.substring(1)); } }
{ "content_hash": "530ecb7742ee3b1b3d87688f1bc1cc12", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 69, "avg_line_length": 21.333333333333332, "alnum_prop": 0.5234375, "repo_name": "jaredsburrows/cs-interview-questions", "id": "2de5bdfe0d5fbd90972670f9842f3549f3e76822", "size": "384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/src/main/java/codingbat/recursion1/AllStar.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "17437" }, { "name": "C++", "bytes": "11260" }, { "name": "Groovy", "bytes": "130358" }, { "name": "Java", "bytes": "476415" }, { "name": "Kotlin", "bytes": "20657" }, { "name": "Python", "bytes": "27394" } ], "symlink_target": "" }
package org.zerograph.util; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.PropertyContainer; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Toolbox { public static boolean equalMaps(Map<String, Object> first, Map<String, Object> second) { if (first.size() == second.size()) { if (first.keySet().equals(second.keySet())) { for (String key : first.keySet()) { if (!first.get(key).equals(second.get(key))) return false; } return true; } else { return false; } } else { return false; } } public static Set<String> labelNameSet(Iterable<Label> labels) { HashSet<String> labelNameSet = new HashSet<>(); for (Label label : labels) { labelNameSet.add(label.name()); } return labelNameSet; } public static Map<String, Object> propertyMap(PropertyContainer entity) { HashMap<String, Object> propertyMap = new HashMap<>(); for (String key : entity.getPropertyKeys()) { propertyMap.put(key, entity.getProperty(key)); } return propertyMap; } public static boolean delete(File file) { File[] files = file.listFiles(); if (files != null) { for (File f : files) delete(f); } return file.delete(); } }
{ "content_hash": "352c010d0f7e48bf465d77c5168ca296", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 92, "avg_line_length": 28.12727272727273, "alnum_prop": 0.5565610859728507, "repo_name": "nigelsmall/zerograph", "id": "43a544ca4a239335607738edef4343943d26487e", "size": "1547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/server/java/org/zerograph/util/Toolbox.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1243" }, { "name": "Java", "bytes": "123988" }, { "name": "Python", "bytes": "88189" }, { "name": "Shell", "bytes": "6921" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Hugo 0.30.2" /> <title>Power - Let&#39;s See What Happens When We Take Away The Puppy</title> <meta property="og:title" content="Power - Let&#39;s See What Happens When We Take Away The Puppy"> <link href="/oliverclark.github.io/tags/power/index.xml" rel="alternate" type="application/rss+xml" title="Let&#39;s See What Happens When We Take Away The Puppy" /> <link rel="stylesheet" href="/oliverclark.github.io/css/fonts.css" media="all"> <link rel="stylesheet" href="/oliverclark.github.io/css/main.css" media="all"> </head> <body> <div class="wrapper"> <header class="header"> <nav class="nav"> <a href="/oliverclark.github.io/" class="nav-logo"> <img src="/oliverclark.github.io/images/puppa.JPG" width="50" height="50" alt="Logo"> </a> <ul class="nav-links"> <li><a href="/oliverclark.github.io/about/">About</a></li> <li><a href="https://github.com/olijimbo">GitHub</a></li> <li><a href="https://osf.io/rza9u/">OSF</a></li> <li><a href="https://twitter.com/PsyTechOli">Twitter</a></li> </ul> </nav> </header> <main class="content" role="main"> <div class="archive"> <h2 class="archive-title">2018</h2> <article class="archive-item"> <a href="/oliverclark.github.io/2018/11/22/dropping-t-bombs/" class="archive-item-link">Dropping T-bombs</a> <span class="archive-item-date"> 2018/11/22 </span> </article> </div> </main> <footer class="footer"> <ul class="footer-links"> <li> <a href="/oliverclark.github.io/index.xml" type="application/rss+xml" target="_blank">RSS feed</a> </li> <li> <a href="https://gohugo.io/" class="footer-links-kudos">Made with <img src="/oliverclark.github.io/images/hugo-logo.png" width="22" height="22"></a> </li> </ul> </footer> </div> </body> </html>
{ "content_hash": "6042b46cd6ebc6487a3c0698244f811b", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 165, "avg_line_length": 22.697916666666668, "alnum_prop": 0.5860486461679669, "repo_name": "OliJimbo/oliverclark.github.io", "id": "c37630653feb93435e5a0e8e291cd79e06d4de1e", "size": "2179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tags/power/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33544" }, { "name": "HTML", "bytes": "305284" }, { "name": "JavaScript", "bytes": "257837" } ], "symlink_target": "" }
import os import os.path import shutil import sys import tempfile from distutils import errors import commands C_PYTHON_DEV = """ #include <Python.h> int main(int argc, char **argv) { return 0; } """ C_PYTHON_DEV_ERROR_MESSAGE = """ Could not find <Python.h>. This could mean the following: * You're on Ubuntu and haven't run `apt-get install <PY_REPR>-dev`. * You're on RHEL/Fedora and haven't run `yum install <PY_REPR>-devel` or `dnf install <PY_REPR>-devel` (make sure you also have redhat-rpm-config installed) * You're on Mac OS X and the usual Python framework was somehow corrupted (check your environment variables or try re-installing?) * You're on Windows and your Python installation was somehow corrupted (check your environment variables or try re-installing?) """ if sys.version_info[0] == 2: PYTHON_REPRESENTATION = 'python' elif sys.version_info[0] == 3: PYTHON_REPRESENTATION = 'python3' else: raise NotImplementedError('Unsupported Python version: %s' % sys.version) C_CHECKS = { C_PYTHON_DEV: C_PYTHON_DEV_ERROR_MESSAGE.replace('<PY_REPR>', PYTHON_REPRESENTATION), } def _compile(compiler, source_string): tempdir = tempfile.mkdtemp() cpath = os.path.join(tempdir, 'a.c') with open(cpath, 'w') as cfile: cfile.write(source_string) try: compiler.compile([cpath]) except errors.CompileError as error: return error finally: shutil.rmtree(tempdir) def _expect_compile(compiler, source_string, error_message): if _compile(compiler, source_string) is not None: sys.stderr.write(error_message) raise commands.CommandError( "Diagnostics found a compilation environment issue:\n{}".format( error_message)) def diagnose_compile_error(build_ext, error): """Attempt to diagnose an error during compilation.""" for c_check, message in C_CHECKS.items(): _expect_compile(build_ext.compiler, c_check, message) python_sources = [ source for source in build_ext.get_source_files() if source.startswith('./src/python') and source.endswith('c') ] for source in python_sources: if not os.path.isfile(source): raise commands.CommandError(( "Diagnostics found a missing Python extension source file:\n{}\n\n" "This is usually because the Cython sources haven't been transpiled " "into C yet and you're building from source.\n" "Try setting the environment variable " "`GRPC_PYTHON_BUILD_WITH_CYTHON=1` when invoking `setup.py` or " "when using `pip`, e.g.:\n\n" "pip install -rrequirements.txt\n" "GRPC_PYTHON_BUILD_WITH_CYTHON=1 pip install .").format(source)) def diagnose_attribute_error(build_ext, error): if any('_needs_stub' in arg for arg in error.args): raise commands.CommandError( "We expect a missing `_needs_stub` attribute from older versions of " "setuptools. Consider upgrading setuptools.") _ERROR_DIAGNOSES = { errors.CompileError: diagnose_compile_error, AttributeError: diagnose_attribute_error, } def diagnose_build_ext_error(build_ext, error, formatted): diagnostic = _ERROR_DIAGNOSES.get(type(error)) if diagnostic is None: raise commands.CommandError( "\n\nWe could not diagnose your build failure. If you are unable to " "proceed, please file an issue at http://www.github.com/grpc/grpc " "with `[Python install]` in the title; please attach the whole log " "(including everything that may have appeared above the Python " "backtrace).\n\n{}".format(formatted)) else: diagnostic(build_ext, error)
{ "content_hash": "4e46b9ebe6475e31931b91483a571cb4", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 85, "avg_line_length": 36.63461538461539, "alnum_prop": 0.6587926509186351, "repo_name": "firebase/grpc", "id": "217f3cb9ed5db917e6a89b11673774484ca17f42", "size": "4388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/python/grpcio/support.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "5444" }, { "name": "Batchfile", "bytes": "35774" }, { "name": "C", "bytes": "3708933" }, { "name": "C#", "bytes": "2162951" }, { "name": "C++", "bytes": "12275592" }, { "name": "CMake", "bytes": "495117" }, { "name": "CSS", "bytes": "1519" }, { "name": "DTrace", "bytes": "147" }, { "name": "Dockerfile", "bytes": "169468" }, { "name": "Go", "bytes": "34794" }, { "name": "HTML", "bytes": "14" }, { "name": "Java", "bytes": "6259" }, { "name": "JavaScript", "bytes": "84355" }, { "name": "M4", "bytes": "69163" }, { "name": "Makefile", "bytes": "1104867" }, { "name": "Mako", "bytes": "5629" }, { "name": "Objective-C", "bytes": "696194" }, { "name": "Objective-C++", "bytes": "77574" }, { "name": "PHP", "bytes": "392133" }, { "name": "PowerShell", "bytes": "3226" }, { "name": "Python", "bytes": "3401091" }, { "name": "Ruby", "bytes": "982979" }, { "name": "Shell", "bytes": "532295" }, { "name": "Starlark", "bytes": "554304" }, { "name": "Swift", "bytes": "3516" }, { "name": "TSQL", "bytes": "4901" }, { "name": "XSLT", "bytes": "9846" } ], "symlink_target": "" }
#!/bin/bash #------------------------------------------------------------------------------- # Copyright 2017 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- echo "#################### Installing Grafana (running as BG process) ####################" touch /etc/profile.d/insightsenvvar.sh . /etc/environment . /etc/profile.d/insightsenvvar.sh cd /opt #sudo mkdir grafana #cd grafana read -p "Please enter Grafana version number you want to install(ex. 7.5.10 or 8.1.3): " version_number version_number=`echo $version_number | sed -e 's/^[[:space:]]*//'` sudo wget https://dl.grafana.com/oss/release/grafana-${version_number}.linux-amd64.tar.gz sudo tar -zxvf grafana-${version_number}.linux-amd64.tar.gz sudo mv /opt/grafana-${version_number} /opt/grafana cd /opt/grafana cd /opt wget https://github.com/CognizantOneDevOps/Insights/archive/refs/heads/master.zip -O Insightsrepo.zip sudo unzip Insightsrepo.zip sudo mkdir /opt/grafana/data/plugins sudo chmod -R 777 data sudo cp -r /opt/Insightsrepo/Insights-master/PlatformGrafanaPlugins/Panels/* /opt/grafana/data/plugins/ sudo cp -r /opt/Insightsrepo/Insights-master/PlatformGrafanaPlugins/DataSources/* /opt/grafana/data/plugins/ sudo rm -rf /opt/Insightsrepo/* cd /opt/grafana/public/dashboards wget https://raw.githubusercontent.com/CognizantOneDevOps/Insights/master/PlatformGrafanaPlugins/ScriptedDashboard/iSight_ui3.js cd /opt/grafana/conf wget https://raw.githubusercontent.com/CognizantOneDevOps/Insights/master/PlatformGrafanaPlugins/GrafanaConf/ldap.toml echo "Please provide postgres grafana user credentials" echo -n "credentials: " read grafanacreds sed -i "/type =/ s/=.*/=postgres/" defaults.ini sed -i "/host =/ s/=.*/=localhost:5432/" defaults.ini sed -i "/name =/ s/=.*/=grafana/" defaults.ini sed -i "/user =/ s/=.*/=grafana/" defaults.ini sed -i "/password =/ s/=.*/=$grafanacreds/" defaults.ini sed -i "/allow_loading_unsigned_plugins =/ s/=.*/=neo4j-datasource,Inference,cde-inference-plugin,cde-fusion-panel,cognizant-insights-charts/" defaults.ini sed -i "/allow_embedding =/ s/=.*/=true/" defaults.ini cd /opt/grafana export GRAFANA_HOME=`pwd` sudo echo GRAFANA_HOME=`pwd` | sudo tee -a /etc/environment sudo echo "export" GRAFANA_HOME=`pwd` | sudo tee -a /etc/profile.d/insightsenvvar.sh . /etc/environment . /etc/profile.d/insightsenvvar.sh sudo nohup ./bin/grafana-server & sudo echo $! > grafana-pid.txt sleep 10 sudo chmod -R 777 /opt/grafana cd /etc/init.d/ sudo wget https://raw.githubusercontent.com/CognizantOneDevOps/Insights/master/PlatformDeployment/RHEL8/initscripts/Grafana.sh sudo apt-get install -y dos2unix sudo dos2unix Grafana.sh sudo mv Grafana.sh Grafana sudo chmod +x Grafana sudo chkconfig Grafana on sleep 10 sudo service Grafana stop sudo service Grafana start
{ "content_hash": "8e0bc9b5c25380d4f13d64919e582d95", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 155, "avg_line_length": 45.10666666666667, "alnum_prop": 0.7194797516996748, "repo_name": "CognizantOneDevOps/Insights", "id": "752509c25a369c016e9c4376ab69f33900d16aee", "size": "3383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PlatformDeployment/UBUNTU/insights_grafana.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "93761" }, { "name": "CSS", "bytes": "362982" }, { "name": "Dockerfile", "bytes": "30938" }, { "name": "HTML", "bytes": "1118798" }, { "name": "Java", "bytes": "4099059" }, { "name": "JavaScript", "bytes": "39094" }, { "name": "Python", "bytes": "1518111" }, { "name": "SCSS", "bytes": "218059" }, { "name": "Shell", "bytes": "541300" }, { "name": "TypeScript", "bytes": "2097909" } ], "symlink_target": "" }
package org.apache.camel.dsl.yaml; import java.util.Map; import java.util.Objects; import org.apache.camel.CamelContextAware; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.builder.DeadLetterChannelBuilder; import org.apache.camel.builder.DefaultErrorHandlerBuilder; import org.apache.camel.builder.ErrorHandlerBuilder; import org.apache.camel.builder.NoErrorHandlerBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteConfigurationBuilder; import org.apache.camel.dsl.yaml.common.YamlDeserializerSupport; import org.apache.camel.dsl.yaml.deserializers.OutputAwareFromDefinition; import org.apache.camel.model.OnExceptionDefinition; import org.apache.camel.model.RouteConfigurationDefinition; import org.apache.camel.model.RouteDefinition; import org.apache.camel.model.RouteTemplateDefinition; import org.apache.camel.model.errorhandler.DefaultErrorHandlerProperties; import org.apache.camel.model.rest.RestConfigurationDefinition; import org.apache.camel.model.rest.RestDefinition; import org.apache.camel.model.rest.VerbDefinition; import org.apache.camel.spi.CamelContextCustomizer; import org.apache.camel.spi.annotations.RoutesLoader; import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.util.URISupport; import org.snakeyaml.engine.v2.nodes.MappingNode; import org.snakeyaml.engine.v2.nodes.Node; import org.snakeyaml.engine.v2.nodes.NodeTuple; import org.snakeyaml.engine.v2.nodes.NodeType; import org.snakeyaml.engine.v2.nodes.SequenceNode; import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asMap; import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asMappingNode; import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asSequenceNode; import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asText; import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.nodeAt; @ManagedResource(description = "Managed YAML RoutesBuilderLoader") @RoutesLoader(YamlRoutesBuilderLoader.EXTENSION) public class YamlRoutesBuilderLoader extends YamlRoutesBuilderLoaderSupport { public static final String EXTENSION = "yaml"; // API versions for Camel-K Integration and Kamelet Binding // we are lenient so lets just assume we can work with any of the v1 even if they evolve private static final String INTEGRATION_VERSION = "camel.apache.org/v1"; private static final String BINDING_VERSION = "camel.apache.org/v1"; private static final String STRIMZI_VERSION = "kafka.strimzi.io/v1"; public YamlRoutesBuilderLoader() { super(EXTENSION); } protected RouteBuilder builder(Node root) { return new RouteConfigurationBuilder() { @Override public void configure() throws Exception { Object target = preConfigureNode(root); if (target == null) { return; } if (target instanceof Node) { SequenceNode seq = asSequenceNode((Node) target); for (Node node : seq.getValue()) { Object item = getDeserializationContext().mandatoryResolve(node).construct(node); doConfigure(item); } } else { doConfigure(target); } } private void doConfigure(Object item) throws Exception { if (item instanceof OutputAwareFromDefinition) { RouteDefinition route = new RouteDefinition(); route.setInput(((OutputAwareFromDefinition) item).getDelegate()); route.setOutputs(((OutputAwareFromDefinition) item).getOutputs()); CamelContextAware.trySetCamelContext(getRouteCollection(), getCamelContext()); getRouteCollection().route(route); } else if (item instanceof RouteDefinition) { CamelContextAware.trySetCamelContext(getRouteCollection(), getCamelContext()); getRouteCollection().route((RouteDefinition) item); } else if (item instanceof CamelContextCustomizer) { ((CamelContextCustomizer) item).configure(getCamelContext()); } else if (item instanceof OnExceptionDefinition) { if (!getRouteCollection().getRoutes().isEmpty()) { throw new IllegalArgumentException( "onException must be defined before any routes in the RouteBuilder"); } CamelContextAware.trySetCamelContext(getRouteCollection(), getCamelContext()); getRouteCollection().getOnExceptions().add((OnExceptionDefinition) item); } else if (item instanceof ErrorHandlerBuilder) { if (!getRouteCollection().getRoutes().isEmpty()) { throw new IllegalArgumentException( "errorHandler must be defined before any routes in the RouteBuilder"); } errorHandler((ErrorHandlerBuilder) item); } else if (item instanceof RouteTemplateDefinition) { CamelContextAware.trySetCamelContext(getRouteTemplateCollection(), getCamelContext()); getRouteTemplateCollection().routeTemplate((RouteTemplateDefinition) item); } else if (item instanceof RestDefinition) { RestDefinition definition = (RestDefinition) item; for (VerbDefinition verb : definition.getVerbs()) { verb.setRest(definition); } CamelContextAware.trySetCamelContext(getRestCollection(), getCamelContext()); getRestCollection().rest(definition); } else if (item instanceof RestConfigurationDefinition) { ((RestConfigurationDefinition) item).asRestConfiguration( getCamelContext(), getCamelContext().getRestConfiguration()); } } @Override public void configuration() throws Exception { Object target = preConfigureNode(root); if (target == null) { return; } if (target instanceof Node) { SequenceNode seq = asSequenceNode((Node) target); for (Node node : seq.getValue()) { Object item = getDeserializationContext().mandatoryResolve(node).construct(node); doConfiguration(item); } } else { doConfiguration(target); } } private void doConfiguration(Object item) { if (item instanceof RouteConfigurationDefinition) { CamelContextAware.trySetCamelContext(getRouteConfigurationCollection(), getCamelContext()); getRouteConfigurationCollection().routeConfiguration((RouteConfigurationDefinition) item); } } }; } private Object preConfigureNode(Node root) throws Exception { Object target = root; // check if the yaml is a camel-k yaml with embedded binding/routes (called flow(s)) if (Objects.equals(root.getNodeType(), NodeType.MAPPING)) { final MappingNode mn = YamlDeserializerSupport.asMappingNode(root); // camel-k: integration boolean integration = anyTupleMatches(mn.getValue(), "apiVersion", v -> v.startsWith(INTEGRATION_VERSION)) && anyTupleMatches(mn.getValue(), "kind", "Integration"); // camel-k: kamelet binding are still at v1alpha1 boolean binding = anyTupleMatches(mn.getValue(), "apiVersion", v -> v.startsWith(BINDING_VERSION)) && anyTupleMatches(mn.getValue(), "kind", "KameletBinding"); if (integration) { target = preConfigureIntegration(root, target); } else if (binding) { target = preConfigureKameletBinding(root, target); } } return target; } /** * Camel K Integration file */ private Object preConfigureIntegration(Node root, Object target) { Node routes = nodeAt(root, "/spec/flows"); if (routes == null) { routes = nodeAt(root, "/spec/flow"); } if (routes != null) { target = routes; } return target; } /** * Camel K Kamelet Binding file */ private Object preConfigureKameletBinding(Node root, Object target) throws Exception { final RouteDefinition route = new RouteDefinition(); String routeId = asText(nodeAt(root, "/metadata/name")); if (routeId != null) { route.routeId(routeId); } // kamelet binding is a bit more complex, so grab the source and sink // and map those to Camel route definitions MappingNode source = asMappingNode(nodeAt(root, "/spec/source")); MappingNode sink = asMappingNode(nodeAt(root, "/spec/sink")); if (source != null && sink != null) { // source at the beginning (mandatory) String from = extractCamelEndpointUri(source); route.from(from); // steps in the middle (optional) Node steps = nodeAt(root, "/spec/steps"); if (steps != null) { SequenceNode sn = asSequenceNode(steps); for (Node node : sn.getValue()) { MappingNode step = asMappingNode(node); String uri = extractCamelEndpointUri(step); if (uri != null) { // if kamelet then use kamelet eip instead of to boolean kamelet = uri.startsWith("kamelet:"); if (kamelet) { uri = uri.substring(8); route.kamelet(uri); } else { route.to(uri); } } } } // sink is at the end (mandatory) String to = extractCamelEndpointUri(sink); route.to(to); // is there any error handler? MappingNode errorHandler = asMappingNode(nodeAt(root, "/spec/errorHandler")); if (errorHandler != null) { // there are 5 different error handlers, which one is it NodeTuple nt = errorHandler.getValue().get(0); String ehName = asText(nt.getKeyNode()); DefaultErrorHandlerProperties ehb = null; if ("dead-letter-channel".equals(ehName)) { DeadLetterChannelBuilder dlch = new DeadLetterChannelBuilder(); // endpoint MappingNode endpoint = asMappingNode(nodeAt(nt.getValueNode(), "/endpoint")); String dlq = extractCamelEndpointUri(endpoint); dlch.setDeadLetterUri(dlq); ehb = dlch; } else if ("log".equals(ehName)) { // log is the default error handler ehb = new DefaultErrorHandlerBuilder(); } else if ("none".equals(ehName)) { route.errorHandler(new NoErrorHandlerBuilder()); } else if ("bean".equals(ehName)) { throw new IllegalArgumentException("Bean error handler is not supported"); } else if ("ref".equals(ehName)) { throw new IllegalArgumentException("Ref error handler is not supported"); } // some error handlers support additional parameters if (ehb != null) { // properties that are general for all kind of error handlers MappingNode prop = asMappingNode(nodeAt(nt.getValueNode(), "/parameters")); Map<String, Object> params = asMap(prop); if (params != null) { PropertyBindingSupport.build() .withIgnoreCase(true) .withFluentBuilder(true) .withRemoveParameters(true) .withCamelContext(getCamelContext()) .withTarget(ehb) .withProperties(params) .bind(); } route.errorHandler(ehb); } } target = route; } return target; } private String extractCamelEndpointUri(MappingNode node) throws Exception { MappingNode mn = null; Node ref = nodeAt(node, "/ref"); if (ref != null) { mn = asMappingNode(ref); } // extract uri is different if kamelet or not boolean kamelet = mn != null && anyTupleMatches(mn.getValue(), "kind", "Kamelet"); boolean strimzi = !kamelet && mn != null && anyTupleMatches(mn.getValue(), "apiVersion", v -> v.startsWith(STRIMZI_VERSION)) && anyTupleMatches(mn.getValue(), "kind", "KafkaTopic"); String uri; if (kamelet || strimzi) { uri = extractTupleValue(mn.getValue(), "name"); } else { uri = extractTupleValue(node.getValue(), "uri"); } // properties MappingNode prop = asMappingNode(nodeAt(node, "/properties")); Map<String, Object> params = asMap(prop); if (params != null && !params.isEmpty()) { String query = URISupport.createQueryString(params); uri = uri + "?" + query; } if (kamelet) { return "kamelet:" + uri; } else if (strimzi) { return "kafka:" + uri; } else { return uri; } } }
{ "content_hash": "1b6e644b32479c26e3f414639585a3a5", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 124, "avg_line_length": 45.55591054313099, "alnum_prop": 0.5815975874886037, "repo_name": "pax95/camel", "id": "8952b531d5af40acec029455b22ef11c014be8f9", "size": "15061", "binary": false, "copies": "1", "ref": "refs/heads/CAMEL-17322", "path": "dsl/camel-yaml-dsl/camel-yaml-dsl/src/main/java/org/apache/camel/dsl/yaml/YamlRoutesBuilderLoader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "30373" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "54390" }, { "name": "HTML", "bytes": "190919" }, { "name": "Java", "bytes": "68575773" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "PLSQL", "bytes": "1419" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "323702" }, { "name": "Shell", "bytes": "17107" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "284638" } ], "symlink_target": "" }
using Microsoft.VisualStudio.TestTools.UnitTesting; using RAML.Parser; using System.Linq; using RAML.Parser.Model; namespace RAML.Parser.Tests { [TestClass] public class BankingAccountProcessTests { private AmfModel model; [TestInitialize] public void Initialize() { var parser = new RamlParser(); model = parser.Load("./specs/account-aggregation-process-api-2.0.0-raml/banking_accounts_process_api.raml").Result; } [TestMethod] public void Endpoints_should_be_2() { Assert.AreEqual(2, model.WebApi.EndPoints.Count()); } [TestMethod] public void Has_validations() { Assert.IsTrue(model.ValidationMessages.Count() > 0); Assert.IsTrue(model.Validates.HasValue && model.Validates.Value); } [TestMethod] public void should_include_shapes_in_uses() { Assert.AreEqual(39, model.Shapes.Count()); } } }
{ "content_hash": "eab164a1616749b6732c521605873105", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 127, "avg_line_length": 25.65, "alnum_prop": 0.5994152046783626, "repo_name": "raml-org/raml-dotnet-parser", "id": "2fdeba7ba10fd458232f059ae9cb045f70d540f3", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/RAML.Parser.Tests/BankingAccountProcessTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "92583" }, { "name": "Groovy", "bytes": "2212" }, { "name": "JavaScript", "bytes": "13410" }, { "name": "PowerShell", "bytes": "3137" }, { "name": "RAML", "bytes": "43213" } ], "symlink_target": "" }
from . import Request from pygithub3.resources.users import User from pygithub3.resources.repos import Repo class List(Request): uri = 'repos/{user}/{repo}/watchers' resource = User class List_repos(Request): uri = 'users/{user}/watched' resource = Repo def clean_uri(self): if not self.user: return 'user/watched' class Is_watching(Request): uri = 'user/watched/{user}/{repo}' class Watch(Request): uri = 'user/watched/{user}/{repo}' class Unwatch(Request): uri = 'user/watched/{user}/{repo}'
{ "content_hash": "11ebf5700e81bd0533b3d19f3b6404ba", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 42, "avg_line_length": 16.529411764705884, "alnum_prop": 0.6476868327402135, "repo_name": "bclay/teamtechdraft", "id": "46e01d7e66b407a709871c884a0cd282352df972", "size": "611", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "pygithub3/requests/repos/watchers.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "58" }, { "name": "JavaScript", "bytes": "3373" }, { "name": "Python", "bytes": "256748" }, { "name": "Shell", "bytes": "1549" } ], "symlink_target": "" }
package org.knowm.xchange.campbx.service; import org.knowm.xchange.Exchange; import org.knowm.xchange.campbx.CampBX; import org.knowm.xchange.service.BaseExchangeService; import org.knowm.xchange.service.BaseService; import org.knowm.xchange.utils.CertHelper; import si.mazi.rescu.ClientConfig; import si.mazi.rescu.RestProxyFactory; /** @author timmolter */ public class CampBXBaseService extends BaseExchangeService implements BaseService { protected final CampBX campBX; /** * Constructor * * @param exchange */ public CampBXBaseService(Exchange exchange) { super(exchange); ClientConfig config = getClientConfig(); // campbx server raises "internal error" if connected via these protocol versions config.setSslSocketFactory(CertHelper.createRestrictedSSLSocketFactory("TLSv1", "TLSv1.1")); this.campBX = RestProxyFactory.createProxy( CampBX.class, exchange.getExchangeSpecification().getSslUri(), config); } }
{ "content_hash": "aabb8a792ea478675acd9074fea49cdd", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 96, "avg_line_length": 29.727272727272727, "alnum_prop": 0.7594291539245668, "repo_name": "TSavo/XChange", "id": "c4b6c302e309dcb957a12072b804302616e52121", "size": "981", "binary": false, "copies": "7", "ref": "refs/heads/develop", "path": "xchange-campbx/src/main/java/org/knowm/xchange/campbx/service/CampBXBaseService.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "9299003" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.kinesis; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorSplit; import com.facebook.presto.spi.HostAddress; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; /** * * Kinesis vertion of ConnectorSplit. KinesisConnector fetch the data from kinesis stream and splits the big chunk to multiple split. * By default, one shard data is one KinesisSplit. * */ public class KinesisSplit implements ConnectorSplit { private final String connectorId; private final String streamName; private final String messageDataFormat; private final String shardId; private final String start; private final String end; private final ConnectorSession session; @JsonCreator public KinesisSplit( @JsonProperty("connectorId") String connectorId, @JsonProperty("session") ConnectorSession session, @JsonProperty("streamName") String streamName, @JsonProperty("messageDataFormat") String messageDataFormat, @JsonProperty("shardId") String shardId, @JsonProperty("start") String start, @JsonProperty("end") String end) { this.connectorId = checkNotNull(connectorId, "connector id is null"); this.session = checkNotNull(session, "connector session is null"); this.streamName = checkNotNull(streamName, "streamName is null"); this.messageDataFormat = checkNotNull(messageDataFormat, "messageDataFormat is null"); this.shardId = shardId; this.start = start; this.end = end; } @JsonProperty public String getConnectorId() { return connectorId; } @JsonProperty public ConnectorSession getSession() { return session; } @JsonProperty public String getStart() { return start; } @JsonProperty public String getEnd() { return end; } @JsonProperty public String getStreamName() { return streamName; } @JsonProperty public String getMessageDataFormat() { return messageDataFormat; } @JsonProperty public String getShardId() { return shardId; } @Override public boolean isRemotelyAccessible() { return true; } @Override public List<HostAddress> getAddresses() { return ImmutableList.of(); } @Override public Object getInfo() { return this; } @Override public String toString() { return toStringHelper(this) .add("connectorId", connectorId) .add("streamName", streamName) .add("messageDataFormat", messageDataFormat) .add("shardId", shardId) .add("start", start) .add("end", end) .toString(); } }
{ "content_hash": "64dc033ee907e5492bf7559f514a28a9", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 133, "avg_line_length": 27.441176470588236, "alnum_prop": 0.6631832797427653, "repo_name": "buremba/presto-kinesis", "id": "a7ec25cb2a0988d5547c4bcb4f31c152ad5cdff7", "size": "3732", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/facebook/presto/kinesis/KinesisSplit.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "235532" } ], "symlink_target": "" }
classdef TaskNoPlatformCameraPersonSize<Task % Task to test camera parameters assertions % % TaskNoPlatformCamera methods: % init() - loads and returns the parameters for the various simulation objects % reset() - defines the starting state for the task % updateReward() - updates the running costs (zero for this task) % reward() - computes the final reward for this task % step() - computes pitch, roll, yaw, throttle commands from the user dVn,dVe commands % properties (Constant) numUAVs = 1; startHeight = -25; durationInSteps = 200; PENALTY = 1000; % penalty reward in case of collision end properties (Access=public) prngId; % id of the prng stream used to select the initial positions velPIDs; % pid used to control the uavs initialX; end methods (Sealed,Access=public) function obj = TaskNoPlatformCameraPersonSize(state) obj = obj@Task(state); end function taskparams=init(obj) % loads and returns the parameters for the various simulation objects % % Example: % params = obj.init(); % params - the task parameters % taskparams.dt = 1; % task timestep i.e. rate at which controls % are supplied and measurements are received taskparams.seed = 0; % set to zero to have a seed that depends on the system time %%%%% visualization %%%%% % 3D display parameters taskparams.display3d.on = 0; taskparams.display3d.width = 1000; taskparams.display3d.height = 600; %%%%% environment %%%%% % these need to follow the conventions of axis(), they are in m, Z down % note that the lowest Z limit is the refence for the computation of wind shear and turbulence effects taskparams.environment.area.limits = [-50 50 -50 50 -80 0]; taskparams.environment.area.dt = 1; taskparams.environment.area.type = 'BoxWithPersonsArea'; % originutmcoords is the location of the RVC (our usual flying site) % generally when this is changed gpsspacesegment.orbitfile and % gpsspacesegment.svs need to be changed [E N zone h] = llaToUtm([51.71190;-0.21052;0]); taskparams.environment.area.originutmcoords.E = E; taskparams.environment.area.originutmcoords.N = N; taskparams.environment.area.originutmcoords.h = h; taskparams.environment.area.originutmcoords.zone = zone; taskparams.environment.area.numpersonsrange = [2,2]; % number of person selected at random between these limits taskparams.environment.area.personfounddistancethreshold = 2; taskparams.environment.area.personfoundspeedthreshold = 0.1; % GPS % The space segment of the gps system taskparams.environment.gpsspacesegment.on = 0; %% NO GPS NOISE!!! taskparams.environment.gpsspacesegment.dt = 0.2; % real satellite orbits from NASA JPL taskparams.environment.gpsspacesegment.orbitfile = 'ngs15992_16to17.sp3'; % simulation start in GPS time, this needs to agree with the sp3 file above, % alternatively it can be set to 0 to have a random initialization %taskparams.environment.gpsspacesegment.tStart = Orbits.parseTime(2010,8,31,16,0,0); taskparams.environment.gpsspacesegment.tStart = 0; % id number of visible satellites, the one below are from a typical flight day at RVC % these need to match the contents of gpsspacesegment.orbitfile taskparams.environment.gpsspacesegment.svs = [3,5,6,7,13,16,18,19,20,22,24,29,31]; % the following model is from [2] %taskparams.environment.gpsspacesegment.type = 'GPSSpaceSegmentGM'; %taskparams.environment.gpsspacesegment.PR_BETA = 2000; % process time constant %taskparams.environment.gpsspacesegment.PR_SIGMA = 0.1746; % process standard deviation % the following model was instead designed to match measurements of real % data, it appears more relistic than the above taskparams.environment.gpsspacesegment.type = 'GPSSpaceSegmentGM2'; taskparams.environment.gpsspacesegment.PR_BETA2 = 4; % process time constant taskparams.environment.gpsspacesegment.PR_BETA1 = 1.005; % process time constant taskparams.environment.gpsspacesegment.PR_SIGMA = 0.003; % process standard deviation % Wind % i.e. a steady omogeneous wind with a direction and magnitude % this is common to all helicopters taskparams.environment.wind.on = 0; %% NO WIND!!! taskparams.environment.wind.type = 'WindConstMean'; taskparams.environment.wind.direction = degsToRads(45); %mean wind direction, rad clockwise from north set to [] to initialise it randomly taskparams.environment.wind.W6 = 0.5; % velocity at 6m from ground in m/s %%%%% platforms %%%%% % Configuration and initial state for each of the platforms for i=1:obj.numUAVs, taskparams.platforms(i).configfile = 'pelican_with_camera_ok'; end end function reset(obj) % uav randomly placed, but not too close to the edges of the area for i=1:obj.numUAVs, r = rand(obj.simState.rStreams{obj.prngId},2,1); l = obj.simState.environment.area.getLimits(); px = 0.5*(l(2)+l(1)) + (r(1)-0.5)*0.9*(l(2)-l(1)); py = 0.5*(l(4)+l(3)) + (r(2)-0.5)*0.9*(l(4)-l(3)); obj.simState.platforms{i}.setX([px;py;obj.startHeight;0;0;0]); obj.initialX{i} = obj.simState.platforms{i}.getX(); obj.velPIDs{i} = VelocityHeightPID(obj.simState.DT); end % persons randomly placed, but not too close to the edges of the area obj.simState.environment.area.reset(); end function UU = step(obj,U) % compute the UAVs controls from the velocity inputs UU=zeros(5,length(obj.simState.platforms)); for i=1:length(obj.simState.platforms), if(obj.simState.platforms{i}.isValid()) UU(:,i) = obj.velPIDs{i}.computeU(obj.simState.platforms{i}.getEX(),U(:,i),obj.startHeight,0); else UU(:,i) = obj.velPIDs{i}.computeU(obj.simState.platforms{i}.getEX(),[0;0],obj.startHeight,0); end end end function updateReward(~,~) % updates reward end function r=reward(obj) % returns the total reward for this task % in this case simply the sum of the squared distances of the % cats to the mouse (multiplied by -1) valid = 1; for i=1:length(obj.simState.platforms) valid = valid && obj.simState.platforms{i}.isValid(); end if(valid) justFound = obj.simState.environment.area.getPersonsJustFound(); r = sum(sum(justFound)); r = obj.currentReward + r; else % returning a large penalty in case the state is not valid % i.e. one the helicopters is out of the area, there was a % collision or one of the helicoptera has crashed r = - obj.PENALTY; end end end end
{ "content_hash": "64218e169c85c859adcbe8c05c4059b1", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 150, "avg_line_length": 48.088235294117645, "alnum_prop": 0.572354740061162, "repo_name": "UCL-CompLACS/qrsim", "id": "cd5cc8f2f11998ce4eac8d0447ab6cfd6abf2a3c", "size": "8175", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/assert/TaskNoPlatformCameraPersonSize.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "38977" }, { "name": "C++", "bytes": "34935" }, { "name": "Java", "bytes": "4907" }, { "name": "M", "bytes": "236788" }, { "name": "Matlab", "bytes": "1526777" }, { "name": "Objective-C", "bytes": "961" }, { "name": "TeX", "bytes": "160387" } ], "symlink_target": "" }
package sample.insurance.pageobjects; import com.borland.silktest.jtf.common.TruelogScreenshotMode; import com.borland.silktest.jtf.common.types.FindOptions; import com.borland.silktest.jtf.xbrowser.DomButton; import com.borland.silktest.jtf.xbrowser.DomElement; import com.borland.silktest.jtf.xbrowser.DomTextField; public class HomePage extends InsuranceMainPage { private final String locLogoutBtn = "//INPUT[@id='logout-form:logout']"; private final String locEMailTxt = "Web.Login.EMail"; private final String locPasswordTxt = "Web.Login.Password"; private final String locLoginBtn = "Web.Login.Login"; public HomePage() { super(); } public HomePage login(String username, String password) { DomButton logout = browserWindow.<DomButton>find(locLogoutBtn, new FindOptions(false, 500)); if (logout != null) logout.select(); desktop.<DomTextField>find(locEMailTxt).setText(username); desktop.<DomTextField>find(locPasswordTxt).setText(password); desktop.logInfo("Login", TruelogScreenshotMode.ActiveWindow); desktop.<DomButton>find(locLoginBtn).select(); desktop.logInfo("Logged In", TruelogScreenshotMode.ActiveWindow); return this; } public String getUserName() { DomElement userName = browserWindow.<DomElement> find( "//LABEL[@class='login' and @for='logout-form']", new FindOptions(false, 500)); if (userName != null) return userName.getText(); return ""; } public HomePage logout() { DomButton logout = browserWindow.<DomButton>find(locLogoutBtn, new FindOptions(false, 500)); if (logout != null) logout.select(); return this; } }
{ "content_hash": "8feb25fb4d30c9c979ac6e0054202218", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 94, "avg_line_length": 30.471698113207548, "alnum_prop": 0.74984520123839, "repo_name": "MicroFocus/InsuranceWeb-Testing", "id": "64c6a30df3babed88e75e07a8650a7b5d6e6be85", "size": "1761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Silk4J/src/sample/insurance/pageobjects/HomePage.java", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8803" }, { "name": "Java", "bytes": "24988" }, { "name": "SourcePawn", "bytes": "2834" }, { "name": "Terra", "bytes": "2841" } ], "symlink_target": "" }
layout: post date: 2017-02-13 title: "Jovani Grey Trumpet Dress 26506 Short Sleeves Floor-Length Mermaid/Trumpet" category: Jovani tags: [Jovani ,Jovani,Mermaid/Trumpet,V-neck,Floor-Length,Short Sleeves] --- ### Jovani Grey Trumpet Dress 26506 Just **$406.98** ### Short Sleeves Floor-Length Mermaid/Trumpet <table><tr><td>BRANDS</td><td>Jovani</td></tr><tr><td>Silhouette</td><td>Mermaid/Trumpet</td></tr><tr><td>Neckline</td><td>V-neck</td></tr><tr><td>Hemline/Train</td><td>Floor-Length</td></tr><tr><td>Sleeve</td><td>Short Sleeves</td></tr></table> <a href="https://www.readybrides.com/en/jovani-/39785-jovani-grey-trumpet-dress-26506.html"><img src="//img.readybrides.com/85821/jovani-grey-trumpet-dress-26506.jpg" alt="Jovani Grey Trumpet Dress 26506" style="width:100%;" /></a> <!-- break --><a href="https://www.readybrides.com/en/jovani-/39785-jovani-grey-trumpet-dress-26506.html"><img src="//img.readybrides.com/85822/jovani-grey-trumpet-dress-26506.jpg" alt="Jovani Grey Trumpet Dress 26506" style="width:100%;" /></a> <a href="https://www.readybrides.com/en/jovani-/39785-jovani-grey-trumpet-dress-26506.html"><img src="//img.readybrides.com/85820/jovani-grey-trumpet-dress-26506.jpg" alt="Jovani Grey Trumpet Dress 26506" style="width:100%;" /></a> Buy it: [https://www.readybrides.com/en/jovani-/39785-jovani-grey-trumpet-dress-26506.html](https://www.readybrides.com/en/jovani-/39785-jovani-grey-trumpet-dress-26506.html)
{ "content_hash": "53b19d7b6b396cec46ecf553ff5274db", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 245, "avg_line_length": 96.26666666666667, "alnum_prop": 0.731994459833795, "repo_name": "novstylessee/novstylessee.github.io", "id": "9eab04cd59edb7ee3f790e797e566e3147d2279b", "size": "1448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-02-13-Jovani-Grey-Trumpet-Dress-26506-Short-Sleeves-FloorLength-MermaidTrumpet.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "83876" }, { "name": "HTML", "bytes": "14755" }, { "name": "Ruby", "bytes": "897" } ], "symlink_target": "" }
require 'ansible/ruby/modules/base' module Ansible module Ruby module Modules # Manages members in a device group. Members in a device group can only be added or removed, never updated. This is because the members are identified by unique name values and changing that name would invalidate the uniqueness. class Bigip_device_group_member < Base # @return [String] Specifies the name of the device that you want to add to the device group. Often this will be the hostname of the device. This member must be trusted by the device already. Trusting can be done with the C(bigip_device_trust) module and the C(peer_hostname) option to that module. attribute :name validates :name, presence: true, type: String # @return [String] The device group that you want to add the member to. attribute :device_group validates :device_group, presence: true, type: String # @return [:present, :absent, nil] When C(present), ensures that the device group member exists.,When C(absent), ensures the device group member is removed. attribute :state validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true end end end end
{ "content_hash": "ad48f549dafaf7e67f2b2220796de2b4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 306, "avg_line_length": 58.54545454545455, "alnum_prop": 0.7104037267080745, "repo_name": "wied03/ansible-ruby", "id": "bdcc21d9af7b1f177c7dbb63c8b143efd7a7f20f", "size": "1391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ansible/ruby/modules/generated/network/f5/bigip_device_group_member.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "180" }, { "name": "Ruby", "bytes": "5807644" } ], "symlink_target": "" }
FROM ubuntu:14.04 MAINTAINER Matias Carrasco Kind <[email protected]> MAINTAINER Matias Carrasco Kind <[email protected]> ENV HOME /root ENV SHELL /bin/bash RUN apt-get update && apt-get -y upgrade RUN apt-get install -y git nano git curl nano wget dialog net-tools build-essential vim unzip libaio1 RUN apt-get install -y python RUN apt-get install -y python-pip python-dev build-essential RUN apt-get install -y python-numpy python-matplotlib python-scipy RUN pip install --upgrade pip RUN apt-get install -y build-essential openssl libssl-dev pkg-config RUN apt-get install -y nodejs RUN apt-get install -y npm RUN apt-get install -y graphviz RUN sudo apt-get install -y g++ flex bison gperf ruby perl libsqlite3-dev libfontconfig1-dev libicu-dev libfreetype6 libssl-dev libpng-dev libjpeg-dev libx11-dev libxext-dev RUN apt-get install nodejs-legacy #Phantom.js RUN git clone git://github.com/ariya/phantomjs.git RUN cd /phantomjs WORKDIR /phantomjs RUN git checkout 2.0 RUN ./build.sh --confirm RUN cp /phantomjs/bin/phantomjs /usr/bin/phantomjs EXPOSE 80 RUN mkdir -p /test WORKDIR /test RUN cd /test RUN echo 'new' RUN git clone https://github.com/mgckind/GraphMaker.git WORKDIR /test/GraphMaker RUN cd /test/GraphMaker RUN cd /test/GraphMaker/test_socket WORKDIR /test/GraphMaker/test_socket RUN npm install CMD ["node","graphmaker.js"]
{ "content_hash": "f6e6edb51b57d533e5eb4ae0c65e8262", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 174, "avg_line_length": 28.354166666666668, "alnum_prop": 0.7803085966201323, "repo_name": "tcaron/exampleJointJS", "id": "d60139326672839c7340184c3ad0fc1a1bf57adf", "size": "1384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "custom_edit/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34826" }, { "name": "HTML", "bytes": "162680" }, { "name": "JavaScript", "bytes": "3737274" }, { "name": "Python", "bytes": "16377" } ], "symlink_target": "" }
#include "platform/openthread-posix-config.h" #include <openthread/config.h> #include <assert.h> #include <errno.h> #include <getopt.h> #include <libgen.h> #include <setjmp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <unistd.h> #ifdef __linux__ #include <sys/prctl.h> #endif #ifndef HAVE_LIBEDIT #define HAVE_LIBEDIT 0 #endif #ifndef HAVE_LIBREADLINE #define HAVE_LIBREADLINE 0 #endif #include <openthread/cli.h> #include <openthread/diag.h> #include <openthread/logging.h> #include <openthread/tasklet.h> #include <openthread/thread.h> #include <openthread/platform/radio.h> #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE #include <openthread/cli.h> #include "cli/cli_config.h" #endif #include <common/code_utils.hpp> #include <lib/platform/exit_code.h> #include <openthread/openthread-system.h> #include <openthread/platform/misc.h> #include "lib/platform/reset_util.h" /** * This function initializes NCP app. * * @param[in] aInstance A pointer to the OpenThread instance. * */ void otAppNcpInit(otInstance *aInstance); /** * This function deinitializes NCP app. * */ void otAppNcpUpdate(otSysMainloopContext *aContext); /** * This function updates the file descriptor sets with file descriptors used by console. * * @param[in,out] aMainloop A pointer to the mainloop context. * */ void otAppNcpProcess(const otSysMainloopContext *aContext); /** * This function initializes CLI app. * * @param[in] aInstance A pointer to the OpenThread instance. * */ void otAppCliInit(otInstance *aInstance); /** * This function deinitializes CLI app. * */ void otAppCliDeinit(void); /** * This function updates the file descriptor sets with file descriptors used by console. * * @param[in,out] aMainloop A pointer to the mainloop context. * */ void otAppCliUpdate(otSysMainloopContext *aMainloop); /** * This function performs console driver processing. * * @param[in] aMainloop A pointer to the mainloop context. * */ void otAppCliProcess(const otSysMainloopContext *aMainloop); typedef struct PosixConfig { otPlatformConfig mPlatformConfig; ///< Platform configuration. otLogLevel mLogLevel; ///< Debug level of logging. bool mPrintRadioVersion; ///< Whether to print radio firmware version. bool mIsVerbose; ///< Whether to print log to stderr. } PosixConfig; /** * This enumeration defines the argument return values. * */ enum { OT_POSIX_OPT_BACKBONE_INTERFACE_NAME = 'B', OT_POSIX_OPT_DEBUG_LEVEL = 'd', OT_POSIX_OPT_DRY_RUN = 'n', OT_POSIX_OPT_HELP = 'h', OT_POSIX_OPT_INTERFACE_NAME = 'I', OT_POSIX_OPT_TIME_SPEED = 's', OT_POSIX_OPT_VERBOSE = 'v', OT_POSIX_OPT_SHORT_MAX = 128, OT_POSIX_OPT_RADIO_VERSION, OT_POSIX_OPT_REAL_TIME_SIGNAL, }; static const struct option kOptions[] = { {"backbone-interface-name", required_argument, NULL, OT_POSIX_OPT_BACKBONE_INTERFACE_NAME}, {"debug-level", required_argument, NULL, OT_POSIX_OPT_DEBUG_LEVEL}, {"dry-run", no_argument, NULL, OT_POSIX_OPT_DRY_RUN}, {"help", no_argument, NULL, OT_POSIX_OPT_HELP}, {"interface-name", required_argument, NULL, OT_POSIX_OPT_INTERFACE_NAME}, {"radio-version", no_argument, NULL, OT_POSIX_OPT_RADIO_VERSION}, {"real-time-signal", required_argument, NULL, OT_POSIX_OPT_REAL_TIME_SIGNAL}, {"time-speed", required_argument, NULL, OT_POSIX_OPT_TIME_SPEED}, {"verbose", no_argument, NULL, OT_POSIX_OPT_VERBOSE}, {0, 0, 0, 0}}; static void PrintUsage(const char *aProgramName, FILE *aStream, int aExitCode) { fprintf(aStream, "Syntax:\n" " %s [Options] RadioURL [RadioURL]\n" "Options:\n" " -B --backbone-interface-name Backbone network interface name.\n" " -d --debug-level Debug level of logging.\n" " -h --help Display this usage information.\n" " -I --interface-name name Thread network interface name.\n" " -n --dry-run Just verify if arguments is valid and radio spinel is compatible.\n" " --radio-version Print radio firmware version.\n" " -s --time-speed factor Time speed up factor.\n" " -v --verbose Also log to stderr.\n", aProgramName); #ifdef __linux__ fprintf(aStream, " --real-time-signal (Linux only) The real-time signal number for microsecond timer.\n" " Use +N for relative value to SIGRTMIN, and use N for absolute value.\n"); #endif fprintf(aStream, "%s", otSysGetRadioUrlHelpString()); exit(aExitCode); } static void ParseArg(int aArgCount, char *aArgVector[], PosixConfig *aConfig) { memset(aConfig, 0, sizeof(*aConfig)); aConfig->mPlatformConfig.mSpeedUpFactor = 1; aConfig->mLogLevel = OT_LOG_LEVEL_CRIT; #ifdef __linux__ aConfig->mPlatformConfig.mRealTimeSignal = SIGRTMIN; #endif optind = 1; while (true) { int index = 0; int option = getopt_long(aArgCount, aArgVector, "B:d:hI:ns:v", kOptions, &index); if (option == -1) { break; } switch (option) { case OT_POSIX_OPT_DEBUG_LEVEL: aConfig->mLogLevel = (otLogLevel)atoi(optarg); break; case OT_POSIX_OPT_HELP: PrintUsage(aArgVector[0], stdout, OT_EXIT_SUCCESS); break; case OT_POSIX_OPT_INTERFACE_NAME: aConfig->mPlatformConfig.mInterfaceName = optarg; break; case OT_POSIX_OPT_BACKBONE_INTERFACE_NAME: aConfig->mPlatformConfig.mBackboneInterfaceName = optarg; break; case OT_POSIX_OPT_DRY_RUN: aConfig->mPlatformConfig.mDryRun = true; break; case OT_POSIX_OPT_TIME_SPEED: { char *endptr = NULL; aConfig->mPlatformConfig.mSpeedUpFactor = (uint32_t)strtol(optarg, &endptr, 0); if (*endptr != '\0' || aConfig->mPlatformConfig.mSpeedUpFactor == 0) { fprintf(stderr, "Invalid value for TimerSpeedUpFactor: %s\n", optarg); exit(OT_EXIT_INVALID_ARGUMENTS); } break; } case OT_POSIX_OPT_VERBOSE: aConfig->mIsVerbose = true; break; case OT_POSIX_OPT_RADIO_VERSION: aConfig->mPrintRadioVersion = true; break; #ifdef __linux__ case OT_POSIX_OPT_REAL_TIME_SIGNAL: if (optarg[0] == '+') { aConfig->mPlatformConfig.mRealTimeSignal = SIGRTMIN + atoi(&optarg[1]); } else { aConfig->mPlatformConfig.mRealTimeSignal = atoi(optarg); } break; #endif // __linux__ case '?': PrintUsage(aArgVector[0], stderr, OT_EXIT_INVALID_ARGUMENTS); break; default: assert(false); break; } } for (; optind < aArgCount; optind++) { VerifyOrDie(aConfig->mPlatformConfig.mRadioUrlNum < OT_ARRAY_LENGTH(aConfig->mPlatformConfig.mRadioUrls), OT_EXIT_INVALID_ARGUMENTS); aConfig->mPlatformConfig.mRadioUrls[aConfig->mPlatformConfig.mRadioUrlNum++] = aArgVector[optind]; } if (aConfig->mPlatformConfig.mRadioUrlNum == 0) { PrintUsage(aArgVector[0], stderr, OT_EXIT_INVALID_ARGUMENTS); } } static otInstance *InitInstance(PosixConfig *aConfig) { otInstance *instance = NULL; syslog(LOG_INFO, "Running %s", otGetVersionString()); syslog(LOG_INFO, "Thread version: %hu", otThreadGetVersion()); IgnoreError(otLoggingSetLevel(aConfig->mLogLevel)); instance = otSysInit(&aConfig->mPlatformConfig); VerifyOrDie(instance != NULL, OT_EXIT_FAILURE); syslog(LOG_INFO, "Thread interface: %s", otSysGetThreadNetifName()); if (aConfig->mPrintRadioVersion) { printf("%s\n", otPlatRadioGetVersionString(instance)); } else { syslog(LOG_INFO, "RCP version: %s", otPlatRadioGetVersionString(instance)); } if (aConfig->mPlatformConfig.mDryRun) { exit(OT_EXIT_SUCCESS); } return instance; } void otTaskletsSignalPending(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); } void otPlatReset(otInstance *aInstance) { OT_UNUSED_VARIABLE(aInstance); gPlatResetReason = OT_PLAT_RESET_REASON_SOFTWARE; otSysDeinit(); longjmp(gResetJump, 1); assert(false); } static void ProcessNetif(void *aContext, uint8_t aArgsLength, char *aArgs[]) { OT_UNUSED_VARIABLE(aContext); OT_UNUSED_VARIABLE(aArgsLength); OT_UNUSED_VARIABLE(aArgs); otCliOutputFormat("%s:%u\r\n", otSysGetThreadNetifName(), otSysGetThreadNetifIndex()); } #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE static void ProcessExit(void *aContext, uint8_t aArgsLength, char *aArgs[]) { OT_UNUSED_VARIABLE(aContext); OT_UNUSED_VARIABLE(aArgsLength); OT_UNUSED_VARIABLE(aArgs); exit(EXIT_SUCCESS); } #endif static const otCliCommand kCommands[] = { #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE {"exit", ProcessExit}, #endif {"netif", ProcessNetif}, }; int main(int argc, char *argv[]) { otInstance *instance; int rval = 0; PosixConfig config; #ifdef __linux__ // Ensure we terminate this process if the // parent process dies. prctl(PR_SET_PDEATHSIG, SIGHUP); #endif OT_SETUP_RESET_JUMP(argv); ParseArg(argc, argv, &config); openlog(argv[0], LOG_PID | (config.mIsVerbose ? LOG_PERROR : 0), LOG_DAEMON); setlogmask(setlogmask(0) & LOG_UPTO(LOG_DEBUG)); instance = InitInstance(&config); #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE otAppCliInit(instance); #endif otCliSetUserCommands(kCommands, OT_ARRAY_LENGTH(kCommands), instance); while (true) { otSysMainloopContext mainloop; otTaskletsProcess(instance); FD_ZERO(&mainloop.mReadFdSet); FD_ZERO(&mainloop.mWriteFdSet); FD_ZERO(&mainloop.mErrorFdSet); mainloop.mMaxFd = -1; mainloop.mTimeout.tv_sec = 10; mainloop.mTimeout.tv_usec = 0; #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE otAppCliUpdate(&mainloop); #endif otSysMainloopUpdate(instance, &mainloop); if (otSysMainloopPoll(&mainloop) >= 0) { otSysMainloopProcess(instance, &mainloop); #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE otAppCliProcess(&mainloop); #endif } else if (errno != EINTR) { perror("select"); ExitNow(rval = OT_EXIT_FAILURE); } } #if !OPENTHREAD_POSIX_CONFIG_DAEMON_ENABLE otAppCliDeinit(); #endif exit: otSysDeinit(); return rval; }
{ "content_hash": "529be35c7f091f0ed1651de96f3c192a", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 120, "avg_line_length": 28.134177215189872, "alnum_prop": 0.6217942949698552, "repo_name": "abtink/openthread", "id": "df014ea5fd0ea9ad6b2f47ced20ee101806dd663", "size": "12721", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/posix/main.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "2295" }, { "name": "C", "bytes": "1554371" }, { "name": "C++", "bytes": "8051010" }, { "name": "CMake", "bytes": "106238" }, { "name": "Dockerfile", "bytes": "5901" }, { "name": "M4", "bytes": "32606" }, { "name": "Makefile", "bytes": "189483" }, { "name": "Python", "bytes": "4542699" }, { "name": "Shell", "bytes": "161238" } ], "symlink_target": "" }
module EpubForge module Action class Epub < Action2 define_action( "epub" ) do |action| # include_standard_options action.help( "Create ebooks in various formats from the .markdown files in the project's book/ and notes/ subdirectories." ) # keyword( "forge" ) # desc( "forge", "Wraps the project up in a .epub (ebook) file.") action.execute do epub_common( "book" ) end end define_action( "epub:notes" ) do |action| action.help( "Create ebooks for your story bible, instead of your main book" ) action.execute do epub_common( "notes" ) end end define_action( "epub:unzip" ) do |action| action.help( "Unzip your generated .epub file into a temporary directory." ) action.execute do @book = @project.filename_for_book.ext("epub") create_book_if_needed raise "Error unzipping epub: No ebook at #{@book}" unless @book.file? tmpdir = @book.dirname.join("tmp").timestamp.touch_dir `unzip #{@book} -d #{tmpdir}` end end protected def epub_common( target, opts = {} ) # opts[:page_order] ||= project.config["pages"][target] case target when "book" opts[:book_dir] ||= project.book_dir outfile = opts.delete(:outfile) || project.filename_for_book.ext("epub") when "notes" opts[:book_dir] ||= project.notes_dir outfile = opts.delete(:outfile) || project.filename_for_notes.ext("epub") else # Hope the caller knows what it's doing. opts[:book_dir] ||= project.book_dir.up.join( target ) outfile = opts.delete(:outfile) || project.root_dir.join( "#{project.default_project_basename}.#{target}.epub" ) end opts[:verbose] = verbose? builder = EpubForge::Builder::Epub.new( project, opts ) builder.build builder.package( outfile ) builder.clean say_all_is_well( "Done building epub <#{outfile}>" ) end def create_book_if_needed unless @book.file? Runner.new.exec( "epub", @project.root_dir ) end end end end end
{ "content_hash": "9886cfa40895e70b10633f62ea730cb0", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 132, "avg_line_length": 33.02857142857143, "alnum_prop": 0.5618512110726643, "repo_name": "darthschmoo/epubforge", "id": "14eddd8164d4b845f39fd18905c30f9ed69d0ffc", "size": "2312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/actions/epub.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "142" }, { "name": "Ruby", "bytes": "138446" } ], "symlink_target": "" }
@interface LQModelMiaoShaJiLu : NSObject @property (nonatomic, strong) LQModelProductDetail *period; @end
{ "content_hash": "8271d732280b785edcbda1c831a19b86", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 59, "avg_line_length": 18.166666666666668, "alnum_prop": 0.7981651376146789, "repo_name": "daqiangge/ZhengFengDuoMiao", "id": "0ab0e2086d4acf94ef55c825ff105ac93b705b70", "size": "281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MiaoSha/MiaoSha/MainClass/Me(我)/M/LQModelMiaoShaJiLu.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "32476" }, { "name": "DTrace", "bytes": "412" }, { "name": "Java", "bytes": "33216" }, { "name": "Objective-C", "bytes": "2397891" }, { "name": "Ruby", "bytes": "495" }, { "name": "Shell", "bytes": "9296" }, { "name": "Swift", "bytes": "227386" } ], "symlink_target": "" }
from rest_framework.response import Response from rest_framework.decorators import api_view from app.serializers.heroes_serializer import HeroesSerializer from app.services.heroes_service import get_heroes @api_view() #pylint: disable=unused-argument def heroes_list(request): serializer = HeroesSerializer(get_heroes()) return Response(serializer.data)
{ "content_hash": "ab3d37c9dcc85e287838f6d8dd70d23d", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 62, "avg_line_length": 33.09090909090909, "alnum_prop": 0.8104395604395604, "repo_name": "lucashanke/houseofdota", "id": "053f3badfc4264aa7b4200643dc79351747e9e5b", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/api/heroes_view.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6664" }, { "name": "Clojure", "bytes": "4254" }, { "name": "HTML", "bytes": "1914" }, { "name": "JavaScript", "bytes": "69894" }, { "name": "Python", "bytes": "120362" } ], "symlink_target": "" }