text
stringlengths
2
1.04M
meta
dict
package dk.statsbiblioteket.summa.common.util; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.util.Timing; import org.junit.Test; import static org.junit.Assert.*; /* * 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. * */ public class TestStatUtil { @Test public void testConfigStats() { Configuration conf = Configuration.newMemoryBased( "foo." + StatUtil.CONF_TIMING_STATS, "name, utilization" ); Timing timing = StatUtil.createTiming(conf, "foo", "bar", null, "zoo", null); timing.addMS(100); System.out.println(timing.toString()); } }
{ "content_hash": "9ba512ecdb54a74589b9e07213879c36", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 85, "avg_line_length": 33.6, "alnum_prop": 0.7049319727891157, "repo_name": "statsbiblioteket/summa", "id": "d2ccac609a750dd09e4673b12cd0ca962139fe61", "size": "1176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/src/test/java/dk/statsbiblioteket/summa/common/util/TestStatUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7987" }, { "name": "CSS", "bytes": "26332" }, { "name": "HTML", "bytes": "18963" }, { "name": "Java", "bytes": "8345964" }, { "name": "JavaScript", "bytes": "81483" }, { "name": "Shell", "bytes": "136136" }, { "name": "Tcl", "bytes": "12029" }, { "name": "XSLT", "bytes": "3770667" } ], "symlink_target": "" }
import hashlib import io from os import path import pytest import slackviewer from slackviewer import archive from slackviewer.utils.six import to_bytes def test_SHA1_file(): filepath = path.join("tests", "testarchive.zip") version = to_bytes(slackviewer.__version__) def SHA1_file(filepath, extra=b''): """The original unoptimized method (reads whole file instead of chunks)""" with io.open(filepath, 'rb') as f: return hashlib.sha1(f.read() + extra).hexdigest() expected = SHA1_file(filepath, version) actual = archive.SHA1_file(filepath, version) assert actual == expected
{ "content_hash": "fc9db4107585e305a7fd1dfcb1e90b42", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 82, "avg_line_length": 27.565217391304348, "alnum_prop": 0.694006309148265, "repo_name": "hfaran/slack-export-viewer", "id": "34ae14493bd51b51fef2fb1eb6de931599b25f60", "size": "634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_archive.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3332" }, { "name": "HTML", "bytes": "9895" }, { "name": "Python", "bytes": "40640" } ], "symlink_target": "" }
function [theta] = Canny_18_OrientationDetection(sig, imageName, Th, Tl) % Canny Edge Detection implementation % by Muhammad Shahid Farid % Check for correct number of arguments if (nargin ~= 4) error('ERROR: Invalid number of parameters'); end % Validate the value of sigma and thresold bounds if (sig <= 0 || sig > 4) error('ERROR: Invalid value of sigma. Sigma should be between 0 and 4 '); end if (Th < Tl) error('ERROR: Th < Tl'); end fx = GenerateMask(sig); s = size(fx); hs = ceil(s/2); im = imread(imageName); if ndims(im) == 3 gim = double(rgb2gray(im)); else gim = double(im); end % Convolve the image with Horizontal and Vertical Masks fy = fx'; im2 = conv2(gim, fx, 'same'); im3 = conv2(gim, fy, 'same'); % Display the convolved images and save them % set(0,'DefaultFigurePaperPositionMode','auto'); % str = strcat('This call is: canny(',int2str(sig),', ',imageName,', ', int2str(Th),', ', int2str(Tl),')'); % figure, imagesc(im); % title(str); % colormap gray; % truesize; % Make a file name to save this image % position = findstr('.', imageName); % name = imageName(1:position-1); % time = datestr(now, 'HHMMSS'); % fn = strcat(name,time,'.pdf'); % print('-f1', '-dpdf', fn); % % figure, imagesc(im2); % title('Convolved Image with fx mask'); % colormap gray; % truesize; % print('-f2', '-dpdf', '-append', fn); % % figure, imagesc(im3); % title('Convolved Image with fy mask'); % colormap gray; % truesize; % % % Make a file name to save this image % % time = datestr(now, 'HHMMSS'); % % imwrite(im3,strcat(name,'-fy-',time,'.jpg')); % % print('-f3', '-dpdf', '-append', fn); % % Find the Gradient Magnitude and direction, save them in a matrices % gradient and direction [m, n] = size(im2); for i=1:m for j=1:n % gradient(i, j) = sqrt(im2(i, j)^2 + im3(i, j)^2); angle = atan2(im3(i, j), im2(i, j)); angle = rad2deg(angle); angle = angle + 180; theta(i, j) = mod(angle,180); end end end
{ "content_hash": "367733b4c69f935a84a7313dafd0489f", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 113, "avg_line_length": 23.44705882352941, "alnum_prop": 0.6256899147014551, "repo_name": "yunas/LMTH", "id": "b7345a7e2ca45a0c523acaf18553e2e5a69d7db8", "size": "1993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "implementation/MTH_Canny_18/Canny_18_OrientationDetection.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "M", "bytes": "5917" }, { "name": "Matlab", "bytes": "69325" } ], "symlink_target": "" }
struct t_lidar_user_data { cv::Mat *lidar_image; int image_width; double lidar_map_scale_factor; t_lidar_controller* LIDAR_controller; }; void create_and_init_lidar_image(cv::Mat &lidar_image, int image_width, double lidar_map_scale_factor); int lidar_map(t_lidar_controller &LIDAR_controller, const char* lidar_com_port, f_log_callback to_log); void on_lidar_mouse_event(int event, int x, int y, int flags, void *userdata); bool update_lidar_image(t_lidar_controller &LIDAR_controller, cv::Mat &lidar_image, int image_width, double lidar_map_scale_factor, f_log_callback to_log); #endif
{ "content_hash": "4ca2a57b3b3ccc53a9f09503eb6efa40", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 155, "avg_line_length": 42.357142857142854, "alnum_prop": 0.7537942664418212, "repo_name": "jenny5-robot/jenny5-html5", "id": "7ed64f3641b0a96ea4c5897214b24fc6c6cc200b", "size": "1099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/include/lidar_map.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1473513" }, { "name": "C++", "bytes": "144324" }, { "name": "HTML", "bytes": "4245" }, { "name": "JavaScript", "bytes": "24258" } ], "symlink_target": "" }
using System.Reflection; 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("Json.Net.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Json.Net.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9061d715-9f94-4c09-b80f-bf4be1b26d07")] // 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 Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "6f1550145e72c8b9d86a00f1d4a5a80a", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.916666666666664, "alnum_prop": 0.7430406852248393, "repo_name": "livarcocc/corefxlab", "id": "6e51ba8a327d141893ab63a2e393feb77a43fa7b", "size": "1404", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/System.Text.Json/experiments/Json.Net.Test/Json.Net.Tests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1741" }, { "name": "C#", "bytes": "2343380" }, { "name": "Groovy", "bytes": "2621" }, { "name": "PowerShell", "bytes": "673" } ], "symlink_target": "" }
An easy way to send emails with stack trace whenever an exception occurs on the server for Laravel Applications. ![sneaker example image](sneaker.png?raw=true "Sneaker") ## Install ### Install via composer ``` $ composer require yocmen/sneaker ^1.0 ``` ### Configure Laravel Once installation operation is complete, simply add the service provider to your project's `config/app.php` file: #### Service Provider ``` Yocmen\Sneaker\SneakerServiceProvider::class, ``` ### Add Sneaker's Exception Capturing Add exception capturing to `app/Exceptions/Handler.php`: ```php public function report(Exception $exception) { app('sneaker')->captureException($exception); parent::report($exception); } ``` ### Configuration File Create the Sneaker configuration file with this command: ```bash $ php artisan vendor:publish --provider="Yocmen\Sneaker\SneakerServiceProvider" ``` The config file will be published in `config/sneaker.php` Following are the configuration attributes used for the sneaker. #### silent The package comes with `'silent' => true,` configuration by default, since you probably don't want error emailing enabled on your development environment. Especially if you've set `'debug' => true,`. ```php 'silent' => env('SNEAKER_SILENT', true), ``` For sending emails when an exception occurs set `SNEAKER_SILENT=false` in your `.env` file. #### capture It contains the list of the exception types that should be captured. You can add your exceptions here for which you want to send error emails. By default, the package has included `Symfony\Component\Debug\Exception\FatalErrorException::class`. ```php 'capture' => [ Symfony\Component\Debug\Exception\FatalErrorException::class, ], ``` You can also use `'*'` in the `$capture` array which will in turn captures every exception. ```php 'capture' => [ '*' ], ``` To use this feature you should add the following code in `app/Exceptions/Handler.php`: ```php public function report(Exception $exception) { if ($this->shouldReport($exception)) { app('sneaker')->captureException($exception); } parent::report($exception); } ``` #### to This is the list of recipients of error emails. ```php 'to' => [ // 'hello@example.com', ], ``` #### ignored_bots This is the list of bots for which we should NOT send error emails. ```php 'ignored_bots' => [ 'googlebot', // Googlebot 'bingbot', // Microsoft Bingbot 'slurp', // Yahoo! Slurp 'ia_archiver', // Alexa ], ``` ## Customize If you need to customize the subject and body of email, run following command: ```bash $ php artisan vendor:publish --provider="Yocmen\Sneaker\SneakerServiceProvider" ``` > Note - Don't run this command again if you have run it already. Now the email's subject and body view are located in the `resources/views/vendor/sneaker` directory. We have passed the thrown exception object `$exception` in the view which you can use to customize the view to fit your needs. ## Security If you discover any security related issues, please email amit.gupta@squareboat.com instead of using the issue tracker. ## Credits - [Amit Gupta](https://github.com/akaamitgupta) - [All Contributors](../../contributors) ## About Squareboat Squareboat is a startup focused, product development company based in Gurgaon, India. You'll find an overview of all our open source projects [on GitHub](https://github.com/squareboat). # License The MIT License. Please see [License File](LICENSE.md) for more information. Copyright © 2016 [SquareBoat](https://squareboat.com)
{ "content_hash": "c0d37a8738a6faeb325d3268735d7898", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 199, "avg_line_length": 25.118055555555557, "alnum_prop": 0.7152336190212883, "repo_name": "yocmen/sneaker", "id": "bf7462088427f5e0a1c82a0518343d6d63b7e008", "size": "3653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1942" }, { "name": "PHP", "bytes": "13446" } ], "symlink_target": "" }
package edu.vu.isis.logger.ui; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class LogElementAdapter extends ArrayAdapter<LogElement> { private Logger logger = LoggerFactory.getLogger("ui.logger.adapter"); private Context mContext; private int maxNumLines = 0; // 0 means unlimited lines public LogElementAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { logger.trace("Adding view for position {}", position); View view = super.getView(position, convertView, parent); final TextView tv = (TextView) view; final LogElement element = super.getItem(position); final LogLevel level = element.getLogLevel(); tv.setText(element.getMessage()); tv.setTextColor(level.getColor(mContext)); return view; } public void addAll(List<LogElement> elemList) { synchronized(elemList) { for(LogElement e : elemList) { super.add(e); if(this.maxNumLines != 0 && this.maxNumLines < super.getCount()) { // Remove the first item in the list if we have exceeded the // max number of lines allowed super.remove(super.getItem(0)); } } } } /** * Sets the max number of elements that will be held by this adapter. * The adapter will remove all elements that exceed the new max * automatically. * @param newMax */ public void setMaxLines(int newMax) { this.maxNumLines = newMax; reduceCacheSizeToNewMax(); } private void reduceCacheSizeToNewMax() { if(!(this.maxNumLines < super.getCount())) return; if(this.maxNumLines == 0) return; while(this.maxNumLines < super.getCount()) { super.remove(super.getItem(0)); } } }
{ "content_hash": "4ee1d851b3d05d485b65ce6e01bbd7d4", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 72, "avg_line_length": 21.815217391304348, "alnum_prop": 0.7035376183358246, "repo_name": "isis-ammo/ammo-core", "id": "8ef58c04a8b1e6b4ad944fbdeee5d4e840dd5106", "size": "3137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AmmoCore/src/main/java/edu/vu/isis/logger/ui/LogElementAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "45199" }, { "name": "Java", "bytes": "1752631" }, { "name": "Makefile", "bytes": "474" } ], "symlink_target": "" }
<?php namespace AB\ThemeBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; /** * Class DefaultController * @package AB\ThemeBundle\Controller */ class DefaultController extends Controller { /** * @Route("/", name="homepage") * @Template() */ public function indexAction() { return array(); } }
{ "content_hash": "69ad3955dc102e00b12d659ef56ca0cd", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 62, "avg_line_length": 21.217391304347824, "alnum_prop": 0.7110655737704918, "repo_name": "shaunthornburgh/addressbook", "id": "1696b9fefd473f618cf328fb7af23b98a4512810", "size": "488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AB/ThemeBundle/Controller/DefaultController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6031" }, { "name": "JavaScript", "bytes": "664541" }, { "name": "PHP", "bytes": "62885" } ], "symlink_target": "" }
/** * auto code generation */ package com.sishuok.es.sys.xxs.service; import java.util.List; import org.springframework.stereotype.Service; import com.sishuok.es.common.service.BaseService; import com.sishuok.es.sys.xxs.entity.XxsAttribute; import com.sishuok.es.sys.xxs.repository.XxsAttributeRepository; /** * 不知道叫什么功能,可耻的用了自己的名字Service * @author xxs * @version 2015-03-22 */ @Service public class XxsAttributeService extends BaseService<XxsAttribute, Long> { private XxsAttributeRepository getXxsAttributeRepository() { return (XxsAttributeRepository) baseRepository; } public void save(List<XxsAttribute> attributes) { for (int i = 0; i < attributes.size(); i++) { baseRepository.save(attributes.get(i)); } } public List<XxsAttribute> findByName(String classname){ return getXxsAttributeRepository().findByName(classname); }; }
{ "content_hash": "eb0cab32928ed43e5b6d6cf93a961e02", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 74, "avg_line_length": 24.783783783783782, "alnum_prop": 0.7175572519083969, "repo_name": "xxs/es-shop", "id": "69a8307e882008ae7df275e2832702e43b4778c3", "size": "955", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sishuok/es/sys/xxs/service/XxsAttributeService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "3753" }, { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "2260" }, { "name": "CSS", "bytes": "995523" }, { "name": "FreeMarker", "bytes": "12470" }, { "name": "HTML", "bytes": "3217360" }, { "name": "Java", "bytes": "1953370" }, { "name": "JavaScript", "bytes": "8151405" }, { "name": "PHP", "bytes": "8060" }, { "name": "PLSQL", "bytes": "38298" } ], "symlink_target": "" }
import time import hashlib import hmac try: import simplejson as json except ImportError: import json # NOQA from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlencode from libcloud.common.base import ConnectionUserAndKey, JsonResponse from libcloud.common.types import InvalidCredsError, LibcloudError from libcloud.storage.base import Container, StorageDriver class NimbusResponse(JsonResponse): valid_response_codes = [httplib.OK, httplib.NOT_FOUND, httplib.CONFLICT, httplib.BAD_REQUEST] def success(self): return self.status in self.valid_response_codes def parse_error(self): if self.status in [httplib.UNAUTHORIZED]: raise InvalidCredsError(self.body) raise LibcloudError('Unknown error. Status code: %d' % (self.status), driver=self.driver) class NimbusConnection(ConnectionUserAndKey): host = 'nimbus.io' responseCls = NimbusResponse def __init__(self, *args, **kwargs): self.id = kwargs.pop('id') super(NimbusConnection, self).__init__(*args, **kwargs) def pre_connect_hook(self, params, headers): timestamp = str(int(time.time())) signature = self._calculate_signature(user_id=self.user_id, method=self.method, params=params, path=self.action, timestamp=timestamp, key=self.key) headers['X-NIMBUS-IO-Timestamp'] = timestamp headers['Authorization'] = 'NIMBUS.IO %s:%s' % (self.id, signature) return params, headers def _calculate_signature(self, user_id, method, params, path, timestamp, key): if params: uri_path = path + '?' + urlencode(params) else: uri_path = path string_to_sign = [user_id, method, str(timestamp), uri_path] string_to_sign = '\n'.join(string_to_sign) hmac_value = hmac.new(key, string_to_sign, hashlib.sha256) return hmac_value.hexdigest() class NimbusStorageDriver(StorageDriver): name = 'Nimbus.io' website = 'https://nimbus.io/' connectionCls = NimbusConnection def __init__(self, *args, **kwargs): self.user_id = kwargs['user_id'] super(NimbusStorageDriver, self).__init__(*args, **kwargs) def iterate_containers(self): response = self.connection.request('/customers/%s/collections' % (self.connection.user_id)) return self._to_containers(response.object) def create_container(self, container_name): params = {'action': 'create', 'name': container_name} response = self.connection.request('/customers/%s/collections' % (self.connection.user_id), params=params, method='POST') return self._to_container(response.object) def _to_containers(self, data): for item in data: yield self._to_container(item) def _to_container(self, data): name = data[0] extra = {'date_created': data[2]} return Container(name=name, extra=extra, driver=self) def _ex_connection_class_kwargs(self): result = {'id': self.user_id} return result
{ "content_hash": "4752a77fbfefcf3b2e688920732bb874", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 77, "avg_line_length": 35.76767676767677, "alnum_prop": 0.5741316012425869, "repo_name": "elastacloud/libcloud", "id": "b649e8b30603407f1cc27cc7c380f80f9869f684", "size": "4323", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "libcloud/storage/drivers/nimbus.py", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/// <reference path="angular.d.ts" /> declare function inject(...fns: Function[]): Function; /////////////////////////////////////////////////////////////////////////////// // ngMock module (angular-mocks.js) /////////////////////////////////////////////////////////////////////////////// module ng { /////////////////////////////////////////////////////////////////////////// // AngularStatic // We reopen it to add the MockStatic definition /////////////////////////////////////////////////////////////////////////// interface IAngularStatic { mock: IMockStatic; } interface IMockStatic { // see http://docs.angularjs.org/api/angular.mock.debug debug(obj: any): string; // see http://docs.angularjs.org/api/angular.mock.inject inject(...fns: Function[]): void; // see http://docs.angularjs.org/api/angular.mock.module module(...modules: any[]): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; TzDate(offset: number, timestamp: string): Date; } /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService // see http://docs.angularjs.org/api/ngMock.$exceptionHandler // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider /////////////////////////////////////////////////////////////////////////// interface IExceptionHandlerProvider extends IServiceProvider { mode(mode: string): void; } /////////////////////////////////////////////////////////////////////////// // TimeoutService // see http://docs.angularjs.org/api/ngMock.$timeout // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { flush(): void; } /////////////////////////////////////////////////////////////////////////// // LogService // see http://docs.angularjs.org/api/ngMock.$log // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ILogService { assertEmpty(): void; reset(): void; } interface LogCall { logs: string[]; } /////////////////////////////////////////////////////////////////////////// // HttpBackendService // see http://docs.angularjs.org/api/ngMock.$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { flush(count: number): void; resetExpectations(): void; verifyNoOutstandingExpectation(): void; verifyNoOutstandingRequest(): void; expect(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; expect(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; expect(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; expect(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; when(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; when(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; expectDELETE(url: string, headers?: any): mock.IRequestHandler; expectDELETE(url: RegExp, headers?: any): mock.IRequestHandler; expectGET(url: string, headers?: any): mock.IRequestHandler; expectGET(url: RegExp, headers?: any): mock.IRequestHandler; expectHEAD(url: string, headers?: any): mock.IRequestHandler; expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler; expectJSONP(url: string): mock.IRequestHandler; expectJSONP(url: RegExp): mock.IRequestHandler; expectPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; expectPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; expectPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; expectPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; expectPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; expectPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; expectPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; expectPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; expectPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; whenDELETE(url: string, headers?: any): mock.IRequestHandler; whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler; whenGET(url: string, headers?: any): mock.IRequestHandler; whenGET(url: RegExp, headers?: any): mock.IRequestHandler; whenHEAD(url: string, headers?: any): mock.IRequestHandler; whenHEAD(url: RegExp, headers?: any): mock.IRequestHandler; whenJSONP(url: string): mock.IRequestHandler; whenJSONP(url: RegExp): mock.IRequestHandler; whenPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; whenPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; whenPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; whenPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; whenPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; whenPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; whenPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; whenPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; whenPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; } export module mock { // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { respond(func: Function): void; respond(status: number, data?: any, headers?: any): void; respond(data: any, headers?: any): void; // Available wehn ngMockE2E is loaded passThrough(): void; } } }
{ "content_hash": "fbea748ba2825dbd4ce1324975dc00cd", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 104, "avg_line_length": 52.88157894736842, "alnum_prop": 0.5631998009455088, "repo_name": "shogogg/angularjs-examples", "id": "3fecc3dc448720151b8bf17fab7a9d7f6ab37dcb", "size": "8266", "binary": false, "copies": "2", "ref": "refs/heads/gh-pages", "path": "02-Form/lib/angularjs/angular-mocks.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2875077" } ], "symlink_target": "" }
package org.apache.flink.table.types.logical.utils; import org.apache.flink.annotation.Internal; import org.apache.flink.table.types.logical.DateType; import org.apache.flink.table.types.logical.DistinctType; import org.apache.flink.table.types.logical.LogicalType; import org.apache.flink.table.types.logical.LogicalTypeFamily; import org.apache.flink.table.types.logical.LogicalTypeRoot; import org.apache.flink.table.types.logical.RowType; import org.apache.flink.table.types.logical.StructuredType; import org.apache.flink.table.types.logical.VarBinaryType; import org.apache.flink.table.types.logical.VarCharType; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; import static org.apache.flink.table.types.logical.LogicalTypeFamily.BINARY_STRING; import static org.apache.flink.table.types.logical.LogicalTypeFamily.CHARACTER_STRING; import static org.apache.flink.table.types.logical.LogicalTypeFamily.CONSTRUCTED; import static org.apache.flink.table.types.logical.LogicalTypeFamily.DATETIME; import static org.apache.flink.table.types.logical.LogicalTypeFamily.EXACT_NUMERIC; import static org.apache.flink.table.types.logical.LogicalTypeFamily.INTEGER_NUMERIC; import static org.apache.flink.table.types.logical.LogicalTypeFamily.INTERVAL; import static org.apache.flink.table.types.logical.LogicalTypeFamily.NUMERIC; import static org.apache.flink.table.types.logical.LogicalTypeFamily.PREDEFINED; import static org.apache.flink.table.types.logical.LogicalTypeFamily.TIME; import static org.apache.flink.table.types.logical.LogicalTypeFamily.TIMESTAMP; import static org.apache.flink.table.types.logical.LogicalTypeRoot.BIGINT; import static org.apache.flink.table.types.logical.LogicalTypeRoot.BINARY; import static org.apache.flink.table.types.logical.LogicalTypeRoot.BOOLEAN; import static org.apache.flink.table.types.logical.LogicalTypeRoot.CHAR; import static org.apache.flink.table.types.logical.LogicalTypeRoot.DATE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.DECIMAL; import static org.apache.flink.table.types.logical.LogicalTypeRoot.DISTINCT_TYPE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.DOUBLE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.FLOAT; import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTEGER; import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTERVAL_DAY_TIME; import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTERVAL_YEAR_MONTH; import static org.apache.flink.table.types.logical.LogicalTypeRoot.NULL; import static org.apache.flink.table.types.logical.LogicalTypeRoot.RAW; import static org.apache.flink.table.types.logical.LogicalTypeRoot.ROW; import static org.apache.flink.table.types.logical.LogicalTypeRoot.SMALLINT; import static org.apache.flink.table.types.logical.LogicalTypeRoot.STRUCTURED_TYPE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.SYMBOL; import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITH_TIME_ZONE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE; import static org.apache.flink.table.types.logical.LogicalTypeRoot.TINYINT; import static org.apache.flink.table.types.logical.LogicalTypeRoot.VARBINARY; import static org.apache.flink.table.types.logical.LogicalTypeRoot.VARCHAR; import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getLength; import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isSingleFieldInterval; /** * Utilities for casting {@link LogicalType}. * * <p>This class aims to be compatible with the SQL standard. It is inspired by Apache Calcite's * {@code SqlTypeUtil#canCastFrom} method. * * <p>Casts can be performed in two ways: implicit or explicit. * * <p>Explicit casts correspond to the SQL cast specification and represent the logic behind a * {@code CAST(sourceType AS targetType)} operation. For example, it allows for converting most * types of the {@link LogicalTypeFamily#PREDEFINED} family to types of the {@link * LogicalTypeFamily#CHARACTER_STRING} family. * * <p>Implicit casts are used for safe type widening and type generalization (finding a common * supertype for a set of types) without loss of information. Implicit casts are similar to the Java * semantics (e.g. this is not possible: {@code int x = (String) z}). * * <p>Conversions that are defined by the {@link LogicalType} (e.g. interpreting a {@link DateType} * as integer value) are not considered here. They are an internal bridging feature that is not * standard compliant. If at all, {@code CONVERT} methods should make such conversions available. */ @Internal public final class LogicalTypeCasts { private static final Map<LogicalTypeRoot, Set<LogicalTypeRoot>> implicitCastingRules; private static final Map<LogicalTypeRoot, Set<LogicalTypeRoot>> explicitCastingRules; static { implicitCastingRules = new HashMap<>(); explicitCastingRules = new HashMap<>(); // identity casts for (LogicalTypeRoot typeRoot : allTypes()) { castTo(typeRoot).implicitFrom(typeRoot).build(); } // cast specification castTo(CHAR).implicitFrom(CHAR).explicitFromFamily(PREDEFINED).build(); castTo(VARCHAR).implicitFromFamily(CHARACTER_STRING).explicitFromFamily(PREDEFINED).build(); castTo(BOOLEAN) .implicitFrom(BOOLEAN) .explicitFromFamily(CHARACTER_STRING, INTEGER_NUMERIC) .build(); castTo(BINARY) .implicitFrom(BINARY) .explicitFromFamily(CHARACTER_STRING) .explicitFrom(VARBINARY) .explicitFrom(RAW) .build(); castTo(VARBINARY) .implicitFromFamily(BINARY_STRING) .explicitFromFamily(CHARACTER_STRING) .explicitFrom(BINARY) .explicitFrom(RAW) .build(); castTo(DECIMAL) .implicitFromFamily(NUMERIC) .explicitFromFamily(CHARACTER_STRING, INTERVAL) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(TINYINT) .implicitFrom(TINYINT) .explicitFromFamily(NUMERIC, CHARACTER_STRING, INTERVAL) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(SMALLINT) .implicitFrom(TINYINT, SMALLINT) .explicitFromFamily(NUMERIC, CHARACTER_STRING, INTERVAL) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(INTEGER) .implicitFrom(TINYINT, SMALLINT, INTEGER) .explicitFromFamily(NUMERIC, CHARACTER_STRING, INTERVAL) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(BIGINT) .implicitFrom(TINYINT, SMALLINT, INTEGER, BIGINT) .explicitFromFamily(NUMERIC, CHARACTER_STRING, INTERVAL) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(FLOAT) .implicitFrom(TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DECIMAL) .explicitFromFamily(NUMERIC, CHARACTER_STRING) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(DOUBLE) .implicitFromFamily(NUMERIC) .explicitFromFamily(CHARACTER_STRING) .explicitFrom(BOOLEAN, TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .build(); castTo(DATE) .implicitFrom(DATE, TIMESTAMP_WITHOUT_TIME_ZONE) .explicitFromFamily(TIMESTAMP, CHARACTER_STRING) .build(); castTo(TIME_WITHOUT_TIME_ZONE) .implicitFrom(TIME_WITHOUT_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE) .explicitFromFamily(TIME, TIMESTAMP, CHARACTER_STRING) .build(); castTo(TIMESTAMP_WITHOUT_TIME_ZONE) .implicitFrom(TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) .explicitFromFamily(DATETIME, CHARACTER_STRING, NUMERIC) .build(); castTo(TIMESTAMP_WITH_TIME_ZONE) .implicitFrom(TIMESTAMP_WITH_TIME_ZONE) .explicitFromFamily(DATETIME, CHARACTER_STRING) .build(); castTo(TIMESTAMP_WITH_LOCAL_TIME_ZONE) .implicitFrom(TIMESTAMP_WITH_LOCAL_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE) .explicitFromFamily(DATETIME, CHARACTER_STRING, NUMERIC) .build(); castTo(INTERVAL_YEAR_MONTH) .implicitFrom(INTERVAL_YEAR_MONTH) .explicitFromFamily(EXACT_NUMERIC, CHARACTER_STRING) .build(); castTo(INTERVAL_DAY_TIME) .implicitFrom(INTERVAL_DAY_TIME) .explicitFromFamily(EXACT_NUMERIC, CHARACTER_STRING) .build(); } /** * Returns whether the source type can be safely interpreted as the target type. This allows * avoiding casts by ignoring some logical properties. This is basically a relaxed {@link * LogicalType#equals(Object)}. * * <p>In particular this means: * * <p>Atomic, non-string types (INT, BOOLEAN, ...) and user-defined structured types must be * fully equal (i.e. {@link LogicalType#equals(Object)}). However, a NOT NULL type can be stored * in NULL type but not vice versa. * * <p>Atomic, string types must be contained in the target type (e.g. CHAR(2) is contained in * VARCHAR(3), but VARCHAR(2) is not contained in CHAR(3)). Same for binary strings. * * <p>Constructed types (ARRAY, ROW, MAP, etc.) and user-defined distinct type must be of same * kind but ignore field names and other logical attributes. Structured and row kinds are * compatible. However, all the children types ({@link LogicalType#getChildren()}) must be * compatible. */ public static boolean supportsAvoidingCast(LogicalType sourceType, LogicalType targetType) { final CastAvoidanceChecker checker = new CastAvoidanceChecker(sourceType); return targetType.accept(checker); } /** See {@link #supportsAvoidingCast(LogicalType, LogicalType)}. */ public static boolean supportsAvoidingCast( List<LogicalType> sourceTypes, List<LogicalType> targetTypes) { if (sourceTypes.size() != targetTypes.size()) { return false; } for (int i = 0; i < sourceTypes.size(); i++) { if (!supportsAvoidingCast(sourceTypes.get(i), targetTypes.get(i))) { return false; } } return true; } /** * Returns whether the source type can be safely casted to the target type without loosing * information. * * <p>Implicit casts are used for type widening and type generalization (finding a common * supertype for a set of types). Implicit casts are similar to the Java semantics (e.g. this is * not possible: {@code int x = (String) z}). */ public static boolean supportsImplicitCast(LogicalType sourceType, LogicalType targetType) { return supportsCasting(sourceType, targetType, false); } /** * Returns whether the source type can be casted to the target type. * * <p>Explicit casts correspond to the SQL cast specification and represent the logic behind a * {@code CAST(sourceType AS targetType)} operation. For example, it allows for converting most * types of the {@link LogicalTypeFamily#PREDEFINED} family to types of the {@link * LogicalTypeFamily#CHARACTER_STRING} family. */ public static boolean supportsExplicitCast(LogicalType sourceType, LogicalType targetType) { return supportsCasting(sourceType, targetType, true); } // -------------------------------------------------------------------------------------------- private static boolean supportsCasting( LogicalType sourceType, LogicalType targetType, boolean allowExplicit) { // a NOT NULL type cannot store a NULL type // but it might be useful to cast explicitly with knowledge about the data if (sourceType.isNullable() && !targetType.isNullable() && !allowExplicit) { return false; } // ignore nullability during compare if (sourceType.copy(true).equals(targetType.copy(true))) { return true; } final LogicalTypeRoot sourceRoot = sourceType.getTypeRoot(); final LogicalTypeRoot targetRoot = targetType.getTypeRoot(); if (sourceRoot == NULL) { // null can be cast to an arbitrary type return true; } else if (sourceRoot == DISTINCT_TYPE && targetRoot == DISTINCT_TYPE) { // the two distinct types are not equal (from initial invariant), casting is not // possible return false; } else if (sourceRoot == DISTINCT_TYPE) { return supportsCasting( ((DistinctType) sourceType).getSourceType(), targetType, allowExplicit); } else if (targetRoot == DISTINCT_TYPE) { return supportsCasting( sourceType, ((DistinctType) targetType).getSourceType(), allowExplicit); } else if (sourceType.is(INTERVAL) && targetType.is(EXACT_NUMERIC)) { // cast between interval and exact numeric is only supported if interval has a single // field return isSingleFieldInterval(sourceType); } else if (sourceType.is(EXACT_NUMERIC) && targetType.is(INTERVAL)) { // cast between interval and exact numeric is only supported if interval has a single // field return isSingleFieldInterval(targetType); } else if (sourceType.is(CONSTRUCTED) || targetType.is(CONSTRUCTED)) { return supportsConstructedCasting(sourceType, targetType, allowExplicit); } else if (sourceRoot == STRUCTURED_TYPE || targetRoot == STRUCTURED_TYPE) { return supportsStructuredCasting( sourceType, targetType, (s, t) -> supportsCasting(s, t, allowExplicit)); } else if (sourceRoot == RAW && !targetType.is(BINARY_STRING) || targetRoot == RAW) { // the two raw types are not equal (from initial invariant), casting is not possible return false; } else if (sourceRoot == SYMBOL || targetRoot == SYMBOL) { // the two symbol types are not equal (from initial invariant), casting is not possible return false; } if (implicitCastingRules.get(targetRoot).contains(sourceRoot)) { return true; } if (allowExplicit) { return explicitCastingRules.get(targetRoot).contains(sourceRoot); } return false; } private static boolean supportsStructuredCasting( LogicalType sourceType, LogicalType targetType, BiFunction<LogicalType, LogicalType, Boolean> childPredicate) { final LogicalTypeRoot sourceRoot = sourceType.getTypeRoot(); final LogicalTypeRoot targetRoot = targetType.getTypeRoot(); if (sourceRoot != STRUCTURED_TYPE || targetRoot != STRUCTURED_TYPE) { return false; } final StructuredType sourceStructuredType = (StructuredType) sourceType; final StructuredType targetStructuredType = (StructuredType) targetType; // non-anonymous structured types must be fully equal if (sourceStructuredType.getObjectIdentifier().isPresent() || targetStructuredType.getObjectIdentifier().isPresent()) { return false; } // for anonymous structured types we are a bit more lenient, if they provide similar fields // e.g. this is necessary when structured types derived from type information and // structured types derived within Table API are slightly different final Class<?> sourceClass = sourceStructuredType.getImplementationClass().orElse(null); final Class<?> targetClass = targetStructuredType.getImplementationClass().orElse(null); if (sourceClass != targetClass) { return false; } final List<String> sourceNames = sourceStructuredType.getAttributes().stream() .map(StructuredType.StructuredAttribute::getName) .collect(Collectors.toList()); final List<String> targetNames = sourceStructuredType.getAttributes().stream() .map(StructuredType.StructuredAttribute::getName) .collect(Collectors.toList()); if (!sourceNames.equals(targetNames)) { return false; } final List<LogicalType> sourceChildren = sourceType.getChildren(); final List<LogicalType> targetChildren = targetType.getChildren(); for (int i = 0; i < sourceChildren.size(); i++) { if (!childPredicate.apply(sourceChildren.get(i), targetChildren.get(i))) { return false; } } return true; } private static boolean supportsConstructedCasting( LogicalType sourceType, LogicalType targetType, boolean allowExplicit) { final LogicalTypeRoot sourceRoot = sourceType.getTypeRoot(); final LogicalTypeRoot targetRoot = targetType.getTypeRoot(); // all constructed types can only be casted within the same type root, // however, rows can be converted to structured types and vice versa if (sourceRoot == targetRoot || (sourceRoot == ROW && targetRoot == STRUCTURED_TYPE) || (sourceRoot == STRUCTURED_TYPE && targetRoot == ROW)) { final List<LogicalType> sourceChildren = sourceType.getChildren(); final List<LogicalType> targetChildren = targetType.getChildren(); if (sourceChildren.size() != targetChildren.size()) { return false; } for (int i = 0; i < sourceChildren.size(); i++) { if (!supportsCasting(sourceChildren.get(i), targetChildren.get(i), allowExplicit)) { return false; } } return true; } return false; } private static CastingRuleBuilder castTo(LogicalTypeRoot targetType) { return new CastingRuleBuilder(targetType); } private static LogicalTypeRoot[] allTypes() { return LogicalTypeRoot.values(); } private static class CastingRuleBuilder { private final LogicalTypeRoot targetType; private final Set<LogicalTypeRoot> implicitSourceTypes = new HashSet<>(); private final Set<LogicalTypeRoot> explicitSourceTypes = new HashSet<>(); CastingRuleBuilder(LogicalTypeRoot targetType) { this.targetType = targetType; } CastingRuleBuilder implicitFrom(LogicalTypeRoot... sourceTypes) { this.implicitSourceTypes.addAll(Arrays.asList(sourceTypes)); return this; } CastingRuleBuilder implicitFromFamily(LogicalTypeFamily... sourceFamilies) { for (LogicalTypeFamily family : sourceFamilies) { for (LogicalTypeRoot root : LogicalTypeRoot.values()) { if (root.getFamilies().contains(family)) { this.implicitSourceTypes.add(root); } } } return this; } CastingRuleBuilder explicitFrom(LogicalTypeRoot... sourceTypes) { this.explicitSourceTypes.addAll(Arrays.asList(sourceTypes)); return this; } CastingRuleBuilder explicitFromFamily(LogicalTypeFamily... sourceFamilies) { for (LogicalTypeFamily family : sourceFamilies) { for (LogicalTypeRoot root : LogicalTypeRoot.values()) { if (root.getFamilies().contains(family)) { this.explicitSourceTypes.add(root); } } } return this; } /** * Should be called after {@link #explicitFromFamily(LogicalTypeFamily...)} to remove * previously added types. */ CastingRuleBuilder explicitNotFromFamily(LogicalTypeFamily... sourceFamilies) { for (LogicalTypeFamily family : sourceFamilies) { for (LogicalTypeRoot root : LogicalTypeRoot.values()) { if (root.getFamilies().contains(family)) { this.explicitSourceTypes.remove(root); } } } return this; } void build() { implicitCastingRules.put(targetType, implicitSourceTypes); explicitCastingRules.put(targetType, explicitSourceTypes); } } // -------------------------------------------------------------------------------------------- /** Checks if a source type can safely be interpreted as the target type. */ private static class CastAvoidanceChecker extends LogicalTypeDefaultVisitor<Boolean> { private final LogicalType sourceType; private CastAvoidanceChecker(LogicalType sourceType) { this.sourceType = sourceType; } @Override public Boolean visit(VarCharType targetType) { if (sourceType.isNullable() && !targetType.isNullable()) { return false; } // CHAR and VARCHAR are very compatible within bounds if (sourceType.isAnyOf(LogicalTypeRoot.CHAR, LogicalTypeRoot.VARCHAR) && getLength(sourceType) <= targetType.getLength()) { return true; } return defaultMethod(targetType); } @Override public Boolean visit(VarBinaryType targetType) { if (sourceType.isNullable() && !targetType.isNullable()) { return false; } // BINARY and VARBINARY are very compatible within bounds if (sourceType.isAnyOf(LogicalTypeRoot.BINARY, LogicalTypeRoot.VARBINARY) && getLength(sourceType) <= targetType.getLength()) { return true; } return defaultMethod(targetType); } @Override public Boolean visit(RowType targetType) { if (sourceType.isNullable() && !targetType.isNullable()) { return false; } // ROW and structured types are very compatible if field types match if (sourceType.is(STRUCTURED_TYPE)) { final List<LogicalType> sourceChildren = sourceType.getChildren(); final List<LogicalType> targetChildren = targetType.getChildren(); return supportsAvoidingCast(sourceChildren, targetChildren); } return defaultMethod(targetType); } @Override public Boolean visit(StructuredType targetType) { if (sourceType.isNullable() && !targetType.isNullable()) { return false; } // ROW and structured types are very compatible if field types match if (sourceType.is(ROW)) { final List<LogicalType> sourceChildren = sourceType.getChildren(); final List<LogicalType> targetChildren = targetType.getChildren(); return supportsAvoidingCast(sourceChildren, targetChildren); } if (sourceType.equals(targetType) || sourceType.copy(true).equals(targetType)) { return true; } return supportsStructuredCasting( sourceType, targetType, LogicalTypeCasts::supportsAvoidingCast); } @Override protected Boolean defaultMethod(LogicalType targetType) { // quick path if (sourceType == targetType) { return true; } if (sourceType.isNullable() && !targetType.isNullable() || sourceType.getClass() != targetType.getClass() || // TODO drop this line once we remove legacy types sourceType.getTypeRoot() != targetType.getTypeRoot()) { return false; } final List<LogicalType> sourceChildren = sourceType.getChildren(); final List<LogicalType> targetChildren = targetType.getChildren(); if (sourceChildren.isEmpty()) { // handles all types that are not of family CONSTRUCTED or USER DEFINED return sourceType.equals(targetType) || sourceType.copy(true).equals(targetType); } else { // handles all types of CONSTRUCTED family as well as distinct types return supportsAvoidingCast(sourceChildren, targetChildren); } } } private LogicalTypeCasts() { // no instantiation } }
{ "content_hash": "6e4566d74fd0a5b6bc2c176ba03c6831", "timestamp": "", "source": "github", "line_count": 565, "max_line_length": 100, "avg_line_length": 45.892035398230085, "alnum_prop": 0.6468047360098731, "repo_name": "StephanEwen/incubator-flink", "id": "2bbf2550f093ddfa81ecf2df54bb3708c2886bf5", "size": "26734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeCasts.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4588" }, { "name": "CSS", "bytes": "57936" }, { "name": "Clojure", "bytes": "90539" }, { "name": "Dockerfile", "bytes": "10807" }, { "name": "FreeMarker", "bytes": "11924" }, { "name": "HTML", "bytes": "224454" }, { "name": "Java", "bytes": "48116532" }, { "name": "JavaScript", "bytes": "1829" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "747014" }, { "name": "Scala", "bytes": "13208937" }, { "name": "Shell", "bytes": "461052" }, { "name": "TypeScript", "bytes": "243702" } ], "symlink_target": "" }
package org.encuestame.core.test.config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; import org.junit.runner.RunWith; import org.springframework.context.annotation.Scope; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Description Class. * @author Picado, Juan juanATencuestame.org * @since Feb 12, 2011 1:21:01 AM */ @RunWith(SpringJUnit4ClassRunner.class) @Scope("singleton") @ContextConfiguration(locations = { "classpath:spring-test/encuestame-integration.xml" }) @Ignore public class AbstractIntegrationConfig{ public Log log = LogFactory.getLog(this.getClass()); }
{ "content_hash": "6d301957a15129b0245e6b04882aaf83", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 71, "avg_line_length": 27.214285714285715, "alnum_prop": 0.7769028871391076, "repo_name": "cristiani/encuestame", "id": "8fcddd5f6c83725490c23cd2b4592cb80e7936f0", "size": "1532", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "enme-core/src/test/java/org/encuestame/core/test/config/AbstractIntegrationConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9772228" }, { "name": "HTML", "bytes": "552" }, { "name": "Java", "bytes": "4752329" }, { "name": "JavaScript", "bytes": "7194351" }, { "name": "Ruby", "bytes": "1012" }, { "name": "Shell", "bytes": "4346" } ], "symlink_target": "" }
namespace net { NetworkBindingClientSocketFactory::NetworkBindingClientSocketFactory( handles::NetworkHandle network) : network_(network) {} std::unique_ptr<DatagramClientSocket> NetworkBindingClientSocketFactory::CreateDatagramClientSocket( DatagramSocket::BindType bind_type, NetLog* net_log, const NetLogSource& source) { return std::make_unique<UDPClientSocket>(bind_type, net_log, source, network_); } std::unique_ptr<TransportClientSocket> NetworkBindingClientSocketFactory::CreateTransportClientSocket( const AddressList& addresses, std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, NetworkQualityEstimator* network_quality_estimator, NetLog* net_log, const NetLogSource& source) { return std::make_unique<TCPClientSocket>( addresses, std::move(socket_performance_watcher), network_quality_estimator, net_log, source, network_); } std::unique_ptr<SSLClientSocket> NetworkBindingClientSocketFactory::CreateSSLClientSocket( SSLClientContext* context, std::unique_ptr<StreamSocket> stream_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config) { return ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( context, std::move(stream_socket), host_and_port, ssl_config); } } // namespace net
{ "content_hash": "362a8dbeee8599a2395cbfb0abc9395d", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 73, "avg_line_length": 36.10526315789474, "alnum_prop": 0.7456268221574344, "repo_name": "nwjs/chromium.src", "id": "ba24d158bdbfa010c6d1c2ce12aee814fe579f61", "size": "1664", "binary": false, "copies": "7", "ref": "refs/heads/nw70", "path": "net/socket/network_binding_client_socket_factory.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<idea-plugin> <extensionPoints> <extensionPoint name="additionalLibraryRootsProvider" interface="com.intellij.openapi.roots.AdditionalLibraryRootsProvider" dynamic="true"/> <extensionPoint name="directoryIndexExcludePolicy" interface="com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy" area="IDEA_PROJECT" dynamic="true"/> <extensionPoint name="projectExtension" interface="com.intellij.openapi.roots.ProjectExtension" area="IDEA_PROJECT" dynamic="true"/> <extensionPoint name="workspaceModel.moduleExtensionBridgeFactory" interface="com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridgeFactory" dynamic="true"/> <extensionPoint name="projectPathMacroContributor" interface="com.intellij.openapi.components.impl.ProjectWidePathMacroContributor" dynamic="true"/> </extensionPoints> <extensions defaultExtensionNs="com.intellij"> <projectService serviceInterface="com.intellij.openapi.roots.impl.DirectoryIndex" serviceImplementation="com.intellij.openapi.roots.impl.DirectoryIndexImpl" preload="true"/> <projectService serviceInterface="com.intellij.openapi.components.PathMacroManager" serviceImplementation="com.intellij.openapi.components.impl.ProjectPathMacroManager"/> <projectService serviceInterface="com.intellij.openapi.roots.impl.ModifiableModelCommitterService" serviceImplementation="com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModifiableModelCommitterServiceBridge"/> <applicationService serviceInterface="com.intellij.openapi.project.ProjectLocator" serviceImplementation="com.intellij.openapi.project.ProjectLocatorImpl"/> <projectService serviceInterface="com.intellij.openapi.roots.FileIndexFacade" serviceImplementation="com.intellij.openapi.roots.impl.ProjectFileIndexFacade"/> <projectService serviceInterface="com.intellij.openapi.roots.ProjectFileIndex" serviceImplementation="com.intellij.openapi.roots.impl.ProjectFileIndexImpl"/> <projectService serviceInterface="com.intellij.workspaceModel.ide.WorkspaceModel" serviceImplementation="com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl" preload="await"/> <projectService serviceInterface="com.intellij.workspaceModel.storage.url.VirtualFileUrlManager" serviceImplementation="com.intellij.workspaceModel.ide.impl.IdeVirtualFileUrlManagerImpl"/> <backgroundPostStartupActivity implementation="com.intellij.workspaceModel.ide.impl.VirtualFileUrlsLazyInitializer"/> <projectService serviceImplementation="com.intellij.workspaceModel.ide.WorkspaceModelTopics"/> <projectService serviceImplementation="com.intellij.workspaceModel.ide.impl.JpsProjectLoadingManagerImpl" serviceInterface="com.intellij.workspaceModel.ide.JpsProjectLoadingManager"/> <projectService serviceInterface="com.intellij.openapi.module.AutomaticModuleUnloader" serviceImplementation="com.intellij.openapi.module.DummyAutomaticModuleUnloader"/> <applicationService serviceInterface="com.intellij.openapi.roots.AdditionalLibraryRootsListenerHelper" serviceImplementation="com.intellij.openapi.roots.impl.AdditionalLibraryRootsListenerHelperImpl"/> <workspaceModel.preUpdateHandler implementation="com.intellij.workspaceModel.ide.impl.ModulePreUpdateHandler"/> </extensions> </idea-plugin>
{ "content_hash": "c524102b77a502d457c99e1a94f502c8", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 146, "avg_line_length": 77.67391304347827, "alnum_prop": 0.7699412258606213, "repo_name": "jwren/intellij-community", "id": "bbd013e67ed328c44e514d8fc9d7fff6a637130f", "size": "3573", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/projectModel-impl/resources/META-INF/ProjectModelImpl.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as moment from 'moment'; import { Queriable, Query } from './utils/query'; import { Downloadable } from './utils/download'; import { LoggerageOptions } from './loggerage-options'; import { LoggerageObject } from './loggerage-object'; import { LoggerageLevel } from './loggerage-level'; import { Storage } from './storage-interface'; /** * Loggerage class */ declare class Loggerage implements Queriable, Downloadable { /** * Constructor for Loggerage * @param app App or Logger name * @param rest Optional parameters */ constructor(app: string, options?: LoggerageOptions); /** * Set your own Storage * @param otherStorage Your Storage that implement Storage interface [https://developer.mozilla.org/en-US/docs/Web/API/Storage] * @returns {Loggerage} */ setStorage(storage: Storage): Loggerage; /** * Get the actual log * @returns {LoggerageObject[]} */ getLog(): LoggerageObject[]; /** * Get the actual log asynchronously * @param callback Is a function that recived two params. The first param is an error if occurs, otherwise is null. The second param is log. * @returns {void} */ getLogAsync(callback: (error: Error, data?: LoggerageObject[]) => void): void; /** * Return the app version * @returns {number} */ getVersion(): number | string; /** * Return the app name for localStorage * @returns {string} */ getApp(): string; /** * Set the default log level * @param defaultLogLevel * @returns {Loggerage} */ setDefaultLogLevel(defaultLogLevel: LoggerageLevel): Loggerage; /** * Get the default log level * @returns {string} */ getDefaultLogLevel(): string; /** * Get the default log level number * @returns {number} */ getDefaultLogLevelNumber(): number; /** * Set the silence property * @param silence * @returns {Loggerage} */ setSilence(silence: boolean): Loggerage; /** * Get the silence property * @returns {boolean} */ getSilence(): boolean; /** * Clear all the log * @returns {Loggerage} */ clearLog(): Loggerage; /** * Clear all the log asynchronously * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ clearLogAsync(callback: (error: Error | void) => void): void; /** * Log a message of all levels * @param logLevel * @param message * @param stacktrace [optional] * @returns {Loggerage} */ log(logLevel: LoggerageLevel, message: string, stacktrace?: string): Loggerage; /** * Log a message of all levels * @param logLevel Level log * @param message Message to log * @param stacktrace (Can be null) * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ logAsync(logLevel: LoggerageLevel, message: string, stacktrace: string, callback: (error: Error | void) => void): void; /** * Log a debug message * @param message * @returns {Loggerage} */ debug(message: string): Loggerage; /** * Log a failure message * @param message * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ debugAsync(message: string, callback: (error: Error | void) => void): void; /** * Log an info message * @param message * @returns {Loggerage} */ info(message: string): Loggerage; /** * Log a failure message * @param message * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ infoAsync(message: string, callback: (error: Error | void) => void): void; /** * Log a trace message * @param message * @returns {Loggerage} */ trace(message: string): Loggerage; /** * Log a failure message * @param message * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ traceAsync(message: string, callback: (error: Error | void) => void): void; /** * Log a success message * @param message * @returns {Loggerage} */ success(message: string): Loggerage; /** * Log a failure message * @param message * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ successAsync(message: string, callback: (error: Error | void) => void): void; /** * Log a warn message * @param message * @returns {Loggerage} */ warn(message: string): Loggerage; /** * Log a failure message * @param message * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ warnAsync(message: string, callback: (error: Error | void) => void): void; /** * Log an error message * @param message * @param stacktrace * @returns {Loggerage} */ error(message: string, stacktrace?: string): Loggerage; /** * Log a failure message * @param message * @param stacktrace * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ errorAsync(message: string, stacktrace: string, callback: (error: Error | void) => void): void; /** * Log a failure message * @param message * @param stacktrace * @returns {Loggerage} */ failure(message: string, stacktrace?: string): Loggerage; /** * Log a failure message * @param message * @param stacktrace * @param callback Is a function that recived one param, an error if occurs, otherwise this param is null. * @returns {void} */ failureAsync(message: string, stacktrace: string, callback: (error: Error | void) => void): void; /** * Return a stored logger * @param {string} app App or logger name * @return {Loggerage} */ static getLogger(app: string): Loggerage; /** * Destroy a stored logger * @param {string} app App or logger name */ static destroy(app: string): void; /** * App name for localStorage */ private _app; /** * Indicate if localStorage is ok (false by default) */ private _isStorageOk; /** * Options for logger */ private _options; /** * Store of loggers */ private static _loggers; /** * Make an object for log * @param logLevel * @param message * @private * @returns {LoggerageObject} */ private _makeLoggerageObject(logLevel, message); isQueryRequested: boolean; getQueryRequest: () => Query; from: (from: moment.Moment | Date | string | number, dateStringFormat?: string) => Queriable; to: (to: moment.Moment | Date | string | number, dateStringFormat?: string) => Queriable; level: (level: LoggerageLevel | LoggerageLevel[]) => Queriable; app: (app: string) => Queriable; version: (version: number | string) => Queriable; resetQuery: () => Queriable; _fromFormatFilter: string; _fromFilter: moment.Moment | Date | string | number; _toFormatFilter: string; _toFilter: moment.Moment | Date | string | number; _levelFilter: LoggerageLevel | LoggerageLevel[]; _appFilter: string; _versionFilter: number | string; downloadFileLog: (type: string) => Downloadable; downloadFileLogAsync: (type: string, callback: (error: Error | void, blob?: Blob) => void) => void; } export { Loggerage, LoggerageOptions, LoggerageObject, LoggerageLevel };
{ "content_hash": "813100a37b337dc55e6e43f12f63103d", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 147, "avg_line_length": 32.48790322580645, "alnum_prop": 0.6118902817425841, "repo_name": "lmfresneda/LogStorage.js", "id": "0452a4a857bf030ff54b4881e128e16aa218a9e6", "size": "8057", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "types/loggerage.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "538" }, { "name": "JavaScript", "bytes": "130803" }, { "name": "TypeScript", "bytes": "9230" } ], "symlink_target": "" }
<?php class CM_Request_AbstractTest extends CMTest_TestCase { public function tearDown() { CMTest_TH::clearEnv(); } public function testGetViewer() { $user = CMTest_TH::createUser(); $uri = '/'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive'); $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); /** @var CM_Request_Abstract $mock */ $this->assertNull($mock->getViewer()); $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive', 'Cookie' => 'sessionId=a1d2726e5b3801226aafd12fd62496c8'); $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); try { $mock->getViewer(true); $this->fail(); } catch (CM_Exception_AuthRequired $ex) { $this->assertTrue(true); } $session = new CM_Session(); $session->setUser($user); $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive', 'Cookie' => 'sessionId=' . $session->getId()); unset($session); $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertEquals($user, $mock->getViewer(true)); $user2 = CMTest_TH::createUser(); $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers, null, $user2)); $this->assertEquals($user2, $mock->getViewer(true)); } public function testGetCookie() { $uri = '/'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive', 'Cookie' => ';213q;213;=foo=hello;bar=tender; adkhfa ; asdkf===fsdaf'); $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertEquals('hello', $mock->getCookie('foo')); $this->assertEquals('tender', $mock->getCookie('bar')); $this->assertNull($mock->getCookie('asdkf')); } public function testGetLanguageLoggedUser() { $user = CMTest_TH::createUser(); $request = $this->_prepareRequest('/', null, $user); // No language at all $this->assertSame($request->getLanguage(), null); // Getting default language, user has no language $defaultLanguage = CMTest_TH::createLanguage(); $this->assertEquals($request->getLanguage(), $defaultLanguage); // Getting user language $anotherUserLanguage = CMTest_TH::createLanguage(); $user->setLanguage($anotherUserLanguage); $this->assertEquals($request->getLanguage(), $anotherUserLanguage); } public function testGetLanguageGuest() { $request = $this->_prepareRequest('/'); // No language at all $this->assertSame($request->getLanguage(), null); // Getting default language (guest has no language) $defaultLanguage = CMTest_TH::createLanguage(); $this->assertEquals($request->getLanguage(), $defaultLanguage); } public function testGetLanguageByUrl() { $request = $this->_prepareRequest('/de/home'); CM_Response_Abstract::factory($request); $this->assertNull($request->getLanguage()); CMTest_TH::createLanguage('en'); // default language $urlLanguage = CMTest_TH::createLanguage('de'); CM_Model_Language::changeAll(); // Need to flush CM_Paging_Languages_Enabled() cache $request = $this->_prepareRequest('/de/home'); CM_Response_Abstract::factory($request); $this->assertEquals($request->getLanguage(), $urlLanguage); } public function testGetLanguageByBrowser() { $defaultLanguage = CMTest_TH::createLanguage('en'); $browserLanguage = CMTest_TH::createLanguage('de'); $this->assertEquals(CM_Model_Language::findDefault(), $defaultLanguage); $request = $this->_prepareRequest('/', array('Accept-Language' => 'de')); $this->assertEquals($request->getLanguage(), $browserLanguage); $request = $this->_prepareRequest('/', array('Accept-Language' => 'pl')); $this->assertEquals($request->getLanguage(), $defaultLanguage); } public function testFactory() { $this->assertInstanceOf('CM_Request_Get', CM_Request_Abstract::factory('GET', '/test')); $this->assertInstanceOf('CM_Request_Post', CM_Request_Abstract::factory('POST', '/test')); } public function testSetUri() { $language = CM_Model_Language::createStatic(array('name' => 'english', 'abbreviation' => 'en', 'enabled' => true)); $uri = '/en/foo/bar?foo1=bar1'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive'); /** @var CM_Request_Abstract $mock */ $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertEquals($language, $mock->popPathLanguage()); $this->assertSame('/foo/bar', $mock->getPath()); $this->assertSame(array('foo', 'bar'), $mock->getPathParts()); $this->assertSame(array('foo1' => 'bar1'), $mock->getQuery()); $this->assertEquals($language, $mock->getLanguageUrl()); $mock->setUri('/foo1/bar1?foo=bar'); $this->assertSame('/foo1/bar1', $mock->getPath()); $this->assertSame(array('foo1', 'bar1'), $mock->getPathParts()); $this->assertSame(array('foo' => 'bar'), $mock->getQuery()); $this->assertNull($mock->getLanguageUrl()); } public function testSetUriRelativeAndColon() { $uri = '/foo/bar?foo1=bar1:80'; /** @var CM_Request_Abstract $mock */ $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri)); $this->assertSame('/foo/bar', $mock->getPath()); $this->assertSame(array('foo1' => 'bar1:80'), $mock->getQuery()); } public function testGetClientId() { $uri = '/en/foo/bar?foo1=bar1'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive'); /** @var CM_Request_Abstract $mock */ $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertFalse($mock->hasClientId()); $clientId = $mock->getClientId(); $this->assertInternalType('int', $clientId); $this->assertTrue($mock->hasClientId()); $uri = '/'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive', 'Cookie' => ';213q;213;=clientId=WRONG;'); /** @var CM_Request_Abstract $mock */ $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertFalse($mock->hasClientId()); $this->assertSame($clientId + 1, $mock->getClientId()); $this->assertTrue($mock->hasClientId()); $id = $mock->getClientId(); $this->assertSame($id, $mock->getClientId()); $uri = '/'; $headers = array('Host' => 'example.ch', 'Connection' => 'keep-alive', 'Cookie' => ';213q;213;=clientId=' . $id . ';'); /** @var CM_Request_Abstract $mock */ $mock = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers)); $this->assertFalse($mock->hasClientId()); $this->assertSame($id, $mock->getClientId()); $this->assertTrue($mock->hasClientId()); } public function testGetClientIdSetCookie() { $request = new CM_Request_Post('/foo/null/'); $clientId = $request->getClientId(); /** @var CM_Response_Abstract $response */ $response = $this->getMock('CM_Response_Abstract', array('_process', 'setCookie'), array($request)); $response->expects($this->once())->method('setCookie')->with('clientId', (string) $clientId); $response->process(); } public function testIsBotCrawler() { $useragents = array( 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' => true, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)' => false, 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)' => true, ); foreach ($useragents as $useragent => $expected) { $request = new CM_Request_Get('/foo', array('user-agent' => $useragent)); $this->assertSame($expected, $request->isBotCrawler()); } } public function testIsBotCrawlerWithoutUseragent() { $request = new CM_Request_Get('/foo'); $this->assertFalse($request->isBotCrawler()); } public function testGetHost() { $request = new CM_Request_Get('/', array('host' => 'www.example.com')); $this->assertSame('www.example.com', $request->getHost()); } public function testGetHostWithPort() { $request = new CM_Request_Get('/', array('host' => 'www.example.com:80')); $this->assertSame('www.example.com', $request->getHost()); } /** * @expectedException CM_Exception_Invalid */ public function testGetHostWithoutHeader() { $request = new CM_Request_Get('/'); $request->getHost(); } /** * @param string $uri * @param array|null $additionalHeaders * @param CM_Model_User|null $user * @return CM_Request_Abstract */ private function _prepareRequest($uri, array $additionalHeaders = null, CM_Model_User $user = null) { $headers = array('Host' => 'example.com', 'Connection' => 'keep-alive'); if ($additionalHeaders) { $headers = array_merge($headers, $additionalHeaders); } /** @var CM_Request_Abstract $request */ $request = $this->getMockForAbstractClass('CM_Request_Abstract', array($uri, $headers), '', true, true, true, array('getViewer')); $request->expects($this->any())->method('getViewer')->will($this->returnValue($user)); $this->assertSame($request->getViewer(), $user); return $request; } }
{ "content_hash": "85f45db5ec8e1818af2a922564b8e1dd", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 138, "avg_line_length": 45.63013698630137, "alnum_prop": 0.5945161613129191, "repo_name": "christopheschwyzer/CM", "id": "1e54aac758cf679786676843eb5a82395c4f44e9", "size": "9993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/library/CM/Request/AbstractTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46749" }, { "name": "JavaScript", "bytes": "98497" }, { "name": "PHP", "bytes": "1756966" }, { "name": "Puppet", "bytes": "188" }, { "name": "SQL", "bytes": "15796" }, { "name": "Shell", "bytes": "422" } ], "symlink_target": "" }
layout: post title: "June 2014 Meeting Summary" subtitle: "Jeff Hicks gave a presentation entitled Getting Started with Desired State Configuration (DSC)." date: 2014-06-09 11:19 author: john comments: true categories: Philadelphia Desired State Configuration Jeff Hicks presentation presentation materials --- [Jeff Hicks](http://jdhitsolutions.com/blog/) gave a presentation entitled Getting Started with Desired State Configuration (DSC). During his talked Jeff gave an overview of [DSC](http://technet.microsoft.com/en-us/library/dn249912.aspx) and walked through an example of a push mode configuration. A copy of his presentation materials are available [here](https://github.com/PhillyPoSH/2014-06-Jeff-Hicks-DSC). A [recording of this meeting](http://youtu.be/J5ru8h73F0g) has been posted to our [YouTube channel](http://www.youtube.com/channel/UCAc_ow5FIJtRpvew__9Iqzg). <iframe width="560" height="315" src="//www.youtube.com/embed/J5ru8h73F0g" frameborder="0" allowfullscreen></iframe>
{ "content_hash": "c1dfbffe9b8c00f67427e7c288977e04", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 410, "avg_line_length": 71.35714285714286, "alnum_prop": 0.7897897897897898, "repo_name": "PhillyPoSH/phillyposh.github.io", "id": "81d3cb803818abff362110c4957ccf9d0632365f", "size": "1003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2014-06-09-June-Meeting-Summary.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21519" }, { "name": "HTML", "bytes": "12767" }, { "name": "JavaScript", "bytes": "53821" }, { "name": "Ruby", "bytes": "87" } ], "symlink_target": "" }
using Jal.Router.Model; using System.Threading.Tasks; namespace Jal.Router.Patterns.Interface { public interface IMessageHandler<in TMessage> { Task Handle(TMessage message); Task HandleWithContext(TMessage message, MessageContext context); bool IsSuccessfulWithContext(TMessage message, MessageContext context); bool IsSuccessful(TMessage message); Task CompensateWithContext(TMessage message, MessageContext context); Task Compensate(TMessage message); } }
{ "content_hash": "bb0eab958cd3d3f3347910f0cee51b17", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 26.2, "alnum_prop": 0.7347328244274809, "repo_name": "raulnq/Jal.Router", "id": "93ebbd16b07d4a8b81426c7590e03688a0bf873f", "size": "524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Jal.Router.Patterns/Interface/IMessageHandler.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "835" }, { "name": "C#", "bytes": "625473" } ], "symlink_target": "" }
require('dotenv').config(); var TheMachine = require('./features/the-machine/the-machine'); new TheMachine();
{ "content_hash": "6608d97f289c05858b4ed215887c9688", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 63, "avg_line_length": 22.4, "alnum_prop": 0.7142857142857143, "repo_name": "CodeCorico/MemoryOverflow", "id": "06bfa652ebf8e1487591fde4a10c4b7f568c3de4", "size": "112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "the-machine/start.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23043" }, { "name": "HTML", "bytes": "39186" }, { "name": "JavaScript", "bytes": "55127" } ], "symlink_target": "" }
import Layer from '../../Layer' import unsqueeze from 'ndarray-unsqueeze' import tile from 'ndarray-tile' /** * RepeatVector layer class * Turns 2D tensors of shape [features] to 3D tensors of shape [n, features]. * Note there is no concept of batch size in these layers (single-batch) so we're actually going from 1D to 2D. */ export default class RepeatVector extends Layer { /** * Creates a RepeatVector layer * @param {number} attrs.n */ constructor(attrs = {}) { super(attrs) this.layerClass = 'RepeatVector' const { n = 1 } = attrs this.n = n } /** * Method for layer computational logic * @param {Tensor} x * @returns {Tensor} x */ call(x) { if (x.tensor.shape.length !== 1) { throw new Error(`${this.name} [RepeatVector layer] Only 1D tensor inputs allowed.`) } x.tensor = tile(unsqueeze(x.tensor, 0), [this.n, 1]) return x } }
{ "content_hash": "9575bba5870761557f198183b20f15f9", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 111, "avg_line_length": 26.114285714285714, "alnum_prop": 0.6389496717724289, "repo_name": "qinwf-nuan/keras-js", "id": "6f6ab9123616b35a09a85292f426807365b82e13", "size": "914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/layers/core/RepeatVector.js", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "49430" }, { "name": "HTML", "bytes": "10847" }, { "name": "JavaScript", "bytes": "2406515" }, { "name": "Jupyter Notebook", "bytes": "2340361" }, { "name": "Python", "bytes": "2970" } ], "symlink_target": "" }
from construct import * import socket import sys import subprocess import logging # monkeys were here # currently only works with AF_INET and SOCK_STREAM due # to my shitty understanding of patching getaddrinfo # but at least it doesn't leak DNS resolves TORIP="127.0.0.1" TORPORT=9050 PROTO="socks4a" # or socks5, dependent on tor-resolve USERID="anonymous" # for 4a only log = logging.getLogger("torSocket") class IpAddressAdapter(Adapter): def _encode(self, obj, context): return "".join(chr(int(b)) for b in obj.split(".")) def _decode(self, obj, context): return ".".join(str(ord(b)) for b in obj) def IpAddress(name): return IpAddressAdapter(Bytes(name, 4)) class SocksException(Exception): pass class TorSocket(): def __init__(self, *args, **kwargs): self._sock = oldSocket(socket.AF_INET, socket.SOCK_STREAM) self.connect = getattr(self, "%sconnect" % PROTO) self._sock.connect((TORIP, TORPORT)) def socks5connect(self, address): log.debug("using socks5") connect = Struct("connect", Byte("ver"), Byte("nmethods"), Byte("methods"), ) connectResponse = Struct("response", Byte("ver"), Byte("method"), ) p = Container( ver=5, nmethods=1, methods=0 ) self._sock.send(connect.build(p)) data = self._sock.recv(1024) response = connectResponse.parse(data) if response.method == 255: raise SocksException request = Struct("request", Byte("ver"), Byte("cmd"), Byte("rsv"), Byte("atyp"), IpAddress("dstaddr"), UBInt16("dstport") ) requestResponse = Struct("requestResponse", Byte("ver"), Byte("rep"), Byte("rsv"), Byte("atyp"), UBInt16("bndport") ) p = Container( ver=5, cmd=1, rsv=0, atyp=1, dstaddr=address[0], dstport=address[1] ) self._sock.send(request.build(p)) data = self._sock.recv(1024) response = requestResponse.parse(data) if response.rep != 0: raise SocksException def socks4aconnect(self, address): log.debug("using socks4a") connect = Struct("connect", Byte("ver"), Byte("cd"), UBInt16("dstport"), IpAddress("dstip"), CString("userid"), CString("domain") ) connectResponse = Struct("response", Byte("ver"), Byte("cd"), UBInt16("dstport"), IpAddress("dstip") ) p = Container( ver=4, cd=1, dstport=address[1], dstip="0.0.0.1", userid=USERID, domain=address[0] ) self._sock.send(connect.build(p)) data = self._sock.recv(1024) response = connectResponse.parse(data) if response.cd != 90: raise SocksException def connect(self, address): raise NotImplementedError def makefile(self, *args): return self._sock.makefile(*args) def sendall(self, *args): self._sock.sendall(*args) def send(self, *args): self._sock.send(*args) def recv(self, *args): return self._sock.recv(*args) def close(self): self._sock.close() def torResolve(name): log.debug("resolving %s with tor-resolve" % name) p = subprocess.Popen(['tor-resolve', name], stdout=subprocess.PIPE) ip = p.stdout.read().strip() return ip def getaddrinfo(*args): if PROTO == "socks4a": return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] elif PROTO == "socks5": ip = torResolve(args[0]) return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (ip, args[1]))] else: raise SocksException oldSocket = socket.socket oldAddrInfo = socket.getaddrinfo socket.socket = TorSocket socket.getaddrinfo = getaddrinfo socket.gethostbyname = torResolve sys.modules['socket'] = socket
{ "content_hash": "593c2df171e01ad8edacf25ad511da9b", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 74, "avg_line_length": 20.871345029239766, "alnum_prop": 0.655645839170636, "repo_name": "ActiveState/code", "id": "d7853711f65b8cdfaa81ba33cbbe9aced09a21a7", "size": "3569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipes/Python/521921_tor_socket_monkeypatch/recipe-521921.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "35894" }, { "name": "C", "bytes": "56048" }, { "name": "C++", "bytes": "90880" }, { "name": "HTML", "bytes": "11656" }, { "name": "Java", "bytes": "57468" }, { "name": "JavaScript", "bytes": "181218" }, { "name": "PHP", "bytes": "250144" }, { "name": "Perl", "bytes": "37296" }, { "name": "Perl 6", "bytes": "9914" }, { "name": "Python", "bytes": "17387779" }, { "name": "Ruby", "bytes": "40233" }, { "name": "Shell", "bytes": "190732" }, { "name": "Tcl", "bytes": "674650" } ], "symlink_target": "" }
class UserTest < ActiveSupport::TestCase def test_allows_valid_users user = User.new({ email: 'allows_valid_users@example.com', password: 'password', password_confirmation: 'password', }) user.valid?.must_equal true end end
{ "content_hash": "9c09ecfe67112d9ad59a1cd11a6cef67", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 46, "avg_line_length": 23.545454545454547, "alnum_prop": 0.6602316602316602, "repo_name": "ericboehs/stacky", "id": "c2863c1a489645032275d49b5855cf8f3a6db5c2", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/models/user_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "42677" }, { "name": "CoffeeScript", "bytes": "1325" }, { "name": "HTML", "bytes": "13815" }, { "name": "Ruby", "bytes": "62647" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>pymatgen.cli.get_environment module &#8212; pymatgen 2017.9.23 documentation</title> <link rel="stylesheet" href="_static/proBlue.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '2017.9.23', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="_static/favicon.ico"/> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-33990148-1']); _gaq.push(['_trackPageview']); </script> </head> <body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="nav-item nav-item-0"><a href="index.html">pymatgen 2017.9.23 documentation</a> &#187;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="module-pymatgen.cli.get_environment"> <span id="pymatgen-cli-get-environment-module"></span><h1>pymatgen.cli.get_environment module<a class="headerlink" href="#module-pymatgen.cli.get_environment" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="pymatgen.cli.get_environment.main"> <code class="descname">main</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/cli/get_environment.html#main"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.cli.get_environment.main" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/pymatgen.cli.get_environment.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="nav-item nav-item-0"><a href="index.html">pymatgen 2017.9.23 documentation</a> &#187;</li> </ul> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2011, Pymatgen Development Team. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.3. </div> <div class="footer">This page uses <a href="http://analytics.google.com/"> Google Analytics</a> to collect statistics. You can disable it by blocking the JavaScript coming from www.google-analytics.com. <script type="text/javascript"> (function() { var ga = document.createElement('script'); ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; ga.setAttribute('async', 'true'); document.documentElement.firstChild.appendChild(ga); })(); </script> </div> </body> </html>
{ "content_hash": "11b3a5e779875ccf727ab4d32084f9ad", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 341, "avg_line_length": 41.377049180327866, "alnum_prop": 0.6198494453248812, "repo_name": "matk86/pymatgen", "id": "ee467273028dc24acee734eed994fe410af0dd4b", "size": "5051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/pymatgen.cli.get_environment.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5938" }, { "name": "CSS", "bytes": "7550" }, { "name": "Common Lisp", "bytes": "3029065" }, { "name": "HTML", "bytes": "4886182" }, { "name": "Makefile", "bytes": "5573" }, { "name": "Perl", "bytes": "229104" }, { "name": "Propeller Spin", "bytes": "4026362" }, { "name": "Python", "bytes": "6054951" }, { "name": "Roff", "bytes": "868" } ], "symlink_target": "" }
<?php namespace Didbot\DidbotApi\Controllers; use Illuminate\Http\Request; use Didbot\DidbotApi\CustomCursor as Cursor; use Didbot\DidbotApi\Transformers\SourceTransformer; use DB; class SourceController extends Controller { /** * Display a listing of the resource. * * @param Request $request * * @return \Illuminate\Http\Response */ public function index(Request $request) { $limit = 20; $sources = $request->user()->sources() ->orderBy('id', 'DESC')->limit($limit)->get(); $results = fractal() ->collection($sources, new SourceTransformer()) ->withCursor(new Cursor($request->cursor, $request->prev, $sources, $limit)); return $results; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { abort(404); } /** * Store a newly created resource in storage. * * @return \Illuminate\Http\Response */ public function store() { abort(404); } /** * Display the specified resource. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request, $id) { abort(404); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { abort(404); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { abort(404); } /** * Remove the specified resource from storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { abort(404); } }
{ "content_hash": "80e82b8193e69744e822a4e6a3488836", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 89, "avg_line_length": 21.24, "alnum_prop": 0.5673258003766478, "repo_name": "didbot/didbot-api", "id": "f2c56b1e116b8e0475f0cf6373ae69c900b52597", "size": "2124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Controllers/SourceController.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "60171" } ], "symlink_target": "" }
package ui import ( "strings" "sync" "github.com/gdamore/tcell" "github.com/gdamore/tcell/termbox" "github.com/moncho/dry/search" ) const ( endtext = "(end)" starttext = "(start)" ) //Less is a View specialization with less-like behavior and characteristics, meaning: // * The cursor is always shown at the bottom of the screen. // * Navigation is done using less keybindings. // * Basic search is supported. type Less struct { *View searchResult *search.Result filtering bool following bool refresh chan struct{} screen *Screen renderer ScreenTextRenderer searchHitStyle tcell.Style defaultStyle tcell.Style sync.Mutex } //NewLess creates a view that partially simulates less. func NewLess(theme *ColorTheme) *Less { sd := ActiveScreen.Dimensions() view := NewView("", 0, 0, sd.Width, sd.Height, true, theme) view.cursorY = sd.Height - 1 //Last line is at height -1 less := &Less{ View: view, screen: ActiveScreen, } less.renderer = NewRenderer(screenStyledRuneRenderer{ActiveScreen}).WithWidth(sd.Width) less.searchHitStyle = mkStyle(termbox.ColorYellow, termbox.Attribute(less.View.theme.Bg)) less.defaultStyle = mkStyle(termbox.ColorWhite, termbox.Attribute(less.View.theme.Bg)) return less } //Focus sets the view as active, so it starts handling terminal events //and user actions func (less *Less) Focus(events <-chan *tcell.EventKey) error { refreshChan := make(chan struct{}, 1) less.refresh = refreshChan less.newLineCallback = func() { if less.following { //ScrollToBottom refreshes the buffer as well less.ScrollToBottom() } else { less.refreshBuffer() } } inputMode := false //This ensures at least one refresh less.refreshBuffer() go func(inputMode *bool) { inputBoxEventChan := make(chan *tcell.EventKey) inputBoxOutput := make(chan string, 1) defer close(inputBoxOutput) defer close(inputBoxEventChan) for { select { case input := <-inputBoxOutput: *inputMode = false less.search(input) less.refreshBuffer() case event := <-events: if !*inputMode { if event.Key() == tcell.KeyEsc { less.newLineCallback = func() {} close(refreshChan) return } else if event.Key() == tcell.KeyDown { //cursor down less.ScrollDown() } else if event.Key() == tcell.KeyUp { // cursor up less.ScrollUp() } else if event.Key() == tcell.KeyPgDn { //cursor one page down less.ScrollPageDown() } else if event.Key() == tcell.KeyPgUp { // cursor one page up less.ScrollPageUp() } else if event.Rune() == 'f' { //toggle follow less.flipFollow() } else if event.Rune() == 'F' { *inputMode = true less.filtering = true go less.readInput(inputBoxEventChan, inputBoxOutput) } else if event.Rune() == 'g' { //to the top of the view less.ScrollToTop() } else if event.Rune() == 'G' { //to the bottom of the view less.ScrollToBottom() } else if event.Rune() == 'N' { //to the top of the view less.gotoPreviousSearchHit() } else if event.Rune() == 'n' { //to the bottom of the view less.gotoNextSearchHit() } else if event.Rune() == '/' { *inputMode = true less.filtering = false go less.readInput(inputBoxEventChan, inputBoxOutput) } } else { inputBoxEventChan <- event } } } }(&inputMode) for range less.refresh { //If input is being read, refresh events are ignore //the only UI changes are happening on the input bar //and are done by the InputBox if !inputMode { less.screen.Clear() less.render() less.screen.Flush() } } return nil } //Search searches in the view buffer for the given pattern func (less *Less) search(pattern string) error { if pattern != "" { searchResult, err := search.NewSearch(less.lines, pattern) if err == nil { less.searchResult = searchResult if searchResult.Hits > 0 { _, y := less.Position() searchResult.InitialLine(y) less.gotoNextSearchHit() } } else { return err } } else { less.searchResult = nil } return nil } func (less *Less) readInput(inputBoxEventChan chan *tcell.EventKey, inputBoxOutput chan string) error { _, height := less.ViewSize() eb := NewInputBox(0, height, ">>> ", inputBoxOutput, inputBoxEventChan, less.theme, less.screen) eb.Focus() return nil } // Render renders the view buffer contents. func (less *Less) render() { less.Lock() defer less.Unlock() _, maxY := less.renderableArea() y := 0 bufferStart := 0 if less.bufferY < less.bufferSize() && less.bufferY > 0 { bufferStart = less.bufferY } for _, line := range less.lines[bufferStart:] { if y > maxY { break } less.renderLine(0, y, string(line)) y++ } less.renderStatusLine() less.drawCursor() } func (less *Less) flipFollow() { less.following = !less.following if less.following { less.ScrollToBottom() } else { less.refreshBuffer() } } //ScrollDown moves the cursor down one line func (less *Less) ScrollDown() { less.scrollDown(1) } //ScrollUp moves the cursor up one line func (less *Less) ScrollUp() { less.scrollUp(1) } //ScrollPageDown moves the buffer position down by the length of the screen, //at the end of buffer it also moves the cursor position to the bottom //of the screen func (less *Less) ScrollPageDown() { _, height := less.renderableArea() less.scrollDown(height) } //ScrollPageUp moves the buffer position up by the length of the screen, //at the beginning of buffer it also moves the cursor position to the beginning //of the screen func (less *Less) ScrollPageUp() { _, height := less.renderableArea() less.scrollUp(height) } //ScrollToBottom moves the cursor to the bottom of the view buffer func (less *Less) ScrollToBottom() { less.bufferY = less.bufferSize() - less.y1 less.refreshBuffer() } //ScrollToTop moves the cursor to the top of the view buffer func (less *Less) ScrollToTop() { less.bufferY = 0 less.refreshBuffer() } func (less *Less) atTheStartOfBuffer() bool { _, y := less.Position() return y == 0 } func (less *Less) atTheEndOfBuffer() bool { viewLength := less.bufferSize() _, y := less.Position() _, height := less.ViewSize() return y+height >= viewLength-1 } func (less *Less) bufferSize() int { return len(less.lines) } func (less *Less) gotoPreviousSearchHit() { sr := less.searchResult if sr != nil { x, _ := less.Position() if newy, err := sr.PreviousLine(); err == nil { less.setPosition(x, newy) } } less.refreshBuffer() } func (less *Less) gotoNextSearchHit() { sr := less.searchResult if sr != nil { x, _ := less.Position() if newY, err := sr.NextLine(); err == nil { less.setPosition(x, newY) } } less.refreshBuffer() } func (less *Less) refreshBuffer() { //Non blocking send. Since the refresh channel is buffered, losing //refresh messages because of a full buffer should not be a problem //since there is already a refresh message waiting to be processed. select { case less.refresh <- struct{}{}: default: } } //renderableArea return the part of the view size available for rendering. func (less *Less) renderableArea() (int, int) { maxX, maxY := less.ViewSize() return maxX, maxY - 1 } func (less *Less) renderLine(x int, y int, line string) (int, error) { var lines = 1 maxWidth, _ := less.renderableArea() if less.searchResult != nil { //If markup support is active then it might happen that tags are present in the line //but since we are searching, markups are ignored and coloring output is //decided here. if strings.Contains(line, less.searchResult.Pattern) { if less.markup != nil { var builder strings.Builder for _, token := range Tokenize(line, SupportedTags) { if less.markup.IsTag(token) { continue } builder.WriteString(token) } line = builder.String() } lines = less.renderer.On(x, y).WithStyle(less.searchHitStyle).WithWidth(maxWidth).Render(line) } else if !less.filtering { return less.View.renderLine(x, y, line) } } else { return less.View.renderLine(x, y, line) } return lines, nil } //scrollDown moves the buffer position down by the given number of lines func (less *Less) scrollDown(lines int) { _, height := less.ViewSize() viewLength := less.bufferSize() posX, posY := less.Position() //This is as down as scrolling can go maxY := viewLength - height if posY+lines < maxY { newOy := posY + lines if newOy >= viewLength { less.setPosition(posX, viewLength-height) } else { less.setPosition(posX, newOy) } } else { less.ScrollToBottom() } less.refreshBuffer() } //scrollUp moves the buffer position up by the given number of lines func (less *Less) scrollUp(lines int) { ox, bufferY := less.Position() if bufferY-lines >= 0 { less.setPosition(ox, bufferY-lines) } else { less.setPosition(ox, 0) } less.refreshBuffer() } func (less *Less) renderStatusLine() { maxWidth, maxLength := less.ViewSize() var cursorX = 1 status := less.statusLine() if less.atTheEndOfBuffer() { cursorX = len(endtext) } else if less.atTheStartOfBuffer() { cursorX = len(starttext) } less.renderer.On(0, maxLength).WithStyle( less.defaultStyle).WithWidth(maxWidth).Render(status) less.cursorX = cursorX } func (less *Less) statusLine() string { maxWidth, _ := less.ViewSize() var start string switch { case less.atTheStartOfBuffer(): start = starttext case less.atTheEndOfBuffer(): start = endtext default: start = ":" } var end string if less.filtering && less.searchResult != nil { end = strings.Join([]string{less.searchResult.String(), "Filter: On"}, " ") } else { end = "Filter: Off" } if less.following { end += " Follow: On" } else { end += " Follow: Off" } return strings.Join( []string{start, end}, strings.Repeat(" ", maxWidth-len(start)-len(end))) } func (less *Less) drawCursor() { less.screen.ShowCursor(less.Cursor()) }
{ "content_hash": "dca6ec7372e35caab6a82e1b2e4f7542", "timestamp": "", "source": "github", "line_count": 403, "max_line_length": 103, "avg_line_length": 24.707196029776675, "alnum_prop": 0.6745003515114995, "repo_name": "moncho/dry", "id": "edbd512677e84b522fd39b72dab917cc4e34b433", "size": "9957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/less.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "415" }, { "name": "Go", "bytes": "559811" }, { "name": "Makefile", "bytes": "3112" }, { "name": "Shell", "bytes": "8555" } ], "symlink_target": "" }
<?php namespace RK\ShowRoomModule\Base; /** * Events definition base class. */ abstract class AbstractShowRoomEvents { /** * The rkshowroommodule.showroomitem_post_load event is thrown when show room items * are loaded from the database. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postLoad() * @var string */ const SHOWROOMITEM_POST_LOAD = 'rkshowroommodule.showroomitem_post_load'; /** * The rkshowroommodule.showroomitem_pre_persist event is thrown before a new show room item * is created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::prePersist() * @var string */ const SHOWROOMITEM_PRE_PERSIST = 'rkshowroommodule.showroomitem_pre_persist'; /** * The rkshowroommodule.showroomitem_post_persist event is thrown after a new show room item * has been created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postPersist() * @var string */ const SHOWROOMITEM_POST_PERSIST = 'rkshowroommodule.showroomitem_post_persist'; /** * The rkshowroommodule.showroomitem_pre_remove event is thrown before an existing show room item * is removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preRemove() * @var string */ const SHOWROOMITEM_PRE_REMOVE = 'rkshowroommodule.showroomitem_pre_remove'; /** * The rkshowroommodule.showroomitem_post_remove event is thrown after an existing show room item * has been removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postRemove() * @var string */ const SHOWROOMITEM_POST_REMOVE = 'rkshowroommodule.showroomitem_post_remove'; /** * The rkshowroommodule.showroomitem_pre_update event is thrown before an existing show room item * is updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preUpdate() * @var string */ const SHOWROOMITEM_PRE_UPDATE = 'rkshowroommodule.showroomitem_pre_update'; /** * The rkshowroommodule.showroomitem_post_update event is thrown after an existing new show room item * has been updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomItemEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postUpdate() * @var string */ const SHOWROOMITEM_POST_UPDATE = 'rkshowroommodule.showroomitem_post_update'; /** * The rkshowroommodule.showroomalbum_post_load event is thrown when show room albums * are loaded from the database. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postLoad() * @var string */ const SHOWROOMALBUM_POST_LOAD = 'rkshowroommodule.showroomalbum_post_load'; /** * The rkshowroommodule.showroomalbum_pre_persist event is thrown before a new show room album * is created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::prePersist() * @var string */ const SHOWROOMALBUM_PRE_PERSIST = 'rkshowroommodule.showroomalbum_pre_persist'; /** * The rkshowroommodule.showroomalbum_post_persist event is thrown after a new show room album * has been created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postPersist() * @var string */ const SHOWROOMALBUM_POST_PERSIST = 'rkshowroommodule.showroomalbum_post_persist'; /** * The rkshowroommodule.showroomalbum_pre_remove event is thrown before an existing show room album * is removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preRemove() * @var string */ const SHOWROOMALBUM_PRE_REMOVE = 'rkshowroommodule.showroomalbum_pre_remove'; /** * The rkshowroommodule.showroomalbum_post_remove event is thrown after an existing show room album * has been removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postRemove() * @var string */ const SHOWROOMALBUM_POST_REMOVE = 'rkshowroommodule.showroomalbum_post_remove'; /** * The rkshowroommodule.showroomalbum_pre_update event is thrown before an existing show room album * is updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preUpdate() * @var string */ const SHOWROOMALBUM_PRE_UPDATE = 'rkshowroommodule.showroomalbum_pre_update'; /** * The rkshowroommodule.showroomalbum_post_update event is thrown after an existing new show room album * has been updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterShowRoomAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postUpdate() * @var string */ const SHOWROOMALBUM_POST_UPDATE = 'rkshowroommodule.showroomalbum_post_update'; /** * The rkshowroommodule.story_post_load event is thrown when stories * are loaded from the database. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postLoad() * @var string */ const STORY_POST_LOAD = 'rkshowroommodule.story_post_load'; /** * The rkshowroommodule.story_pre_persist event is thrown before a new story * is created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::prePersist() * @var string */ const STORY_PRE_PERSIST = 'rkshowroommodule.story_pre_persist'; /** * The rkshowroommodule.story_post_persist event is thrown after a new story * has been created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postPersist() * @var string */ const STORY_POST_PERSIST = 'rkshowroommodule.story_post_persist'; /** * The rkshowroommodule.story_pre_remove event is thrown before an existing story * is removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preRemove() * @var string */ const STORY_PRE_REMOVE = 'rkshowroommodule.story_pre_remove'; /** * The rkshowroommodule.story_post_remove event is thrown after an existing story * has been removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postRemove() * @var string */ const STORY_POST_REMOVE = 'rkshowroommodule.story_post_remove'; /** * The rkshowroommodule.story_pre_update event is thrown before an existing story * is updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preUpdate() * @var string */ const STORY_PRE_UPDATE = 'rkshowroommodule.story_pre_update'; /** * The rkshowroommodule.story_post_update event is thrown after an existing new story * has been updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postUpdate() * @var string */ const STORY_POST_UPDATE = 'rkshowroommodule.story_post_update'; /** * The rkshowroommodule.storyalbum_post_load event is thrown when story album * are loaded from the database. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postLoad() * @var string */ const STORYALBUM_POST_LOAD = 'rkshowroommodule.storyalbum_post_load'; /** * The rkshowroommodule.storyalbum_pre_persist event is thrown before a new story album * is created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::prePersist() * @var string */ const STORYALBUM_PRE_PERSIST = 'rkshowroommodule.storyalbum_pre_persist'; /** * The rkshowroommodule.storyalbum_post_persist event is thrown after a new story album * has been created in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postPersist() * @var string */ const STORYALBUM_POST_PERSIST = 'rkshowroommodule.storyalbum_post_persist'; /** * The rkshowroommodule.storyalbum_pre_remove event is thrown before an existing story album * is removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preRemove() * @var string */ const STORYALBUM_PRE_REMOVE = 'rkshowroommodule.storyalbum_pre_remove'; /** * The rkshowroommodule.storyalbum_post_remove event is thrown after an existing story album * has been removed from the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postRemove() * @var string */ const STORYALBUM_POST_REMOVE = 'rkshowroommodule.storyalbum_post_remove'; /** * The rkshowroommodule.storyalbum_pre_update event is thrown before an existing story album * is updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::preUpdate() * @var string */ const STORYALBUM_PRE_UPDATE = 'rkshowroommodule.storyalbum_pre_update'; /** * The rkshowroommodule.storyalbum_post_update event is thrown after an existing new story album * has been updated in the system. * * The event listener receives an * RK\ShowRoomModule\Event\FilterStoryAlbumEvent instance. * * @see RK\ShowRoomModule\Listener\EntityLifecycleListener::postUpdate() * @var string */ const STORYALBUM_POST_UPDATE = 'rkshowroommodule.storyalbum_post_update'; }
{ "content_hash": "ab86580005d6a070f2d0adc8786a0abe", "timestamp": "", "source": "github", "line_count": 347, "max_line_length": 107, "avg_line_length": 35.85302593659942, "alnum_prop": 0.6877260670364118, "repo_name": "rallek/showroom", "id": "1a9ddeb6cc6acaeb70761a1e80a74289cf210b97", "size": "12745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modules/RK/ShowRoomModule/Base/AbstractShowRoomEvents.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "4472" }, { "name": "CSS", "bytes": "8568" }, { "name": "HTML", "bytes": "307955" }, { "name": "JavaScript", "bytes": "41183" }, { "name": "PHP", "bytes": "1289399" }, { "name": "PowerShell", "bytes": "2952" }, { "name": "Smarty", "bytes": "46022" } ], "symlink_target": "" }
export default function(object, props) { if (!Array.isArray(props)) { return { ...object }; } return Object.keys(object || {}).reduce((memo, key) => { if (props.indexOf(key) === -1) { memo[key] = object[key]; } return memo; }, {}); }
{ "content_hash": "fb80907fffafa1c76a788b2325fda1e0", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 58, "avg_line_length": 22.083333333333332, "alnum_prop": 0.5358490566037736, "repo_name": "lexich/redux-api", "id": "6a7b4615d2938182347509d8843e286d328c3b03", "size": "265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils/omit.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "111084" } ], "symlink_target": "" }
require 'test_helper' class ViewsControllerTest < ActionDispatch::IntegrationTest setup do @workspace = workspaces(:one) @view = views(:one) end test "should get index" do get workspace_views_url(@workspace) assert_response :success end test "should get new" do get new_workspace_view_url(@workspace) assert_response :success end test "should create view" do assert_difference('@workspace.views.count') do post workspace_views_url(@workspace), params: { view: { name: @view.name + " testing" } } end assert_redirected_to workspace_view_url(@workspace, View.last) end test "should show view" do get workspace_view_url(@workspace, @view) assert_response :success end test "should get edit" do get edit_workspace_view_url(@workspace, @view) assert_response :success end test "should update view" do patch workspace_view_url(@workspace, @view), params: { view: { name: @view.name } } assert_redirected_to workspace_view_url(@workspace, @view) end test "should destroy view" do assert_difference('@workspace.views.count', -1) do delete workspace_view_url(@workspace, @view) end assert_redirected_to workspaces_url end test "should duplicate view" do assert_difference('@workspace.views.count') do get duplicate_workspace_view_url(@workspace, @view) end assert_response :redirect end test "should fail to duplicate view" do @view.duplicate get duplicate_workspace_view_url(@workspace, @view) assert_response :success assert_equal flash['error'], 'Error saving duplicate view' end end
{ "content_hash": "3819771dfb008b9db853d6d34893692f", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 95, "avg_line_length": 25.384615384615383, "alnum_prop": 0.6903030303030303, "repo_name": "gina-alaska/nasa-ace-web", "id": "f8b595d947aa6d2bdcef1bc4923c0b49a6f1f884", "size": "1681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/controllers/views_controller_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8432" }, { "name": "CoffeeScript", "bytes": "32486" }, { "name": "HTML", "bytes": "54785" }, { "name": "JavaScript", "bytes": "21791" }, { "name": "Ruby", "bytes": "112423" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>pressure_to_height_std &mdash; MetPy 0.5.1</title> <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/> <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.pressure_to_height_std.html"/> <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" /> <link rel="stylesheet" href="../../_static/theme_override.css" type="text/css" /> <link rel="index" title="Index" href="../../genindex.html"/> <link rel="search" title="Search" href="../../search.html"/> <link rel="top" title="MetPy 0.5.1" href="../../index.html"/> <link rel="up" title="calc" href="metpy.calc.html"/> <link rel="next" title="psychrometric_vapor_pressure_wet" href="metpy.calc.psychrometric_vapor_pressure_wet.html"/> <link rel="prev" title="potential_temperature" href="metpy.calc.potential_temperature.html"/> <script src="../../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../../index.html" class="icon icon-home"> MetPy <img src="../../_static/metpy_150x150.png" class="logo" /> </a> <div class="version"> 0.5.1 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="../../installguide.html">Installation Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../units.html">Unit Support</a></li> <li class="toctree-l1"><a class="reference internal" href="../../examples/index.html">MetPy Examples</a></li> <li class="toctree-l1"><a class="reference internal" href="../../tutorials/index.html">MetPy Tutorials</a></li> <li class="toctree-l1 current"><a class="reference internal" href="../index.html">The MetPy API</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="metpy.constants.html">constants</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.units.html">units</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.io.html">io</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.io.cdm.html">cdm</a></li> <li class="toctree-l2 current"><a class="reference internal" href="metpy.calc.html">calc</a><ul class="current"> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.advection.html">advection</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.convergence_vorticity.html">convergence_vorticity</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.coriolis_parameter.html">coriolis_parameter</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.density.html">density</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint.html">dewpoint</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint_rh.html">dewpoint_rh</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.dry_lapse.html">dry_lapse</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.el.html">el</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.equivalent_potential_temperature.html">equivalent_potential_temperature</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.find_intersections.html">find_intersections</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.friction_velocity.html">friction_velocity</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.geostrophic_wind.html">geostrophic_wind</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_perturbation.html">get_perturbation</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_components.html">get_wind_components</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_dir.html">get_wind_dir</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_speed.html">get_wind_speed</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.h_convergence.html">h_convergence</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.heat_index.html">heat_index</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.interpolate_nans.html">interpolate_nans</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.kinematic_flux.html">kinematic_flux</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.lcl.html">lcl</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.lfc.html">lfc</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio.html">mixing_ratio</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.moist_lapse.html">moist_lapse</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.nearest_intersection_idx.html">nearest_intersection_idx</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.parcel_profile.html">parcel_profile</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.potential_temperature.html">potential_temperature</a></li> <li class="toctree-l3 current"><a class="current reference internal" href="#">pressure_to_height_std</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.psychrometric_vapor_pressure_wet.html">psychrometric_vapor_pressure_wet</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.reduce_point_density.html">reduce_point_density</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_wet_psychrometric.html">relative_humidity_wet_psychrometric</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.resample_nn_1d.html">resample_nn_1d</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_mixing_ratio.html">saturation_mixing_ratio</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_vapor_pressure.html">saturation_vapor_pressure</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.tke.html">tke</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.v_vorticity.html">v_vorticity</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.vapor_pressure.html">vapor_pressure</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_potential_temperature.html">virtual_potential_temperature</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_temperature.html">virtual_temperature</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.calc.windchill.html">windchill</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="metpy.plots.html">plots</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.plots.ctables.html">ctables</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.gridding.html">gridding</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../developerguide.html">Developer&#8217;s Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../citing.html">Citing MetPy</a></li> <li class="toctree-l1"><a class="reference internal" href="../../references.html">References</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../index.html">MetPy</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../index.html">Docs</a> &raquo;</li> <li><a href="../index.html">The MetPy API</a> &raquo;</li> <li><a href="metpy.calc.html">calc</a> &raquo;</li> <li>pressure_to_height_std</li> <li class="wy-breadcrumbs-aside"> <a href="../../_sources/api/generated/metpy.calc.pressure_to_height_std.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="pressure-to-height-std"> <h1>pressure_to_height_std<a class="headerlink" href="#pressure-to-height-std" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="metpy.calc.pressure_to_height_std"> <code class="descclassname">metpy.calc.</code><code class="descname">pressure_to_height_std</code><span class="sig-paren">(</span><em>pressure</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/metpy/calc/basic.html#pressure_to_height_std"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#metpy.calc.pressure_to_height_std" title="Permalink to this definition">¶</a></dt> <dd><p>Convert pressure data to heights using the U.S. standard atmosphere.</p> <p>The implementation uses the formula outlined in <a class="reference internal" href="../../references.html#hobbs1977" id="id1">[Hobbs1977]</a> pg.60-61.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>pressure</strong> (<em class="xref py py-obj">pint.Quantity</em>) &#8211; Atmospheric pressure</td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><em class="xref py py-obj">pint.Quantity</em> &#8211; The corresponding height value(s)</td> </tr> </tbody> </table> <p class="rubric">Notes</p> <div class="math"> \[Z = \frac{T_0}{\Gamma}[1-\frac{p}{p_0}^\frac{R\Gamma}{g}]\]</div> </dd></dl> <div style='clear:both'></div></div> </div> <div class="articleComments"> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="metpy.calc.psychrometric_vapor_pressure_wet.html" class="btn btn-neutral float-right" title="psychrometric_vapor_pressure_wet" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="metpy.calc.potential_temperature.html" class="btn btn-neutral" title="potential_temperature" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2016, MetPy Developers. Last updated on Jul 01, 2017 at 19:04:50. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-92978945-1', 'auto'); ga('send', 'pageview'); </script> <p>Do you enjoy using MetPy? <a href="https://saythanks.io/to/unidata" class="btn btn-neutral" title="Installation Guide" accesskey="n">Say Thanks!</a> </p> </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../', VERSION:'0.5.1', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
{ "content_hash": "6fbdf6c411490175db9df9fc732ee43c", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 434, "avg_line_length": 41.95348837209303, "alnum_prop": 0.6425304878048781, "repo_name": "metpy/MetPy", "id": "c8179a5884da035521c0eaf4956e2df139234b1d", "size": "14436", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v0.5/api/generated/metpy.calc.pressure_to_height_std.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "989941" }, { "name": "Python", "bytes": "551868" } ], "symlink_target": "" }
package org.apache.hadoop.ipc; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.lang.reflect.Field; import java.lang.reflect.Method; import junit.framework.TestCase; import java.util.Arrays; import java.util.concurrent.atomic.*; import org.apache.commons.logging.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.io.UTF8; import org.apache.hadoop.io.Writable; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.authorize.AuthorizationException; import org.apache.hadoop.security.authorize.ConfiguredPolicy; import org.apache.hadoop.security.authorize.PolicyProvider; import org.apache.hadoop.security.authorize.Service; import org.apache.hadoop.security.authorize.ServiceAuthorizationManager; /** Unit tests for RPC. */ public class TestRPC extends TestCase { private static final String ADDRESS = "0.0.0.0"; public static final Log LOG = LogFactory.getLog(TestRPC.class); private static Configuration conf = new Configuration(); int datasize = 1024*100; int numThreads = 50; public TestRPC(String name) { super(name); } public interface TestProtocol extends VersionedProtocol { public static final long versionID = 1L; void ping() throws IOException; void slowPing(boolean shouldSlow) throws IOException; String echo(String value) throws IOException; String[] echo(String[] value) throws IOException; Writable echo(Writable value) throws IOException; int add(int v1, int v2) throws IOException; int add(int[] values) throws IOException; int error() throws IOException; void testServerGet() throws IOException; int[] exchange(int[] values) throws IOException; } public class TestImpl implements TestProtocol { int fastPingCounter = 0; public long getProtocolVersion(String protocol, long clientVersion) { return TestProtocol.versionID; } public void ping() {} public synchronized void slowPing(boolean shouldSlow) { if (shouldSlow) { while (fastPingCounter < 2) { try { wait(); // slow response until two fast pings happened } catch (InterruptedException ignored) {} } fastPingCounter -= 2; } else { fastPingCounter++; notify(); } } public String echo(String value) throws IOException { return value; } public String[] echo(String[] values) throws IOException { return values; } public Writable echo(Writable writable) { return writable; } public int add(int v1, int v2) { return v1 + v2; } public int add(int[] values) { int sum = 0; for (int i = 0; i < values.length; i++) { sum += values[i]; } return sum; } public int error() throws IOException { throw new IOException("bobo"); } public void testServerGet() throws IOException { if (!(Server.get() instanceof RPC.Server)) { throw new IOException("Server.get() failed"); } } public int[] exchange(int[] values) { for (int i = 0; i < values.length; i++) { values[i] = i; } return values; } public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int clientMethodsHash) throws IOException { return ProtocolSignature.getProtocolSignature( this, protocol, clientVersion, clientMethodsHash); } } // // an object that does a bunch of transactions // static class Transactions implements Runnable { int datasize; TestProtocol proxy; Transactions(TestProtocol proxy, int datasize) { this.proxy = proxy; this.datasize = datasize; } // do two RPC that transfers data. public void run() { int[] indata = new int[datasize]; int[] outdata = null; int val = 0; try { outdata = proxy.exchange(indata); val = proxy.add(1,2); } catch (IOException e) { assertTrue("Exception from RPC exchange() " + e, false); } assertEquals(indata.length, outdata.length); assertEquals(val, 3); for (int i = 0; i < outdata.length; i++) { assertEquals(outdata[i], i); } } } // // A class that does an RPC but does not read its response. // static class SlowRPC implements Runnable { private TestProtocol proxy; private volatile boolean done; SlowRPC(TestProtocol proxy) { this.proxy = proxy; done = false; } boolean isDone() { return done; } public void run() { try { proxy.slowPing(true); // this would hang until two fast pings happened done = true; } catch (IOException e) { assertTrue("SlowRPC ping exception " + e, false); } } } public void testSlowRpc() throws Exception { System.out.println("Testing Slow RPC"); // create a server with two handlers Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, 2, false, conf); TestProtocol proxy = null; try { server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); // create a client proxy = (TestProtocol)RPC.getProxy( TestProtocol.class, TestProtocol.versionID, addr, conf); SlowRPC slowrpc = new SlowRPC(proxy); Thread thread = new Thread(slowrpc, "SlowRPC"); thread.start(); // send a slow RPC, which won't return until two fast pings assertTrue("Slow RPC should not have finished1.", !slowrpc.isDone()); proxy.slowPing(false); // first fast ping // verify that the first RPC is still stuck assertTrue("Slow RPC should not have finished2.", !slowrpc.isDone()); proxy.slowPing(false); // second fast ping // Now the slow ping should be able to be executed while (!slowrpc.isDone()) { System.out.println("Waiting for slow RPC to get done."); try { Thread.sleep(1000); } catch (InterruptedException e) {} } } finally { server.stop(); if (proxy != null) { RPC.stopProxy(proxy); } System.out.println("Down slow rpc testing"); } } public void testDnsUpdate() throws Exception { int oldMaxRetry = conf.getInt("ipc.client.connect.max.retries", 10); int oldmaxidletime = conf.getInt("ipc.client.connection.maxidletime", 10000); InetAddress oldAddr = null; InetSocketAddress addr = null; Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, conf); TestProtocol proxy = null; try { server.start(); addr = NetUtils.getConnectAddress(server); oldAddr = addr.getAddress(); conf.setInt("ipc.client.connect.max.retries", 0); conf.setInt("ipc.client.connection.maxidletime", 500); proxy = (TestProtocol) RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); // Since we change the addr object. We have to wait for the // connection cache to expire before we issue issue RPC. // In real case it is not necessary since addr won't change. Thread.sleep(1000); Field addressField = addr.getClass().getDeclaredField("addr"); addressField.setAccessible(true); addressField.set(addr, InetAddress.getByName("66.66.66.66")); Field hostField = addr.getClass().getDeclaredField("hostname"); hostField.setAccessible(true); hostField.set(addr, "localhost"); try { proxy.echo("foo"); TestCase.fail(); } catch (IOException e) { LOG.info("Caught " + e); } String stringResult = proxy.echo("foo"); TestCase.assertEquals("foo", stringResult); try { proxy.error(); TestCase.fail(); } catch (IOException e) { LOG.debug("Caught " + e); } } finally { server.stop(); if (proxy != null) RPC.stopProxy(proxy); conf.setInt("ipc.client.connect.max.retries", oldMaxRetry); conf.setInt("ipc.client.connection.maxidletime", oldmaxidletime); } } public void testCalls() throws Exception { Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, conf); TestProtocol proxy = null; try { server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); proxy = (TestProtocol)RPC.getProxy( TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); String stringResult = proxy.echo("foo"); assertEquals(stringResult, "foo"); stringResult = proxy.echo((String)null); assertEquals(stringResult, null); String[] stringResults = proxy.echo(new String[]{"foo","bar"}); assertTrue(Arrays.equals(stringResults, new String[]{"foo","bar"})); stringResults = proxy.echo((String[])null); assertTrue(Arrays.equals(stringResults, null)); UTF8 utf8Result = (UTF8)proxy.echo(new UTF8("hello world")); assertEquals(utf8Result, new UTF8("hello world")); utf8Result = (UTF8)proxy.echo((UTF8)null); assertEquals(utf8Result, null); int intResult = proxy.add(1, 2); assertEquals(intResult, 3); intResult = proxy.add(new int[] {1, 2}); assertEquals(intResult, 3); boolean caught = false; try { proxy.error(); } catch (IOException e) { LOG.debug("Caught " + e); caught = true; } assertTrue(caught); proxy.testServerGet(); // create multiple threads and make them do large data transfers System.out.println("Starting multi-threaded RPC test..."); server.setSocketSendBufSize(1024); Thread threadId[] = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { Transactions trans = new Transactions(proxy, datasize); threadId[i] = new Thread(trans, "TransactionThread-" + i); threadId[i].start(); } // wait for all transactions to get over System.out.println("Waiting for all threads to finish RPCs..."); for (int i = 0; i < numThreads; i++) { try { threadId[i].join(); } catch (InterruptedException e) { i--; // retry } } // try some multi-calls Method echo = TestProtocol.class.getMethod("echo", new Class[] { String.class }); String[] strings = (String[])RPC.call(echo, new String[][]{{"a"},{"b"}}, new InetSocketAddress[] {addr, addr}, conf); assertTrue(Arrays.equals(strings, new String[]{"a","b"})); Method ping = TestProtocol.class.getMethod("ping", new Class[] {}); Object[] voids = (Object[])RPC.call(ping, new Object[][]{{},{}}, new InetSocketAddress[] {addr, addr}, conf); assertEquals(voids, null); } finally { server.stop(); if(proxy!=null) RPC.stopProxy(proxy); } } public void testStandaloneClient() throws IOException { try { RPC.waitForProxy(TestProtocol.class, TestProtocol.versionID, new InetSocketAddress(ADDRESS, 20), conf, 15000L); fail("We should not have reached here"); } catch (ConnectException ioe) { //this is what we expected } } private static final String ACL_CONFIG = "test.protocol.acl"; private static class TestPolicyProvider extends PolicyProvider { @Override public Service[] getServices() { return new Service[] { new Service(ACL_CONFIG, TestProtocol.class) }; } } private void doRPCs(Configuration conf, boolean expectFailure) throws Exception { SecurityUtil.setPolicy(new ConfiguredPolicy(conf, new TestPolicyProvider())); Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, 5, true, conf); TestProtocol proxy = null; server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); try { proxy = (TestProtocol)RPC.getProxy( TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); if (expectFailure) { fail("Expect RPC.getProxy to fail with AuthorizationException!"); } } catch (RemoteException e) { if (expectFailure) { assertTrue(e.unwrapRemoteException() instanceof AuthorizationException); } else { throw e; } } finally { server.stop(); if (proxy != null) { RPC.stopProxy(proxy); } } } public void testAuthorization() throws Exception { Configuration conf = new Configuration(); conf.setBoolean( ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, true); // Expect to succeed conf.set(ACL_CONFIG, "*"); doRPCs(conf, false); // Reset authorization to expect failure conf.set(ACL_CONFIG, "invalid invalid"); doRPCs(conf, true); } public void testRPCInterrupted() throws IOException, InterruptedException { final MiniDFSCluster cluster; Configuration conf = new Configuration(); cluster = new MiniDFSCluster(conf, 3, true, null); final AtomicBoolean passed = new AtomicBoolean(false); try { cluster.waitActive(); Thread rpcThread = new Thread(new Runnable() { @Override public void run() { FileSystem fs = null; try { fs = cluster.getUniqueFileSystem(); int i = 0; while (true) { fs.create(new Path(String.format("/file-%09d", i++))); fs.listStatus(new Path("/")); } } catch (IOException e) { if (e.getCause() instanceof InterruptedException) { // the underlying InterruptedException should be wrapped to an // IOException and end up here passed.set(true); } else { passed.set(false); fail(e.getMessage()); } } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { passed.set(false); LOG.error(e); fail(e.toString()); } } } } }); FileSystem fs2 = cluster.getUniqueFileSystem(); rpcThread.start(); Thread.sleep(1000); rpcThread.interrupt(); rpcThread.join(); FileStatus[] statuses = fs2.listStatus(new Path("/")); assertTrue("expect at least 1 file created", statuses.length > 0); assertTrue("error in writing thread, see above", passed.get()); } finally { cluster.shutdown(); } } public static void main(String[] args) throws Exception { new TestRPC("test").testCalls(); } }
{ "content_hash": "c8f8535282cb2d148ac762e068164a40", "timestamp": "", "source": "github", "line_count": 500, "max_line_length": 86, "avg_line_length": 29.78, "alnum_prop": 0.6268636668905305, "repo_name": "iVCE/RDFS", "id": "755b2e6ee0e4645fa98dd89e5045f18d9e4a37a8", "size": "15696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/org/apache/hadoop/ipc/TestRPC.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "1817" }, { "name": "C", "bytes": "519569" }, { "name": "C++", "bytes": "250515" }, { "name": "CSS", "bytes": "39718" }, { "name": "Erlang", "bytes": "44463" }, { "name": "Java", "bytes": "19378398" }, { "name": "JavaScript", "bytes": "387630" }, { "name": "PHP", "bytes": "101295" }, { "name": "Perl", "bytes": "74440" }, { "name": "Python", "bytes": "475166" }, { "name": "R", "bytes": "55" }, { "name": "Shell", "bytes": "1478533" }, { "name": "XSLT", "bytes": "14484" } ], "symlink_target": "" }
<!doctype html> <html lang="en" ng-app="spBlogger"> <head> <meta charset="utf-8"> <base href="/"> <title>The Single Page Blogger</title> <link rel="stylesheet" href="built/app.min.css"/> </head> <body> <div class="container"> <br/> <div class="jumbotron text-center"> <h1>The Single Page Blogger</h1> <p>One stop blogging solution</p> </div> <div ui-view></div> <div class="row footer"> <div class="col-xs-12 text-center"> <p>The Single Page Blogger <app-version/></p> </div> </div> </div> </body> <script src="built/app.min.js"></script> </html>
{ "content_hash": "b834b81522f15dedf39ad781599583f3", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 51, "avg_line_length": 24.08, "alnum_prop": 0.6046511627906976, "repo_name": "zgithubber/sp-blogger", "id": "a2f90d2ccff449833acc145e49766bb9331d173c", "size": "602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/app/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "561" }, { "name": "CSS", "bytes": "1398" }, { "name": "HTML", "bytes": "8184" }, { "name": "JavaScript", "bytes": "25414" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "2150" } ], "symlink_target": "" }
/* $NetBSD: portald.h,v 1.10 2009/12/05 20:11:02 pooka Exp $ */ /* * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software donated to Berkeley by * Jan-Simon Pendry. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: Id: portald.h,v 1.1 1992/05/25 21:43:09 jsp Exp * @(#)portald.h 8.1 (Berkeley) 6/5/93 */ #include <sys/cdefs.h> /* * Meta-chars in an RE. Paths in the config file containing * any of these characters will be matched using regexec, other * paths will be prefix-matched. */ #define RE_CHARS ".|()[]*+?\\^$" typedef struct qelem qelem; struct qelem { qelem *q_forw; qelem *q_back; }; struct portal_cred { int pcr_flag; /* File open mode */ uid_t pcr_uid; /* From cred */ gid_t pcr_gid; /* From cred */ uint16_t pcr_ngroups; /* From cred */ gid_t pcr_groups[NGROUPS]; /* From cred */ }; typedef struct provider provider; struct provider { const char *pr_match; int (*pr_func)(struct portal_cred *, char *key, char **v, int *fdp); }; extern provider providers[]; /* * Portal providers */ extern int portal_exec(struct portal_cred *, char *key, char **v, int *fdp); extern int portal_file(struct portal_cred *, char *key, char **v, int *fdp); extern int portal_tcp(struct portal_cred *, char *key, char **v, int *fdp); extern int portal_rfilter(struct portal_cred *, char *key, char **v, int *fdp); extern int portal_wfilter(struct portal_cred *, char *key, char **v, int *fdp); /* * Global functions */ extern void activate(qelem *q, int so); extern int activate_argv(struct portal_cred *, char *, char **, int *); extern char **conf_match(qelem *q, char *key); extern int conf_read(qelem *q, const char *conf); extern int lose_credentials(struct portal_cred *);
{ "content_hash": "3f3ba60434153faba0a0ba6022b4e563", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 77, "avg_line_length": 35.934065934065934, "alnum_prop": 0.709480122324159, "repo_name": "execunix/vinos", "id": "58cb20c5ab29ddf196723da72171055641f8dfe4", "size": "3270", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sbin/mount_portal/portald.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
use core::pso; use comptr::ComPtr; use winapi; use std::collections::BTreeMap; #[derive(Clone, Debug, Hash)] pub struct ShaderLib { pub shaders: BTreeMap<pso::EntryPoint, ComPtr<winapi::ID3DBlob>>, } unsafe impl Send for ShaderLib {} unsafe impl Sync for ShaderLib {} #[derive(Clone, Debug, Hash)] pub struct RenderPass; unsafe impl Send for RenderPass {} unsafe impl Sync for RenderPass {} #[derive(Clone, Debug, Hash)] pub struct GraphicsPipeline { pub inner: ComPtr<winapi::ID3D12PipelineState>, } unsafe impl Send for GraphicsPipeline {} unsafe impl Sync for GraphicsPipeline {} #[derive(Clone, Debug, Hash)] pub struct ComputePipeline { pub inner: ComPtr<winapi::ID3D12PipelineState>, } unsafe impl Send for ComputePipeline {} unsafe impl Sync for ComputePipeline {} #[derive(Clone, Debug, Hash)] pub struct PipelineLayout { pub inner: ComPtr<winapi::ID3D12RootSignature>, } unsafe impl Send for PipelineLayout {} unsafe impl Sync for PipelineLayout {} pub struct CommandBuffer { pub inner: ComPtr<winapi::ID3D12GraphicsCommandList>, } pub struct GeneralCommandBuffer(pub CommandBuffer); pub struct GraphicsCommandBuffer(pub CommandBuffer); pub struct ComputeCommandBuffer(pub CommandBuffer); pub struct TransferCommandBuffer(pub CommandBuffer); pub struct SubpassCommandBuffer(pub CommandBuffer); #[derive(Clone, Debug, Hash)] pub struct Buffer { pub resource: ComPtr<winapi::ID3D12Resource>, pub size: u32, } unsafe impl Send for Buffer {} unsafe impl Sync for Buffer {} #[derive(Clone, Debug, Hash)] pub struct Image { pub resource: ComPtr<winapi::ID3D12Resource>, } unsafe impl Send for Image {} unsafe impl Sync for Image {} #[derive(Clone, Debug)] pub struct RenderTargetView { pub handle: winapi::D3D12_CPU_DESCRIPTOR_HANDLE, } #[derive(Clone, Debug)] pub struct DepthStencilView { pub handle: winapi::D3D12_CPU_DESCRIPTOR_HANDLE, } #[derive(Debug)] pub struct Fence; #[derive(Debug)] pub struct Semaphore; #[derive(Debug)] pub struct FrameBuffer;
{ "content_hash": "c217b1d35f3ed3d5c130b48d57e158e9", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 69, "avg_line_length": 23.476744186046513, "alnum_prop": 0.7508667657256067, "repo_name": "JohnColanduoni/gfx", "id": "eb5eda55f5b5c48a57aba23b75e421e55374a964", "size": "2619", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/backend/dx12ll/src/native.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "1099228" }, { "name": "Shell", "bytes": "666" } ], "symlink_target": "" }
<?php namespace Oro\Bundle\DataGridBundle\Event; use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration; use Oro\Bundle\DataGridBundle\Datagrid\ParameterBag; use Symfony\Component\EventDispatcher\Event; /** * Class PreBuild * @package Oro\Bundle\DataGridBundle\Event * * This event dispatched at start of datagrid builder * Listeners could apply validation of config and provide changes of config */ class PreBuild extends Event implements GridConfigurationEventInterface { const NAME = 'oro_datagrid.datagrid.build.pre'; /** @var DatagridConfiguration */ protected $config; /** @var ParameterBag */ protected $parameters; public function __construct(DatagridConfiguration $config, ParameterBag $parameters) { $this->config = $config; $this->parameters = $parameters; } /** * @return ParameterBag */ public function getParameters() { return $this->parameters; } /** * {@inheritdoc} */ public function getConfig() { return $this->config; } }
{ "content_hash": "9591760bf66d61e0d18393ebb08f68fc", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 88, "avg_line_length": 23.148936170212767, "alnum_prop": 0.6801470588235294, "repo_name": "orocrm/platform", "id": "ed8bd7422f752e7f2ec2c90e104422d9b1ac1d60", "size": "1088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Oro/Bundle/DataGridBundle/Event/PreBuild.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
TSMarkdownParser ================ [![Build Status](https://travis-ci.org/laptobbe/TSMarkdownParser.svg)](https://travis-ci.org/laptobbe/TSMarkdownParser) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Version](https://img.shields.io/cocoapods/v/TSMarkdownParser.svg)](http://cocoadocs.org/docsets/TSMarkdownParser) [![Platform](https://img.shields.io/cocoapods/p/TSMarkdownParser.svg)](http://cocoadocs.org/docsets/TSMarkdownParser) [![Licence](https://img.shields.io/cocoapods/l/TSMarkdownParser.svg)](http://cocoadocs.org/docsets/TSMarkdownParser) TSMarkdownParser is a markdown to NSAttributedString parser for iOS implemented using NSRegularExpressions. It supports many of the standard tags layed out by John Gruber on his site [Daring Fireball](http://daringfireball.net/projects/markdown/syntax). It is also very extendable via Regular Expressions making it easy to add your own custom tags or a totally different parsing syntax if you like. # Supported tags Below is a list of tags supported by the parser out of the box, to add your own tags see "Adding custom parsing" ```` Escaping \` `code` ``code`` Headings # H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 Lists * item ** item + item ++ item - item -- item Quotes > text >> text Images ![Alternative text](image.png) URL [Link text](https://www.example.net) Autodetection https://www.example.net Emphasis *Em* _Em_ **Strong** __Strong__ ```` # Requirements TSMarkdownParser 2.x requires Xcode 7 or newer. # Installation TSMarkdownParser is distributed via CocoaPods ````ruby pod 'TSMarkdownParser' ```` alternativly you can clone the project and build the static library setup in the project, or drag the source files into you project. # Usage The standardParser class method provides a new instance of the parser configured to parse the tags listed above. You can also just create a new instance of TSMarkdownParser and add your own parsing. See "Adding custom parsing" for information on how to do this. ````objc NSAttributedString *string = [[TSMarkdownParser standardParser] attributedStringFromMarkdown:markdown]; ```` # Customizing appearance You can configure how the markdown is to be displayed by changing the different properties on a TSMarkdownParser instance. Alternatively you could implement the parsing yourself and add custom attributes to the attributed string. You can also alter the attributed string returned from the parser. # Adding custom parsing Below is an example of how parsing of the bold tag is implemented. You can add your own parsing using the same addParsingRuleWithRegularExpression:block: method. You can add a parsing rule to the standardParser or to your own instance of the parser. If you want to use any of the configuration properties within makesure you use a weak reference to the parser so you don't create a retain cycle. ````objc NSRegularExpression *boldParsing = [NSRegularExpression regularExpressionWithPattern:@"(\\*\\*|__)(.+?)(\\1)" options:kNilOptions error:nil]; __weak TSMarkdownParser *weakSelf = self; [self addParsingRuleWithRegularExpression:boldParsing block:^(NSTextCheckingResult *match, NSMutableAttributedString *attributedString) { [attributedString deleteCharactersInRange:[match rangeAtIndex:3]]; [attributedString addAttributes:weakSelf.strongAttributes range:[match rangeAtIndex:2]; [attributedString deleteCharactersInRange:[match rangeAtIndex:1]]; }]; ```` # License TSMarkdownParser is distributed under a MIT licence, see the licence file for more info.
{ "content_hash": "23d1776940c001261166c6a10da1bfd3", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 398, "avg_line_length": 37.65625, "alnum_prop": 0.7753803596127248, "repo_name": "laptobbe/TSMarkdownParser", "id": "c8cbc2035bc48253ec27f1102892548623b1a783", "size": "3615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "94540" }, { "name": "Ruby", "bytes": "2135" }, { "name": "Swift", "bytes": "981" } ], "symlink_target": "" }
class EndUserAddressSegmentField < UserSegment::FieldHandler def self.user_segment_fields_handler_info { :name => 'User Address Fields', :domain_model_class => EndUserAddress, } end register_field :home_address, EndUserAddressSegmentType::AddressStringType, :name => 'Home Address', :field => :address register_field :home_address_2, EndUserAddressSegmentType::AddressStringType, :name => 'Home Address (2)', :field => :address_2 register_field :home_phone, EndUserAddressSegmentType::AddressStringType, :name => 'Home Phone', :field => :phone register_field :home_city, EndUserAddressSegmentType::AddressStringType, :name => 'Home City', :field => :city register_field :home_state, EndUserAddressSegmentType::AddressStringType, :name => 'Home State', :field => :state register_field :home_zip, EndUserAddressSegmentType::AddressStringType, :name => 'Home Zip', :field => :zip register_field :home_country, EndUserAddressSegmentType::AddressStringType, :name => 'Home Country', :field => :country register_field :work_address, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work Address', :field => :address register_field :work_address_2, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work Address (2)', :field => :address_2 register_field :work_phone, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work Phone', :field => :phone register_field :work_city, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work City', :field => :city register_field :work_state, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work State', :field => :state register_field :work_zip, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work Zip', :field => :zip register_field :work_country, EndUserAddressSegmentType::WorkAddressStringType, :name => 'Work Country', :field => :country def self.get_handler_data(ids, fields) data = {} field_prefix = fields.map { |fld| fld.to_s.split("_")[0] }.compact.uniq field_mapping = { 'home' => 'address_id', 'work' => 'work_address_id' } field_prefix.each do |prefix| address_type = field_mapping[prefix] data[prefix] = EndUserAddress.find(:all, :conditions => ["end_user_id in (?) AND end_users.#{address_type} = end_user_addresses.id", ids ],:joins => :end_user).index_by(&:end_user_id) if address_type end data end def self.field_output(user, handler_data, field) prefix = field.to_s.split("_")[0] if handler_data[prefix] UserSegment::FieldType.field_output(user, handler_data[prefix],field) else "" end end end
{ "content_hash": "cd52cf3271a5e4f1256b44a88d202cda", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 206, "avg_line_length": 50.78846153846154, "alnum_prop": 0.7118515713744794, "repo_name": "cykod/Webiva", "id": "74961ccacdc2d973bdf9af2ef668111d16515d88", "size": "2642", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/models/end_user_address_segment_field.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1603531" }, { "name": "PHP", "bytes": "19204" }, { "name": "Perl", "bytes": "4042" }, { "name": "Ruby", "bytes": "3033832" }, { "name": "Shell", "bytes": "17397" } ], "symlink_target": "" }
package org.apache.amber.signature; import java.net.URI; import java.util.Collection; import java.util.SortedSet; import java.util.TreeSet; import org.apache.amber.HTTPMethod; import org.apache.amber.OAuthMessageParameter; import org.apache.amber.OAuthParameter; import org.apache.amber.OAuthParameterLocation; import org.apache.amber.OAuthRequest; import org.apache.amber.OAuthRequestParameter; /** * * @version $Id$ */ final class FakeOAuthRequest implements OAuthRequest { private HTTPMethod httpMethod; private URI requestURL; private OAuthParameterLocation parameterLocation; private final SortedSet<OAuthMessageParameter> messageParameters = new TreeSet<OAuthMessageParameter>(); private final SortedSet<OAuthRequestParameter> requestParameters = new TreeSet<OAuthRequestParameter>(); public void addOAuthMessageParameter(OAuthMessageParameter parameter) { this.messageParameters.add(parameter); } public void addOAuthRequestParameter(OAuthRequestParameter parameter) { this.requestParameters.add(parameter); } public HTTPMethod getHTTPMethod() { return this.httpMethod; } public void setHTTPMethod(HTTPMethod httpMethod) { this.httpMethod = httpMethod; } public OAuthParameterLocation getParameterLocation() { return this.parameterLocation; } public void setParameterLocation(OAuthParameterLocation parameterLocation) { this.parameterLocation = parameterLocation; } public Collection<OAuthMessageParameter> getOAuthMessageParameters() { return this.messageParameters; } public Collection<OAuthRequestParameter> getOAuthRequestParameters() { return this.requestParameters; } public URI getRequestURL() { return this.requestURL; } public void setRequestURL(URI requestURL) { this.requestURL = requestURL; } public String getOAuthMessageParameter(OAuthParameter parameter) { for (OAuthMessageParameter omp : this.messageParameters) { if (omp.getKey().equals(parameter)) { return omp.getValue(); } } return null; // not ideal, but it's only a test } public String getOAuthRequestParameter(String name) { for (OAuthRequestParameter orp : this.requestParameters) { if (orp.getKey().equals(name)) { return orp.getValue(); } } return null; // not ideal, but it's only a test } }
{ "content_hash": "f3e3a051e2e06052ca4659bb46ff2998", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 109, "avg_line_length": 28.1, "alnum_prop": 0.7054171609331752, "repo_name": "jimbarritt/amber", "id": "9973e72e30780339f246905e37c10dac7dc177e0", "size": "3331", "binary": false, "copies": "3", "ref": "refs/heads/trunk", "path": "signature-api/src/test/java/org/apache/amber/signature/FakeOAuthRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "625977" }, { "name": "JavaScript", "bytes": "31882" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title>ACE</title> <meta charset="utf-8" /> <style type="text/css" media="screen"> body { overflow: hidden; } #editor { margin: 0; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } </style> </head> <body> <pre id="editor"></pre> <script src="editor/ace.js" type="text/javascript" charset="utf-8"></script> <script src="editor/ext-language_tools.js"></script> <script> ace.require("ace/ext/language_tools"); var editor = ace.edit("editor"); editor.setOptions({ showInvisibles : true, useWorker : false, mode : "ace/mode/itrysql", theme : "ace/theme/itrysql", enableBasicAutocompletion: true, enableSnippets : false, enableLiveAutocompletion : false }); </script> </body> </html>
{ "content_hash": "f0fbb41babe0a450701cd9ec742958f4", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 77, "avg_line_length": 18.125, "alnum_prop": 0.5724137931034483, "repo_name": "Silent-Fred/iTrySQL", "id": "7f33ab5874a6ed530a0e01393bb43199184e5e92", "size": "870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/external-resources/ace/sql_editor.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "209" }, { "name": "CSS", "bytes": "5335" }, { "name": "HTML", "bytes": "101496" }, { "name": "Java", "bytes": "841354" }, { "name": "JavaScript", "bytes": "5943" }, { "name": "Shell", "bytes": "211" }, { "name": "TSQL", "bytes": "500578" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name null ### Remarks null
{ "content_hash": "bcd1cfaf6f4a1e21ce94cecc6712f5bd", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 18, "avg_line_length": 8.384615384615385, "alnum_prop": 0.6788990825688074, "repo_name": "mdoering/backbone", "id": "097369e05ea7edd74c55f9bb781dc6d7a75f591b", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Candelariales/Candelariaceae/Candelaria/Candelaria indica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>code</title> <link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg"> <script>var pathToRoot = "../../../../";</script> <script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script> <link href="../../../../styles/style.css" rel="Stylesheet"> <link href="../../../../styles/logo-styles.css" rel="Stylesheet"> <link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../../styles/main.css" rel="Stylesheet"> <script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/main.js" async="async"></script> </head> <body> <div id="container"> <div id="leftColumn"> <div id="logo"></div> <div id="paneSearch"></div> <div id="sideMenu"></div> </div> <div id="main"> <div id="leftToggler"><span class="icon-toggler"></span></div> <script type="text/javascript" src="../../../../scripts/pages.js"></script> <script type="text/javascript" src="../../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="org.hexworks.zircon.api.uievent/KeyCode.KEY_O/code/#/PointingToDeclaration//-828656838"> <div class="navigation-wrapper" id="navigation-wrapper"> <div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.api.uievent</a>/<a href="../index.html">KeyCode</a>/<a href="index.html">KEY_O</a>/<a href="code.html">code</a></div> <div class="pull-right d-flex"> <div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div> <div id="searchBar"></div> </div> </div> <div class="cover "> <h1 class="cover"><span>code</span></h1> </div> <div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div> <div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">val <a href="code.html">code</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html">Int</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div> </div> <p class="paragraph">The unicode key code for the given key</p></div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
{ "content_hash": "df4870e1212f3e8dd0058f5e1da566e5", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 559, "avg_line_length": 70.33333333333333, "alnum_prop": 0.624756063562866, "repo_name": "Hexworks/zircon", "id": "3a1d9781c56fd6e268a476326a0983bf39f1b337", "size": "3588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.uievent/-key-code/-k-e-y_-o/code.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "121457" }, { "name": "Kotlin", "bytes": "1792092" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
from __future__ import division from operator import and_ from os import getcwd, makedirs, path import re from struct import calcsize, unpack from sys import exit from warnings import warn import numpy as np from rpy2.rinterface import NULL, TRUE from rpy2.robjects import numpy2ri from rpy2.robjects.packages import importr from sklearn.manifold import TSNE from . import Tree_classes __all__ = ['Annotation', 'cytometry_preprocess', 'Cyto_data', 'FCS_handler', 'get_FCS_data', 'infer_pseudotime', 'PCR_preprocess', 'RNASeq_preprocess'] def infer_pseudotime(data, output_directory, tag = '', pcv_method = 'Rprincurve', anchor_gene = None, markers = None): assert pcv_method in {'Rprincurve'} # taking into account the possibility of adding # in future versions other methods # for principal curve analysis N_dim = 3 model = TSNE(n_components = N_dim) TSNE_data = model.fit_transform(data) if pcv_method == 'Rprincurve': with open(path.join(output_directory, "{0}_TSNE_d{1}.tsv".format(tag, N_dim)), 'w') as f: f.write('\t'.join(['T{0}'.format(k) for k in xrange(1, N_dim + 1)])) f.write('\n') np.savetxt(f, TSNE_data, fmt = '%.6f', delimiter = '\t') numpy2ri.activate() princurve = importr('princurve') procedure = princurve.principal_curve fitpc = procedure(TSNE_data, NULL, 0.001, TRUE, 200, 2, 'lowess') curve_projections_matrix = np.array(fitpc.rx('s')[0]) pseudotime_series = np.array(fitpc.rx('lambda')[0]) with open(path.join(output_directory, "{0}_TSNE_d{1}_pcv.tsv".format(tag, N_dim)), 'w') as f: np.savetxt(f, curve_projections_matrix, fmt = '%.6f', delimiter = '\t') with open(path.join(output_directory, "{0}_TSNE_d{1}_lambda.tsv".format(tag, N_dim)), 'w') as f: np.savetxt(f, pseudotime_series, fmt = '%.6f', delimiter = '\t') else: print("ERROR: PySCUBA: Preprocessing: infer_pseudotime:\n" "your choice of method for principal curve analysis is not supported " "by the present version of PySCUBA.") exit(1) if anchor_gene: assert isinstance(anchor_gene, str) assert markers is not None N_cells_anchor = 1000 gene_idx = np.where(markers == anchor_gene)[0] pseudotime_idx = np.argsort(pseudotime_series) anchor_gene_avg_beg = np.mean(data[pseudotime_idx[:N_cells_anchor], gene_idx]) anchor_gene_avg_end = np.mean(data[pseudotime_idx[N_cells_anchor:], gene_idx]) if anchor_gene_avg_end > anchor_gene_avg_beg: pseudotime_series = np.max(pseudotime_series) - pseudotime_series t_min = np.min(pseudotime_series) t_max = np.max(pseudotime_series) t_bins = 8 cell_stages = t_bins * (pseudotime_series - t_min + 0.0001) / (t_max - t_min + 0.0002) cell_stages = np.ceil(cell_stages).astype(int).astype('str') return cell_stages def parse_pairs(text): """Return (key, value) pairs from a string featuring particular delimiters. Modified from a corresponding function in the outdated 'fcm' Python package by Jacob Frelinger. """ delim = text[0] if delim == r'|': delim = '\|' elif delim == r'\a'[0]: delim = '\\\\' if delim != text[-1]: warn("WARNING: the text does not start and end with the same delimiter!") regex = re.compile('(?<=[^%s])%s(?!%s)' % (delim, delim, delim)) tmp = text[1:-1].replace('$', '') tmp = regex.split(tmp) return dict(zip([x.lower() for x in tmp[::2]], tmp[1::2])) class Annotation(object): """An annotation class instance stores meta-data from the recordings of a cytometry experiment. Modified from a corresponding class in the outdated 'fcm' Python package by Jacob Frelinger. """ def __init__(self, annotations = None): if annotations == None: annotations = {} self.__dict__['_mydict'] = annotations def __getattr__(self, name): if name in self._mydict.keys(): self.__dict__[name] = self._mydict[name] return self._mydict[name] else: try: return self._mydict.__getattribute__(name) except: raise AttributeError("'{0}' has no attribue '{1}'".format(str(self.__class__), name)) def __getstate__(self): return self._mydict def __setstate__(self, dict): self.__dict__['_mydict'] = dict for i in dict.keys(): self.__dict__[i] = dict[i] def __setattr__(self, name, value): Annotation.__getattribute__(self, '_mydict')[name] = value self.__dict__[name] = value def __setitem__(self, name, value): self._mydict[name] = value self.__dict__[name] = self._mydict[name] def __getitem__(self, name): return self._mydict[name] def __repr__(self): return 'Annotation(' + self._mydict.__repr__() + ')' def __getstate__(self): return self.__dict__ def __setstate(self, state): self.__dict__ = state def __getinitargs__(self): return (self._mydict,) def copy(self): return Annotation(self._mydict.copy()) class Cyto_data(object): """ A Cyto_data object stores the data from a cytometry experiment. Modified from a corresponding class in the outdated 'fcm' Python package by Jacob Frelinger. Members: -------- Cyto_data.data_points : numpy.array The data points. Cyto_data.channels : list Records which markers or scatters are in which columns. Cyto_data.scatters : list Keeps track of which indexes in Cyto_data.channels are scatters. """ def __init__(self, name, data_points, channels, scatters = None, notes = None): """ Parameters ---------- name: name of the *.fcs file, barring any extension data_points: an array of data points channels: list Records which markers/scatters are in which columns. scatters: list Which channels indexes denote scatters """ self.name = name self.data_points = data_points self.tree = Tree_classes.Tree(data_points, channels) self.scatters = scatters self.markers = [] if self.scatters is not None: for channel in range(len(channels)): if channel in self.scatters: pass elif self.tree.root.channels[channel] in self.scatters: pass else: self.markers.append(channel) if notes == None: notes = Annotation() self.notes = notes def __unicode__(self): return self.name def __repr__(self): return self.name def __getitem__(self, item): """Return the Cyto_data points. """ if isinstance(item, tuple): item = list(item) if isinstance(item[1], str): item[1] = self.name_to_index(item[1]) elif isinstance(item[1], tuple) or isinstance(item[1], list): item[1] = list(item[1]) for i, j in enumerate(item[1]): if isinstance(j, str): print('{0} is string {1}'.format(i, j)) item[1][i] = self.name_to_index(j) item = tuple(item) return self.tree.view()[item] @property def channels(self): return self.current_node.channels def __getattr__(self, name): if name in dir(self.current_node.view()): return self.current_node.view().__getattribute__(name) else: raise AttributeError("'{0}' has no attribue '{1}'".format(str(self.__class__), name)) def __getstate__(self): return self.__dict__ def __setstate__(self, dict): for i in dict.keys(): self.__dict__[i] = dict[i] def name_to_index(self, channels): """Return the channel indexes for the channels provided as arguments. """ if isinstance(channels, str): return self.channels.index(channels) idx = [] for i in channels: try: idx.append(self.channels.index(i)) except ValueError: try: for j in range(1, int(self.notes.text['par']) + 1): if i == self.notes.text['p%dn' % j]: idx.append(self.channels.index(self.notes.text['p%ds' % j])) except ValueError: raise ValueError('{0} is not in list'.format(i)) if idx: return idx else: raise ValueError('The field {0} was not found'.format(str(channels))) def get_channel_by_name(self, channels): """Return the data associated with specific channel names. """ return self.tree.view()[:, self.name_to_index(channels)] def get_markers(self): """Return the data associated with all the markers. """ return self.view()[:, self.markers] def view(self): """Return the current view of the data. """ return self.tree.view() def visit(self, name): """Switch the current view of the data. """ self.tree.visit(name) @property def current_node(self): """Return the current node. """ return self.tree.current def copy(self): """Return a copy of the Cyto_data object. """ tname = self.name tree_data_points = self.tree.root.data tnotes = self.notes.copy() tchannels = self.channels[:] tscchannels = self.scatters[:] tmp = Cyto_data(tname, tree_data_points, tchannels, tscchannels, tnotes) from copy import deepcopy tmp.tree = deepcopy(self.tree) return tmp def gate(self, g, chan=None): """Return a gated region of the cytometry data. """ return g.gate(self, chan) def subsample(self, s): """Return subsampled cytometry data. """ return s.subsample(self) def get_current_node(self): """Return the current node. """ return self.current_node def add_view(self, node): """Add a new node to the visualization tree. """ self.tree.add_child(node.name, node) return self def summary(self): """Provide a summary of current view. """ data_points = self.view() means = data_points.mean(0) stds = data_points.std(0) mins = data_points.min(0) maxs = data_points.max(0) medians = np.median(data_points, 0) dim = data_points.shape[1] summary = '' for i in range(dim): summary = summary + self.channels[i] + ":\n" summary = summary + " max: " + str(maxs[i]) + "\n" summary = summary + " mean: " + str(means[i]) + "\n" summary = summary + " median: " + str(medians[i]) + "\n" summary = summary + " min: " + str(mins[i]) + "\n" summary = summary + " std: " + str(stds[i]) + "\n" return summary def boundary_events(self): """Return a dictionary of the percentage of all events that are in the first and in the last channel for each channel. """ boundary_dict = {} for k, channel in enumerate(self.channels): col = self.view()[:, k] boundary_dict[channel] = \ sum((col == min(col)) | (col == max(col))) / len(col) return boundary_dict class NotSupportedFCSDataMode(Exception): """Exception raised for data modes in a *.fcs file that are not currently supported. Modified from a corresponding exception in the outdated 'fcm' Python package by Jacob Frelinger. """ def __init__(self, mode): self.mode = mode self.message = "Unfortunately, the FCS data stored as type {0} is not currently supported.".format(mode) self.args = (mode,) def integer_format(b): """Return the binary format of an integer. """ if b == 8: return 'B' elif b == 16: return 'H' elif b == 32: return 'I' else: print("Cannot handle integers of bit size {0}.".format(b)) return None def integer_bit_mask(b, ub): """Return the bit-mask of an integer and a bit-witdh. """ if b == 8: return (0xFF >> (b - ub)) elif b == 16: return (0xFFFF >> (b - ub)) elif b == 32: return (0xFFFFFFFF >> (b - ub)) else: print("Cannot handle integers of bit size {0}.".format(b)) return None def fluorescent_channel(name): """Check if a channel is a fluorescent channel. """ name = name.lower() if name.startswith('cs'): return False elif name.startswith('fs'): return False elif name.startswith('ss'): return False elif name.startswith('ae'): return False elif name.startswith('cv'): return False elif name.startswith('time'): return False else: return True class FCS_handler(object): """Hold object to read and parse *.fcs files. Modified from a corresponding class in the outdated 'fcm' Python package by Jacob Frelinger. """ def __init__(self, file_path): self.file_path = file_path self.current_offset = 0 def get_next_dataset(self, **kwargs): """Return the next cytometry dataset stored in a *.fcs file. """ with open(self.file_path, 'rb') as self._f: header = self.parse_header(self.current_offset) text = self.parse_text(self.current_offset, header['text_start'], header['text_stop']) try: analysis_beg = text['begin_analysis'] except KeyError: analysis_beg = header['analysis_start'] try: analysis_end = text['end_analysis'] except KeyError: analysis_end = header['analysis_end'] analysis = self.parse_analysis(self.current_offset, analysis_beg, analysis_end) try: data_beg = int(text['begin_data']) except KeyError: data_beg = header['data_start'] try: data_end = int(text['end_data']) except KeyError: data_end = header['data_end'] LMD = self.fix_LMD(self.current_offset, header['text_start'], header['text_stop']) data_end = data_end + LMD data = self.parse_data(self.current_offset, data_beg, data_end, text) channels = [] scchannels = [] scchannel_indexes = [] base_chan_name = [] for i in range(1, int(text['par']) + 1): base_chan_name.append(text['p%dn' % i]) try: if text['p%ds' % i] not in ['',' ']: name = text['p%ds' % i] else: name = text['p%dn' % i] except KeyError: name = text['p%dn' % i] channels.append(name) if not fluorescent_channel(name): scchannels.append(name) if name != 'Time': scchannel_indexes.append(i - 1) _, name = path.split(self.file_path) name, _ = path.splitext(name) cyto_object = Cyto_data(name, data, channels, scchannels, Annotation({'text': text, 'header': header, 'analysis': analysis,})) return cyto_object def read_bytes(self, offset, start, stop): """Read bytes from start to stop, included. """ self._f.seek(offset + start) return self._f.read(stop - start + 1) def parse_header(self, offset): """ Parse the cytometry data in a *.fcs file at the specified offset (accounting for the possibility of several data parts in the said file). """ header = {} header['version'] = float(self.read_bytes(offset, 3, 5)) header['text_start'] = int(self.read_bytes(offset, 10, 17)) header['text_stop'] = int(self.read_bytes(offset, 18, 25)) header['data_start'] = int(self.read_bytes(offset, 26, 33)) header['data_end'] = int(self.read_bytes(offset, 34, 41)) try: header['analysis_start'] = int(self.read_bytes(offset, 42, 49)) except ValueError: header['analysis_start'] = -1 try: header['analysis_end'] = int(self.read_bytes(offset, 50, 57)) except ValueError: header['analysis_end'] = -1 return header def parse_text(self, offset, start, stop): """Return the parsed text segment of a *.fcs file. """ text = self.read_bytes(offset, start, stop) return parse_pairs(text) def parse_analysis(self, offset, start, stop): """Return the parsed analysis part of the *.fcs file under consideration. """ if start == stop: return {} else: text = self.read_bytes(offset, start, stop) return parse_pairs(text) def fix_LMD(self, offset, start, stop): """Handle the LMD format (embedded FCS format) and the way it counts, which differs from other FCS formats. """ text = self.read_bytes(offset, start, stop) if text[0] == text[-1]: return 0 else: return -1 def parse_data(self, offset, start, stop, text): """Return an array holding the data part of *.fcs file at hand. """ dtype = text['datatype'] mode = text['mode'] tot = int(text['tot']) if mode == 'c' or mode == 'u': raise NotSupportedFCSDataMode(mode) if text['byteord'] == '1,2,3,4' or text['byteord'] == '1,2': order = '<' elif text['byteord'] == '4,3,2,1' or text['byteord'] == '2,1': order = '>' else: warn("WARNING: unsupported byte order {0}; using default @".format(text['byteord'])) order = '@' bit_width = [] data_range = [] for i in range(1, int(text['par']) + 1): bit_width.append(int(text['p%db' % i])) data_range.append(int(text['p%dr' % i])) if dtype.lower() == 'i': data = self.parse_int_data(offset, start, stop, bit_width, data_range, tot, order) elif dtype.lower() == 'f' or dtype.lower() == 'd': data = self.parse_float_data(offset, start, stop, dtype.lower(), tot, order) else: data = self.parse_ASCII_data(offset, start, stop, bit_width, dtype, tot, order) return data def parse_int_data(self, offset, start, stop, bit_width, data_range, tot, order): """Parse *.fcs file and return data as an integer list. """ if reduce(and_, [item in [8, 16, 32] for item in bit_width]): if len(set(bit_width)) == 1: num_items = (stop - start + 1) / calcsize(integer_format(bit_width[0])) tmp = unpack('%s%d%s' % (order, num_items, integer_format(bit_width[0])), self.read_bytes(offset, start, stop)) else: unused_bit_widths = map(int, map(np.log2, data_range)) tmp = [] current = start while current < stop: for i, current_width in enumerate(bit_width): bit_mask = integer_bit_mask(current_width, unused_bit_widths[i]) N_bytes = current_width / 8 bin_string = self.read_bytes(offset, current, current + N_bytes - 1) current += N_bytes val = bit_mask & unpack('%s%s' % (order, integer_format(current_width)), bin_string)[0] tmp.append(val) else: warn('WARNING: non-standard bit widths for the data part.') return None return np.array(tmp).reshape((tot, len(bit_width))) def parse_float_data(self, offset, start, stop, dtype, tot, order): """Parse a *.fcs file and return list of float data entries. """ N_items = (stop - start + 1) / calcsize(dtype) tmp = unpack('%s%d%s' % (order, N_items, dtype), self.read_bytes(offset, start, stop)) return np.array(tmp).reshape((tot, len(tmp) / tot)) def parse_ASCII_data(self, offset, start, stop, bit_width, dtype, tot, order): """Parse ASCII encoded data from a *.fcs file. """ N_items = (stop - start + 1) / calcsize(dtype) tmp = unpack('%s%d%s' % (order, N_items, dtype), self.read_bytes(offset, start, stop)) return np.array(tmp).reshape((tot, len(tmp) / tot)) def cytometry_preprocess(file_path, log_mode = False, pseudotime_mode = True, pcv_method = 'Rprincurve', anchor_gene = None, exclude_marker_names = None): data_tag, output_directory = create_output_directory(file_path) cyto_object = get_FCS_data(file_path) marker_idx = np.array(cyto_objects.markers, dtype = str) marker_names = np.array(cyto_objects.channels[marker_idx], dtype = str) data = cyto_object.data_points data = data[:, marker_idx] cell_IDs = np.array(['cell_{0}'.format(i) for i in xrange(1, data.shape[0] + 1)], dtype = str) if exclude_marker_names: indices = np.zeros(0, dtype = int) for name in exclude_marker_names: indices = np.append(indices, np.where(marker_names == name)[0]) data = np.delete(data, indices, axis = 1) marker_names = np.delete(marker_names, indices) cell_stages = infer_pseudotime(data, output_directory, data_tag, pcv_method, anchor_gene, marker_names) write_preprocessed_data(output_directory, cell_IDs, cell_stages, data, markers) return cell_IDs, data, marker_names, cell_stages.astype(float), data_tag, output_directory def PCR_preprocess(file_path, log_mode = False, pseudotime_mode = False, pcv_method = 'Rprincurve', anchor_gene = None, exclude_marker_names = None): low_gene_fraction_max = 0.8 data_tag, output_directory = create_output_directory(file_path) cell_IDs, cell_stages, data = get_PCR_or_RNASeq_data(file_path, pseudotime_mode) with open(file_path, 'r') as f: markers = np.loadtxt(f, dtype = str, delimiter = '\t', skiprows = 1 if pseudotime_mode else 2, usecols = [0]) markers.reshape(markers.size) if exclude_marker_names: indices = np.zeros(0, dtype = int) for name in exclude_marker_names: indices = np.append(indices, np.where(markers == name)[0]) data = np.delete(data, indices, axis = 1) markers = np.delete(markers, indices) if pseudotime_mode: cell_stages = infer_pseudotime(data, output_directory, data_tag, pcv_method, anchor_gene, markers) condition = np.mean(data == 0, axis = 0) < low_gene_fraction_max data = np.compress(condition, data, 1) markers = np.compress(condition, markers) write_preprocessed_data(output_directory, cell_IDs, cell_stages, data, markers) return cell_IDs, data, markers, cell_stages.astype(float), data_tag, output_directory def RNASeq_preprocess(file_path, log_mode = True, pseudotime_mode = False, pcv_method = 'Rprincurve', anchor_gene = None, exclude_marker_names = None): assert isinstance(log_mode, bool) assert isinstance(pseudotime_mode, bool) # Threshold value for genes of low expression levels low_gene_threshold = 1 # Maximum fraction of lowly-expressed cells allowed for each gene low_gene_fraction_max = 0.7 # Number of highly variable genes selected N_selected_genes = 1000 data_tag, output_directory = create_output_directory(file_path) cell_IDs, cell_stages, data = get_PCR_or_RNASeq_data(file_path, pseudotime_mode) with open(file_path, 'r') as f: markers = np.loadtxt(f, dtype = str, delimiter = '\t', skiprows = 1 if pseudotime_mode else 2, usecols = [0]) markers.reshape(markers.size) if exclude_marker_names: indices = np.zeros(0, dtype = int) for name in exclude_marker_names: indices = np.append(indices, np.where(markers == name)[0]) data = np.delete(data, indices, axis = 1) markers = np.delete(markers, indices) if pseudotime_mode: cell_stages = infer_pseudotime(data, output_directory, data_tag, pcv_method, anchor_gene, markers) condition = np.mean(data < low_gene_threshold, axis = 0) < low_gene_fraction_max data = np.compress(condition, data, 1) markers = np.compress(condition, markers) Fano_factors = np.var(data, axis = 0) / np.mean(data, axis = 0).astype(float) idx = np.argsort(Fano_factors)[::-1][:N_selected_genes] data = data[:, idx] markers = markers[idx] if log_mode: np.log2(data + 1, data) write_preprocessed_data(output_directory, cell_IDs, cell_stages, data, markers) return cell_IDs, data, markers, cell_stages.astype(float), data_tag, output_directory def create_output_directory(file_path): data_tag = path.basename(path.abspath(file_path)).split('.')[0] output_directory = path.join(getcwd(), 'SCUBA_analysis_of_{0}'.format(data_tag)) try: makedirs(output_directory) except OSError: if not path.isdir(output_directory): raise return data_tag, output_directory def get_FCS_data(file_path, **kwargs): """Return a data object from an *.fcs file""" cyto_object = FCS_handler(file_path) data = cyto_object.get_next_dataset(**kwargs) cyto_object._f.close() del cyto_object return data def get_PCR_or_RNASeq_data(file_path, pseudotime_mode = False): with open(file_path, 'r') as f: cell_IDs = f.readline().rstrip('\n').split('\t') cell_IDs = np.array(cell_IDs[1:], dtype = str) if pseudotime_mode: cell_stages = np.empty(0, dtype = float) else: cell_stages = f.readline().rstrip('\n').split('\t') cell_stages = np.array(cell_stages[1:], dtype = str) data = np.loadtxt(f, dtype = float, delimiter = '\t', usecols = xrange(1, len(cell_IDs) + 1)) data = data.T return cell_IDs, cell_stages, data def write_preprocessed_data(output_directory, cell_IDs, cell_stages, data, markers): processed_data_path = path.join(output_directory, 'processed_data.tsv') with open(processed_data_path, 'w') as f: f.write('\t'.join(cell_IDs)) f.write('\n') f.write('\t'.join(cell_stages)) f.write('\n') np.savetxt(f, data.T, fmt = '%.6f', delimiter = '\t') dataset = np.genfromtxt(processed_data_path, delimiter = '\t', dtype = str) dataset = np.insert(dataset, 0, np.append(['Cell ID', 'Stage'], markers), axis = 1) with open(processed_data_path, 'w') as f: np.savetxt(f, dataset, fmt = '%s', delimiter = '\t')
{ "content_hash": "1be74eebc6c169fb744043426a488128", "timestamp": "", "source": "github", "line_count": 882, "max_line_length": 112, "avg_line_length": 33.61904761904762, "alnum_prop": 0.527148253068933, "repo_name": "GGiecold/PySCUBA", "id": "e122b49d3b360526b0ee46029d3ca20fc676827c", "size": "29858", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/PySCUBA/Preprocessing.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "102304" } ], "symlink_target": "" }
var util = require('util') , bops = require('bops') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN function DeferredLevelDOWN (location) { AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares? this._db = undefined this._operations = [] } util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) // called by LevelUP when we have a real DB to take its place DeferredLevelDOWN.prototype.setDb = function (db) { this._db = db this._operations.forEach(function (op) { db[op.method].apply(db, op.args) }) } DeferredLevelDOWN.prototype._open = function (options, callback) { return process.nextTick(callback) } // queue a new deferred operation DeferredLevelDOWN.prototype._operation = function (method, args) { if (this._db) return this._db[method].apply(this._db, args) this._operations.push({ method: method, args: args }) } // deferrables 'put get del batch approximateSize'.split(' ').forEach(function (m) { DeferredLevelDOWN.prototype['_' + m] = function () { this._operation(m, arguments) } }) DeferredLevelDOWN.prototype._isBuffer = function (obj) { return bops.is(obj) } // don't need to implement this as LevelUP's ReadStream checks for 'ready' state DeferredLevelDOWN.prototype._iterator = function () { throw new TypeError('not implemented') } module.exports = DeferredLevelDOWN
{ "content_hash": "e39827f9d53061549dd3a3a5a6f511bb", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 108, "avg_line_length": 30, "alnum_prop": 0.7006944444444444, "repo_name": "fahadmajeedverto/grunt-s3-sync-windows-fix", "id": "3e854241ea67ded12532348d378fe924f144ff6c", "size": "1440", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/level/node_modules/level-packager/node_modules/levelup/node_modules/deferred-leveldown/deferred-leveldown.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5071" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_15) on Sat May 30 22:34:28 CEST 2015 --> <title>de.hdu.pvs.crashfinder.diagnosis</title> <meta name="date" content="2015-05-30"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="de.hdu.pvs.crashfinder.diagnosis"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../de/hdu/pvs/crashfinder/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../de/hdu/pvs/crashfinder/experiments/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?de/hdu/pvs/crashfinder/diagnosis/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;de.hdu.pvs.crashfinder.diagnosis</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../de/hdu/pvs/crashfinder/diagnosis/OutputMain.html" title="class in de.hdu.pvs.crashfinder.diagnosis">OutputMain</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../de/hdu/pvs/crashfinder/diagnosis/Ranker.html" title="class in de.hdu.pvs.crashfinder.diagnosis">Ranker</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../de/hdu/pvs/crashfinder/analysis/package-summary.html">Prev Package</a></li> <li><a href="../../../../../de/hdu/pvs/crashfinder/experiments/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?de/hdu/pvs/crashfinder/diagnosis/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "b476ee0ed7ee50c2a1d7bb4cc2cb230d", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 164, "avg_line_length": 36.42335766423358, "alnum_prop": 0.6196392785571142, "repo_name": "heiqs/crashfinder", "id": "108da8cf3a4685e66cd2e381320af2c71bbbae52", "size": "4990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/de/hdu/pvs/crashfinder/diagnosis/package-summary.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "137787" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Telerik.JustMock.AutoMock.Ninject.Components; #endregion namespace Telerik.JustMock.AutoMock.Ninject.Modules { /// <summary> /// Finds modules defined in external files. /// </summary> public interface IModuleLoader : INinjectComponent { /// <summary> /// Loads any modules found in the files that match the specified patterns. /// </summary> /// <param name="patterns">The patterns to search.</param> void LoadModules(IEnumerable<string> patterns); } } #endif
{ "content_hash": "70bc52423da21b735152e0c03c1a8c1d", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 83, "avg_line_length": 28.95, "alnum_prop": 0.6770293609671848, "repo_name": "telerik/JustMockLite", "id": "ed7131a758440d580147b805b854915447d9ec47", "size": "881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoader.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "3250617" } ], "symlink_target": "" }
set(FIPS_PLATFORM WASISDK) set(FIPS_PLATFORM_NAME "wasisdk") set(FIPS_WASISDK 1) set(FIPS_POSIX 1) set(WASISDK_SYSROOT "${WASISDK_ROOT}/share/wasi-sysroot") set(FIPS_WASISDK_POSTFIX ".wasm" CACHE STRING "wasisdk output postfix") set(WASISDK_COMMON_FLAGS) set(WASISDK_COMMON_FLAGS_RELEASE) set(WASISDK_CXX_FLAGS) set(WASISDK_LINKER_FLAGS) set(WASISDK_LINKER_FLAGS_RELEASE) set(WASISDK_EXE_LINKER_FLAGS) if (NOT FIPS_EXCEPTIONS) set(WASISDK_CXX_FLAGS "${WASISDK_CXX_FLAGS} -fno-exceptions") endif() if (NOT FIPS_RTTI) set(WASISDK_CXX_FLAGS "${WASISDK_CXX_FLAGS} -fno-rtti") endif() set(WASISDK_OPT "-O3") set(CMAKE_SYSTEM_NAME Generic) set(CMAKE_SYSTEM_VERSION 1) set(CMAKE_SYSTEM_PROCESSOR wasm32) set(CMAKE_CONFIGURATION_TYPES Debug Release Profiling) set(CMAKE_C_COMPILER_TARGET "wasm32-wasi") set(CMAKE_CXX_COMPILER_TARGET "wasm32-wasi") set(CMAKE_SYSROOT "${WASISDK_SYSROOT}") set(CMAKE_C_COMPILER_WORKS TRUE) set(CMAKE_CXX_COMPILER_WORKS TRUE) if(WIN32) set(WASI_HOST_EXE_SUFFIX ".exe") else() set(WASI_HOST_EXE_SUFFIX "") endif() # specify cross-compilers set(CMAKE_C_COMPILER "${WASISDK_ROOT}/bin/clang${WASI_HOST_EXE_SUFFIX}" CACHE PATH "gcc" FORCE) set(CMAKE_CXX_COMPILER "${WASISDK_ROOT}/bin/clang++${WASI_HOST_EXE_SUFFIX}" CACHE PATH "g++" FORCE) set(CMAKE_AR "${WASISDK_ROOT}/bin/ar${WASI_HOST_EXE_SUFFIX}" CACHE PATH "archive" FORCE) set(CMAKE_LINKER "${WASISDK_ROOT}/bin/clang${WASI_HOST_EXE_SUFFIX}" CACHE PATH "linker" FORCE) set(CMAKE_RANLIB "${WASISDK_ROOT}/bin/ranlib${WASI_HOST_EXE_SUFFIX}" CACHE PATH "ranlib" FORCE) # only search for libraries and includes in the toolchain #set(CMAKE_FIND_ROOT_PATH ${WASISDK_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_C_USE_RESPONSE_FILE_FOR_LIBRARIES 1) set(CMAKE_CXX_USE_RESPONSE_FILE_FOR_LIBRARIES 1) set(CMAKE_C_USE_RESPONSE_FILE_FOR_OBJECTS 1) set(CMAKE_CXX_USE_RESPONSE_FILE_FOR_OBJECTS 1) set(CMAKE_C_USE_RESPONSE_FILE_FOR_INCLUDES 1) set(CMAKE_CXX_USE_RESPONSE_FILE_FOR_INCLUDES 1) set(CMAKE_C_RESPONSE_FILE_LINK_FLAG "@") set(CMAKE_CXX_RESPONSE_FILE_LINK_FLAG "@") set(CMAKE_C_CREATE_STATIC_LIBRARY "<CMAKE_AR> rc <TARGET> <LINK_FLAGS> <OBJECTS>") set(CMAKE_CXX_CREATE_STATIC_LIBRARY "<CMAKE_AR> rc <TARGET> <LINK_FLAGS> <OBJECTS>") # c++ compiler flags set(CMAKE_CXX_FLAGS "${WASISDK_COMMON_FLAGS} ${WASISDK_CXX_FLAGS} -fstrict-aliasing -Wall -Wno-multichar -Wextra -Wno-unknown-pragmas -Wno-ignored-qualifiers -Wno-long-long -Wno-overloaded-virtual -Wno-deprecated-writable-strings -Wno-unused-volatile-lvalue -Wno-inconsistent-missing-override -Wno-expansion-to-defined") set(CMAKE_CXX_FLAGS_RELEASE "${WASISDK_COMMON_FLAGS_RELEASE} ${WASISDK_OPT} -DNDEBUG") set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -D_DEBUG_ -D_DEBUG -DFIPS_DEBUG=1") set(CMAKE_CXX_FLAGS_PROFILING "${WASISDK_OPT} -DNDEBUG --profiling") # c compiler flags set(CMAKE_C_FLAGS "${WASISDK_COMMON_FLAGS} -fstrict-aliasing -Wall -Wextra -Wno-multichar -Wno-unknown-pragmas -Wno-ignored-qualifiers -Wno-long-long -Wno-overloaded-virtual -Wno-deprecated-writable-strings -Wno-unused-volatile-lvalue -Wno-expansion-to-defined") set(CMAKE_C_FLAGS_RELEASE "${WASISDK_OPT} ${WASISDK_COMMON_FLAGS_RELEASE} -DNDEBUG") set(CMAKE_C_FLAGS_DEBUG "-O0 -g -D_DEBUG_ -D_DEBUG -DFIPS_DEBUG=1") set(CMAKE_C_FLAGS_PROFILING "${WASISDK_OPT} -DNDEBUG --profiling") # linker flags set(CMAKE_EXE_LINKER_FLAGS "${WASISDK_COMMON_FLAGS} ${WASISDK_LINKER_FLAGS} ${WASISDK_EXE_LINKER_FLAGS}") set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${WASISDK_OPT} ${WASISDK_COMMON_FLAGS_RELEASE} ${WASISDK_LINKER_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS_DEBUG "-O0 -g") set(CMAKE_EXE_LINKER_FLAGS_PROFILING "--profiling ${WASISDK_OPT} ${WASISDK_LINKER_FLAGS_RELEASE}") # dynamic lib linker flags set(CMAKE_SHARED_LINKER_FLAGS "-shared ${WASISDK_COMMON_FLAGS} ${WASISDK_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${WASISDK_OPT} ${WASISDK_COMMON_FLAGS_RELEASE} ${WASISDK_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${WASISDK_OPT} -g") set(CMAKE_SHARED_LINKER_FLAGS_PROFILING "--profiling ${WASISDK_OPT} ${WASISDK_LINKER_FLAGS_RELEASE}") # update cache variables for cmake gui set(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING "Config Type" FORCE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" CACHE STRING "Generic C++ Compiler Flags" FORCE) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING "C++ Debug Compiler Flags" FORCE) set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}" CACHE STRING "C++ Release Compiler Flags" FORCE) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}" CACHE STRING "Generic C Compiler Flags" FORCE) set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}" CACHE STRING "C Debug Compiler Flags" FORCE) set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}" CACHE STRING "C Release Compiler Flags" FORCE) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}" CACHE STRING "Generic Linker Flags" FORCE) set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" CACHE STRING "Debug Linker Flags" FORCE) set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}" CACHE STRING "Release Linker Flags" FORCE) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" CACHE STRING "Generic Shared Linker Flags" FORCE) set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" CACHE STRING "Debug Shared Linker Flags" FORCE) set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}" CACHE STRING "Release Shared Linker Flags" FORCE) set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS}" CACHE STRING "Static Lib Flags" FORCE) # set the build type to use if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Compile Type" FORCE) endif() set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS Debug Release Profiling)
{ "content_hash": "877a928d4aa44a25480ff94ad5e978fb", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 320, "avg_line_length": 52.442477876106196, "alnum_prop": 0.7556530543368208, "repo_name": "floooh/fips", "id": "a3e025d6428726b9fdb36a55a348b8f8ce5a5169", "size": "6318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmake-toolchains/wasisdk.toolchain.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "34" }, { "name": "CMake", "bytes": "126512" }, { "name": "Java", "bytes": "162" }, { "name": "Python", "bytes": "648132" }, { "name": "Shell", "bytes": "2581" }, { "name": "Vim Script", "bytes": "211" } ], "symlink_target": "" }
from __future__ import print_function # Authors: Christoph Dinh <chdinh@nmr.mgh.harvard.edu> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import socket import time import struct from ..externals.six.moves import StringIO import threading import numpy as np from ..utils import logger, verbose from ..io.constants import FIFF from ..io.meas_info import read_meas_info from ..io.tag import Tag, read_tag from ..io.tree import make_dir_tree # Constants for fiff realtime fiff messages MNE_RT_GET_CLIENT_ID = 1 MNE_RT_SET_CLIENT_ALIAS = 2 def _recv_tag_raw(sock): """Read a tag and the associated data from a socket Parameters ---------- sock : socket.socket The socket from which to read the tag. Returns ------- tag : instance of Tag The tag. buff : str The raw data of the tag (including header). """ s = sock.recv(4 * 4) if len(s) != 16: raise RuntimeError('Not enough bytes received, something is wrong. ' 'Make sure the mne_rt_server is running.') tag = Tag(*struct.unpack(">iiii", s)) n_received = 0 rec_buff = [s] while n_received < tag.size: n_buffer = min(4096, tag.size - n_received) this_buffer = sock.recv(n_buffer) rec_buff.append(this_buffer) n_received += len(this_buffer) if n_received != tag.size: raise RuntimeError('Not enough bytes received, something is wrong. ' 'Make sure the mne_rt_server is running.') buff = ''.join(rec_buff) return tag, buff def _buffer_recv_worker(rt_client, nchan): """Worker thread that constantly receives buffers""" try: for raw_buffer in rt_client.raw_buffers(nchan): rt_client._push_raw_buffer(raw_buffer) except RuntimeError as err: # something is wrong, the server stopped (or something) rt_client._recv_thread = None print('Buffer receive thread stopped: %s' % err) class RtClient(object): """Realtime Client Client to communicate with mne_rt_server Parameters ---------- host : str Hostname (or IP address) of the host where mne_rt_server is running. cmd_port : int Port to use for the command connection. data_port : int Port to use for the data connection. timeout : float Communication timeout in seconds. verbose : bool, str, int, or None Log verbosity see mne.verbose. """ @verbose def __init__(self, host, cmd_port=4217, data_port=4218, timeout=1.0, verbose=None): self._host = host self._data_port = data_port self._cmd_port = cmd_port self._timeout = timeout try: self._cmd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._cmd_sock.settimeout(timeout) self._cmd_sock.connect((host, cmd_port)) self._cmd_sock.setblocking(0) except Exception: raise RuntimeError('Setting up command connection (host: %s ' 'port: %d) failed. Make sure mne_rt_server ' 'is running. ' % (host, cmd_port)) try: self._data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._data_sock.settimeout(timeout) self._data_sock.connect((host, data_port)) self._data_sock.setblocking(1) except Exception: raise RuntimeError('Setting up data connection (host: %s ' 'port: %d) failed. Make sure mne_rt_server ' 'is running.' % (host, data_port)) self.verbose = verbose # get my client ID self._client_id = self.get_client_id() self._recv_thread = None self._recv_callbacks = list() def _send_command(self, command): """Send a command to the server Parameters ---------- command : str The command to send. Returns ------- resp : str The response from the server. """ logger.debug('Sending command: %s' % command) command += '\n' self._cmd_sock.sendall(command.encode('utf-8')) buf, chunk, begin = [], '', time.time() while True: #if we got some data, then break after wait sec if buf and time.time() - begin > self._timeout: break #if we got no data at all, wait a little longer elif time.time() - begin > self._timeout * 2: break try: chunk = self._cmd_sock.recv(8192) if chunk: buf.append(chunk) begin = time.time() else: time.sleep(0.1) except: pass return ''.join(buf) def _send_fiff_command(self, command, data=None): """Send a command through the data connection as a fiff tag Parameters ---------- command : int The command code. data : str Additional data to send. """ kind = FIFF.FIFF_MNE_RT_COMMAND type = FIFF.FIFFT_VOID size = 4 if data is not None: size += len(data) # first 4 bytes are the command code next = 0 msg = np.array(kind, dtype='>i4').tostring() msg += np.array(type, dtype='>i4').tostring() msg += np.array(size, dtype='>i4').tostring() msg += np.array(next, dtype='>i4').tostring() msg += np.array(command, dtype='>i4').tostring() if data is not None: msg += np.array(data, dtype='>c').tostring() self._data_sock.sendall(msg) def get_measurement_info(self): """Get the measurement information Returns ------- info : dict The measurement information. """ cmd = 'measinfo %d' % self._client_id self._send_command(cmd) buff = [] directory = [] pos = 0 while True: tag, this_buff = _recv_tag_raw(self._data_sock) tag.pos = pos pos += 16 + tag.size directory.append(tag) buff.append(this_buff) if tag.kind == FIFF.FIFF_BLOCK_END and tag.type == FIFF.FIFFT_INT: val = np.fromstring(this_buff[-4:], dtype=">i4") if val == FIFF.FIFFB_MEAS_INFO: break buff = ''.join(buff) fid = StringIO(buff) tree, _ = make_dir_tree(fid, directory) info, meas = read_meas_info(fid, tree) return info def set_client_alias(self, alias): """Set client alias Parameters ---------- alias : str The client alias. """ self._send_fiff_command(MNE_RT_SET_CLIENT_ALIAS, alias) def get_client_id(self): """Get the client ID Returns ------- id : int The client ID. """ self._send_fiff_command(MNE_RT_GET_CLIENT_ID) # ID is send as answer tag, buff = _recv_tag_raw(self._data_sock) if (tag.kind == FIFF.FIFF_MNE_RT_CLIENT_ID and tag.type == FIFF.FIFFT_INT): client_id = int(np.fromstring(buff[-4:], dtype=">i4")) else: raise RuntimeError('wrong tag received') return client_id def start_measurement(self): """Start the measurement""" cmd = 'start %d' % self._client_id self._send_command(cmd) def stop_measurement(self): """Stop the measurement""" self._send_command('stop-all') def start_receive_thread(self, nchan): """Start the receive thread If the measurement has not been started, it will also be started. Parameters ---------- nchan : int The number of channels in the data. """ if self._recv_thread is None: self.start_measurement() self._recv_thread = threading.Thread(target=_buffer_recv_worker, args=(self, nchan)) self._recv_thread.start() def stop_receive_thread(self, nchan, stop_measurement=False): """Stop the receive thread Parameters ---------- stop_measurement : bool Also stop the measurement. """ if self._recv_thread is not None: self._recv_thread.stop() self._recv_thread = None if stop_measurement: self.stop_measurement() def register_receive_callback(self, callback): """Register a raw buffer receive callback Parameters ---------- callback : callable The callback. The raw buffer is passed as the first parameter to callback. """ if callback not in self._recv_callbacks: self._recv_callbacks.append(callback) def unregister_receive_callback(self, callback): """Unregister a raw buffer receive callback """ if callback in self._recv_callbacks: self._recv_callbacks.remove(callback) def _push_raw_buffer(self, raw_buffer): """Push raw buffer to clients using callbacks""" for callback in self._recv_callbacks: callback(raw_buffer) def read_raw_buffer(self, nchan): """Read a single buffer with raw data Parameters ---------- nchan : int The number of channels (info['nchan']). Returns ------- raw_buffer : float array, shape=(nchan, n_times) The raw data. """ tag, this_buff = _recv_tag_raw(self._data_sock) # skip tags until we get a data buffer while tag.kind != FIFF.FIFF_DATA_BUFFER: tag, this_buff = _recv_tag_raw(self._data_sock) buff = StringIO(this_buff) tag = read_tag(buff) raw_buffer = tag.data.reshape(-1, nchan).T return raw_buffer def raw_buffers(self, nchan): """Return an iterator over raw buffers Parameters ---------- nchan : int The number of channels (info['nchan']). Returns ------- raw_buffer : generator Generator for iteration over raw buffers. """ while True: raw_buffer = self.read_raw_buffer(nchan) if raw_buffer is not None: yield raw_buffer else: break
{ "content_hash": "4bf0097b270408ae423ba6e92adc6a92", "timestamp": "", "source": "github", "line_count": 371, "max_line_length": 79, "avg_line_length": 29.00808625336927, "alnum_prop": 0.5398624790931054, "repo_name": "jaeilepp/eggie", "id": "d82e414c297bac4fbab7469321cd7a99fdc84b05", "size": "10762", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mne/realtime/client.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "3357472" } ], "symlink_target": "" }
package pacman.entries.pacman.evaluators; import java.util.Collection; import pacman.entries.pacman.GameNode; import pacman.entries.pacman.MonteCarloPacManSimulator; import pacman.game.Constants.GHOST; import pacman.game.Game; /** * Adds a penalty to a move which eats a power pill if there is still a power pill active. */ public class PowerPillActiveEvaluator implements ITreeEvaluator { private static final int DEFAULT_PENALTY = 300; private int penalty; public PowerPillActiveEvaluator(int penalty) { this.penalty = penalty; } public PowerPillActiveEvaluator() { this(DEFAULT_PENALTY); } @Override public void evaluateTree(MonteCarloPacManSimulator simulator) { //get the children of the root node, if there aren't any we can't make any decisions Collection<GameNode> children = simulator.getPacManChildren(); if (children == null) return; Game game = simulator.getGameState(); if (isPowerPillActive(game)) { //no ghosts nearby, penalise nodes which eat power pills for (GameNode child: children) { if (child.getMoveEatsPowerPill()) { child.addScoreBonus(-penalty); } } } } /** * Returns true if any ghosts are edible; otherwise, returns false. * @param game * @return */ private boolean isPowerPillActive(Game game) { int edibleTime = game.getGhostEdibleTime(GHOST.BLINKY) + game.getGhostEdibleTime(GHOST.INKY) + game.getGhostEdibleTime(GHOST.PINKY) + game.getGhostEdibleTime(GHOST.SUE); return edibleTime > 0; } }
{ "content_hash": "52ebcc356d607737de32ec82184b25f3", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 90, "avg_line_length": 22.718309859154928, "alnum_prop": 0.6918784872907625, "repo_name": "stewartml/4thYearProject", "id": "2c2b395cbc5e72a75a31989d00bc4dd810aad531", "size": "1613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "agent/src/pacman/entries/pacman/evaluators/PowerPillActiveEvaluator.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "152743" }, { "name": "JavaScript", "bytes": "43601" }, { "name": "Matlab", "bytes": "105209" }, { "name": "PHP", "bytes": "164919" }, { "name": "Shell", "bytes": "1111" } ], "symlink_target": "" }
layout: default title: Your New Jekyll Site --- <div id="home"> <h1>Blog Posts</h1> <ul class="posts"> {% for post in paginator.posts %} <li><span>{{ post.date | date_to_string }}</span> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> <a href="{{ paginator.previous_page_path }}">Previous Page</a> <a href="{{ paginator.next_page_path }}">Next Page</a> </div>
{ "content_hash": "fe50f1cf903cbfeb660909d6968eeba2", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 114, "avg_line_length": 29.642857142857142, "alnum_prop": 0.5783132530120482, "repo_name": "jthiller/jthiller.github.io", "id": "f85b25f9798ed84a62aa47b1009fe6e15ce0b5eb", "size": "419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Calandrinia calyptrata var. pumila Benth. ### Remarks null
{ "content_hash": "87f59273865f0fd6a91b22d2d44cdb59", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 12.538461538461538, "alnum_prop": 0.7361963190184049, "repo_name": "mdoering/backbone", "id": "bdc5b37cfaad69b789e347aae870222d62b98351", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Montiaceae/Claytonia/Claytonia pumila/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
.class Lcom/android/internal/policy/impl/sec/TickerWidget$2$5; .super Ljava/lang/Object; .source "TickerWidget.java" # interfaces .implements Ljava/lang/Runnable; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/android/internal/policy/impl/sec/TickerWidget$2;->onReceive(Landroid/content/Context;Landroid/content/Intent;)V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; # direct methods .method constructor <init>(Lcom/android/internal/policy/impl/sec/TickerWidget$2;)V .locals 0 .parameter .prologue .line 210 iput-object p1, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public run()V .locals 3 .prologue const/16 v1, 0x12c4 const/4 v2, 0x0 .line 212 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #calls: Lcom/android/internal/policy/impl/sec/TickerWidget;->updateTickerData()V invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$700(Lcom/android/internal/policy/impl/sec/TickerWidget;)V .line 213 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #getter for: Lcom/android/internal/policy/impl/sec/TickerWidget;->mHandler:Landroid/os/Handler; invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$800(Lcom/android/internal/policy/impl/sec/TickerWidget;)Landroid/os/Handler; move-result-object v0 invoke-virtual {v0, v1}, Landroid/os/Handler;->hasMessages(I)Z move-result v0 if-eqz v0, :cond_0 .line 214 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #getter for: Lcom/android/internal/policy/impl/sec/TickerWidget;->mHandler:Landroid/os/Handler; invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$800(Lcom/android/internal/policy/impl/sec/TickerWidget;)Landroid/os/Handler; move-result-object v0 invoke-virtual {v0, v1}, Landroid/os/Handler;->removeMessages(I)V .line 215 :cond_0 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #getter for: Lcom/android/internal/policy/impl/sec/TickerWidget;->mTickerSlidingDrawer:Lcom/android/internal/policy/impl/sec/TickerSlidingDrawer; invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$900(Lcom/android/internal/policy/impl/sec/TickerWidget;)Lcom/android/internal/policy/impl/sec/TickerSlidingDrawer; move-result-object v0 invoke-virtual {v0}, Lcom/android/internal/policy/impl/sec/TickerSlidingDrawer;->isOpened()Z move-result v0 if-eqz v0, :cond_1 .line 216 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #getter for: Lcom/android/internal/policy/impl/sec/TickerWidget;->mHandleRefreshImage:Landroid/widget/ImageView; invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$1000(Lcom/android/internal/policy/impl/sec/TickerWidget;)Landroid/widget/ImageView; move-result-object v0 invoke-virtual {v0, v2}, Landroid/widget/ImageView;->setVisibility(I)V .line 217 :cond_1 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; #getter for: Lcom/android/internal/policy/impl/sec/TickerWidget;->mHandleProgressBar:Landroid/widget/ProgressBar; invoke-static {v0}, Lcom/android/internal/policy/impl/sec/TickerWidget;->access$1100(Lcom/android/internal/policy/impl/sec/TickerWidget;)Landroid/widget/ProgressBar; move-result-object v0 const/16 v1, 0x8 invoke-virtual {v0, v1}, Landroid/widget/ProgressBar;->setVisibility(I)V .line 219 iget-object v0, p0, Lcom/android/internal/policy/impl/sec/TickerWidget$2$5;->this$1:Lcom/android/internal/policy/impl/sec/TickerWidget$2; iget-object v0, v0, Lcom/android/internal/policy/impl/sec/TickerWidget$2;->this$0:Lcom/android/internal/policy/impl/sec/TickerWidget; iput-boolean v2, v0, Lcom/android/internal/policy/impl/sec/TickerWidget;->mFacebookRefreshing:Z .line 220 return-void .end method
{ "content_hash": "5186460becafb9319391a3cfa1aa7a86", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 198, "avg_line_length": 41.284671532846716, "alnum_prop": 0.7568953323903819, "repo_name": "baidurom/devices-n7108", "id": "c0d0a03a6515463aed9defca0d646ab7cd1d37fb", "size": "5656", "binary": false, "copies": "2", "ref": "refs/heads/coron-4.1", "path": "android.policy.jar.out/smali/com/android/internal/policy/impl/sec/TickerWidget$2$5.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12697" }, { "name": "Shell", "bytes": "1974" } ], "symlink_target": "" }
<?php require_once(__CA_MODELS_DIR__."/ca_objects.php"); require_once(__CA_MODELS_DIR__."/ca_sets.php"); require_once(__CA_APP_DIR__.'/helpers/accessHelpers.php'); $t_object = new ca_objects(); $t_featured_obj = new ca_sets(); # --- load the featured items set - set name assigned in app.conf $t_featured_obj->load(array('set_code' => 'featured_object')); # --- Enforce access control on set if((sizeof($va_access_values) == 0) || (sizeof($va_access_values) && in_array($t_featured_obj->get("access"), $va_access_values))){ $vn_featured_set_id = $t_featured_obj->get("set_id"); $va_featured_ids = array_keys(is_array($va_tmp = $t_featured_obj->getItemRowIDs(array('checkAccess' => $va_access_values, 'limit' => 1))) ? $va_tmp : array()); // These are the object ids in the set } if(is_array($va_featured_ids) && (sizeof($va_featured_ids) > 0)){ $t_object = new ca_objects($va_featured_ids[0]); $va_rep = $t_object->getPrimaryRepresentation(array('widepreview'), null, array('return_with_access' => $va_access_values)); $feat_obj_content_id = $va_featured_ids[0]; $feat_obj_content_widepreview = $va_rep["tags"]["widepreview"]; $vs_featured_content_label = $t_object->getLabelForDisplay(); } # --- Recently Added # --- get the 12 most recently added objects to display $va_recently_added_items = $t_object->getRecentlyAddedItems(12, array('checkAccess' => $va_access_values, 'hasRepresentations' => 1)); $va_labels = $t_object->getPreferredDisplayLabelsForIDs(array_keys($va_recently_added_items)); $va_media = $t_object->getPrimaryMediaForIDs(array_keys($va_recently_added_items), array('small', 'thumbnail', 'preview', 'widepreview'), array("checkAccess" => $va_access_values)); foreach($va_recently_added_items as $vn_object_id => $va_object_info){ $va_object_info['title'] = $va_labels[$vn_object_id]; $va_object_info['media'] = $va_media[$vn_object_id]; $va_recently_added_objects[$vn_object_id] = $va_object_info; } #$this->view->setVar('recently_added_objects', $va_recently_added_objects); if(is_array($va_recently_added_objects) && (sizeof($va_recently_added_objects) > 0)){ $va_object_info = array_shift($va_recently_added_objects); $recently_added_id = $va_object_info['object_id']; $recently_added_widepreview = $va_media[$va_object_info['object_id']]["tags"]["widepreview"]; } ?> <div id="splashBrowsePanel" class="browseSelectPanel" style="z-index:1000;"> <a href="#" onclick="caUIBrowsePanel.hideBrowsePanel()" class="browseSelectPanelButton"></a> <div id="splashBrowsePanelContent"> </div> </div> <script type="text/javascript"> var caUIBrowsePanel = caUI.initBrowsePanel({ facetUrl: '<?php print caNavUrl($this->request, '', 'Browse', 'getFacet'); ?>'}); </script><pre> <?php $t_featured = new ca_objects($this->getVar("featured_content_id")); $t_info = $t_featured->getPrimaryRepresentation(array('mediumlarge'), null, array('return_with_access' => $va_access_values)); $vn_image_height = $t_info['info']['mediumlarge']['HEIGHT']; $vn_padding_top_bottom = (450 - $vn_image_height)/2; ?></pre> <div id="hpFeatured"> <table cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><div> <img src='<?php print $this->request->getThemeUrlPath() ?>/graphics/ladyliberty.png' border='0'> <?php # print caNavLink($this->request, $this->getVar("featured_content_mediumlarge"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("featured_content_id"))); ?> </div></td></tr></table> <div id="featuredLabel"> <?php # print $this->getVar("featured_content_label"); ?> </div><!-- end featuredLabel --> <div id="hpText"> <?php print $this->render('Splash/splash_intro_text_html.php'); ?> </div> </div><!-- end hpfeatured --> <div id="hpBrowse"> <div class="quickBrowseTitle"><b><?php print _t("Quickly browse by"); ?>:</b></div> <div class="quickBrowseLinks" style="margin-top:10px;"> <?php $va_facets = $this->getVar('available_facets'); foreach($va_facets as $vs_facet_name => $va_facet_info) { ?> <a href="#" style="white-space:nowrap;" onclick='caUIBrowsePanel.showBrowsePanel("<?php print $vs_facet_name; ?>")'><?php print ucwords($va_facet_info['label_plural']); ?></a> <?php } ?> </div> <div class="hpRss"><?php print caNavLink($this->request, '<img src="'.$this->request->getThemeUrlPath(true).'/graphics/feed.gif" border="0" title="'._t('Get alerted to newly added items by RSS').'" width="14" height="14"/> '._t('Get alerted to newly added items by RSS'), 'caption', '', 'Feed', 'recentlyAdded'); ?></div> </div><!-- end hpBrowse--> <div id="quickLinkItems"> <div class="quickLinkItem" > <div class="title"><?php print _t("Recently Added"); ?></div> <?php print caNavLink($this->request, $recently_added_widepreview, '', 'Detail', 'Object', 'Show', array('object_id' => $recently_added_id)); ?> </div> <div class="quickLinkItem"> <div class="title"><?php print _t("Most Viewed"); ?></div> <?php print caNavLink($this->request, $this->getVar("most_viewed_widepreview"), '', 'Detail', 'Object', 'Show', array('object_id' => $this->getVar("most_viewed_id"))); ?> </div> <div class="quickLinkItem" style="margin-right:0px;"> <div class="title"><?php print _t("Featured Object"); ?></div> <?php print caNavLink($this->request, $feat_obj_content_widepreview, '', 'Detail', 'Object', 'Show', array('object_id' => $feat_obj_content_id)); ?> </div> </div><!-- end quickLinkItems -->
{ "content_hash": "49d2ca1e98c8eea7318df641ef7428d5", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 325, "avg_line_length": 52.16822429906542, "alnum_prop": 0.6451092798280186, "repo_name": "PreserveLafayette/PreserveLafayette", "id": "f870ef7bcf5a2efee5f4fa7fe233f109a8eb5656", "size": "5582", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "themes/ns11mm/views/Splash/splash_html.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "28850" } ], "symlink_target": "" }
<html> <body jwcid="$content$"> <span jwcid="border@Border"> <form jwcid="@Form" listener="ognl:listeners.addBookmark" delegate="ognl:beans.delegate"> <span key="category" class="label">Category:</span> <select jwcid="category@PropertySelection" value="ognl:category" model="ognl:categoryModel"/><br/> <span jwcid="@FieldLabel" class="label" field="ognl:components.title">Title:</span> <input type="text" jwcid="title"/><br/> <span jwcid="@FieldLabel" class="label" field="ognl:components.url">URL:</span> <input type="text" jwcid="url"/><br/> <span key="description" class="label">Description:</span> <textarea rows="10" jwcid="description@TextArea" value="ognl:bookmark.description"></textarea><br/> <p><input type="submit" value="Add" jwcid="@Submit"/></p> </form> <p/> <a href="#" jwcid="@PageLink" page="AddCategory"><span key="addCategory">Add Category</span></a> </span> </body> </html>
{ "content_hash": "e3d35b3b443b9e10103a378e18547dae", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 107, "avg_line_length": 39.69230769230769, "alnum_prop": 0.6124031007751938, "repo_name": "nirvdrum/bookmarker", "id": "d6e28017082a33ab7488c22fa84d32fe0cc1b07f", "size": "1032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "context/WEB-INF/pages/AddBookmark.html", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" /> /// <reference path="../model/event.js" /> (function () { var initAppBarGlobalCommands = function () { var eventsButton = document.getElementById("navigate-onClick-to-events"); eventsButton.addEventListener("click", function () { WinJS.Navigation.navigate("/js/view/events/events.html"); }); } var initAppBarrEventsCommands = function () { var eventsButton = document.getElementById("call-form-for-event"); eventsButton.addEventListener("click", function () { var eventCreationFormHolder = document.getElementById("event-form-creation-form").winControl; eventCreationFormHolder.show(eventCreationFormHolder, "right", "center"); }); } var initNewEventCreateBtn = function () { var createEventBtn = document.getElementById("create-event-btn"); createEventBtn.addEventListener("click", function () { var eventDTO = Models.Event.eventDTO; var title = document.getElementById("new-event-title").value; var description = document.getElementById("new-event-description").innerHTML; eventDTO.title = title; eventDTO.description = description; var localFolder = Windows.Storage.ApplicationData.current.localFolder; localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists).then(function (file) { var content = JSON.stringify(eventDTO); Windows.Storage.FileIO.readTextAsync(file).then(function (oldContent) { oldContent = oldContent.replace("[", ""); oldContent = oldContent.replace("]", ""); content = content + ',' + oldContent; Windows.Storage.FileIO.writeTextAsync(file, "[" + content + "]"); }); }); }); } var readEventsFromLocalFolder = function () { var localFolder = Windows.Storage.ApplicationData.current.localFolder; return localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists); } WinJS.Namespace.define("Commands", { initAppBarCommands: initAppBarGlobalCommands, initAppBarrEventsCommands: initAppBarrEventsCommands, initNewEventCreateBtn: initNewEventCreateBtn, readEventsFromLocalFolder: readEventsFromLocalFolder, }); })();
{ "content_hash": "59d0cd47bf71e5f728da37b390b40b0a", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 126, "avg_line_length": 45.410714285714285, "alnum_prop": 0.6315375540699961, "repo_name": "vaster/RestReminder", "id": "7f9cc8c88b08b02f0314a18b67b025ff6f5b51c9", "size": "2545", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RestReminderApp/RestReminderApp/js/commands/command.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1674" }, { "name": "JavaScript", "bytes": "20903" } ], "symlink_target": "" }
layout: default title: API Evangelist Network overview: true --- <p align="center"><img src="http://kinlane-productions.s3.amazonaws.com/api-evangelist/api-evangelist-logo-400.png" align="center" width="65%" style="padding-bottom: 10px;" /></p> <h1 class="title">API Evangelist Network</h1> <p>API Evangelist is a network of research projects. The website began in July of 2010 as a side research project, and in 2014 not much has changed. I've just gotten more organized about how I manage my research, in real-time using over 100 Github repositories. You can see a complete list of my projects here, but this list is specific to what I do as the API Evangelist.</p> <p><em>An important thing to remember about the API Evangelist network, is that this is my workspace. These projects reflect my work in real-time, and while I constantly am working to refine, and polish the presentation, you are always going to hit unfinished parts of the network. If you find spelling, grammar, and other content or data related mistakes, you can <a href="https://github.com/kinlane/api-evangelist/issues/new" target="_blank">submit a Github issue</a>. If you feel like a list of companies is incomplete, or out of date, you can fork the supporting Github repository, edit the JSON or HTML that drives the content, then submit a pull request to update. For me, learning about the API space is ongoing, and something I hope never stops, and I hope I can instigate the same for you. ;-)</em></p> <p><br /></p> <table width="100%" align="center" cellpadding="1" cellspacing="1"> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19ICsXJ"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-design.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19ICsXJ" style="font-size: 18px; color:#000;"><strong>API Design</strong></a> - Working to understand how developers are designing their APIs, what tools, and services they are using to get a better handle on API design before they actually embark on deploying any code. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19LhUKX" target="_blank"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-api-deployment-2.jpg" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19LhUKX" style="font-size: 18px; color:#000;"><strong>API Deployment</strong></a> - Historically an underdiscussed area, as area has been focused on API management, but recently there is a lot more conversation about how people are actually deploying their APIs using frameworks, cloud services, and other emerging tools and services. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19LhWlS"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/services/api-management.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19LhWlS" style="font-size: 18px; color:#000;"><strong>API Management</strong></a> - Understanding the approach of leading API providers, and trying to aggregate, and share this knowledge so that other API providers can learn from the API pioneers, and better understand which API management tools and services they should be using. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1k7cIHv"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/t-shirts/KL_InApiWeTrust-1000.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1k7cIHv" style="font-size: 18px; color:#000;"><strong>Evangelism</strong></a> - You now have an API, so how do you get the word out? As with other areas, API evangelism, or developer advocacy has emerged with some standardized approaches to how you get the word out about your API, and not just attract new developers, but ensure they integrate a API into their apps. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="/templates/"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-data-template.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="/templates/" style="font-size: 18px; color:#000;"><strong>Templates</strong></a> - As I build out the API Evangelist network, I'm making everything API driven, and publishing API templates I develop to Github, and sharing them here via my site. These aren't meant to be used in production environments, but to be the seeds for further thought in these specific areas. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="/reports/"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-registration.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="/reports/" style="font-size: 18px; color:#000;"><strong>Reports</strong></a> - As I study each area of the API space, I generate reports from the research I do, in hopes of sharing what I am learning with the wider API space. While each research ara has its own Github repository to house the work I do, I also aggregate reports to a single reports page for easy access. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1ktJbuk"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-web-apps.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1ktJbuk" style="font-size: 18px; color:#000;"><strong>Scraping</strong></a> - Not all data and content is easiliy accessible via database connections, or file dumps, and web scraping is proving to be an important approach to deploying valuable data and content via APIs, by harvesting from its existing location and then normalizing for availability via a simple web API. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/OHownu"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/services/bw-embeddable.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/OHownu" style="font-size: 18px; color:#000;"><strong>Embeddable</strong></a> - Embeddable tools were extremeley critical to the success of API pioneers like Twitter and Youtube. These simple, API driven JavaScript tools, allow developers, and even non-developers, to access and extend the valuable resources available via an API.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19IBYkv"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/services/api-discovery.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/19IBYkv" style="font-size: 18px; color:#000;"><strong>Discovery</strong></a> - There are a growing number of ways to find APIs, or inversely, have your API be found. In this decade, API discovery has gone beyond the pioneering website <a href="http://programmableweb.com/">ProgrammableWeb</a>, and we are seeing search engines, and IDE tools emerge to help providers and consumers with API discovery.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/15TuByV"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/services/api-integration.png" width="135" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/15TuByV" style="font-size: 18px; color:#000;"><strong>Integration</strong></a> - As the number of APIs grow, so does the number of APIs used in any single web, mobile, or device based apps. This growth brings with it a wealth of integration challenges, and the results are some interesting tools and services to address common API integration problems--this is my research to better understand the world of API integration. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/18nRqRJ" target="_blank"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/trends/baas-trends.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/18nRqRJ" style="font-size: 18px; color:#000;"><strong>Backend as a Service (BaaS)</strong></a> - In 2011 I started tracking on what people were calling Backend as a Service, or BaaS. This new approach to delivering the resources mobile developers were needing, were similiar to earlier, API driven cloud efforts like PaaS, and IaaS, but ultimately focuses on providing exactly the backend stack, a developer will need to build mobile apps, using APIs.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/10sgtyc" target="_blank"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-stacks.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/10sgtyc" style="font-size: 18px; color:#000;"><strong>The API Stack</strong></a> - I track on over 2,500 public APIs, which I consider to be the best of what the API space has to offer. I publish my profiling of these APIs to a public project I call the API Stack, providing an easy to navigate site of the best APIs out there, including APIs.json definition for each of the API platforms, and when I can, these definitions include machine readable Swagger specifications. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/11RojT4"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/trends/aggregation-trend.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/11RojT4" style="font-size: 18px; color:#000;"><strong>Aggregation</strong></a> - As the number of APIs have grown, the need to aggregate common resources across multiple API providers has increased. API aggregators are emerging in the most mature API sectors like cloud computing, social, and advertising, allowing API consumers to access multiple APIs, using a single common interface--this is my research into API aggregation.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19Li6cS"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/trends/reciprocity-trends.png" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/19Li6cS" style="font-size: 18px; color:#000;"><strong>Reciprocity</strong></a> - As more of our lives move online, and into the clouds, the need to migrate and keep information in sync is increasing. A number of interoperability, automation, and syncing providers are emerging, which put into a bucket called reciprocity--as these companies are providing vital global services, that reflect the objectives of companies, 3rd party developers, and end-users, in this new digital world we've created for ourselves.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/11RorBM"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/trends/real-time-2.jpg" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/11RorBM" style="font-size: 18px; color:#000;"><strong>Real-Time</strong></a> - The pace of technology has significantly increased with the introduction of the Internet, and mobile devices, and there are a number of new API driven approaches to ensure data travels in real-time across the cloud platforms we use, to the mobile devices in our pockets. I'm working hard to better understand the real time realities playing out in the API layer of the Internet.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/10sgWQI"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-microphone.png" width="60" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/10sgWQI" style="font-size: 18px; color:#000;"><strong>Voice</strong></a> - We all know about Siri, the voice system from Apple, but the growing number of API driven voice services is something that doesn't get enough attention. I'm working hard to better understand which providers exist out there, and how they are using APis to connect valuable resources to voice enabled applications and systems.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1k7ffSf"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-hypermedia.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/1k7ffSf" style="font-size: 18px; color:#000;"><strong>Hypermedia</strong></a> - In early 2014 I identified hypermedia was a growing trend that I could no longer ignore. I was seeing a growing number of hypermedia API designs in the wild from leading providers like Amazon, and Paypal, providing a sign that the design matter was moving out of academic discussion, and into the real world. </td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/14ikEgK"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-single-page-app.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/14ikEgK" style="font-size: 18px; color:#000;"><strong>Single Page Apps (SPA)</strong></a> - The concept of building websites as small, single page applications is growing in popularity, and frameworks like Angular.js are making it dead simple to connect these SPAs to vital data and content using APIs. I'm trying to better understand this layer of API deployment, studying how pioneers like SalesForce, and startups are using SPAs + APIs to get business done. </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1wAhy8w"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-shipping-container.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/1wAhy8w" style="font-size: 18px; color:#000;"><strong>Containers</strong></a> - The number one buzzword in 2014 was containers, and the leading approach is coming from Docker. I strongly believe that containers will do for APIs, what APIs have been doing for businesses, and I'm working hard to better understand using containers in conjunction with APIs--this is my research in this area.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/1mTDvG5"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-excel-icon.jpg" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://bit.ly/1mTDvG5" style="font-size: 18px; color:#000;"><strong>Spreadsheets</strong></a> - Most of the worlds data is stored in spreadsheets, making it low hanging fruit for the wave of API deployment. The spreadsheet aspect of APIs doesn't stop there. I'm seeing leading API providers like Twilio deploying spreadsheet connectors for their APIs, allowing anyone to put valuable API resources to work directly from the tool they know best--spreadsheets.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19IDnrj" title="Automobile API"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-car.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/19IDnrj" style="font-size: 18px; color:#000;" title="Automobile API"><strong>Automobile</strong></a> - APIs are moving into our vehicles, with strong API implementations from leading car manufactukrers like Ford. There is also some serious API innovation coming from aftermarket, auto innovators like Carvoyant, and this is my research into better understanding how APIs are colliding with the auto industry.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/17uu35X" title="Home APIs"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-home-icon.jpeg" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://bit.ly/17uu35X" style="font-size: 18px; color:#000;" title="Home APIs"><strong>Home</strong></a> - In 2014 the concept of API driven thermostat, and smoke alarm moved into the mainstream consciousness with Nest. APIs are being deployed to support connecting almost every object in our home to the Internet, from our lights, to our appliances, and home security systems. This is where I keep track of this fast moving sector of APIs.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://federal-government.apievangelist.com/"> <img src="https://s3.amazonaws.com/kinlane-productions/bw-icons/bw-government.jpg" width="100" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"> <a href="http://federal-government.apievangelist.com/" style="font-size: 18px; color:#000;"><strong>Federal Government</strong></a> - The usage of APIs in the federal government has been a personal project for me, over the last two years. Spending time in Washington D.C. as a Presidential Innovation Fellow, and working on open data and API efforts with the White House, GSA, and other agencies. This is the project where I work to publish all of my API research for the federal government, and hoping to help steer this important layer to the API space.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://city-government.apievangelist.com/" target="_blank"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/priorities/bw-city-skyline.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://city-government.apievangelist.com/" style="font-size: 18px; color:#000;"><strong>City Government</strong></a> - Along with API and open data in the federal government, city government has played an important leadership role in the API space. Cities like San Francisco and New York are demonstrating what is possible when cities put APIs to work. 40 of the top 50 cities in the US have open data or API efforts, marking a significant change in how we operate the cities we live in.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://libraries.apievangelist.com/"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/att/universal-library-sign.png" width="110" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://libraries.apievangelist.com" style="font-size: 18px; color:#000;"><strong>Libraries</strong></a> - Libraries are an area where we are seeing important API deployments like the Digital Public Library of America (DPLA), but also an ara I feel we need a lot more investment in API education, and deployments. Libraries will be the stewards of this information change in coming years, and we have a lot of catch up to do--this is my work in helping instigate APIs across our library systems.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> <tr> <td align="center" width="175" style="padding-bottom:5px;padding-top:5px;"> <a href="http://university.apievangelist.com/"> <img src="https://s3.amazonaws.com/kinlane-productions/api-evangelist/priorities/university-of-api.png" width="125" align="center" /> </a> </td> <td align="left" style="padding-bottom:5px;padding-top:5px;"><a href="http://university.apievangelist.com/" style="font-size: 18px; color:#000;"><strong>University</strong></a> - Higher education institutions are ground zero for digital literacy in our world. I've made it a priority to showcase the work of a handful of universities, and how they are using APIs. I am also working to jumpstart API efforts at other institutions, whether it is from the top down out of CTO and CIO office, or from the bottom up, in a student led effort. Here is my work around API in higher eduction.</td> </tr> <tr> <td colspan="2"><hr /><td> </tr> </table> <p>All of these projects live on Github as individual projects, which you can find them under my <a href="https://github.com/kinlane">Github account</a>, and if you have any comments or questions you can <a href="http://kinlane.com/contact/">contact me directly</a>, or feel free to make the change you wish to see in the API Evangelist network. The education of the API space is not just something I do, it is something we all do together.</p> <hr /> <!-- 3scale --> <p align="center"> <a href="http://bit.ly/13esk6Q" target="_blank" title="APIs From 3Scale"> <img src="https://s3.amazonaws.com/kinlane-productions/api-service-providers/3Scale/empowered-by-3scale.png" width="300" style="padding-bottom: 15px;" /> </a> </p>
{ "content_hash": "88655d1e222575a0872998f29fb5c7e9", "timestamp": "", "source": "github", "line_count": 328, "max_line_length": 811, "avg_line_length": 78.64634146341463, "alnum_prop": 0.6544425492324392, "repo_name": "kinlane/dev", "id": "b6c1c0c2bbf29e4a15e874b654a9762383e9dbb4", "size": "25800", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "network/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10717" } ], "symlink_target": "" }
const config = { treis: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TREIS/REST/FeedService/', interval: 120000, name: 'treis' }, tmp: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TMP/REST/FeedService/', interval: 120000, name: 'tmp' }, ssdf: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/SsdfJourney2/REST/FeedService/journeys', interval: 120000, name: 'ssdf' }, cameras: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TrafficCameras2/REST/FeedService/', interval: 120000, name: 'cameras' }, congestion: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TrafficConditions2/REST/FeedService/', interval: 120000, name: 'congestion' }, signs: { url: 'https://infoconnect1.highwayinfo.govt.nz/ic/jbi/VariableMessageSigns2/REST/FeedService/', interval: 120000, name: 'signs' }, ic2Header: { username: process.env.API_USER, password: process.env.API_PASSWORD } }; module.exports = config;
{ "content_hash": "fdf83dbc94ea48679aeb65972da3d2a1", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 97, "avg_line_length": 25.28205128205128, "alnum_prop": 0.7028397565922921, "repo_name": "angelonz/ic2-dashboard", "id": "28395ecff7f642322e7fcb83c9b519a683cdb217", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "configuration/feeds-config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1552" }, { "name": "HTML", "bytes": "271" }, { "name": "JavaScript", "bytes": "16535" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Register of penalty notices | NSW Food Authority</title> <meta name="DC.Identifier" scheme="URI" content="http://www.foodauthority.nsw.gov.au/about"> <meta name="DC.Title" content="Register of penalty notices | NSW Food Authority"> <meta name="DC.Date.modified" scheme="ISO8601" content="2009-02-18"> <meta name="description" content="Name and Shame"> <meta name="keywords" content=""> <meta name="DC.Creator" scheme="AglsAgent" CONTENT="corporateName=NSW Food Authority; jurisdiction=New South Wales; contact=Consumer and Industry Contact Centre; contact=1300 552 406 (Australia wide); contact=+61 02 9741 4850; email=contact@foodauthority.nsw.gov.au; address=PO Box 6682, Silverwater NSW 1811 Australia"> <meta name="DC.Publisher" scheme="AglsAgent" CONTENT="corporateName=NSW Food Authority; jurisdiction=New South Wales; contact=Consumer and Industry Contact Centre; contact=1300 552 406 (Australia wide); contact=+61 02 9741 4850; email=contact@foodauthority.nsw.gov.au; address=PO Box 6682, Silverwater NSW 1811 Australia"> <meta name="DC.Rights" scheme="URI" content="http://www.foodauthority.nsw.gov.au/copyright.asp"> <meta name="DC.Language" scheme="RFC3066" content="en-AU"> <meta name="DC.Format" scheme="IMT" content="text/html"> <meta name="DC.Coverage.jurisdiction" scheme="AglsJuri" content="New South Wales"> <meta name="DC.Type.aggregationLevel" scheme="AGLS" content="collection"> <meta name="DC.Type.category" content="document"> <meta name="DC.Subject" scheme="APAIS" content="food; trade regulation; law; consumer protection; quality control; standards; prosecution; health education; public health; women and health"> <meta name="AGLS.Function" scheme="AGIFT" content="justice administration; law enforcement; prosecution services; food hygiene regulation; food quality assurance; emergency management; consumer protection; product safety; health promotion; public service"> <meta name="DC.Type.documentType" scheme="agls-document" content="guidelines"> <meta name="DC.Type.serviceType" scheme="agls-service" content=""> <meta name="DC.Title.alternative" content=""> <meta name="DC.Date.created" scheme="ISO8601" content="2009-02-18"> <meta name="DC.Date.valid" scheme="DCMIPeriod" content=""> <meta name="DC.description" content="Search tips"> <meta name="DC.keywords" content="role; food act; enforcement; food; safety; standards; health; jurisdiction; structure; organisation; internal"> <meta name="AGLS.Audience" scheme="agls-audience" content="all"> <meta name="DC.Coverage.spatial" scheme="" content="New South Wales"> <meta name="DC.Coverage.temporal" scheme="" content=""> <meta name="DC.Coverage.postcode" scheme="AusPost" content="2000-2599; 2650-2999"> <meta name="DC.Contributor" scheme="" content=""> <meta name="AGLS.Mandate" scheme="" content=""> <meta name="DC.Relation" scheme="" content=""> <meta name="DC.Source" scheme="" content=""> <meta name="robots" content="index; follow"> <meta name="Revisit-After" content="14 days"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta name="rating" content="general"> <link rel="image_src" href="http://images.foodauthority.nsw.gov.au.s3.amazonaws.com/fb_logo_bigger.jpg"> <link rel="stylesheet" media="all" type="text/css" href="css/main-11.css"> <link rel="stylesheet" media="all" type="text/css" href="css/table_sort.css"> <link rel="stylesheet" media="print" type="text/css" href="css/styles_print.css"><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/jquery.cycle.all.min.js"></script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/superfish.js"></script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/reflection.js"></script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/jquery.jcarousel.pack.js"></script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/animatedcollapse.js"></script><script type="text/javascript">document.documentElement.className = 'js';</script><style type="text/css"> .table-data tr.alt td { background-color:#FFFFFF; } #content table.tablesorter tbody tr.odd td { background-color:#F1F6E2; } table.table-data th {background-color: #EA7A37; } </style><script type="text/javascript"> // $(document).ready(function() { $('ul.sf-menu').superfish({ delay:1000, //one second delay on mouse out animation: {opacity:'show'}, // speed: 0 //speed menus show }); $(".table-data tr:even").addClass("alt"); $(".table-data tr th:last").addClass("last-cell"); $('.table-data tr').each(function(){ $(this).children("td:last").addClass("last-cell"); }); }); $(document).ready(function() { $('.slideshow').cycle({ fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc... }); }); /*********************************************** * Animated Collapsible DIV v2.4- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com) * This notice MUST stay intact for legal use * Visit Dynamic Drive at http://www.dynamicdrive.com/ for this script and 100s more ***********************************************/ animatedcollapse.addDiv('translate') //additional addDiv() call... //additional addDiv() call... animatedcollapse.ontoggle=function($, divobj, state){ //fires each time a DIV is expanded/contracted //$: Access to jQuery //divobj: DOM reference to DIV being expanded/ collapsed. Use "divobj.id" to get its ID //state: "block" or "none", depending on state } animatedcollapse.init() // Text increase decrease $(document).ready(function(){ //ID, class and tag element that font size is adjustable in this array //Put in html or body if you want the font of the entire page adjustable var section = new Array('html'); section = section.join(','); // Reset Font Size var originalFontSize = $(section).css('font-size'); $(".resetFont").click(function(){ $(section).css('font-size', originalFontSize); }); // Increase Font Size $(".increaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $(section).css('font-size', newFontSize); return false; }); // Decrease Font Size $(".decreaseFont").click(function(){ var currentFontSize = $(section).css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*.9; $(section).css('font-size', newFontSize); return false; }); }); // </script><script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-11219160-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script><script type="text/javascript" src="http://d1e3w1ke2el0xr.cloudfront.net/jquery.tablesorter.min.js"></script><script type="text/javascript"> $(document).ready(function() { $("#myTable").tablesorter({sortList:[], widgets: ['zebra']}); } ); </script></head> <body id="inner"> <div id="cim_page-wrapper"> <div id="header_wrapper"> <div id="cim_header"> <div id="cim_header-left"><a href="http://www.nsw.gov.au" title="Click for NSW Government portal" class="state" target="_blank"><img src="http://d2o0rfcwltdn3f.cloudfront.net/nswcrest.gif" alt="Click for NSW Government portal" width="53" height="53" align="middle"></a><a href="http://www.foodauthority.nsw.gov.au" title="Click for NSW Food Authority homepage" class="department" style="text-decoration: none;"><img src="http://d2o0rfcwltdn3f.cloudfront.net/logo-nswfa-50.gif" align="middle" alt="Click for NSW Food Authoirty homepage"></a></div> <div id="cim_tools"> <ul> <li class="skip"><a href="#cim_main-content" accesskey="S" title="Go directly to text content. Use access key S to skip on any page.">Skip to content</a></li> <li><a href="/a-z-index">A-Z index</a></li> <li><a href="/aboutus/contact-us/contact-us" accesskey="7">Contact us</a></li> </ul> </div> <div class="search"> <form action="http://www.foodauthority.nsw.gov.au/search/default.htm" id="cse-search-box" method="get" enctype="application/x-www-form-urlencoded"><label for="cim_search-text">Search</label><input type="hidden" name="cx" value="010799167557058114062:vuluuw9iqgg"><input type="hidden" name="cof" value="FORID:10"><input type="hidden" name="ie" value="UTF-8"><input accesskey="4" id="cim_search-text" name="q" onfocus="this.value=''" value="Site search"><input type="image" src="http://d2o0rfcwltdn3f.cloudfront.net/btn-go.gif" value="Search" class="go" alt="Go" name="sa"></form> </div> </div> <div id="cim_top-nav"> <ul id="cim_menu" class="sf-menu"> <li id="menu-item-home"><a href="/" class="btn"><span>Home</span></a></li> <li id="menu-item-news"><a href="/news" class="btn highlight"><span>News</span></a><ul> <li class="btn highlight"><a href="/news/offences">Name &amp; shame</a></li> <li class="btn"><a href="/news/alerts-recalls">Alerts &amp; recalls</a></li> <li class="btn"><a href="/news/media-releases">Media releases</a></li> <li class="btn"><a href="/news/emailalerts">News letter &amp; email</a></li> </ul> </li> <li id="menu-item-everyday"><a href="/consumers" class="btn"><span>Food at home</span></a><ul> <li class="btn"><a href="/consumers/keeping-food-safe">Keeping food safe</a></li> <li class="btn"><a href="/consumers/life-events-and-food">Life events and food</a></li> <li class="btn"><a href="/consumers/food-labels">Labels</a></li> <li class="btn"><a href="/consumers/problems-with-food">Problems with food</a></li> <li class="btn"><a href="/consumers/other-food-topics">Food topics</a></li> <li class="btn"><a href="/consumers/consumer-resources">Resource centre</a></li> <li class="btn"><a href="/consumers/translated-pages-for-consumers">Translations</a></li> </ul> </li> <li id="menu-item-business"><a href="/industry" class="btn"><span>Business standards</span></a><ul> <li class="btn"><a href="/industry/food-standards-and-requirements">General requirements</a></li> <li class="btn"><a href="/industry/industry-sector-requirements">Industry sector requirements</a></li> <li class="btn"><a href="/industry/food-business-issues">Food business topics</a></li> <li class="btn"><a href="/industry/audits-inspections-compliance">Audits, inspections &amp; compliance</a></li> <li class="btn"><a href="/industry/fss-food-safety-supervisors">FSS: food safety supervisors</a></li> <li class="btn"><a href="/industry/complaints-about-food-and-businesses">Complaints</a></li> <li class="btn"><a href="/industry/forms-and-licences">Forms and licences</a></li> <li class="btn"><a href="/industry/news-publications-and-help">Resource centre</a></li> <li class="btn"><a href="/industry/translated-pages-for-industry">Translations</a></li> </ul> </li> <li id="menu-item-science"><a href="/science" class="btn"><span>Science</span></a><ul> <li class="btn"><a href="/science/science-at-authority">Science at the Authority</a></li> <li class="btn"><a href="/science/risk-framework-and-studies">Risk framework &amp; studies</a></li> <li class="btn"><a href="/science/market-analysis">Market analysis</a></li> <li class="btn"><a href="/science/foodborne-illness-case-studies">Foodborne illness case studies</a></li> <li class="btn"><a href="/science/evaluating-what-we-do">Evaluating what we do</a></li> <li class="btn"><a href="/science/science-in-focus">Science in focus</a></li> <li class="btn"><a href="/science/science-links">Science links</a></li> </ul> </li> <li id="menu-item-translations"><a href="/languages" class="btn"><span>Translations</span></a><ul> <li class="btn"><a href="/languages/arabic">لعربية (Arabic)</a></li> <li class="btn"><a href="/languages/chinese">中文 (Chinese)</a></li> <li class="btn"><a href="/languages/greek">Ελληνικά (Greek)</a></li> <li class="btn"><a href="/languages/italian">Italiano (Italian)</a></li> <li class="btn"><a href="/languages/japanese">日本語 (Japanese)</a></li> <li class="btn"><a href="/languages/khmer">Khmer</a></li> <li class="btn"><a href="/languages/korean">한국어 (Korean)</a></li> <li class="btn"><a href="/languages/macedonian">македонски јазик (Macedonian)</a></li> <li class="btn"><a href="/languages/serbian">српски језик (Serbian)</a></li> <li class="btn"><a href="/languages/spanish">español (Spanish)</a></li> <li class="btn"><a href="/languages/thai">ไทย (Thai)</a></li> <li class="btn"><a href="/languages/turkish">Türkçe (Turkish)</a></li> <li class="btn"><a href="/languages/vietnamese">Tiếng Việt (Vietnamese)</a></li> </ul> </li> <li id="menu-item-about"><a href="/aboutus" class="btn"><span>About us</span></a><ul> <li class="btn"><a href="/aboutus/payments">Payments</a></li> <li class="btn"><a href="/aboutus/lists-registers">Lists &amp; registers</a></li> <li class="btn"><a href="/aboutus/publications">Publications</a></li> <li class="btn"><a href="/aboutus/accesstoinformation">Access to information</a></li> <li class="btn"><a href="/aboutus/ministers-message">Minister's message </a></li> <li class="btn"><a href="/aboutus/about-the-authority">About the Authority</a></li> <li class="btn"><a href="/aboutus/about-frp">About Food Regulation Partnership</a></li> <li class="btn"><a href="/aboutus/links-to-other-agencies">Other agencies</a></li> <li class="btn"><a href="/aboutus/contact-us">Contact us</a></li> </ul> </li> </ul> </div> </div> <div class="page_tools"> <div class="page_tools_inner"> <div id="cim_bread-crumbs"> <ul> <li>You are here : <a href="#">Home</a></li> <li>&gt; <a href="/news">News</a></li> <li>&gt; <a href="/news/offences">Name &amp; shame</a></li> <li>&gt; <a href="/news/offences/penalty-notices">Penalty notices</a></li> </ul> </div> <div class="function-icons"> <ul class="function-icons"> <li><a href="javascript:animatedcollapse.toggle('translate')" class="noscript function_icon_translate" title="Translate this page"></a></li> <li><a href="/aboutus/contact-us" title="How to contact the NSW Food Authority" class="function_icon_contact">Contact Us</a></li> <li><a href="#" class="noscript function_icon_print" onclick="window.print();return false;" onkeypress="window.print();return false;" title="Print this page">Print this page</a></li> <li><a href="#" class="noscript function_icon_reducefont decreaseFont" title="Reduce font size">Reduce font size</a></li> <li><a href="#" class="noscript function_icon_increasefont increaseFont" title="Increase font size">Increase font size</a></li> </ul> </div> </div> </div> <div id="translate"><a href="javascript:animatedcollapse.hide('translate')" class="close">[x]</a><script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en' }, 'translate'); } </script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script></div> <div id="cim_content-wrapper"> <div class="c c1"> </div> <div class="c c2"> </div> <div class="c c3"> </div> <div class="c c4"> </div> <div class="wrapper"> <div class="holder"> <div class="frame"> <div id="sidebar"> <ul class="nav"> <li class="active open"><a href="/news/offences">Name &amp; shame</a><ul> <li class="active"><a href="/news/offences/penalty-notices">Penalty notices</a></li> <li><a href="/news/offences/prosecutions">Prosecutions</a></li> <li><a href="/news/offences/changes-and-corrections">Changes and corrections</a></li> </ul> </li> <li><a href="/news/alerts-recalls">Alerts &amp; recalls</a></li> <li class="closed"><a href="/news/media-releases">Media releases</a></li> <li class="closed"><a href="/news/emailalerts">News letter &amp; email</a></li> </ul> </div> <div id="cim_main-content"> <div id="content"> <div class="content-wrapper"> <div class="content-holder"> <div class="content"> <div class="tl"> <div class="tr"> <div class="bl"> <div class="br"> <div class="cim_content"><!-- Details for 7659492262--><h1 class="cim_main">Details - Register of penalty notices</h1> <p>This information about penalty notices issued is published as part of the <em>Register of penalty notices</em>.</p> <div style="WIDTH: 60%"> <table cellspacing="0" cellpadding="0" width="80%" summary="" border="0" class="table-data-pd"> <tbody> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><span class="head"><strong>Penalty notice number</strong></span></td> <td valign="top">7659492262</td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Trade name of party served<br></strong>(or name of place of business)</span></td> <td valign="top">CHICKENS PLUS</td> </tr> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><strong>Address<br></strong>(where offence occurred) </td> <td valign="top">1/1356 PITTWATER ROAD NARRABEEN 2101 </td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Council<br></strong>(where offence occurred)</span></td> <td valign="top">WARRINGAH</td> </tr> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><strong>Date of alleged offence<br></strong>(yyyy-mm-dd) </td> <td valign="top">2011-01-31</td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Offence code</strong></span></td> <td valign="top">11339 - Fail to comply with Food Standards Code - Corporation</td> </tr> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><strong>Nature &amp; circumstances of alleged offence</strong></td> <td valign="top"> <p>Fail to display potentially hazardous food under temperature control - both hot and cold food out of temperature control</p> </td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Amount of penalty </strong></span></td> <td valign="top">$880.00</td> </tr> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><strong>Name of party served<br></strong>(with penalty notice) </td> <td valign="top">WANG TAK INTERNATIONAL PTY LTD</td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Date penalty notice served<br></strong>(yyyy-mm-dd)</span></td> <td valign="top">2011-02-04</td> </tr> <tr bgcolor="#F1F6E2"> <td valign="top" align="right"><strong>Issued by</strong></td> <td valign="top">Warringah Council</td> </tr> <tr> <td valign="top" align="right"><span class="head"><strong>Notes</strong></span></td> <td valign="top"><a href="/aboutus/offences/definitions-notes-to-register"></a></td> </tr> </tbody> </table> </div> <p>Details of this penalty notice were first published 15 Mar 2011, last updated 15 Mar 2011. </p> <p>Payment of a penalty notice is not to be regarded as an admission of liability for the purpose of, nor in any way as affecting or prejudicing, any civil claim, action or proceeding arising out of the same occurrence.</p> <p>People listed in the register or with an interest in a business listed can apply to <a href="http://www.foodauthority.nsw.gov.au/news/offences/changes-and-corrections">add, correct or remove information</a> if a business has been sold or disposed of after an alleged offence, or a correction needs to be made.</p> <p>For information on which penalty notices are included in the register see <a href="http://www.foodauthority.nsw.gov.au/news/offences/penalty-notices/penalty-notice-publication-protocol">Penalty notice publication protocol</a>.</p> <p>Users note this register is <a href="http://www.foodauthority.nsw.gov.au/news/offences/penalty-notices/subject-to-change">subject to change.</a></p> <div id="social"> <div class="right links"> <ul> <li>Follow us: </li> <li><a target="_blank" href="http://twitter.com/NSWFoodAuth"><img class="align" alt="Twitter" src="http://d2o0rfcwltdn3f.cloudfront.net/twitter_16.png"></a></li> <li><a target="_blank" href="http://www.youtube.com/user/nswfoodauthority"><img class="align" alt="YouTube" src="http://d2o0rfcwltdn3f.cloudfront.net/youtube_16.png"></a></li> <li><a target="_blank" href="/news/emailalerts"><img class="align" alt="email alerts" src="http://images.foodauthority.nsw.gov.au.s3.amazonaws.com/email_16.png"></a></li> </ul> </div> <div class="addthis_toolbox addthis_default_style "> <p>Share this:</p><a class="addthis_button_facebook_like"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div><script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4d88138965dbfb06"></script></div><br><div class="also-in-this-site width-50"> <div class="quick-list-box"> <h2>Also on this site</h2> <ul> <li><a href="/penalty-notices">Back to register of penalty notices</a></li> <li><a href="/news/offences">Offences registers</a><em> background</em></li> </ul> <div class="box-endEmpty"> <p> </p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div id="cim_footer"> <div class="page_tools lower_tools"> <div class="page_tools_inner lower_inner"> <div class="function-icons"> <ul class="function-icons"> <li><a href="/aboutus/contact-us" title="How to contact the NSW Food Authority" class="function_icon_contact">Contact Us</a></li> <li><a href="#" class="noscript function_icon_print" onclick="window.print();return false;" onkeypress="window.print();return false;" title="Print this page">Print this page</a></li> <li><a href="#" class="noscript function_icon_reducefont decreaseFont" title="Reduce font size">Reduce font size</a></li> <li><a href="#" class="noscript function_icon_increasefont increaseFont" title="Increase font size">Increase font size</a></li> </ul> </div> </div> </div> <div id="cim_footer_inner"> <div class="footer_content"> <div id="footer_cola"> <h4><a href="/news">News</a></h4> <ul> <li><a href="/news/offences">Name &amp; shame</a></li> <li><a href="/news/alerts-recalls">Alerts &amp; recalls</a></li> <li><a href="/news/media-releases">Media releases</a></li> <li><a href="/news/emailalerts">News letter &amp; email</a></li> </ul> </div> <div id="footer_colb"> <h4><a href="/consumers">Food at home</a></h4> <ul> <li><a href="/consumers/keeping-food-safe">Keeping food safe</a></li> <li><a href="/consumers/life-events-and-food">Life events and food</a></li> <li><a href="/consumers/food-labels">Labels</a></li> <li><a href="/consumers/problems-with-food">Problems with food</a></li> <li><a href="/consumers/other-food-topics">Food topics</a></li> <li><a href="/consumers/consumer-resources">Resource centre</a></li> <li><a href="/consumers/translated-pages-for-consumers">Translations</a></li> </ul> </div> <div id="footer_colc"> <h4><a href="/industry">Business standards</a></h4> <ul> <li><a href="/industry/food-standards-and-requirements">General requirements</a></li> <li><a href="/industry/industry-sector-requirements">Industry sector requirements</a></li> <li><a href="/industry/food-business-issues">Food business topics</a></li> <li><a href="/industry/audits-inspections-compliance">Audits, inspections &amp; compliance</a></li> <li><a href="/industry/fss-food-safety-supervisors">FSS: food safety supervisors</a></li> <li><a href="/industry/complaints-about-food-and-businesses">Complaints</a></li> <li><a href="/industry/forms-and-licences">Forms and licences</a></li> <li><a href="/industry/news-publications-and-help">Resource centre</a></li> <li><a href="/industry/translated-pages-for-industry">Translations</a></li> </ul> </div> <div id="footer_cold"> <h4><a href="/science">Science</a></h4> <ul> <li><a href="/science/science-at-authority">Science at the Authority</a></li> <li><a href="/science/risk-framework-and-studies">Risk framework &amp; studies</a></li> <li><a href="/science/market-analysis">Market analysis</a></li> <li><a href="/science/foodborne-illness-case-studies">Foodborne illness case studies</a></li> <li><a href="/science/evaluating-what-we-do">Evaluating what we do</a></li> <li><a href="/science/science-in-focus">Science in focus</a></li> <li><a href="/science/science-links">Science links</a></li> </ul> </div> <div id="footer_cole"> <h4><a href="/languages">Translations</a></h4> <ul> <li><a href="/languages/arabic">لعربية (Arabic)</a></li> <li><a href="/languages/chinese">中文 (Chinese)</a></li> <li><a href="/languages/greek">Ελληνικά (Greek)</a></li> <li><a href="/languages/italian">Italiano (Italian)</a></li> <li><a href="/languages/japanese">日本語 (Japanese)</a></li> <li><a href="/languages/khmer">Khmer</a></li> <li><a href="/languages/korean">한국어 (Korean)</a></li> <li><a href="/languages/macedonian">македонски јазик (Macedonian)</a></li> <li><a href="/languages/serbian">српски језик (Serbian)</a></li> <li><a href="/languages/spanish">español (Spanish)</a></li> <li><a href="/languages/thai">ไทย (Thai)</a></li> <li><a href="/languages/turkish">Türkçe (Turkish)</a></li> <li><a href="/languages/vietnamese">Tiếng Việt (Vietnamese)</a></li> </ul> </div> <div id="footer_colf"> <h4><a href="/aboutus">About us</a></h4> <ul> <li><a href="/aboutus/payments">Payments</a></li> <li><a href="/aboutus/lists-registers">Lists &amp; registers</a></li> <li><a href="/aboutus/publications">Publications</a></li> <li><a href="/aboutus/accesstoinformation">Access to information</a></li> <li><a href="/aboutus/ministers-message">Minister's message </a></li> <li><a href="/aboutus/about-the-authority">About the Authority</a></li> <li><a href="/aboutus/about-frp">About Food Regulation Partnership</a></li> <li><a href="/aboutus/links-to-other-agencies">Other agencies</a></li> <li><a href="/aboutus/contact-us">Contact us</a></li> </ul> </div> </div><br><div class="footer"> <div class="float-right"> <ul> <li><a href="http://www.jobs.nsw.gov.au/" title="NSW Government jobs database where you can search for vacancies at NSW Food Authority" target="_blank">jobs.nsw</a> </li> <li><a href="/site-map">Sitemap</a> </li> <li><a href="/accessibility" accesskey="3">Accessibility</a> </li> <li><a href="/privacy">Privacy</a> </li> <li><a href="/copyright">Copyright</a> </li> <li><a href="/disclaimer">Disclaimer</a> </li> <li><a href="/contact-us" accesskey="9">Feedback</a></li> </ul> <p id="nswstyle_datelastupdated">Last updated 18-Feb-2009</p> </div> </div> </div> </div> </div> </body> </html><!-- Emma's Birthday 2009 Update -->
{ "content_hash": "e0bc5723ea5612b121511f8b5838c989", "timestamp": "", "source": "github", "line_count": 519, "max_line_length": 803, "avg_line_length": 66.79383429672447, "alnum_prop": 0.5370680205388565, "repo_name": "auxesis/gotgastro.com", "id": "6c8bb734fa8abc4174c07e5daa5c11cd7bd1fdcb", "size": "34815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/cache/penalties/7659492262.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1742" }, { "name": "Ruby", "bytes": "5695" } ], "symlink_target": "" }
package fi.helsinki.cs.nodes.libubispark /** * Created by lagerspe on 21.2.2017. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ class UbisparkException(message: String, cause: Throwable) extends Exception(message, cause) { def this(message: String) = this(message, null) } /** * Exception thrown when execution of some user code in the driver process fails, e.g. * accumulator update fails or failure in takeOrdered (user supplies an Ordering implementation * that can be misbehaving. */ private class UbisparkDriverExecutionException(cause: Throwable) extends UbisparkException("Execution error", cause) /** * Exception thrown when the main user code is run as a child process (e.g. pyspark) and we want * the parent SparkSubmit process to exit with the same exit code. */ private case class UbisparkUserAppException(exitCode: Int) extends UbisparkException(s"User application exited with $exitCode")
{ "content_hash": "de6ded5f0f1eba2bfaf27ec89c742386", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 97, "avg_line_length": 39.325581395348834, "alnum_prop": 0.7575399172087522, "repo_name": "lagerspetz/ubispark-api", "id": "97fb626085b62c47f88081ccc4b1a20bbc3c4550", "size": "1691", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LibUbispark/libubispark/src/main/java/fi/helsinki/cs/nodes/libubispark/UbisparkException.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8894" }, { "name": "Scala", "bytes": "12392" }, { "name": "Shell", "bytes": "30" } ], "symlink_target": "" }
<html> <head> <title>Documentation : JBoss to Geronimo - Security Migration</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff"> <tr> <td valign="top" class="pagebody"> <div class="pageheader"> <span class="pagetitle"> Documentation : JBoss to Geronimo - Security Migration </span> </div> <div class="pagesubheading"> This page last changed on Dec 14, 2005 by <font color="#0050B2">hcunico@gmail.com</font>. </div> <p><a name="JBosstoGeronimo-SecurityMigration-top"></a><br/> <em><b>Article donated by:</b> <a href="mailto:dubrov@isg.axmor.com" title="Send mail to Ivan S Dubrov">Ivan S Dubrov</a>, <a href="mailto:artem@us.ibm.com" title="Send mail to Artem Papkov">Artem Papkov</a>, <a href="mailto:hcunico@gmail.com" title="Send mail to Hernan Cunico">Hernan Cunico</a></em></p> <h1><a name="JBosstoGeronimo-SecurityMigration-Overview"></a>Overview</h1> <p>This article will help you migrate security applications developed for JBoss v4 to Apache Geronimo. This article is part of a series of migration articles covering different types of applications migration.</p> <p>This article provides some details on the differences between these two application servers as well as a detailed step-by-step migration procedure for porting security application from JBoss v4 to Apache Geronimo. To define a common starting point (the source environment), this article provide steps for deploying the sample application into the JBoss source environment. Then you will be guided through the application migration and deployment process onto Apache Geronimo.</p> <p>This article is organized in the following sections:</p> <ul> <li><a href="#JBosstoGeronimo-SecurityMigration-implementation" title="implementation on JBoss to Geronimo - Security Migration">Security implementation analysis</a></li> <li><a href="#JBosstoGeronimo-SecurityMigration-sampleApp" title="sampleApp on JBoss to Geronimo - Security Migration">Sample application</a></li> <li><a href="#JBosstoGeronimo-SecurityMigration-JBoss" title="JBoss on JBoss to Geronimo - Security Migration">The JBoss environment</a></li> <li><a href="#JBosstoGeronimo-SecurityMigration-Geronimo" title="Geronimo on JBoss to Geronimo - Security Migration">The Geronimo environment</a></li> <li><a href="#JBosstoGeronimo-SecurityMigration-migration" title="migration on JBoss to Geronimo - Security Migration">Step-by-step migration</a></li> <li><a href="#JBosstoGeronimo-SecurityMigration-summary" title="summary on JBoss to Geronimo - Security Migration">Summary</a></li> </ul> <h1><a name="JBosstoGeronimo-SecurityMigration-Securityimplementationanalysis"></a>Security implementation analysis <a name="JBosstoGeronimo-SecurityMigration-implementation"></a></h1> <p>Support of J2EE features may vary from one vendor to another and different vendors provide different ways to extend respective specifications and default behaviors with custom ones. The purpose of this section is to provide comparison of similar JBoss and Geronimo features which were applied for the implementation of sample applications. You can use the information below to clearly identify the differences of these two servers and plan accordingly before migration from one to another.</p> <table class='confluenceTable'><tbody> <tr> <th class='confluenceTh'>Features</th> <th class='confluenceTh'>JBoss v4</th> <th class='confluenceTh'>Apache Geronimo</th> </tr> <tr> <td class='confluenceTd'>Custom login modules</td> <td class='confluenceTd'>Supports custom login modules. Custom login modules can be installed as part of the service archive (SAR).</td> <td class='confluenceTd'>Supports custom login modules</td> </tr> <tr> <td class='confluenceTd'>J2EE security</td> <td class='confluenceTd'>Supports both declarative and programmatic J2EE security.</td> <td class='confluenceTd'>Supports both declarative and programmatic J2EE security.</td> </tr> <tr> <td class='confluenceTd'>Deploying realm configuration</td> <td class='confluenceTd'>Supports deployment of realm configuration as part of the service archive (SAR).</td> <td class='confluenceTd'>Realm configuration can be deployed as part of the module or as part of the application.</td> </tr> </tbody></table> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h1><a name="JBosstoGeronimo-SecurityMigration-Sampleapplication"></a>Sample application <a name="JBosstoGeronimo-SecurityMigration-sampleApp"></a></h1> <p>The <a href="http://localhost:9090/download/attachments/1566/security.zip?version=1" title="security.zip attached to JBoss to Geronimo - Security Migration">Security application</a> represents a sample application that exploits security related features in the JBoss. It represents a simple document manager in which users can view and upload documents. It consists of the following three pages:</p> <ul> <li>Login Page</li> <li>Documents Page</li> <li>Login Error Page</li> </ul> <p><img src="JBoss to Geronimo - Security Migration_attachments/secApp_flow.jpg" align="absmiddle" border="0" /></p> <p>The application starts with the Login page. After logging in the user is redirected to the Documents page. There are two types of users - viewers and editors. Both kinds can view documents, but only the editor can upload them.</p> <p>If a user has "editor" role, the upload form is displayed below the documents list. When the user selects a document and presses the "upload" button, the upload method of the BusinessLogic EJB is invoked through the execution of the "Upload" servlet. The Security application will throw an exception if a non-authorized user attempts to call the upload servlet.</p> <p>Users are defined through the property files j2g_users.properties and j2g_groups.properties located in the &lt;security_home&gt;/properties directory.</p> <p>Two predefined users are "user" with password "1" and "editor" with password "2".</p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-ApplicationclassesandJSPpages"></a>Application classes and JSP pages</h2> <p>The Application contains the following JSP pages:</p> <ul> <li>login.jsp - The login page of the application.</li> <li>loginError.jsp - The default error page of the application.</li> <li>main.jsp - The main application page with documents list</li> <li>upload Servlet - Servlet that handles the uploads</li> <li>BusinessLogicEJB - Stateless Session EJB that handles uploads.</li> </ul> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Toolsused"></a>Tools used</h2> <p>The tools used for developing and building security sample application are:</p> <h3><a name="JBosstoGeronimo-SecurityMigration-EclipsewithJBossIDE"></a>Eclipse with JBoss IDE</h3> <p>The Eclipse with JBoss IDE plug-ins was used for development of Java-source code of the sample applications. Eclipse is a very powerful and popular open source development tool. Eclipse can be downloaded from the following URL:</p> <p><a href="http://www.eclipse.org" title="Visit page outside Confluence">&#104;ttp://www.eclipse.org</a></p> <p>JBoss plug-ins are also open source extensions for Eclipse that add some helpful features for creation of J2EE applications (which are not designed for deployment on JBoss only). These plug-ins can be downloaded from the following URL:</p> <p><a href="http://sf.net/projects/jboss" title="Visit page outside Confluence">&#104;ttp://sf.net/projects/jboss</a></p> <h3><a name="JBosstoGeronimo-SecurityMigration-ApacheAnt"></a>Apache Ant</h3> <p>Ant is a pure Java build tool. It is used for building the war files and populating the database for the Online Brokerage application. Ant can be downloaded from the following URL:</p> <p><a href="http://ant.apache.org" title="Visit page outside Confluence">&#104;ttp://ant.apache.org</a></p> <h3><a name="JBosstoGeronimo-SecurityMigration-XDoclet"></a>XDoclet</h3> <p>XDoclet is a tool for generating various artifacts (deployment descriptors, source code) basing on the JavaDoc tags. XDoclet can be downloaded from the following URL:</p> <p><a href="http://xdoclet.sourceforge.net" title="Visit page outside Confluence">&#104;ttp://xdoclet.sourceforge.net</a></p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h1><a name="JBosstoGeronimo-SecurityMigration-TheJBossenvironment"></a>The JBoss environment <a name="JBosstoGeronimo-SecurityMigration-JBoss"></a></h1> <p>This section shows you how and where the sample JBoss reference environment was installed so you can map this scenario to your own implementation.</p> <p>Detailed instructions for installing, configuring, and managing JBoss are provided in the product documentation. Check the product Web site for the most updated documents.</p> <p>The following list highlights the general tasks you will need to complete to install and configure the initial environment as the starting point for deploying the sample application.</p> <ol> <li>Download and install JBoss v4 as explained in the product documentation guides. From now on the installation directory will be referred as <b>&lt;jboss_home&gt;</b></li> <li>Create a copy of the default JBoss v4 application server. Copy recursively <b>&lt;jboss_home&gt;\server\default</b> to <b>&lt;jboss_home&gt;\server\&lt;your_server_name&gt;</b></li> <li>Start the new server by running the <tt>run.sh -c &lt;your_server_name&gt;</tt> command from the <b>&lt;jboss_home&gt;\bin</b> directory.</li> <li>Once the server is started, you can verify that it is running by opening a Web browser and pointing it to this URL: <a href="http://localhost:8080" title="Visit page outside Confluence">&#104;ttp://localhost:8080</a>. You should see the JBoss Welcome window and be able to access the JBoss console.</li> <li>Once the application server is up and running, the next step is to install and configure all the remaining prerequisite software required by the sample application. This step is described in the following section.</li> </ol> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Installandconfigureprerequisitesoftware"></a>Install and configure prerequisite software</h2> <p>Compilation of source code of the sample applications is based on Java libraries distributed along with JBoss. The only additional software which is required for building the applications is Apache Ant.</p> <h3><a name="JBosstoGeronimo-SecurityMigration-ApacheAnt"></a>Apache Ant</h3> <p>If you do not have Ant installed, this is a good time for doing so and making sure that <b>&lt;ant_home&gt;\bin</b> directory is added to the path system environment variable. Apache Ant can be downloaded from the following URL:</p> <p><a href="http://ant.apache.org" title="Visit page outside Confluence">&#104;ttp://ant.apache.org</a></p> <h3><a name="JBosstoGeronimo-SecurityMigration-XDoclet"></a>XDoclet</h3> <p>If you do not have XDoclet installed, this is a good time for doing so. Although XDoclet installation is not required to build the sources at this time. It will be required for modifying the source code. The XDoclet can be downloaded from the following URL:</p> <p><a href="http://xdoclet.sourceforge.net" title="Visit page outside Confluence">&#104;ttp://xdoclet.sourceforge.net</a></p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Buildthesampleapplication"></a>Build the sample application</h2> <p>The Security sample application included with this article provides an Ant script that you will use in order to build the application. Download the Securityapplication from the following link:</p> <p><a href="http://localhost:9090/download/attachments/1566/security.zip?version=1" title="security.zip attached to JBoss to Geronimo - Security Migration">Security Sample</a></p> <p>After extracting the zip file a security directory is created, from now on this directory will be referred as &lt;security_home&gt;. In that directory open the <b>build.properties</b> file and edit the properties to match your environment as shown in the following example:</p> <div class="preformatted" style="border-style: solid; "><div class="preformattedHeader" style="border-bottom-style: solid; "><b>build.properties</b></div><div class="preformattedContent"> <pre># Home directory of JBoss 4.0.2 J2ee Application Server and name of the server # instance on which the application should be deployed (JBoss is also used for # building purposes): jboss.home = &lt;jboss_home&gt; jboss.server = &lt;your_server_name&gt;</pre> </div></div> <p>After the properties are specified run the command <b>ant all</b> in the same directory. Ant will build the Enterprise application archive containing the sample application for JBoss. The archives together with any additional required files (if any) will be placed into the &lt;security_home&gt;/build/jboss directory.</p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Deploythesampleapplication"></a>Deploy the sample application</h2> <p>To deploy the Security application on JBoss, copy the <b>security.ear</b> from the &lt;security_home&gt;/build/jboss directory into the &lt;jboss_home&gt;\server\&lt;your_server_name&gt;\deploy directory.</p> <p>If JBoss is running, it will automatically deploy and start the application. Otherwise, the application will be deployed and started at the next invocation of the application server.</p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Testthesampleapplication"></a>Test the sample application</h2> <p>To test the application, open a Web browser and access the following URL:</p> <p><a href="http://localhost:8080/security" title="Visit page outside Confluence">&#104;ttp://localhost:8080/security</a></p> <p>Try logging in as "user" and as "editor". Try invoking upload servlet directly typing the following URL in the browser <a href="http://localhost:8080/security/upload" title="Visit page outside Confluence">&#104;ttp://localhost:8080/security/upload</a>, you should receive an exception if you do not use an "editor" type user.</p> <p><img src="JBoss to Geronimo - Security Migration_attachments/Security_test.jpg" align="absmiddle" border="0" /></p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h1><a name="JBosstoGeronimo-SecurityMigration-TheGeronimoenvironment"></a>The Geronimo environment <a name="JBosstoGeronimo-SecurityMigration-Geronimo"></a></h1> <p>Download and install Geronimo from the following URL:</p> <p><a href="http://geronimo.apache.org/downloads.html" title="Visit page outside Confluence">&#104;ttp://geronimo.apache.org/downloads.html</a></p> <p>The release notes available there provide clear instructions on system requirements and how to install and start Geronimo. Throughout the rest of this article we will refer to the Geronimo installation directory as <b>&lt;geronimo_home&gt;</b>.</p> <table cellpadding='5' width='85%' cellspacing='8px' class='warningMacro' border="0" align='center'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="icons/emoticons/forbidden.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b class="strong">TCP/IP ports conflict</b><br />If you are planning to run JBoss and Geronimo on the same machine consider to change the default service ports on, at least, one of these servers.</td></tr></table> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h1><a name="JBosstoGeronimo-SecurityMigration-Stepbystepmigration"></a>Step-by-step migration <a name="JBosstoGeronimo-SecurityMigration-migration"></a></h1> <p>Geronimo does not have an equivalent of the JBoss service archives (SARs). In the Security sample application, this archive is used for deploying the realm configuration on JBoss. In the case of Geronimo, this configuration can be placed in the application-wide Geronimo deployment plan <b>geronimo-application.xml</b>. </p> <p>The following steps were performed to migrate the sample application:</p> <ul class="alternate" type="square"> <li>Developed a Geronimo specific deployment plan for the Enterprise application. The <b>geronimo-application.xml</b> deployment plan is located in the &lt;security_home&gt;modules/security.ear/src/META-INF/geronimo directory. During the build process, this deployment plan is placed in the META-INF subdirectory in the EAR archive and should look like the following example:</li> </ul> <div class="code" style="border-style: solid; "><div class="codeHeader" style="border-bottom-style: solid; "><b>geronimo-application.xml</b></div><div class="codeContent"> <pre class="code-xml"><span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span> &lt;application xmlns=<span class="code-quote">"http://geronimo.apache.org/xml/ns/j2ee/application"</span> configId=<span class="code-quote">"com/ibm/j2g/security"</span> parentId=<span class="code-quote">"org/apache/geronimo/Server"</span>&gt; <span class="code-tag">&lt;security xmlns=<span class="code-quote">"http://geronimo.apache.org/xml/ns/security"</span>&gt;</span> <span class="code-tag">&lt;default-principal realm-name=<span class="code-quote">"j2g"</span>&gt;</span> <span class="code-tag">&lt;principal class=<span class="code-quote">"org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"</span> name=<span class="code-quote">"system"</span>/&gt;</span> <span class="code-tag">&lt;/default-principal&gt;</span> <span class="code-tag">&lt;role-mappings&gt;</span> <span class="code-tag">&lt;role role-name=<span class="code-quote">"authenticated"</span>&gt;</span> <span class="code-tag">&lt;realm realm-name=<span class="code-quote">"j2g"</span>&gt;</span> <span class="code-tag">&lt;principal class=<span class="code-quote">"org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"</span> name=<span class="code-quote">"authenticated"</span>/&gt;</span> <span class="code-tag">&lt;/realm&gt;</span> <span class="code-tag">&lt;/role&gt;</span> <span class="code-tag">&lt;role role-name=<span class="code-quote">"uploader"</span>&gt;</span> <span class="code-tag">&lt;realm realm-name=<span class="code-quote">"j2g"</span>&gt;</span> <span class="code-tag">&lt;principal class=<span class="code-quote">"org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"</span> name=<span class="code-quote">"uploader"</span>/&gt;</span> <span class="code-tag">&lt;/realm&gt;</span> <span class="code-tag">&lt;/role&gt;</span> <span class="code-tag">&lt;/role-mappings&gt;</span> <span class="code-tag">&lt;/security&gt;</span> &lt;gb:gbean name=<span class="code-quote">"j2g-realm"</span> class=<span class="code-quote">"org.apache.geronimo.security.realm.GenericSecurityRealm"</span> <span class="code-keyword">xmlns:gb</span>=<span class="code-quote">"http://geronimo.apache.org/xml/ns/deployment-1.0"</span>&gt; <span class="code-tag">&lt;gb:reference name=<span class="code-quote">"ServerInfo"</span>&gt;</span> <span class="code-tag">&lt;gb:application&gt;</span>*<span class="code-tag">&lt;/gb:application&gt;</span> <span class="code-tag">&lt;gb:module&gt;</span>org/apache/geronimo/System<span class="code-tag">&lt;/gb:module&gt;</span> <span class="code-tag">&lt;gb:name&gt;</span>ServerInfo<span class="code-tag">&lt;/gb:name&gt;</span> <span class="code-tag">&lt;/gb:reference&gt;</span> <span class="code-tag">&lt;gb:reference name=<span class="code-quote">"LoginService"</span>&gt;</span> <span class="code-tag">&lt;gb:application&gt;</span>*<span class="code-tag">&lt;/gb:application&gt;</span> <span class="code-tag">&lt;gb:module&gt;</span>org/apache/geronimo/Security<span class="code-tag">&lt;/gb:module&gt;</span> <span class="code-tag">&lt;gb:name&gt;</span>JaasLoginService<span class="code-tag">&lt;/gb:name&gt;</span> <span class="code-tag">&lt;/gb:reference&gt;</span> <span class="code-tag">&lt;gb:attribute name=<span class="code-quote">"realmName"</span>&gt;</span>j2g<span class="code-tag">&lt;/gb:attribute&gt;</span> <span class="code-tag">&lt;gb:xml-reference name=<span class="code-quote">"LoginModuleConfiguration"</span>&gt;</span> <span class="code-tag">&lt;l:login-config <span class="code-keyword">xmlns:l</span>=<span class="code-quote">"http://geronimo.apache.org/xml/ns/loginconfig"</span>&gt;</span> <span class="code-tag">&lt;l:login-module control-flag=<span class="code-quote">"REQUIRED"</span> server-side=<span class="code-quote">"true"</span>&gt;</span> <span class="code-tag">&lt;l:login-domain-name&gt;</span>j2g<span class="code-tag">&lt;/l:login-domain-name&gt;</span> <span class="code-tag">&lt;l:login-module-class&gt;</span> org.apache.geronimo.security.realm.providers.PropertiesFileLoginModule <span class="code-tag">&lt;/l:login-module-class&gt;</span> <span class="code-tag">&lt;l:option name=<span class="code-quote">"usersURI"</span>&gt;</span> var/security/j2g_users.properties <span class="code-tag">&lt;/l:option&gt;</span> <span class="code-tag">&lt;l:option name=<span class="code-quote">"groupsURI"</span>&gt;</span> var/security/j2g_groups.properties <span class="code-tag">&lt;/l:option&gt;</span> <span class="code-tag">&lt;/l:login-module&gt;</span> <span class="code-tag">&lt;/l:login-config&gt;</span> <span class="code-tag">&lt;/gb:xml-reference&gt;</span> <span class="code-tag">&lt;/gb:gbean&gt;</span> <span class="code-tag">&lt;/application&gt;</span></pre> </div></div> <table cellpadding='5' width='85%' cellspacing='8px' class='infoMacro' border="0" align='center'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>Note that in contrast to JBoss, application roles must be explicitly defined in the deployment plan.</td></tr></table> <ul class="alternate" type="square"> <li>Created a Geronimo specific deployment plan for the EJB module <b>openejb-jar.xml</b>. This deployment plan is located in the &lt;security_home&gt;/modules/security.jar/src/META-INF/geronimo/openejb-jar.xml. During the build the file is copied to the META-INF subdirectory of the security.jar EJB module. This deployment plan should look like the following example:</li> </ul> <div class="code" style="border-style: solid; "><div class="codeHeader" style="border-bottom-style: solid; "><b>openejb-jar.xml</b></div><div class="codeContent"> <pre class="code-xml"><span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span>?&gt;</span> &lt;openejb-jar xmlns=<span class="code-quote">"http://www.openejb.org/xml/ns/openejb-jar"</span> configId=<span class="code-quote">"com/ibm/j2g/security/ejb"</span> parentId=<span class="code-quote">"com/ibm/j2g/security"</span>&gt; <span class="code-tag">&lt;enterprise-beans&gt;</span> <span class="code-tag">&lt;session&gt;</span> <span class="code-tag">&lt;ejb-name&gt;</span>BusinessLogic<span class="code-tag">&lt;/ejb-name&gt;</span> <span class="code-tag">&lt;/session&gt;</span> <span class="code-tag">&lt;/enterprise-beans&gt;</span> <span class="code-tag">&lt;/openejb-jar&gt;</span></pre> </div></div> <ul class="alternate" type="square"> <li>Created a Geronimo specificdeployment plan for the Web module <b>geronimo-web.xml</b>. This plan is located in the security/modules/security.war/src/WEB-INF/geronimo/geronimo-web.xml. During the build, this file is copied to the WEB-INF subdirectory of the security.war Web module. This deployment plan should look like the following example:</li> </ul> <div class="code" style="border-style: solid; "><div class="codeHeader" style="border-bottom-style: solid; "><b>geronimo-web.xml</b></div><div class="codeContent"> <pre class="code-xml">&lt;web-app xmlns=<span class="code-quote">"http://geronimo.apache.org/xml/ns/web"</span> configId=<span class="code-quote">"com/ibm/j2g/security/web"</span> parentId=<span class="code-quote">"com/ibm/j2g/security"</span>&gt; <span class="code-tag">&lt;context-root&gt;</span>/security<span class="code-tag">&lt;/context-root&gt;</span> <span class="code-tag">&lt;context-priority-classloader&gt;</span>true<span class="code-tag">&lt;/context-priority-classloader&gt;</span> <span class="code-tag">&lt;security-realm-name&gt;</span>j2g<span class="code-tag">&lt;/security-realm-name&gt;</span> <span class="code-tag">&lt;/web-app&gt;</span></pre> </div></div> <ul class="alternate" type="square"> <li>Rewrited the properties files with users to group mapping. JBoss login module have mapping in the form of "user=group1,group2" and Geronimo have mapping in the form of "group=user1,user2".</li> </ul> <p>Since the realm configuration is done in the geronimo-application.xml, the SAR archive is not required anymore. Actually, this archive can contain custom login modules as well, but since there is some difficulties regarding the deployment of custom login modules to Geronimo (see JIRA <a href="http://issues.apache.org/jira/browse/GERONIMO-1044" title="Visit page outside Confluence">GERONIMO-1044</a> ) they are not covered in this article.</p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <h2><a name="JBosstoGeronimo-SecurityMigration-Buildthemigratedsampleapplication"></a>Build the migrated sample application</h2> <p>In order to build modules of the Security application file for Geronimo, make sure that the properties starting with the prefix <b>jboss</b> still match your environment. The build scripts still refer to JBoss libraries for J2EE API interfaces required for the source code compilation.</p> <table cellpadding='5' width='85%' cellspacing='8px' class='infoMacro' border="0" align='center'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>You can update the classpath in the <b>build.xml</b> file to point to Geronimo and get the jars from there and not from JBoss.</td></tr></table> <p>After the properties have been specified, run the <b>ant all</b> command in the &lt;security_home&gt; directory. Ant will build the Enterprise application archive containing the sample application for Geronimo. The archives together with additional required files (if any) will be placed in the &lt;security_home&gt;/build/geronimo directory.</p> <p>The build system was updated to include Geronimo-specific deployment plan in the application modules. SAR archive was removed from the build.</p> <h2><a name="JBosstoGeronimo-SecurityMigration-Deploythemigratedsampleapplication"></a>Deploy the migrated sample application</h2> <p>To deploy the migrated Security application, make sure the Geronimo server is up and running.</p> <p>Copy the properties files with users and groups definition from the &lt;security_home&gt;/properties directory to the &lt;geronimo_home&gt;/var/security directory</p> <p>From a command line, change directory to &lt;geronimo_home&gt;/bin and type the following command:</p> <p>java -jar deployer.jar --user system --password manager deploy &lt;security_home&gt;/build/geronimo/security.ear</p> <p>Once the application is deployed, open a Web browser and access the following URL:</p> <p><a href="http://localhost:8080/security" title="Visit page outside Confluence">&#104;ttp://localhost:8080/security</a></p> <p>Login with the same user name and password you used when testing the application from JBoss.</p> <h1><a name="JBosstoGeronimo-SecurityMigration-Summary"></a>Summary <a name="JBosstoGeronimo-SecurityMigration-summary"></a></h1> <p>This article showed you how to migrate a Security application that exploits some of the J2EE security-related features such as EJB declarative security, Web declarative security and Web programmatic security. </p> <p>In both environments built-in login module was used. This article showed that such kind of applications require minimal migration efforts, although in more complex cases there could be more time-consuming issues.</p> <p><a href="#JBosstoGeronimo-SecurityMigration-top" title="top on JBoss to Geronimo - Security Migration">Back to Top</a></p> <br/> <div class="tabletitle"> <a name="attachments">Attachments:</a> </div> <div class="greybox" align="left"> <img src="icons/bullet_blue.gif" height="8" width="8" alt=""/> <a href="JBoss to Geronimo - Security Migration_attachments/secApp_flow.jpg">secApp_flow.jpg</a> (image/pjpeg) <br/> <img src="icons/bullet_blue.gif" height="8" width="8" alt=""/> <a href="JBoss to Geronimo - Security Migration_attachments/security.zip">security.zip</a> (application/x-zip-compressed) <br/> <img src="icons/bullet_blue.gif" height="8" width="8" alt=""/> <a href="JBoss to Geronimo - Security Migration_attachments/Security_test.jpg">Security_test.jpg</a> (image/pjpeg) <br/> </div> </td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td height="12" background="border/border_bottom.gif"><img src="border/spacer.gif" width="1" height="1" border="0"/></td> </tr> <tr> <td align="center"><font color="grey">Document generated by Confluence on Dec 15, 2005 19:14</font></td> </tr> </table> </body> </html>
{ "content_hash": "5cae27696a49c1b1acbb7b516c57f7cb", "timestamp": "", "source": "github", "line_count": 377, "max_line_length": 496, "avg_line_length": 84.03713527851458, "alnum_prop": 0.7196831008143425, "repo_name": "meetdestiny/geronimo-trader", "id": "83209ec3e19c2c7aae9a7733d0c4d48b61b0e0e4", "size": "31682", "binary": false, "copies": "2", "ref": "refs/heads/1.0", "path": "modules/scripts/src/resources/docs/JBoss to Geronimo - Security Migration.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "47972" }, { "name": "Java", "bytes": "8387339" }, { "name": "JavaScript", "bytes": "906" }, { "name": "Shell", "bytes": "62441" }, { "name": "XSLT", "bytes": "4468" } ], "symlink_target": "" }
package org.kie.workbench.common.screens.server.management.client; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.enterprise.event.Event; import org.jboss.errai.common.client.api.Caller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.server.controller.api.model.events.ServerInstanceDeleted; import org.kie.server.controller.api.model.events.ServerTemplateDeleted; import org.kie.server.controller.api.model.events.ServerTemplateUpdated; import org.kie.server.controller.api.model.runtime.ServerInstanceKey; import org.kie.server.controller.api.model.spec.ContainerSpec; import org.kie.server.controller.api.model.spec.ContainerSpecKey; import org.kie.server.controller.api.model.spec.ServerTemplate; import org.kie.server.controller.api.model.spec.ServerTemplateKey; import org.kie.server.controller.api.model.spec.ServerTemplateKeyList; import org.kie.workbench.common.screens.server.management.client.container.ContainerPresenter; import org.kie.workbench.common.screens.server.management.client.container.empty.ServerContainerEmptyPresenter; import org.kie.workbench.common.screens.server.management.client.empty.ServerEmptyPresenter; import org.kie.workbench.common.screens.server.management.client.events.ContainerSpecSelected; import org.kie.workbench.common.screens.server.management.client.events.ServerInstanceSelected; import org.kie.workbench.common.screens.server.management.client.events.ServerTemplateSelected; import org.kie.workbench.common.screens.server.management.client.navigation.ServerNavigationPresenter; import org.kie.workbench.common.screens.server.management.client.navigation.template.ServerTemplatePresenter; import org.kie.workbench.common.screens.server.management.client.remote.RemotePresenter; import org.kie.workbench.common.screens.server.management.client.util.ClientContainerRuntimeOperation; import org.kie.workbench.common.screens.server.management.model.ContainerRuntimeOperation; import org.kie.workbench.common.screens.server.management.model.ContainerRuntimeState; import org.kie.workbench.common.screens.server.management.model.ContainerUpdateEvent; import org.kie.workbench.common.screens.server.management.service.SpecManagementService; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.uberfire.mocks.CallerMock; import org.uberfire.mocks.EventSourceMock; import org.uberfire.workbench.events.NotificationEvent; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.Silent.class) public class ServerManagementBrowserPresenterTest { @Mock Logger logger; @Mock ServerTemplatePresenter serverTemplatePresenter; @Mock ServerEmptyPresenter serverEmptyPresenter; @Mock ServerContainerEmptyPresenter serverContainerEmptyPresenter; @Mock ContainerPresenter containerPresenter; @Mock RemotePresenter remotePresenter; Caller<SpecManagementService> specManagementServiceCaller; @Mock SpecManagementService specManagementService; @Spy Event<ServerTemplateSelected> serverTemplateSelectedEvent = new EventSourceMock<ServerTemplateSelected>(); @Spy Event<NotificationEvent> notification = new EventSourceMock<NotificationEvent>(); @Mock ServerManagementBrowserPresenter.View view; @Mock ServerNavigationPresenter navigationPresenter; ServerManagementBrowserPresenter presenter; @Before public void init() { specManagementServiceCaller = new CallerMock<SpecManagementService>( specManagementService ); doNothing().when( serverTemplateSelectedEvent ).fire( any( ServerTemplateSelected.class ) ); doNothing().when( notification ).fire( any( NotificationEvent.class ) ); presenter = spy( new ServerManagementBrowserPresenter( logger, view, navigationPresenter, serverTemplatePresenter, serverEmptyPresenter, serverContainerEmptyPresenter, containerPresenter, remotePresenter, specManagementServiceCaller, serverTemplateSelectedEvent, notification ) ); } @Test public void testInit() { presenter.init(); verify( view ).setNavigation( navigationPresenter.getView() ); assertEquals( view, presenter.getView() ); } @Test public void testOnSelectedContainerSpec() { final ContainerPresenter.View containerView = mock( ContainerPresenter.View.class ); when( containerPresenter.getView() ).thenReturn( containerView ); presenter.onSelected( new ContainerSpecSelected( new ContainerSpecKey() ) ); verify( view ).setContent( containerView ); } @Test public void testOnSelectedServerInstance() { final RemotePresenter.View remoteView = mock( RemotePresenter.View.class ); when( remotePresenter.getView() ).thenReturn( remoteView ); presenter.onSelected( new ServerInstanceSelected( new ServerInstanceKey() ) ); verify( view ).setContent( remoteView ); } @Test public void testOnSelectedServerTemplate() { final ServerTemplate serverTemplate = new ServerTemplate( "ServerTemplateId", "ServerTemplateName" ); final ServerTemplateKey serverTemplateKey = new ServerTemplateKey( "ServerTemplateKeyId", "ServerTemplateKeyName" ); when( specManagementService.getServerTemplate( serverTemplateKey.getId() ) ).thenReturn( serverTemplate ); final ServerTemplatePresenter.View serverView = mock( ServerTemplatePresenter.View.class ); when( serverTemplatePresenter.getView() ).thenReturn( serverView ); final ServerContainerEmptyPresenter.View serverEmptyView = mock( ServerContainerEmptyPresenter.View.class ); when( serverContainerEmptyPresenter.getView() ).thenReturn( serverEmptyView ); presenter.onSelected( new ServerTemplateSelected( serverTemplateKey ) ); verify( view ).setServerTemplate( serverView ); verify( specManagementService ).getServerTemplate( serverTemplateKey.getId() ); verify( serverContainerEmptyPresenter ).setTemplate( serverTemplate ); verify( view ).setContent( serverEmptyView ); verify( serverTemplatePresenter ).setup( serverTemplate, null ); } @Test public void testOnSelectedNonEmptyServerTemplate() { final ServerTemplate serverTemplate = new ServerTemplate( "ServerTemplateId", "ServerTemplateName" ); final ContainerSpec toBeSelected = mock( ContainerSpec.class ); serverTemplate.addContainerSpec( toBeSelected ); when( toBeSelected.getId() ).thenReturn( "other-id" ); final ContainerSpec forcedToBeSelected = mock( ContainerSpec.class ); when( forcedToBeSelected.getId() ).thenReturn( "container-id" ); serverTemplate.addContainerSpec( forcedToBeSelected ); final ServerTemplateKey serverTemplateKey = new ServerTemplateKey( "ServerTemplateKeyId", "ServerTemplateKeyName" ); when( specManagementService.getServerTemplate( serverTemplateKey.getId() ) ).thenReturn( serverTemplate ); final ServerTemplatePresenter.View serverView = mock( ServerTemplatePresenter.View.class ); when( serverTemplatePresenter.getView() ).thenReturn( serverView ); presenter.onSelected( new ServerTemplateSelected( serverTemplateKey ) ); verify( view ).setServerTemplate( serverView ); verify( specManagementService ).getServerTemplate( serverTemplateKey.getId() ); verify( serverTemplatePresenter ).setup( serverTemplate, toBeSelected ); presenter.onSelected( new ServerTemplateSelected( serverTemplateKey, "container-id" ) ); verify( serverTemplatePresenter ).setup( serverTemplate, forcedToBeSelected ); } @Test public void testOnOpen() { final ServerTemplateKey serverTemplateKey = new ServerTemplateKey( "ServerTemplateKeyId", "ServerTemplateKeyName" ); final List<ServerTemplateKey> serverTemplateKeys = Collections.singletonList( serverTemplateKey ); when( specManagementService.listServerTemplateKeys() ).thenReturn( new ServerTemplateKeyList(serverTemplateKeys) ); presenter.onOpen(); verify( navigationPresenter ).setup( serverTemplateKey, serverTemplateKeys ); final ArgumentCaptor<ServerTemplateSelected> templateSelectedCaptor = ArgumentCaptor.forClass( ServerTemplateSelected.class ); verify( serverTemplateSelectedEvent ).fire( templateSelectedCaptor.capture() ); assertEquals( serverTemplateKey, templateSelectedCaptor.getValue().getServerTemplateKey() ); } @Test public void testSetupEmpty() { final ServerEmptyPresenter.View serverEmptyView = mock( ServerEmptyPresenter.View.class ); when( serverEmptyPresenter.getView() ).thenReturn( serverEmptyView ); presenter.setup( Collections.<ServerTemplateKey>emptyList(), null ); verify( view ).setEmptyView( serverEmptyView ); verify( navigationPresenter ).clear(); } @Test public void testOnServerDeleted() { final ServerTemplateKey serverTemplateKey = new ServerTemplateKey( "ServerTemplateKeyId", "ServerTemplateKeyName" ); final List<ServerTemplateKey> serverTemplateKeys = Collections.singletonList( serverTemplateKey ); when( specManagementService.listServerTemplateKeys() ).thenReturn( new ServerTemplateKeyList(serverTemplateKeys) ); presenter.onServerDeleted( new ServerTemplateDeleted() ); verify( navigationPresenter ).setup( serverTemplateKey, serverTemplateKeys ); final ArgumentCaptor<ServerTemplateSelected> templateSelectedCaptor = ArgumentCaptor.forClass( ServerTemplateSelected.class ); verify( serverTemplateSelectedEvent ).fire( templateSelectedCaptor.capture() ); assertEquals( serverTemplateKey, templateSelectedCaptor.getValue().getServerTemplateKey() ); } @Test public void testOnServerTemplateUpdated() { final ServerTemplate serverTemplate = new ServerTemplate( "ServerTemplateId", "ServerTemplateName" ); presenter.onServerTemplateUpdated( new ServerTemplateUpdated( serverTemplate ) ); final ArgumentCaptor<Collection> serverTemplateKeysCaptor = ArgumentCaptor.forClass( Collection.class ); verify( navigationPresenter ).setup( eq( serverTemplate ), serverTemplateKeysCaptor.capture() ); final Collection<ServerTemplateKey> serverTemplateKeys = serverTemplateKeysCaptor.getValue(); assertEquals( 1, serverTemplateKeys.size() ); assertTrue( serverTemplateKeys.contains( serverTemplate ) ); final ArgumentCaptor<ServerTemplateSelected> templateSelectedCaptor = ArgumentCaptor.forClass( ServerTemplateSelected.class ); verify( serverTemplateSelectedEvent ).fire( templateSelectedCaptor.capture() ); assertEquals( serverTemplate, templateSelectedCaptor.getValue().getServerTemplateKey() ); } @Test public void testOnDelete() { final ServerInstanceKey serverInstanceKey = new ServerInstanceKey( "serverInstanceKeyId", "serverName", "serverInstanceId", "url" ); final ServerTemplate serverTemplate = new ServerTemplate( "ServerTemplateId", "ServerTemplateName" ); serverTemplate.addServerInstance( serverInstanceKey ); when( serverTemplatePresenter.getCurrentServerTemplate() ).thenReturn( serverTemplate ); final ServerTemplateKey serverTemplateKey = new ServerTemplateKey( "ServerTemplateKeyId", "ServerTemplateKeyName" ); final List<ServerTemplateKey> serverTemplateKeys = Collections.singletonList( serverTemplateKey ); when( specManagementService.listServerTemplateKeys() ).thenReturn( new ServerTemplateKeyList(serverTemplateKeys) ); presenter.onDelete( new ServerInstanceDeleted( serverInstanceKey.getServerInstanceId() ) ); verify( navigationPresenter ).setup( serverTemplateKey, serverTemplateKeys ); final ArgumentCaptor<ServerTemplateSelected> templateSelectedCaptor = ArgumentCaptor.forClass( ServerTemplateSelected.class ); verify( serverTemplateSelectedEvent ).fire( templateSelectedCaptor.capture() ); assertEquals( serverTemplateKey, templateSelectedCaptor.getValue().getServerTemplateKey() ); } @Test public void testOnDeleteWithoutCurrentServer() { final ServerInstanceKey serverInstanceKey = new ServerInstanceKey( "serverInstanceKeyId", "serverName", "serverInstanceId", "url" ); presenter.onDelete( new ServerInstanceDeleted( serverInstanceKey.getServerInstanceId() ) ); verify( specManagementService, never() ).listServerTemplateKeys(); } @Test public void testOnContainerUpdateSuccess() { when( view.getSuccessMessage( ClientContainerRuntimeOperation.START_CONTAINER, 2 ) ).thenReturn( "Success" ); presenter.onContainerUpdate( new ContainerUpdateEvent( mock( ServerTemplateKey.class ), mock( ContainerSpec.class ), new ArrayList<ServerInstanceKey>() {{ add( mock( ServerInstanceKey.class ) ); add( mock( ServerInstanceKey.class ) ); }}, ContainerRuntimeState.ONLINE, ContainerRuntimeOperation.START_CONTAINER ) ); verify( notification ).fire( new NotificationEvent( "Success", NotificationEvent.NotificationType.SUCCESS ) ); } @Test public void testOnContainerUpdateFailed() { when( view.getErrorMessage( ClientContainerRuntimeOperation.START_CONTAINER, 2 ) ).thenReturn( "Error" ); presenter.onContainerUpdate( new ContainerUpdateEvent( mock( ServerTemplateKey.class ), mock( ContainerSpec.class ), new ArrayList<ServerInstanceKey>() {{ add( mock( ServerInstanceKey.class ) ); add( mock( ServerInstanceKey.class ) ); }}, ContainerRuntimeState.OFFLINE, ContainerRuntimeOperation.START_CONTAINER ) ); verify( notification ).fire( new NotificationEvent( "Error", NotificationEvent.NotificationType.ERROR ) ); } @Test public void testOnContainerUpdateWarn() { when( view.getWarnMessage( ClientContainerRuntimeOperation.START_CONTAINER, 2 ) ).thenReturn( "Warn" ); presenter.onContainerUpdate( new ContainerUpdateEvent( mock( ServerTemplateKey.class ), mock( ContainerSpec.class ), new ArrayList<ServerInstanceKey>() {{ add( mock( ServerInstanceKey.class ) ); add( mock( ServerInstanceKey.class ) ); }}, ContainerRuntimeState.PARTIAL_ONLINE, ContainerRuntimeOperation.START_CONTAINER ) ); verify( notification ).fire( new NotificationEvent( "Warn", NotificationEvent.NotificationType.WARNING ) ); } @Test public void testOnContainerEmptyList() { presenter.onContainerUpdate( new ContainerUpdateEvent( mock( ServerTemplateKey.class ), mock( ContainerSpec.class ), Collections.emptyList(), ContainerRuntimeState.PARTIAL_ONLINE, ContainerRuntimeOperation.START_CONTAINER ) ); verify( notification, never() ).fire( any() ); } @Test public void testOnContainerNull() { presenter.onContainerUpdate( new ContainerUpdateEvent() ); verify( notification, never() ).fire( any() ); } }
{ "content_hash": "864996856fad3d794c6a92f8a9b52b6b", "timestamp": "", "source": "github", "line_count": 335, "max_line_length": 140, "avg_line_length": 50.59701492537314, "alnum_prop": 0.6845427728613569, "repo_name": "romartin/kie-wb-common", "id": "67fd87f20f182d79dedb934c46273f5a2d968add", "size": "17571", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "kie-wb-common-screens/kie-wb-common-server-ui/kie-wb-common-server-ui-client/src/test/java/org/kie/workbench/common/screens/server/management/client/ServerManagementBrowserPresenterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2591" }, { "name": "CSS", "bytes": "171885" }, { "name": "Dockerfile", "bytes": "210" }, { "name": "FreeMarker", "bytes": "38625" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "448966" }, { "name": "Java", "bytes": "51118150" }, { "name": "JavaScript", "bytes": "34587" }, { "name": "Shell", "bytes": "905" }, { "name": "TypeScript", "bytes": "26851" }, { "name": "VBA", "bytes": "86549" }, { "name": "XSLT", "bytes": "2327" } ], "symlink_target": "" }
package org.robolectric.shadows; import android.os.Parcel; import android.os.Parcelable; class TestParcelableImpl extends TestParcelableBase implements Parcelable { public TestParcelableImpl(int contents) { super(contents); } @Override public int describeContents() { return 0; } public static final Creator<TestParcelableImpl> CREATOR = new Creator<TestParcelableImpl>() { @Override public TestParcelableImpl createFromParcel(Parcel source) { return new TestParcelableImpl(source.readInt()); } @Override public TestParcelableImpl[] newArray(int size) { return new TestParcelableImpl[0]; } }; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(contents); } }
{ "content_hash": "2bbbef88eafff1d44b0d8b9d110b793e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 75, "avg_line_length": 24.242424242424242, "alnum_prop": 0.68875, "repo_name": "spotify/robolectric", "id": "524156d6c1a0c38c8cd32dc3465bd96536d1ba18", "size": "800", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "robolectric/src/test/java/org/robolectric/shadows/TestParcelableImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "27392" }, { "name": "Java", "bytes": "4430781" }, { "name": "Ruby", "bytes": "9159" }, { "name": "Shell", "bytes": "20540" } ], "symlink_target": "" }
<?php namespace nitm\search; interface SearchInterface { const SEARCH_PARAM = '__searchType'; const SEARCH_PARAM_BOOL = '__searchIncl'; const SEARCH_FULLTEXT = 'text'; const SEARCH_NORMAL = 'default'; } ?>
{ "content_hash": "10b4d6128e3e27448339f96c89a8fcb5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 42, "avg_line_length": 17.583333333333332, "alnum_prop": 0.7061611374407583, "repo_name": "mhdevnet/yii2-search", "id": "9154af5c348e62b84cbc1af9f9dbba96a80c7e93", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SearchInterface.php", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3875" }, { "name": "PHP", "bytes": "152368" } ], "symlink_target": "" }
#include "config.h" #include "Pasteboard.h" #include "BitmapInfo.h" #include "ClipboardUtilitiesWin.h" #include "Document.h" #include "DocumentFragment.h" #include "Element.h" #include "Frame.h" #include "HWndDC.h" #include "HitTestResult.h" #include "Image.h" #include "KURL.h" #include "NotImplemented.h" #include "Page.h" #include "Range.h" #include "RenderImage.h" #include "TextEncoding.h" #include "WebCoreInstanceHandle.h" #include "WindowsExtras.h" #include "markup.h" #include <wtf/text/CString.h> namespace WebCore { static UINT HTMLClipboardFormat = 0; static UINT BookmarkClipboardFormat = 0; static UINT WebSmartPasteFormat = 0; static LRESULT CALLBACK PasteboardOwnerWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT lresult = 0; switch (message) { case WM_RENDERFORMAT: // This message comes when SetClipboardData was sent a null data handle // and now it's come time to put the data on the clipboard. break; case WM_RENDERALLFORMATS: // This message comes when SetClipboardData was sent a null data handle // and now this application is about to quit, so it must put data on // the clipboard before it exits. break; case WM_DESTROY: break; #if !OS(WINCE) case WM_DRAWCLIPBOARD: break; case WM_CHANGECBCHAIN: break; #endif default: lresult = DefWindowProc(hWnd, message, wParam, lParam); break; } return lresult; } Pasteboard* Pasteboard::generalPasteboard() { static Pasteboard* pasteboard = new Pasteboard; return pasteboard; } Pasteboard::Pasteboard() { WNDCLASS wc; memset(&wc, 0, sizeof(WNDCLASS)); wc.lpfnWndProc = PasteboardOwnerWndProc; wc.hInstance = WebCore::instanceHandle(); wc.lpszClassName = L"PasteboardOwnerWindowClass"; RegisterClass(&wc); m_owner = ::CreateWindow(L"PasteboardOwnerWindowClass", L"PasteboardOwnerWindow", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0); HTMLClipboardFormat = ::RegisterClipboardFormat(L"HTML Format"); BookmarkClipboardFormat = ::RegisterClipboardFormat(L"UniformResourceLocatorW"); WebSmartPasteFormat = ::RegisterClipboardFormat(L"WebKit Smart Paste Format"); } void Pasteboard::clear() { if (::OpenClipboard(m_owner)) { ::EmptyClipboard(); ::CloseClipboard(); } } void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame) { clear(); // Put CF_HTML format on the pasteboard if (::OpenClipboard(m_owner)) { ExceptionCode ec = 0; Vector<char> data; markupToCFHTML(createMarkup(selectedRange, 0, AnnotateForInterchange), selectedRange->startContainer(ec)->document()->url().string(), data); HGLOBAL cbData = createGlobalData(data); if (!::SetClipboardData(HTMLClipboardFormat, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // Put plain string on the pasteboard. CF_UNICODETEXT covers CF_TEXT as well String str = frame->editor()->selectedText(); replaceNewlinesWithWindowsStyleNewlines(str); replaceNBSPWithSpace(str); if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(str); if (!::SetClipboardData(CF_UNICODETEXT, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // enable smart-replacing later on by putting dummy data on the pasteboard if (canSmartCopyOrDelete) { if (::OpenClipboard(m_owner)) { ::SetClipboardData(WebSmartPasteFormat, 0); ::CloseClipboard(); } } } void Pasteboard::writePlainText(const String& text, SmartReplaceOption smartReplaceOption) { clear(); // Put plain string on the pasteboard. CF_UNICODETEXT covers CF_TEXT as well String str = text; replaceNewlinesWithWindowsStyleNewlines(str); if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(str); if (!::SetClipboardData(CF_UNICODETEXT, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // enable smart-replacing later on by putting dummy data on the pasteboard if (smartReplaceOption == CanSmartReplace) { if (::OpenClipboard(m_owner)) { ::SetClipboardData(WebSmartPasteFormat, 0); ::CloseClipboard(); } } } void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame) { ASSERT(!url.isEmpty()); clear(); String title(titleStr); if (title.isEmpty()) { title = url.lastPathComponent(); if (title.isEmpty()) title = url.host(); } // write to clipboard in format com.apple.safari.bookmarkdata to be able to paste into the bookmarks view with appropriate title if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(url, title); if (!::SetClipboardData(BookmarkClipboardFormat, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // write to clipboard in format CF_HTML to be able to paste into contenteditable areas as a link if (::OpenClipboard(m_owner)) { Vector<char> data; markupToCFHTML(urlToMarkup(url, title), "", data); HGLOBAL cbData = createGlobalData(data); if (!::SetClipboardData(HTMLClipboardFormat, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } // bare-bones CF_UNICODETEXT support if (::OpenClipboard(m_owner)) { HGLOBAL cbData = createGlobalData(url.string()); if (!::SetClipboardData(CF_UNICODETEXT, cbData)) ::GlobalFree(cbData); ::CloseClipboard(); } } void Pasteboard::writeImage(Node* node, const KURL&, const String&) { ASSERT(node); if (!(node->renderer() && node->renderer()->isImage())) return; RenderImage* renderer = toRenderImage(node->renderer()); CachedImage* cachedImage = renderer->cachedImage(); if (!cachedImage || cachedImage->errorOccurred()) return; Image* image = cachedImage->imageForRenderer(renderer); ASSERT(image); clear(); HWndDC dc(0); HDC compatibleDC = CreateCompatibleDC(0); HDC sourceDC = CreateCompatibleDC(0); OwnPtr<HBITMAP> resultBitmap = adoptPtr(CreateCompatibleBitmap(dc, image->width(), image->height())); HGDIOBJ oldBitmap = SelectObject(compatibleDC, resultBitmap.get()); BitmapInfo bmInfo = BitmapInfo::create(image->size()); HBITMAP coreBitmap = CreateDIBSection(dc, &bmInfo, DIB_RGB_COLORS, 0, 0, 0); HGDIOBJ oldSource = SelectObject(sourceDC, coreBitmap); image->getHBITMAP(coreBitmap); BitBlt(compatibleDC, 0, 0, image->width(), image->height(), sourceDC, 0, 0, SRCCOPY); SelectObject(sourceDC, oldSource); DeleteObject(coreBitmap); SelectObject(compatibleDC, oldBitmap); DeleteDC(sourceDC); DeleteDC(compatibleDC); if (::OpenClipboard(m_owner)) { ::SetClipboardData(CF_BITMAP, resultBitmap.leakPtr()); ::CloseClipboard(); } } void Pasteboard::writeClipboard(Clipboard*) { notImplemented(); } bool Pasteboard::canSmartReplace() { return ::IsClipboardFormatAvailable(WebSmartPasteFormat); } String Pasteboard::plainText(Frame* frame) { if (::IsClipboardFormatAvailable(CF_UNICODETEXT) && ::OpenClipboard(m_owner)) { HANDLE cbData = ::GetClipboardData(CF_UNICODETEXT); if (cbData) { UChar* buffer = static_cast<UChar*>(GlobalLock(cbData)); String fromClipboard(buffer); GlobalUnlock(cbData); ::CloseClipboard(); return fromClipboard; } ::CloseClipboard(); } if (::IsClipboardFormatAvailable(CF_TEXT) && ::OpenClipboard(m_owner)) { HANDLE cbData = ::GetClipboardData(CF_TEXT); if (cbData) { char* buffer = static_cast<char*>(GlobalLock(cbData)); String fromClipboard(buffer); GlobalUnlock(cbData); ::CloseClipboard(); return fromClipboard; } ::CloseClipboard(); } return String(); } PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText) { chosePlainText = false; if (::IsClipboardFormatAvailable(HTMLClipboardFormat) && ::OpenClipboard(m_owner)) { // get data off of clipboard HANDLE cbData = ::GetClipboardData(HTMLClipboardFormat); if (cbData) { SIZE_T dataSize = ::GlobalSize(cbData); String cfhtml(UTF8Encoding().decode(static_cast<char*>(GlobalLock(cbData)), dataSize)); GlobalUnlock(cbData); ::CloseClipboard(); PassRefPtr<DocumentFragment> fragment = fragmentFromCFHTML(frame->document(), cfhtml); if (fragment) return fragment; } else ::CloseClipboard(); } if (allowPlainText && ::IsClipboardFormatAvailable(CF_UNICODETEXT)) { chosePlainText = true; if (::OpenClipboard(m_owner)) { HANDLE cbData = ::GetClipboardData(CF_UNICODETEXT); if (cbData) { UChar* buffer = static_cast<UChar*>(GlobalLock(cbData)); String str(buffer); GlobalUnlock(cbData); ::CloseClipboard(); RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), str); if (fragment) return fragment.release(); } else ::CloseClipboard(); } } if (allowPlainText && ::IsClipboardFormatAvailable(CF_TEXT)) { chosePlainText = true; if (::OpenClipboard(m_owner)) { HANDLE cbData = ::GetClipboardData(CF_TEXT); if (cbData) { char* buffer = static_cast<char*>(GlobalLock(cbData)); String str(buffer); GlobalUnlock(cbData); ::CloseClipboard(); RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), str); if (fragment) return fragment.release(); } else ::CloseClipboard(); } } return 0; } } // namespace WebCore
{ "content_hash": "568ee239c8b7a88178f97a43b2dda2b0", "timestamp": "", "source": "github", "line_count": 331, "max_line_length": 141, "avg_line_length": 31.253776435045317, "alnum_prop": 0.6330594490091832, "repo_name": "yoavweiss/RespImg-WebCore", "id": "f9fe00de4f0c92cb203a13bd380159eb42f3cae9", "size": "11703", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "platform/win/PasteboardWin.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1301" }, { "name": "C", "bytes": "2369715" }, { "name": "C++", "bytes": "39064862" }, { "name": "JavaScript", "bytes": "3763760" }, { "name": "Objective-C", "bytes": "2038598" }, { "name": "Perl", "bytes": "768866" }, { "name": "Prolog", "bytes": "519" }, { "name": "Python", "bytes": "210630" }, { "name": "Ruby", "bytes": "1927" }, { "name": "Shell", "bytes": "8214" } ], "symlink_target": "" }
export JAVA_HOME=/usr/java/latest ant $1
{ "content_hash": "a2be257009e50114c46268d4d678da21", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 33, "avg_line_length": 14, "alnum_prop": 0.7380952380952381, "repo_name": "martin-nordberg/steamflake-legacy", "id": "1b0e107317e3790f3f3e3c32db41457ac55739e4", "size": "53", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SteamflakeBuild/build.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "13743" }, { "name": "Java", "bytes": "167794" }, { "name": "JavaScript", "bytes": "249072" }, { "name": "Shell", "bytes": "2729" }, { "name": "TypeScript", "bytes": "364285" } ], "symlink_target": "" }
/** * @module ol/renderer/canvas/VectorLayer */ import {getUid} from '../../util.js'; import ViewHint from '../../ViewHint.js'; import {listen, unlisten} from '../../events.js'; import EventType from '../../events/EventType.js'; import {buffer, createEmpty, containsExtent, getWidth} from '../../extent.js'; import {labelCache} from '../../render/canvas.js'; import CanvasBuilderGroup from '../../render/canvas/BuilderGroup.js'; import ExecutorGroup, {replayDeclutter} from '../../render/canvas/ExecutorGroup.js'; import CanvasLayerRenderer from './Layer.js'; import {defaultOrder as defaultRenderOrder, getTolerance as getRenderTolerance, getSquaredTolerance as getSquaredRenderTolerance, renderFeature} from '../vector.js'; import {toString as transformToString, makeScale, makeInverse} from '../../transform.js'; /** * @classdesc * Canvas renderer for vector layers. * @api */ class CanvasVectorLayerRenderer extends CanvasLayerRenderer { /** * @param {import("../../layer/Vector.js").default} vectorLayer Vector layer. */ constructor(vectorLayer) { super(vectorLayer); /** * @private * @type {boolean} */ this.dirty_ = false; /** * @private * @type {number} */ this.renderedRevision_ = -1; /** * @private * @type {number} */ this.renderedResolution_ = NaN; /** * @private * @type {import("../../extent.js").Extent} */ this.renderedExtent_ = createEmpty(); /** * @private * @type {function(import("../../Feature.js").default, import("../../Feature.js").default): number|null} */ this.renderedRenderOrder_ = null; /** * @private * @type {import("../../render/canvas/ExecutorGroup").default} */ this.replayGroup_ = null; /** * A new replay group had to be created by `prepareFrame()` * @type {boolean} */ this.replayGroupChanged = true; listen(labelCache, EventType.CLEAR, this.handleFontsChanged_, this); } /** * @inheritDoc */ disposeInternal() { unlisten(labelCache, EventType.CLEAR, this.handleFontsChanged_, this); super.disposeInternal(); } /** * @inheritDoc */ renderFrame(frameState, layerState) { const context = this.context; const canvas = context.canvas; const replayGroup = this.replayGroup_; if (!replayGroup || replayGroup.isEmpty()) { if (canvas.width > 0) { canvas.width = 0; } return canvas; } const pixelRatio = frameState.pixelRatio; // set forward and inverse pixel transforms makeScale(this.pixelTransform_, 1 / pixelRatio, 1 / pixelRatio); makeInverse(this.inversePixelTransform_, this.pixelTransform_); // resize and clear const width = Math.round(frameState.size[0] * pixelRatio); const height = Math.round(frameState.size[1] * pixelRatio); if (canvas.width != width || canvas.height != height) { canvas.width = width; canvas.height = height; const canvasTransform = transformToString(this.pixelTransform_); if (canvas.style.transform !== canvasTransform) { canvas.style.transform = canvasTransform; } } else { context.clearRect(0, 0, width, height); } this.preRender(context, frameState); const extent = frameState.extent; const viewState = frameState.viewState; const projection = viewState.projection; const rotation = viewState.rotation; const projectionExtent = projection.getExtent(); const vectorSource = this.getLayer().getSource(); // clipped rendering if layer extent is set const clipExtent = layerState.extent; const clipped = clipExtent !== undefined; if (clipped) { this.clip(context, frameState, clipExtent); } const viewHints = frameState.viewHints; const snapToPixel = !(viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]); const transform = this.getRenderTransform(frameState, width, height, 0); const skippedFeatureUids = layerState.managed ? frameState.skippedFeatureUids : {}; const declutterReplays = /** @type {import("../../layer/Vector.js").default} */ (this.getLayer()).getDeclutter() ? {} : null; replayGroup.execute(context, transform, rotation, skippedFeatureUids, snapToPixel, undefined, declutterReplays); if (vectorSource.getWrapX() && projection.canWrapX() && !containsExtent(projectionExtent, extent)) { let startX = extent[0]; const worldWidth = getWidth(projectionExtent); let world = 0; let offsetX; while (startX < projectionExtent[0]) { --world; offsetX = worldWidth * world; const transform = this.getRenderTransform(frameState, width, height, offsetX); replayGroup.execute(context, transform, rotation, skippedFeatureUids, snapToPixel, undefined, declutterReplays); startX += worldWidth; } world = 0; startX = extent[2]; while (startX > projectionExtent[2]) { ++world; offsetX = worldWidth * world; const transform = this.getRenderTransform(frameState, width, height, offsetX); replayGroup.execute(context, transform, rotation, skippedFeatureUids, snapToPixel, undefined, declutterReplays); startX -= worldWidth; } } if (declutterReplays) { const viewHints = frameState.viewHints; const hifi = !(viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]); replayDeclutter(declutterReplays, context, rotation, hifi, frameState.declutterItems); } if (clipped) { context.restore(); } this.postRender(context, frameState); const opacity = layerState.opacity; if (opacity !== parseFloat(canvas.style.opacity)) { canvas.style.opacity = opacity; } return canvas; } /** * @inheritDoc */ forEachFeatureAtCoordinate(coordinate, frameState, hitTolerance, callback, declutteredFeatures) { if (!this.replayGroup_) { return undefined; } else { const resolution = frameState.viewState.resolution; const rotation = frameState.viewState.rotation; const layer = /** @type {import("../../layer/Vector").default} */ (this.getLayer()); /** @type {!Object<string, boolean>} */ const features = {}; const result = this.replayGroup_.forEachFeatureAtCoordinate(coordinate, resolution, rotation, hitTolerance, {}, /** * @param {import("../../Feature.js").FeatureLike} feature Feature. * @return {?} Callback result. */ function(feature) { const key = getUid(feature); if (!(key in features)) { features[key] = true; return callback(feature, layer); } }, layer.getDeclutter() ? declutteredFeatures : null); return result; } } /** * @param {import("../../events/Event.js").default} event Event. */ handleFontsChanged_(event) { const layer = this.getLayer(); if (layer.getVisible() && this.replayGroup_) { layer.changed(); } } /** * Handle changes in image style state. * @param {import("../../events/Event.js").default} event Image style change event. * @private */ handleStyleImageChange_(event) { this.renderIfReadyAndVisible(); } /** * @inheritDoc */ prepareFrame(frameState, layerState) { const vectorLayer = /** @type {import("../../layer/Vector.js").default} */ (this.getLayer()); const vectorSource = vectorLayer.getSource(); const animating = frameState.viewHints[ViewHint.ANIMATING]; const interacting = frameState.viewHints[ViewHint.INTERACTING]; const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); if (!this.dirty_ && (!updateWhileAnimating && animating) || (!updateWhileInteracting && interacting)) { return true; } const frameStateExtent = frameState.extent; const viewState = frameState.viewState; const projection = viewState.projection; const resolution = viewState.resolution; const pixelRatio = frameState.pixelRatio; const vectorLayerRevision = vectorLayer.getRevision(); const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); let vectorLayerRenderOrder = vectorLayer.getRenderOrder(); if (vectorLayerRenderOrder === undefined) { vectorLayerRenderOrder = defaultRenderOrder; } const extent = buffer(frameStateExtent, vectorLayerRenderBuffer * resolution); const projectionExtent = viewState.projection.getExtent(); if (vectorSource.getWrapX() && viewState.projection.canWrapX() && !containsExtent(projectionExtent, frameState.extent)) { // For the replay group, we need an extent that intersects the real world // (-180° to +180°). To support geometries in a coordinate range from -540° // to +540°, we add at least 1 world width on each side of the projection // extent. If the viewport is wider than the world, we need to add half of // the viewport width to make sure we cover the whole viewport. const worldWidth = getWidth(projectionExtent); const gutter = Math.max(getWidth(extent) / 2, worldWidth); extent[0] = projectionExtent[0] - gutter; extent[2] = projectionExtent[2] + gutter; } if (!this.dirty_ && this.renderedResolution_ == resolution && this.renderedRevision_ == vectorLayerRevision && this.renderedRenderOrder_ == vectorLayerRenderOrder && containsExtent(this.renderedExtent_, extent)) { this.replayGroupChanged = false; return true; } if (this.replayGroup_) { this.replayGroup_.dispose(); } this.replayGroup_ = null; this.dirty_ = false; const replayGroup = new CanvasBuilderGroup( getRenderTolerance(resolution, pixelRatio), extent, resolution, pixelRatio, vectorLayer.getDeclutter()); vectorSource.loadFeatures(extent, resolution, projection); /** * @param {import("../../Feature.js").default} feature Feature. * @this {CanvasVectorLayerRenderer} */ const render = function(feature) { let styles; const styleFunction = feature.getStyleFunction() || vectorLayer.getStyleFunction(); if (styleFunction) { styles = styleFunction(feature, resolution); } if (styles) { const dirty = this.renderFeature( feature, resolution, pixelRatio, styles, replayGroup); this.dirty_ = this.dirty_ || dirty; } }.bind(this); if (vectorLayerRenderOrder) { /** @type {Array<import("../../Feature.js").default>} */ const features = []; vectorSource.forEachFeatureInExtent(extent, /** * @param {import("../../Feature.js").default} feature Feature. */ function(feature) { features.push(feature); }); features.sort(vectorLayerRenderOrder); for (let i = 0, ii = features.length; i < ii; ++i) { render(features[i]); } } else { vectorSource.forEachFeatureInExtent(extent, render); } const replayGroupInstructions = replayGroup.finish(); const executorGroup = new ExecutorGroup(extent, resolution, pixelRatio, vectorSource.getOverlaps(), replayGroupInstructions, vectorLayer.getRenderBuffer()); this.renderedResolution_ = resolution; this.renderedRevision_ = vectorLayerRevision; this.renderedRenderOrder_ = vectorLayerRenderOrder; this.renderedExtent_ = extent; this.replayGroup_ = executorGroup; this.replayGroupChanged = true; return true; } /** * @param {import("../../Feature.js").default} feature Feature. * @param {number} resolution Resolution. * @param {number} pixelRatio Pixel ratio. * @param {import("../../style/Style.js").default|Array<import("../../style/Style.js").default>} styles The style or array of styles. * @param {import("../../render/canvas/BuilderGroup.js").default} builderGroup Builder group. * @return {boolean} `true` if an image is loading. */ renderFeature(feature, resolution, pixelRatio, styles, builderGroup) { if (!styles) { return false; } let loading = false; if (Array.isArray(styles)) { for (let i = 0, ii = styles.length; i < ii; ++i) { loading = renderFeature( builderGroup, feature, styles[i], getSquaredRenderTolerance(resolution, pixelRatio), this.handleStyleImageChange_, this) || loading; } } else { loading = renderFeature( builderGroup, feature, styles, getSquaredRenderTolerance(resolution, pixelRatio), this.handleStyleImageChange_, this); } return loading; } } export default CanvasVectorLayerRenderer;
{ "content_hash": "08da898d4a634e3bcf89777e1f454d5f", "timestamp": "", "source": "github", "line_count": 381, "max_line_length": 165, "avg_line_length": 33.653543307086615, "alnum_prop": 0.6526282951177663, "repo_name": "cdnjs/cdnjs", "id": "26a9ff6e4b0897a0e733bebe67ff0c152fe6154b", "size": "12826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/openlayers/6.0.0-beta.8/src/renderer/canvas/VectorLayer.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.avantssar.aslan; import java.util.ArrayList; import java.util.List; import org.avantssar.commons.ErrorGatherer; import org.avantssar.commons.LocationInfo; public class InitialState extends TermsHolder { protected InitialState(LocationInfo location, ErrorGatherer err, String name) { super(location, err, name); } public InitialState addFact(ITerm term) { if (!term.getType().equals(IASLanSpec.FACT)) { getErrorGatherer().addException(term.getLocation(), ASLanErrorMessages.CONSTRUCT_EXPECTS_ONLY_FACTS, "Initial state", term.getRepresentation(), term.getType()); } super.addOneTerm(term); return this; } public List<ITerm> getFacts() { List<ITerm> facts = new ArrayList<ITerm>(); for (ITerm t : getTerms()) { facts.add(t); } return facts; } public void accept(IASLanVisitor visitor) { visitor.visit(this); } }
{ "content_hash": "5bdb2cb35c909ae81e04db4b4f1009d5", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 163, "avg_line_length": 25.38235294117647, "alnum_prop": 0.7381228273464658, "repo_name": "siemens/ASLanPPConnector", "id": "142ea5743f6df117338e0fec9fb5d34135a0f8b8", "size": "1497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/aslan-core/src/main/java/org/avantssar/aslan/InitialState.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "73255" }, { "name": "HTML", "bytes": "55778" }, { "name": "Java", "bytes": "1628076" }, { "name": "Ruby", "bytes": "462" }, { "name": "Shell", "bytes": "25815" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66-internal) on Tue Dec 08 09:28:00 GMT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.apache.jena.atlas.json.io.parserjavacc.javacc (Apache Jena ARQ)</title> <meta name="date" content="2015-12-08"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../../../org/apache/jena/atlas/json/io/parserjavacc/javacc/package-summary.html" target="classFrame">org.apache.jena.atlas.json.io.parserjavacc.javacc</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="JSON_ParserConstants.html" title="interface in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame"><span class="interfaceName">JSON_ParserConstants</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="JavaCharStream.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">JavaCharStream</a></li> <li><a href="JSON_Parser.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">JSON_Parser</a></li> <li><a href="JSON_ParserBase.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">JSON_ParserBase</a></li> <li><a href="JSON_ParserTokenManager.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">JSON_ParserTokenManager</a></li> <li><a href="Token.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">Token</a></li> </ul> <h2 title="Exceptions">Exceptions</h2> <ul title="Exceptions"> <li><a href="ParseException.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">ParseException</a></li> </ul> <h2 title="Errors">Errors</h2> <ul title="Errors"> <li><a href="TokenMgrError.html" title="class in org.apache.jena.atlas.json.io.parserjavacc.javacc" target="classFrame">TokenMgrError</a></li> </ul> </div> </body> </html>
{ "content_hash": "ad2fc9601fd106b01e3b81167c0f0f0e", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 199, "avg_line_length": 62.83783783783784, "alnum_prop": 0.712258064516129, "repo_name": "Jelkya/amber-sparql", "id": "b6af1a23a6d5cc6dbe4baa2b4c8d660024b330cd", "size": "2325", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/apache-jena-3.0.1/javadoc-arq/org/apache/jena/atlas/json/io/parserjavacc/javacc/package-frame.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "171714" }, { "name": "Shell", "bytes": "902" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Class: TTYCoke::Config::Configuration &mdash; Active Paypal Adaptive Payment Documentation </title> <link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" /> <script type="text/javascript" charset="utf-8"> relpath = '../..'; if (relpath != '') relpath += '/'; </script> <script type="text/javascript" charset="utf-8" src="../../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../../js/app.js"></script> </head> <body> <script type="text/javascript" charset="utf-8"> if (window.top.frames.main) document.body.className = 'frames'; </script> <div id="header"> <div id="menu"> <a href="../../_index.html">Index (C)</a> &raquo; <span class='title'><span class='object_link'><a href="../../TTYCoke.html" title="TTYCoke (module)">TTYCoke</a></span></span> &raquo; <span class='title'><span class='object_link'><a href="../Config.html" title="TTYCoke::Config (module)">Config</a></span></span> &raquo; <span class="title">Configuration</span> <div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div> </div> <div id="search"> <a id="class_list_link" href="#">Class List</a> <a id="method_list_link" href="#">Method List</a> <a id="file_list_link" href="#">File List</a> </div> <div class="clear"></div> </div> <iframe id="search_frame"></iframe> <div id="content"><h1>Class: TTYCoke::Config::Configuration </h1> <dl class="box"> <dt class="r1">Inherits:</dt> <dd class="r1"> <span class="inheritName">Object</span> <ul class="fullTree"> <li>Object</li> <li class="next">TTYCoke::Config::Configuration</li> </ul> <a href="#" class="inheritanceTree">show all</a> </dd> <dt class="r2 last">Defined in:</dt> <dd class="r2 last">lib/ttycoke.rb</dd> </dl> <div class="clear"></div> <h2>Constant Summary</h2> <dl class="constants"> <dt id="files-classvariable" class="">@@files = </dt> <dd><pre class="code"><span class='lbrace'>{</span> <span class='label'>home:</span> <span class='const'>ENV</span><span class='lbracket'>[</span><span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>HOME</span><span class='tstring_end'>'</span></span><span class='rbracket'>]</span> <span class='op'>+</span> <span class='tstring'><span class='tstring_beg'>&quot;</span><span class='tstring_content'>/.ttycoke.yaml</span><span class='tstring_end'>&quot;</span></span><span class='comma'>,</span> <span class='label'>tty_coke:</span> <span class='const'>File</span><span class='period'>.</span><span class='id identifier rubyid_dirname'>dirname</span><span class='lparen'>(</span><span class='kw'>__FILE__</span><span class='rparen'>)</span> <span class='op'>+</span> <span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>/../config/config.yaml</span><span class='tstring_end'>'</span></span> <span class='rbrace'>}</span></pre></dd> </dl> <h2> Class Method Summary <small>(<a href="#" class="summary_toggle">collapse</a>)</small> </h2> <ul class="summary"> <li class="public "> <span class="summary_signature"> <a href="#file-class_method" title="file (class method)">+ (Object) <strong>file</strong>(file = nil) </a> </span> <span class="summary_desc"><div class='inline'></div></span> </li> </ul> <div id="class_method_details" class="method_details_list"> <h2>Class Method Details</h2> <div class="method_details first"> <p class="signature first" id="file-class_method"> + (<tt>Object</tt>) <strong>file</strong>(file = nil) </p><table class="source_code"> <tr> <td> <pre class="lines"> 33 34 35 36 37 38 39 40 41 42 43 44</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/ttycoke.rb', line 33</span> <span class='kw'>def</span> <span class='kw'>self</span><span class='period'>.</span><span class='id identifier rubyid_file'>file</span> <span class='id identifier rubyid_file'>file</span><span class='op'>=</span><span class='kw'>nil</span> <span class='kw'>begin</span> <span class='kw'>return</span> <span class='id identifier rubyid_file'>file</span> <span class='kw'>if</span> <span class='id identifier rubyid_file'>file</span> <span class='kw'>if</span> <span class='const'>FileTest</span><span class='period'>.</span><span class='id identifier rubyid_exist?'>exist?</span><span class='lparen'>(</span><span class='cvar'>@@files</span><span class='period'>.</span><span class='id identifier rubyid_fetch'>fetch</span><span class='lparen'>(</span><span class='symbol'>:home</span><span class='rparen'>)</span><span class='rparen'>)</span> <span class='cvar'>@@files</span><span class='period'>.</span><span class='id identifier rubyid_fetch'>fetch</span><span class='lparen'>(</span><span class='symbol'>:home</span><span class='rparen'>)</span> <span class='kw'>else</span> <span class='cvar'>@@files</span><span class='period'>.</span><span class='id identifier rubyid_fetch'>fetch</span><span class='lparen'>(</span><span class='symbol'>:tty_coke</span><span class='rparen'>)</span> <span class='kw'>end</span> <span class='kw'>rescue</span> <span class='const'>IndexError</span> <span class='op'>=&gt;</span> <span class='id identifier rubyid_e'>e</span> <span class='id identifier rubyid_log_error'>log_error</span><span class='lparen'>(</span><span class='kw'>self</span><span class='comma'>,</span> <span class='id identifier rubyid___method__'>__method__</span><span class='comma'>,</span> <span class='id identifier rubyid_caller'>caller</span><span class='comma'>,</span> <span class='id identifier rubyid_e'>e</span><span class='rparen'>)</span> <span class='kw'>end</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated on Tue Jan 24 03:45:04 2012 by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a> 0.7.4 (ruby-1.9.3). </div> </body> </html>
{ "content_hash": "a41787bb4c128a0fcc911c29cb639613", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 478, "avg_line_length": 32.79047619047619, "alnum_prop": 0.6076096427534127, "repo_name": "jpablobr/ttycoke", "id": "14967021f3058b9e9d87016f57e7ec4b3a5ca00a", "size": "6886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/TTYCoke/Config/Configuration.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "11472" }, { "name": "Ruby", "bytes": "22749" } ], "symlink_target": "" }
namespace ME3D { class Material { public: struct Property { String name; E_Uniform type; int value_int; float value_float; Vector2 value_vec2; Vector3 value_vec3; Vector4 value_vec4; Texture* value_texture; }; public: Material( String name ); virtual ~Material() {} // getters String GetName() const { return _name; } Shader* GetShader() const { return _shader; } bool IsWireframe() const { return _wireframe; } float GetLineWidth() const { return _lineWidth; } E_FaceCulling GetFaceCulling() const { return _cullFace; } // setters void SetName( String name ) { _name = name; } void SetShader( Shader* shader ) { _shader = shader; } void SetWireframe( bool value ) { _wireframe = value; } void SetLineWidth( float value ) { _lineWidth = value; } void SetFaceCulling( E_FaceCulling value ) { _cullFace = value; } // getters uint GetPropertiesCount() const { return _properties.size(); } Property GetPropertyAt( uint index ) const { return _properties[index]; } // setters void SetProperty( String name, int value ); void SetProperty( String name, float value ); void SetProperty( String name, Vector2& value ); void SetProperty( String name, Vector3& value ); void SetProperty( String name, Vector4& value ); void SetProperty( String name, Texture* value ); protected: String _name; Shader* _shader; bool _wireframe; float _lineWidth; E_FaceCulling _cullFace; std::vector<Property> _properties; // scripting public: const char* S_GetName() const; Shader* S_GetShader() const; bool S_IsWireframe() const; float S_GetLineWidth() const; const char* S_GetFaceCulling() const; void S_SetName( const char* name ); void S_SetShader( Shader* shader ); void S_SetWireframe( bool value ); void S_SetLineWidth( float value ); void S_SetFaceCulling( const char* value ); void S_SetPropertyInt( const char* name, int value ); void S_SetPropertyFloat( const char* name, float value ); void S_SetPropertyVec2( const char* name, Vector2& value ); void S_SetPropertyVec3( const char* name, Vector3& value ); void S_SetPropertyVec4( const char* name, Vector4& value ); void S_SetPropertyTex( const char* name, Texture* value ); }; }
{ "content_hash": "e6cdbd67f69d4dd9c6dad128dc4dce12", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 75, "avg_line_length": 26.976190476190474, "alnum_prop": 0.6853486319505737, "repo_name": "MorcoFreeCode/2015__MorcoEngine3D", "id": "1ffd7c963c8576d1dea9b3afbff6ff7957323645", "size": "2470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MorcoEngine3D v0.13/Source/Engine/Data/Fragments/Material.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3307448" }, { "name": "C++", "bytes": "6500495" }, { "name": "CMake", "bytes": "2834" }, { "name": "CSS", "bytes": "3477" }, { "name": "GLSL", "bytes": "77043" }, { "name": "Lua", "bytes": "25172" }, { "name": "Objective-C", "bytes": "26" } ], "symlink_target": "" }
package engine import ( "container/list" "fmt" "github.com/recruit-tech/walter/config" "github.com/recruit-tech/walter/log" "github.com/recruit-tech/walter/pipelines" "github.com/recruit-tech/walter/stages" ) type Engine struct { Pipeline *pipelines.Pipeline Opts *config.Opts MonitorCh *chan stages.Mediator } func (e *Engine) RunOnce() stages.Mediator { p := e.Pipeline var mediator stages.Mediator log.Info("geting starting to run pipeline process...") for stageItem := p.Stages.Front(); stageItem != nil; stageItem = stageItem.Next() { log.Debugf("Executing planned stage: %s\n", stageItem.Value) mediator = e.Execute(stageItem.Value.(stages.Stage), mediator) } log.Info("finished to run pipeline process...") return mediator } func (e *Engine) receiveInputs(inputCh *chan stages.Mediator) []stages.Mediator { mediatorsReceived := make([]stages.Mediator, 0) for { m, ok := <-*inputCh if !ok { break } log.Debugf("received input: %+v", m) mediatorsReceived = append(mediatorsReceived, m) } return mediatorsReceived } func (e *Engine) ExecuteStage(stage stages.Stage) { log.Debug("receiveing input") mediatorsReceived := e.receiveInputs(stage.GetInputCh()) log.Debugf("received input size: %v", len(mediatorsReceived)) log.Debugf("mediator received: %+v", mediatorsReceived) log.Debugf("execute as parent: %+v", stage) log.Debugf("execute as parent name %+v", stage.GetStageName()) var result bool if !e.isUpstreamAnyFailure(mediatorsReceived) || e.Opts.StopOnAnyFailure { result = stage.(stages.Runner).Run() } else { log.Warnf("execution is skipped: %v", stage.GetStageName()) result = false } log.Debugf("stage executution results: %+v, %+v", stage.GetStageName(), result) e.Pipeline.Report(fmt.Sprintf("stage executution results: %+v, %+v", stage.GetStageName(), result)) mediator := stages.Mediator{States: make(map[string]string)} mediator.States[stage.GetStageName()] = fmt.Sprintf("%v", result) if childStages := stage.GetChildStages(); childStages.Len() > 0 { log.Debugf("execute childstage: %v", childStages) e.executeAllChildStages(&childStages, mediator) e.waitAllChildStages(&childStages, &stage) } log.Debugf("sending output of stage: %+v %v", stage.GetStageName(), mediator) *stage.GetOutputCh() <- mediator log.Debugf("closing output of stage: %+v", stage.GetStageName()) close(*stage.GetOutputCh()) for _, m := range mediatorsReceived { *e.MonitorCh <- m } *e.MonitorCh <- mediator e.finalizeMonitorChAfterExecute(mediatorsReceived) } func (e *Engine) isUpstreamAnyFailure(mediators []stages.Mediator) bool { for _, m := range mediators { for _, v := range m.States { if v == "false" { return true } } } return false } func (e *Engine) executeAllChildStages(childStages *list.List, mediator stages.Mediator) { for childStage := childStages.Front(); childStage != nil; childStage = childStage.Next() { log.Debugf("child name %+v\n", childStage.Value.(stages.Stage).GetStageName()) childInputCh := *childStage.Value.(stages.Stage).GetInputCh() go func(stage stages.Stage) { e.ExecuteStage(stage) }(childStage.Value.(stages.Stage)) log.Debugf("input child: %+v", mediator) childInputCh <- mediator log.Debugf("closing input: %+v", childStage.Value.(stages.Stage).GetStageName()) close(childInputCh) } } func (e *Engine) waitAllChildStages(childStages *list.List, stage *stages.Stage) { for childStage := childStages.Front(); childStage != nil; childStage = childStage.Next() { s := childStage.Value.(stages.Stage) for { log.Debugf("receiving child: %v", s.GetStageName()) childReceived, ok := <-*s.GetOutputCh() if !ok { log.Debug("closing child output") break } log.Debugf("sending child: %v", childReceived) *(*stage).GetOutputCh() <- childReceived log.Debugf("send child: %v", childReceived) } log.Debugf("finished executing child: %v", s.GetStageName()) } } func (e *Engine) finalizeMonitorChAfterExecute(mediators []stages.Mediator) { if mediators[0].Type == "start" { log.Debug("finalize monitor channel..") mediatorEnd := stages.Mediator{States: make(map[string]string), Type: "end"} *e.MonitorCh <- mediatorEnd } else { log.Debugf("skipped finalizing") } } func (e *Engine) setChildStatus(stage *stages.Stage, mediator *stages.Mediator, status string) { if childStages := (*stage).GetChildStages(); childStages.Len() > 0 { for childStage := childStages.Front(); childStage != nil; childStage = childStage.Next() { name := childStage.Value.(stages.Stage).GetStageName() mediator.States[name] = fmt.Sprintf("%v", status) } } } func (e *Engine) Execute(stage stages.Stage, mediator stages.Mediator) stages.Mediator { monitorCh := e.MonitorCh mediator.Type = "start" name := stage.GetStageName() log.Debugf("----- Execute %v start ------\n", name) go func(mediator stages.Mediator) { *stage.GetInputCh() <- mediator close(*stage.GetInputCh()) }(mediator) go e.ExecuteStage(stage) for { receive, ok := <-*stage.GetOutputCh() if !ok { log.Debugf("outputCh closed") break } log.Debugf("outputCh received %+v\n", receive) } receives := make([]stages.Mediator, 0) for { receive := <-*monitorCh receives = append(receives, receive) if receive.Type == "end" { log.Debugf("monitorCh closed") log.Debugf("monitorCh last received: %+v\n", receive) log.Debugf("----- Execute %v done ------\n\n", name) return e.bindReceives(&receives) } log.Debugf("monitorCh received %+v\n", receive) } } func (e *Engine) bindReceives(rs *[]stages.Mediator) stages.Mediator { ret := &stages.Mediator{States: make(map[string]string)} for _, r := range *rs { for k, v := range r.States { ret.States[k] = v } } return *ret }
{ "content_hash": "3d18e6e500111531b31ce0457888c8a5", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 100, "avg_line_length": 29.692307692307693, "alnum_prop": 0.6925734024179621, "repo_name": "ainoya/walter", "id": "4d175dcaee9f3ace3ab0df5056277135a76f8182", "size": "6484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/engine.go", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/*-------------------------------------------------------------------- This source distribution is placed in the public domain by its author, Jason Papadopoulos. You may use it for any purpose, free of charge, without having to notify anyone. I disclaim any responsibility for any errors. Optionally, please be nice and tell me if you find this source to be useful. Again optionally, if you add to the functionality present here please consider making those additions public too, so that others may benefit from your work. $Id: poly.h 897 2013-06-22 13:16:18Z jasonp_sf $ --------------------------------------------------------------------*/ #ifndef _GNFS_POLY_POLY_H_ #define _GNFS_POLY_POLY_H_ #include <common.h> #include <dd.h> #include <ddcomplex.h> #include <integrate.h> #include <polyroot.h> #include "gnfs.h" #ifdef __cplusplus extern "C" { #endif #if MAX_POLY_DEGREE < 6 #error "Polynomial generation assumes degree <= 6 allowed" #endif /* parameters */ typedef struct { double digits; double stage1_norm; double stage2_norm; double final_norm; uint32 deadline; } poly_param_t; /* used if polynomials will ever be generated in parallel */ #define POLY_HEAP_SIZE 1 /* when analyzing a polynomial's root properties, the bound on factor base primes that are checked */ #define PRIME_BOUND 2000 typedef struct { mpz_poly_t rpoly; mpz_poly_t apoly; double size_score; double root_score; double combined_score; double skewness; uint32 num_real_roots; } poly_select_t; /* main structure for poly selection */ typedef struct { poly_select_t *heap[POLY_HEAP_SIZE]; uint32 heap_num_filled; integrate_t integ_aux; dickman_t dickman_aux; } poly_config_t; void poly_config_init(poly_config_t *config); void poly_config_free(poly_config_t *config); #define SIZE_EPS 1e-6 /* main routines */ void get_poly_params(msieve_obj *obj, mpz_t n, uint32 *degree_out, poly_param_t *params_out); void find_poly_core(msieve_obj *obj, mpz_t n, poly_param_t *params, poly_config_t *config, uint32 degree); typedef struct { uint32 degree; double coeff[MAX_POLY_DEGREE + 1]; } dpoly_t; typedef struct { uint32 degree; dd_t coeff[MAX_POLY_DEGREE + 1]; } ddpoly_t; uint32 analyze_poly_size(integrate_t *integ_aux, ddpoly_t *rpoly, ddpoly_t *apoly, double *result); uint32 analyze_poly_murphy(integrate_t *integ_aux, dickman_t *dickman_aux, ddpoly_t *rpoly, double root_score_r, ddpoly_t *apoly, double root_score_a, double skewness, double *result, uint32 *num_real_roots); uint32 analyze_poly_roots(mpz_poly_t *poly, uint32 prime_bound, double *result); uint32 analyze_poly_roots_projective(mpz_poly_t *poly, uint32 prime_bound, double *result); void get_poly_combined_score(poly_select_t *poly); void analyze_poly(poly_config_t *config, poly_select_t *poly); void save_poly(poly_config_t *config, poly_select_t *poly); #ifdef __cplusplus } #endif #endif /* _GNFS_POLY_POLY_H_ */
{ "content_hash": "9a7b2c118b3061a45b42da0e590f79e7", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 74, "avg_line_length": 24.278688524590162, "alnum_prop": 0.6887238352464551, "repo_name": "sganis/rsa", "id": "a4a593326a5a656559d6103450b407dce86ff837", "size": "2962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "msieve-1.52/gnfs/poly/poly.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "925787" }, { "name": "C", "bytes": "13641695" }, { "name": "C++", "bytes": "447521" }, { "name": "Cuda", "bytes": "352529" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "Groff", "bytes": "5" }, { "name": "HTML", "bytes": "239" }, { "name": "Makefile", "bytes": "762715" }, { "name": "Objective-C", "bytes": "31422" }, { "name": "Perl", "bytes": "3591085" }, { "name": "Perl6", "bytes": "27602" }, { "name": "Prolog", "bytes": "29177" }, { "name": "Protocol Buffer", "bytes": "2764" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "180347" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
<?php /** * @see Microsoft_AutoLoader */ require_once dirname(__FILE__) . '/../../AutoLoader.php'; /** * Sample command. * * @command-handler sample * @command-handler-description Sample command. * @command-handler-header Windows Azure SDK for PHP * @command-handler-header (C) RealDolmen 2011 - www.realdolmen.com */ class Sample extends Microsoft_Console_Command { /** * Hello command * * @command-name hello * @command-description Prints Hello, World! * @command-parameter-for $name Microsoft_Console_Command_ParameterSource_Argv|Microsoft_Console_Command_ParameterSource_Env|Microsoft_Console_Command_ParameterSource_StdIn --name|-n Required. Name to say hello to. * @command-parameter-for $bePolite Microsoft_Console_Command_ParameterSource_Argv -p Optional. Switch to enable polite mode or not. * @command-example Print "Hello, Maarten! How are you?" (using polite mode): * @command-example hello -n="Maarten" -p * * @param string $name */ public function helloCommand($name, $bePolite = false) { echo 'Hello, ' . $name . '.'; if ($bePolite) { echo ' How are you?'; } echo "\r\n"; } /** * What time is it command * * @command-name timestamp * @command-description Prints the current timestamp. * * @param string $name */ public function timestampCommand() { echo date(); echo "\r\n"; } } Microsoft_Console_Command::bootstrap($_SERVER['argv']);
{ "content_hash": "eb19153404c0238e50fd1a4b6f88a64b", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 215, "avg_line_length": 26.462962962962962, "alnum_prop": 0.6836948915325403, "repo_name": "chgeuer/PHP_SharedAccessSignature_WindowsAzure", "id": "7452f9142e1b3e7bd4e5e2c58fed55474234def8", "size": "1429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure_sdk/library/Microsoft/WindowsAzure/CommandLine/sample.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "1384" } ], "symlink_target": "" }
<html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/console-test.js"></script> <script src="resources/stack-with-sourceUrl.js"></script> <script src="resources/stack-with-sourceMap.js"></script> <script> function forStack() { console.log(new Error("line\nbreak").stack); } forStack(); function stack1(errorConstructor, text) { function stack2() { console.log(new errorConstructor(text).stack); } stack2(); } function domError() { try { document.body.removeChild(document.createElement("a")); } catch (e) { console.log(e.stack); } } domError(); function logError() { try { throw new Error("some error"); } catch (e) { console.log(e); } } logError(); console.log("Error message without stacks http://www.chromium.org/"); console.log("Error valid stack #2\n at http://www.chromium.org/boo.js:40:70\n at foo(http://www.chromium.org/foo.js:10:50)"); console.log("Error valid stack #3\n at http://www.chromium.org/foo.js:40"); console.log("Error: MyError\n at throwError (http://www.chromium.org/foo.js:40)\n at eval (eval at <anonymous> (http://www.chromium.org/foo.js:42:1), <anonymous>:1:1)\n at http://www.chromium.org/foo.js:239"); stack1(ReferenceError, "valid stack"); stack1(EvalError, "valid stack"); stack1(SyntaxError, "valid stack"); stack1(RangeError, "valid stack"); stack1(TypeError, "valid stack"); stack1(URIError, "valid stack"); console.log("Error broken stack\n at function_name(foob.js foob.js:30:1)\n at foob.js:40:70"); console.log("Error broken stack #2\n at function_name(foob.js:20:30"); console.log("Error broken stack #3\n at function_name(foob:20.js:30 bla"); console.log("Error broken stack #4\n at function_name)foob.js:20:30("); console.log("Error broken stack #5\n at function_name foob.js:20:30)"); console.log("Error broken stack #6\n at foob.js foob.js:40:70"); //# sourceURL=console-log-linkify-stack-in-errors.html </script> <script> function test() { InspectorTest.evaluateInPageWithTimeout("failure()"); InspectorTest.waitUntilMessageReceived(waitForUISourceCode); function waitForUISourceCode() { InspectorTest.waitForUISourceCode(dumpMessages, "stack-with-sourceMap.coffee"); } function dumpMessages() { InspectorTest.dumpConsoleMessages(false, true); InspectorTest.completeTest(); } } </script> </head> <body onload="runTest()"> <p> Test that console.log(new Error().stack) would linkify links in stacks for sourceUrls and sourceMaps <a href="http://crbug.com/424001">Bug 424001.</a> </p> </body> </html>
{ "content_hash": "1c4710b659dedcc4bda9852acfd7102d", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 218, "avg_line_length": 29.096774193548388, "alnum_prop": 0.6773835920177383, "repo_name": "google-ar/WebARonARCore", "id": "6e1f4dad2e5f324f7585097e65dda12abda665ef", "size": "2706", "binary": false, "copies": "2", "ref": "refs/heads/webarcore_57.0.2987.5", "path": "third_party/WebKit/LayoutTests/inspector/console/console-log-linkify-stack-in-errors.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
VFDCVTA ;DSS/WLC - Quick Docs for VFDC VISIT APIs ;06/07/2006 13:26 ;;2011.1.2;DSS,INC VXVISTA OPEN SOURCE;;11 Jun 2013;Build 164 ;Copyright 1995-2013,Document Storage Systems Inc. All Rights Reserved ; ;DBIA# Supported Reference ;----- -------------------------------- ;10104 $$CJ^XLFSTR N I,X,Y,Z S Z="",$P(Z,"-",80)="" F I=1:1 S X=$T(T+I) Q:X="" S X=$P($T(T+I),";",3,99) D .I X'?1"VFDCVT".E W !," "_X Q .W !,Z,!,$$CJ^XLFSTR("Routine "_X,80),!,Z .Q Q T ; ;;VFDCVT3: ;; ;; VS(RETX,DFN,BEG,END,ZLOC,CAT,SCR) ;; This get VISITs only ;; Child visits are excluded: I $P(^AUPNVSIT(ien,0),U,12) ;; ;; RETX = $name of global root that stores data [^TMP("VFDC",$J,"VSIT")] ;; DFN = required - pointer to file 2 ;; BEG = optional - Fileman beginning date/time - default 2500101 ;; END = optional - Fileman ending date/time - default DT+.25 ;; ZLOC = optional - used to screen selected locations ;; passed by reference where ZLOC(ien)="" ;; ien is pointer to file 44 ;; kept for backward compAtibility, use SCR instead ;; CAT = optional - default 0 - if 1 then return historical visits ;; SCR - optional - added 7/3/2002 - sgm ;; passed by reference ;; format: SCR(sub) = code ^ value where ;; code = C for hospital location #44 ;; D for medical center division #40.8 ;; S for 3-digit stop code from file 40.7 (not ien) ;; value = for codes C,D - any unique lookup value or ien ;; for code S - 3-digit stop code (not ien to 40.7) ;; ;; return @RETX@(#) = V ^ ptr to 9000010 ^ ext date.time ^ ext loc ^ ;; int date.time ^ int loc ;; if errors, then return -1^error message ;; ;; Documentation Notes ;; =================== ;; SELECTED^VSIT returns ^TMP("VSIT",$J,visitien,#) = p1^p2^p3^p4^p5^p6 ;; p1 = visit date.time ;; p2 = file 44 ien ; ext loc name or ;; if serv cat = "H" then file 9999999.06 ien ; ext name ;; p3 = service category - internal .07 field value ;; p4 = service connected - external 80001 field value ;; p5 = patient status in/out - field 15002 set of codes ;; p6 = clinic stop ien (#40.7) ; external name ;; ;; v1.01 - screen out child visits ;; ;; ACT(A,B) : return ien^name^3-digit stop code;ien^name^3-digit stop... ;; ; for active stop codes only. Return <null> if none found. ;; ; A = ien to file 40.7, B = 3-digit stop code ;; ; ;; ;; SCR(INP,RET) ;; Convert screen entries to array of IENs. Called as extrinsic function. ;; ;; INP(#) = code ^ value where ;; code = C [hospital location file #44] ;; D [medical center division file #40.8] ;; S [clinic stop code file #40.7] ;; value = .01 name value ;; ;; RETURNS: RET passed by reference ;; Sets RET(...) array as follows ;; RET(code,ien) = value where ;; code = C,D,S, from above ;; ien = pointer to appropriate file ;; Note: RET is not killed so subsequent calls may append to it. ;; ;; GV( DFN, DATE) ;; get VISIT for a scheduled appointment ;; ;; DFN = Patient IEN to PATTIENT (#2) file. ;; DATE = Appointment Date ;; ;; RETURNS: VISIT (#900010) file pointer ;;
{ "content_hash": "a5455320c0e658cf63eae0545a835432", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 79, "avg_line_length": 43.10588235294118, "alnum_prop": 0.5166484716157205, "repo_name": "OSEHRA/vxVistA-M", "id": "6b87f567d078f72b735ef53b3e5e2fa8b8f07ce3", "size": "3664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Packages/DSS vxVistA Enhancement/Routines/VFDCVTA.m", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
//---------------------------------------------------------------------------- #pragma once #if !defined( _BINDEROO_CONTAINERS_H_ ) #define _BINDEROO_CONTAINERS_H_ #include "binderoo/defs.h" #include "binderoo/allocator.h" #include <string> #include <vector> #include <algorithm> namespace binderoo { template< AllocatorSpace eSpace > struct Containers { typedef std::basic_string< char, std::char_traits< char >, binderoo::Allocator< eSpace, char > > InternalString; typedef std::basic_string< wchar_t, std::char_traits< wchar_t >, binderoo::Allocator< eSpace, wchar_t > > InternalWString; typedef std::vector< InternalString, binderoo::Allocator< eSpace, InternalString > > StringVector; typedef std::vector< char, binderoo::Allocator< eSpace, char > > CharVector; }; //------------------------------------------------------------------------ } #endif // !defined( _BINDEROO_CONTAINERS_H_ ) //============================================================================
{ "content_hash": "dd8ebfba79fee427b4276a8d08fd1f07", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 124, "avg_line_length": 31.59375, "alnum_prop": 0.5450049455984174, "repo_name": "Remedy-Entertainment/binderoo", "id": "1556dceb38723084330c13b3b8bf2b4720d79e63", "size": "2517", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "binderoo_common/cpp/src/binderoo/containers.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "1436498" }, { "name": "D", "bytes": "237598" } ], "symlink_target": "" }
<?php class User_authentication_model extends CI_Model{ public function get_user_credentials($username,$password){ $this->db->select('*'); $this->db->where('username', $username); $this->db->where('password', $password); $this->db->where('status', 1); return $this->db->get('users')->row_object(); } }?>
{ "content_hash": "2b5ab8fa06941948df45652989464d39", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 62, "avg_line_length": 20.055555555555557, "alnum_prop": 0.5706371191135734, "repo_name": "rhonneljickaincordova/minsan", "id": "b19fd3780ec2a48d004df0d216248f40f42e02ea", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/User_authentication_model.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "584" }, { "name": "CSS", "bytes": "175858" }, { "name": "HTML", "bytes": "8413296" }, { "name": "JavaScript", "bytes": "120892" }, { "name": "PHP", "bytes": "1837481" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Page 68 | Comics | Kamigen | A Tropical Cyberpunk World </title> <base href="/"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet"><!-- Facebook Pixel Code --><script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1266796517023212'); fbq('track', 'PageView');</script><noscript> <img height="1" width="1" src="https://www.facebook.com/tr?id=1266796517023212&ev=PageView&noscript=1"/></noscript><!-- End Facebook Pixel Code --> <link href="/dist/website.css" rel="stylesheet"> </head> <body> <div class="ui grid stackable"> <div class="row"> <div class="column"> <div class="ui five column very relaxed grid center aligned" id="main_menu"> <div class="column"><a class="ui button inverted big fluid" href="/comics.html">Comics</a></div> <div class="column"><a class="ui button inverted big fluid" href="/game.html">Game</a></div> <div class="column logo"><a href="/"><img src="/art/design/Website%20Logo-01.png" title="Return to the Kamigen Homepage"></a></div> <div class="column"><a class="ui button inverted big fluid" href="/shop.html">Shop</a></div> <div class="column"><a class="ui button inverted big fluid" href="/wiki.html">Wiki</a></div> </div> <div class="ui fluid vertical menu inverted" id="mobile_menu"> <div class="item logo"><a href="/"><img src="/art/design/Website%20Logo-01.png" title="Return to the Kamigen Homepage"></a> <div id="mobile_menu_toggle"><i class="content icon"></i></div> </div> <div class="item"><a class="ui button inverted big fluid" href="/comics.html">Comics</a></div> <div class="item"><a class="ui button inverted big fluid" href="/game.html">Game</a></div> <div class="item"><a class="ui button inverted big fluid" href="/shop.html">Shop</a></div> <div class="item"><a class="ui button inverted big fluid" href="/wiki.html">Wiki</a></div> </div> </div> </div> <div class="ui dividing header"></div> <div class="row"> <div class="column center aligned"> <h2><a href="/comics.html">Comics</a> \ <a href="/comics/issue_3.html">Issue 03</a> \ Page 68</h2> </div> </div> <div class="row"> <div class="column"> <div class="ui one column center aligned page grid"> <div class="column eight wide"><a class="ui grey large labeled icon button" href="/comics/page_67.html"><i class="icon reply"></i>Previous</a></div> <div class="column eight wide"><a class="ui grey large right labeled icon button" href="/comics/page_69.html"><i class="icon share"></i>Next</a> </div> </div> </div> </div> <div class="row"> <div class="column"> <div class="ui one column stackable center aligned page grid"> <div class="column sixteen wide"></div><a href="/comics/page_69.html"><img class="ui image fluid" src="../art/comics/HD/Kamigen Page 68-01.png"></a> </div> </div> </div> <div class="row"> <div class="column"> <div class="ui one column center aligned page grid"> <div class="column eight wide"><a class="ui grey large labeled icon button" href="/comics/page_67.html"><i class="icon reply"></i>Previous</a></div> <div class="column eight wide"><a class="ui grey large right labeled icon button" href="/comics/page_69.html"><i class="icon share"></i>Next</a> </div> </div> </div> </div> <div class="row"> <div class="column center aligned"> <h2><a href="/comics.html">Comics</a> \ <a href="/comics/issue_3.html">Issue 03</a> \ Page 68</h2> </div> </div> <div class="row"> <div class="column"> <div class="ui one column center aligned page grid" id="page_script"> </div> </div> </div> <div class="row"> <div class="column"> <div class="ui one column stackable center aligned page grid"> <div class="column sixteen wide"> <div id="disqus_thread"></div> </div> </div> </div> </div> <div class="row footer"> <div class="column five wide"> <div class="ui horizontal list"> <div class="item"><a href="https://www.deviantart.com/thezeski/gallery/70776399/kamigen-comics" title="Kamigen Comics on DeviantArt"><img class="ui mini image" src="/assets/deviantart.png" alt="Deviantart"></a></div> <div class="item"><a href="https://www.facebook.com/kamigengame/" title="Kamigen Facebook Page"><img class="ui mini image" src="/assets/facebook.png" alt="Facebook"></a></div> </div> </div> <div class="column six wide"><a href="/"><img src="/art/design/Website%20Footer%20Logo-01.png" title="Kamigen"></a></div> <div class="column five wide"><a href="https://openstudios.xyz" title="An Open Studios Project"><img class="ui image small" src="/assets/open_studios_logo.png" style="margin: 0 auto"></a></div> </div> </div> <script id="landVertexShader" type="x-shader/x-vertex">uniform sampler2D bumpTexture; uniform float bumpScale; varying float vAmount; varying vec2 vUV; varying vec4 worldPosition; varying vec3 vViewPosition; varying vec3 vNormal; void main() { vUV = uv; vec4 bumpData = texture2D( bumpTexture, uv ); vAmount = bumpData.r; // assuming map is grayscale it doesn't matter if you use r, g, or b. // move the position along the normal vec3 newPosition = position + normal * bumpScale * vAmount; worldPosition = modelMatrix * vec4( newPosition, 1.0 ); // Normal position. vNormal = normalize( normalMatrix * normal ); // View vector. vViewPosition = cameraPosition - worldPosition.xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 ); } </script> <script id="landFragmentShader" type="x-shader/x-fragment">uniform float landSize; uniform float time; uniform sampler2D sandyTexture; uniform sampler2D forestTexture; uniform sampler2D rockyTexture; uniform sampler2D texture; uniform vec3 sunPosition; uniform vec3 center; varying vec2 vUV; varying float vAmount; varying vec4 worldPosition; varying vec3 vViewPosition; varying vec3 vNormal; // Shade island based on sun direction. float sunshadeIsland() { float radius = landSize / 4.; // Distance between this point and sun. float a = distance(worldPosition.xyz, sunPosition); // Distance between the center and sun. float b = distance(center, sunPosition); // Default shade float c = 0.0; // Sun max height float maxSun = 150000.; float brightness = (sunPosition.y / maxSun); if (sunPosition.y > 0.) { if (a < b) { brightness *= 0.5; } else { brightness *= 0.3; } } else { brightness *= 0.05; } return brightness; } float snoise ( vec3 coord, float scale, float time_factor ) { vec3 scaledCoord = coord * scale - (vNormal / time_factor + vec3(0.0, 0.0, -time / time_factor)); vec2 uvTimeShift = vec2((scaledCoord.x + scaledCoord.z) / 2.0, scaledCoord.y) + vec2( -0.7, 1.5 ) * time / time_factor * 0.015; vec4 noiseGeneratorTimeShift = texture2D( forestTexture, uvTimeShift ) * 50.; vec2 uvNoiseTimeShift = vec2(scaledCoord.x, scaledCoord.y) + 0.5 * vec2( noiseGeneratorTimeShift.r, noiseGeneratorTimeShift.b ); vec4 baseColor = texture2D( forestTexture, uvNoiseTimeShift * vec2(4.0, 4.0) ); return baseColor.b; } float heightMap( vec3 coord ) { float n = abs(snoise(coord , 1.0 , 18.0)); n -= 0.75 * abs(snoise(coord , 4.0 , 25.0)); n += 0.125 * abs(snoise(coord , 14.0 , 35.0)); n *= 0.7; return n; } // normal vec3 getNormalLightWeight() { const float e = .01; float n = heightMap(worldPosition.xyz); float nx = heightMap( worldPosition.xyz + vec3( e, 0.0, 0.0 ) ); float ny = heightMap( worldPosition.xyz + vec3( 0.0, e, 0.0 ) ); float nz = heightMap( worldPosition.xyz + vec3( 0.0, 0.0, e ) ); vec3 normal = normalize( vNormal + .5 * vec3( n - nx, n - ny, n - nz ) / e ); // diffuse light vec3 vLightWeighting = vec3( 0.005 ); vec4 lDirection = viewMatrix * vec4( normalize( vec3( 1.0, 0.0, 0.5 ) ), 0.0 ); float directionalLightWeighting = dot( normal, normalize( lDirection.xyz ) ) * 0.15 + 0.85; vLightWeighting += vec3( 1.0 ) * directionalLightWeighting; // specular light vec3 dirHalfVector = normalize( lDirection.xyz + normalize( vViewPosition ) ); float dirDotNormalHalf = dot( normal, dirHalfVector ); float dirSpecularWeight = 0.0; if ( dirDotNormalHalf >= 0.0 ) dirSpecularWeight = ( 1.0 - n ) * pow( dirDotNormalHalf, 5.0 ); vLightWeighting *= vec3( 1.0, 0.5, 0.0 ) * dirSpecularWeight * n * 2.0; return vLightWeighting; } void main() { if (vAmount < 0.01) { gl_FragColor = texture2D( sandyTexture, vUV * 50.0 ); gl_FragColor.a = 0.0; } else { vec4 sandy = (smoothstep(0.01, 0.03, vAmount) - smoothstep(0.05, 0.07, vAmount)) * texture2D( sandyTexture, vUV * 50.0 ); vec4 forest = (smoothstep(0.05, 0.07, vAmount) - smoothstep(0.40, 0.70, vAmount)) * texture2D( forestTexture, vUV * 50.0 ); vec4 rocky = (smoothstep(0.50, 0.65, vAmount)) * texture2D( rockyTexture, vUV * 25.0 ); gl_FragColor = sandy + forest + rocky; gl_FragColor -= (texture2D( texture, vUV ) * 0.5); // Alternative shading.. needs work. Look to integrate above old functions from Langenium.. //float diffuse = max(sunPosition.x * gl_FragColor.r + sunPosition.y * gl_FragColor.g + sunPosition.z * gl_FragColor.b, 0.0); //gl_FragColor *= 1. + diffuse * 0.1; gl_FragColor += sunshadeIsland(); gl_FragColor.a = 1.0; } } </script> <script id="spriteVertexShader" type="x-shader/x-vertex">varying vec2 vUV; void main() { vUV = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); } </script> <script id="spriteFragmentShader" type="x-shader/x-fragment">varying vec2 vUV; void main() { vec2 uv = vUV; uv -= 0.5; uv.x *= 0.8; float d = length(uv); float c = smoothstep(0.4, 0.4-0.6, d); c *= 0.5; gl_FragColor = vec4(c); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.js"></script> <script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126811218-1"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.4.0/Tween.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r116/three.min.js"></script> <script src="./vendor/ImprovedNoise.js"></script> <script src="./vendor/simplex.js"></script> <script src="./vendor/threex.keyboardstate.js"></script> <script src="./vendor/stats.min.js"></script> <script src="./vendor/OrbitControls.js"></script> <script src="./vendor/Water.js"></script> <script src="./vendor/Sky.js"></script> <script data-ad-client="ca-pub-5962056869598854" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> $(document).ready(()=>{ $('#mobile_menu_toggle').click(()=>{ $('#mobile_menu .item:not(.logo)').slideToggle(); }); }); </script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-126811218-1'); </script> <script> (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://kamigen.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> </body> </html>
{ "content_hash": "6b62e61a1f7c3738600e8119263415bf", "timestamp": "", "source": "github", "line_count": 308, "max_line_length": 746, "avg_line_length": 40.94155844155844, "alnum_prop": 0.6220459952418715, "repo_name": "paulbrzeski/kamigen", "id": "e57e164df42928299715bde523aef946503bf87a", "size": "12610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "comics/page_68.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1147" }, { "name": "GLSL", "bytes": "4003" }, { "name": "HTML", "bytes": "765682" }, { "name": "JavaScript", "bytes": "23756" } ], "symlink_target": "" }
#ifndef __PERF_RECORD_H #define __PERF_RECORD_H #include <limits.h> #include "../perf.h" #include "map.h" /* * PERF_SAMPLE_IP | PERF_SAMPLE_TID | * */ struct ip_event { struct perf_event_header header; u64 ip; u32 pid, tid; unsigned char __more_data[]; }; struct mmap_event { struct perf_event_header header; u32 pid, tid; u64 start; u64 len; u64 pgoff; char filename[PATH_MAX]; }; struct comm_event { struct perf_event_header header; u32 pid, tid; char comm[16]; }; struct fork_event { struct perf_event_header header; u32 pid, ppid; u32 tid, ptid; u64 time; }; struct lost_event { struct perf_event_header header; u64 id; u64 lost; }; /* * PERF_FORMAT_ENABLED | PERF_FORMAT_RUNNING | PERF_FORMAT_ID */ struct read_event { struct perf_event_header header; u32 pid, tid; u64 value; u64 time_enabled; u64 time_running; u64 id; }; #define PERF_SAMPLE_MASK \ (PERF_SAMPLE_IP | PERF_SAMPLE_TID | \ PERF_SAMPLE_TIME | PERF_SAMPLE_ADDR | \ PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD) struct sample_event { struct perf_event_header header; u64 array[]; }; struct perf_sample { u64 ip; u32 pid, tid; u64 time; u64 addr; u64 id; u64 stream_id; u64 period; u32 cpu; u32 raw_size; void *raw_data; struct ip_callchain *callchain; }; #define BUILD_ID_SIZE 20 struct build_id_event { struct perf_event_header header; pid_t pid; u8 build_id[ALIGN(BUILD_ID_SIZE, sizeof(u64))]; char filename[]; }; enum perf_user_event_type { /* above any possible kernel type */ PERF_RECORD_USER_TYPE_START = 64, PERF_RECORD_HEADER_ATTR = 64, PERF_RECORD_HEADER_EVENT_TYPE = 65, PERF_RECORD_HEADER_TRACING_DATA = 66, PERF_RECORD_HEADER_BUILD_ID = 67, PERF_RECORD_FINISHED_ROUND = 68, PERF_RECORD_HEADER_MAX }; struct attr_event { struct perf_event_header header; struct perf_event_attr attr; u64 id[]; }; #define MAX_EVENT_NAME 64 struct perf_trace_event_type { u64 event_id; char name[MAX_EVENT_NAME]; }; struct event_type_event { struct perf_event_header header; struct perf_trace_event_type event_type; }; struct tracing_data_event { struct perf_event_header header; u32 size; }; union perf_event { struct perf_event_header header; struct ip_event ip; struct mmap_event mmap; struct comm_event comm; struct fork_event fork; struct lost_event lost; struct read_event read; struct sample_event sample; struct attr_event attr; struct event_type_event event_type; struct tracing_data_event tracing_data; struct build_id_event build_id; }; void perf_event__print_totals(void); struct perf_session; struct thread_map; typedef int (*perf_event__handler_synth_t)(union perf_event *event, struct perf_session *session); typedef int (*perf_event__handler_t)(union perf_event *event, struct perf_sample *sample, struct perf_session *session); int perf_event__synthesize_thread_map(struct thread_map *threads, perf_event__handler_t process, struct perf_session *session); int perf_event__synthesize_threads(perf_event__handler_t process, struct perf_session *session); int perf_event__synthesize_kernel_mmap(perf_event__handler_t process, struct perf_session *session, struct machine *machine, const char *symbol_name); int perf_event__synthesize_modules(perf_event__handler_t process, struct perf_session *session, struct machine *machine); int perf_event__process_comm(union perf_event *event, struct perf_sample *sample, struct perf_session *session); int perf_event__process_lost(union perf_event *event, struct perf_sample *sample, struct perf_session *session); int perf_event__process_mmap(union perf_event *event, struct perf_sample *sample, struct perf_session *session); int perf_event__process_task(union perf_event *event, struct perf_sample *sample, struct perf_session *session); int perf_event__process(union perf_event *event, struct perf_sample *sample, struct perf_session *session); struct addr_location; int perf_event__preprocess_sample(const union perf_event *self, struct perf_session *session, struct addr_location *al, struct perf_sample *sample, symbol_filter_t filter); const char *perf_event__name(unsigned int id); int perf_event__parse_sample(const union perf_event *event, u64 type, int sample_size, bool sample_id_all, struct perf_sample *sample, bool swapped); #endif /* __PERF_RECORD_H */
{ "content_hash": "f02a0a29b8b8702e2aca4a95f6d0a892", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 81, "avg_line_length": 23.80628272251309, "alnum_prop": 0.6956234880140753, "repo_name": "WhiteBearSolutions/WBSAirback", "id": "357a85b852487a055454a358a78c5cfae023acc6", "size": "4547", "binary": false, "copies": "547", "ref": "refs/heads/master", "path": "packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/tools/perf/util/event.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4780982" } ], "symlink_target": "" }
/* jshint node: true */ // TODO: Make long comparison impervious to precision loss. // TODO: Optimize binary comparison methods. 'use strict'; /** Various utilities used across this library. */ var buffer = require('buffer'); var crypto = require('crypto'); var util = require('util'); var Buffer = buffer.Buffer; // Shared buffer pool for all taps. var POOL = new BufferPool(4096); // Valid (field, type, and symbol) name regex. var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; // Convenience imports. var f = util.format; /** * Create a new empty buffer. * * @param size {Number} The buffer's size. */ function newBuffer(size) { if (typeof Buffer.alloc == 'function') { return Buffer.alloc(size); } else { return new Buffer(size); } } /** * Create a new buffer with the input contents. * * @param data {Array|String} The buffer's data. * @param enc {String} Encoding, used if data is a string. */ function bufferFrom(data, enc) { if (typeof Buffer.from == 'function') { return Buffer.from(data, enc); } else { return new Buffer(data, enc); } } /** * Uppercase the first letter of a string. * * @param s {String} The string. */ function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); } /** * Compare two numbers. * * @param n1 {Number} The first one. * @param n2 {Number} The second one. */ function compare(n1, n2) { return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1); } /** * Get option or default if undefined. * * @param opts {Object} Options. * @param key {String} Name of the option. * @param def {...} Default value. * * This is useful mostly for true-ish defaults and false-ish values (where the * usual `||` idiom breaks down). */ function getOption(opts, key, def) { var value = opts[key]; return value === undefined ? def : value; } /** * Compute a string's hash. * * @param str {String} The string to hash. * @param algorithm {String} The algorithm used. Defaults to MD5. */ function getHash(str, algorithm) { algorithm = algorithm || 'md5'; var hash = crypto.createHash(algorithm); hash.end(str); return hash.read(); } /** * Find index of value in array. * * @param arr {Array} Can also be a false-ish value. * @param v {Object} Value to find. * * Returns -1 if not found, -2 if found multiple times. */ function singleIndexOf(arr, v) { var pos = -1; var i, l; if (!arr) { return -1; } for (i = 0, l = arr.length; i < l; i++) { if (arr[i] === v) { if (pos >= 0) { return -2; } pos = i; } } return pos; } /** * Convert array to map. * * @param arr {Array} Elements. * @param fn {Function} Function returning an element's key. */ function toMap(arr, fn) { var obj = {}; var i, elem; for (i = 0; i < arr.length; i++) { elem = arr[i]; obj[fn(elem)] = elem; } return obj; } /** * Convert map to array of values (polyfill for `Object.values`). * * @param obj {Object} Map. */ function objectValues(obj) { return Object.keys(obj).map(function (key) { return obj[key]; }); } /** * Check whether an array has duplicates. * * @param arr {Array} The array. * @param fn {Function} Optional function to apply to each element. */ function hasDuplicates(arr, fn) { var obj = Object.create(null); var i, l, elem; for (i = 0, l = arr.length; i < l; i++) { elem = arr[i]; if (fn) { elem = fn(elem); } if (obj[elem]) { return true; } obj[elem] = true; } return false; } /** * Copy properties from one object to another. * * @param src {Object} The source object. * @param dst {Object} The destination object. * @param overwrite {Boolean} Whether to overwrite existing destination * properties. Defaults to false. */ function copyOwnProperties(src, dst, overwrite) { var names = Object.getOwnPropertyNames(src); var i, l, name; for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (!dst.hasOwnProperty(name) || overwrite) { var descriptor = Object.getOwnPropertyDescriptor(src, name); Object.defineProperty(dst, name, descriptor); } } return dst; } /** * Check whether a string is a valid Avro identifier. */ function isValidName(str) { return NAME_PATTERN.test(str); } /** * Verify and return fully qualified name. * * @param name {String} Full or short name. It can be prefixed with a dot to * force global namespace. * @param namespace {String} Optional namespace. */ function qualify(name, namespace) { if (~name.indexOf('.')) { name = name.replace(/^\./, ''); // Allow absolute referencing. } else if (namespace) { name = namespace + '.' + name; } name.split('.').forEach(function (part) { if (!isValidName(part)) { throw new Error(f('invalid name: %j', name)); } }); return name; } /** * Remove namespace from a name. * * @param name {String} Full or short name. */ function unqualify(name) { var parts = name.split('.'); return parts[parts.length - 1]; } /** * Return the namespace implied by a name. * * @param name {String} Full or short name. If short, the returned namespace * will be empty. */ function impliedNamespace(name) { var match = /^(.*)\.[^.]+$/.exec(name); return match ? match[1] : undefined; } /** * Returns offset in the string of the end of JSON object (-1 if past the end). * * To keep the implementation simple, this function isn't a JSON validator. It * will gladly return a result for invalid JSON (which is OK since that will be * promptly rejected by the JSON parser). What matters is that it is guaranteed * to return the correct end when presented with valid JSON. * * @param str {String} Input string containing serialized JSON.. * @param pos {Number} Starting position. */ function jsonEnd(str, pos) { pos = pos | 0; // Handle the case of a simple literal separately. var c = str.charAt(pos++); if (/[\d-]/.test(c)) { while (/[eE\d.+-]/.test(str.charAt(pos))) { pos++; } return pos; } else if (/true|null/.test(str.slice(pos - 1, pos + 3))) { return pos + 3; } else if (/false/.test(str.slice(pos - 1, pos + 4))) { return pos + 4; } // String, object, or array. var depth = 0; var literal = false; do { switch (c) { case '{': case '[': if (!literal) { depth++; } break; case '}': case ']': if (!literal && !--depth) { return pos; } break; case '"': literal = !literal; if (!depth && !literal) { return pos; } break; case '\\': pos++; // Skip the next character. } } while ((c = str.charAt(pos++))); return -1; } /** "Abstract" function to help with "subclassing". */ function abstractFunction() { throw new Error('abstract'); } /** Batch-deprecate "getters" from an object's prototype. */ function addDeprecatedGetters(obj, props) { var proto = obj.prototype; var i, l, prop, getter; for (i = 0, l = props.length; i < l; i++) { prop = props[i]; getter = 'get' + capitalize(prop); proto[getter] = util.deprecate( createGetter(prop), 'use `.' + prop + '` instead of `.' + getter + '()`' ); } function createGetter(prop) { return function () { var delegate = this[prop]; return typeof delegate == 'function' ? delegate.apply(this, arguments) : delegate; }; } } /** * Simple buffer pool to avoid allocating many small buffers. * * This provides significant speedups in recent versions of node (6+). */ function BufferPool(len) { this._len = len | 0; this._pos = 0; this._slab = newBuffer(this._len); } BufferPool.prototype.alloc = function (len) { if (len < 0) { throw new Error('negative length'); } var maxLen = this._len; if (len > maxLen) { return newBuffer(len); } if (this._pos + len > maxLen) { this._slab = newBuffer(maxLen); this._pos = 0; } return this._slab.slice(this._pos, this._pos += len); }; /** * Generator of random things. * * Inspired by: http://stackoverflow.com/a/424445/1062617 */ function Lcg(seed) { var a = 1103515245; var c = 12345; var m = Math.pow(2, 31); var state = Math.floor(seed || Math.random() * (m - 1)); this._max = m; this._nextInt = function () { return state = (a * state + c) % m; }; } Lcg.prototype.nextBoolean = function () { // jshint -W018 return !!(this._nextInt() % 2); }; Lcg.prototype.nextInt = function (start, end) { if (end === undefined) { end = start; start = 0; } end = end === undefined ? this._max : end; return start + Math.floor(this.nextFloat() * (end - start)); }; Lcg.prototype.nextFloat = function (start, end) { if (end === undefined) { end = start; start = 0; } end = end === undefined ? 1 : end; return start + (end - start) * this._nextInt() / this._max; }; Lcg.prototype.nextString = function(len, flags) { len |= 0; flags = flags || 'aA'; var mask = ''; if (flags.indexOf('a') > -1) { mask += 'abcdefghijklmnopqrstuvwxyz'; } if (flags.indexOf('A') > -1) { mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; } if (flags.indexOf('#') > -1) { mask += '0123456789'; } if (flags.indexOf('!') > -1) { mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\'; } var result = []; for (var i = 0; i < len; i++) { result.push(this.choice(mask)); } return result.join(''); }; Lcg.prototype.nextBuffer = function (len) { var arr = []; var i; for (i = 0; i < len; i++) { arr.push(this.nextInt(256)); } return bufferFrom(arr); }; Lcg.prototype.choice = function (arr) { var len = arr.length; if (!len) { throw new Error('choosing from empty array'); } return arr[this.nextInt(len)]; }; /** * Ordered queue which returns items consecutively. * * This is actually a heap by index, with the added requirements that elements * can only be retrieved consecutively. */ function OrderedQueue() { this._index = 0; this._items = []; } OrderedQueue.prototype.push = function (item) { var items = this._items; var i = items.length | 0; var j; items.push(item); while (i > 0 && items[i].index < items[j = ((i - 1) >> 1)].index) { item = items[i]; items[i] = items[j]; items[j] = item; i = j; } }; OrderedQueue.prototype.pop = function () { var items = this._items; var len = (items.length - 1) | 0; var first = items[0]; if (!first || first.index > this._index) { return null; } this._index++; if (!len) { items.pop(); return first; } items[0] = items.pop(); var mid = len >> 1; var i = 0; var i1, i2, j, item, c, c1, c2; while (i < mid) { item = items[i]; i1 = (i << 1) + 1; i2 = (i + 1) << 1; c1 = items[i1]; c2 = items[i2]; if (!c2 || c1.index <= c2.index) { c = c1; j = i1; } else { c = c2; j = i2; } if (c.index >= item.index) { break; } items[j] = item; items[i] = c; i = j; } return first; }; /** * A tap is a buffer which remembers what has been already read. * * It is optimized for performance, at the cost of failing silently when * overflowing the buffer. This is a purposeful trade-off given the expected * rarity of this case and the large performance hit necessary to enforce * validity. See `isValid` below for more information. */ function Tap(buf, pos) { this.buf = buf; this.pos = pos | 0; if (this.pos < 0) { throw new Error('negative offset'); } } /** * Check that the tap is in a valid state. * * For efficiency reasons, none of the methods below will fail if an overflow * occurs (either read, skip, or write). For this reason, it is up to the * caller to always check that the read, skip, or write was valid by calling * this method. */ Tap.prototype.isValid = function () { return this.pos <= this.buf.length; }; Tap.prototype._invalidate = function () { this.pos = this.buf.length + 1; }; // Read, skip, write methods. // // These should fail silently when the buffer overflows. Note this is only // required to be true when the functions are decoding valid objects. For // example errors will still be thrown if a bad count is read, leading to a // negative position offset (which will typically cause a failure in // `readFixed`). Tap.prototype.readBoolean = function () { return !!this.buf[this.pos++]; }; Tap.prototype.skipBoolean = function () { this.pos++; }; Tap.prototype.writeBoolean = function (b) { this.buf[this.pos++] = !!b; }; Tap.prototype.readInt = Tap.prototype.readLong = function () { var n = 0; var k = 0; var buf = this.buf; var b, h, f, fk; do { b = buf[this.pos++]; h = b & 0x80; n |= (b & 0x7f) << k; k += 7; } while (h && k < 28); if (h) { // Switch to float arithmetic, otherwise we might overflow. f = n; fk = 268435456; // 2 ** 28. do { b = buf[this.pos++]; f += (b & 0x7f) * fk; fk *= 128; } while (b & 0x80); return (f % 2 ? -(f + 1) : f) / 2; } return (n >> 1) ^ -(n & 1); }; Tap.prototype.skipInt = Tap.prototype.skipLong = function () { var buf = this.buf; while (buf[this.pos++] & 0x80) {} }; Tap.prototype.writeInt = Tap.prototype.writeLong = function (n) { var buf = this.buf; var f, m; if (n >= -1073741824 && n < 1073741824) { // Won't overflow, we can use integer arithmetic. m = n >= 0 ? n << 1 : (~n << 1) | 1; do { buf[this.pos] = m & 0x7f; m >>= 7; } while (m && (buf[this.pos++] |= 0x80)); } else { // We have to use slower floating arithmetic. f = n >= 0 ? n * 2 : (-n * 2) - 1; do { buf[this.pos] = f & 0x7f; f /= 128; } while (f >= 1 && (buf[this.pos++] |= 0x80)); } this.pos++; }; Tap.prototype.readFloat = function () { var buf = this.buf; var pos = this.pos; this.pos += 4; if (this.pos > buf.length) { return 0; } return this.buf.readFloatLE(pos); }; Tap.prototype.skipFloat = function () { this.pos += 4; }; Tap.prototype.writeFloat = function (f) { var buf = this.buf; var pos = this.pos; this.pos += 4; if (this.pos > buf.length) { return; } return this.buf.writeFloatLE(f, pos); }; Tap.prototype.readDouble = function () { var buf = this.buf; var pos = this.pos; this.pos += 8; if (this.pos > buf.length) { return 0; } return this.buf.readDoubleLE(pos); }; Tap.prototype.skipDouble = function () { this.pos += 8; }; Tap.prototype.writeDouble = function (d) { var buf = this.buf; var pos = this.pos; this.pos += 8; if (this.pos > buf.length) { return; } return this.buf.writeDoubleLE(d, pos); }; Tap.prototype.readFixed = function (len) { var pos = this.pos; this.pos += len; if (this.pos > this.buf.length) { return; } var fixed = POOL.alloc(len); this.buf.copy(fixed, 0, pos, pos + len); return fixed; }; Tap.prototype.skipFixed = function (len) { this.pos += len; }; Tap.prototype.writeFixed = function (buf, len) { len = len || buf.length; var pos = this.pos; this.pos += len; if (this.pos > this.buf.length) { return; } buf.copy(this.buf, pos, 0, len); }; Tap.prototype.readBytes = function () { var len = this.readLong(); if (len < 0) { this._invalidate(); return; } return this.readFixed(len); }; Tap.prototype.skipBytes = function () { var len = this.readLong(); if (len < 0) { this._invalidate(); return; } this.pos += len; }; Tap.prototype.writeBytes = function (buf) { var len = buf.length; this.writeLong(len); this.writeFixed(buf, len); }; /* istanbul ignore else */ if (typeof Buffer.prototype.utf8Slice == 'function') { // Use this optimized function when available. Tap.prototype.readString = function () { var len = this.readLong(); if (len < 0) { this._invalidate(); return ''; } var pos = this.pos; var buf = this.buf; this.pos += len; if (this.pos > buf.length) { return; } return this.buf.utf8Slice(pos, pos + len); }; } else { Tap.prototype.readString = function () { var len = this.readLong(); if (len < 0) { this._invalidate(); return ''; } var pos = this.pos; var buf = this.buf; this.pos += len; if (this.pos > buf.length) { return; } return this.buf.slice(pos, pos + len).toString(); }; } Tap.prototype.skipString = function () { var len = this.readLong(); if (len < 0) { this._invalidate(); return; } this.pos += len; }; Tap.prototype.writeString = function (s) { var len = Buffer.byteLength(s); var buf = this.buf; this.writeLong(len); var pos = this.pos; this.pos += len; if (this.pos > buf.length) { return; } if (len > 64 && typeof Buffer.prototype.utf8Write == 'function') { // This method is roughly 50% faster than the manual implementation below // for long strings (which is itself faster than the generic `Buffer#write` // at least in most browsers, where `utf8Write` is not available). buf.utf8Write(s, pos, len); } else { var i, l, c1, c2; for (i = 0, l = len; i < l; i++) { c1 = s.charCodeAt(i); if (c1 < 0x80) { buf[pos++] = c1; } else if (c1 < 0x800) { buf[pos++] = c1 >> 6 | 0xc0; buf[pos++] = c1 & 0x3f | 0x80; } else if ( (c1 & 0xfc00) === 0xd800 && ((c2 = s.charCodeAt(i + 1)) & 0xfc00) === 0xdc00 ) { c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff); i++; buf[pos++] = c1 >> 18 | 0xf0; buf[pos++] = c1 >> 12 & 0x3f | 0x80; buf[pos++] = c1 >> 6 & 0x3f | 0x80; buf[pos++] = c1 & 0x3f | 0x80; } else { buf[pos++] = c1 >> 12 | 0xe0; buf[pos++] = c1 >> 6 & 0x3f | 0x80; buf[pos++] = c1 & 0x3f | 0x80; } } } }; /* istanbul ignore else */ if (typeof Buffer.prototype.latin1Write == 'function') { // `binaryWrite` has been renamed to `latin1Write` in Node v6.4.0, see // https://github.com/nodejs/node/pull/7111. Note that the `'binary'` // encoding argument still works however. Tap.prototype.writeBinary = function (str, len) { var pos = this.pos; this.pos += len; if (this.pos > this.buf.length) { return; } this.buf.latin1Write(str, pos, len); }; } else if (typeof Buffer.prototype.binaryWrite == 'function') { Tap.prototype.writeBinary = function (str, len) { var pos = this.pos; this.pos += len; if (this.pos > this.buf.length) { return; } this.buf.binaryWrite(str, pos, len); }; } else { // Slowest implementation. Tap.prototype.writeBinary = function (s, len) { var pos = this.pos; this.pos += len; if (this.pos > this.buf.length) { return; } this.buf.write(s, pos, len, 'binary'); }; } // Binary comparison methods. // // These are not guaranteed to consume the objects they are comparing when // returning a non-zero result (allowing for performance benefits), so no other // operations should be done on either tap after a compare returns a non-zero // value. Also, these methods do not have the same silent failure requirement // as read, skip, and write since they are assumed to be called on valid // buffers. Tap.prototype.matchBoolean = function (tap) { return this.buf[this.pos++] - tap.buf[tap.pos++]; }; Tap.prototype.matchInt = Tap.prototype.matchLong = function (tap) { var n1 = this.readLong(); var n2 = tap.readLong(); return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1); }; Tap.prototype.matchFloat = function (tap) { var n1 = this.readFloat(); var n2 = tap.readFloat(); return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1); }; Tap.prototype.matchDouble = function (tap) { var n1 = this.readDouble(); var n2 = tap.readDouble(); return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1); }; Tap.prototype.matchFixed = function (tap, len) { return this.readFixed(len).compare(tap.readFixed(len)); }; Tap.prototype.matchBytes = Tap.prototype.matchString = function (tap) { var l1 = this.readLong(); var p1 = this.pos; this.pos += l1; var l2 = tap.readLong(); var p2 = tap.pos; tap.pos += l2; var b1 = this.buf.slice(p1, this.pos); var b2 = tap.buf.slice(p2, tap.pos); return b1.compare(b2); }; // Functions for supporting custom long classes. // // The two following methods allow the long implementations to not have to // worry about Avro's zigzag encoding, we directly expose longs as unpacked. Tap.prototype.unpackLongBytes = function () { var res = newBuffer(8); var n = 0; var i = 0; // Byte index in target buffer. var j = 6; // Bit offset in current target buffer byte. var buf = this.buf; var b, neg; b = buf[this.pos++]; neg = b & 1; res.fill(0); n |= (b & 0x7f) >> 1; while (b & 0x80) { b = buf[this.pos++]; n |= (b & 0x7f) << j; j += 7; if (j >= 8) { // Flush byte. j -= 8; res[i++] = n; n >>= 8; } } res[i] = n; if (neg) { invert(res, 8); } return res; }; Tap.prototype.packLongBytes = function (buf) { var neg = (buf[7] & 0x80) >> 7; var res = this.buf; var j = 1; var k = 0; var m = 3; var n; if (neg) { invert(buf, 8); n = 1; } else { n = 0; } var parts = [ buf.readUIntLE(0, 3), buf.readUIntLE(3, 3), buf.readUIntLE(6, 2) ]; // Not reading more than 24 bits because we need to be able to combine the // "carry" bits from the previous part and JavaScript only supports bitwise // operations on 32 bit integers. while (m && !parts[--m]) {} // Skip trailing 0s. // Leading parts (if any), we never bail early here since we need the // continuation bit to be set. while (k < m) { n |= parts[k++] << j; j += 24; while (j > 7) { res[this.pos++] = (n & 0x7f) | 0x80; n >>= 7; j -= 7; } } // Final part, similar to normal packing aside from the initial offset. n |= parts[m] << j; do { res[this.pos] = n & 0x7f; n >>= 7; } while (n && (res[this.pos++] |= 0x80)); this.pos++; // Restore original buffer (could make this optional?). if (neg) { invert(buf, 8); } }; // Helpers. /** * Invert all bits in a buffer. * * @param buf {Buffer} Non-empty buffer to invert. * @param len {Number} Buffer length (must be positive). */ function invert(buf, len) { while (len--) { buf[len] = ~buf[len]; } } module.exports = { abstractFunction: abstractFunction, addDeprecatedGetters: addDeprecatedGetters, bufferFrom: bufferFrom, capitalize: capitalize, copyOwnProperties: copyOwnProperties, getHash: getHash, compare: compare, getOption: getOption, impliedNamespace: impliedNamespace, isValidName: isValidName, jsonEnd: jsonEnd, newBuffer: newBuffer, objectValues: objectValues, qualify: qualify, toMap: toMap, singleIndexOf: singleIndexOf, hasDuplicates: hasDuplicates, unqualify: unqualify, BufferPool: BufferPool, Lcg: Lcg, OrderedQueue: OrderedQueue, Tap: Tap };
{ "content_hash": "5fbff3f8a6868e5583d92da3731ea722", "timestamp": "", "source": "github", "line_count": 965, "max_line_length": 79, "avg_line_length": 23.798963730569948, "alnum_prop": 0.5918749455717147, "repo_name": "mtth/avsc", "id": "d8c525bdf2ce072dec0737c2e3f1ac3a63421db5", "size": "22966", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7424" }, { "name": "JavaScript", "bytes": "592618" }, { "name": "Python", "bytes": "10248" }, { "name": "Ruby", "bytes": "1017" }, { "name": "Shell", "bytes": "805" } ], "symlink_target": "" }
#ifndef BOOST_SERIALIZATION_SERIALIZATION_HPP #define BOOST_SERIALIZATION_SERIALIZATION_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif #if defined(_MSC_VER) # pragma warning (disable : 4675) // suppress ADL warning #endif #include <boost/config.hpp> #include <boost/serialization/strong_typedef.hpp> /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // serialization.hpp: interface for serialization system. // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. ////////////////////////////////////////////////////////////////////// // public interface to serialization. ///////////////////////////////////////////////////////////////////////////// // layer 0 - intrusive verison // declared and implemented for each user defined class to be serialized // // template<Archive> // serialize(Archive &ar, const unsigned int file_version){ // ar & base_object<base>(*this) & member1 & member2 ... ; // } ///////////////////////////////////////////////////////////////////////////// // layer 1 - layer that routes member access through the access class. // this is what permits us to grant access to private class member functions // by specifying friend class pdalboost::serialization::access #include <boost/serialization/access.hpp> ///////////////////////////////////////////////////////////////////////////// // layer 2 - default implementation of non-intrusive serialization. // // note the usage of function overloading to compensate that C++ does not // currently support Partial Template Specialization for function templates // We have declared the version number as "const unsigned long". // Overriding templates for specific data types should declare the version // number as "const unsigned int". Template matching will first be applied // to functions with the same version types - that is the overloads. // If there is no declared function prototype that matches, the second argument // will be converted to "const unsigned long" and a match will be made with // one of the default template functions below. namespace pdalboost { namespace serialization { BOOST_STRONG_TYPEDEF(unsigned int, version_type) // default implementation - call the member function "serialize" template<class Archive, class T> inline void serialize( Archive & ar, T & t, const unsigned int file_version ){ access::serialize(ar, t, static_cast<unsigned int>(file_version)); } // save data required for construction template<class Archive, class T> inline void save_construct_data( Archive & /*ar*/, const T * /*t*/, const unsigned int /*file_version */ ){ // default is to save no data because default constructor // requires no arguments. } // load data required for construction and invoke constructor in place template<class Archive, class T> inline void load_construct_data( Archive & /*ar*/, T * t, const unsigned int /*file_version*/ ){ // default just uses the default constructor. going // through access permits usage of otherwise private default // constructor access::construct(t); } ///////////////////////////////////////////////////////////////////////////// // layer 3 - move call into serialization namespace so that ADL will function // in the manner we desire. // // on compilers which don't implement ADL. only the current namespace // i.e. pdalboost::serialization will be searched. // // on compilers which DO implement ADL // serialize overrides can be in any of the following // // 1) same namepace as Archive // 2) same namespace as T // 3) pdalboost::serialization // // Due to Martin Ecker template<class Archive, class T> inline void serialize_adl( Archive & ar, T & t, const unsigned int file_version ){ // note usage of function overloading to delay final resolution // until the point of instantiation. This works around the two-phase // lookup "feature" which inhibits redefintion of a default function // template implementation. Due to Robert Ramey // // Note that this trick generates problems for compiles which don't support // PFTO, suppress it here. As far as we know, there are no compilers // which fail to support PFTO while supporting two-phase lookup. const version_type v(file_version); serialize(ar, t, v); } template<class Archive, class T> inline void save_construct_data_adl( Archive & ar, const T * t, const unsigned int file_version ){ // see above const version_type v(file_version); save_construct_data(ar, t, v); } template<class Archive, class T> inline void load_construct_data_adl( Archive & ar, T * t, const unsigned int file_version ){ // see above comment const version_type v(file_version); load_construct_data(ar, t, v); } } // namespace serialization } // namespace pdalboost #endif //BOOST_SERIALIZATION_SERIALIZATION_HPP
{ "content_hash": "790d4f611836ca96ca8ec57f15644249", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 80, "avg_line_length": 33.967532467532465, "alnum_prop": 0.6597208946664118, "repo_name": "lucadelu/PDAL", "id": "2955a1be1a0e7cfb3d6178c8adc3c72a7f488d8c", "size": "5231", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/pdalboost/boost/serialization/serialization.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "7294" }, { "name": "C", "bytes": "13415" }, { "name": "C++", "bytes": "2574781" }, { "name": "CMake", "bytes": "135083" }, { "name": "Python", "bytes": "13397" }, { "name": "SQLPL", "bytes": "844" }, { "name": "Shell", "bytes": "19962" } ], "symlink_target": "" }
fs = require('fs'); path = require('path'); exports.stripExt = function(filename) { return filename.substr(0, filename.length - path.extname(filename).length); }; exports.readFileSync = function(filename) { return fs.readFileSync(filename, {encoding:'utf8'}); }; exports.memorize = function(fn) { var memorized = {}; return function() { var key = Array.prototype.join.call(arguments, ','); if (!(key in memorized)) { memorized[key] = fn.apply(null, arguments); } return memorized[key]; }; };
{ "content_hash": "064443ecdd3f6d473ad1315d88dc50e0", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 79, "avg_line_length": 26.61904761904762, "alnum_prop": 0.6189624329159212, "repo_name": "zweifisch/ccjs", "id": "8d606ee8e88c828ba6fd5943b03cf9e70af9dcac", "size": "559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4242" }, { "name": "CoffeeScript", "bytes": "38" }, { "name": "HTML", "bytes": "385" }, { "name": "JavaScript", "bytes": "256866" } ], "symlink_target": "" }
<?php /** * Test helpers */ // require_once __DIR__ . '/../../../../TestHelper.php'; if (!defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'Zend_Service_SqlAzure_Management_AllTests::main'); } require_once 'Zend/Service/SqlAzure/Management/ManagementClientTest.php'; /** * @category Zend * @package Zend_Service_SqlAzure * @subpackage UnitTests * @version $Id$ * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_SqlAzure_Management_AllTests { public static function main() { PHPUnit_TextUI_TestRunner::run(self::suite()); } public static function suite() { $suite = new PHPUnit_Framework_TestSuite(__CLASS__); $suite->addTestSuite('Zend_Service_SqlAzure_Management_ManagementClientTest'); return $suite; } } if (PHPUnit_MAIN_METHOD == 'Zend_Service_SqlAzure_Management_AllTests::main') { Zend_Service_SqlAzure_Management_AllTests::main(); }
{ "content_hash": "0a9b9462d0fb6d46260dc55ab6569bac", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 87, "avg_line_length": 26.51219512195122, "alnum_prop": 0.6605335786568537, "repo_name": "holtkamp/zf1", "id": "706d75a36fc50d6639c3ede918507619873e6cbd", "size": "1818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Zend/Service/SqlAzure/Management/AllTests.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1036" }, { "name": "HTML", "bytes": "90766" }, { "name": "Hack", "bytes": "7" }, { "name": "JavaScript", "bytes": "1588" }, { "name": "PHP", "bytes": "29840536" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Roff", "bytes": "307" }, { "name": "Shell", "bytes": "3011" }, { "name": "TSQL", "bytes": "1167" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.5.2 - v0.5.3: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.5.2 - v0.5.3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><b>internal</b></li><li class="navelem"><a class="el" href="structv8_1_1internal_1_1_internal_constants_3_018_01_4.html">InternalConstants&lt; 8 &gt;</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::internal::InternalConstants&lt; 8 &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structv8_1_1internal_1_1_internal_constants_3_018_01_4.html">v8::internal::InternalConstants&lt; 8 &gt;</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kStringResourceOffset</b> (defined in <a class="el" href="structv8_1_1internal_1_1_internal_constants_3_018_01_4.html">v8::internal::InternalConstants&lt; 8 &gt;</a>)</td><td class="entry"><a class="el" href="structv8_1_1internal_1_1_internal_constants_3_018_01_4.html">v8::internal::InternalConstants&lt; 8 &gt;</a></td><td class="entry"><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:47:17 for V8 API Reference Guide for node.js v0.5.2 - v0.5.3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "b57dd6ce67133bb04f790d927224d807", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 441, "avg_line_length": 47.626168224299064, "alnum_prop": 0.6510989010989011, "repo_name": "v8-dox/v8-dox.github.io", "id": "a34b5c54c22ab4826ba69dbf6d5f89b331222973", "size": "5096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fea524e/html/structv8_1_1internal_1_1_internal_constants_3_018_01_4-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "91e0d01ae9704a737e61f40a640447d6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7d4038645a0f947c9118f09ead747fbe71900a09", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Bignoniaceae/Kigelianthe/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package ast; import ast.visitors.Visitor; public class Type { public void accept(Visitor vis) { vis.visit(this); } }
{ "content_hash": "5af08edf9fc59bd00fb07e1de707b890", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 37, "avg_line_length": 13.818181818181818, "alnum_prop": 0.5723684210526315, "repo_name": "lhcavalcanti/compilers-cin", "id": "96110261e010c5f7351656673e0e3720c8916d5d", "size": "152", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "demos/type-checking/src/main/java/ast/Type.java", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "9267" }, { "name": "Batchfile", "bytes": "323" }, { "name": "Java", "bytes": "307085" }, { "name": "Shell", "bytes": "584" } ], "symlink_target": "" }
import React, { Component } from 'react'; import { AppRegistry, NavigatorIOS, StyleSheet } from 'react-native'; import Main from './app/components/Main'; export default class App extends Component { render() { return ( <NavigatorIOS style={styles.container} initialRoute = {{ title : "githubprofileviewer", component: Main }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#111111' } }) AppRegistry.registerComponent('githubprofileviewer', () => App);
{ "content_hash": "8c52313e300cfe70473b8636a6da82cc", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 69, "avg_line_length": 24.304347826086957, "alnum_prop": 0.6368515205724508, "repo_name": "pritamstyz4ever/github-profile-viewer", "id": "70c5fab306cbb354a83d15150b18adf167a49dfe", "size": "559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "githubprofileviewer/index.ios.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1350" }, { "name": "JavaScript", "bytes": "14501" }, { "name": "Objective-C", "bytes": "4444" }, { "name": "Python", "bytes": "1748" } ], "symlink_target": "" }
layout: post title: 'TIP: Hosts file in Mac OSX and POW!!' tags: - mac - tip - hosts - dns - rack - pow description: Alan Rubin writes about host files in Mac and also about a nice rack server called POW --- This is an old tip, but I keep going back to google in order to find it out. So I decided to put it here in my blog in order to save google queries and also to give you some nice rack server connected to rails. So if you need to configure additional dns names for different ip's in your local computer, open your terminal and write: {% highlight bash %} sudo nano /private/etc/hosts {% endhighlight %} You can also use any editor you want instead of 'nano', this includes [textmate](http://macromates.com/) and textedit. Edit the hosts file as you need : for each line, enter the ip and the host name you want to configure. For commented lines, use # char at the beginning of the line, as shown below. Exit 'nano' and save the file (Crtl-X and Yes). {% highlight bash %} 127.0.0.1 portalondemand # this line is commented line and also the line below #10.23.22.30 deactivate.name {% endhighlight %} After saving, you will need to refresh the dns cache of your computer by running: {% highlight bash %} dscacheutil -flushcache {% endhighlight %} ... and you are done. Why editing host files ? Sometimes you need to associate an ip to a hostname in your local computer. For example, if you are developing an application locally and you want to test it with a domain name in your browser instead of using 'localhost' or '127.0.0.1'. If this is your scenario, I recommend you also to take a look at 37Signals [POW](http://pow.cx/), a very nice zero configuration Rack server for Mac OSX. [POW](http://pow.cx/) saves you additional work by using convention over configuration so you can get all your applications running with different hostnames. If you are interested about UI design like I am, you can also enjoy the nice design of the [POW](http://pow.cx/)'s website and checkout additional info about its designer [Jamie Dihiansan](http://37signals.com/svn/posts/1210-introducing-our-new-designer-jamie-dihiansan). <a href="http://pow.cx/"><img src="/images/logo-pow.png"></a>
{ "content_hash": "f722039cf7c73d494e5424e4c37b5efa", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 311, "avg_line_length": 53.63414634146341, "alnum_prop": 0.7485220554797636, "repo_name": "alanrubin/alanrubin.github.com", "id": "cd8292933b6db66f0f869d39dd2422a19166264f", "size": "2204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2011-06-29-hosts-file-in-mac-osx-and-pow!!.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3868" } ], "symlink_target": "" }
extern volatile int f_wdt; extern unsigned long millisOffset; void sleepInit(); void sleep(int); inline unsigned long fixedMillis() { return millis() + millisOffset; } inline unsigned long fixedMicros() { const unsigned long microsecondsPerMillsecond = 1000; return micros() + millisOffset * microsecondsPerMillsecond; } #endif // _SLEEP_H_
{ "content_hash": "54a5c7290dd7b90acc57b2f1d4bc90d6", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 61, "avg_line_length": 19.5, "alnum_prop": 0.7521367521367521, "repo_name": "twd2/SmartD", "id": "07f19de361d7c01036db53f6256b2562db1aefae", "size": "388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Arduino/controllers/plant/sleep.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4660" }, { "name": "C++", "bytes": "16072" }, { "name": "CSS", "bytes": "981" }, { "name": "HTML", "bytes": "17322" }, { "name": "Python", "bytes": "16235" }, { "name": "Shell", "bytes": "454" } ], "symlink_target": "" }
module Tuura.Fantasi.VHDL.Writer ( Tuura.Fantasi.VHDL.Writer.writeGraph, Tuura.Fantasi.VHDL.Writer.writeEnvironment ) where import Tuura.Fantasi.VHDL.Internal.EnvironmentWriter as VHDL import Tuura.Fantasi.VHDL.Internal.GraphWriter as VHDL import Data.ByteString.Char8(pack) import Data.ByteString(ByteString) import Pangraph -- | A serialiser which will write a graph into a VHDL connections. See more in the Fantasi section. writeGraph :: Pangraph -> ByteString writeGraph = pack . VHDL.writeGraph -- | A serialiser which will write an enviroment VHDL file. See more in the Fantasi section. writeEnvironment :: Pangraph -> ByteString writeEnvironment = pack . VHDL.writeEnvironment
{ "content_hash": "75082404d7a245f5c180c5ebbd5089da", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 100, "avg_line_length": 36.526315789473685, "alnum_prop": 0.7982708933717579, "repo_name": "tuura/fantasi", "id": "fe465a3858ec6c3efe476de78705806bf9827665", "size": "694", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Tuura/Fantasi/VHDL/Writer.hs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "77370" }, { "name": "Haskell", "bytes": "44822" }, { "name": "Shell", "bytes": "1745" } ], "symlink_target": "" }
import sys import gdb import os import os.path pythondir = '/home/a0273864/yagarto/install/share/gcc-4.7.1/python' libdir = '/home/a0273864/yagarto/install/arm-none-eabi/lib' # This file might be loaded when there is no current objfile. This # can happen if the user loads it manually. In this case we don't # update sys.path; instead we just hope the user managed to do that # beforehand. if gdb.current_objfile () is not None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want to apply that relative path to the # directory holding the objfile with which this file is associated. # This preserves relocatability of the gcc tree. # Do a simple normalization that removes duplicate separators. pythondir = os.path.normpath (pythondir) libdir = os.path.normpath (libdir) prefix = os.path.commonprefix ([libdir, pythondir]) # In some bizarre configuration we might have found a match in the # middle of a directory name. if prefix[-1] != '/': prefix = os.path.dirname (prefix) + '/' # Strip off the prefix. pythondir = pythondir[len (prefix):] libdir = libdir[len (prefix):] # Compute the ".."s needed to get from libdir to the prefix. dotdots = ('..' + os.sep) * len (libdir.split (os.sep)) objfile = gdb.current_objfile ().filename dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir) if not dir_ in sys.path: sys.path.insert(0, dir_) # Load the pretty-printers. from libstdcxx.v6.printers import register_libstdcxx_printers register_libstdcxx_printers (gdb.current_objfile ())
{ "content_hash": "4ecaacdd439245574b4048441ba34eeb", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 72, "avg_line_length": 37.45454545454545, "alnum_prop": 0.7008495145631068, "repo_name": "UECIDE/UECIDE_data", "id": "65dc5c95c0c1a43382ca4e8b12410a1fcf862269", "size": "2359", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "compilers/arm-eabi-gcc/windows/arm-eabi-gcc/arm-none-eabi/lib/libstdc++.a-gdb.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arduino", "bytes": "3816646" }, { "name": "Assembly", "bytes": "1421566" }, { "name": "C", "bytes": "546627695" }, { "name": "C++", "bytes": "113272035" }, { "name": "CSS", "bytes": "64919" }, { "name": "Emacs Lisp", "bytes": "237675" }, { "name": "Erlang", "bytes": "5952" }, { "name": "Java", "bytes": "3443" }, { "name": "JavaScript", "bytes": "22190" }, { "name": "Max", "bytes": "312593" }, { "name": "Objective-C", "bytes": "98663423" }, { "name": "Perl", "bytes": "563426" }, { "name": "Processing", "bytes": "1052533" }, { "name": "Pure Data", "bytes": "9910" }, { "name": "Python", "bytes": "383681" }, { "name": "Shell", "bytes": "800332" }, { "name": "Tcl", "bytes": "1379995" }, { "name": "TeX", "bytes": "510" }, { "name": "XC", "bytes": "79648" } ], "symlink_target": "" }
package ugego import ( "errors" "fmt" "log" "os" "os/exec" "strconv" "strings" ) // UserList is a Univa Grid Engine access control list or Department. type UserList struct { Name string Type string FShare int OTicket int Entries []string } // ParseUserList parses an Univa Grid Engine ACL by the given name into an struct. // The expected structure of ul is a multiline string in the Univa Grid Engine format: // name exclude // type ACL // fshare 0 // oticket 0 // entries daniel,root,%wheel func ParseUserList(ul string) (userList *UserList, err error) { var ol UserList el := strings.Split(ul, "\n") if len(el) != 5 { return nil, errors.New(fmt.Sprintf("User list does not have 5 lines, it has %d.\n", len(el))) } name := strings.Split(el[0], "name") if len(name) != 2 { return nil, errors.New("Error during name parsing.") } ol.Name = strings.TrimSpace(name[1]) t := strings.Split(el[1], "type") if len(t) != 2 { return nil, errors.New("Error during type parsing.") } ol.Type = strings.TrimSpace(t[1]) fs := strings.Split(el[2], "fshare") if len(fs) != 2 { return nil, errors.New("Error during fshare parsing.") } ot := strings.Split(el[3], "oticket") if len(ot) != 2 { return nil, errors.New("Error during oticket parsing.") } ent := strings.Split(el[4], "entries") if len(ent) != 2 { return nil, errors.New("Error during entries parsing.") } if ol.FShare, err = strconv.Atoi(strings.TrimSpace(fs[1])); err != nil { return nil, err } if ol.OTicket, err = strconv.Atoi(strings.TrimSpace(ot[1])); err != nil { return nil, err } ol.Entries = strings.Split(strings.TrimSpace(ent[1]), ",") return &ol, nil } // GetUserLists calls qconf -su <listOfUl> and parses the output // into UserList structs. func GetUserLists(userlist ...string) ([]UserList, error) { rootPath := os.Getenv("SGE_ROOT") if rootPath == "" { return nil, errors.New("$SGE_ROOT environment variable not set") } qconf := fmt.Sprintf("%s/bin/lx-amd64/qconf", rootPath) // create comma separated list of user list names var csvUserList string for k, v := range userlist { if k == 0 { csvUserList = fmt.Sprintf("%s", v) } else { csvUserList = fmt.Sprintf("%s,%s", csvUserList, v) } } cmd := exec.Command(qconf, "-su", csvUserList) if out, errOut := cmd.CombinedOutput(); errOut == nil { // empty line is the delimiter uls := strings.Split(string(out), "\n\n") if len(uls) == 0 { return nil, errors.New(fmt.Sprintf("Could not split output: %s", string(out))) } outputList := make([]UserList, len(uls), len(uls)) for i, ul := range uls { parsedUserList, errParse := ParseUserList(strings.TrimSpace(uls[i])) if errParse != nil { log.Printf("Error during parsing user list: %s\n%s\n", errParse, ul) log.Printf("%s", ul) return nil, errParse } outputList[i] = *parsedUserList } return outputList, nil } else { log.Printf("Error: %s\n", out) return nil, errOut } }
{ "content_hash": "7019c8ac27ca410d09d101ecc4c0a58d", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 95, "avg_line_length": 27.036363636363635, "alnum_prop": 0.6540013449899126, "repo_name": "dgruber/ugego", "id": "c6fe51b9ddb7be3f41386feb69df798224bd2626", "size": "3582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "userList.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "33521" } ], "symlink_target": "" }
package com.sohu.pp; import android.content.Context; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.SparseArray; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.viewpagerindicator.TabPageIndicator; public class PhotoFragment extends Fragment { private String[] photoTabs = null; private SparseArray<Fragment> photoTabFragments = new SparseArray<Fragment>(); private ImageView toggle = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); initResource(); } private void initResource() { Resources res = getResources(); photoTabs = res.getStringArray(R.array.photo_tab_array); photoTabFragments.append(0, new PhotoTimeFragment()); photoTabFragments.append(1, TestFragment.newInstance(photoTabs[1])); photoTabFragments.append(2, TestFragment.newInstance(photoTabs[2])); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Context contextThemeWrapper = new ContextThemeWrapper( getActivity(), R.style.Theme_PageIndicatorDefaults); // clone the inflater using the ContextThemeWrapper LayoutInflater localInflater = inflater .cloneInContext(contextThemeWrapper); // inflater the layout View view = localInflater.inflate(R.layout.photo_fragment, null); toggle = (ImageView) view.findViewById(R.id.btn_photo_toggle); toggle.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { // TODO Auto-generated method stub ((MainActivity) getActivity()).getSlidingMenu().toggle(); } }); FragmentPagerAdapter adapter = new PhotoFragmentPagerAdapter( getActivity().getSupportFragmentManager()); ViewPager pager = (ViewPager) view.findViewById(R.id.pager); pager.setAdapter(adapter); TabPageIndicator indicator = (TabPageIndicator) view .findViewById(R.id.indicator); indicator.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int paramInt) { // TODO Auto-generated method stub SlidingMenu sm = ((MainActivity) getActivity()) .getSlidingMenu(); if (paramInt == 0) { sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); } else { sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); } } @Override public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int paramInt) { // TODO Auto-generated method stub } }); indicator.setViewPager(pager); return view; } public void showMsg(String msg) { } private class PhotoFragmentPagerAdapter extends FragmentPagerAdapter { public PhotoFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return photoTabFragments.get(position); } @Override public CharSequence getPageTitle(int position) { return photoTabs[position % photoTabs.length]; } @Override public int getCount() { return photoTabs.length; } } }
{ "content_hash": "77660dc228d15d135c82b2a69ec077a9", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 79, "avg_line_length": 27.39097744360902, "alnum_prop": 0.7595388416140544, "repo_name": "willby/Sliding_Indicator_Frame", "id": "126f40504699fc874c7eeca8c7bc7ea6825102d8", "size": "3643", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "SohuPicFrame/src/com/sohu/pp/PhotoFragment.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var tableStyle = { width: '100%', borderSpacing: '2px 0', marginBottom: '2px' }; var firstTdStyle = { width: '6em', textTransform: 'capitalize' }; var PropertyStyle = { tableStyle: tableStyle, firstTdStyle: firstTdStyle }; export default PropertyStyle;
{ "content_hash": "1e18c3dc7c8e34f5755811c73ae4f949", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 80, "avg_line_length": 28.666666666666668, "alnum_prop": 0.7170542635658915, "repo_name": "cvdlab/react-planner", "id": "adc67ec11ce037bb28ecac8b734ee307950650ed", "size": "258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "es/catalog/properties/shared-property-style.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1014" }, { "name": "JavaScript", "bytes": "2019709" } ], "symlink_target": "" }
 /* Combined processedModules by KISSY Module Compiler: xtemplate/nodejs */ /** * load tpl from file in nodejs * @author yiminghe@gmail.com */ KISSY.add('xtemplate/nodejs', function (S, XTemplate) { var fs = require('fs'); var cached = {}; return { loadFromModuleName: function (moduleName, config) { config = S.merge(config, { cacheFile: 1 }); config.extname = config.extname || 'html'; var loader = getLoader(config); config.name = moduleName; config.loader = loader; var tpl = loader(moduleName); delete config.extname; return new XTemplate(tpl, config); } }; function getLoader(cfg) { var cacheFile = cfg.cacheFile; var extname = cfg.extname; return function (subTplName) { if (cacheFile && cached[subTplName]) { return cached[subTplName]; } var module = new S.Loader.Module({ name: subTplName, type: extname, runtime: S }); var tpl = fs.readFileSync(new S.Uri(module.getFullPath()).getPath(), { encoding: 'utf-8' }); if (cacheFile) { cached[subTplName] = tpl; } return tpl; } } }, { requires: ['xtemplate'] });
{ "content_hash": "f7d3fa4109722b36cc5121e0b9bf5e5a", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 82, "avg_line_length": 25.607142857142858, "alnum_prop": 0.50139470013947, "repo_name": "110035/kissy", "id": "59181121528f59ac66a3c0f68d968d1f332800bf", "size": "1521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/xtemplate/nodejs.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
[bouzuya/node-hatena-graph-cli][]をつくった。Hatena::Graph APIを使用するためのクライアント。まだ GET DATAしか実装していないけど。 コマンドライン引数の解釈に[visionmedia/commander][]を使っていて、これがなかなか使い心地が良い。そもそも、これを試すために書いてるようなもの。これ書いたら、[bouzuya/node-backlog-api][]にもCLIつけようかな。むしろ、こっちより使いそう。 [bouzuya/node-hatena-graph-cli]: https://github.com/bouzuya/node-hatena-graph-cli [bouzuya/node-backlog-api]: https://github.com/bouzuya/node-backlog-api [visionmedia/commander]: https://github.com/visionmedia/commander
{ "content_hash": "f61219b71f1a7237f6e3684029e5b52c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 144, "avg_line_length": 57.875, "alnum_prop": 0.8120950323974082, "repo_name": "bouzuya/blog.bouzuya.net", "id": "b86b163deea9a9014de9af56d47165f1273146ea", "size": "709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/2014/02/2014-02-07.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "377" }, { "name": "Shell", "bytes": "158" } ], "symlink_target": "" }
<div class="backup" ng-controller="backupController as wordsC"> <nav class="tab-bar"> <section class="left-small" ng-show="(wordsC.step != 1 && wordsC.step != 4)"> <a ng-click="wordsC.goToStep(1);"> <i class="icon-arrow-left3 icon-back"></i> </a> </section> <section class="middle tab-bar-section"> </section> <section class="right-small"> <a class="p10" ng-click="$root.go(index.prevState);"> <span class="text-close"> <i class="fi-x size-24"></i> </span> </a> </section> </nav> <div class="content preferences"> <div class="box-notification" ng-show="wordsC.error"> <span class="text-warning"> {{wordsC.error|translate}} </span> </div> <!-- ## STEP 1 --> <div ng-show="wordsC.step == 1"> <div ng-show="wordsC.mnemonicWords || (wordsC.credentialsEncrypted && !wordsC.deleted)" class="row"> <h5 class="text-center" translate>Write your wallet seed</h5> <div class="size-14 text-gray columns" ng-show="(index.n>1 && index.m != index.n )"> <span translate> To restore this {{index.m}}-{{index.n}} <b>shared</b> wallet you will need </span>: <ol class="m10t columns size-14 text-gray"> <li translate>Your wallet seed and access to the server that coordinated the initial wallet creation. You still need {{index.m}} keys to spend.</li> <li translate><b>OR</b> the wallet seed of <b>all</b> copayers in the wallet</li> <li translate><b>OR</b> 1 wallet export file and the remaining quorum of wallet seeds (e.g. in a 3-5 wallet: 1 wallet export file + 2 wallet seeds of any of the other copayers).</li> </ol> </span> </div> <div class="size-14 text-gray columns" ng-show="(index.n>1 && index.m == index.n )"> <span translate> To restore this {{index.m}}-{{index.n}} <b>shared</b> wallet you will need </span>: <ol class="m10t columns size-14 text-gray"> <li translate>Your wallet seed and access to the server that coordinated the initial wallet creation. You still need {{index.m}} keys to spend.</li> <li translate><b>OR</b> the wallet seeds of <b>all</b> copayers in the wallet</li> </ol> </span> </div> </div> <div class="row m20t" ng-show="wordsC.deleted"> <div class="columns size-14 text-gray text-center" translate> Wallet seed not available. You can still export it from Advanced &gt; Export. </div> </div> <div ng-show="wordsC.mnemonicWords || (wordsC.credentialsEncrypted && !wordsC.deleted)"> <p class="text-center columns text-gray" ng-show="index.n==1 && wordsC.step == 1"> <span translate> You need the wallet seed to restore this personal wallet. Write it down and keep them somewhere safe. </span> </p> <div class="row" ng-show="wordsC.credentialsEncrypted"> <div class="m10t columns"> <a class="button outline light-gray expand tiny" ng-click="wordsC.toggle()"> <i class="fi-widget m3r"></i> <span translate ng-hide="wordsC.show">Show Wallet Seed</span> </a> </div> </div> <div class="row" ng-show="!wordsC.credentialsEncrypted"> <div class="columns"> <div class="panel" ng-class="{'enable_text_select': index.network == 'testnet'}"> <span ng-repeat="word in wordsC.mnemonicWords track by $index"><span style="white-space:nowrap">{{word}}</span><span ng-show="wordsC.useIdeograms">&#x3000;</span> </span> </div> </div> </div> </div> <div class="columns extra-padding-bottom" ng-show="!wordsC.credentialsEncrypted"> <div class="line-t p10 size-10 text-gray text-center" ng-show="wordsC.mnemonicHasPassphrase"> <i class="fi-alert"></i> <span translate> This seed was created with a passphrase. To recover this wallet both the mnemonic and passphrase are needed. </span> </div> </div> <div class="button-box"> <button ng-show="!wordsC.deleted" ng-disabled="wordsC.credentialsEncrypted" class="round expand m0" ng-style="{'background-color':index.backgroundColor}" ng-click="wordsC.goToStep(2);" translate>Continue </button> </div> </div> <!-- ## STEP 2 --> <div ng-show="wordsC.step == 2"> <div class="columns text-center extra-padding-bottom"> <h5 translate>Confirm your wallet seed</h5> <p class="text-gray m0" translate> Please tap the words in order to confirm your backup phrase is correctly written. </p> <div class="panel words text-left" ng-class="{'enable_text_select': index.network == 'testnet'}"> <div id="addWord"></div> </div> <div class="text-left" ng-class="{'enable_text_select': index.network == 'testnet'}" id="buttons"> <span ng-repeat="word in wordsC.shuffledMnemonicWords track by $index"> <button class="button radius tiny words" ng-if="$index > 9" ng-click="wordsC.disableButton($index, word)" id="{{$index + word}}">{{word}}</button> <button class="button radius tiny words" ng-if="$index <= 9" ng-click="wordsC.disableButton('0' + $index, word)" id="{{'0' + $index + word}}">{{word}}</button> </span> </div> </div> <div class="button-box"> <button ng-disabled="!wordsC.selectComplete" class="round expand m0" ng-style="{'background-color':index.backgroundColor}" ng-click="wordsC.goToStep(3);" translate>Continue </button> </div> </div> <!-- ## STEP 3 --> <div ng-show="wordsC.step == 3"> <div class="columns text-center"> <h5 translate>Enter your passphrase</h5> <p class="text-gray m0" translate> In order to verify your wallet backup, please type your passphrase: </p> <div class="m20v"> <input type="text" id="passphrase" ng-model="passphrase" autocapitalize="off" spellcheck="false" autofocus/> </div> </div> <div class="button-box"> <button ng-disabled="!passphrase" ng-style="{'background-color':index.backgroundColor}" class="button round expand m0" ng-click="wordsC.goToStep(4);" translate>Continue </button> </div> </div> <!-- ## STEP 4 --> <div ng-show="wordsC.step == 4"> <div class="row m10t m10b text-center" ng-show="!wordsC.backupError"> <div class="circle-icon"> <i class="fi-like size-48"></i> </div> <h5 translate>Congratulations!</h5> <p class="text-gray columns" translate> You backed up your wallet. You can now restore this wallet at any time. </p> <div class="columns text-center m20t"> <button ng-style="{'background-color':index.backgroundColor}" class="button round expand" ng-click="$root.go('walletHome');" translate>Finish </button> <!-- hide this in multisig just to show less text --> <div class="row m20t" ng-show="index.n==1"> <div class="columns size-10 text-gray"> <div class="p10t line-t"> <span translate>You can safely install your wallet on another device and use it from multiple devices at the same time.</span> <a href="#" ng-click="$root.openExternalLink('https://github.com/bitpay/copay/blob/master/README.md#copay-backups-and-recovery')" translate> Learn more about DigiByte Gaming backups </a> </div> </div> </div> </div> </div> <div class="row m10t m10b text-center" ng-show="wordsC.backupError"> <div class="circle-icon"> <i class="fi-dislike size-48"></i> </div> <h5 translate>Backup failed</h5> <p class="text-gray columns" translate> Failed to verify backup. Please check your information </p> <div class="columns size-10 text-gray extra-padding-bottom" ng-show="index.n==1"> <div class="p10t line-t"> <span translate>You can safely install your wallet on another device and use it from multiple devices at the same time.</span> <a href="#" ng-click="$root.openExternalLink('https://github.com/bitpay/copay/blob/master/README.md#copay-backups-and-recovery')" translate> Learn more about DigiByte Gaming backups </a> </div> </div> <div class="button-box"> <button ng-style="{'background-color':index.backgroundColor}" class="button round expand m0" ng-click="wordsC.goToStep(1);" translate>Try again </button> </div> </div> </div> </div> </div> <div class="extra-margin-bottom"></div>
{ "content_hash": "676ec84e434fe401b37ab4e5078895d6", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 194, "avg_line_length": 40.427947598253276, "alnum_prop": 0.5713977100885721, "repo_name": "dgbholdings/digibyte-gaming-wallet", "id": "489f184df8f97687511af0cfb3f8354e5872f7cc", "size": "9258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/views/backup.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2066" }, { "name": "CSS", "bytes": "48259" }, { "name": "HTML", "bytes": "185238" }, { "name": "Inno Setup", "bytes": "1933" }, { "name": "JavaScript", "bytes": "446038" }, { "name": "Makefile", "bytes": "4100" }, { "name": "Shell", "bytes": "11597" } ], "symlink_target": "" }
<?php namespace Qsardw\Frontend\Traits; use Qsardw\Frontend\Application; use Qsardw\Frontend\Utils\String; /** * @author Javier Caride Ulloa <javier.caride@qsardw.org> */ trait BeanSerializer { /** * Returns an key-value array with the data contained in the object * * @return array */ public function toArray($getNulls = true) { $objectProperties = get_object_vars($this); $objectArray = array(); foreach ($objectProperties as $property => $propertyValue) { if ($getNulls === true) { $objectArray[$property] = $this->getPropertyValue($propertyValue); } else { if ($propertyValue !== null) { $objectArray[$property] = $this->getPropertyValue($propertyValue); } } } ksort($objectArray); return $objectArray; } /** * Returns the bean data as it's needed by database to deal with database * * @return array Bean data represented as a database row */ public function toRow($getNulls = true) { $row = array(); $objectProperties = get_object_vars($this); foreach ($objectProperties as $property => $propertyValue) { $columnName = String::camelcaseUnderscorer($property); if ($getNulls === true) { $row[$columnName] = $this->getPropertyValue($propertyValue); } else { if ($propertyValue !== null) { $row[$columnName] = $this->getPropertyValue($propertyValue); } } } ksort($row); return $row; } /** * Converts the object to JSON representation * * @return type */ public function toJson() { return json_encode($this->toArray()); } /** * Returns the right value of a property * * @param mixed $propertyValue * @return mixed */ protected function getPropertyValue($propertyValue) { if ($propertyValue instanceof \DateTime) { return $propertyValue->format(Application::TIMESTAMP); } else { return $propertyValue; } } }
{ "content_hash": "25167b3bf33069dd7580005771629120", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 86, "avg_line_length": 25.39325842696629, "alnum_prop": 0.5451327433628319, "repo_name": "qsardw/qsardw-frontend", "id": "686663221a5f018c6a9561e859f317e89c6b8628", "size": "2505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Qsardw/Frontend/Traits/BeanSerializer.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2178" }, { "name": "HTML", "bytes": "45019" }, { "name": "JavaScript", "bytes": "7152" }, { "name": "PHP", "bytes": "75712" }, { "name": "Shell", "bytes": "279" } ], "symlink_target": "" }
require 'spec_helper' describe RISBN::GData do it "can create a gdata instance from a string" do RISBN::GData("9780596101992").should be_an_instance_of(RISBN::GData) end it "can create a gdata instance from a RISBN" do RISBN("9780596101992").gdata.should be_an_instance_of(RISBN::GData) RISBN::GData(RISBN("9780596101992")).should be_an_instance_of(RISBN::GData) end it "raises Invalid ISBN if apropriate" do expect { RISBN::GData("6660596101992") }.to raise_exception(RISBN::InvalidISBN) expect { RISBN("6660596101992").gdata }.to raise_exception(RISBN::InvalidISBN) expect { RISBN::GData(RISBN("6660596101992")) }.to raise_exception(RISBN::InvalidISBN) end context "#data" do let(:isbn) { RISBN("9780596101992") } before { isbn.gdata.stub!(:xml).and_return(FIXTURE["book.xml"]) } let(:required_keys) do more = [:open_access, :rating_max, :rating_min, :thumbnail_url, :info_url, :annotation_url, :alternate_url, :self_url] isbn.gdata.to_hash.keys.uniq - [:link, :openAccess] + more end subject { isbn.gdata.data } it { should be_an_instance_of(RISBN::GData::BookData) } it "maps the attributes of the hash form of the google response to an struct" do required_keys.each { |key| should respond_to(key) } end it "is able to convert the struct to a hash and return its keys" do isbn.gdata.data.to_hash.should be_an_instance_of(Hash) isbn.gdata.data.keys.should be_an_instance_of(Array) isbn.gdata.data.keys.should_not be_empty end end context "specific cases" do context "0072253592" do let(:isbn) { RISBN("0072253592") } before { isbn.gdata.stub!(:xml).and_return(FIXTURE["#{isbn.to_s}.xml"]) } subject { isbn.gdata.data } it { should be_an_instance_of(RISBN::GData::BookData) } end end end
{ "content_hash": "c103ce664f1d45e581c9180525da2f46", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 90, "avg_line_length": 37.333333333333336, "alnum_prop": 0.6570378151260504, "repo_name": "EmmanuelOga/risbn", "id": "ab42558d20750a4cf4fa27f9b1b3261885d1df0d", "size": "1904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/gdata_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10959" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using System.Threading; using System; namespace QarnotSDK { /// <summary> /// This class manages tasks life cycle: submission, monitor, delete. /// </summary> public partial class QTaskSummary : AQTask { private AdvancedRanges _advancedRange = null; /// <summary> /// The task shortname identifier. The shortname is provided by the user. It has to be unique. /// </summary> public virtual string Shortname { get { return _taskApi.Shortname == null ? _taskApi.Uuid.ToString() : _taskApi.Shortname; } } /// <summary> /// The task name. /// </summary> public virtual string Name { get { return _taskApi.Name; } } /// <summary> /// The task profile. /// </summary> public virtual string Profile { get { return _taskApi.Profile; } } /// <summary> /// Retrieve the task state (see QTaskStates). /// Available only after the submission. /// </summary> public virtual string State { get { return _taskApi != null ? _taskApi.State : null; } } /// <summary> /// The task creation date. /// Available only after the submission. /// </summary> public virtual DateTime CreationDate { get { return _taskApi.CreationDate; } } /// <summary> /// The pool where the task is running or null if the task doesn't belong to a pool. /// </summary> public virtual QPool Pool { get { return (_taskApi.PoolUuid == null || _taskApi.PoolUuid == Guid.Empty.ToString()) ? null : new QPool(_api, new Guid(_taskApi.PoolUuid)); } } /// <summary> /// True if the task is completed or false if the task is still running or deploying. /// </summary> public virtual bool Completed { get { return State == QTaskStates.Success || State == QTaskStates.Failure || State == QTaskStates.Cancelled; } } /// <summary> /// True if the task is executing (PartiallyExecuting or FullyExecuting) or false if the task is in another state. /// </summary> public virtual bool Executing { get { return State == QTaskStates.PartiallyExecuting || State == QTaskStates.FullyExecuting; } } /// <summary> /// How many times this task have to run. /// </summary> public virtual uint InstanceCount { get { if (_advancedRange == null) return _taskApi.InstanceCount; else return _advancedRange.Count; } } /// <summary> /// Queue in-pool task execution behind pool resources update. /// </summary> /// <remarks> /// For an in-pool task, if set to true, any task submitted after a pool resources update will be sure to see /// the newer pool resources during its execution. The task will be queued until a pool slot with recent enough /// resources is available. /// Setting this to false will deactivate this behavior. /// If left null, then the pool's TaskDefaultWaitForPoolResourcesSynchronization value will be used. If both are /// null, then it will default to false. /// </remarks> /// <seealso cref="QPool.TaskDefaultWaitForPoolResourcesSynchronization" /> public virtual bool? WaitForPoolResourcesSynchronization { get { return _taskApi?.WaitForPoolResourcesSynchronization; } } internal QTaskSummary() { } internal QTaskSummary(Connection qapi, TaskApi taskApi) : base(qapi, taskApi) { } internal async new Task<QTaskSummary> InitializeAsync(Connection qapi, TaskApi taskApi) { await base.InitializeAsync(qapi, taskApi); _uri = "tasks/" + taskApi.Uuid.ToString(); await SyncFromApiObjectAsync(taskApi); return this; } internal async static Task<QTaskSummary> CreateAsync(Connection qapi, TaskApi taskApi) { return await new QTaskSummary().InitializeAsync(qapi, taskApi); } /// <summary> /// Delete the task. If the task is running, the task is aborted and deleted. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <param name="failIfDoesntExist">If set to false and the task doesn't exist, no exception is thrown. Default is true.</param> /// <param name="purgeResources">Boolean to trigger all resource storages deletion. Default is false.</param> /// <param name="purgeResults">Boolean to trigger result storage deletion. Default is false.</param> /// <returns></returns> public override async Task DeleteAsync(CancellationToken cancellationToken, bool failIfDoesntExist = false, bool purgeResources=false, bool purgeResults=false) { if (_api.IsReadOnly) throw new Exception("Can't delete tasks, this connection is configured in read-only mode"); // the summary task hasn't the resources and the results. (switching to fullTask for purging) if (purgeResources || purgeResults) { var fullTask = await GetFullQTaskAsync(cancellationToken); await fullTask.DeleteAsync(cancellationToken, failIfDoesntExist, purgeResources, purgeResults); } else { try { using(var response = await _api._client.DeleteAsync(_uri, cancellationToken)) await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken); } catch (QarnotApiResourceNotFoundException ex) { if (failIfDoesntExist) throw ex; } } } private async Task SyncFromApiObjectAsync(TaskApi result) { _taskApi = result; if (_taskApi.AdvancedRanges != null) _advancedRange = new AdvancedRanges(_taskApi.AdvancedRanges); else _advancedRange = null; await Task.FromResult(0); } #region helpers /// <summary> /// Enumeration on the task instance ids. /// Useful if an advanced range is used. /// </summary> public virtual IEnumerable<UInt32> Instances { get { if (_advancedRange != null) { foreach (var i in _advancedRange) yield return i; } else { for (UInt32 i = 0; i < _taskApi.InstanceCount; i++) yield return i; } } } #endregion /// <summary> /// Get The Full Task from this task summary. /// <param name="ct">Optional token to cancel the request.</param> /// </summary> public virtual async Task<QTask> GetFullQTaskAsync(CancellationToken ct = default(CancellationToken)) { using (var response = await _api._client.GetAsync(_uri, ct)) { await Utils.LookForErrorAndThrowAsync(_api._client, response, ct); var result = await response.Content.ReadAsAsync<TaskApi>(); return await QTask.CreateAsync(Connection, result); } } } }
{ "content_hash": "b92b4837c5efeac4d1aa063cb529416c", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 181, "avg_line_length": 42.94252873563219, "alnum_prop": 0.5930139186295503, "repo_name": "qarnot/qarnot-sdk-csharp", "id": "1856ca727b4c5cb073fcf72f6be92a29f29c51a1", "size": "7472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QarnotSDK/Sdk/TaskSummary.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "825409" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.github.jass2125</groupId> <artifactId>carrinho-de-compras-ejb</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>carrinho-de-compras-ejb</name> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> </dependencies> </project>
{ "content_hash": "57fdd9343b7cb6a83409b9bb2972af62", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 204, "avg_line_length": 33.88461538461539, "alnum_prop": 0.7094211123723042, "repo_name": "ifpb-disciplinas-2015-2/carrinho-compras-ejb-stateful", "id": "1e5578b1bfcee0ade0ab173c1aed08cab8fd09dc", "size": "881", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "target/m2e-wtp/web-resources/META-INF/maven/io.github.jass2125/carrinho-de-compras-ejb/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2688" } ], "symlink_target": "" }