identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/zzjtnb/Alive_Gist/blob/master/src/main.js
Github Open Source
Open Source
MIT
null
Alive_Gist
zzjtnb
JavaScript
Code
277
1,102
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import './registerServiceWorker' import util from './utils/util' import 'normalize.css' import 'material-design-icons/iconfont/material-icons.css' // 按需引入 import { Form, FormItem, Card, Button, Input, MessageBox, Message, Loading, Tag, Row, Col, Breadcrumb, BreadcrumbItem, Upload, Dialog, Pagination, ColorPicker, Table, TableColumn, Popover, Switch, } from 'element-ui' Vue.use(Form); Vue.use(FormItem); Vue.use(Card); Vue.use(Button); Vue.use(Input); Vue.use(Breadcrumb); Vue.use(BreadcrumbItem); Vue.use(Upload); Vue.use(Dialog); /** * Message不要用使用use引入,这样会在页面加载后没有进行任何操作,但是会自动弹出一次空的通知框 * Vue.use(Message); */ Vue.prototype.$message = Message; Vue.prototype.$confirm = MessageBox.confirm; Vue.use(Loading.directive); Vue.use(Tag); Vue.use(Row); Vue.use(Col); Vue.use(Pagination); Vue.use(ColorPicker); Vue.use(Table); Vue.use(TableColumn); Vue.use(Popover); Vue.use(Switch); /** * fastClick的300ms延迟 */ import FastClick from 'fastclick'; // 引入插件 FastClick.attach(document.body); // 使用 fastclick Vue.prototype.$util = util; Vue.config.productionTip = false /** * mavonEditor */ import mavonEditor from 'mavon-editor'; import 'mavon-editor/dist/css/index.css'; Vue.use(mavonEditor); Vue.prototype.$reload = function (context) { let NewPage = '/empty' context.$router.push(NewPage) context.$nextTick(() => (context.$router.go(-1))) } Vue.prototype.$markdown = function (value) { return mavonEditor.markdownIt.render(value) } /** * 设置title */ Vue.prototype.$setTitle = function (title) { if (title) { document.title = store.state.configuration.htmlTitle + ' - ' + title } else { document.title = store.state.configuration.htmlTitle } } /** * 分享文章 */ Vue.prototype.$share = function (message) { if (!message) { message = window.location } else { // let arr = (window.location + '').split('#') // message = arr[0] + '#' + message message = window.location.origin + message } if (util.copy(message)) { Vue.prototype.$confirm('链接已复制,去分享给好友吧!!', '分享', { showCancelButton: false, showClose: false, type: 'success' }) } else { Vue.prototype.$confirm('链接复制失败,可能因为浏览器不兼容', '分享', { showCancelButton: false, showClose: false, type: 'warning' }) } } //为文章详情添加代码高亮 Vue.directive('highlight', (el) => { let blocks = el.querySelectorAll('pre code'); blocks.forEach((block) => { hljs.highlightBlock(block) }) }) // 注册一个全局自定义指令 `v-focus` Vue.directive('focus', { // 当被绑定的元素插入到 DOM 中时…… inserted: function (el) { // 聚焦元素 el.focus() } }) new Vue({ router, store, render: h => h(App) }).$mount('#app')
23,031
https://github.com/NaohiroTamura/ironic-staging-drivers/blob/master/ironic_staging_drivers/intel_nm/nm_vendor.py
Github Open Source
Open Source
Apache-2.0
null
ironic-staging-drivers
NaohiroTamura
Python
Code
1,257
3,960
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import os from ironic.common import exception from ironic.drivers import base from ironic.drivers.modules import ipmitool from ironic_lib import utils as ironic_utils import jsonschema from jsonschema import exceptions as json_schema_exc from oslo_config import cfg from oslo_log import log from oslo_utils import excutils import six from ironic_staging_drivers.common.i18n import _ from ironic_staging_drivers.common.i18n import _LE from ironic_staging_drivers.common.i18n import _LI from ironic_staging_drivers.intel_nm import nm_commands CONF = cfg.CONF CONF.import_opt('tempdir', 'ironic.common.utils') LOG = log.getLogger(__name__) SCHEMAS = ('control_schema', 'get_cap_schema', 'main_ids_schema', 'policy_schema', 'suspend_schema', 'statistics_schema') def _command_to_string(cmd): """Convert a list with command raw bytes to string.""" return ' '.join(cmd) def _get_nm_address(task): """Get Intel Node Manager target channel and address. :param task: a TaskManager instance. :raises: IPMIFailure if Intel Node Manager is not detected on a node or if an error happens during detection. :returns: a tuple with IPMI channel and address of Intel Node Manager. """ node = task.node driver_internal_info = node.driver_internal_info def _save_to_node(channel, address): driver_internal_info['intel_nm_channel'] = channel driver_internal_info['intel_nm_address'] = address node.driver_internal_info = driver_internal_info node.save() channel = driver_internal_info.get('intel_nm_channel') address = driver_internal_info.get('intel_nm_address') if channel and address: return channel, address if channel is False and address is False: raise exception.IPMIFailure(_('Driver data indicates that Intel ' 'Node Manager detection failed.')) LOG.info(_LI('Start detection of Intel Node Manager on node %s'), node.uuid) sdr_filename = os.path.join(CONF.tempdir, node.uuid + '.sdr') res = None try: ipmitool.dump_sdr(task, sdr_filename) res = nm_commands.parse_slave_and_channel(sdr_filename) finally: ironic_utils.unlink_without_raise(sdr_filename) if res is None: _save_to_node(False, False) raise exception.IPMIFailure(_('Intel Node Manager is not detected.')) address, channel = res LOG.debug('Intel Node Manager sensors present in SDR on node %(node)s, ' 'channel %(channel)s address %(address)s.', {'node': node.uuid, 'channel': channel, 'address': address}) # SDR can contain wrong info, try simple command node.driver_info['ipmi_bridging'] = 'single' node.driver_info['ipmi_target_channel'] = channel node.driver_info['ipmi_target_address'] = address try: ipmitool.send_raw(task, _command_to_string(nm_commands.get_version(None))) _save_to_node(channel, address) return channel, address except exception.IPMIFailure: _save_to_node(False, False) raise exception.IPMIFailure(_('Intel Node Manager sensors record ' 'present in SDR but Node Manager is not ' 'responding.')) def _execute_nm_command(task, data, command_func, parse_func=None): """Execute Intel Node Manager command via send_raw(). :param task: a TaskManager instance. :param data: a dict with data passed to vendor's method. :param command_func: a function that returns raw command bytes. :param parse_func: a function that parses returned raw bytes. :raises: IPMIFailure if Intel Node Manager is not detected on a node or if an error happens during command execution. :returns: a dict with parsed output or None if command does not return user's info. """ try: channel, address = _get_nm_address(task) except exception.IPMIFailure as e: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Can not obtain Intel Node Manager address for ' 'node %(node)s: %(err)s'), {'node': task.node.uuid, 'err': six.text_type(e)}) driver_info = task.node.driver_info driver_info['ipmi_bridging'] = 'single' driver_info['ipmi_target_channel'] = channel driver_info['ipmi_target_address'] = address cmd = _command_to_string(command_func(data)) out = ipmitool.send_raw(task, cmd)[0] if parse_func: try: return parse_func(out.split()) except exception.IPMIFailure as e: with excutils.save_and_reraise_exception(): LOG.exception(_LE('Error in returned data for node %(node)s: ' '%(err)s'), {'node': task.node.uuid, 'err': six.text_type(e)}) class IntelNMVendorPassthru(base.VendorInterface): """Intel Node Manager policies vendor interface.""" def __init__(self): schemas_dir = os.path.dirname(__file__) for schema in SCHEMAS: filename = os.path.join(schemas_dir, schema + '.json') with open(filename, 'r') as sf: setattr(self, schema, json.load(sf)) def _validate_policy_methods(self, method, **kwargs): if method in ('get_nm_policy', 'remove_nm_policy', 'get_nm_policy_suspend', 'remove_nm_policy_suspend'): jsonschema.validate(kwargs, self.main_ids_schema) elif method == 'control_nm_policy': jsonschema.validate(kwargs, self.control_schema) if kwargs['scope'] != 'global' and 'domain_id' not in kwargs: raise exception.MissingParameterValue(_('Missing "domain_id"')) if kwargs['scope'] == 'policy' and 'policy_id' not in kwargs: raise exception.MissingParameterValue(_('Missing "policy_id"')) elif method == 'set_nm_policy': jsonschema.validate(kwargs, self.policy_schema) if kwargs['policy_trigger'] == 'boot': if not isinstance(kwargs['target_limit'], dict): raise exception.InvalidParameterValue(_('Invalid boot ' 'policy')) elif 'correction_time' not in kwargs: raise exception.MissingParameterValue( _('Missing "correction_time" for no-boot policy')) elif method == 'set_nm_policy_suspend': jsonschema.validate(kwargs, self.suspend_schema) elif method == 'get_nm_capabilities': jsonschema.validate(kwargs, self.get_cap_schema) def _validate_statistics_methods(self, method, **kwargs): jsonschema.validate(kwargs, self.statistics_schema) global_params = ('unhandled_requests', 'response_time', 'cpu_throttling', 'memory_throttling', 'communication_failures') if kwargs['scope'] == 'policy' and 'policy_id' not in kwargs: raise exception.MissingParameterValue(_('Missing "policy_id"')) if kwargs.get('parameter_name') not in global_params: if 'domain_id' not in kwargs: raise exception.MissingParameterValue(_('Missing "domain_id"')) if method == 'reset_nm_statistics': if 'parameter_name' in kwargs: if kwargs['parameter_name'] not in global_params: raise exception.InvalidParameterValue( _('Invalid parameter name for resetting statistic, ' 'individual reset is possible only for: %s') % ', '.join(global_params)) elif method == 'get_nm_statistics': if 'parameter_name' not in kwargs: raise exception.MissingParameterValue( _('Parameter name is mandatory for getting statistics')) # valid parameters depend on scope if (kwargs['parameter_name'] not in nm_commands.STATISTICS[kwargs['scope']]): raise exception.InvalidParameterValue( _('Invalid parameter name %(param)% for scope ' '%(scope)s') % {'param': kwargs['parameter_name'], 'scope': kwargs['scope']}) def get_properties(self): """Returns the properties of the interface..""" return {} def validate(self, task, method, http_method, **kwargs): """Validates the vendor method's parameters. This method validates whether the supplied data contains the required information for the driver. :param task: a TaskManager instance. :param method: name of vendor method. :param http_method: HTTP method. :param kwargs: data passed to vendor's method. :raises: InvalidParameterValue if supplied data is not valid. :raises: MissingParameterValue if parameters missing in supplied data. """ try: if 'statistics' in method: self._validate_statistics_methods(method, **kwargs) else: self._validate_policy_methods(method, **kwargs) except json_schema_exc.ValidationError as e: raise exception.InvalidParameterValue(_('Input data validation ' 'error: %s') % e) @base.passthru(['PUT']) def control_nm_policy(self, task, **kwargs): """Enable or disable Intel Node Manager policy control. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.control_policies) @base.passthru(['PUT']) def set_nm_policy(self, task, **kwargs): """Set Intel Node Manager policy. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.set_policy) @base.passthru(['GET'], async=False) def get_nm_policy(self, task, **kwargs): """Get Intel Node Manager policy. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. :returns: a dictionary containing policy settings. """ return _execute_nm_command(task, kwargs, nm_commands.get_policy, nm_commands.parse_policy) @base.passthru(['DELETE']) def remove_nm_policy(self, task, **kwargs): """Remove Intel Node Manager policy. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.remove_policy) @base.passthru(['PUT']) def set_nm_policy_suspend(self, task, **kwargs): """Set Intel Node Manager policy suspend periods. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.set_policy_suspend) @base.passthru(['GET'], async=False) def get_nm_policy_suspend(self, task, **kwargs): """Get Intel Node Manager policy suspend periods. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. :returns: a dictionary containing suspend info for a policy. """ return _execute_nm_command(task, kwargs, nm_commands.get_policy_suspend, nm_commands.parse_policy_suspend) @base.passthru(['DELETE']) def remove_nm_policy_suspend(self, task, **kwargs): """Remove Intel Node Manager policy suspend periods. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.remove_policy_suspend) @base.passthru(['GET'], async=False) def get_nm_capabilities(self, task, **kwargs): """Get Intel Node Manager capabilities. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. :returns: a dictionary containing Intel NM capabilities. """ return _execute_nm_command(task, kwargs, nm_commands.get_capabilities, nm_commands.parse_capabilities) @base.passthru(['GET'], async=False) def get_nm_version(self, task, **kwargs): """Get Intel Node Manager version. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. :returns: a dictionary containing Intel NM version. """ return _execute_nm_command(task, kwargs, nm_commands.get_version, nm_commands.parse_version) @base.passthru(['GET'], async=False) def get_nm_statistics(self, task, **kwargs): """Get Intel Node Manager statistics. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. :returns: a dictionary containing statistics info. """ return _execute_nm_command(task, kwargs, nm_commands.get_statistics, nm_commands.parse_statistics) @base.passthru(['PUT']) def reset_nm_statistics(self, task, **kwargs): """Reset Intel Node Manager statistics. :param task: a TaskManager instance. :param kwargs: data passed to method. :raises: IPMIFailure on an error. """ _execute_nm_command(task, kwargs, nm_commands.reset_statistics)
25,731
https://github.com/rirwin/sandbox/blob/master/dns-perf-mon/dns_perf_mon.cpp
Github Open Source
Open Source
MIT
null
sandbox
rirwin
C++
Code
572
1,889
#include <stdio.h> #include <getopt.h> #include <stdlib.h> #include <string> #include <pthread.h> #include <iostream> #include <vector> #include "MySQLQueryHandler.hpp" #include "DNSQueryHandler.hpp" /** * Parsing/usage functions */ char *progname; static void usage(); static void parse_args(int, char**,int*, int*); /** * function for calling dns query threads */ void* dns_query_thread_function(void *arg); /** * main */ int main(int argc, char *argv[]) { // variables for arguments to program int freq_ms, num_queries; parse_args(argc, argv, &freq_ms, &num_queries); printf("Query once every %d ms for a total of %d queries\n", freq_ms, num_queries); // vector containing the domain names as strings // could use c++11 to make this faster std::vector<std::string> dom_str_vec; dom_str_vec.push_back("google.com"); dom_str_vec.push_back("facebook.com"); dom_str_vec.push_back("youtube.com"); dom_str_vec.push_back("yahoo.com"); dom_str_vec.push_back("live.com"); dom_str_vec.push_back("wikipedia.org"); dom_str_vec.push_back("baidu.com"); dom_str_vec.push_back("blogger.com"); dom_str_vec.push_back("msn.com"); dom_str_vec.push_back("qq.com"); int num_domains = dom_str_vec.size(); // Initialize database called thousandeyes with a table // for each domain to be queried MySQLQueryHandler *mysql_handler = new MySQLQueryHandler("dns_perf_mon_db",dom_str_vec); // A container of DNS query handlers std::vector<DNSQueryHandler*> dns_handlers; // Initialize container for (int dom_idx = 0; dom_idx < num_domains; dom_idx++) { DNSQueryHandler *handler = new DNSQueryHandler(dom_str_vec[dom_idx], freq_ms, num_queries, mysql_handler); dns_handlers.push_back(handler); } // threads for handling pthread_t dns_query_threads[num_domains]; for (int domain_idx = 0; domain_idx < num_domains; domain_idx++) { pthread_create(&dns_query_threads[domain_idx], NULL, dns_query_thread_function, (void *) dns_handlers[domain_idx]); } // Join the threads and check the status for (int domain_idx = 0; domain_idx < num_domains; domain_idx++) { void *status; pthread_join(dns_query_threads[domain_idx], &status); if ((int)status != 0){ std::cout << "Non-zero status " << (int)status << " for " << dom_str_vec[domain_idx] << std::endl; } else { std::cout << "Joined thread for " << dom_str_vec[domain_idx] << std::endl; std::cout << dns_handlers[domain_idx]->get_num_queries_performed() << " Queries performed" << std::endl; } } // Print out final stats for all domains mysql_handler->print_all_stats_summaries(); // Free memory for (int i = 0; i < num_domains; i++) { delete dns_handlers[i]; } delete mysql_handler; return 0; } /** * dns query thread function passed when creating threads */ void* dns_query_thread_function(void *arg) { DNSQueryHandler *dns_qh; dns_qh = (DNSQueryHandler*) arg; if (dns_qh) { int query_freq_ms = dns_qh->get_query_freq_ms(); int num_queries_to_perform = dns_qh->get_num_queries_to_perform(); for (int query_i = 0; query_i < num_queries_to_perform; query_i++) { std::cout << "launching query " << dns_qh->get_num_queries_performed()+1; std::cout << " to " << dns_qh->get_dom_str() << std::endl; int query_time_ms = dns_qh->perform_query(); // print warning if query time > sleep period (frequency) if (query_freq_ms - (double)query_time_ms > 0) { usleep(1000*((double)query_freq_ms - (double)query_time_ms)); } else { std::cout << "WARNING: query response time for " << dns_qh->get_dom_str() << " exceeded query interval time (frequency)" << std::endl; } } return (int*)0; } return (int*)1; } /** * handles arguments in long form */ static struct option longopts [] = { { "help", no_argument, NULL, 'h' }, { "frequency", required_argument, NULL, 'f' }, { "num-queries", required_argument, NULL, 'n' } }; static void usage(){ printf("usage: %s -f <int> -n <int>\n",progname); printf("-f <int> the frequency with which to query, (default is 1000 ms) \n"); printf("-n <int> the number of times to query (default is 10) \n"); printf("-h|? this help message\n"); } /** * Parses arguments for frequency and number of queries */ static void parse_args (int argc, char *argv[], int *freq_ms, int *num_queries) { progname = argv[0]; int opt; *freq_ms = 0; *num_queries = 0; while(opt = getopt_long(argc, argv, "hf:n:", longopts, (int*)NULL), opt != EOF) { switch(opt) { case 'h': usage(); break; case 'f': *freq_ms = atoi(optarg); if(*freq_ms <= 0) usage(); break; case 'n': *num_queries = atoi(optarg); if(*num_queries <= 0) usage(); break; default: usage(); break; } } if (*freq_ms <= 0 && *num_queries <= 0) { usage(); } if(*freq_ms <= 0) { *freq_ms = 1000; } if(*num_queries <= 0) { *num_queries = 10; } }
29,461
https://github.com/johan-gorter/Instantlogic/blob/master/instantlogic-fabric/src/main/java/org/instantlogic/fabric/model/Entity.java
Github Open Source
Open Source
MIT
null
Instantlogic
johan-gorter
Java
Code
680
2,334
package org.instantlogic.fabric.model; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import org.instantlogic.fabric.Instance; import org.instantlogic.fabric.text.TextTemplate; /** * Can be compared to a Class, only more powerful */ public abstract class Entity<I extends Instance> extends Concept { private static final Entity<?>[] NO_ENTITIES = new Entity[0]; public static boolean extendsFrom(Entity<?> entity, Entity<?> from) { if (entity==from) return true; if (entity==null) return false; return extendsFrom(entity.extendsEntity(), from); } private static class BaseEntityFirstIterable<E> implements Iterable<E> { private Iterable<E> baseEntityIterator; private E[] items; public BaseEntityFirstIterable(Iterable<E> baseEntityIterator, E[] items) { this.baseEntityIterator = baseEntityIterator; this.items = items; } @Override public Iterator<E> iterator() { return new BaseEntityFirstIterator<E>(baseEntityIterator, items); } } private static class BaseEntityFirstIterator<E> implements Iterator<E> { private Iterator<E> baseEntityIterator; private E[] items; private int index = 0; public BaseEntityFirstIterator(Iterable<E> baseEntityIterator, E[] items) { if (baseEntityIterator!=null) { this.baseEntityIterator = baseEntityIterator.iterator(); } this.items = items; } @Override public boolean hasNext() { if (baseEntityIterator!=null) { boolean hasNext = baseEntityIterator.hasNext(); if (hasNext) { return true; } else { baseEntityIterator = null; } } return index<items.length; } @Override public E next() { if (baseEntityIterator!=null) { return baseEntityIterator.next(); } return items[index++]; } @Override public void remove() { throw new UnsupportedOperationException("Not implemented"); } } public TextTemplate getTitle() { return null; } // TODO: Allow multiple inheritance (Java code generation: generate Instance classes + interfaces and implement all baseclass-interfaces instead of extending baseclass) public Entity<?> extendsEntity() { return null; } public Entity<?>[] extensions() { return NO_ENTITIES; } public abstract Attribute<I, ? extends Object, ? extends Object>[] getLocalAttributes(); public abstract Relation<I, ? extends Object, ? extends Instance>[] getLocalRelations(); public abstract Relation<? extends Instance, ? extends Object, I>[] getLocalReverseRelations(); public Validation[] getLocalValidations() { // TODO: make abstract return new Validation[0]; } public abstract I createInstance(); public abstract Class<I> getInstanceClass(); @SuppressWarnings({ "rawtypes", "unchecked" }) public final Iterable<Attribute<I, ? extends Object, ? extends Object>> getAttributes() { Entity<?> extendsEntity = extendsEntity(); Iterable<?> baseEntityIterator=null; if (extendsEntity!=null) { baseEntityIterator = (Iterable<?>)extendsEntity.getAttributes(); } return new BaseEntityFirstIterable(baseEntityIterator, getLocalAttributes()); } @SuppressWarnings({ "unchecked", "rawtypes" }) public final Iterable<Relation<I, ? extends Object, ? extends Instance>> getRelations() { Entity<?> extendsEntity = extendsEntity(); Iterable<?> baseEntityIterator=null; if (extendsEntity!=null) { baseEntityIterator = (Iterable<?>)extendsEntity.getRelations(); } return new BaseEntityFirstIterable(baseEntityIterator, getLocalRelations()); } @SuppressWarnings({ "unchecked", "rawtypes" }) public final Iterable<Relation<? extends Instance, ? extends Object, I>> getReverseRelations() { Entity<?> extendsEntity = extendsEntity(); Iterable<?> baseEntityIterator=null; if (extendsEntity!=null) { baseEntityIterator = extendsEntity.getReverseRelations(); } return new BaseEntityFirstIterable(baseEntityIterator, getLocalReverseRelations()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public final Iterable<Validation> getValidations() { Entity<?> extendsEntity = extendsEntity(); Iterable<?> baseEntityIterator=null; if (extendsEntity!=null) { baseEntityIterator = (Iterable<?>)extendsEntity.getValidations(); } return new BaseEntityFirstIterable(baseEntityIterator, getLocalValidations()); } protected I addStaticInstance(String name, I instance) { instance.getMetadata().makeStatic(name); return instance; } @SuppressWarnings("unchecked") public Map<String, I> getStaticInstances() { return Collections.EMPTY_MAP; } // Convenience method for obtaining an attribute @SuppressWarnings("rawtypes") public Attribute getAttribute(String attributeName) { for (Attribute attribute: getAttributes()) { if (attributeName.equals(attribute.getName())) { return attribute; } } throw new NoSuchElementException(attributeName); } @SuppressWarnings("rawtypes") public Attribute tryGetAttribute(String attributeName) { for (Attribute attribute: getAttributes()) { if (attributeName.equals(attribute.getName())) { return attribute; } } return null; } // Convenience method for obtaining an attribute @SuppressWarnings("rawtypes") public Relation getRelation(String relationName) { for (Relation relation: getRelations()) { if (relationName.equals(relation.getName())) { return relation; } } throw new NoSuchElementException(relationName); } // Convenience method for obtaining an attribute @SuppressWarnings("rawtypes") public Relation tryGetRelation(String relationName) { for (Relation relation: getRelations()) { if (relationName.equals(relation.getName())) { return relation; } } return null; } @SuppressWarnings("rawtypes") public Attribute getAttributeOrRelation(String name) { for (Attribute attribute: getLocalAttributes()) { if (name.equals(attribute.getName())) { return attribute; } } for (Attribute attribute: getLocalRelations()) { if (name.equals(attribute.getName())) { return attribute; } } for (Attribute attribute: getLocalReverseRelations()) { if (name.equals(attribute.getName())) { return attribute; } } if (extendsEntity()!=null) { return extendsEntity().getAttributeOrRelation(name); } throw new NoSuchElementException(name); } @SuppressWarnings("rawtypes") public Attribute getAttributeOrRelationById(String id) { for (Attribute attribute: getLocalAttributes()) { if (id.equals(attribute.getUniqueId())) { return attribute; } } for (Attribute attribute: getLocalRelations()) { if (id.equals(attribute.getUniqueId())) { return attribute; } } for (Attribute attribute: getLocalReverseRelations()) { if (id.equals(attribute.getUniqueId())) { return attribute; } } if (extendsEntity()!=null) { return extendsEntity().getAttributeOrRelationById(id); } throw new NoSuchElementException(id); } @SuppressWarnings("rawtypes") public Relation getRelationById(String relationId) { for (Relation relation: getRelations()) { if (relationId.equals(relation.getUniqueId())) { return relation; } } return null; } @SuppressWarnings("rawtypes") public Attribute getAttributeById(String attributeId) { for (Attribute attribute: getAttributes()) { if (attributeId.equals(attribute.getUniqueId())) { return attribute; } } return null; } }
28,644
https://github.com/wanchopeblanco/Buscocasa/blob/master/resources/views/admin/listing-types/index.blade.php
Github Open Source
Open Source
MIT
null
Buscocasa
wanchopeblanco
PHP
Code
228
1,144
@extends('layouts.master') @section('head') <title>Listing Types - {{ Settings::get('site_name') }}</title> @endsection @section('css') @parent <link href="{{ asset('/css/floatinglabel.css') }}" rel="stylesheet"> @endsection @section('content') <div class="uk-container uk-container-center uk-margin-top"> <div class="uk-panel"> <h3 class="uk-panel-title">Listing Types</h3> <hr> <div class=""> <!-- This is a button toggling the modal --> <button class="uk-button" data-uk-modal="{target:'#new_object_modal'}">New</button> <button class="uk-button uk-button-danger" onclick="deleteObjects()"><i class="uk-icon-trash"></i></button> </div> <div class="uk-panel uk-panel-box uk-margin-top"> <table class="uk-table uk-table-hover uk-table-striped"> <thead> <tr> <th style="width:15px"><input type="checkbox" id="checkedLineHeader" onclick="toggle(this)"/></th> <th style="width:15px">id</th> <th style="width:20px">Published</th> <th>Name</th> <th style="width:120px">Actions</th> </tr> </thead> <tbody> @foreach($types as $type) <tr> <td><input type="checkbox" name="checkedLine" value="{{$type->id}}"/></td> <td>{{ $type->id }}</td> <td class="uk-text-center">@if($type->published)<i class="uk-icon-check"></i>@else<i class="uk-icon-remove"></i>@endif</td> <td>{{ $type->name }}</td> <td> <!-- This is the container enabling the JavaScript --> <div class="uk-button-dropdown" data-uk-dropdown> <!-- This is the button toggling the dropdown --> <button class="uk-button">Actions <i class="uk-icon-caret-down"></i></button> <!-- This is the dropdown --> <div class="uk-dropdown uk-dropdown-small"> <ul class="uk-nav uk-nav-dropdown"> <li><a href="bikes/types/{{ $type->id }}">Edit</a></li> <li><a href="bikes/types/clone/{{ $type->id }}">Clone</a></li> <li><a id="{{ $type->id }}" onclick="deleteObject(this)">Delete</a></li> </ul> </div> </div> </td> </tr> @endforeach </tbody> </table> <?php echo $types->render(); ?> </div> @include('admin.listing-types.new') </div> </div> @endsection @section('js') @parent <script src="{{ asset('/js/floatinglabel.min.js') }}"></script> <script type="text/javascript"> $('#create_form').floatinglabel({ ignoreId: ['ignored'] }); function toggle(source){ checkboxes = document.getElementsByName('checkedLine'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } function deleteObject(sender) { $.post("{{ url('/admin/feature-categories') }}/" + sender.id, {_token: "{{ csrf_token() }}", _method:"DELETE"}, function(result){ location.reload(); }); } function deleteObjects() { var checkedValues = $('input[name="checkedLine"]:checked').map(function() { return this.value; }).get(); $.post("{{ url('/admin/feature-categories/delete') }}", {_token: "{{ csrf_token() }}", ids: checkedValues}, function(result){ location.reload(); }); } </script> @endsection
33,531
https://github.com/dg227/NLSA/blob/master/nlsa/classes/@nlsaKoopmanOperator/getFDOrder.m
Github Open Source
Open Source
BSD-3-Clause
2,023
NLSA
dg227
MATLAB
Code
45
93
function res = getFDOrder( obj ) % GEFDORDER Returns finite-differnce order of an array of nlsaKoopmanOperator % objects. % % Modified 2020/04/09 res = zeros( size( obj ) ); for iObj = 1 : numel( obj ) res( iObj ) = obj( iObj ).fdOrd; end
14,165
https://github.com/hyb1234hi/bitnotify/blob/master/bitnotify/management/commands/bitnotify_cron.py
Github Open Source
Open Source
MIT
2,017
bitnotify
hyb1234hi
Python
Code
24
77
from django.core.management.base import BaseCommand from bitnotify.cron import cron class Command(BaseCommand): help = 'Run bitnotify cron task defined in bitnotify/cron.py' def handle(self, *args, **options): cron()
46,320
https://github.com/srghma/purescript-ocelot/blob/master/src/Blocks/ToggleButton.purs
Github Open Source
Open Source
Apache-2.0
2,022
purescript-ocelot
srghma
PureScript
Code
132
466
module Ocelot.Block.ToggleButton where import Prelude import DOM.HTML.Indexed (HTMLinput, HTMLspan) import Halogen.HTML as HH import Halogen.HTML.Properties as HP import Ocelot.HTML.Properties ((<&>)) toggleButton :: ∀ p i . Array (HH.IProp HTMLspan i) -> Array (HH.IProp HTMLinput i) -> Array (HH.HTML p i) -> HH.HTML p i toggleButton iprops inprops html = HH.label_ [ HH.input inputProps , HH.span labelProps html ] where inputProps = [ HP.classes inputClasses , HP.type_ HP.InputRadio ] <&> inprops labelProps = [ HP.classes toggleButtonClasses ] <&> iprops inputClasses :: Array HH.ClassName inputClasses = HH.ClassName <$> [ "checked:neighbor:bg-grey-50" , "checked:neighbor:text-white" , "checked:neighbor:border-grey-50" , "!checked:neighbor:hover:bg-grey-80" , "!checked:neighbor:hover:text-black-10!" , "offscreen" ] toggleButtonClasses :: Array HH.ClassName toggleButtonClasses = HH.ClassName <$> [ "no-outline" , "px-4" , "py-2" , "disabled:opacity-50" , "disabled:cursor-default" , "!disabled:cursor-pointer" , "bg-white" , "border-grey-80" , "border-2" , "focus:bg-grey-50-a30" , "text-black-20" , "inline-block" ]
1,593
https://github.com/capagot/swpathtracer/blob/master/primitives/smooth_triangle.cpp
Github Open Source
Open Source
MIT
2,022
swpathtracer
capagot
C++
Code
33
132
#include "smooth_triangle.h" SmoothTriangle::SmoothTriangle(const glm::vec3 &v0, const glm::vec3 &v1, const glm::vec3 &v2, const glm::vec3 &n0, const glm::vec3 &n1, const glm::vec3 &n2, long unsigned int material_id) : Triangle(v0, v1, v2, material_id), n0_(n0), n1_(n1), n2_(n2) {}
41,362
https://github.com/ahmedChaari/ask-blog/blob/master/resources/js/components/askHome.vue
Github Open Source
Open Source
MIT
2,020
ask-blog
ahmedChaari
Vue
Code
46
203
<template> <v-parallax dark src="https://cdn.vuetifyjs.com/images/backgrounds/vbanner.jpg" height="700" > <v-row align="center" justify="center" > <v-col class="text-center" cols="12"> <h1 class="display-1 font-weight-thin mb-4">Ask question in informatique</h1> <h4 class="subheading">ce site vous permet de poser des question <br> dans le monde informatique</h4> </v-col> </v-row> </v-parallax> </template> <script> export default { } </script> <style> </style>
45,421
https://github.com/ladenedge/FluentNHibernate.Cfg.Db.CsharpSqlite/blob/master/CsSQLiteConfiguration.cs
Github Open Source
Open Source
CC-PDDC, LicenseRef-scancode-public-domain
2,013
FluentNHibernate.Cfg.Db.CsharpSqlite
ladenedge
C#
Code
69
237
using FluentNHibernate.Cfg.Db; using NHibernate.Dialect; namespace FluentNHibernate.Cfg.Db.CsharpSqlite { /// <summary> /// Fluent configuration for the C#-SQLite driver. /// </summary> public class CsharpSqliteConfiguration : SQLiteConfiguration { /// <summary> /// Instantiates a new configuration object. /// </summary> public CsharpSqliteConfiguration() { Driver<CsharpSqliteDriver>(); Dialect<SQLiteDialect>(); Raw("query.substitutions", "true=1;false=0"); } /// <summary> /// Gets a default instantiation of the class. /// </summary> public static new CsharpSqliteConfiguration Standard { get { return new CsharpSqliteConfiguration(); } } } }
39,174
https://github.com/Northeastern-University-Blockchain/NeuCheck/blob/master/src/main/java/ru/smartdec/soliditycheck/Version.java
Github Open Source
Open Source
MIT
2,021
NeuCheck
Northeastern-University-Blockchain
Java
Code
180
425
package ru.smartdec.soliditycheck; import java.util.Collections; import java.util.List; /** * */ public final class Version implements Comparable<Version> { /** * @param list list * @param index index * @param value default value * @param <T> list element type * @return element at the specified position or default value */ private static <T> T getOrDefault( final List<T> list, final int index, final T value) { T result = value; if (index < list.size()) { result = list.get(index); } return result; } /** * */ private final List<Integer> value; /** * @param val value */ public Version(final List<Integer> val) { this.value = val; } /** * @param val value */ public Version(final Integer val) { this(Collections.singletonList(val)); } @Override public int compareTo(final Version other) { int result = 0; final int size = Math.max(this.value.size(), other.value.size()); for (int index = 0; index < size; index++) { final int first = getOrDefault(this.value, index, 0); final int second = getOrDefault(other.value, index, 0); if (first < second) { result = -1; break; } else if (first > second) { result = 1; break; } } return result; } }
44,074
https://github.com/tniraj7/Nettofurixu/blob/master/Nettofurixu/Nettofurixu/Views/EpisodeView.swift
Github Open Source
Open Source
MIT
null
Nettofurixu
tniraj7
Swift
Code
137
574
import SwiftUI struct EpisodeView: View { var episodes: [Episode] @Binding var showSeasonPicker: Bool @Binding var selectedSeason : Int func getEpisodesForSeason(forSeason season: Int) -> [Episode] { return episodes.filter({ $0.season == season}) } var body: some View { VStack(spacing: 14) { HStack { Button(action: { showSeasonPicker = true }, label: { Group { Text("Season \(selectedSeason)") Image(systemName: "chevron.down") } .font(.system(size: 16)) }) Spacer() } ForEach(getEpisodesForSeason(forSeason: selectedSeason)) { episode in VStack { HStack { VideoPreviewImage(imageURL: episode.thumbnailURL, videoURL: episode.videoURL) .frame(width: 120, height: 70) .clipped() VStack(alignment: .leading) { Text("\(episode.episodeNumber). \(episode.name)") .font(.system(size: 16)) Text("Episode Info: \(episode.length)m") .font(.system(size: 12)) .foregroundColor(.gray) } Spacer() Image(systemName: "arrow.down.to.line.alt") .font(.system(size: 20)) } Text(episode.description) .font(.system(size: 13)) .lineLimit(3) } .padding(.bottom, 20) } Spacer() } .foregroundColor(.white) .padding(.horizontal, 20) } } struct EpisodeView_Previews: PreviewProvider { static var previews: some View { EpisodeView(episodes: [episode1, episode2, episode3], showSeasonPicker: .constant(false), selectedSeason: .constant(1)) .preferredColorScheme(.dark) .previewLayout(.sizeThatFits) .padding() } }
18,017
https://github.com/chenpx976/cnpmcore/blob/master/app/schedule/CreateSyncBinaryTask.ts
Github Open Source
Open Source
MIT
2,022
cnpmcore
chenpx976
TypeScript
Code
92
262
import { Subscription } from 'egg'; import { BinarySyncerService } from '../core/service/BinarySyncerService'; import binaries from '../../config/binaries'; const cnpmcoreCore = 'cnpmcoreCore'; export default class CreateSyncBinaryTask extends Subscription { static get schedule() { return { // every 5 mins interval: 60000 * 5, type: 'worker', }; } async subscribe() { const { ctx, app } = this; if (!app.config.cnpmcore.enableSyncBinary) return; await ctx.beginModuleScope(async () => { const binarySyncerService: BinarySyncerService = ctx.module[cnpmcoreCore].binarySyncerService; for (const binary of Object.values(binaries)) { if (app.config.env === 'unittest' && binary.category !== 'node') continue; if (binary.disable) continue; await binarySyncerService.createTask(binary.category); } }); } }
14,916
https://github.com/shrikar007/customer-rest-api/blob/master/go.mod
Github Open Source
Open Source
MIT
2,020
customer-rest-api
shrikar007
Go Module
Code
15
106
module github.com/shrikar007/customer-rest-api go 1.12 require ( github.com/go-chi/chi v4.1.1+incompatible github.com/go-chi/render v1.0.1 github.com/go-sql-driver/mysql v1.5.0 github.com/jinzhu/gorm v1.9.12 )
24,378
https://github.com/worph/WFS/blob/master/src/main/java/net/worph/filesytem/nio/WFSNIOFileSystem.java
Github Open Source
Open Source
Apache-2.0
2,015
WFS
worph
Java
Code
192
666
package net.worph.filesytem.nio; import java.io.IOException; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.WatchService; import java.nio.file.attribute.UserPrincipalLookupService; import java.nio.file.spi.FileSystemProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.worph.filesytem.FileSystemLayer.wfsName.WFSName; /** * * @author Worph */ public class WFSNIOFileSystem extends FileSystem{ WFSName fileSystem; FileSystemProvider provider; boolean open; Path root; public WFSNIOFileSystem(WFSName fileSystem, FileSystemProvider provider) { this.fileSystem = fileSystem; this.provider = provider; open = true; } @Override public FileSystemProvider provider() { return provider; } @Override public void close() throws IOException { fileSystem.close(); } @Override public boolean isOpen() { return open; } @Override public boolean isReadOnly() { return false; } @Override public String getSeparator() { return "/"; } @Override public Iterable<Path> getRootDirectories() { return Arrays.asList(root); } @Override public Iterable<FileStore> getFileStores() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<String> supportedFileAttributeViews() { return new HashSet<>(); } @Override public Path getPath(String first, String... more) { ArrayList<String> newArray = new ArrayList<>(); newArray.add(first); newArray.addAll(Arrays.asList(more)); return new WFSNIOPath(this, newArray); } /* no */ @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException("Not supported yet."); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { throw new UnsupportedOperationException("Not supported yet."); } @Override public WatchService newWatchService() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }
46,270
https://github.com/treymerkley/minetest-mods/blob/master/tsm_railcorridors/gameconfig.lua
Github Open Source
Open Source
MIT
2,018
minetest-mods
treymerkley
Lua
Code
423
1,144
-- This file stores the various node types. This makes it easier to plug this mod into subgames -- in which you need to change the node names. -- Node names (Don't use aliases!) tsm_railcorridors.nodes = { dirt = "default:dirt", chest = "default:chest", rail = "default:rail", torch_floor = "default:torch", torch_wall = "default:torch_wall", --[[ Wood types for the corridors. Corridors are made out of full wood blocks and posts. For each corridor system, a random wood type is chosen with the chance specified in per mille. ]] corridor_woods = { { wood = "default:wood", post = "default:fence_wood", chance = 800}, { wood = "default:junglewood", post = "default:fence_junglewood", chance = 150}, { wood = "default:acacia_wood", post = "default:fence_acacia_wood", chance = 45}, { wood = "default:pine_wood", post = "default:fence_pine_wood", chance = 3}, { wood = "default:aspen_wood", post = "default:fence_aspen_wood", chance = 2}, }, } -- List of cart entities. Carts will be placed randomly of the right-hand or left side of -- the main rail. tsm_railcorridors.carts = {} if minetest.get_modpath("carts") then table.insert(tsm_railcorridors.carts, "carts:cart") end if minetest.get_modpath("mobs_monster") then tsm_railcorridors.nodes.cobweb = "mobs:cobweb" -- This is for subgames to add their spawner node. No spawner is added by default -- because Mobs Redo's mob spawner is still unfinished. -- If you set this, you MUST also set tsm_railcorridors.place_spawner. tsm_railcorridors.nodes.spawner = nil end -- This is called after a spawner has been placed by the game. -- Use this to properly set up the metadata and stuff. -- This is needed for subgames if they include mob spawners. function tsm_railcorridors.on_construct_spawner(pos) end -- This is called after a cart has been placed by the game. -- Use this to properly set up entity metadata and stuff. -- * pos: Position of cart -- * cart: Cart entity function tsm_railcorridors.on_construct_cart(pos, cart) end -- Fallback function. Returns a random treasure. This function is called for chests -- only if the Treasurer mod is not found. -- pr: A PseudoRandom object function tsm_railcorridors.get_default_treasure(pr) if pr:next(0,1000) < 30 then return "farming:bread "..pr:next(1,3) elseif pr:next(0,1000) < 50 then if pr:next(0,1000) < 500 then return "farming:seed_cotton "..pr:next(1,5) else return "farming:seed_wheat "..pr:next(1,5) end elseif pr:next(0,1000) < 5 then return "tnt:tnt "..pr:next(1,3) elseif pr:next(0,1000) < 5 then return "default:pick_steel" elseif pr:next(0,1000) < 3 then local r = pr:next(0, 1000) if r < 400 then return "default:steel_ingot "..pr:next(1,5) elseif r < 700 then return "default:gold_ingot "..pr:next(1,3) elseif r < 900 then return "default:mese_crystal "..pr:next(1,3) else return "default:diamond "..pr:next(1,2) end elseif pr:next(0,1000) < 30 then return "default:torch "..pr:next(1,16) elseif pr:next(0,1000) < 20 then return "default:coal_lump "..pr:next(3,8) else return "" end end
3,374
https://github.com/ajyan/list.en/blob/master/client/src/components/Playlists.js
Github Open Source
Open Source
Apache-2.0
2,020
list.en
ajyan
JavaScript
Code
51
184
import React from 'react'; function Playlists(props) { return ( <div className="box is-primary column" id="playlistContainer"> {props.playlists && props.playlists.map((playlist, i) => { return ( <div key={i}> <br /> <div id={i} className="button is-large is-primary playlistButtons" onClick={(e) => { props.handlePlaylistChange(e.currentTarget.id); }} > {playlist.name} </div> <br /> </div> ); })} </div> ); } export default Playlists;
6,557
https://github.com/maichong/alaska/blob/master/packages/alaska-email/locales/zh-CN/messages.js
Github Open Source
Open Source
MIT
2,018
alaska
maichong
JavaScript
Code
58
245
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { Subject: '主题', Driver: '驱动', 'Test Template Variables': '测试模板值', 'Test Send To': '测试发送到', 'Test Send': '测试发送', 'Email Task': '邮件任务', Ready: '就绪', Running: '运行中', Run: '运行', Pause: '暂停', Resume: '继续', Complete: '完成', Interval: '间隔', Filters: '过滤器', Seconds: '秒', Progress: '进度', Total: '总数', 'Last User': '用户', 'Next At': '下次时间' };
32,635
https://github.com/eric-erki/waltz/blob/master/waltz-web/src/main/java/com/khartec/waltz/web/endpoints/api/EntitySearchEndpoint.java
Github Open Source
Open Source
Apache-2.0
null
waltz
eric-erki
Java
Code
212
673
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ package com.khartec.waltz.web.endpoints.api; import com.khartec.waltz.model.EntityReference; import com.khartec.waltz.model.entity_search.EntitySearchOptions; import com.khartec.waltz.model.entity_search.ImmutableEntitySearchOptions; import com.khartec.waltz.service.entity_search.EntitySearchService; import com.khartec.waltz.web.ListRoute; import com.khartec.waltz.web.endpoints.Endpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import static com.khartec.waltz.common.Checks.checkNotNull; import static com.khartec.waltz.web.WebUtilities.*; import static com.khartec.waltz.web.endpoints.EndpointUtilities.postForList; @Service public class EntitySearchEndpoint implements Endpoint { private static final Logger LOG = LoggerFactory.getLogger(EntitySearchEndpoint.class); private static final String BASE_URL = mkPath("api", "entity-search"); private final EntitySearchService entitySearchService; @Autowired public EntitySearchEndpoint(EntitySearchService entitySearchService) { checkNotNull(entitySearchService, "entitySearchService cannot be null"); this.entitySearchService = entitySearchService; } @Override public void register() { String searchPath = mkPath(BASE_URL); ListRoute<EntityReference> searchRoute = (request, response) -> { String username = getUsername(request); EntitySearchOptions entitySearchOptions = readBody(request, EntitySearchOptions.class); return entitySearchService.search( ImmutableEntitySearchOptions .copyOf(entitySearchOptions) .withUserId(username)); }; postForList(searchPath, searchRoute); } }
26,642
https://github.com/michelada/ektar/blob/master/test/mailers/ektar/reset_password_mailer_test.rb
Github Open Source
Open Source
MIT
2,021
ektar
michelada
Ruby
Code
39
139
# typed: ignore # frozen_string_literal: true require "test_helper" module Ektar class ResetPasswordMailerTest < ActionMailer::TestCase test "reset" do user = ektar_users(:user) user.update(reset_password_token: "8383833") host = "https://ektar.io" subject = ResetPasswordMailer.with(host: host, user: user).reset assert_emails 1 do subject.deliver_now end end end end
8,569
https://github.com/twillouer/metrics/blob/master/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java
Github Open Source
Open Source
Apache-2.0
2,021
metrics
twillouer
Java
Code
314
1,430
package com.codahale.metrics.httpclient5; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.MetricRegistryListener; import com.codahale.metrics.Timer; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; import org.apache.hc.client5.http.async.methods.SimpleHttpRequests; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.ConnectionClosedException; import org.apache.hc.core5.http.HttpRequest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class InstrumentedHttpAsyncClientsTest { @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock private HttpClientMetricNameStrategy metricNameStrategy; @Mock private MetricRegistryListener registryListener; private HttpServer httpServer; private MetricRegistry metricRegistry; private CloseableHttpAsyncClient client; @Before public void setUp() throws IOException { httpServer = HttpServer.create(new InetSocketAddress(0), 0); metricRegistry = new MetricRegistry(); metricRegistry.addListener(registryListener); client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); client.start(); } @After public void tearDown() throws IOException { if (client != null) { client.close(); } if (httpServer != null) { httpServer.stop(0); } } @Test public void registersExpectedMetricsGivenNameStrategy() throws Exception { final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/"); final String metricName = "some.made.up.metric.name"; httpServer.createContext("/", exchange -> { exchange.sendResponseHeaders(200, 0L); exchange.setStreams(null, null); exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); exchange.close(); }); httpServer.start(); when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() { @Override public void completed(SimpleHttpResponse result) { assertThat(result.getBodyText()).isEqualTo("TEST"); } @Override public void failed(Exception ex) { fail(); } @Override public void cancelled() { fail(); } }); responseFuture.get(1L, TimeUnit.SECONDS); verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); } @Test public void registersExpectedExceptionMetrics() throws Exception { final CountDownLatch countDownLatch = new CountDownLatch(1); final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/"); final String requestMetricName = "request"; final String exceptionMetricName = "exception"; httpServer.createContext("/", HttpExchange::close); httpServer.start(); when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) .thenReturn(requestMetricName); when(metricNameStrategy.getNameFor(any(), any(Exception.class))) .thenReturn(exceptionMetricName); try { final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() { @Override public void completed(SimpleHttpResponse result) { fail(); } @Override public void failed(Exception ex) { countDownLatch.countDown(); } @Override public void cancelled() { fail(); } }); countDownLatch.await(5, TimeUnit.SECONDS); responseFuture.get(5, TimeUnit.SECONDS); fail(); } catch (ExecutionException e) { assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); await().atMost(5, TimeUnit.SECONDS) .untilAsserted(() -> assertThat(metricRegistry.getMeters()).containsKey("exception")); } } }
30,325
https://github.com/anas-domesticus/gitlab-utils/blob/master/api-tool/go.mod
Github Open Source
Open Source
MIT
2,020
gitlab-utils
anas-domesticus
Go Module
Code
11
57
module api-tool go 1.15 require ( github.com/sirupsen/logrus v1.7.0 github.com/xanzy/go-gitlab v0.40.1 )
34,528
https://github.com/2024davidchen/double-eagle/blob/master/src/main/java/frc/robot/subsystems/Climber.java
Github Open Source
Open Source
BSD-3-Clause
null
double-eagle
2024davidchen
Java
Code
85
316
package frc.robot.subsystems; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import frc.robot.Constants.CAN; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.CommandXboxController; public class Climber extends SubsystemBase { private final CANSparkMax climber = new CANSparkMax(CAN.climberID, MotorType.kBrushless); private final CommandXboxController controller = new CommandXboxController(0); /** Creates a new Climber. */ public Climber() { climber.restoreFactoryDefaults(); climber.setInverted(true); } @Override public void periodic() { // This method will be called once per scheduler run if (controller.getRightTriggerAxis() > 0) { climber.set(controller.getRightTriggerAxis() * 0.2); } else { climber.set(-controller.getLeftTriggerAxis() * 0.2); } } public void pullUp(double speed){ climber.set(-1 * speed); } }
22,251
https://github.com/NaskoVasilev/CSharp-Advanced/blob/master/Functional Programming/FunctionalProgramming-Exercise/KnightsOfHonor/KnightsOfHonor.cs
Github Open Source
Open Source
MIT
2,020
CSharp-Advanced
NaskoVasilev
C#
Code
35
113
using System; using System.Linq; namespace KnightsOfHonor { class KnightsOfHonor { static void Main(string[] args) { Console.ReadLine() .Split(' ', StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(editor); } public static Action<string> editor = (name) => Console.WriteLine("Sir " + name); } }
7,438
https://github.com/alwanof/whatsappneed/blob/master/resources/views/vendor/nova/partials/meta.blade.php
Github Open Source
Open Source
MIT
null
whatsappneed
alwanof
PHP
Code
7
27
<link rel="icon" type="image/png" href="{{ asset('/images/favicon.png') }} ">
22,683
https://github.com/NLnetLabs/kmip/blob/master/src/types/traits.rs
Github Open Source
Open Source
BSD-3-Clause
2,021
kmip
NLnetLabs
Rust
Code
168
426
//! Dynamic traits for sync or async use depending on the Cargo features used. //! //! The `ReadWrite` trait is the set of traits used by the [Client](crate::client::Client) to read/write to a TLS //! stream. //! //! The exact composition of the set is dependent on the Cargo feature flags used to compile this crate. //! //! | Feature Flag | Traits included in the `ReadWrite` trait | //! |------------------------|------------------------------------------| //! | `sync` (default) | `std::io::Read + std::io::Write` | //! | `async-with-tokio` | `tokio::io::AsyncReadExt + tokio::io::AsyncWriteExt + std::marker::Unpin` | //! | `async-with-async-std` | `async_std::io::ReadExt + async_std::io::WriteExt + std::marker::Unpin` | //! //! This enables code that is otherwise identical to be re-used. cfg_if::cfg_if! { if #[cfg(feature = "sync")] { trait_set::trait_set! { pub trait ReadWrite = std::io::Read + std::io::Write; } } else if #[cfg(feature = "async-with-tokio")] { trait_set::trait_set! { pub trait ReadWrite = tokio::io::AsyncReadExt + tokio::io::AsyncWriteExt + std::marker::Unpin; } } else if #[cfg(feature = "async-with-async-std")] { trait_set::trait_set! { pub trait ReadWrite = async_std::io::ReadExt + async_std::io::WriteExt + std::marker::Unpin; } } }
48,193
https://github.com/inyeolsohnn/Squirrel/blob/master/src/squirrel/ir/IRQualityMetrics.java
Github Open Source
Open Source
MIT
null
Squirrel
inyeolsohnn
Java
Code
358
840
package squirrel.ir; import squirrel.ir.retrieve.RT_Query; /** * IRQualityMetrics holds data about the quality of search for a particular * query. * * @author Steffen Zschaler */ public class IRQualityMetrics { private RT_Query query; private int topK; private double precision; private double rPrecision; private double recall; private double patternPrecision; private double patternRecall; private double patternRPrecision; public IRQualityMetrics(RT_Query query, int topK, double precision, double patternPrecision, double recall, double patternRecall, double rPrecision, double patternRPrecision) { this.query = query; this.topK = topK; this.precision = precision; this.rPrecision = rPrecision; this.patternPrecision = patternPrecision; this.patternRecall = patternRecall; this.recall = recall; this.patternRPrecision = patternRPrecision; } /** * Get the query for which these metrics hold. */ public RT_Query getQuery() { return query; } /** * Get the number of search results that were taken into account when * computing these metrics. */ public int getTopK() { return topK; } /** * Get the precision of search results at the given top K value. */ public double getPrecisionAtTopK() { return precision; } /** * Get the R-precision of search results. */ public double getRPrecision() { return rPrecision; } /** * Return the precision of found patterns within topK documents that are * considered relevant for the query. * * @return */ public double getPatternPrecision() { return patternPrecision; } /** * Get pattern r-Precision based on ranked (weighted) list of patterns and * set of relevant patterns for the query. * * @return */ public double getPatternRPrecision() { return patternRPrecision; } /** * Get the recall of search results at the given top K value. */ public double getRecallAtTopK() { return recall; } /** * Return the recall of found patterns within topK documents that are * considered relevant for the query. * * @return */ public double getPatternRecall() { return patternRecall; } /** * Compute the F-measure for this query and top K value using the given * weight. * * @param weight * ranges from 0.5 to 2.0. Higher values favour recall. */ public double getFMeasureAtTopK(double weight) { double tentativeResult = (1 + weight * weight) * (precision * recall) / ((weight * weight * precision) + recall); if (Double.isNaN(tentativeResult)) return 0; else return tentativeResult; } }
36,181
https://github.com/Jedy15/SARH/blob/master/application/views/Plantilla/v_frm_laboral.php
Github Open Source
Open Source
MIT
null
SARH
Jedy15
PHP
Code
1,513
7,144
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title> SARH | <?php echo $title;?> Registro</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/bootstrap/dist/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/Ionicons/css/ionicons.min.css"> <!-- daterange picker --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/bootstrap-daterangepicker/daterangepicker.css"> <!-- bootstrap datepicker --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css"> <!-- iCheck for checkboxes and radio inputs --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/iCheck/all.css"> <!-- Bootstrap Color Picker --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css"> <!-- Bootstrap time Picker --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/timepicker/bootstrap-timepicker.min.css"> <!-- Select2 --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/bower_components/select2/dist/css/select2.min.css"> <!-- Theme style --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/dist/css/AdminLTE.min.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/dist/css/skins/_all-skins.min.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]--> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> </head> <?php if($this->session->flashdata("error")):?> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-ban"></i> Error!</h4> <?php echo $this->session->flashdata("error")?> </div> <?php endif; ?> <?php if($this->session->flashdata("Aviso")):?> <div class="alert alert-info alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-ban"></i> Exito!</h4> <?php echo $this->session->flashdata("Aviso")?> </div> <?php endif; ?> <body class="hold-transition skin-blue sidebar-collapse sidebar-mini"> <div class="wrapper"> <?php $this->load->view('layout/main_header'); $this->load->view('layout/aside'); ?> <div class="content-wrapper"> <section class="content-header"> <h1> <?php echo $persona[0]->NOMBRES.' '.$persona[0]->APELLIDOS ?> <small><?php echo $title;?> Registro Laboral</small> </h1> </section> <section class="content"> <?php echo form_open(); ?> <div class="box box-success"> <div class="box-header with-border"> <h3 class="box-title">Datos Laborales <?php if ($this->uri->segment(2)=='EditarLaboral' ){ echo 'N° '.$datos_reg[0]->IdLaboral; } ?></h3> <?php if ($this->uri->segment(2)=='EditarLaboral') {?> <div class="box-tools pull-right"> <span data-toggle="tooltip" title="" class="badge bg-green" data-original-title="Creación"><?php echo $datos_reg[0]->FechaReg ?></span> <span data-toggle="tooltip" title="" class="badge bg-blue" data-original-title="Ultima Actualización"><?php echo $datos_reg[0]->Fecha ?></span> <span data-toggle="tooltip" title="" class="badge bg-navy" data-original-title="Ultimo Usuario"><?php echo $Usuario[0]->Nombre.' '.$Usuario[0]->Apellido ?></span> </div> <?php } ?> </div> <div class="box-body"> <div class="row"> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="form-group" id="SelectJuris"> <label for="IdJuris">Jurisdicción</label> <select required class="form-control select2" name="Jurisdicción" id="IdJuris" style="width: 100%;" <?php if ($this->session->userdata("IdPerfil")>=3 ){echo 'disabled';} ?>> <option value="">--Seleccione Jurisdicción--</option> </select> </div> <div class="form-group" id="SelectUnidad" style="display:none"> <label for="IdAds">Unidad de Adscripción</label> <select class="form-control select2" style="width: 100%;" name="IdAds" id="IdAds" required="" <?php if ($this->session->userdata("IdPerfil")>=3 ){echo 'disabled';} ?>> </select> </div> <div class="form-group"> <label for="IdTipoTrabajador">Tipo de Trabajador</label> <select class="form-control select2" style="width: 100%;" name="IdTipoTrabajador" id="IdTipoTrabajador" required="" <?php if ($this->session->userdata("IdPerfil")>=3 ){echo 'disabled';} ?> > <option selected="selected" value="">--Seleccione Tipo--</option> <?php foreach ($tra as $item): if($item->IdTipoTrabajador==set_value('IdTipoTrabajador',@$datos_reg[0]->IdTipoTrabajador)){?> <option value="<?php echo $item->IdTipoTrabajador;?>" selected="selected"><?php echo $item->TIPOTRABAJADOR;?></option> <?php } else { ?> <option value="<?php echo $item->IdTipoTrabajador;?>"><?php echo $item->TIPOTRABAJADOR;?></option> <?php } endforeach;?> </select> </div> <div class="form-group"> <label for="CODIGO">Codigo</label> <select class="form-control select2" style="width: 100%;" name="Codigo" id="Codigo" required <?php if ($this->session->userdata("IdPerfil")>=3 ){echo 'disabled';} ?> > <option selected="selected" value="">--Seleccione Codigo--</option> <?php foreach ($codigo as $item): if($item->CODIGO==set_value('Codigo',@$datos_reg[0]->Codigo)){?> <option value="<?php echo $item->CODIGO;?>" selected="selected"><?php echo $item->CODIGO.' '.$item->PUESTO;?></option> <?php } else { ?> <option value="<?php echo $item->CODIGO;?>"><?php echo $item->CODIGO.' '.$item->PUESTO;?></option> <?php } endforeach;?> </select> </div> <div class="form-group"> <label for="Id_Programa">Programa</label> <select class="form-control select2" style="width: 100%;" name="Id_Programa" id="Id_Programa"> <option></option> </select> </div> </div><!-- fin de columna 1 --> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="form-group"> <label for="FInicio">Fecha de Ingreso a SSA</label> <div class="input-group"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="date" required=”required” class="form-control" name="FInicio" id="FInicio" value="<?php echo set_value('FInicio',@$datos_reg[0]->FInicio); ?>"> </div> </div> <div class="form-group"> <label for="FIGF">Fecha de Ingreso a Gobierno Federal</label> <div class="input-group"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="date" class="form-control" name="FIGF" id="FIGF" value="<?php echo set_value('FIGF',@$datos_reg[0]->FIGF); ?>"> </div> </div> <div class="form-group"> <label for="Clave">Clave Presupuestal</label> <input type="text" class="form-control" required name="Clave" id="Clave" placeholder="Clave" maxlength="28" size="28" onKeyUp="this.value = this.value.toUpperCase();" value="<?php echo set_value('Clave',@$datos_reg[0]->Clave); ?>"> </div> <?php if ($this->session->userdata("IdPerfil")<2 and $this->uri->segment(2)=='EditarLaboral') { ?> <div class="form-group"> <label for="IdEstatus">Estatus</label> <select class="form-control select2" style="width: 100%;" name="IdEstatus" id="IdEstatus" required="" <?php if ($this->session->userdata("IdPerfil")>=3 ){echo 'disabled';} ?> > <option selected="selected" value="">--Seleccione Estatus--</option> <?php foreach ($estatus as $item): if($item->IdEstatus==set_value('IdEstatus',@$datos_reg[0]->IdEstatus)){?> <option value="<?php echo $item->IdEstatus;?>" selected="selected"><?php echo $item->Estatus?></option> <?php } else { ?> <option value="<?php echo $item->IdEstatus;?>"><?php echo $item->Estatus?></option> <?php } endforeach;?> </select> </div> <?php } ?> <div class="form-group"> <label for="IdTipoTrabajador">Sindicato</label> <select class="form-control select2" style="width: 100%;" name="IdSeccion" id="IdSeccion"> <option></option> </select> </div> <div class="form-group" id="ListaSubseccion" style="display:none"> <label for="Id_Subseccion">Subsección</label> <select class="form-control select2" style="width: 100%;" name="Id_Subseccion" id="Id_Subseccion"> <option></option> </select> </div> </div><!-- fin de columna 2 --> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="form-group"> <label for="PERCEPCION">Percepción Quincenal</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-dollar"></i></span> <input type="number" class="form-control" name="PERCEPCION" id="PERCEPCION" step="0.01" value="<?php echo set_value('PERCEPCION',@$datos_reg[0]->PERCEPCION); ?>"> </div> </div> <div class="form-group"> <label for="DEDUCCION">Deducción Quincenal</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-dollar"></i></span> <input type="number" class="form-control" name="DEDUCCION" id="DEDUCCION" step="0.01" value="<?php echo set_value('DEDUCCION',@$datos_reg[0]->DEDUCCION); ?>"> </div> </div> <div class="form-group"> <label for="NETO">Neto Quincenal</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-dollar"></i></span> <input type="number" class="form-control" name="NETO" id="NETO" step="0.01" value="<?php echo set_value('NETO',@$datos_reg[0]->NETO); ?>"> </div> </div> <div class="form-group"> <label for="nota">Observaciones Generales</label> <textarea class="form-control" rows="3" name="nota" id="nota" placeholder="Observaciones..."><?php echo set_value('nota',@$datos_reg[0]->nota); ?></textarea> </div> <?php if ($this->session->userdata("IdPerfil")<2 ) { ?> <?php if ($this->uri->segment(2)=='EditarLaboral') {?> <div class="form-group"> <label for="">Activo:</label> <div class="row"> <div class="col-xs-6"> <label> <input type="radio" name="status" class="minimal" value="1" <?php if(set_value('status',@$datos_reg[0]->status)=='1'){echo 'checked';}?>> Si </label> </div> <div class="col-xs-6"> <label> <input type="radio" name="status" class="minimal" value="0" <?php if(set_value('status',@$datos_reg[0]->status)=='0'){echo 'checked';}?>> No </label> </div> </div> </div> <?php } }?> </div><!-- fin de columna 3 --> </div> <div class="box-footer"> <a href="<?php echo base_url();?>plantilla/ver/<?php echo $persona[0]->IdPersonal ?>" class="btn btn-danger" id="btncancelar" >Cancelar</a> <button type="submit" class="btn btn-primary pull-right" id="btnGuardar">Guardar</button> </div> </div> </div> <?php echo form_close(); ?> </section> </div> <?php $this->load->view('layout/footer_v2'); ?> </div> <!-- ./wrapper --> <!-- jQuery 3 --> <script src="<?php echo base_url(); ?>assets/bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="<?php echo base_url(); ?>assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Select2 --> <script src="<?php echo base_url(); ?>assets/bower_components/select2/dist/js/select2.full.min.js"></script> <!-- InputMask --> <script src="<?php echo base_url(); ?>assets/plugins/input-mask/jquery.inputmask.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/input-mask/jquery.inputmask.date.extensions.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/input-mask/jquery.inputmask.extensions.js"></script> <!-- date-range-picker --> <script src="<?php echo base_url(); ?>assets/bower_components/moment/min/moment.min.js"></script> <script src="<?php echo base_url(); ?>assets/bower_components/bootstrap-daterangepicker/daterangepicker.js"></script> <!-- bootstrap datepicker --> <script src="<?php echo base_url(); ?>assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script> <!-- bootstrap color picker --> <script src="<?php echo base_url(); ?>assets/bower_components/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.min.js"></script> <!-- bootstrap time picker --> <script src="<?php echo base_url(); ?>assets/plugins/timepicker/bootstrap-timepicker.min.js"></script> <!-- SlimScroll --> <script src="<?php echo base_url(); ?>assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> <!-- iCheck 1.0.1 --> <script src="<?php echo base_url(); ?>assets/plugins/iCheck/icheck.min.js"></script> <!-- FastClick --> <script src="<?php echo base_url(); ?>assets/bower_components/fastclick/lib/fastclick.js"></script> <!-- AdminLTE App --> <script src="<?php echo base_url(); ?>assets/dist/js/adminlte.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="<?php echo base_url(); ?>assets/dist/js/demo.js"></script> <!-- Page script --> <script> $(function () { //Initialize Select2 Elements $('.select2').select2() $.post('<?php echo base_url(); ?>Administrar/ListaSeccion', function(data, textStatus, xhr) { var datos = $.parseJSON(data); $('#IdSeccion').select2({ placeholder: "Seleccione una opción", data: datos }); <?php if ($datos_reg[0]) { ?> var id = <?php echo $datos_reg[0]->IdSeccion ?>; if (id>0) { $('#IdSeccion').val(id); $('#IdSeccion').trigger('change'); } <?php } ?> }); $.post('<?php echo base_url(); ?>Administrar/ListaPrograma', function(data, textStatus, xhr) { var datos = $.parseJSON(data); $('#Id_Programa').select2({ placeholder: "Seleccione una opción", data: datos }); <?php if ($datos_reg[0]) { ?> var id = <?php echo $datos_reg[0]->Id_Programa ?>; $('#Id_Programa').val(id); $('#Id_Programa').trigger('change'); <?php } ?> }); //Datemask dd/mm/yyyy $('#datemask').inputmask('yyyy/mm/dd', { 'placeholder': 'yyyy/mm/dd' }) //Datemask2 mm/dd/yyyy $('#datemask2').inputmask('mm/dd/yyyy', { 'placeholder': 'mm/dd/yyyy' }) //Money Euro $('[data-mask]').inputmask() //Date range picker $('#reservation').daterangepicker() //Date range picker with time picker $('#reservationtime').daterangepicker({ timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A' }) //Date range as a button $('#daterange-btn').daterangepicker( { ranges : { 'Today' : [moment(), moment()], 'Yesterday' : [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days' : [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month' : [moment().startOf('month'), moment().endOf('month')], 'Last Month' : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, startDate: moment().subtract(29, 'days'), endDate : moment() }, function (start, end) { $('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')) } ) //Date picker $('#datepicker').datepicker({ autoclose: true }) //iCheck for checkbox and radio inputs $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass : 'iradio_minimal-blue' }) //Red color scheme for iCheck $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({ checkboxClass: 'icheckbox_minimal-red', radioClass : 'iradio_minimal-red' }) //Flat red color scheme for iCheck $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass : 'iradio_flat-green' }) //Colorpicker $('.my-colorpicker1').colorpicker() //color picker with addon $('.my-colorpicker2').colorpicker() //Timepicker $('.timepicker').timepicker({ showInputs: false // use24hours: true, // format: 'HH:mm' }) }) </script> <script> $(document).ready(function(){ $('#IdSeccion').change(function(event) { $('#Id_Subseccion').html(''); //Vaciar la lista desplegable antes de carnuevamente los datos var selecionado = $('#IdSeccion option:selected').val(); SelectSubseccion(selecionado); $('#ListaSubseccion').show('slow/400/fast'); }); // $('#SelectUnidad').hide(); lista1(0); <?php if ($datos_reg[0]) { ?> var reg = <?php echo $datos_reg[0]->CLAVE_JURISDICCION; ?>; lista1(reg); var Adscripcion = <?php echo $datos_reg[0]->IdAds; ?>; lista2(reg, Adscripcion); var IdSeccion = <?php echo $datos_reg[0]->IdSeccion; ?>; if (IdSeccion > 0) { SelectSubseccion(IdSeccion); var Id_Subseccion = <?php echo $datos_reg[0]->Id_Subseccion; ?>; if(Id_Subseccion > 0) { $('#ListaSubseccion').show(); $('#Id_Subseccion').val(Id_Subseccion); $('#Id_Subseccion').trigger('change'); // Notify any JS components that the value changed } } <?php } ?> $("#IdJuris").change(function() { $('#SelectUnidad').show('slow/400/fast', function() { }); var valor = $('#IdJuris option:selected').text() lista2(valor, 0); }); function lista1(clavejuris) { $.post('<?php echo base_url(); ?>Plantilla/CargarJuris', {}, function(data, textStatus, xhr) { var datos = $.parseJSON(data); for(var i in datos) { if (clavejuris == datos[i].CLAVE_JURISDICCION) { $("#IdJuris").append('<option selected="selected" value="'+datos[i].CLAVE_JURISDICCION+'">'+datos[i].CLAVE_JURISDICCION+'</option>'); } else { $("#IdJuris").append('<option value="'+datos[i].CLAVE_JURISDICCION+'">'+datos[i].CLAVE_JURISDICCION+'</option>'); } } }); } //Fin funcion lista1 function lista2(clavejuris, IdAds){ $.post("<?php echo base_url(); ?>Plantilla/CargarUnidad", { id : clavejuris}, function(data) { var datos = $.parseJSON(data); var opciones for(var i in datos) { if (IdAds==datos[i].ID) { opciones += '<option selected="selected" value="'+datos[i].ID+'">'+datos[i].CLUES+' '+datos[i].NOMBREUNIDAD+'</option>'; } else { opciones += '<option value="'+datos[i].ID+'">'+datos[i].CLUES+' '+datos[i].NOMBREUNIDAD+'</option>'; } } $('#SelectUnidad').show(); $("#IdAds").html(opciones); }); } function SelectSubseccion(seccion){ $.post('<?php echo base_url(); ?>Administrar/ListaSubseccion', {IdSeccion: seccion}, function(data, textStatus, xhr) { var datos = $.parseJSON(data); if (datos) { $('#Id_Subseccion').select2({ allowClear: true, placeholder: "Seleccione una opción", data: datos }); } }); } }); //fin ready Function </script> </body> </html>
40,125
https://github.com/zweifel/Physis-Shard/blob/master/agents/self_organized_systems/create_datasets.r
Github Open Source
Open Source
Apache-2.0
2,021
Physis-Shard
zweifel
R
Code
19
150
y <- runif(1:10000,min=0,max=180) #exponential x <- rexp(1:10000,3) k2 <- cbind(x*sin(y),x*cos(y)) #uniform x2 <- runif(1:10000,min=0,max=3) k <- cbind(x2*sin(y),x2*cos(y)) write.table(k2,"circular_exp",row.names=F,col.names=F) write.table(k,"circular_uniform",row.names=F,col.names=F)
11,282
https://github.com/kring/terriajs/blob/master/src/ViewModels/CatalogViewModel.js
Github Open Source
Open Source
Apache-2.0
null
terriajs
kring
JavaScript
Code
741
1,758
'use strict'; /*global require*/ var defaultValue = require('../../third_party/cesium/Source/Core/defaultValue'); var defined = require('../../third_party/cesium/Source/Core/defined'); var defineProperties = require('../../third_party/cesium/Source/Core/defineProperties'); var DeveloperError = require('../../third_party/cesium/Source/Core/DeveloperError'); var knockout = require('../../third_party/cesium/Source/ThirdParty/knockout'); var RuntimeError = require('../../third_party/cesium/Source/Core/RuntimeError'); var createCatalogMemberFromType = require('./createCatalogMemberFromType'); var CatalogGroupViewModel = require('./CatalogGroupViewModel'); /** * The view model for the geospatial data catalog. * * @param {ApplicationViewModel} application The application. * * @alias CatalogViewModel * @constructor */ var CatalogViewModel = function(application) { if (!defined(application)) { throw new DeveloperError('application is required'); } this._application = application; this._group = new CatalogGroupViewModel(application); this._group.name = 'Root Group'; /** * Gets or sets a flag indicating whether the catalog is currently loading. * @type {Boolean} */ this.isLoading = false; knockout.track(this, ['isLoading']); knockout.defineProperty(this, 'userAddedDataGroup', { get : function() { var group; var groups = this.group.items; for (var i = 0; i < groups.length; ++i) { group = groups[i]; if (group.name === 'User-Added Data') { return group; } } group = new CatalogGroupViewModel(this.application); group.name = 'User-Added Data'; group.description = 'The group for data that was added by the user via the Add Data panel.'; this.group.add(group); return group; } }); }; defineProperties(CatalogViewModel.prototype, { /** * Gets the application. * @memberOf CatalogViewModel.prototype * @type {ApplicationViewModel} */ application : { get : function() { return this._application; } }, /** * Gets the catalog's top-level group. * @memberOf CatalogViewModel.prototype * @type {CatalogGroupViewModel} */ group : { get : function() { return this._group; } } }); /** * Updates the catalog from a JSON object-literal description of the available collections. * Existing collections with the same name as a collection in the JSON description are * updated. If the description contains a collection with a name that does not yet exist, * it is created. * * @param {Object} json The JSON description. The JSON should be in the form of an object literal, not a string. * @param {Object} [options] Object with the following properties: * @param {Boolean} [options.onlyUpdateExistingItems] true to only update existing items and never create new ones, or false is new items * may be created by this update. * @param {Boolean} [options.isUserSupplied] If specified, sets the {@link CatalogMemberViewModel#isUserSupplied} property of updated catalog members * to the given value. If not specified, the property is left unchanged. */ CatalogViewModel.prototype.updateFromJson = function(json, options) { if (!(json instanceof Array)) { throw new DeveloperError('JSON catalog description must be an array of groups.'); } options = defaultValue(options, defaultValue.EMPTY_OBJECT); var onlyUpdateExistingItems = defaultValue(options.onlyUpdateExistingItems, false); for (var groupIndex = 0; groupIndex < json.length; ++groupIndex) { var group = json[groupIndex]; if (!defined(group.name)) { throw new RuntimeError('A group must have a name.'); } // Find an existing group with the same name, if any. var existingGroup = this.group.findFirstItemByName(group.name); if (!defined(existingGroup)) { // Skip this item entirely if we're not allowed to create it. if (onlyUpdateExistingItems) { continue; } if (!defined(group.type)) { throw new RuntimeError('A group must have a type.'); } existingGroup = createCatalogMemberFromType(group.type, this.application); this.group.add(existingGroup); } existingGroup.updateFromJson(group, options); } this.application.nowViewing.sortByNowViewingIndices(); }; /** * Serializes the catalog to JSON. * * @param {Object} [options] Object with the following properties: * @param {Boolean} [options.enabledItemsOnly=false] true if only enabled data items (and their groups) should be serialized, * or false if all data items should be serialized. * @param {CatalogMemberViewModel[]} [options.itemsSkippedBecauseTheyAreNotEnabled] An array that, if provided, is populated on return with * all of the data items that were not serialized because they were not enabled. The array will be empty if * options.enabledItemsOnly is false. * @param {Boolean} [options.skipItemsWithLocalData=false] true if items with a serializable 'data' property should be skipped entirely. * This is useful to avoid creating a JSON data structure with potentially very large embedded data. * @param {CatalogMemberViewModel[]} [options.itemsSkippedBecauseTheyHaveLocalData] An array that, if provided, is populated on return * with all of the data items that were not serialized because they have a serializable 'data' property. The array will be empty * if options.skipItemsWithLocalData is false. * @param {Boolean} [options.serializeForSharing=false] true to only serialize properties that are typically necessary for sharing this member * with other users, such as {@link CatalogGroupViewModel#isOpen}, {@link CatalogItemViewModel#isEnabled}, * {@link CatalogItemViewModel#isLegendVisible}, and {@link ImageryLayerViewModel#opacity}, * rather than serializing all properties needed to completely recreate the catalog. * @param {Boolean} [options.userSuppliedOnly=false] true to only serialize catalog members (and their containing groups) that have been identified as having been * supplied by the user ({@link CatalogMemberViewModel#isUserSupplied} is true); false to serialize all catalog members. * @return {Object} The serialized JSON object-literal. */ CatalogViewModel.prototype.serializeToJson = function(options) { this.application.nowViewing.recordNowViewingIndices(); var json = {}; CatalogGroupViewModel.defaultSerializers.items(this.group, json, 'items', options); return json.items; }; module.exports = CatalogViewModel;
35,891
https://github.com/yscorecore/ys.knife/blob/master/gen/YS.Knife.Generator/ConvertTo/ConvertToAttribute.cs
Github Open Source
Open Source
MIT
2,021
ys.knife
yscorecore
C#
Code
72
186
using System; using System.Collections.Generic; using System.Text; namespace YS.Knife { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] public sealed class ConvertToAttribute : Attribute { public ConvertToAttribute(Type sourceType, Type targetType) { SourceType = sourceType ?? throw new ArgumentNullException(nameof(sourceType)); TargetType = targetType ?? throw new ArgumentNullException(nameof(targetType)); } public Type SourceType { get; } public Type TargetType { get; } public string[] IgnoreTargetProperties { get; set; } public string[] CustomMappings { get; set; } } }
10,394
https://github.com/sy-data/dtzine/blob/master/views/index.ejs
Github Open Source
Open Source
MIT-0
2,021
dtzine
sy-data
EJS
Code
381
1,846
<!DOCTYPE html> <html lang="en"> <head> <%- include('include/header-meta') %> <%- include('include/header-css') %> <%- include('include/header-js') %> </head> <body> <header class="site-header sticky-top py-1"> <nav class="container d-flex flex-column flex-md-row justify-content-between"> <a class="py-2" href="#" aria-label="Product"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="d-block mx-auto" role="img" viewBox="0 0 24 24"><title>Product</title><circle cx="12" cy="12" r="10"/><path d="M14.31 8l5.74 9.94M9.69 8h11.48M7.38 12l5.74-9.94M9.69 16L3.95 6.06M14.31 16H2.83m13.79-4l-5.74 9.94"/></svg> </a> <a class="py-2 d-none d-md-inline-block" href="#">NewsRoom</a> <a class="py-2 d-none d-md-inline-block" href="#">Previous releases</a> </nav> </header> <main> <div class="position-relative overflow-hidden p-3 p-md-5 m-md-3 text-center bg-light"> <div class="col-md-5 p-lg-5 mx-auto my-5"> <h1 class="display-4 fw-normal">London ville</h1> <p class="lead fw-normal">Kasa 1호 건물 런던빌이 달성한 기록</p> <a class="btn btn-outline-secondary" href="#">Coming soon</a> </div> <div class="product-device shadow-sm d-none d-md-block"> </div> <div class="product-device product-device-2 shadow-sm d-none d-md-block"></div> </div> <div class="d-md-flex flex-md-equal w-100 my-md-3 ps-md-3"> <div class="bg-dark me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center text-white overflow-hidden"> <div class="my-3 py-3"> <h2 class="display-5">Active User</h2> <p class="lead">플랫폼 성장지표 액티브 유저의 이야기</p> </div> <div class="bg-light shadow-sm mx-auto" style="width: 80%; height: 300px; border-radius: 21px 21px 0 0;"> <i class="bi bi-graph-up" style="color:blue;font-size:10em;opacity:0.7;"></i> </div> </div> <div class="bg-light me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center overflow-hidden"> <div class="my-3 p-3"> <h2 class="display-5">Redash</h2> <p class="lead">카사의 데이터 시각화 시스템</p> </div> <div class="bg-dark shadow-sm mx-auto" style="width: 80%; height: 300px; border-radius: 21px 21px 0 0;"> <img src="https://redash.io/assets/images/elements/redash-logo.svg" width="250px;" style="margin-top:3em;"> </div> </div> </div> <div class="d-md-flex flex-md-equal w-100 my-md-3 ps-md-3"> <div class="bg-light me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center overflow-hidden"> <div class="my-3 p-3"> <h2 class="display-5">Data Pipeline</h2> <p class="lead">Coming soon</p> </div> <div class="bg-dark shadow-sm mx-auto" style="width: 80%; height: 300px; border-radius: 21px 21px 0 0;"></div> </div> <div class="bg-primary me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center text-white overflow-hidden"> <div class="my-3 py-3"> <h2 class="display-5">MIDB</h2> <p class="lead">Coming soon</p> </div> <div class="bg-light shadow-sm mx-auto" style="width: 80%; height: 300px; border-radius: 21px 21px 0 0;"></div> </div> </div> <div class="d-md-flex flex-md-equal w-100 my-md-3 ps-md-3"> <div class="bg-light me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center overflow-hidden"> <div class="my-3 p-3"> <h2 class="display-5">데이터팀 소개</h2> <p class="lead">아주 먼 옛날 알렉스와 디케이가 있었습니다</p> </div> <div class="bg-white shadow-sm mx-auto" style="padding-top:3em; width: 80%; height: 300px; border-radius: 21px 21px 0 0;"> <img src="https://jira.kasa.network/secure/useravatar?avatarId=10336" width="150px"> <img src="https://jira.kasa.network/secure/useravatar?avatarId=10341" width="150px"> </div> </div> <div class="bg-light me-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center overflow-hidden"> <div class="my-3 py-3"> <h2 class="display-5">DB에 접근하는 방법</h2> <p class="lead">DB접근과 데이터 요청 방법은 비밀입니다</p> </div> <div class="bg-white shadow-sm mx-auto" style="width: 80%; height: 300px; border-radius: 21px 21px 0 0;"> <i class="bi bi-lock-fill" style="color:black;font-size:10em;opacity:0.7;"></i> </div> </div> </div> </main> <%- include('include/footer-menu') %> <%- include('include/footer-js') %> </body> </html>
26,378
https://github.com/clinwiki-org/clinwiki/blob/master/front/src/services/search/api.ts
Github Open Source
Open Source
MIT
2,021
clinwiki
clinwiki-org
TypeScript
Code
368
1,291
import * as query from './queries'; import * as mutate from './mutations'; // import SearchPageParamsQuery from 'queries/SearchPageParamsQuery'; // import AUTOSUGGEST_QUERY from 'queries/CrumbsSearchPageAggBucketsQuery'; import { callGraphql, get_gql_url, getGraphQLMigrationURL, getHasuraClinwikiURL, callHasuraClinwiki, } from 'utils/graphqlUtil'; // This is a temporary measure to support different enpoints during the backend migration to NodeJS // Once that is complete, all endpoint URLs should be pulled from a common constant const ENDPOINT = get_gql_url(); const NODE_ENDPOINT = getGraphQLMigrationURL(); const HASURA_CW = getHasuraClinwikiURL(); export const fetchSearchPageAggs = (searchParams: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_AGGS_QUERY, searchParams ); }; export const fetchSearchPageAggBuckets = (searchParams: any, aggId?: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_AGG_BUCKETS_QUERY, searchParams, ); //TODO CHeck params }; export const fetchSearchPageCrowdAggBuckets = (searchParams: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_CROWD_AGG_BUCKETS_QUERY, searchParams ); //TODO CHeck params }; export const fetchSearchPageOpenAggBuckets = (searchParams: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_OPEN_AGG_BUCKETS_QUERY, searchParams ); //TODO CHeck params }; export const fetchSearchPageOpenCrowdAggBuckets = (searchParams: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_OPEN_CROWD_AGG_BUCKETS_QUERY, searchParams ); //TODO CHeck params }; export const fetchSearchParams = (hash: any) => { return callGraphql(NODE_ENDPOINT, query.SEARCH_PAGE_PARAMS_QUERY, { hash }); }; export const fetchSearchStudies = (searchParams: any) => { return callGraphql( NODE_ENDPOINT, query.SEARCH_PAGE_SEARCH_QUERY, searchParams ); }; export const updateSearchParams = searchParams => { return callGraphql( NODE_ENDPOINT, mutate.SEARCH_PAGE_HASH_MUTATION, searchParams.searchParams ); }; export const fetchSearchAutoSuggest = (searchParams: any) => { return callGraphql(ENDPOINT, query.AUTOSUGGEST_QUERY, searchParams); }; export const fetchSavedSearches = (userId: any) => { return callHasuraClinwiki(HASURA_CW, query.HASURA_SAVED_SEARCHES_QUERY, { userId: userId, }); }; export const findShortLinkId = (searchHash: string) => { return callHasuraClinwiki(HASURA_CW, query.FIND_SHORT_LINK, { searchHash: searchHash, }); }; export const createSavedSearch = ( searchHash: string, url: string, userId: number, nameLabel: string, shortLinkId: number ) => { return callHasuraClinwiki(HASURA_CW, mutate.HASURA_CREATE_SAVED_SEARCH, { searchHash: searchHash, url: url, userId: userId, nameLabel: nameLabel, shortLinkId: shortLinkId, }); }; export const deleteSavedSearch = id => { return callHasuraClinwiki(HASURA_CW, mutate.HASURA_DELETE_SAVED_SEARCH, { id: id, }); }; export const fetchIslandConfig = (idList) => { return callHasuraClinwiki(HASURA_CW, query.ISLAND_CONFIG_QUERY, { idList: idList }); }; export const updateFacetConfig = input => { return callGraphql(ENDPOINT, mutate.UPDATE_FACET_CONFIG, { input: input.input, }); }; export const searchExport = (searchExportId: number) => { return callGraphql(ENDPOINT, query.SEARCH_EXPORT_QUERY, { searchExportId: searchExportId, }); }; export const exportToCsv = (searchHash: string, siteViewId: number) => { return callGraphql(ENDPOINT, mutate.EXPORT_TO_CSV_MUTATION, { searchHash: searchHash, siteViewId: siteViewId, }); };
14,603
https://github.com/jsdelivrbot/dockerfiles-1/blob/master/data/a/ajoergensen/baseimage-centos-mono/Dockerfile
Github Open Source
Open Source
MIT
2,018
dockerfiles-1
jsdelivrbot
Dockerfile
Code
23
130
FROM ajoergensen/baseimage-centos RUN \ rpm --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF" && \ yum-config-manager --add-repo http://download.mono-project.com/repo/centos7/ && \ yum install -y mono-complete && \ yum clean all
50,937
https://github.com/marinusmaurice/MvsSln/blob/master/MvsSln/Core/ProjectItem.cs
Github Open Source
Open Source
MIT
2,022
MvsSln
marinusmaurice
C#
Code
926
2,570
/* * The MIT License (MIT) * * Copyright (c) 2013-2021 Denis Kuzmin <x-3F@outlook.com> github/3F * Copyright (c) MvsSln contributors https://github.com/3F/MvsSln/graphs/contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using net.r_eg.MvsSln.Extensions; using net.r_eg.MvsSln.Log; namespace net.r_eg.MvsSln.Core { /// <summary> /// Properties of project in solution file /// </summary> [DebuggerDisplay("{DbgDisplay}")] public struct ProjectItem { /// <summary> /// Project GUID. /// </summary> public string pGuid; /// <summary> /// Project type GUID. /// </summary> public string pType; /// <summary> /// Project name. /// </summary> public string name; /// <summary> /// Relative path to project. /// </summary> public string path; /// <summary> /// Evaluated full path to project. /// </summary> public string fullPath; /// <summary> /// Contains parent item or null if it's a root element. /// </summary> public RefType<SolutionFolder?> parent; /// <summary> /// Evaluated project type. /// </summary> public ProjectType EpType; /// <summary> /// Evaluate project type via GUID. /// </summary> /// <param name="guid">Project type GUID.</param> /// <returns></returns> [Obsolete("Use `Guids.ProjectTypeBy(string guid)` instead.", false)] public static ProjectType ProjectTypeBy(string guid) { return Guids.ProjectTypeBy(guid); } public static bool operator ==(ProjectItem a, ProjectItem b) => a.Equals(b); public static bool operator !=(ProjectItem a, ProjectItem b) => !(a == b); public override bool Equals(object obj) { if(obj is null || !(obj is ProjectItem)) { return false; } var b = (ProjectItem)obj; return pGuid == b.pGuid && pType == b.pType && name == b.name && path == b.path && fullPath == b.fullPath && EpType == b.EpType && parent == b.parent; } public override int GetHashCode() { return 0.CalculateHashCode ( pGuid, pType, name, path, fullPath, EpType, parent ); } /// <param name="name">Project name.</param> /// <param name="pType">Project type GUID.</param> /// <param name="parent">Parent folder.</param> public ProjectItem(string name, ProjectType pType, SolutionFolder? parent = null) : this(name, pType, name, parent) { } /// <param name="name">Project name.</param> /// <param name="pType">Project type GUID.</param> /// <param name="path"></param> /// <param name="parent">Parent folder.</param> /// <param name="slnDir">To evaluate `fullPath` define path to solution directory.</param> public ProjectItem(string name, ProjectType pType, string path, SolutionFolder? parent = null, string slnDir = null) : this(Guid.NewGuid().SlnFormat(), name, pType, path, parent, slnDir) { } /// <param name="pGuid">Project GUID.</param> /// <param name="name">Project name.</param> /// <param name="pType">Project type GUID.</param> /// <param name="parent">Parent folder.</param> public ProjectItem(string pGuid, string name, ProjectType pType, SolutionFolder? parent = null) : this(pGuid, name, pType, name, parent) { } /// <param name="pGuid">Project GUID.</param> /// <param name="name">Project name.</param> /// <param name="pType">Project type GUID.</param> /// <param name="path">Relative path to project.</param> /// <param name="parent">Parent folder.</param> /// <param name="slnDir">To evaluate `fullPath` define path to solution directory.</param> public ProjectItem(string pGuid, string name, ProjectType pType, string path, SolutionFolder? parent = null, string slnDir = null) : this() { Init(pGuid, name, path, pType, parent, slnDir); } /// <param name="pGuid">Project GUID.</param> /// <param name="name">Project name.</param> /// <param name="path">Relative path to project.</param> /// <param name="pType">Project type GUID.</param> /// <param name="slnDir">To evaluate `fullPath` define path to solution directory.</param> public ProjectItem(string pGuid, string name, string path, string pType, string slnDir = null) : this() { Init(pGuid, name, path, pType, slnDir); } /// <param name="prj">Initialize data from other project.</param> public ProjectItem(ProjectItem prj) { pGuid = prj.pGuid.ReformatSlnGuid(); pType = prj.pType.ReformatSlnGuid(); name = prj.name; path = prj.path; fullPath = prj.fullPath; EpType = prj.EpType; parent = prj.parent; } /// <param name="raw">Initialize data from raw line.</param> /// <param name="solutionDir">To evaluate `fullPath` define path to solution directory.</param> public ProjectItem(string raw, string solutionDir) : this() { Match m = RPatterns.ProjectLine.Match(raw ?? String.Empty); if(!m.Success) { LSender.Send(this, $"ProjectItem: incorrect line :: '{raw}'", Message.Level.Warn); return; } Init ( m.Groups["Guid"].Value, m.Groups["Name"].Value, m.Groups["Path"].Value, m.Groups["TypeGuid"].Value, solutionDir ); } private void Init(string pGuid, string name, string path, ProjectType pType, SolutionFolder? parent, string slnDir) { SetProjectType(pType); SetFields(pGuid, name, path, slnDir, parent); } private void Init(string pGuid, string name, string path, string pType, string slnDir) { SetProjectType(pType); SetFields(pGuid, name, path, slnDir); } private void SetFields(string pGuid, string name, string path, string slnDir, SolutionFolder? parent = null) { this.name = name?.Trim(); this.path = path?.Trim(); this.pGuid = pGuid.ReformatSlnGuid(); SetFullPath(slnDir); LSender.Send(this, $"ProjectItem ->['{pGuid}'; '{name}'; '{path}'; '{fullPath}'; '{pType}' ]", Message.Level.Trace); this.parent = new RefType<SolutionFolder?>(parent); } private void SetProjectType(ProjectType pType) { this.pType = Guids.GuidBy(pType); EpType = pType; } /// <summary> /// We reserved raw type for future new Guids before our updates. /// </summary> /// <param name="pType"></param> private void SetProjectType(string pType) { this.pType = pType.ReformatSlnGuid(); EpType = Guids.ProjectTypeBy(pType); } private void SetFullPath(string slnDir) { if(path == null) { return; } if(Path.IsPathRooted(path)) { fullPath = path; } else { fullPath = (slnDir != null) ? Path.Combine(slnDir, path) : path; } fullPath = Path.GetFullPath(fullPath); // D:\a\b\c\..\..\MvsSlnTest.csproj -> D:\a\MvsSlnTest.csproj } #region DebuggerDisplay private string DbgDisplay { get => $"{name} [^{parent?.Value?.header.name}] [{pGuid}] = {path}"; } #endregion } }
48,532
https://github.com/Sohl-Dickstein/NL-Augmenter/blob/master/analysis/filters_mapping_analysis.py
Github Open Source
Open Source
MIT
2,022
NL-Augmenter
Sohl-Dickstein
Python
Code
217
735
""" # Filter Mapping Analysis This script analyses the filters in the NL-Augmenter notebook and maps each filter into specific groups using the supplied metadata. @author = Saad Mahamood """ import inspect from importlib import import_module from analysis.mapping_analysis_utils import MappingAnalysisUtilities from interfaces.Operation import Operation class FilterMappingAnalysis(): ignore_list = [] mapping_analysis_utils = None def __init__(self): self.mapping_analysis_utils = MappingAnalysisUtilities() def fetch_filter_directories(self): return self.mapping_analysis_utils.fetch_directories(ignore_list=self.ignore_list, type="filters") def find_filter_classes(self, package_dir_list: list): print("*** Finding Filter Classes.") filter_package = "filters.{}.filter" filters = {} for a_package in package_dir_list: filters[a_package] = [] # Import the module: module = import_module(filter_package.format(a_package)) # Instantiate the object: for name, obj in inspect.getmembers(module): if inspect.isclass(obj): if issubclass(obj, Operation) and not "Operation" in name: print(f"Loading: Package Name: {a_package}, Class Name: {name}") result_obj = None if name == "GenderBiasFilter": result_obj = obj("en") elif name == "PhoneticMatchFilter": result_obj = obj([]) elif name == "SentenceAndTargetLengthFilter": result_obj = obj([">", "<"], [3, 10]) elif name == "ToxicityFilter": result_obj = obj("toxicity") elif name == "GroupInequityFilter": result_obj = obj("en", ["she", "her", "hers"], ["he", "him", "his"], ["cake"], ["program"]) elif name == "TokenAmountFilter": result_obj = obj(["in", "at"], [2, 3], [">=", "<"]) else: result_obj = obj() # Find out which operation type: operation_type = self.mapping_analysis_utils.get_operation_type(result_obj) filters[a_package].append({"class_name": name, "operation_type": operation_type, "result_obj": result_obj}) return filters def main(): analysis = FilterMappingAnalysis() package_dir_list = analysis.fetch_filter_directories() transformations = analysis.find_filter_classes(package_dir_list) analysis.mapping_analysis_utils.build_keyword_mappings(operations=transformations, type="Filters") analysis.mapping_analysis_utils.generate_csv(type="filters") if __name__ == '__main__': main()
35
https://github.com/AngelsAutoTowing/junkcarsmass.com/blob/master/src/pages/used-auto-parts.jsx
Github Open Source
Open Source
MIT
2,021
junkcarsmass.com
AngelsAutoTowing
JavaScript
Code
1,050
3,022
import React from 'react'; import { graphql, Link, useStaticQuery } from 'gatsby'; import { Container, Row, Col } from 'react-bootstrap'; import Img from 'gatsby-image'; import SEO from '../components/common/SEO/Seo'; import Header from '../components/layouts/Header/Header'; import Body from '../components/layouts/Body'; import BodyContent from '../components/layouts/BodyContent'; import BodySidebar from '../components/layouts/BodySidebar'; import SidebarNav from '../components/common/SidebarNav'; import FormSidebar from '../components/common/Forms/FormSidebar'; import ButtonExternalLink from '../components/common/Buttons/ButtonExternalLink/ButtonExternalLink'; const UsedAutoPartsPage = ({ pageContext, location }) => { const data = useStaticQuery(graphql` query UsedAutoPartsPageQ { headerBgImg: file( relativePath: { eq: "assets/images/used-auto-parts/used-auto-parts-angels-towing-junk-car-mass.jpg" } ) { childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } companyName: site { siteMetadata { title } } phoneNumber: site { siteMetadata { phoneDisplay phoneHref } } imgContentTop: file( relativePath: { eq: "assets/images/used-auto-parts/buy-used-car-parts-salvage-angels-towing-junk-car-mass.jpg" } ) { childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } imgUsedAutoParts: file( relativePath: { eq: "assets/images/used-auto-parts/used-auto-parts-angels-towing-junk-car-mass.jpg" } ) { childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } imgUsedCarParts: file( relativePath: { eq: "assets/images/used-auto-parts/used-car-parts-online-angels-towing-junk-car-mass.jpg" } ) { childImageSharp { fluid(quality: 90, maxWidth: 1920) { ...GatsbyImageSharpFluid_withWebp } } } } `); const imageDataHeader = data.headerBgImg.childImageSharp.fluid; const imgContentTop = data.imgContentTop.childImageSharp.fluid; const imgUsedAutoParts = data.imgUsedAutoParts.childImageSharp.fluid; const imgUsedCarParts = data.imgUsedCarParts.childImageSharp.fluid; const siteMetadata = data.companyName.siteMetadata; const phone = data.phoneNumber.siteMetadata; const { breadcrumb: { crumbs }, } = pageContext; const urlSlashRemoved = location.pathname.replace('/', '').replace('/', ''); const urlArrayDashRemoved = urlSlashRemoved.split('-'); const customCrumbLabel = urlArrayDashRemoved .map((word) => { return word[0].toUpperCase() + word.substring(1); }) .join(' '); const navList = [ { name: 'Cash For Junk Cars', url: '/cash-for-junk-cars/', }, { name: 'Used Auto Parts', url: '/used-auto-parts/', }, ]; return ( <> <SEO title={`Buy Used Auto Parts - Find Auto Parts Online | ${siteMetadata.title}`} description={`Search our used auto parts inventory to find high-quality used car parts at an affordable price. Call us at ${phone.phoneDisplay} for used auto parts.`} canonicalLink="https://junkcarsmass.com/used-auto-parts/" /> <Header Tag="header" className="bg-img-page-top" fluid={imageDataHeader} alt="Used auto parts for sale from our salvage yard" textMain="Find Used Auto Parts From Our Salvage Yard" crumbs={crumbs} customCrumbLabel={customCrumbLabel} /> <Body bodyContent={ <BodyContent> <Container> <h2 className="mb-3">Best Website To Buy Used Auto Parts</h2> <span className="display-6 font-italic"> Easily Find Used Auto Parts Online From Our Inventory </span> <p className="mt-5"> If you're looking for used auto parts, transparent prices, and great customer service, Angels Towing - Junk Car Mass has exactly what you're looking for. </p> <p> Whether you need a transmission for your Toyota, a radiator for your Ford, or a crank to rebuild your Chevy, our auto recycling business can help you find affordable used auto parts today. </p> <p> Our family-owned business specializes in selling high-quality salvage auto parts to customers at competitive prices. We have an incredible selection of parts for all vehicle makes, models, and years. </p> <p> Our team of professionals thoroughly inspects all used auto parts to ensure their quality. That way we can tell you what condition the parts are in, and how much life they have left. </p> <h2 className="pt-4 my-5"> Search Our Inventory For Junkyard Auto Parts </h2> <p>Need a part for your car? Don’t go to the dealership!</p> <p> The parts you need are probably sitting in our junkyard. Angels Towing - Junk Car Mass is here to help you find them. </p> <p> Our certified auto parts technicians run all of our parts through a series of tests to ensure they are safe to use and in good working condition. Once added to our inventory, you can search our databse to find what you need. </p> <p> If you’re not sure exactly what you’re looking for, use our "Search by Image" to help identify the part. </p> <p className="mt-5 text-center lead font-weight-bold"> Check our inventory here: <div className="text-center py-5"> <ButtonExternalLink btnLabel="Search Our Used Auto Parts Inventory" btnLink="http://www.angelsautosalvage.com/" /> </div> </p> <a href="http://www.angelsautosalvage.com/" target="_blank"> <Img fluid={imgContentTop} title="Search Our Used Auto Parts Inventory Online" alt="Angels Auto Salvage car part inventory" className="my-5" /> </a> <h2 className="pt-4 my-5"> Find Used Salvage Auto Parts Online For Any Vehicle </h2> <p> Our salvage yard has millions of parts and can help you repair cars, trucks, sport utility vehicles, vans, motorcycles, RVs, and more. </p> <p> Save time calling around and simply search our salvage yard inventory for quality automobile parts ranging from: </p> <Row> <Col xs={12} lg={6}> <ul className="mb-2 mb-lg-5"> <li>Engines</li> <li>Cylinders</li> <li>Transmissions</li> <li>Suspensions​</li> <li>Frames</li> <li>Body parts​​​</li> </ul> </Col> <Col xs={12} lg={6}> <ul className="mb-5"> <li>Brakes​​​</li> <li>Bumpers​​​</li> <li>Interior trim​​​</li> <li>Tires​​​</li> <li>Glass</li> <li>and the list goes on...</li> </ul> </Col> </Row> <p>We also offer several easy methods to search our inventory:</p> <ul className="mb-5"> <li>Search by make, model, year, and part​</li> <li>Search by image​</li> <li>Search by multi-parts</li> </ul> <p className="display-6 text-center mt-5 pt-5"> Have any questions? Give us a call at{' '} <a className="font-weight-bold text-secondary" href={phone.phoneHref} > {phone.phoneDisplay} </a> . </p> <Img fluid={imgUsedCarParts} title="Find Used Auto Parts Online" alt="Used car parts available to purchase from our junkyard" className="my-5" /> <h2 className="pt-4 my-5">Save Money With Used Car Parts</h2> <p> If you can't find the used car parts you need for your vehicle at an affordable rate, consider searching our inventory to find the lowest prices. </p> <p> Shopping for used auto parts from our salvage yard is the only way to go if you’re looking to save time, save money, and keep your used vehicle on the road. </p> <p> It's not uncommon for auto salvage yards to offer used parts for significantly less than you'd pay at the dealership. </p> <p> A lot of times, it's because the parts are used, but in good working order. These parts are also offered at a reduced price since they are no longer under warranty. </p> <Img fluid={imgUsedAutoParts} title="Search Our Used Auto Parts Inventory" alt="Used truck parts available to purchase from our salvage yard" className="my-5" /> <h2 className="pt-4 my-5">Give Us A Call To Find Your Parts</h2> <p> Not quite sure what parts you're looking for? Having any questions about our inventory or prices? </p> <p> Just give us a call at{' '} <a className="font-weight-bold text-secondary" href={phone.phoneHref} > {phone.phoneDisplay} </a>{' '} and we can help answer any of your questions.​​ </p> <p> ​Not ready to talk on the phone? Try filling out our contact form instead! We will receive your message and get back to you as soon as we can. </p> ​ ​ ​ </Container> </BodyContent> } bodySidebar={ <BodySidebar> <Container> <h2 className="text-center">What We Do</h2> <Container className="my-3 px-0 px-lg-3"> <SidebarNav navList={navList} /> </Container> <Container className="my-3 px-0 px-lg-3"> <FormSidebar /> </Container> </Container> </BodySidebar> } /> </> ); }; export default UsedAutoPartsPage;
37,083
https://github.com/jasonTangxd/clockwork/blob/master/clockwork-common/src/main/java/com/creditease/adx/clockwork/common/entity/gen/TbClockworkTaskAndSlotRelationExample.java
Github Open Source
Open Source
Apache-2.0
2,021
clockwork
jasonTangxd
Java
Code
2,268
6,754
package com.creditease.adx.clockwork.common.entity.gen; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TbClockworkTaskAndSlotRelationExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected List<Criteria> oredCriteria; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected Integer limitStart; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected Integer limitEnd; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public TbClockworkTaskAndSlotRelationExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void setLimitStart(Integer limitStart) { this.limitStart=limitStart; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public Integer getLimitStart() { return limitStart; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public void setLimitEnd(Integer limitEnd) { this.limitEnd=limitEnd; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public Integer getLimitEnd() { return limitEnd; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andSlotIdIsNull() { addCriterion("slot_id is null"); return (Criteria) this; } public Criteria andSlotIdIsNotNull() { addCriterion("slot_id is not null"); return (Criteria) this; } public Criteria andSlotIdEqualTo(Integer value) { addCriterion("slot_id =", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdNotEqualTo(Integer value) { addCriterion("slot_id <>", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdGreaterThan(Integer value) { addCriterion("slot_id >", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdGreaterThanOrEqualTo(Integer value) { addCriterion("slot_id >=", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdLessThan(Integer value) { addCriterion("slot_id <", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdLessThanOrEqualTo(Integer value) { addCriterion("slot_id <=", value, "slotId"); return (Criteria) this; } public Criteria andSlotIdIn(List<Integer> values) { addCriterion("slot_id in", values, "slotId"); return (Criteria) this; } public Criteria andSlotIdNotIn(List<Integer> values) { addCriterion("slot_id not in", values, "slotId"); return (Criteria) this; } public Criteria andSlotIdBetween(Integer value1, Integer value2) { addCriterion("slot_id between", value1, value2, "slotId"); return (Criteria) this; } public Criteria andSlotIdNotBetween(Integer value1, Integer value2) { addCriterion("slot_id not between", value1, value2, "slotId"); return (Criteria) this; } public Criteria andTaskIdIsNull() { addCriterion("task_id is null"); return (Criteria) this; } public Criteria andTaskIdIsNotNull() { addCriterion("task_id is not null"); return (Criteria) this; } public Criteria andTaskIdEqualTo(Integer value) { addCriterion("task_id =", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotEqualTo(Integer value) { addCriterion("task_id <>", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThan(Integer value) { addCriterion("task_id >", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThanOrEqualTo(Integer value) { addCriterion("task_id >=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThan(Integer value) { addCriterion("task_id <", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThanOrEqualTo(Integer value) { addCriterion("task_id <=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdIn(List<Integer> values) { addCriterion("task_id in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotIn(List<Integer> values) { addCriterion("task_id not in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdBetween(Integer value1, Integer value2) { addCriterion("task_id between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotBetween(Integer value1, Integer value2) { addCriterion("task_id not between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andGroupIdIsNull() { addCriterion("group_id is null"); return (Criteria) this; } public Criteria andGroupIdIsNotNull() { addCriterion("group_id is not null"); return (Criteria) this; } public Criteria andGroupIdEqualTo(Integer value) { addCriterion("group_id =", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdNotEqualTo(Integer value) { addCriterion("group_id <>", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdGreaterThan(Integer value) { addCriterion("group_id >", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdGreaterThanOrEqualTo(Integer value) { addCriterion("group_id >=", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdLessThan(Integer value) { addCriterion("group_id <", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdLessThanOrEqualTo(Integer value) { addCriterion("group_id <=", value, "groupId"); return (Criteria) this; } public Criteria andGroupIdIn(List<Integer> values) { addCriterion("group_id in", values, "groupId"); return (Criteria) this; } public Criteria andGroupIdNotIn(List<Integer> values) { addCriterion("group_id not in", values, "groupId"); return (Criteria) this; } public Criteria andGroupIdBetween(Integer value1, Integer value2) { addCriterion("group_id between", value1, value2, "groupId"); return (Criteria) this; } public Criteria andGroupIdNotBetween(Integer value1, Integer value2) { addCriterion("group_id not between", value1, value2, "groupId"); return (Criteria) this; } public Criteria andTaskExecDateIsNull() { addCriterion("task_exec_date is null"); return (Criteria) this; } public Criteria andTaskExecDateIsNotNull() { addCriterion("task_exec_date is not null"); return (Criteria) this; } public Criteria andTaskExecDateEqualTo(Date value) { addCriterion("task_exec_date =", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateNotEqualTo(Date value) { addCriterion("task_exec_date <>", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateGreaterThan(Date value) { addCriterion("task_exec_date >", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateGreaterThanOrEqualTo(Date value) { addCriterion("task_exec_date >=", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateLessThan(Date value) { addCriterion("task_exec_date <", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateLessThanOrEqualTo(Date value) { addCriterion("task_exec_date <=", value, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateIn(List<Date> values) { addCriterion("task_exec_date in", values, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateNotIn(List<Date> values) { addCriterion("task_exec_date not in", values, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateBetween(Date value1, Date value2) { addCriterion("task_exec_date between", value1, value2, "taskExecDate"); return (Criteria) this; } public Criteria andTaskExecDateNotBetween(Date value1, Date value2) { addCriterion("task_exec_date not between", value1, value2, "taskExecDate"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated do_not_delete_during_merge Wed Aug 05 09:46:16 CST 2020 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table tb_clockwork_task_and_slot_relation * * @mbg.generated Wed Aug 05 09:46:16 CST 2020 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
9,903
https://github.com/matthew-hilty/purescript-subcategory/blob/master/src/Functor/Functor.purs
Github Open Source
Open Source
MIT
2,021
purescript-subcategory
matthew-hilty
PureScript
Code
48
107
module Control.Subcategory.Functor ( class Functor ) where import Control.Subcategory.Category (class Category) import Control.Subcategory.Functor.HasMap (class HasMap) import Record.Builder (Builder) class (Category c, HasMap c f) <= Functor c f instance functorBuilder :: HasMap Builder f => Functor Builder f instance functorFunction :: HasMap Function f => Functor Function f
46,437
https://github.com/gucong3000/sonar-web-frontend-plugin/blob/master/sonar-report-core/src/main/java/fr/sii/sonar/report/core/duplication/factory/DuplicationSaverFactory.java
Github Open Source
Open Source
Apache-2.0
2,020
sonar-web-frontend-plugin
gucong3000
Java
Code
92
424
package fr.sii.sonar.report.core.duplication.factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.sii.sonar.report.core.common.PluginContext; import fr.sii.sonar.report.core.common.exception.CreateException; import fr.sii.sonar.report.core.common.factory.SaverFactory; import fr.sii.sonar.report.core.common.save.NoOpSaver; import fr.sii.sonar.report.core.common.save.Saver; import fr.sii.sonar.report.core.duplication.DuplicationConstants; import fr.sii.sonar.report.core.duplication.domain.DuplicationReport; import fr.sii.sonar.report.core.duplication.save.DuplicationSaver; /** * Factory that creates a {@link DuplicationSaver} instance with provided sonar context * * @author Aurélien Baudet * */ public class DuplicationSaverFactory implements SaverFactory<DuplicationReport> { private static final Logger LOG = LoggerFactory.getLogger(DuplicationSaverFactory.class); public Saver<DuplicationReport> create(PluginContext pluginContext) throws CreateException { // if duplication skipped => provide no op saver to do nothing if(pluginContext.getSettings().getBoolean(((DuplicationConstants) pluginContext.getConstants()).getSkipDuplicationKey())) { LOG.debug("Saving duplications skipped"); return new NoOpSaver<DuplicationReport>(); } else { return new DuplicationSaver(pluginContext); } } }
24,340
https://github.com/wasit7/datascience/blob/master/01day03_etl1/day03_etl1_example/myproject/day03 ETL.ipynb
Github Open Source
Open Source
BSD-2-Clause
2,019
datascience
wasit7
Jupyter Notebook
Code
3,377
15,679
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Q1 How many transactions in the dataset?\n", "\n", "## Q2 What is the top-3 most expensive item in the database? \n", "* show the price of item.\n", "\n", "## Q3 Show number of customers were born in each month.\n", "* there are 12 months\n", "\n", "## Q4 Show top-3 popular items that make most income.\n", "* show the total income of each item.\n", "\n", "## Q5 A manager want to crate a birth-month promotion in January 2017.\n", "* How many customers were born in January and also made transcations in January 2017?\n", "\n", "## Q6 In January, what were the top-3 favorite items that customer bought with \"Bread\"?\n", "* show number of times\n", "\n", "## Q7 Who are the top-3 customers that pay most money for \"Tea\"? \n", "* show total payment of each customer.\n", "\n", "## Q8 What are the top-5 items that \"Harry Brown\" pay most money? \n", "* show total payment of each item.\n", "\n", "## Q9 Who are top-5 customer paid most money in 2016? \n", "* show total payment of each customer\n", "\n", "## Q10 Between January and March 2017, Who are top-3 customers that paid most for Coffee?\n", "* show total payment" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# import sqlite3\n", "# import pandas as pd\n", "# con = sqlite3.connect('db.sqlite3')" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>id</th>\n", " <th>name</th>\n", " <th>price</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>1</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>2</td>\n", " <td>Scandinavian</td>\n", " <td>320.0</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>3</td>\n", " <td>Hot chocolate</td>\n", " <td>390.0</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>4</td>\n", " <td>Jam</td>\n", " <td>210.0</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>5</td>\n", " <td>Cookies</td>\n", " <td>210.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " id name price\n", "0 1 Bread 380.0\n", "1 2 Scandinavian 320.0\n", "2 3 Hot chocolate 390.0\n", "3 4 Jam 210.0\n", "4 5 Cookies 210.0" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import psycopg2 as pg\n", "import pandas as pd\n", " \n", "# get connected to the database\n", "con = pg.connect(\"host='bem.ei.team' dbname='myproject' user='myprojectuser' password='password' port='5432'\")\n", "dataframe = pd.read_sql_query(\"SELECT * FROM myapp_item\", con)\n", "dataframe.head()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>datetime</th>\n", " <th>customer_id</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>2016-10-30 09:58:11+00:00</td>\n", " <td>27</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>2016-10-30 10:05:34+00:00</td>\n", " <td>92</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>2016-10-30 10:07:57+00:00</td>\n", " <td>73</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>2016-10-30 10:08:41+00:00</td>\n", " <td>94</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>2016-10-30 10:13:03+00:00</td>\n", " <td>100</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " datetime customer_id\n", "id \n", "1 2016-10-30 09:58:11+00:00 27\n", "2 2016-10-30 10:05:34+00:00 92\n", "3 2016-10-30 10:07:57+00:00 73\n", "4 2016-10-30 10:08:41+00:00 94\n", "5 2016-10-30 10:13:03+00:00 100" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_transaction = pd.read_sql(\n", " sql=\"SELECT * FROM myapp_transaction\",\n", " con=con,\n", " parse_dates={'datetime': {'format': '%Y-%m-%d %H:%M:%S'}},\n", " index_col ='id'\n", ")\n", "df_transaction.head()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>firstname</th>\n", " <th>lastname</th>\n", " <th>dob</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>Jack</td>\n", " <td>Jones</td>\n", " <td>1969-10-03</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Oscar</td>\n", " <td>Taylor</td>\n", " <td>1938-05-20</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Bob</td>\n", " <td>Davies</td>\n", " <td>1940-06-03</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Charlie</td>\n", " <td>Smith</td>\n", " <td>1951-06-16</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>Cath</td>\n", " <td>Brown</td>\n", " <td>1926-02-17</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " firstname lastname dob\n", "id \n", "1 Jack Jones 1969-10-03\n", "2 Oscar Taylor 1938-05-20\n", "3 Bob Davies 1940-06-03\n", "4 Charlie Smith 1951-06-16\n", "5 Cath Brown 1926-02-17" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_customer = pd.read_sql(\n", " sql=\"SELECT * FROM myapp_customer\",\n", " con=con,\n", " parse_dates={'dob': {'format': '%Y-%m-%d'}},\n", " index_col ='id'\n", ")\n", "df_customer.head()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>item_id</th>\n", " <th>transaction_id</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>1</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>2</td>\n", " <td>2</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>2</td>\n", " <td>2</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>3</td>\n", " <td>3</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>4</td>\n", " <td>3</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " item_id transaction_id\n", "id \n", "1 1 1\n", "2 2 2\n", "3 2 2\n", "4 3 3\n", "5 4 3" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_record = pd.read_sql(\n", " sql=\"SELECT * FROM myapp_record\",\n", " con=con,\n", " index_col ='id'\n", ")\n", "df_record.head()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>name</th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Scandinavian</td>\n", " <td>320.0</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Hot chocolate</td>\n", " <td>390.0</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Jam</td>\n", " <td>210.0</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>Cookies</td>\n", " <td>210.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " name price\n", "id \n", "1 Bread 380.0\n", "2 Scandinavian 320.0\n", "3 Hot chocolate 390.0\n", "4 Jam 210.0\n", "5 Cookies 210.0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_item = pd.read_sql(\n", " sql=\"SELECT * FROM myapp_item\",\n", " con=con,\n", " index_col ='id'\n", ")\n", "df_item.head()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "datetime 9531\n", "customer_id 9531\n", "dtype: int64" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q1 How many transactions in the dataset?\n", "df_transaction.count()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>name</th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>48</th>\n", " <td>Bacon</td>\n", " <td>400.0</td>\n", " </tr>\n", " <tr>\n", " <th>39</th>\n", " <td>Fairy Doors</td>\n", " <td>400.0</td>\n", " </tr>\n", " <tr>\n", " <th>17</th>\n", " <td>Juice</td>\n", " <td>390.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " name price\n", "id \n", "48 Bacon 400.0\n", "39 Fairy Doors 400.0\n", "17 Juice 390.0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q2 What is the top-3 most expensive item in the database?\n", "#show the price of item.\n", "df_item.sort_values(by=['price'],ascending=False).head(3)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th>month</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th>count</th>\n", " </tr>\n", " <tr>\n", " <th>month</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>13</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>9</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>8</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>6</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>12</td>\n", " </tr>\n", " <tr>\n", " <th>6</th>\n", " <td>7</td>\n", " </tr>\n", " <tr>\n", " <th>7</th>\n", " <td>9</td>\n", " </tr>\n", " <tr>\n", " <th>8</th>\n", " <td>13</td>\n", " </tr>\n", " <tr>\n", " <th>9</th>\n", " <td>9</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <td>15</td>\n", " </tr>\n", " <tr>\n", " <th>11</th>\n", " <td>6</td>\n", " </tr>\n", " <tr>\n", " <th>12</th>\n", " <td>13</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " month\n", " count\n", "month \n", "1 13\n", "2 9\n", "3 8\n", "4 6\n", "5 12\n", "6 7\n", "7 9\n", "8 13\n", "9 9\n", "10 15\n", "11 6\n", "12 13" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q3 Show number of customers were born in each month.\n", "#there are 12 months\n", "df_customer['month']=df_customer.dob.dt.month\n", "df_customer.groupby(by=['month']).agg({'month':['count']})" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th>sum</th>\n", " </tr>\n", " <tr>\n", " <th>name</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>Coffee</th>\n", " <td>1531880.0</td>\n", " </tr>\n", " <tr>\n", " <th>Bread</th>\n", " <td>1263500.0</td>\n", " </tr>\n", " <tr>\n", " <th>Tea</th>\n", " <td>530950.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " price\n", " sum\n", "name \n", "Coffee 1531880.0\n", "Bread 1263500.0\n", "Tea 530950.0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q4 Show top-3 popular items that make most income.¶\n", "#show the total income of each item.\n", "df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .groupby('name')\\\n", " .agg({'price':['sum']})\\\n", " .sort_values(('price','sum'),ascending=False)\\\n", " .head(3)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "customer_id count 13\n", "dtype: int64" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q5 A manager want to crate a birth-month promotion in January 2017.\n", "#How many customers were born in January and also made transcations in January 2017?\n", "df1=df_customer[df_customer.month==1]\n", "df_transaction['month_transaction']=df_transaction.datetime.dt.month\n", "df2=df_transaction[df_transaction.month_transaction==1]\n", "\n", "df1.merge(\n", " right=df2,\n", " left_index=True,\n", " right_on='customer_id'\n", ").groupby(by=['customer_id'])\\\n", ".agg({'customer_id':['count']})\\\n", ".count()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th>transaction_id</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th>count</th>\n", " </tr>\n", " <tr>\n", " <th>item_id</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>552</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " transaction_id\n", " count\n", "item_id \n", "1 552" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Q6 In January, what were the top-3 favorite items that customer bought with \"Bread\"?\n", "#* show number of times\n", "\n", "\n", "df_all=df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .merge(right=df_transaction,left_on='transaction_id',right_index=True)\n", "\n", "df_all[\n", " (df_all.datetime.dt.month==1) &\\\n", " (df_all.name=='Bread')\n", " ]\\\n", " .groupby(['item_id'])\\\n", " .agg({'transaction_id':['count']})\\\n", " .sort_values(('transaction_id','count'),ascending=False)\\\n", ".head()\n", "\n", "#df_all.head()\n", "# \\\n", "# .groupby(['item_id'])\\\n", "# .agg({'price':['count']})\\\n", "# .sort_values(('price','sum'),ascending=False)\\\n", "# .head(3)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>item_id</th>\n", " <th>transaction_id</th>\n", " <th>name</th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th>id</th>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>1</th>\n", " <td>1</td>\n", " <td>1</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <td>1</td>\n", " <td>5</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>19</th>\n", " <td>1</td>\n", " <td>8</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>20</th>\n", " <td>1</td>\n", " <td>9</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " <tr>\n", " <th>24</th>\n", " <td>1</td>\n", " <td>11</td>\n", " <td>Bread</td>\n", " <td>380.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " item_id transaction_id name price\n", "id \n", "1 1 1 Bread 380.0\n", "10 1 5 Bread 380.0\n", "19 1 8 Bread 380.0\n", "20 1 9 Bread 380.0\n", "24 1 11 Bread 380.0" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_record.merge(right=df_item,left_on='item_id',right_index=True).head()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>sum</th>\n", " </tr>\n", " <tr>\n", " <th>customer_id</th>\n", " <th>firstname</th>\n", " <th>lastname</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>119</th>\n", " <th>William</th>\n", " <th>Smith</th>\n", " <td>7770.0</td>\n", " </tr>\n", " <tr>\n", " <th>57</th>\n", " <th>Bob</th>\n", " <th>Brown</th>\n", " <td>7400.0</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <th>Bob</th>\n", " <th>Davies</th>\n", " <td>7030.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " price\n", " sum\n", "customer_id firstname lastname \n", "119 William Smith 7770.0\n", "57 Bob Brown 7400.0\n", "3 Bob Davies 7030.0" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Q7 Who are the top-3 customers that pay most money for \"Tea\"? \n", "#* show total payment of each customer.\n", "df_all=df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .merge(right=df_transaction,left_on='transaction_id',right_index=True)\\\n", " .merge(right=df_customer,left_on='customer_id',right_index=True)\\\n", "\n", "df_all[df_all.name=='Tea']\\\n", " .groupby(['customer_id','firstname','lastname'])\\\n", " .agg({'price':['sum']})\\\n", " .sort_values(('price','sum'),ascending=False)\\\n", " .head(3)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th>sum</th>\n", " </tr>\n", " <tr>\n", " <th>item_id</th>\n", " <th>name</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>7</th>\n", " <th>Coffee</th>\n", " <td>11480.0</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <th>Bread</th>\n", " <td>8740.0</td>\n", " </tr>\n", " <tr>\n", " <th>10</th>\n", " <th>Tea</th>\n", " <td>3700.0</td>\n", " </tr>\n", " <tr>\n", " <th>25</th>\n", " <th>Cake</th>\n", " <td>3240.0</td>\n", " </tr>\n", " <tr>\n", " <th>9</th>\n", " <th>Medialuna</th>\n", " <td>2590.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " price\n", " sum\n", "item_id name \n", "7 Coffee 11480.0\n", "1 Bread 8740.0\n", "10 Tea 3700.0\n", "25 Cake 3240.0\n", "9 Medialuna 2590.0" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q8 What are the top-5 items that \"Harry Brown\" pay most money?\n", "#show total payment of each item.\n", "\n", "df_all=df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .merge(right=df_transaction,left_on='transaction_id',right_index=True)\\\n", " .merge(right=df_customer,left_on='customer_id',right_index=True)\\\n", "\n", "df_all[(df_all.firstname=='Harry') & (df_all.lastname=='Brown')]\\\n", " .groupby(['item_id','name'])\\\n", " .agg({'price':['sum']})\\\n", " .sort_values(('price','sum'),ascending=False)\\\n", " .head(5)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>sum</th>\n", " </tr>\n", " <tr>\n", " <th>customer_id</th>\n", " <th>firstname</th>\n", " <th>lastname</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>107</th>\n", " <th>James</th>\n", " <th>Taylor</th>\n", " <td>36340.0</td>\n", " </tr>\n", " <tr>\n", " <th>116</th>\n", " <th>Claire</th>\n", " <th>Evans</th>\n", " <td>33190.0</td>\n", " </tr>\n", " <tr>\n", " <th>17</th>\n", " <th>James</th>\n", " <th>Smith</th>\n", " <td>33040.0</td>\n", " </tr>\n", " <tr>\n", " <th>32</th>\n", " <th>Alex</th>\n", " <th>Brown</th>\n", " <td>31380.0</td>\n", " </tr>\n", " <tr>\n", " <th>93</th>\n", " <th>Charlie</th>\n", " <th>Johnson</th>\n", " <td>31030.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " price\n", " sum\n", "customer_id firstname lastname \n", "107 James Taylor 36340.0\n", "116 Claire Evans 33190.0\n", "17 James Smith 33040.0\n", "32 Alex Brown 31380.0\n", "93 Charlie Johnson 31030.0" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q9 Who are top-5 customer paid most money in 2016?\n", "#show total payment of each customer\n", "df_all=df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .merge(right=df_transaction,left_on='transaction_id',right_index=True)\\\n", " .merge(right=df_customer,left_on='customer_id',right_index=True)\\\n", "\n", "df_all[df_all.datetime.dt.year==2016]\\\n", " .groupby(['customer_id','firstname','lastname'])\\\n", " .agg({'price':['sum']})\\\n", " .sort_values(('price','sum'),ascending=False)\\\n", " .head(5)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead tr th {\n", " text-align: left;\n", " }\n", "\n", " .dataframe thead tr:last-of-type th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>price</th>\n", " </tr>\n", " <tr>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th>sum</th>\n", " </tr>\n", " <tr>\n", " <th>customer_id</th>\n", " <th>firstname</th>\n", " <th>lastname</th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>81</th>\n", " <th>Thomas</th>\n", " <th>Johnson</th>\n", " <td>11200.0</td>\n", " </tr>\n", " <tr>\n", " <th>98</th>\n", " <th>Cath</th>\n", " <th>Taylor</th>\n", " <td>11200.0</td>\n", " </tr>\n", " <tr>\n", " <th>70</th>\n", " <th>Jacob</th>\n", " <th>Johnson</th>\n", " <td>10080.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " price\n", " sum\n", "customer_id firstname lastname \n", "81 Thomas Johnson 11200.0\n", "98 Cath Taylor 11200.0\n", "70 Jacob Johnson 10080.0" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Q10 Between January and March 2017, Who are top-3 customers that paid most for Coffee?¶\n", "#show total payment\n", "\n", "df_all=df_record.merge(right=df_item,left_on='item_id',right_index=True)\\\n", " .merge(right=df_transaction,left_on='transaction_id',right_index=True)\\\n", " .merge(right=df_customer,left_on='customer_id',right_index=True)\\\n", "\n", "df_all[\n", " (df_all.datetime.dt.year==2017) &\\\n", " (df_all.datetime.dt.month>=1) &\\\n", " (df_all.datetime.dt.month<=3) &\\\n", " (df_all.name=='Coffee')\n", " ]\\\n", " .groupby(['customer_id','firstname','lastname'])\\\n", " .agg({'price':['sum']})\\\n", " .sort_values(('price','sum'),ascending=False)\\\n", " .head(3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }
38,257
https://github.com/shoutem/extensions/blob/master/shoutem.auth/server/src/pages/protected-screens-page/components/protected-screen-row/index.js
Github Open Source
Open Source
BSD-3-Clause
2,023
extensions
shoutem
JavaScript
Code
7
22
import ProtectedScreenRow from './ProtectedScreenRow'; export default ProtectedScreenRow;
13,913
https://github.com/MichaelDiers/surveys/blob/master/frontend/SurveyFrame/client/scss/base/_typographie.scss
Github Open Source
Open Source
MIT
null
surveys
MichaelDiers
SCSS
Code
31
105
body { font-family: 'Montserrat', sans-serif; font-size: 110%; } h1 { font-size: 3rem; text-align: center; } form textarea { text-align: left; } .table-header { font-weight: bold; } .theme-toggle { font-size: 70%; }
26,589
https://github.com/jyi2ya/artifacts/blob/master/luogu.com.cn/P1015/a.c
Github Open Source
Open Source
MIT
null
artifacts
jyi2ya
C
Code
105
579
#define true (1) #define false (0) typedef int bool; #define inline static #include <stdio.h> #include <ctype.h> int num[10000],buf[10000]; int len,MODE; void out(int* a){ for(int i=0;i<len;i++) printf("%d ",a[i]); putchar('\n'); } void add(int* dest ,int* src){ for(int i=0;i<len;i++){ dest[i]+=src[i]; dest[i+1]+=(dest[i]/MODE); dest[i]%=MODE; } if(dest[len]>0)len++; } int isrevers(int* num){ int i=len-1,j=0; while(i>j){ if(num[i]!=num[j])return false; i--;j++; } return true; } void revers(int* a,int* b){ int i=len-1,j=0; while(i>=0){ a[i]=b[j]; i--;j++; } } void read(int* a){ scanf("%d",&MODE); int ch,i; while(!isalnum(ch=getchar())); ungetc(ch,stdin); for(i=0;isalnum(ch=getchar());i++){ if(isdigit(ch))buf[i]=ch-'0'; else if(islower(ch))buf[i]=ch-'a'+10; else if(isupper(ch))buf[i]=ch-'A'+10; } len=i; revers(a,buf); #ifdef DEBUG out(num); #endif } int main(){ read(num); int i; for(i=0;!isrevers(num) && i<=30;i++){ revers(buf,num); add(num,buf); } if(i>30)printf("Impossible!\n"); else printf("STEP=%d\n",i); return 0; }
30,703
https://github.com/devantennae786/idexy_custom_webapp/blob/master/src/app/pages/pages.module.ts
Github Open Source
Open Source
MIT
2,022
idexy_custom_webapp
devantennae786
TypeScript
Code
87
246
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { p404Component } from './404.component'; import { p500Component } from './500.component'; import { LoginComponent } from './login.component'; import { RegisterComponent } from './register.component'; import { PagesRoutingModule } from './pages-routing.module'; import { HttpClientService } from '../providers/http/http-client.service'; import { UserService } from '../providers/user/user.service'; @NgModule({ imports: [ CommonModule, PagesRoutingModule, FormsModule, ReactiveFormsModule ], declarations: [ p404Component, p500Component, LoginComponent, RegisterComponent ], providers: [ HttpClientService, UserService ] }) export class PagesModule { }
11,731
https://github.com/bhoffy2002/api-plugin-for-nopcommerce/blob/master/Nop.Plugin.Api/Services/IShipmentItemApiService.cs
Github Open Source
Open Source
MIT
null
api-plugin-for-nopcommerce
bhoffy2002
C#
Code
27
114
using System.Collections.Generic; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Shipping; namespace Nop.Plugin.Api.Services { public interface IShipmentItemApiService { IList<ShipmentItem> GetShipmentItemsForShipment(Shipment shipment, int limit, int page, int sinceId); int GetShipmentItemsCount(Shipment shipment); } }
23,205
https://github.com/halotron/ProtobufGenerator/blob/master/ProtobufGeneratorGRPC.cs
Github Open Source
Open Source
MIT
2,019
ProtobufGenerator
halotron
C#
Code
185
479
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Runtime.InteropServices; using System.CodeDom.Compiler; using System.CodeDom; using System.IO; using System.Text; using Microsoft.Win32; using Microsoft.VisualStudio.Shell; using VSLangProj80; namespace Knacka.Se.ProtobufGenerator { /// <summary> /// This is the generator class. /// When setting the 'Custom Tool' property of a C#, VB, or J# project item to "ProtobufGenerator", /// the GenerateCode function will get called and will return the contents of the generated file /// to the project system /// </summary> [ComVisible(true)] [Guid("52FD1149-33FA-4DD3-AC44-AB655C27671C")] [CodeGeneratorRegistration(typeof(ProtobufGeneratorGRPC), "ProtobufGeneratorGRPC - Generate C# from proto files", vsContextGuids.vsContextGuidVCSProject, GeneratesDesignTimeSource = true)] [CodeGeneratorRegistration(typeof(ProtobufGeneratorGRPC), "ProtobufGeneratorGRPC - Generate C# from proto files", TempNetSdkProjectGuid, GeneratesDesignTimeSource = true)] [ProvideObject(typeof(ProtobufGeneratorGRPC))] public class ProtobufGeneratorGRPC : ProtobufGeneratorBase { #pragma warning disable 0414 //The name of this generator (use for 'Custom Tool' property of project item) internal static string name = "ProtobufGeneratorGRPC"; #pragma warning restore 0414 protected override bool GenerateGRPC => true; } }
111
https://github.com/phadjido/CubismZ/blob/master/Tests/Test1_dp/genref.sh
Github Open Source
Open Source
BSD-2-Clause
2,019
CubismZ
phadjido
Shell
Code
160
390
#!/usr/bin/env bash # genref.sh # CubismZ # # Copyright 2018 ETH Zurich. All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # set -x #echo on [[ ! -f ../Data/demo_dp.h5 ]] && tar -C ../Data -xJf ../Data/data.tar.xz h5file=../Data/demo_dp.h5 bs=32 # block size (per dimension) (total: bs^3) ds=128 # domain size (per dimension) (total: ds^3) nb=4 # number of blocks (per dimension) (total: nb^3) # $(echo "$ds/$bs" | bc) rm -f ref.cz # remove any previous instance of the reference file ref.cz # 1x1x1 process grid with 16^3 blocks export OMP_NUM_THREADS=1 mpirun -n 1 ../../Tools/bin/default/hdf2cz -nprocx 1 -nprocy 1 -nprocz 1 -bpdx 4 -bpdy 4 -bpdz 4 -h5file $h5file -czfile ref.cz # 2x2x2 process grid with 8^3 blocks on each process # mpirun -n 8 ../../Tools/bin/default/hdf2cz -nprocx 2 -nprocy 2 -nprocz 2 -bpdx 2 -bpdy 2 -bpdz 2 -h5file $h5file -czfile ref.cz
13,937
https://github.com/fusion-jena/CoMerger/blob/master/SourceCode/src/fusion/comerger/algorithm/merger/holisticMerge/localTest/StatisticTest.java
Github Open Source
Open Source
Apache-2.0
2,022
CoMerger
fusion-jena
Java
Code
1,261
4,014
package fusion.comerger.algorithm.merger.holisticMerge.localTest; /* * CoMerger: Holistic Ontology Merging * %% * Copyright (C) 2019 Heinz Nixdorf Chair for Distributed Information Systems, Friedrich Schiller University Jena * %% * 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. */ /** * Author: Samira Babalou<br> * email: samira[dot]babalou[at]uni[dash][dot]jena[dot]de * Heinz-Nixdorf Chair for Distributed Information Systems<br> * Institute for Computer Science, Friedrich Schiller University Jena, Germany<br> * Date: 17/12/2019 */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.HashMap; import java.util.logging.Level; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import fusion.comerger.servlets.MatchingProcess; import fusion.comerger.algorithm.merger.holisticMerge.HolisticMerger; import fusion.comerger.algorithm.merger.holisticMerge.MyLogging; import fusion.comerger.algorithm.merger.holisticMerge.evaluator.HEvaluator; import fusion.comerger.algorithm.merger.model.HModel; public class StatisticTestGit { public static HashMap<String, String> result = new HashMap<String, String>(); public static int k = -1; public static String manualChanges = "NoChanges"; public static void main(String[] args) throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { runTestStatistic(); } public static void runTestStatistic() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { HolisticMerger MA = new HolisticMerger(); HEvaluator Eval = new HEvaluator(); HModel ontM = new HModel(); String Refinement_without_local = SetRefinement(); String Refinement_with_local = Refinement_without_local + "," + "localRefinement"; String prefferdOnt = "equal"; String evalDimension = SetEvalDimension(); long beforeUsedMem = 0, afterUsedMem = 0, actualMemUsed = 0; String ResultPath = "C:\\LOCAL_FOLDER\\HolisticDataSet\\result.csv"; GenerateOutput.createOutputHeader(ResultPath); int currentNumberDataSet = 3; int startIndex = 3; String[] address = new String[currentNumberDataSet + 1]; String baseAddress = "C:\\LOCAL_FOLDER\\HolisticDataSet\\"; for (int j = startIndex; j <= currentNumberDataSet; j++) address[j] = baseAddress + "d" + j; for (int i = startIndex; i <= currentNumberDataSet; i++) { File folder = new File(address[i] + "\\originalFiles"); String ontList = listFilesForFolder(folder); folder = new File(address[i] + "\\align_perfect"); String mappingFilePerfect = listFilesForFolder(folder); folder = new File(address[i] + "\\align_nonPerfect"); String mappingFileNonPerfect = listFilesForFolder(folder); String UPLOAD_DIRECTORY = address[i] + "\\"; // run version 1: perfect mapping with refinement with local // refinement // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); String testVersion = "$d_{" + i + "}V_1$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); // MA = new HolisticMerger(); // ontM = new HModel(); ontM = MA.run(ontList, mappingFilePerfect, UPLOAD_DIRECTORY, Refinement_with_local, prefferdOnt, "RDFtype"); // //Runtime.getRuntime().gc(); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed + "\n Strat doing evlaution"); // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); System.out.println("finsihed saving result in csv"); // **** // run version 2: perfect mapping with refinement without local // refinement // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); testVersion = "$d_{" + i + "}V_2$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); MA = new HolisticMerger(); ontM = MA.run(ontList, mappingFilePerfect, UPLOAD_DIRECTORY, Refinement_without_local, prefferdOnt, "RDFtype"); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); // run version 3: perfect mapping without any refinement // (without local refinement) // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); testVersion = "$d_{" + i + "}V_3$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); MA = new HolisticMerger(); ontM = MA.run(ontList, mappingFilePerfect, UPLOAD_DIRECTORY, null, prefferdOnt, "RDFtype"); // //Runtime.getRuntime().gc(); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); // run version 4: non-perfect mapping with refinement with local // refinement // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); testVersion = "$d_{" + i + "}V_4$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); MA = new HolisticMerger(); ontM = MA.run(ontList, mappingFileNonPerfect, UPLOAD_DIRECTORY, Refinement_with_local, prefferdOnt, "RDFtype"); // //Runtime.getRuntime().gc(); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); // run version 5: non-perfect mapping with refinement without // local refinement // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); testVersion = "$d_{" + i + "}V_5$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); MA = new HolisticMerger(); ontM = MA.run(ontList, mappingFileNonPerfect, UPLOAD_DIRECTORY, Refinement_without_local, prefferdOnt, "RDFtype"); // Runtime.getRuntime().gc(); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); // run version 6: non-perfect mapping without any refinement // (without local refinement) // Runtime.getRuntime().gc(); beforeUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); result = new HashMap<String, String>(); testVersion = "$d_{" + i + "}V_6$"; new MyLogging(UPLOAD_DIRECTORY); MyLogging.log(Level.INFO, "Log information for test_version: " + testVersion + "\n \n"); MA = new HolisticMerger(); ontM = MA.run(ontList, mappingFileNonPerfect, UPLOAD_DIRECTORY, null, prefferdOnt, "RDFtype"); // Runtime.getRuntime().gc(); afterUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); actualMemUsed = afterUsedMem - beforeUsedMem; // Runtime.getRuntime().gc(); // result.put("MU_TotalMerge", String.valueOf(actualMemUsed)); System.out.println("\t -***Total: \t afterUsedMem: " + afterUsedMem + "\t beforeUsedMem:" + beforeUsedMem + "\t actualMemUsed: " + actualMemUsed); Eval = new HEvaluator(); Eval.run(ontM, evalDimension); GenerateOutput.saveResult(ResultPath, testVersion, result); // insert empty line in output // GenerateOutput.inserEmptyLine(ResultPath); System.out.println("\t ---------********finished " + "d" + i); } System.out.println("The End!"); } public static String SetEvalDimension() { String eDim = new String(); eDim = "CompletenessCheck"; eDim = eDim + "," + "ConstraintCheck"; eDim = eDim + "," + "AcyclicityCheck"; eDim = eDim + "," + "ConnectivityCheck"; eDim = eDim + "," + "CoverageCheck"; // eDim = eDim + "," + "DeductionCheck"; return eDim; } public static String SetRefinement() { String Rules = new String(); Rules = "ClassCheck"; Rules = Rules + "," + "ProCheck"; Rules = Rules + "," + "InstanceCheck"; // Rules = Rules + "," + "CorresCheck"; // Rules = Rules + "," + "CorssPropCheck"; // Rules = Rules + "," + "ValueCheck"; Rules = Rules + "," + "StrCheck"; // Rules = Rules + "," + "ClRedCheck"; // Rules = Rules + "," + "ProRedCheck"; // Rules = Rules + "," + "InstRedCheck"; // Rules = Rules + "," + "ExtCheck"; Rules = Rules + "," + "DomRangMinCheck"; Rules = Rules + "," + "AcyClCheck"; Rules = Rules + "," + "AcyProCheck"; Rules = Rules + "," + "RecProCheck"; Rules = Rules + "," + "UnconnClCheck"; Rules = Rules + "," + "UnconnProCheck"; // Rules = Rules + "," + "EntCheck"; // Rules = Rules + "," + "TypeCheck"; // Rules = Rules + "," + "ConstValCheck"; return Rules; } public static String listFilesForFolder(final File folder) { String fileList = ""; for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { // listFilesForFolder(fileEntry); // do not need it } else { if (fileList == null || fileList.length() < 1) { fileList = fileEntry.toString(); } else { fileList = fileList + ";" + fileEntry.toString(); } } } return fileList; } }
9,364
https://github.com/santicevic/askSplit/blob/master/client/src/utils/role.js
Github Open Source
Open Source
MIT
null
askSplit
santicevic
JavaScript
Code
14
30
const Role = { Guest: "Guest", User: "User", Admin: "Admin" }; export default Role;
18,530
https://github.com/calnet-oss/ucb-ldif-diff/blob/master/src/main/groovy/edu/berkeley/calnet/ldif/UidExtractor.groovy
Github Open Source
Open Source
Apache-2.0, BSD-2-Clause, BSD-3-Clause
2,016
ucb-ldif-diff
calnet-oss
Groovy
Code
322
609
/* * Copyright (c) 2016, Regents of the University of California and * contributors. * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.berkeley.calnet.ldif /** * Extract a uid from DNs that start with "uid=". * * @author Brian Koehmstedt */ class UidExtractor implements UniqueIdentifierExtractor { /** * Extract uid from DN. */ String extractUniqueIdentifier(String dn) { if (dn.startsWith("uid=")) { return dn.substring(4, dn.indexOf(",")) } else { return null } } /** * Creates "uid=uniqueIdentifier" as the prefix to a DN. */ String uniqueIdentifierToDnPrefix(String uniqueIdentifier) { if (uniqueIdentifier) { return "uid=${uniqueIdentifier}," } else { return null } } /** * Returns "uid=uniqueIdentifier" from a DN that starts with a uid= prefix. */ String extractUniqueIdentifierAsDnPrefix(String dn) { return uniqueIdentifierToDnPrefix(extractUniqueIdentifier(dn)) } }
24,399
https://github.com/Berkaroad/AutoTestFramework.Net/blob/master/src/Examples/AutoTestFrameworkWinFormDemo/frmMain.Designer.cs
Github Open Source
Open Source
MIT
2,016
AutoTestFramework.Net
Berkaroad
C#
Code
921
4,589
namespace AutoTestFrameworkWinForm { partial class frmMain { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.button4 = new System.Windows.Forms.Button(); this.textBox2 = new System.Windows.Forms.TextBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.dataGridView2 = new System.Windows.Forms.DataGridView(); this.button5 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox3 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox4 = new System.Windows.Forms.TextBox(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.dataGridView3 = new System.Windows.Forms.DataGridView(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.tabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit(); this.tabPage3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 36); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(89, 12); this.label1.TabIndex = 0; this.label1.Text = "测试脚本文件:"; // // openFileDialog1 // this.openFileDialog1.Filter = "Html文件(*.html)|*.html"; this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(109, 31); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(300, 21); this.textBox1.TabIndex = 1; // // button1 // this.button1.Location = new System.Drawing.Point(416, 30); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(60, 23); this.button1.TabIndex = 2; this.button1.Text = "浏览"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(109, 68); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(90, 30); this.button2.TabIndex = 3; this.button2.Text = "加载测试脚本"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(233, 68); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(90, 30); this.button3.TabIndex = 5; this.button3.Text = "导出数据模板"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // saveFileDialog1 // this.saveFileDialog1.DefaultExt = "xlsx"; this.saveFileDialog1.Filter = "Excel文件(*.xlsx)|*.xlsx"; this.saveFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk); // // button4 // this.button4.Location = new System.Drawing.Point(610, 68); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(90, 30); this.button4.TabIndex = 6; this.button4.Text = "加载测试数据"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // textBox2 // this.textBox2.Location = new System.Drawing.Point(611, 30); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(300, 21); this.textBox2.TabIndex = 7; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Location = new System.Drawing.Point(4, 122); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(983, 445); this.tabControl1.TabIndex = 8; // // tabPage1 // this.tabPage1.Controls.Add(this.dataGridView1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(975, 419); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "测试脚本"; this.tabPage1.UseVisualStyleBackColor = true; // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(3, 3); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowTemplate.Height = 23; this.dataGridView1.Size = new System.Drawing.Size(969, 413); this.dataGridView1.TabIndex = 5; // // tabPage2 // this.tabPage2.Controls.Add(this.dataGridView2); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(975, 419); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "测试数据"; this.tabPage2.UseVisualStyleBackColor = true; // // dataGridView2 // this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView2.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView2.Location = new System.Drawing.Point(3, 3); this.dataGridView2.Name = "dataGridView2"; this.dataGridView2.RowTemplate.Height = 23; this.dataGridView2.Size = new System.Drawing.Size(969, 413); this.dataGridView2.TabIndex = 6; // // button5 // this.button5.Location = new System.Drawing.Point(918, 29); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(60, 23); this.button5.TabIndex = 9; this.button5.Text = "浏览"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // button6 // this.button6.Location = new System.Drawing.Point(715, 68); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(90, 30); this.button6.TabIndex = 10; this.button6.Text = "开始测试"; this.button6.UseVisualStyleBackColor = true; this.button6.Click += new System.EventHandler(this.button6_Click); // // button7 // this.button7.Location = new System.Drawing.Point(821, 68); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(90, 30); this.button7.TabIndex = 11; this.button7.Text = "导出测试结果"; this.button7.UseVisualStyleBackColor = true; this.button7.Visible = false; this.button7.Click += new System.EventHandler(this.button7_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(516, 35); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(89, 12); this.label2.TabIndex = 12; this.label2.Text = "测试数据文件:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(36, 9); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 12); this.label3.TabIndex = 13; this.label3.Text = "测试站点:"; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(107, 4); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(369, 21); this.textBox3.TabIndex = 14; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(516, 9); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(89, 12); this.label4.TabIndex = 15; this.label4.Text = "测试脚本标题:"; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(610, 4); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(300, 21); this.textBox4.TabIndex = 16; // // tabPage3 // this.tabPage3.Controls.Add(this.dataGridView3); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(975, 419); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "测试结果"; this.tabPage3.UseVisualStyleBackColor = true; // // dataGridView3 // this.dataGridView3.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView3.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView3.Location = new System.Drawing.Point(0, 0); this.dataGridView3.Name = "dataGridView3"; this.dataGridView3.RowTemplate.Height = 23; this.dataGridView3.Size = new System.Drawing.Size(975, 419); this.dataGridView3.TabIndex = 7; // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(990, 571); this.Controls.Add(this.textBox4); this.Controls.Add(this.label4); this.Controls.Add(this.textBox3); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.button7); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.tabControl1); this.Controls.Add(this.textBox2); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.Name = "frmMain"; this.Text = "自动化测试Demo"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.tabPage2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit(); this.tabPage3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.Button button4; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; private System.Windows.Forms.Button button7; private System.Windows.Forms.Label label2; private System.Windows.Forms.DataGridView dataGridView2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.DataGridView dataGridView3; } }
34,949
https://github.com/imacks/HOCON/blob/master/src/HOCON/Impl/HoconField.cs
Github Open Source
Open Source
Apache-2.0
null
HOCON
imacks
C#
Code
538
1,668
//----------------------------------------------------------------------- // <copyright file="HoconField.cs" company="Hocon Project"> // Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/hocon> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hocon { /// <summary> /// This class represents a key and value tuple representing a Hocon field. /// <code> /// root { /// items = [ /// "1", /// "2"] /// } /// </code> /// </summary> public sealed class HoconField:IHoconElement { private readonly List<HoconValue> _internalValues; /// <inheritdoc/> public IHoconElement Parent { get; } /// <inheritdoc/> public HoconType Type => Value.Type; /// <inheritdoc/> public string Raw => Value.Raw; public HoconPath Path { get; } public string Key => Path.Key; internal HoconField ParentField { get { var p = Parent; while (p != null && !(p is HoconField)) p = p.Parent; return p as HoconField; } } /// <summary> /// Returns true if there are old values stored. /// </summary> internal bool HasOldValues => _internalValues.Count > 1; public HoconValue Value { get => _internalValues.Count > 0 ? _internalValues.Last() : HoconValue.Undefined; //set => _internalValues.Add(value); } public HoconField(HoconPath path, HoconObject parent) { if(path == null) throw new ArgumentNullException(nameof(path)); Path = new HoconPath(path); Parent = parent; _internalValues = new List<HoconValue>(); } internal void EnsureFieldIsObject() { if (Type == HoconType.Object) return; var v = new HoconValue(this); var o = new HoconObject(v); v.Add(o); _internalValues.Add(v); } internal List<HoconSubstitution> SetValue(HoconValue value) { var removedSubs = new List<HoconSubstitution>(); if (value.Type == HoconType.Array || value.Type == HoconType.Literal) { var subs = value.GetSubstitutions(); if (subs.All(sub => sub.Path != Path)) { foreach (var item in _internalValues) { removedSubs.AddRange(item.GetSubstitutions()); } _internalValues.Clear(); } } _internalValues.Add(value); return removedSubs; } internal void RestoreOldValue() { if(HasOldValues) _internalValues.RemoveAt(_internalValues.Count - 1); } internal HoconValue OlderValueThan(IHoconElement marker) { var objectList = new List<HoconObject>(); var index = 0; while (index < _internalValues.Count) { var value = _internalValues[index]; if (value.Any(v => ReferenceEquals(v, marker))) { break; } switch (value.Type) { case HoconType.Object: objectList.Add(value.GetObject()); break; case HoconType.Literal: case HoconType.Array: objectList.Clear(); break; } index++; } if(objectList.Count == 0) return index == 0 ? null : _internalValues[index - 1]; var result = new HoconValue(null); var o = new HoconObject(result); result.Add(o); foreach (var obj in objectList) { o.Merge(obj); } return result; } public HoconObject GetObject() { List<HoconObject> objectList = new List<HoconObject>(); foreach (var value in _internalValues) { switch (value.Type) { case HoconType.Object: objectList.Add(value.GetObject()); break; case HoconType.Literal: case HoconType.Array: objectList.Clear(); break; } } switch (objectList.Count) { case 0: return null; case 1: return objectList[0]; default: return new HoconMergedObject(this, objectList); } } public string GetString() => Value.GetString(); public List<HoconValue> GetArray() => Value.GetArray(); internal void ResolveValue(HoconValue value) { if (value.Type != HoconType.Empty) return; ((HoconObject)Parent).ResolveValue(this); } public IHoconElement Clone(IHoconElement newParent) { var newField = new HoconField(Path, (HoconObject)newParent); newField._internalValues.AddRange(_internalValues); return newField; } public override string ToString() => ToString(0, 2); public string ToString(int indent, int indentSize) => Value.ToString(indent, indentSize); public bool Equals(IHoconElement other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return other is HoconField field && Path.Equals(field.Path) && Value.Equals(other); } public override bool Equals(object obj) { return obj is IHoconElement element && Equals(element); } public override int GetHashCode() { unchecked { return Path.GetHashCode() + Value.GetHashCode(); } } public static bool operator ==(HoconField left, HoconField right) { return Equals(left, right); } public static bool operator !=(HoconField left, HoconField right) { return !Equals(left, right); } } }
35,408
https://github.com/IOriens/taro-ui/blob/master/packages/taro-ui-demo/src/pages/form/form/index.tsx
Github Open Source
Open Source
MIT
null
taro-ui
IOriens
TypeScript
Code
288
1,156
import React from 'react' import { AtButton, AtCheckbox, AtForm, AtInput, AtToast } from '@ioriens/taro-ui' import { CheckboxOption } from 'types/checkbox' import { View } from '@tarojs/components' import Taro from '@tarojs/taro' import DocsHeader from '../../components/doc-header' import './index.scss' interface PageFormState { value1: string value2: string value3: CheckboxOption<string>[] text: string isOpened: boolean [key: string]: string | boolean | CheckboxOption<string>[] } export default class PageForm extends React.Component<{}, PageFormState> { public config: Taro.PageConfig = { navigationBarTitleText: 'Taro UI' } public constructor(props: any) { super(props) this.state = { value1: '', value2: '', value3: [], text: '', isOpened: false } } private handleChange(stateName: string, value: any): void { this.setState({ [stateName]: value }) } private handleSubmit(): void { const { value1, value2, value3 } = this.state if (!value1 || !value2) { this.setState({ isOpened: true, text: `表单必填项未填写完整` }) } else { this.setState({ isOpened: true, text: value3 && value3.length > 0 ? `${value1} / ${value2} / ${value3.join(',')}` : `${value1} / ${value2}` }) } this.closeToast() } private closeToast(): void { setTimeout(() => { this.setState({ isOpened: false }) }, 2000) } private handleReset(): void { this.setState({ isOpened: true, text: `表单已被重置`, value1: '', value2: '', value3: [] }) this.closeToast() } public render(): JSX.Element { return ( <View className='page'> <DocsHeader title='Form 表单'></DocsHeader> <View className='doc-body'> {/* 表单提交与重置 */} <View className='panel'> <View className='panel__title'>表单提交与重置</View> <View className='panel__content no-padding'> <View className='component-item'> <AtForm onSubmit={this.handleSubmit.bind(this)} onReset={this.handleReset.bind(this)} > <AtInput required name='value1' title='文本' type='text' placeholder='单行文本' value={this.state.value1} onChange={this.handleChange.bind(this, 'value1')} /> <AtInput required name='value2' title='密码' type='password' placeholder='请输入密码' value={this.state.value2} onChange={this.handleChange.bind(this, 'value2')} /> <AtCheckbox options={[ { label: 'iPhone X', value: 'iPhone X' }, { label: 'HUAWEI P20', value: 'HUAWEI P20' } ]} selectedList={this.state.value3} onChange={this.handleChange.bind(this, 'value3')} /> <View className='component-item__btn-group'> <View className='component-item__btn-group__btn-item'> <AtButton type='primary' formType='submit'> 提交 </AtButton> </View> <View className='component-item__btn-group__btn-item'> <AtButton formType='reset'>重置</AtButton> </View> </View> </AtForm> </View> </View> </View> </View> <AtToast text={this.state.text} isOpened={this.state.isOpened} ></AtToast> </View> ) } }
50,756
https://github.com/zhouyanan617/admin-template-vue/blob/master/src/views/Layout/components/HeaderToolBar.vue
Github Open Source
Open Source
MIT
2,020
admin-template-vue
zhouyanan617
Vue
Code
109
383
<template> <div :class="`header-tool-theme-${theme}`" class="header-tool"> <FullScreen class="action" /> <SettingAction class="action" @click="openSetting" /> <UserMenu class="action" /> </div> </template> <script> import FullScreen from './FullScreen'; import SettingAction from './SettingAction'; import UserMenu from './UserMenu'; export default { name: 'HeaderToolBar', components: { SettingAction, UserMenu, FullScreen, }, props: { theme: { type: String, validator: value => ['dark', 'light'].includes(value), default: 'light', }, }, methods: { openSetting() { this.$emit('click', 'setting'); }, }, }; </script> <style lang="less" scoped> @import '../../../assets/style/variables.less'; .header-tool { display: flex; align-items: center; flex-shrink: 0; margin-left: auto; &-theme { &-dark { .v-icon-hover:hover { cursor: pointer; color: white !important; background: @primary-color; } } &-light { .action { color: rgba(0, 0, 0, 0.76); } } } } </style>
43,695
https://github.com/bluehandle-open/bluehandle-pc/blob/master/src/my/sunny/communication/ServicesSearch.java
Github Open Source
Open Source
MIT
null
bluehandle-pc
bluehandle-open
Java
Code
238
798
package my.sunny.communication; import java.io.IOException; //import java.util.Enumeration; import java.util.Vector; import javax.bluetooth.*; import my.sunny.IBluetoothConst; public class ServicesSearch implements IBluetoothConst { private final Vector<String> serviceFound = new Vector<String>();//服务列表 // private private RemoteDevice device;//要查找服务的设备 public ServicesSearch(RemoteDevice device) { this.device = device; } public Vector<String> getServiceFound() throws InterruptedException { System.out.println("search return"); return serviceFound; } public void search() throws IOException, InterruptedException { serviceFound.clear(); UUID serviceUUID = new UUID(uuid, false); final Object serviceSearchCompletedEvent = new Object(); DiscoveryListener listener = new DiscoveryListener() { public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { } public void inquiryCompleted(int discType) { } public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { for (int i = 0; i < servRecord.length; i++) { String url = servRecord[i].getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); if (url == null) { continue; } serviceFound.add(url); DataElement serviceName = servRecord[i] .getAttributeValue(0x0100); if (serviceName != null) { System.out.println("service " + serviceName.getValue() + " found " + url); } else { System.out.println("service found " + url); } } } public void serviceSearchCompleted(int transID, int respCode) { System.out.println("service search completed!"); synchronized (serviceSearchCompletedEvent) { serviceSearchCompletedEvent.notifyAll(); } } }; UUID[] searchUuidSet = new UUID[] { serviceUUID }; int[] attrIDs = new int[] { 0x0100 // Service name }; synchronized (serviceSearchCompletedEvent) { String address = ""; String friendlyName = ""; try { address = device.getBluetoothAddress(); friendlyName = device.getFriendlyName(false); } catch (Exception e) { e.printStackTrace(); } System.out.println("search services(" + uuid + ") on " + address + " " + friendlyName); //LocalDevice.getLocalDevice().getDiscoveryAgent(); LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices( attrIDs, searchUuidSet, device, listener); serviceSearchCompletedEvent.wait(); } } }
17,493
https://github.com/idorom/Library-Project/blob/master/src/Utils/MyFileLogWriter.java
Github Open Source
Open Source
MIT
null
Library-Project
idorom
Java
Code
198
440
package Utils; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * A utility class for logging output text to a file * note: final means that we can't extends this class * @author Java Course Team 2019 - Ron Ellenbogen * @author University Of Haifa - Israel */ public final class MyFileLogWriter{ /** an output file */ static private File outputLogFile; /** a file writer buffer */ static private FileWriter writer; /** * Creates a file and a writer for logging */ public static void initializeMyFileWriter(){ /* If we don't want to override the same file each time then * we can use Calendar.getInstance().getTimeInMillis() by adding it * to the name of the file. */ outputLogFile = new File("output.txt"); try { writer = new FileWriter(outputLogFile); } catch (IOException e) { e.printStackTrace(); } } /** * Writes a text message to the log file in a separate line * @param message */ public static void writeToFileInSeparateLine(String message){ try { writer.write(message); writer.write(System.getProperty("line.separator")); } catch (IOException e) { e.printStackTrace(); } } /** * Saves the log file (by closing the file writer) */ public static void saveLogFile(){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }//END OF ~ MyFileLogWriter
34,643
https://github.com/fomich-artem/poi/blob/master/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeader.java
Github Open Source
Open Source
Apache-2.0
2,021
poi
fomich-artem
Java
Code
514
1,272
/* ==================================================================== 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. ==================================================================== */ package org.apache.poi.hdgf.chunks; import org.apache.poi.util.LittleEndian; import java.nio.charset.Charset; /** * A chunk header */ public abstract class ChunkHeader { private int type; private int id; private int length; private int unknown1; /** * Creates the appropriate ChunkHeader for the Chunk Header at * the given location, for the given document version. * * @param documentVersion the documentVersion - 4 and higher is supported * @param data the chunk data * @param offset the start offset in the chunk data * @return the ChunkHeader */ public static ChunkHeader createChunkHeader(int documentVersion, byte[] data, int offset) { if(documentVersion >= 6) { ChunkHeaderV6 ch; if(documentVersion > 6) { ch = new ChunkHeaderV11(); } else { ch = new ChunkHeaderV6(); } ch.setType((int)LittleEndian.getUInt(data, offset + 0)); ch.setId((int)LittleEndian.getUInt(data, offset + 4)); ch.setUnknown1((int)LittleEndian.getUInt(data, offset + 8)); ch.setLength((int)LittleEndian.getUInt(data, offset + 12)); ch.setUnknown2(LittleEndian.getShort(data, offset + 16)); ch.setUnknown3(LittleEndian.getUByte(data, offset + 18)); return ch; } else if(documentVersion == 5 || documentVersion == 4) { ChunkHeaderV4V5 ch = new ChunkHeaderV4V5(); ch.setType(LittleEndian.getShort(data, offset + 0)); ch.setId(LittleEndian.getShort(data, offset + 2)); ch.setUnknown2(LittleEndian.getUByte(data, offset + 4)); ch.setUnknown3(LittleEndian.getUByte(data, offset + 5)); ch.setUnknown1(LittleEndian.getShort(data, offset + 6)); ch.setLength(Math.toIntExact(LittleEndian.getUInt(data, offset + 8))); return ch; } else { throw new IllegalArgumentException("Visio files with versions below 4 are not supported, yours was " + documentVersion); } } /** * Returns the size of a chunk header for the given document version. * * @param documentVersion the documentVersion - 4 and higher is supported * * @return the header size */ public static int getHeaderSize(int documentVersion) { if(documentVersion > 6) { return ChunkHeaderV11.getHeaderSize(); } else if(documentVersion == 6) { return ChunkHeaderV6.getHeaderSize(); } else { return ChunkHeaderV4V5.getHeaderSize(); } } public abstract int getSizeInBytes(); public abstract boolean hasTrailer(); public abstract boolean hasSeparator(); public abstract Charset getChunkCharset(); /** * @return the ID/IX of the chunk */ public int getId() { return id; } /** * Returns the length of the trunk, excluding the length * of the header, trailer or separator. * * @return the length of the trunk */ public int getLength() { return length; } /** * Returns the type of the chunk, which affects the * mandatory information * * @return the type of the chunk */ public int getType() { return type; } public int getUnknown1() { return unknown1; } void setType(int type) { this.type = type; } void setId(int id) { this.id = id; } void setLength(int length) { this.length = length; } void setUnknown1(int unknown1) { this.unknown1 = unknown1; } }
3,502
https://github.com/henryyp/codevember2016/blob/master/client/common/wrapper/RootWrapper/RootWrapper.js
Github Open Source
Open Source
Apache-2.0
null
codevember2016
henryyp
JavaScript
Code
36
118
import React from 'react' import './RootWrapper.scss' class RootWrapper extends React.Component { constructor() { super() } componentWillMount() { } render() { return( <div className="rootwrapper__mediahelper"> <div className="rootwrapper__container"> { this.props.children } </div> </div> ) } } export default RootWrapper
41,432
https://github.com/vangiaurecca/Course_CSharp_Basic/blob/master/HocListView/HocListView/SanPham.cs
Github Open Source
Open Source
MIT
null
Course_CSharp_Basic
vangiaurecca
C#
Code
47
108
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HocListView { public class SanPham { public string Ma { get; set; } public string Ten { get; set; } public int Gia { get; set; } public DanhMuc Nhom { get; set; } } }
29,412
https://github.com/vkorotenko/ChatApplication/blob/master/ChatApplication/rcv2/src/components/NavHeader.vue
Github Open Source
Open Source
MIT
2,022
ChatApplication
vkorotenko
Vue
Code
309
1,178
<template> <div class="nav-header"> <div class="row btn_bar"> <div class="col-md-2 mp-0 w36"> <ul class="ul_btn_bar"> <li v-if="showBackButton" @click="backToTopics"> <img src="/img/rc/back_ico.png" class="back_span back_btn"> </li> </ul> </div> <div class="col-md-8 mp-0" style="padding-top: 9px;"> <h2> {{ titleText }} </h2> <span class="rigth_chat_count_bg" v-if="unreadMessages > 0 && !messageMode"> {{unreadMessages}} </span> </div> <div class="col-md-2 mp-0" style="width: 74px;margin-left: auto;"> <ul class="ul_btn_bar"> <li @click="closePanel"> <span class="close_span minimize_btn"></span> </li> <li v-if="appstatemax" @click="collapse"> <span class="close_span restore_btn" v-if="appstatemax"></span> </li> <li v-if="!appstatemax" @click="maximize"> <span class="close_span maximize_btn" v-if="!appstatemax"></span> </li> </ul> </div> </div> </div> </template> <script> var openPanelKey = 'openPanelKey'; import { mapMutations } from 'vuex'; export default { name: 'NavHeader', props: { title: { type: String, default: 'ЧАТ ПОДДЕРЖКИ' } }, data: function () { return { messageMode: false, titleText: this.title, showBackButton: false, unreadMessages: 0 } }, computed: { appstatemax() { return this.$store.state.appstatemax; } }, methods: { ...mapMutations({ minimizeChat: 'minimize', maximizeChat: 'maximize' }), switchTitle: function () { this.messageMode = !this.messageMode; if (this.messageMode) { this.titleText = 'ВЫЙТИ ИЗ ДИАЛОГА' this.showBackButton = true; } else { this.titleText = 'ЧАТ ПОДДЕРЖКИ' this.showBackButton = false; } }, backToTopics: function () { window.console.log('backToTopics'); // todo: backToTopics }, closePanel: function () { var bottom = getComputedStyle(document.getElementById('rigth-chat-app')).bottom; var state = false; if (bottom == '0px') { window.console.log('bottom: 0'); } else { window.console.log('bottom: ' + bottom); } window.console.log('closeRigthPanel: ' + state); localStorage.setItem(openPanelKey, state); showRigthChat(state); }, collapse: function () { window.console.log('minimize'); var chat = document.getElementById('rigth-chat-app'); chat.style.transition = ''; setTimeout(function () { chat.style.transition = 'opacity .4s ease-in, height 0.8s ease-in-out '; chat.style.height = '60%'; }, 4); setTimeout(function () { chat.style.transition = ''; }, 800); this.minimizeChat(); }, maximize: function () { window.console.log('maximize'); // todo: maximize var chat = document.getElementById('rigth-chat-app'); chat.style.transition = ''; setTimeout(function () { chat.style.transition = 'opacity .4s ease-in, height 0.8s ease-in-out '; chat.style.height = '100%'; }, 4); setTimeout(function () { chat.style.transition = ''; }, 800); this.maximizeChat(); }, } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
26,798
https://github.com/BEP-store/bepstore-ui-user/blob/master/app/styles/profile.sass
Github Open Source
Open Source
MIT
null
bepstore-ui-user
BEP-store
Sass
Code
47
185
.big_picture border-radius: 50% height: 400px width: 400px margin-top: -150px overflow: hidden margin-left: 25% margin-bottom: 20px -webkit-box-shadow: 10px 10px 22px 12px rgba(0,0,0,0.75) -moz-box-shadow: 10px 10px 22px 12px rgba(0,0,0,0.75) box-shadow: 10px 10px 22px 12px rgba(0,0,0,0.75) .name_pic font-size: 80px text-align: center height: 250px padding-top: 150px background-color: rgba(0, 125, 0, 0.8)
13,575
https://github.com/SapphireSuite/Engine/blob/master/Tests/UnitTests/Core/Debug/ToStringTests.cpp
Github Open Source
Open Source
MIT
2,022
Engine
SapphireSuite
C++
Code
287
1,200
// Copyright (c) 2021 Sapphire's Suite. All Rights Reserved. #include <UnitTestHelper> #include <SA/Core/Debug/ToString.hpp> using namespace Sa; #if SA_LOGGING namespace Sa::ToString_UT { enum class TestEnum { V1 = 1, V2 = 2 }; struct A { int i = 0; std::string ToString() const { return std::to_string(i); } }; struct B { int i = 0; std::string ToString() const { return std::to_string(i); } std::wstring ToWString() const { return std::to_wstring(i) + L'W'; } }; void ToStringFunc() { const std::string helloStr = "Hello"; SA_UTH_EQ(ToString("Hello"), helloStr); SA_UTH_EQ(ToString(helloStr), helloStr); const int i = 5498; SA_UTH_EQ(ToString(i), std::to_string(i)); SA_UTH_EQ(ToString(2.5f), std::to_string(2.5f)); SA_UTH_EQ(ToString(TestEnum::V2), std::string("2")); SA_UTH_EQ(ToString(&i), "0x" + std::to_string(reinterpret_cast<uint64>(&i))); const A a1{ 9 }; SA_UTH_EQ(ToString(a1), std::to_string(a1.i)); const B b1{ 4 }; SA_UTH_EQ(ToString(b1), std::to_string(b1.i)); int tab1[]{ 5, 6, 3, 4 }; SA_UTH_EQ(ToString(tab1, 4), std::string("{ 5, 6, 3, 4 }")); std::vector<int> v1 = { 6, 8, 1, 3, 4 }; SA_UTH_EQ(ToString(v1), std::string("{ 6, 8, 1, 3, 4 }")); const std::wstring h5 = std::wstring(L"Hello") << ", World!" << L" WIDE " << 5; SA_UTH_EQ(h5, std::wstring(L"Hello, World! WIDE 5")); } void ToWStringFunc() { const std::string helloStr = "Hello"; const std::wstring whelloStr = L"Hello"; SA_UTH_EQ(ToWString("Hello"), whelloStr); SA_UTH_EQ(ToWString(L"Hello"), whelloStr); SA_UTH_EQ(ToWString(helloStr), whelloStr); SA_UTH_EQ(ToWString(whelloStr), whelloStr); const int i = 5498; SA_UTH_EQ(ToWString(i), std::to_wstring(i)); SA_UTH_EQ(ToWString(2.5f), std::to_wstring(2.5f)); SA_UTH_EQ(ToWString(TestEnum::V2), std::wstring(L"2")); SA_UTH_EQ(ToWString(&i), L"0x" + std::to_wstring(reinterpret_cast<uint64>(&i))); const A a1{ 9 }; SA_UTH_EQ(ToWString(a1), std::to_wstring(a1.i)); const B b1{ 4 }; SA_UTH_EQ(ToWString(b1), std::to_wstring(b1.i) + L'W'); int tab1[]{ 5, 6, 3, 4 }; auto aaa = ToWString(tab1, 4); SA_UTH_EQ(ToWString(tab1, 4), std::wstring(L"{ 5, 6, 3, 4 }")); std::vector<int> v1 = { 6, 8, 1, 3, 4 }; SA_UTH_EQ(ToWString(v1), std::wstring(L"{ 6, 8, 1, 3, 4 }")); const std::string h5 = std::string("Hello") << ", World! " << 5; SA_UTH_EQ(h5, std::string("Hello, World! 5")); } } void ToStringTests() { using namespace ToString_UT; SA_UTH_GP(ToStringFunc()); SA_UTH_GP(ToWStringFunc()); } #else void ToStringTests() { } #endif
18,556
https://github.com/tdurieux/smartbugs-wild/blob/master/contracts/0xd99aa77aa54f352f92b284c8a86521c93c067dc6.sol
Github Open Source
Open Source
Apache-2.0
2,022
smartbugs-wild
tdurieux
Solidity
Code
570
1,443
pragma solidity ^0.4.19; contract Ownable { address public owner; /** * The address whcih deploys this contrcat is automatically assgined ownership. * */ function Ownable() public { owner = msg.sender; } /** * Functions with this modifier can only be executed by the owner of the contract. * */ modifier onlyOwner { require(msg.sender == owner); _; } event OwnershipTransferred(address indexed from, address indexed to); /** * Transfers ownership to new Ethereum address. This function can only be called by the * owner. * @param _newOwner the address to be granted ownership. **/ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract TokenInterface { function transfer(address to, uint256 value) public returns (bool); } contract ICO is Ownable { using SafeMath for uint256; string public website = "www.propvesta.com"; uint256 public rate; uint256 public tokensSold; address public fundsWallet = 0x304f970BaA307238A6a4F47caa9e0d82F082e3AD; TokenInterface public constant PROV = TokenInterface(0x409Ec1FCd524480b3CaDf4331aF21A2cB3Db68c9); function ICO() public { rate = 20000000; } function changeRate(uint256 _newRate) public onlyOwner { require(_newRate > 0 && rate != _newRate); rate = _newRate; } function changeFundsWallet(address _fundsWallet) public onlyOwner returns(bool) { fundsWallet = _fundsWallet; return true; } event TokenPurchase(address indexed investor, uint256 tokensPurchased); function buyTokens(address _investor) public payable { require(msg.value >= 1e16); uint256 exchangeRate = rate; uint256 bonus = 0; uint256 investment = msg.value; uint256 remainder = 0; if(investment >= 1e18 && investment < 2e18) { bonus = 30; } else if(investment >= 2e18 && investment < 3e18) { bonus = 35; } else if(investment >= 3e18 && investment < 4e18) { bonus = 40; } else if(investment >= 4e18 && investment < 5e18) { bonus = 45; } else if(investment >= 5e18) { bonus = 50; } exchangeRate = rate.mul(bonus).div(100).add(rate); uint256 toTransfer = 0; if(investment > 10e18) { uint256 bonusCap = 10e18; toTransfer = bonusCap.mul(exchangeRate); remainder = investment.sub(bonusCap); toTransfer = toTransfer.add(remainder.mul(rate)); } else { toTransfer = investment.mul(exchangeRate); } PROV.transfer(_investor, toTransfer); TokenPurchase(_investor, toTransfer); tokensSold = tokensSold.add(toTransfer); fundsWallet.transfer(investment); } function() public payable { buyTokens(msg.sender); } function getTokensSold() public view returns(uint256) { return tokensSold; } event TokensWithdrawn(uint256 totalPROV); function withdrawPROV(uint256 _value) public onlyOwner { PROV.transfer(fundsWallet, _value); TokensWithdrawn(_value); } }
13,343
https://github.com/KristiansKaneps/ToolModifiers/blob/master/src/main/java/k4neps/toolmodifiers/PermCheck.java
Github Open Source
Open Source
MIT
null
ToolModifiers
KristiansKaneps
Java
Code
146
573
package k4neps.toolmodifiers; import org.bukkit.entity.Player; /** * Created by Kristians on 7/28/2017. * * @author Kristians */ public final class PermCheck { private PermCheck() {} public static boolean hasPerm(Player p, String perm) { return p.hasPermission(perm); } public static boolean canUseHammer(Player p) { return hasPerm(p, "toolmodifiers.hammer.use"); } public static boolean canUseExcavator(Player p) { return hasPerm(p, "toolmodifiers.excavator.use"); } public static boolean canUseLumberaxe(Player p) { return hasPerm(p, "toolmodifiers.lumberaxe.use"); } public static boolean canUseLumberaxeToCutTrees(Player p) { return hasPerm(p, "toolmodifiers.lumberaxe.tree"); } public static boolean canCraftHammer(Player p) { return hasPerm(p, "toolmodifiers.hammer.craft"); } public static boolean canCraftExcavator(Player p) { return hasPerm(p, "toolmodifiers.excavator.craft"); } public static boolean canCraftLumberaxe(Player p) { return hasPerm(p, "toolmodifiers.lumberaxe.craft"); } public static boolean canGiveHammerToTheirselves(Player p) { return hasPerm(p, "toolmodifiers.command.give.hammer"); } public static boolean canGiveExcavatorToTheirselves(Player p) { return hasPerm(p, "toolmodifiers.command.give.excavator"); } public static boolean canGiveLumberaxeToTheirselves(Player p) { return hasPerm(p, "toolmodifiers.command.give.lumberaxe"); } public static boolean canUseBaseCommand(Player p) { return hasPerm(p, "toolmodifiers.command"); } }
25,563
https://github.com/eFaps/eFaps-Kernel-Install/blob/master/src/main/efaps/ESJP/org/efaps/esjp/common/properties/PropertiesUtil_Base.java
Github Open Source
Open Source
Apache-2.0
null
eFaps-Kernel-Install
eFaps
Java
Code
930
2,254
/* * Copyright 2003 - 2016 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.common.properties; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.TreeMap; import java.util.UUID; import org.efaps.admin.common.SystemConfiguration; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.util.EFapsException; import org.efaps.util.UUIDUtil; /** * Util class for Properties management. * * @author The eFaps Team */ @EFapsUUID("3e4ee06b-6f4a-4806-a736-e7f48d438b74") @EFapsApplication("eFaps-Kernel") public abstract class PropertiesUtil_Base { /** * Get the properties map. Reads first the Map from * <code>ParameterValues.PROPERTIES</code> and than checks for overwrite by * a SystenConfiguration. * * @param _parameter the _parameter * @return the properties map internal * @throws EFapsException the e faps exception */ @SuppressWarnings("unchecked") protected static Map<?, ?> getPropertiesMap(final Parameter _parameter) throws EFapsException { Map<Object, Object> ret = (Map<Object, Object>) _parameter.get(ParameterValues.PROPERTIES); if (ret == null) { ret = new HashMap<>(); } if (ret != null && ret.containsKey("PropertiesConfig")) { final String config = (String) ret.get("PropertiesConfig"); final SystemConfiguration sysConf; if (UUIDUtil.isUUID(config)) { sysConf = SystemConfiguration.get(UUID.fromString(config)); } else { sysConf = SystemConfiguration.get(config); } if (sysConf != null) { final Properties props = sysConf .getAttributeValueAsProperties((String) ret.get("PropertiesConfigAttribute")); ret = (Map<Object, Object>) _parameter.get(ParameterValues.PROPERTIES); ret.putAll(props); } } return ret; } /** * Get the properties map. Reads first the Map from * <code>ParameterValues.PROPERTIES</code> and than checks for overwrite by * a SystenConfiguration. * * @param _parameter the _parameter * @return the properties map internal * @throws EFapsException the e faps exception */ protected static Properties getProperties(final Parameter _parameter) throws EFapsException { final Properties ret = new Properties(); final Map<?, ?> map = PropertiesUtil.getPropertiesMap(_parameter); ret.putAll(map); return ret; } /** * Check for a Property form the ParameterValues. * * @param _parameter Parameter as passed by the eFaps API * @param _key key of the Property * @return value for the Property, null if not found * @throws EFapsException on error */ protected static boolean containsProperty(final Parameter _parameter, final String _key) throws EFapsException { final Map<?, ?> propertiesMap = PropertiesUtil.getPropertiesMap(_parameter); return propertiesMap.containsKey(_key); } /** * Get a Property form the ParameterValues. * * @param _parameter Parameter as passed by the eFaps API * @param _key key of the Property * @return value for the Property, null if not found * @throws EFapsException on error */ protected static String getProperty(final Parameter _parameter, final String _key) throws EFapsException { return PropertiesUtil.getProperty(_parameter, _key, null); } /** * Get a Property form the ParameterValues. * * @param _parameter Parameter as passed by the eFaps API * @param _key key of the Property * @param _defaultValue defaultvalue * @return value for the Property, if not found the defaultvalue * @throws EFapsException on error */ protected static String getProperty(final Parameter _parameter, final String _key, final String _defaultValue) throws EFapsException { final String ret; if (PropertiesUtil_Base.containsProperty(_parameter, _key)) { final Map<?, ?> propertiesMap = PropertiesUtil.getPropertiesMap(_parameter); ret = String.valueOf(propertiesMap.get(_key)); } else { ret = _defaultValue; } return ret; } /** * Search for the given Property and returns a tree map with the found * values.<br/> * Properties like:<br/> * Name<br/> * Name01<br/> * Name02<br/> * Will return a map with:<br/> * 0 - Value for Name<br/> * 1 - Value for Name01<br/> * 2 - Value for Name02 * * @param _parameter Parameter as passed by the eFaps API * @param _key key of the Property * @param _offset offset to start to search for * @return map with properties * @throws EFapsException on error */ protected static Map<Integer, String> analyseProperty(final Parameter _parameter, final String _key, final int _offset) throws EFapsException { return PropertiesUtil.analyseProperty(PropertiesUtil.getProperties(_parameter), _key, _offset); } /** * Analyse property. * * @param _properties the properties * @param _key the key * @param _offset the offset * @return the map * @throws EFapsException the e faps exception */ protected static Map<Integer, String> analyseProperty(final Properties _properties, final String _key, final int _offset) throws EFapsException { final Map<Integer, String> ret = new TreeMap<>(); // test for basic final int start = _offset == 0 ? 1 : _offset; if (_offset == 0 && _properties.containsKey(_key)) { ret.put(0, String.valueOf(_properties.get(_key))); } String formatStr = "%02d"; if (start > 99) { formatStr = "%03d"; } for (int i = start; i < start + 100; i++) { final String nameTmp = _key + String.format(formatStr, i); if (_properties.containsKey(nameTmp)) { ret.put(i, String.valueOf(_properties.get(nameTmp))); } else { break; } } return ret; } /** * Gets the properties4 prefix. * * @param _properties the properties * @param _prefix the prefix * @return the properties4 prefix */ protected static Properties getProperties4Prefix(final Properties _properties, final String _prefix) { return PropertiesUtil.getProperties4Prefix(_properties, _prefix, false); } /** * Gets the properties4 prefix. * * @param _properties the properties * @param _prefix the prefix * @param _exclude exclude the property if it not starts with the prefix * @return the properties4 prefix */ protected static Properties getProperties4Prefix(final Properties _properties, final String _prefix, final boolean _exclude) { final Properties ret = new Properties(); final String key = _prefix == null ? null : _prefix + "."; for (final Entry<Object, Object> entry : _properties.entrySet()) { if (_prefix != null) { if (entry.getKey().toString().startsWith(key)) { ret.put(entry.getKey().toString().replace(key, ""), entry.getValue()); } else if (!_exclude) { ret.put(entry.getKey(), entry.getValue()); } } else { ret.put(entry.getKey(), entry.getValue()); } } return ret; } }
46,768
https://github.com/berndpfrommer/image_denoising/blob/master/include/image_denoising/nl_means_filter.h
Github Open Source
Open Source
Apache-2.0
2,021
image_denoising
berndpfrommer
C
Code
189
534
// -*-c++-*-------------------------------------------------------------------- // Copyright 2021 Bernd Pfrommer <bernd.pfrommer@gmail.com> // // 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. #ifndef IMAGE_DENOISING_NL_MEANS_FILTER_H_ #define IMAGE_DENOISING_NL_MEANS_FILTER_H_ #include <dynamic_reconfigure/server.h> #include <deque> #include <memory> #include <opencv2/core/core.hpp> #include "image_denoising/NLMeansDynConfig.h" #include "image_denoising/filter.h" namespace image_denoising { class NLMeansFilter : public Filter { public: using Config = NLMeansDynConfig; NLMeansFilter(const ros::NodeHandle & nh); ~NLMeansFilter(); // --- inherited from Filter --- bool initialize() override; void processImage(const StampedImage & img) override; StampedImage getNextDenoisedImage() override; private: StampedImage denoiseSingleImage(const StampedImage & si) const; StampedImage denoiseCenterImage() const; void configure(Config & config, int level); // ------ variables --------- std::shared_ptr<dynamic_reconfigure::Server<Config>> configServer_; std::deque<StampedImage> imageQueue_; float h_{3.0}; int templateWindowSize_{7}; int searchWindowSize_{21}; size_t maxQueueSize_{3}; }; } // namespace image_denoising #endif
6,607
https://github.com/ScalablyTyped/Distribution/blob/master/w/wix-style-react/src/main/scala/typings/wixStyleReact/distTypesTestUtilsUtilsUnidriverReactBaseMod.scala
Github Open Source
Open Source
MIT
2,023
Distribution
ScalablyTyped
Scala
Code
61
282
package typings.wixStyleReact import typings.wixStyleReact.anon.BeforeInput import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object distTypesTestUtilsUtilsUnidriverReactBaseMod { object ReactBase { inline def apply( base: /* import warning: transforms.QualifyReferences#resolveTypeRef many Couldn't qualify UniDriver */ Any ): BeforeInput = ^.asInstanceOf[js.Dynamic].apply(base.asInstanceOf[js.Any]).asInstanceOf[BeforeInput] @JSImport("wix-style-react/dist/types/test-utils/utils/unidriver/ReactBase", "ReactBase") @js.native val ^ : js.Any = js.native inline def clickBody(): Boolean = ^.asInstanceOf[js.Dynamic].applyDynamic("clickBody")().asInstanceOf[Boolean] inline def clickDocument(): Boolean = ^.asInstanceOf[js.Dynamic].applyDynamic("clickDocument")().asInstanceOf[Boolean] } }
29,867
https://github.com/tgraupmann/SwaggerJavaExportFixes/blob/master/src/main/java/io/swagger/client/model/TournamentQualifierTieBreakerModel.java
Github Open Source
Open Source
Apache-2.0
null
SwaggerJavaExportFixes
tgraupmann
Java
Code
471
1,623
/* * Polling API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.swagger.client.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * TournamentQualifierTieBreakerModel */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-02T00:05:30.138Z") public class TournamentQualifierTieBreakerModel { @SerializedName("TieBreakerLevelId") private Integer tieBreakerLevelId = null; @SerializedName("TieBreakerTypeId") private Integer tieBreakerTypeId = null; @SerializedName("TieBreakerName") private String tieBreakerName = null; @SerializedName("TieBreakerDescription") private String tieBreakerDescription = null; public TournamentQualifierTieBreakerModel tieBreakerLevelId(Integer tieBreakerLevelId) { this.tieBreakerLevelId = tieBreakerLevelId; return this; } /** * Get tieBreakerLevelId * @return tieBreakerLevelId **/ @ApiModelProperty(example = "null", value = "") public Integer getTieBreakerLevelId() { return tieBreakerLevelId; } public void setTieBreakerLevelId(Integer tieBreakerLevelId) { this.tieBreakerLevelId = tieBreakerLevelId; } public TournamentQualifierTieBreakerModel tieBreakerTypeId(Integer tieBreakerTypeId) { this.tieBreakerTypeId = tieBreakerTypeId; return this; } /** * Get tieBreakerTypeId * @return tieBreakerTypeId **/ @ApiModelProperty(example = "null", value = "") public Integer getTieBreakerTypeId() { return tieBreakerTypeId; } public void setTieBreakerTypeId(Integer tieBreakerTypeId) { this.tieBreakerTypeId = tieBreakerTypeId; } public TournamentQualifierTieBreakerModel tieBreakerName(String tieBreakerName) { this.tieBreakerName = tieBreakerName; return this; } /** * Get tieBreakerName * @return tieBreakerName **/ @ApiModelProperty(example = "null", value = "") public String getTieBreakerName() { return tieBreakerName; } public void setTieBreakerName(String tieBreakerName) { this.tieBreakerName = tieBreakerName; } public TournamentQualifierTieBreakerModel tieBreakerDescription(String tieBreakerDescription) { this.tieBreakerDescription = tieBreakerDescription; return this; } /** * Get tieBreakerDescription * @return tieBreakerDescription **/ @ApiModelProperty(example = "null", value = "") public String getTieBreakerDescription() { return tieBreakerDescription; } public void setTieBreakerDescription(String tieBreakerDescription) { this.tieBreakerDescription = tieBreakerDescription; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TournamentQualifierTieBreakerModel tournamentQualifierTieBreakerModel = (TournamentQualifierTieBreakerModel) o; return Objects.equals(this.tieBreakerLevelId, tournamentQualifierTieBreakerModel.tieBreakerLevelId) && Objects.equals(this.tieBreakerTypeId, tournamentQualifierTieBreakerModel.tieBreakerTypeId) && Objects.equals(this.tieBreakerName, tournamentQualifierTieBreakerModel.tieBreakerName) && Objects.equals(this.tieBreakerDescription, tournamentQualifierTieBreakerModel.tieBreakerDescription); } @Override public int hashCode() { return Objects.hash(tieBreakerLevelId, tieBreakerTypeId, tieBreakerName, tieBreakerDescription); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TournamentQualifierTieBreakerModel {\n"); sb.append(" tieBreakerLevelId: ").append(toIndentedString(tieBreakerLevelId)).append("\n"); sb.append(" tieBreakerTypeId: ").append(toIndentedString(tieBreakerTypeId)).append("\n"); sb.append(" tieBreakerName: ").append(toIndentedString(tieBreakerName)).append("\n"); sb.append(" tieBreakerDescription: ").append(toIndentedString(tieBreakerDescription)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
5,269
https://github.com/wuyinlei/CocosDemo/blob/master/assets/cases/02_ui/03_button/ButtonInScroll/ButtonControl.js
Github Open Source
Open Source
Apache-2.0
null
CocosDemo
wuyinlei
JavaScript
Code
97
262
cc.Class({ extends: cc.Component, properties: { // foo: { // default: null, // The default value will be used only when the component attaching // to a node for the first time // url: cc.Texture2D, // optional, default is typeof default // serializable: true, // optional, default is true // visible: true, // optional, default is true // displayName: 'Foo', // optional // readonly: false, // optional, default is false // }, // ... button_1: cc.Button, button_2: cc.Button, display: cc.Label }, onClikcedButton_1: function(){ console.log('button_1 clikced'); this.display.string = "button_1"; }, onClikcedButton_2: function(){ console.log('button_2 clikced'); this.display.string = "button_2"; }, });
46,341
https://github.com/inqwell/inq/blob/master/src/main/java/com/inqwell/any/channel/WriteClosedChannelException.java
Github Open Source
Open Source
BSD-3-Clause
2,016
inq
inqwell
Java
Code
112
265
/** * Copyright (C) 2011 Inqwell Ltd * * You may distribute under the terms of the Artistic License, as specified in * the README file. */ /* * $Archive: /src/com/inqwell/any/channel/WriteClosedChannelException.java $ * $Author: sanderst $ * $Revision: 1.2 $ * $Date: 2011-04-07 22:18:22 $ */ package com.inqwell.any.channel; import com.inqwell.any.AnyException; /** * An exception that is thrown to indicate that a channel has * been closed and may no longer be written to. * @author $Author: sanderst $ * @version $Revision: 1.2 $ * @see com.inqwell.any.Any */ public class WriteClosedChannelException extends AnyException { public WriteClosedChannelException() {} public WriteClosedChannelException(String s) { super(s); } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
2,445
https://github.com/truthiswill/intellij-community/blob/master/plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenActionsUsagesCollector.kt
Github Open Source
Open Source
Apache-2.0
null
intellij-community
truthiswill
Kotlin
Code
157
637
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.statistics import com.intellij.internal.statistic.service.fus.collectors.FUSProjectUsageTrigger import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext import com.intellij.internal.statistic.service.fus.collectors.ProjectUsageTriggerCollector import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.util.text.nullize class MavenActionsUsagesCollector : ProjectUsageTriggerCollector() { override fun getGroupId() = "statistics.build.maven.actions" companion object { @JvmStatic fun trigger(project: Project?, featureId: String, place: String?, isFromContextMenu: Boolean, vararg additionalContextData: String) { if (project == null) return // preserve context data ordering val context = FUSUsageContext.create( place.nullize(true) ?: "undefined place", "fromContextMenu.$isFromContextMenu", *additionalContextData ) FUSProjectUsageTrigger.getInstance(project).trigger(MavenActionsUsagesCollector::class.java, UsageDescriptorKeyValidator.ensureProperKey(featureId), context) } @JvmStatic fun trigger(project: Project?, action: AnAction, event: AnActionEvent?, vararg additionalContextData: String) { trigger(project, action.javaClass.simpleName, event?.place, event?.isFromContextMenu ?: false, *additionalContextData) } @JvmStatic fun trigger(project: Project?, featureId: String, event: AnActionEvent?, vararg additionalContextData: String) { trigger(project, featureId, event?.place, event?.isFromContextMenu ?: false, *additionalContextData) } @JvmStatic fun trigger(project: Project?, feature: String) { if (project == null) return val context = FUSUsageContext.create() FUSProjectUsageTrigger.getInstance(project).trigger(MavenActionsUsagesCollector::class.java, feature, context) } } }
15,322
https://github.com/umairakhtar/CareYou/blob/master/src/CompanyPayment.Designer.cs
Github Open Source
Open Source
MIT
null
CareYou
umairakhtar
C#
Code
2,716
13,609
namespace CareYou { partial class CompanyPayment { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.lblbamt = new System.Windows.Forms.Label(); this.lblsbox = new System.Windows.Forms.Label(); this.lblsamt = new System.Windows.Forms.Label(); this.lblsitem = new System.Windows.Forms.Label(); this.GvBillPayment = new System.Windows.Forms.DataGridView(); this.IDI = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Deletee = new System.Windows.Forms.DataGridViewLinkColumn(); this.billPaymentMstBindingSource = new System.Windows.Forms.BindingSource(this.components); this.stockDataSet = new CareYou.StockDataSet(); this.btnsearch = new System.Windows.Forms.Button(); this.drpcompanysearch = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.Gvpayment = new System.Windows.Forms.DataGridView(); this.IDD = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ScaleA = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ScaleB = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Price = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Scale = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Date = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Delete = new System.Windows.Forms.DataGridViewLinkColumn(); this.comPaymentMstBindingSource = new System.Windows.Forms.BindingSource(this.components); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtbillno = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.drpcompnay = new System.Windows.Forms.ComboBox(); this.caldate = new System.Windows.Forms.DateTimePicker(); this.label7 = new System.Windows.Forms.Label(); this.btnadddetail = new System.Windows.Forms.Button(); this.txtbillamt = new System.Windows.Forms.TextBox(); this.txtitems = new System.Windows.Forms.TextBox(); this.txtcarttons = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.txtamtpaidd = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.lblupadate = new System.Windows.Forms.Button(); this.lblpaidamt = new System.Windows.Forms.Label(); this.chkpaidedit = new System.Windows.Forms.CheckBox(); this.lblbillamt = new System.Windows.Forms.Label(); this.btndelete = new System.Windows.Forms.Button(); this.btnview = new System.Windows.Forms.Button(); this.txtbillview = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.drptype = new System.Windows.Forms.ComboBox(); this.label15 = new System.Windows.Forms.Label(); this.drpcomppayment = new System.Windows.Forms.ComboBox(); this.calpayamt = new System.Windows.Forms.DateTimePicker(); this.label6 = new System.Windows.Forms.Label(); this.btnddpayent = new System.Windows.Forms.Button(); this.txtamtpay = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.comPaymentMstTableAdapter = new CareYou.StockDataSetTableAdapters.ComPaymentMstTableAdapter(); this.billPaymentMstTableAdapter = new CareYou.StockDataSetTableAdapters.BillPaymentMstTableAdapter(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.GvBillPayment)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.billPaymentMstBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.stockDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Gvpayment)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comPaymentMstBindingSource)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.SuspendLayout(); // // groupBox2 // this.groupBox2.BackColor = System.Drawing.Color.CadetBlue; this.groupBox2.Controls.Add(this.lblbamt); this.groupBox2.Controls.Add(this.lblsbox); this.groupBox2.Controls.Add(this.lblsamt); this.groupBox2.Controls.Add(this.lblsitem); this.groupBox2.Controls.Add(this.GvBillPayment); this.groupBox2.Controls.Add(this.btnsearch); this.groupBox2.Controls.Add(this.drpcompanysearch); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.Gvpayment); this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F); this.groupBox2.Location = new System.Drawing.Point(317, 78); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(1026, 550); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; this.groupBox2.Text = "View Report"; // // lblbamt // this.lblbamt.AutoSize = true; this.lblbamt.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold); this.lblbamt.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.lblbamt.Location = new System.Drawing.Point(729, 521); this.lblbamt.Name = "lblbamt"; this.lblbamt.Size = new System.Drawing.Size(17, 18); this.lblbamt.TabIndex = 18; this.lblbamt.Text = "0"; // // lblsbox // this.lblsbox.AutoSize = true; this.lblsbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold); this.lblsbox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.lblsbox.Location = new System.Drawing.Point(212, 522); this.lblsbox.Name = "lblsbox"; this.lblsbox.Size = new System.Drawing.Size(17, 18); this.lblsbox.TabIndex = 8; this.lblsbox.Text = "0"; // // lblsamt // this.lblsamt.AutoSize = true; this.lblsamt.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold); this.lblsamt.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.lblsamt.Location = new System.Drawing.Point(328, 522); this.lblsamt.Name = "lblsamt"; this.lblsamt.Size = new System.Drawing.Size(17, 18); this.lblsamt.TabIndex = 17; this.lblsamt.Text = "0"; // // lblsitem // this.lblsitem.AutoSize = true; this.lblsitem.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold); this.lblsitem.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.lblsitem.Location = new System.Drawing.Point(265, 523); this.lblsitem.Name = "lblsitem"; this.lblsitem.Size = new System.Drawing.Size(17, 18); this.lblsitem.TabIndex = 16; this.lblsitem.Text = "0"; // // GvBillPayment // this.GvBillPayment.AutoGenerateColumns = false; this.GvBillPayment.BackgroundColor = System.Drawing.Color.CadetBlue; this.GvBillPayment.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.GvBillPayment.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.IDI, this.dataGridViewTextBoxColumn1, this.dataGridViewTextBoxColumn2, this.dataGridViewTextBoxColumn3, this.dataGridViewTextBoxColumn4, this.Deletee}); this.GvBillPayment.DataSource = this.billPaymentMstBindingSource; this.GvBillPayment.Location = new System.Drawing.Point(585, 55); this.GvBillPayment.Name = "GvBillPayment"; this.GvBillPayment.Size = new System.Drawing.Size(433, 463); this.GvBillPayment.TabIndex = 15; this.GvBillPayment.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.GvBillPayment_CellContentClick); // // IDI // this.IDI.DataPropertyName = "ID"; this.IDI.HeaderText = "ID"; this.IDI.Name = "IDI"; this.IDI.Visible = false; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.DataPropertyName = "CompanyName"; this.dataGridViewTextBoxColumn1.HeaderText = "COMPANY"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.DataPropertyName = "Amount"; this.dataGridViewTextBoxColumn2.HeaderText = "AMOUNT"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; this.dataGridViewTextBoxColumn2.Width = 70; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.DataPropertyName = "Type"; this.dataGridViewTextBoxColumn3.HeaderText = "TYPE"; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; this.dataGridViewTextBoxColumn3.Width = 60; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.DataPropertyName = "PaymentDate"; this.dataGridViewTextBoxColumn4.HeaderText = "DATE"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; this.dataGridViewTextBoxColumn4.Width = 110; // // Deletee // this.Deletee.HeaderText = "Delete"; this.Deletee.Name = "Deletee"; this.Deletee.Text = "Del"; this.Deletee.UseColumnTextForLinkValue = true; this.Deletee.Width = 50; // // billPaymentMstBindingSource // this.billPaymentMstBindingSource.DataMember = "BillPaymentMst"; this.billPaymentMstBindingSource.DataSource = this.stockDataSet; // // stockDataSet // this.stockDataSet.DataSetName = "StockDataSet"; this.stockDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // btnsearch // this.btnsearch.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.btnsearch.ForeColor = System.Drawing.Color.White; this.btnsearch.Location = new System.Drawing.Point(507, 19); this.btnsearch.Name = "btnsearch"; this.btnsearch.Size = new System.Drawing.Size(121, 33); this.btnsearch.TabIndex = 13; this.btnsearch.Text = "SEARCH"; this.btnsearch.UseVisualStyleBackColor = false; this.btnsearch.Click += new System.EventHandler(this.btnsearch_Click); // // drpcompanysearch // this.drpcompanysearch.BackColor = System.Drawing.Color.Honeydew; this.drpcompanysearch.DropDownWidth = 154; this.drpcompanysearch.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.drpcompanysearch.FormattingEnabled = true; this.drpcompanysearch.Location = new System.Drawing.Point(347, 23); this.drpcompanysearch.Name = "drpcompanysearch"; this.drpcompanysearch.Size = new System.Drawing.Size(154, 23); this.drpcompanysearch.TabIndex = 11; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label9.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label9.Location = new System.Drawing.Point(197, 25); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(144, 20); this.label9.TabIndex = 14; this.label9.Text = "Company Name :"; // // Gvpayment // this.Gvpayment.AutoGenerateColumns = false; this.Gvpayment.BackgroundColor = System.Drawing.Color.CadetBlue; this.Gvpayment.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.Gvpayment.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.IDD, this.ID, this.ScaleA, this.ScaleB, this.Price, this.Scale, this.Date, this.Delete}); this.Gvpayment.DataSource = this.comPaymentMstBindingSource; this.Gvpayment.Location = new System.Drawing.Point(6, 58); this.Gvpayment.Name = "Gvpayment"; this.Gvpayment.Size = new System.Drawing.Size(573, 461); this.Gvpayment.TabIndex = 14; this.Gvpayment.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.Gvpayment_CellContentClick); // // IDD // this.IDD.DataPropertyName = "ID"; this.IDD.HeaderText = "ID"; this.IDD.Name = "IDD"; this.IDD.ReadOnly = true; this.IDD.Visible = false; // // ID // this.ID.DataPropertyName = "BillNo"; this.ID.HeaderText = "BILLNO"; this.ID.Name = "ID"; this.ID.ReadOnly = true; this.ID.Width = 70; // // ScaleA // this.ScaleA.DataPropertyName = "Company"; this.ScaleA.HeaderText = "Company"; this.ScaleA.Name = "ScaleA"; this.ScaleA.ReadOnly = true; this.ScaleA.Width = 110; // // ScaleB // this.ScaleB.DataPropertyName = "Boxes"; this.ScaleB.HeaderText = "Boxes"; this.ScaleB.Name = "ScaleB"; this.ScaleB.ReadOnly = true; this.ScaleB.Width = 50; // // Price // this.Price.DataPropertyName = "Items"; this.Price.HeaderText = "Items"; this.Price.Name = "Price"; this.Price.ReadOnly = true; this.Price.Width = 60; // // Scale // this.Scale.DataPropertyName = "Amt"; this.Scale.HeaderText = "Bill Amt"; this.Scale.Name = "Scale"; this.Scale.ReadOnly = true; this.Scale.Width = 80; // // Date // this.Date.DataPropertyName = "Edate"; this.Date.HeaderText = "Date"; this.Date.Name = "Date"; this.Date.Width = 110; // // Delete // this.Delete.HeaderText = "Delete"; this.Delete.Name = "Delete"; this.Delete.Text = "Del"; this.Delete.UseColumnTextForLinkValue = true; this.Delete.Width = 50; // // comPaymentMstBindingSource // this.comPaymentMstBindingSource.DataMember = "ComPaymentMst"; this.comPaymentMstBindingSource.DataSource = this.stockDataSet; // // groupBox1 // this.groupBox1.BackColor = System.Drawing.Color.CadetBlue; this.groupBox1.Controls.Add(this.txtbillno); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.drpcompnay); this.groupBox1.Controls.Add(this.caldate); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.btnadddetail); this.groupBox1.Controls.Add(this.txtbillamt); this.groupBox1.Controls.Add(this.txtitems); this.groupBox1.Controls.Add(this.txtcarttons); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F); this.groupBox1.Location = new System.Drawing.Point(18, 124); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(282, 271); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Bill Entry"; // // txtbillno // this.txtbillno.BackColor = System.Drawing.Color.Honeydew; this.txtbillno.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtbillno.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtbillno.Location = new System.Drawing.Point(117, 58); this.txtbillno.MaxLength = 10; this.txtbillno.Name = "txtbillno"; this.txtbillno.Size = new System.Drawing.Size(88, 23); this.txtbillno.TabIndex = 2; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label8.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label8.Location = new System.Drawing.Point(44, 58); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(70, 20); this.label8.TabIndex = 12; this.label8.Text = "Bill No :"; // // drpcompnay // this.drpcompnay.BackColor = System.Drawing.Color.Honeydew; this.drpcompnay.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.drpcompnay.FormattingEnabled = true; this.drpcompnay.Location = new System.Drawing.Point(117, 26); this.drpcompnay.Name = "drpcompnay"; this.drpcompnay.Size = new System.Drawing.Size(154, 26); this.drpcompnay.TabIndex = 1; // // caldate // this.caldate.CalendarForeColor = System.Drawing.Color.Red; this.caldate.CalendarTitleForeColor = System.Drawing.SystemColors.HotTrack; this.caldate.Location = new System.Drawing.Point(113, 179); this.caldate.Name = "caldate"; this.caldate.Size = new System.Drawing.Size(154, 24); this.caldate.TabIndex = 8; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label7.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label7.Location = new System.Drawing.Point(51, 181); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(58, 20); this.label7.TabIndex = 9; this.label7.Text = "Date :"; // // btnadddetail // this.btnadddetail.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.btnadddetail.ForeColor = System.Drawing.Color.White; this.btnadddetail.Location = new System.Drawing.Point(113, 211); this.btnadddetail.Name = "btnadddetail"; this.btnadddetail.Size = new System.Drawing.Size(134, 40); this.btnadddetail.TabIndex = 9; this.btnadddetail.Text = "ADD DETAIL"; this.btnadddetail.UseVisualStyleBackColor = false; this.btnadddetail.Click += new System.EventHandler(this.btnadddetail_Click); // // txtbillamt // this.txtbillamt.BackColor = System.Drawing.Color.Honeydew; this.txtbillamt.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtbillamt.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtbillamt.Location = new System.Drawing.Point(117, 150); this.txtbillamt.MaxLength = 10; this.txtbillamt.Name = "txtbillamt"; this.txtbillamt.Size = new System.Drawing.Size(88, 23); this.txtbillamt.TabIndex = 5; this.txtbillamt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtbillamt_KeyPress); // // txtitems // this.txtitems.BackColor = System.Drawing.Color.Honeydew; this.txtitems.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtitems.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtitems.Location = new System.Drawing.Point(117, 119); this.txtitems.Name = "txtitems"; this.txtitems.Size = new System.Drawing.Size(88, 23); this.txtitems.TabIndex = 4; // // txtcarttons // this.txtcarttons.BackColor = System.Drawing.Color.Honeydew; this.txtcarttons.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtcarttons.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtcarttons.Location = new System.Drawing.Point(117, 88); this.txtcarttons.Name = "txtcarttons"; this.txtcarttons.Size = new System.Drawing.Size(88, 23); this.txtcarttons.TabIndex = 3; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label5.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label5.Location = new System.Drawing.Point(33, 150); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(80, 20); this.label5.TabIndex = 4; this.label5.Text = "Bill Amt :"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label4.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label4.Location = new System.Drawing.Point(21, 89); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(92, 20); this.label4.TabIndex = 3; this.label4.Text = "Cartoons :"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label3.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label3.Location = new System.Drawing.Point(49, 119); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 20); this.label3.TabIndex = 2; this.label3.Text = "Items :"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label2.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label2.Location = new System.Drawing.Point(16, 28); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(93, 20); this.label2.TabIndex = 1; this.label2.Text = "Company :"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Calibri", 26F, System.Drawing.FontStyle.Bold); this.label1.ForeColor = System.Drawing.Color.Maroon; this.label1.Location = new System.Drawing.Point(-2, 79); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(320, 42); this.label1.TabIndex = 3; this.label1.Text = "COMPANY PAYMENT"; // // groupBox3 // this.groupBox3.Controls.Add(this.groupBox4); this.groupBox3.Controls.Add(this.btndelete); this.groupBox3.Controls.Add(this.btnview); this.groupBox3.Controls.Add(this.txtbillview); this.groupBox3.Controls.Add(this.label11); this.groupBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F); this.groupBox3.Location = new System.Drawing.Point(946, 656); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(375, 206); this.groupBox3.TabIndex = 6; this.groupBox3.TabStop = false; this.groupBox3.Text = "Bill Payment"; // // groupBox4 // this.groupBox4.Controls.Add(this.txtamtpaidd); this.groupBox4.Controls.Add(this.label12); this.groupBox4.Controls.Add(this.lblupadate); this.groupBox4.Controls.Add(this.lblpaidamt); this.groupBox4.Controls.Add(this.chkpaidedit); this.groupBox4.Controls.Add(this.lblbillamt); this.groupBox4.Location = new System.Drawing.Point(33, 62); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(330, 86); this.groupBox4.TabIndex = 7; this.groupBox4.TabStop = false; this.groupBox4.Text = "-"; this.groupBox4.Visible = false; // // txtamtpaidd // this.txtamtpaidd.BackColor = System.Drawing.Color.Honeydew; this.txtamtpaidd.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtamtpaidd.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtamtpaidd.Location = new System.Drawing.Point(80, 55); this.txtamtpaidd.MaxLength = 10; this.txtamtpaidd.Name = "txtamtpaidd"; this.txtamtpaidd.Size = new System.Drawing.Size(75, 23); this.txtamtpaidd.TabIndex = 100; this.txtamtpaidd.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtamtpaidd_KeyPress); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(23, 58); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(48, 17); this.label12.TabIndex = 20; this.label12.Text = " Amt : "; // // lblupadate // this.lblupadate.Font = new System.Drawing.Font("Calibri", 10F); this.lblupadate.ForeColor = System.Drawing.Color.White; this.lblupadate.Location = new System.Drawing.Point(239, 52); this.lblupadate.Name = "lblupadate"; this.lblupadate.Size = new System.Drawing.Size(77, 26); this.lblupadate.TabIndex = 102; this.lblupadate.Text = "Update"; this.lblupadate.UseVisualStyleBackColor = false; // // lblpaidamt // this.lblpaidamt.AutoSize = true; this.lblpaidamt.Location = new System.Drawing.Point(167, 20); this.lblpaidamt.Name = "lblpaidamt"; this.lblpaidamt.Size = new System.Drawing.Size(54, 17); this.lblpaidamt.TabIndex = 4; this.lblpaidamt.Text = "label12"; // // chkpaidedit // this.chkpaidedit.AutoSize = true; this.chkpaidedit.Checked = true; this.chkpaidedit.CheckState = System.Windows.Forms.CheckState.Checked; this.chkpaidedit.Location = new System.Drawing.Point(181, 55); this.chkpaidedit.Name = "chkpaidedit"; this.chkpaidedit.Size = new System.Drawing.Size(55, 21); this.chkpaidedit.TabIndex = 101; this.chkpaidedit.Text = "Paid"; this.chkpaidedit.UseVisualStyleBackColor = true; // // lblbillamt // this.lblbillamt.AutoSize = true; this.lblbillamt.Location = new System.Drawing.Point(23, 19); this.lblbillamt.Name = "lblbillamt"; this.lblbillamt.Size = new System.Drawing.Size(54, 17); this.lblbillamt.TabIndex = 0; this.lblbillamt.Text = "label12"; // // btndelete // this.btndelete.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.btndelete.ForeColor = System.Drawing.Color.Yellow; this.btndelete.Location = new System.Drawing.Point(265, 20); this.btndelete.Name = "btndelete"; this.btndelete.Size = new System.Drawing.Size(88, 30); this.btndelete.TabIndex = 16; this.btndelete.Text = "DELETE"; this.btndelete.UseVisualStyleBackColor = false; this.btndelete.Click += new System.EventHandler(this.btndelete_Click); // // btnview // this.btnview.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.btnview.ForeColor = System.Drawing.Color.White; this.btnview.Location = new System.Drawing.Point(182, 20); this.btnview.Name = "btnview"; this.btnview.Size = new System.Drawing.Size(77, 30); this.btnview.TabIndex = 15; this.btnview.Text = "VIEW"; this.btnview.UseVisualStyleBackColor = false; this.btnview.Click += new System.EventHandler(this.btnview_Click); // // txtbillview // this.txtbillview.BackColor = System.Drawing.Color.Honeydew; this.txtbillview.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtbillview.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtbillview.Location = new System.Drawing.Point(87, 23); this.txtbillview.MaxLength = 10; this.txtbillview.Name = "txtbillview"; this.txtbillview.Size = new System.Drawing.Size(88, 23); this.txtbillview.TabIndex = 14; this.txtbillview.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtbillview_KeyDown); // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label11.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label11.Location = new System.Drawing.Point(15, 24); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(70, 20); this.label11.TabIndex = 0; this.label11.Tag = "16"; this.label11.Text = "Bill No :"; // // groupBox5 // this.groupBox5.Controls.Add(this.drptype); this.groupBox5.Controls.Add(this.label15); this.groupBox5.Controls.Add(this.drpcomppayment); this.groupBox5.Controls.Add(this.calpayamt); this.groupBox5.Controls.Add(this.label6); this.groupBox5.Controls.Add(this.btnddpayent); this.groupBox5.Controls.Add(this.txtamtpay); this.groupBox5.Controls.Add(this.label13); this.groupBox5.Controls.Add(this.label14); this.groupBox5.Font = new System.Drawing.Font("Calibri", 10F); this.groupBox5.Location = new System.Drawing.Point(15, 409); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(284, 219); this.groupBox5.TabIndex = 7; this.groupBox5.TabStop = false; this.groupBox5.Text = "Bill Payment"; // // drptype // this.drptype.BackColor = System.Drawing.Color.Honeydew; this.drptype.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.drptype.FormattingEnabled = true; this.drptype.Items.AddRange(new object[] { "SELECT", "CASH", "CHECK"}); this.drptype.Location = new System.Drawing.Point(116, 89); this.drptype.Name = "drptype"; this.drptype.Size = new System.Drawing.Size(89, 23); this.drptype.TabIndex = 13; // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label15.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label15.Location = new System.Drawing.Point(58, 88); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(57, 20); this.label15.TabIndex = 17; this.label15.Text = "Type :"; // // drpcomppayment // this.drpcomppayment.BackColor = System.Drawing.Color.Honeydew; this.drpcomppayment.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.drpcomppayment.FormattingEnabled = true; this.drpcomppayment.Location = new System.Drawing.Point(117, 23); this.drpcomppayment.Name = "drpcomppayment"; this.drpcomppayment.Size = new System.Drawing.Size(154, 23); this.drpcomppayment.TabIndex = 11; // // calpayamt // this.calpayamt.CalendarFont = new System.Drawing.Font("Microsoft Sans Serif", 11F); this.calpayamt.CalendarForeColor = System.Drawing.Color.Red; this.calpayamt.CalendarTitleForeColor = System.Drawing.SystemColors.HotTrack; this.calpayamt.Location = new System.Drawing.Point(117, 120); this.calpayamt.Name = "calpayamt"; this.calpayamt.Size = new System.Drawing.Size(154, 24); this.calpayamt.TabIndex = 14; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label6.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label6.Location = new System.Drawing.Point(53, 120); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(58, 20); this.label6.TabIndex = 16; this.label6.Text = "Date :"; // // btnddpayent // this.btnddpayent.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.btnddpayent.ForeColor = System.Drawing.Color.White; this.btnddpayent.Location = new System.Drawing.Point(117, 155); this.btnddpayent.Name = "btnddpayent"; this.btnddpayent.Size = new System.Drawing.Size(150, 40); this.btnddpayent.TabIndex = 15; this.btnddpayent.Text = "ADD PAYMENT"; this.btnddpayent.UseVisualStyleBackColor = false; this.btnddpayent.Click += new System.EventHandler(this.btnddpayent_Click); // // txtamtpay // this.txtamtpay.BackColor = System.Drawing.Color.Honeydew; this.txtamtpay.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold); this.txtamtpay.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.txtamtpay.Location = new System.Drawing.Point(117, 56); this.txtamtpay.MaxLength = 10; this.txtamtpay.Name = "txtamtpay"; this.txtamtpay.Size = new System.Drawing.Size(88, 23); this.txtamtpay.TabIndex = 12; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label13.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label13.Location = new System.Drawing.Point(37, 57); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(80, 20); this.label13.TabIndex = 12; this.label13.Text = "Bill Amt :"; // // label14 // this.label14.AutoSize = true; this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold); this.label14.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label14.Location = new System.Drawing.Point(24, 24); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(93, 20); this.label14.TabIndex = 10; this.label14.Text = "Company :"; // // comPaymentMstTableAdapter // this.comPaymentMstTableAdapter.ClearBeforeFill = true; // // billPaymentMstTableAdapter // this.billPaymentMstTableAdapter.ClearBeforeFill = true; // // CompanyPayment // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.CadetBlue; this.ClientSize = new System.Drawing.Size(1362, 741); this.Controls.Add(this.groupBox5); this.Controls.Add(this.groupBox3); this.Controls.Add(this.label1); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.Name = "CompanyPayment"; this.Text = "CompanyPayment"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.CompanyPayment_Load); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.GvBillPayment)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.billPaymentMstBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.stockDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Gvpayment)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comPaymentMstBindingSource)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.DataGridView Gvpayment; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.Label lblbamt; private System.Windows.Forms.Label lblsbox; private System.Windows.Forms.Label lblsamt; private System.Windows.Forms.Label lblsitem; private System.Windows.Forms.DataGridView GvBillPayment; private System.Windows.Forms.Button btnsearch; private System.Windows.Forms.ComboBox drpcompanysearch; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtbillno; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox drpcompnay; private System.Windows.Forms.DateTimePicker caldate; private System.Windows.Forms.Label label7; private System.Windows.Forms.Button btnadddetail; private System.Windows.Forms.TextBox txtbillamt; private System.Windows.Forms.TextBox txtitems; private System.Windows.Forms.TextBox txtcarttons; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.TextBox txtamtpaidd; private System.Windows.Forms.Label label12; private System.Windows.Forms.Button lblupadate; private System.Windows.Forms.Label lblpaidamt; private System.Windows.Forms.CheckBox chkpaidedit; private System.Windows.Forms.Label lblbillamt; private System.Windows.Forms.Button btndelete; private System.Windows.Forms.Button btnview; private System.Windows.Forms.TextBox txtbillview; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox drptype; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox drpcomppayment; private System.Windows.Forms.DateTimePicker calpayamt; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button btnddpayent; private System.Windows.Forms.TextBox txtamtpay; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private StockDataSet stockDataSet; private System.Windows.Forms.BindingSource comPaymentMstBindingSource; private StockDataSetTableAdapters.ComPaymentMstTableAdapter comPaymentMstTableAdapter; private System.Windows.Forms.BindingSource billPaymentMstBindingSource; private StockDataSetTableAdapters.BillPaymentMstTableAdapter billPaymentMstTableAdapter; private System.Windows.Forms.DataGridViewTextBoxColumn IDI; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewLinkColumn Deletee; private System.Windows.Forms.DataGridViewTextBoxColumn IDD; private System.Windows.Forms.DataGridViewTextBoxColumn ID; private System.Windows.Forms.DataGridViewTextBoxColumn ScaleA; private System.Windows.Forms.DataGridViewTextBoxColumn ScaleB; private System.Windows.Forms.DataGridViewTextBoxColumn Price; private new System.Windows.Forms.DataGridViewTextBoxColumn Scale; private System.Windows.Forms.DataGridViewTextBoxColumn Date; private System.Windows.Forms.DataGridViewLinkColumn Delete; } }
1,293
https://github.com/catberry/catberry-oauth2-client/blob/master/test/mocks/UHRMock.js
Github Open Source
Open Source
MIT
2,022
catberry-oauth2-client
catberry
JavaScript
Code
69
231
'use strict'; class UHRMock { constructor(locator) { const config = locator.resolve('config'); this._handler = config.handler; } get(url, options) { const parameters = Object.create(options); parameters.method = 'GET'; parameters.url = url; return this.request(parameters); } post(url, options) { const parameters = Object.create(options); parameters.method = 'POST'; parameters.url = url; return this.request(parameters); } request(parameters) { try { const result = this._handler(parameters); return Promise.resolve(result); } catch (e) { return Promise.reject(e); } } } module.exports = UHRMock;
47,095
https://github.com/DeirdreHegarty/Java_Fun/blob/master/NestedLoops/NestedWhileLoop.java
Github Open Source
Open Source
MIT
null
Java_Fun
DeirdreHegarty
Java
Code
35
103
public class NestedWhileLoop{ public static void main (String [] args){ int x = 0; int y = 1; while(y <= 5){ x = y; while(x > 0){ System.out.print("#"); x--; } y++; System.out.println(); } } }
48,720
https://github.com/skebix/algorithms/blob/master/merge_sort.py
Github Open Source
Open Source
MIT
null
algorithms
skebix
Python
Code
110
298
import random, time def merge_sort(a): """ Sort an array recursively by sorting its halves """ n = len(a) if n == 0 or n == 1: return a middle = n // 2 left = merge_sort(a[:middle]) right = merge_sort(a[middle:]) return merge(left, right) def merge(left, right): """ Merge two sorted arrays in a resulting array of size len(left) + len(right) """ result = [] while len(left) != 0 and len(right) != 0: if left[0] < right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if len(left) == 0: result += right else: result += left return result l = random.sample(range(1, 1000001), 100000) print(l) start_time = time.time() l = merge_sort(l) print("%s seconds" % (time.time() - start_time)) print(l)
32,696
https://github.com/zsiothsu/AVSI/blob/master/inc/flags.h
Github Open Source
Open Source
MIT
2,020
AVSI
zsiothsu
C
Code
29
117
/* * @Author: your name * @Date: 1970-01-01 08:00:00 * @LastEditTime: 2020-06-02 16:52:05 * @Description: file content */ #ifndef ___FLAGS_H___ #define ___FLAGS_H___ #include <gflags/gflags.h> #include <gflags/gflags_declare.h> DECLARE_bool(scope); DECLARE_bool(callStack); #endif
28,461
https://github.com/mayuryeole/test-site/blob/master/easypost-php-master/examples/addresses.php
Github Open Source
Open Source
MIT
2,018
test-site
mayuryeole
PHP
Code
281
1,153
<?php error_reporting(E_ALL); ini_set('display_errors', 1); require_once("../lib/easypost.php"); \EasyPost\EasyPost::setApiKey('aLmLoePe4FYBwC9WfoAmFg'); try { // create address $address_params = array("name" => "Sawyer Bateman", "street1" => "388 Townasend St", "street2" => "Apt 20", "city" => "San Francisco", "state" => "CA", "phone" => "3216549871", "zip" => "94107", "country" => "US"); $ae_address_params = array( "name" => "Ian Caron", "comapny" => "Move One", "street1" => "40th Floor,U-Bora Towers", "city" => "DUBAI", "phone" => "+9714 438 5300", "zip" => "00000", "country" => "AE" ); $nz_address_params = array( "name" => "Queen Elizabeth", "street1" => "50 Seddon Road", "street2" => "50 Seddon Road", "city" => "Hamilton", "zip" => "3204", "phone" => "3216549871", "country" => "NZ" ); // create and verify at the same time $verified_on_to = \EasyPost\Address::create_and_verify($address_params); $verified_on_from = \EasyPost\Address::create_and_verify($nz_address_params); $parcel_params = array("length" => 20.2, "width" => 10.9, "height" => 5, "predefined_package" => null, "weight" => 14.8 ); $parcel = \EasyPost\Parcel::create($parcel_params); // customs info form $customs_item_params = array( "description" => "Many, many EasyPost stickers.", "hs_tariff_number" => 123456, "origin_country" => "NZ", "quantity" => 1, "value" => 879.47, "weight" => 14 ); $customs_item = \EasyPost\CustomsItem::create($customs_item_params); $customs_info_params = array( "customs_certify" => true, "customs_signer" => "Borat Sagdiyev", "contents_type" => "gift", "contents_explanation" => "", // only necessary for contents_type=other "eel_pfc" => "NOEEI 30.37(a)", "non_delivery_option" => "abandon", "restriction_type" => "none", "restriction_comments" => "", "customs_items" => array($customs_item) ); $customs_info = \EasyPost\CustomsInfo::create($customs_info_params); $shipment_params = array("from_address" => $verified_on_from, "to_address" => $verified_on_to, "parcel" => $parcel, "customs_info" => $customs_info, "mode" => "test", "carrier_accounts" => ["ca_cf43b7f220764b6998b0e3843d13f0b7"] ); $shipment = \EasyPost\Shipment::create($shipment_params); $rate = \EasyPost\Rate::retrieve($shipment->lowest_rate()); $rateData = $shipment->lowest_rate(); echo "Lowest Rate"; echo '<pre>'; print_r($shipment->lowest_rate()); $shipment->buy(array('rate' => array('id' => $rateData->id))); echo "Rates"; echo '<pre>'; print_r($shipment->rates); } catch (Exception $e) { echo "Status: " . $e->getHttpStatus() . ":\n"; echo $e->getMessage(); if (!empty($e->param)) { echo "\nInvalid param: {$e->param}"; } exit(); }
26,269
https://github.com/arjanfrans/pokewhat/blob/master/src/engine/three-bmfont-text/index.js
Github Open Source
Open Source
MIT
2,021
pokewhat
arjanfrans
JavaScript
Code
363
996
import { BufferGeometry, Box3, BufferAttribute, Sphere } from 'three'; import * as createIndices from 'quad-indices'; import * as vertices from './lib/vertices' import * as utils from './lib/utils' import {createLayout} from "./lib/layout-bmfont-text"; export class TextGeometry extends BufferGeometry { constructor(opt) { super(); if (typeof opt === 'string') { opt = { text: opt } } // use these as default values for any subsequent // calls to update() this._opt = Object.assign({}, opt) // also do an initial setup... if (opt) this.update(opt) } update(opt) { if (typeof opt === 'string') { opt = { text: opt } } // use constructor defaults opt = Object.assign({}, this._opt, opt) if (!opt.font) { throw new TypeError('must specify a { font } in options') } this.layout = createLayout(opt) // get vec2 texcoords const flipY = opt.flipY !== false; // the desired BMFont data const font = opt.font; // determine texture size from font file const texWidth = font.common.scaleW; const texHeight = font.common.scaleH; // get visible glyphs const glyphs = this.layout.glyphs.filter(function (glyph) { const bitmap = glyph.data; return bitmap.width * bitmap.height > 0 }); // provide visible glyphs for convenience this.visibleGlyphs = glyphs // get common vertex data const positions = vertices.positions(glyphs); const uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY); const indices = createIndices([], { clockwise: true, type: 'uint16', count: glyphs.length }); // update vertex data this.setIndex(indices) this.addAttribute('position', new BufferAttribute(positions, 2)) this.addAttribute('uv', new BufferAttribute(uvs, 2)) // update multipage data if (!opt.multipage && 'page' in this.attributes) { // disable multipage rendering this.removeAttribute('page') } else if (opt.multipage) { // enable multipage rendering const pages = vertices.pages(glyphs); this.addAttribute('page', new BufferAttribute(pages, 1)) } } computeBoundingSphere() { if (this.boundingSphere === null) { this.boundingSphere = new Sphere() } const positions = this.attributes.position.array; const itemSize = this.attributes.position.itemSize; if (!positions || !itemSize || positions.length < 2) { this.boundingSphere.radius = 0 this.boundingSphere.center.set(0, 0, 0) return } utils.computeSphere(positions, this.boundingSphere) if (isNaN(this.boundingSphere.radius)) { console.error('BufferGeometry.computeBoundingSphere(): ' + 'Computed radius is NaN. The ' + '"position" attribute is likely to have NaN values.') } } computeBoundingBox() { if (this.boundingBox === null) { this.boundingBox = new Box3() } const bbox = this.boundingBox; const positions = this.attributes.position.array; const itemSize = this.attributes.position.itemSize; if (!positions || !itemSize || positions.length < 2) { bbox.makeEmpty() return } utils.computeBox(positions, bbox) } }
40,425
https://github.com/JLLeitschuh/myrrix-recommender/blob/master/web-common/src/net/myrrix/web/AllItemSimilarities.java
Github Open Source
Open Source
Apache-2.0
2,021
myrrix-recommender
JLLeitschuh
Java
Code
470
1,360
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.web; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Rescorer; import org.apache.mahout.common.LongPair; import net.myrrix.common.NotReadyException; import net.myrrix.common.parallel.Paralleler; import net.myrrix.common.parallel.Processor; import net.myrrix.online.RescorerProvider; import net.myrrix.online.ServerRecommender; /** * <p>A simple command-line program that will compute most similar items for all items. It does not start * an instance of the Serving Layer that responds to requests via HTTP. Instead it performs all computations * locally, in bulk. This may be useful to create a simple batch recommendation process when that is * all that's needed.</p> * * <p>Results are written to the file indicated by {@code --outFile}. The format mirrors that of the Computation * Layer. Each line begins with an item ID, followed by tab, followed "[item1:sim1,item2:sim2,...]"</p> * * <p>Example usage:</p> * * <p>{@code java -cp myrrix-serving-x.y.jar net.myrrix.web.AllItemSimilarities * --localInputDir=[work dir] --outFile=out.txt --howMany=[# similar items] * --rescorerProviderClass=[your class(es)]}</p> * * @author Sean Owen * @since 1.0 * @see AllRecommendations */ public final class AllItemSimilarities implements Callable<Object> { private final AllConfig config; public AllItemSimilarities(AllConfig config) { Preconditions.checkNotNull(config); this.config = config; } public static void main(String[] args) throws Exception { AllConfig config = AllConfig.build(args); if (config != null) { new AllItemSimilarities(config).call(); } } @Override public Object call() throws IOException, InterruptedException, NotReadyException, ExecutionException { final ServerRecommender recommender = new ServerRecommender(config.getLocalInputDir()); recommender.await(); final RescorerProvider rescorerProvider = config.getRescorerProvider(); final int howMany = config.getHowMany(); File outFile = config.getOutFile(); outFile.delete(); final Writer out = new OutputStreamWriter(new FileOutputStream(outFile), Charsets.UTF_8); Processor<Long> processor = new Processor<Long>() { @Override public void process(Long itemID, long count) throws ExecutionException { Rescorer<LongPair> rescorer = rescorerProvider == null ? null : rescorerProvider.getMostSimilarItemsRescorer(recommender); Iterable<RecommendedItem> similar; try { similar = recommender.mostSimilarItems(new long[]{itemID}, howMany, rescorer); } catch (TasteException te) { throw new ExecutionException(te); } String outLine = formatOutLine(itemID, similar); synchronized (out) { try { out.write(outLine); } catch (IOException e) { throw new ExecutionException(e); } } } }; Paralleler<Long> paralleler = new Paralleler<Long>(recommender.getAllItemIDs().iterator(), processor, "AllItemSimilarities"); if (config.isParallel()) { paralleler.runInParallel(); } else { paralleler.runInSerial(); } out.close(); return null; } static String formatOutLine(long id, Iterable<RecommendedItem> recs) { StringBuilder result = new StringBuilder(100); result.append(id); result.append("\t["); boolean first = true; for (RecommendedItem rec : recs) { if (first) { first = false; } else { result.append(','); } result.append(rec.getItemID()).append(':').append(rec.getValue()); } result.append("]\n"); return result.toString(); } }
5,743
https://github.com/herzcthu/Laravel-HS/blob/master/database/migrations/2015_09_24_000015_create_projects_participants_table.php
Github Open Source
Open Source
MIT
2,016
Laravel-HS
herzcthu
PHP
Code
83
402
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateProjectsParticipantsTable * * Generated by ViKon\DbExporter */ class CreateProjectsParticipantsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects_participants', function(Blueprint $table) { $table->increments('id') ->unsigned(); $table->integer('participant_id') ->unsigned(); $table->integer('project_id') ->unsigned(); $table->timestamps(); $table->index('participant_id', 'projects_participants_participant_id_foreign'); $table->index('project_id', 'projects_participants_project_id_foreign'); $table->foreign('project_id', 'projects_participants_project_id_foreign') ->references('id') ->on('projects'); $table->foreign('participant_id', 'projects_participants_participant_id_foreign') ->references('id') ->on('participants'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('projects_participants', function(Blueprint $table) { $table->dropForeign('projects_participants_project_id_foreign'); $table->dropForeign('projects_participants_participant_id_foreign'); }); Schema::dropIfExists('projects_participants'); } }
40,074
https://github.com/messa/bloom/blob/master/tests/test_main.py
Github Open Source
Open Source
MIT
2,021
bloom
messa
Python
Code
282
1,260
import gzip import lzma from pytest import fixture import zlib from bloom.main import construct_match_array, array_is_subset, construct_file_arrays, index_file, match_file, open_database def test_construct_match_array(): array = construct_match_array(16, ['hello', 'world'], sample_sizes=[4]) assert isinstance(array, bytes) assert array.hex() == '00002000600000000000000000001000' def test_array_is_subset(): assert array_is_subset(bytes.fromhex('00'), bytes.fromhex('00')) is True assert array_is_subset(bytes.fromhex('00'), bytes.fromhex('01')) is True assert array_is_subset(bytes.fromhex('01'), bytes.fromhex('00')) is False assert array_is_subset(bytes.fromhex('01'), bytes.fromhex('02')) is False assert array_is_subset(bytes.fromhex('01'), bytes.fromhex('03')) is True def test_construct_file_arrays_simple(temp_dir): p = temp_dir / 'one.txt' p.write_text('hello\nworld\n') with p.open(mode='rb') as f: array, = construct_file_arrays(f, array_bytesize=16, sample_sizes=[4]) assert isinstance(array, bytes) assert array.hex() == '00002000600000000000000000001000' def test_construct_file_arrays_gzip(temp_dir): p = temp_dir / 'one.txt.gz' with gzip.open(p, mode='wb') as f: f.write(b'hello\nworld\n') with p.open(mode='rb') as f: array, = construct_file_arrays(f, array_bytesize=16, sample_sizes=[4]) assert isinstance(array, bytes) assert array.hex() == '00002000600000000000000000001000' def test_construct_file_arrays_xz(temp_dir): p = temp_dir / 'one.txt.xz' with lzma.open(p, mode='wb') as f: f.write(b'hello\nworld\n') with p.open(mode='rb') as f: array, = construct_file_arrays(f, array_bytesize=16, sample_sizes=[4]) assert isinstance(array, bytes) assert array.hex() == '00002000600000000000000000001000' @fixture def db(temp_dir): return open_database(temp_dir / 'db') def test_index_files(temp_dir, db): p1 = temp_dir / 'one.txt' p1.write_bytes(b'Lorem ipsum dolor sit amet.\nThis is second line.\n') p2 = temp_dir / 'two.txt.gz' p2.write_bytes(gzip.compress(b'This is a compressed file.\n')) index_file(db, p1, array_bytesize=16) index_file(db, p2, array_bytesize=16) cur = db._connect().cursor() cur.execute('SELECT path, key, array FROM bloom_files_v3') row1, row2 = sorted(cur.fetchall()) assert row1[0] == str(p1) assert row1[1] == f"{p1.stat().st_size}:{p1.stat().st_mtime}:fnv1a_64:4,5,6" assert zlib.decompress(row1[2]).hex() == '97e126c173ff9373a75d1967f97219ec' assert row2[0] == str(p2) assert row2[1] == f"{p2.stat().st_size}:{p2.stat().st_mtime}:fnv1a_64:4,5,6" assert zlib.decompress(row2[2]).hex() == '12e3c6f14a0792e8836c194a4e8f00e0' def test_filter_files(temp_dir, db): p1 = temp_dir / 'one.txt' p1.write_bytes(b'Lorem ipsum dolor sit amet.\nThis is second line.\n') p2 = temp_dir / 'two.txt.gz' p2.write_bytes(gzip.compress(b'This is a compressed file.\n')) filter_files = lambda db, paths, q: [p for p in paths if match_file(db, q, p)] assert list(filter_files(db, [p1, p2], ['This'])) == [p1, p2] assert list(filter_files(db, [p1, p2], ['compressed'])) == [p2] assert list(filter_files(db, [p1, p2], ['nothing'])) == []
44,272
https://github.com/getclasslabs/user/blob/master/internal/domains/user.go
Github Open Source
Open Source
MIT
null
user
getclasslabs
Go
Code
81
297
package domains import ( "github.com/getclasslabs/user/internal/repository" ) const ( StudentRegister = 0 TeacherRegister = 1 ) type User struct { Domain FirstName string LastName string BirthDate string Gender int Register int Nickname string Twitter string Facebook string Instagram string Description string Telephone string Address string } func (u *User) Edit() error { uRepo := repository.NewUser() err := uRepo.Edit(u.Tracer, u.Email, u.Nickname, u.FirstName, u.LastName, u.BirthDate, u.Twitter, u.Facebook, u.Instagram, u.Description, u.Telephone, u.Address, u.Gender) if err != nil { u.Tracer.LogError(err) return err } return nil }
30,080
https://github.com/ManGysT/nmoneys/blob/master/src/NMoneys.Serialization.Tests/MonetaryQuantityTester.cs
Github Open Source
Open Source
BSD-3-Clause
2,022
nmoneys
ManGysT
C#
Code
452
2,330
using NMoneys.Extensions; using NMoneys.Serialization.Entity_Framework; using NUnit.Framework; using Testing.Commons; using Testing.Commons.NUnit.Constraints; namespace NMoneys.Serialization.Tests { [TestFixture] public class MonetaryQuantityTester { #region construction [Test] public void Ctor_InstanceWithMoneyValues() { MonetaryQuantity subject = new MonetaryQuantity(42.74m.Eur()); Assert.That(subject, Must.Have.Property<MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) & Must.Have.Property<MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode()))); } [Test] public void Factory_Null_Null() { Assert.That(MonetaryQuantity.From(default(Money?)), Is.Null); } [Test] public void Factory_NotNull_InstanceWithMoneyValues() { Money? notNull = 42.74m.Eur(); MonetaryQuantity quantity = MonetaryQuantity.From(notNull); Assert.That(quantity, Is.Not.Null); Assert.That(quantity, Must.Have.Property<MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) & Must.Have.Property<MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode()))); } [Test] public void Factory_NotNullable_InstanceWithMoneyValues() { Money notNullable = 42.74m.Eur(); MonetaryQuantity quantity = MonetaryQuantity.From(notNullable); Assert.That(quantity, Is.Not.Null); Assert.That(quantity, Must.Have.Property<MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) & Must.Have.Property<MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode()))); } #endregion #region conversion from Money? [Test] public void ExplicitConversion_Null_NullInstance() { MonetaryQuantity @explicit = (MonetaryQuantity) default(Money?); Assert.That(@explicit, Is.Null); } [Test] public void ExplicitConversion_NotNull_InstanceWithMoneyValues() { Money? notNull = 42.74m.Eur(); MonetaryQuantity quantity = (MonetaryQuantity)notNull; Assert.That(quantity, Is.Not.Null); Assert.That(quantity, Must.Have.Property<MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) & Must.Have.Property<MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode()))); } [Test] public void ExplicitConversion_NotNullable_InstanceWithMoneyValues() { Money notNullable = 42.74m.Eur(); MonetaryQuantity quantity = (MonetaryQuantity)notNullable; Assert.That(quantity, Is.Not.Null); Assert.That(quantity, Must.Have.Property<MonetaryQuantity>(q => q.Amount, Is.EqualTo(42.74m)) & Must.Have.Property<MonetaryQuantity>(q => q.Currency, Is.EqualTo(CurrencyIsoCode.EUR.AlphabeticCode()))); } #endregion #region conversion to Money? [Test] public void ToMoney_Null_Null() { MonetaryQuantity @null = null; Assert.That(MonetaryQuantity.ToMoney(@null), Is.Null); } [Test] public void ToMoney_NullAmount_Null() { MonetaryQuantity noAmount = new MonetaryQuantity(null, "XXX"); Assert.That(MonetaryQuantity.ToMoney(noAmount), Is.Null); } [Test] public void ToMoney_NullCurrency_MissingCurrency() { MonetaryQuantity noCurrency = new MonetaryQuantity(12, null); Money? money = MonetaryQuantity.ToMoney(noCurrency); Assert.That(money.HasValue, Is.True); Assert.That(money.Value.CurrencyCode, Is.EqualTo(CurrencyIsoCode.XXX)); } [Test] public void MoneyExplicitConversion_Null_Null() { MonetaryQuantity @null = null; Money? money = (Money?)@null; Assert.That(money, Is.Null); } [Test] public void MoneyExplicitConversion_NullAmount_Null() { MonetaryQuantity noAmount = new MonetaryQuantity(null, "XXX"); Money? money = (Money?) noAmount; Assert.That(money, Is.Null); } [Test] public void MoneyExplicitConversion_NullCurrency_MissingCurrency() { MonetaryQuantity noCurrency = new MonetaryQuantity(12, null); Money? money = (Money?) noCurrency; Assert.That(money.HasValue, Is.True); Assert.That(money.Value.CurrencyCode, Is.EqualTo(CurrencyIsoCode.XXX)); } #endregion [Test] public void Equality_SameCurrencyAndAmount_True() { MonetaryQuantity fiver = new MonetaryQuantity(5m.Gbp()), anotherFiver = (MonetaryQuantity)new Money(5, Currency.Gbp); Assert.That(fiver.Equals(fiver), Is.True); Assert.That(fiver.Equals(anotherFiver), Is.True); Assert.That(anotherFiver.Equals(fiver), Is.True); Assert.That(fiver == anotherFiver, Is.True); Assert.That(anotherFiver == fiver, Is.True); } [Test] public void Equality_DifferentAmountOrCurrency_False() { MonetaryQuantity fiver = new MonetaryQuantity(5m.Gbp()), tenner = (MonetaryQuantity)10m.Gbp(), hund = (MonetaryQuantity)100m.Dkk(); Assert.That(fiver.Equals(tenner), Is.False); Assert.That(tenner.Equals(fiver), Is.False); Assert.That(fiver == tenner, Is.False); Assert.That(tenner == fiver, Is.False); Assert.That(fiver.Equals(hund), Is.False); Assert.That(hund.Equals(fiver), Is.False); Assert.That(fiver == hund, Is.False); Assert.That(hund == fiver, Is.False); } [Test] public void Equality_DifferentTypes() { MonetaryQuantity fiver = new MonetaryQuantity(5m.Gbp()); Assert.That(fiver.Equals("gbp"), Is.False); Assert.That("GBP".Equals(fiver), Is.False); Assert.That(fiver.Equals(5m), Is.False); Assert.That(5m.Equals(fiver), Is.False); } [Test] public void Inequality_SameCurrencyAndAmount_False() { MonetaryQuantity fiver = new MonetaryQuantity(5m.Gbp()), anotherFiver = (MonetaryQuantity)new Money(5, Currency.Gbp); Assert.That(fiver != anotherFiver, Is.False); Assert.That(anotherFiver != fiver, Is.False); } [Test] public void Inequality_DifferentAmountOrCurrency_True() { MonetaryQuantity fiver = new MonetaryQuantity(5m.Gbp()), tenner = (MonetaryQuantity)10m.Gbp(), hund = (MonetaryQuantity)100m.Dkk(); Assert.That(fiver != tenner, Is.True); Assert.That(tenner != fiver, Is.True); Assert.That(fiver != hund, Is.True); Assert.That(hund != fiver, Is.True); } [Test] public void Equality_NoCurrencyAndMissingCurrent_Equals( [Values(null, "", " ", " ")]string missing) { MonetaryQuantity noCurrency = (MonetaryQuantity)12m.Xxx(), missingCurrency = new MonetaryQuantity(12m, missing); Assert.That(noCurrency, Is.EqualTo(missingCurrency)); } } }
38,036
https://github.com/cathode/gear/blob/master/Gear.Client/SceneGraph/VisibilityGroup.cs
Github Open Source
Open Source
MIT
2,015
gear
cathode
C#
Code
164
422
/****************************************************************************** * Gear: An open-world sandbox game for creative people. * * http://github.com/cathode/gear/ * * Copyright © 2009-2017 William 'cathode' Shelley. All Rights Reserved. * * This software is released under the terms and conditions of the MIT * * license. See the included LICENSE file for details. * *****************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Gear.Client.SceneGraph { /// <summary> /// Represents a visibility group, which allows control over whether nodes are shown or hidden. /// </summary> [Flags] public enum VisibilityGroup : ulong { None = 0x0000, G0 = 0x0001, G1 = 0x0002, G2 = 0x0004, G3 = 0x0008, G4 = 0x0010, G5 = 0x0020, G6 = 0x0040, G7 = 0x0080, G8 = 0x0100, G9 = 0x0200, G10 = 0x0400, G11 = 0x0800, G12 = 0x1000, G13 = 0x2000, G14 = 0x4000, G15 = 0x8000, /// <summary> /// Camera visibility group 0. /// </summary> Camera0 = 0x1000000000000000, Camera1 = 0x2000000000000000, Camera2 = 0x4000000000000000, Camera3 = 0x8000000000000000, All = 0xFFFFFFFFFFFFFFFF, } }
15,271
https://github.com/proudust/X4_ComplexCalculator/blob/master/X4_ComplexCalculator/DB/X4DB/Builder/ModuleBuilder.cs
Github Open Source
Open Source
Apache-2.0
2,022
X4_ComplexCalculator
proudust
C#
Code
203
943
using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Linq; using X4_ComplexCalculator.DB.X4DB.Entity; using X4_ComplexCalculator.DB.X4DB.Interfaces; using X4_ComplexCalculator.DB.X4DB.Manager; namespace X4_ComplexCalculator.DB.X4DB.Builder { /// <summary> /// <see cref="Module"/> クラスのインスタンスを作成するBuilderクラス /// </summary> class ModuleBuilder { #region メンバ /// <summary> /// モジュール種別一覧 /// </summary> private readonly IReadOnlyDictionary<string, IModuleType> _ModuleTypes; /// <summary> /// モジュール情報一覧 /// </summary> private readonly IReadOnlyDictionary<string, X4_DataExporterWPF.Entity.Module> _Modules; /// <summary> /// モジュールの製品情報一覧 /// </summary> private readonly ModuleProductManager _ModuleProductManager; /// <summary> /// モジュールの保管庫情報管理 /// </summary> private readonly ModuleStorageManager _StorageManager; /// <summary> /// ウェアの装備情報一覧 /// </summary> private WareEquipmentManager _WareEquipmentManager; #endregion /// <summary> /// コンストラクタ /// </summary> /// <param name="conn">DB接続情報</param> /// <param name="wareProductionManager">ウェア生産情報一覧</param> /// <param name="transportTypeManager">カーゴ種別一覧</param> public ModuleBuilder( IDbConnection conn, WareProductionManager wareProductionManager, TransportTypeManager transportTypeManager, WareEquipmentManager wareEquipmentManager ) { // モジュール種別一覧を作成 { const string sql = "SELECT ModuleTypeID, Name FROM ModuleType"; _ModuleTypes = conn.Query<ModuleType>(sql) .ToDictionary(x => x.ModuleTypeID, x => x as IModuleType); } // モジュール情報一覧を作成 _Modules = conn.Query<X4_DataExporterWPF.Entity.Module>("SELECT * FROM Module") .ToDictionary(x => x.ModuleID); _ModuleProductManager = new(conn, wareProductionManager); _StorageManager = new(conn, transportTypeManager); _WareEquipmentManager = wareEquipmentManager; } /// <summary> /// モジュール情報作成 /// </summary> /// <param name="ware">ベースとなるウェア情報</param> /// <returns>モジュール情報</returns> public IX4Module Builld(IWare ware) { if (!ware.Tags.Contains("module")) { throw new ArgumentException(); } var item = _Modules[ware.ID]; return new Module( ware, item.Macro, _ModuleTypes[item.ModuleTypeID], item.MaxWorkers, item.WorkersCapacity, item.NoBlueprint, _ModuleProductManager.Get(ware.ID), _StorageManager.Get(ware.ID), _WareEquipmentManager.Get(ware.ID).ToDictionary(x => x.ConnectionName) ); } } }
31,266
https://github.com/wollimchacha/chibi/blob/master/exp.py
Github Open Source
Open Source
MIT
2,019
chibi
wollimchacha
Python
Code
282
935
class Val(object): __slots__=['value'] def __init__(self, v = 0): self.value = v def __repr__(self): return f'Val({self.value})' def eval(self): return self.value v = Val(1) print(v) assert v.eval() == 1 class Add(object): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = a self.right = b def eval(self): return self.left.eval() + self.right.eval() e = Add(Val(1), Val(2)) print(e.eval()) assert e.eval() == 3 e = Add(Val(1), Add(Val(2), Val(3))) print(e.eval()) assert e.eval() == 6 class Mul(object): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = a self.right = b def eval(self): return self.left.eval() * self.right.eval() e = Mul(Val(1), Val(2)) print(e.eval()) assert e.eval() == 2 class Sub(object): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = a self.right = b def eval(self): return self.left.eval() - self.right.eval() e = Sub(Val(1), Val(2)) print(e.eval()) assert e.eval() == -1 class Div(object): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = a self.right = b def eval(self): return self.left.eval() / self.right.eval() e = Div(Val(7), Val(2)) print(e.eval()) assert e.eval() == 3.5 class Expr(object): pass class Val(Expr): __slots__=['value'] def __init__(self, v = 0): self.value = v def __repr__(self): return f'Val({self.value})' def eval(self): return self.value v = Val(1) print(v) assert v.eval() == 1 class Add(Expr): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = a self.right = b def eval(self): return self.left.eval() + self.right.eval() e = Add(Val(1),Val(2)) print(e.eval()) assert e.eval() == 3 assert isinstance(v, Expr) assert isinstance(v, Val) assert not isinstance(v, int) def toExpr(a): if not isinstance(a, Expr): a = Val(a) return a class Add(Expr): __slots__ = ['left', 'right'] def __init__(self, a, b): self.left = toExpr(a) self.right = toExpr(b) def eval(self): return self.left.eval() + self.right.eval() e = Add(1,Add(1, 2)) print(e.eval()) assert e.eval() == 4 def __repr__(self): classname = self.__name__ return f'{classname}({self.left},{self.right})' print() print()
47,175
https://github.com/microsoft/iclr2019-learning-to-represent-edits/blob/master/scripts/prof.sh
Github Open Source
Open Source
MIT
2,021
iclr2019-learning-to-represent-edits
microsoft
Shell
Code
47
281
#!/bin/bash work_dir=exp_runs/align_rep_repo_change512_graph_prof mkdir -p ${work_dir} CUDA_VISIBLE_DEVICES=2 python -u -m diff_representation.exp train \ --cuda \ --mode tree \ --prune_grammar \ --train_file=data/commit_files.from_repo.processed.070523.jsonl.dev \ --dev_file=data/commit_files.from_repo.processed.070523.jsonl.dev \ --vocab=data/vocab.repo.070523.freq10.bin \ --batch_size=32 \ --change_vector_size=512 \ --token_embed_size=64 \ --token_encoding_size=64 \ --action_embed_size=64 \ --field_embed_size=32 \ --decoder_hidden_size=256 \ --log_every 25 \ --num_data_load_worker 10 \ --work_dir=${work_dir} 2>${work_dir}/err.log
24,316
https://github.com/iisg/redo/blob/master/src/AdminPanel/src/common/validation/rules/constraints/no-configuration-constraint-backend-validator.ts
Github Open Source
Open Source
MIT
2,019
redo
iisg
TypeScript
Code
102
379
import {SingleValueConstraintValidator} from "./constraint-validator"; import {autoinject} from "aurelia-dependency-injection"; import {BackendValidation} from "../../backend-validation"; import {I18N} from "aurelia-i18n"; import {Metadata} from "../../../../resources-config/metadata/metadata"; import {Resource} from "../../../../resources/resource"; @autoinject export class NoConfigurationConstraintBackendValidator extends SingleValueConstraintValidator { constraintName: string; validatedConstraintName(): string { return this.constraintName || 'any'; } constructor(private backendValidation: BackendValidation, i18n: I18N) { super(i18n); } public forConstraint(constraintName: string): NoConfigurationConstraintBackendValidator { const instance = new NoConfigurationConstraintBackendValidator(this.backendValidation, this.i18n); instance.constraintName = constraintName; return instance; } protected shouldValidate(metadata: Metadata, resource: Resource): boolean { return !!metadata.constraints[this.constraintName]; } validate(value: string, metadata: Metadata, resource: Resource): Promise<boolean> { return this.backendValidation.validate(this.validatedConstraintName(), value, metadata, resource); } getErrorMessage(metadata: Metadata, resource: Resource): string { return this.i18n.tr(`metadata_constraints::${this.constraintName}_failed`, {metadata, resource}); } }
9,759
https://github.com/darrenw2112/eqMac/blob/master/native/app/Source/Audio/Volume/VolumeState.swift
Github Open Source
Open Source
Apache-2.0
2,020
eqMac
darrenw2112
Swift
Code
121
292
// // VolumeState.swift // eqMac // // Created by Roman Kisil on 29/06/2018. // Copyright © 2018 Roman Kisil. All rights reserved. // import Foundation import ReSwift import SwiftyUserDefaults struct VolumeState: State { var gain: Double = 0.5 var muted: Bool = false var balance: Double = 0 var transition: Bool = false } enum VolumeAction: Action { case setGain(Double, Bool) case setBalance(Double, Bool) case setMuted(Bool) } func VolumeStateReducer(action: Action, state: VolumeState?) -> VolumeState { var state = state ?? VolumeState() switch action as? VolumeAction { case .setGain(let gain, let transition)?: state.gain = gain state.transition = transition case .setBalance(let balance, let transition)?: state.balance = balance state.transition = transition case .setMuted(let muted)?: state.muted = muted case .none: break } return state }
40,098
https://github.com/Otarossoni/topicos1/blob/master/dev/app-intro2/src/pages/solicitante/SolicitanteCon.js
Github Open Source
Open Source
MIT
null
topicos1
Otarossoni
JavaScript
Code
333
1,238
import React, { useState, useEffect, useRef } from "react"; import { Toast } from "primereact/toast"; import { ConfirmDialog, confirmDialog } from "primereact/confirmdialog"; import SolicitanteList from "./SolicitanteList"; import SolicitanteForm from "./SolicitanteForm"; import SolicitanteSrv from "./SolicitanteSrv"; import "bootstrap/dist/css/bootstrap.min.css"; import "primereact/resources/themes/saga-blue/theme.css"; import "primereact/resources/primereact.min.css"; import "primeicons/primeicons.css"; function SolicitanteCon() { const [solicitantes, setSolicitantes] = useState([]); const initialState = { id: null, nome: "", email: "", senha: "" }; const [solicitante, setSolicitante] = useState(initialState); const [editando, setEditando] = useState(false); const toastRef = useRef(); useEffect(() => { onClickAtualizar(); // ao inicializar executa o método para atualizar }, []); const onClickAtualizar = () => { SolicitanteSrv.listar() .then((response) => { setSolicitantes(response.data); toastRef.current.show({ severity: "success", summary: "Solicitantes Atualizados!", life: 3000, }); }) .catch((e) => { toastRef.current.show({ severity: "error", summary: e.message, life: 3000, }); }); }; const inserir = () => { setSolicitante(initialState); setEditando(true); }; const salvar = () => { //inclusão if (solicitante._id == null) { SolicitanteSrv.incluir(solicitante) .then((response) => { setEditando(false); onClickAtualizar(); toastRef.current.show({ severity: "success", summary: "Salvou", life: 2000, }); }) .catch((e) => { toastRef.current.show({ severity: "error", summary: e.message, life: 4000, }); }); } else { // alteração SolicitanteSrv.alterar(solicitante) .then((response) => { setEditando(false); onClickAtualizar(); toastRef.current.show({ severity: "success", summary: "Salvou", life: 2000, }); }) .catch((e) => { toastRef.current.show({ severity: "error", summary: e.message, life: 4000, }); }); } }; const cancelar = () => { setEditando(false); }; const editar = (id) => { setSolicitante( solicitantes.filter((solicitante) => solicitante._id === id)[0] ); setEditando(true); }; const excluir = (_id) => { confirmDialog({ message: "Confirma a exclusão?", header: "Confirmação", icon: "pi pi-question", acceptLabel: "Sim", rejectLabel: "Não", acceptClassName: "p-button-danger", accept: () => excluirConfirm(_id), }); }; const excluirConfirm = (_id) => { SolicitanteSrv.excluir(_id) .then((response) => { onClickAtualizar(); toastRef.current.show({ severity: "success", summary: "Excluído", life: 2000, }); }) .catch((e) => { toastRef.current.show({ severity: "error", summary: e.message, life: 4000, }); }); }; if (!editando) { return ( <div> <ConfirmDialog /> <SolicitanteList solicitantes={solicitantes} onClickAtualizar={onClickAtualizar} inserir={inserir} editar={editar} excluir={excluir} /> <Toast ref={toastRef} /> </div> ); } else { return ( <div> <SolicitanteForm solicitante={solicitante} setSolicitante={setSolicitante} salvar={salvar} cancelar={cancelar} /> <Toast ref={toastRef} /> </div> ); } } export default SolicitanteCon;
24,645
https://github.com/RedHatGov/workshop-terminal/blob/master/hack/build.sh
Github Open Source
Open Source
Apache-2.0
2,021
workshop-terminal
RedHatGov
Shell
Code
265
830
#! /usr/bin/env bash # change these CONTAINER_IMAGE=workshop-terminal DOCKERFILE_DIR=terminal function print_usage() { echo "usage: $0 [-l (local|quay)] [-p QUAY_PROJECT] [-t CONTAINER_TAG] [-- BUILD_ARGS]" } # parse args while [ $# -gt 0 ]; do case "$1" in -l|--location=*) if [ "$1" = '-l' ]; then shift LOCATION="$1" else LOCATION=$(echo "$1" | cut -d= -f2-) fi ;; -p|--project=*) if [ "$1" = '-p' ]; then shift QUAY_PROJECT="$1" else QUAY_PROJECT=$(echo "$1" | cut -d= -f2-) fi ;; -t|--tag=*) if [ "$1" = '-t' ]; then shift CONTAINER_TAG="$1" else CONTAINER_TAG=$(echo "$1" | cut -d= -f2-) fi ;; --) shift break ;; *) print_usage >&2 exit 127 ;; esac shift done cd $(dirname $(realpath $0))/../$DOCKERFILE_DIR # some defaults if [ -f .quay_creds -a -z "$LOCATION" ]; then LOCATION=quay . .quay_creds elif [ -z "$LOCATION" ]; then LOCATION=local fi if [ -z "$QUAY_PROJECT" ]; then QUAY_PROJECT=redhatgov fi if [ -z "$CONTAINER_TAG" ]; then CONTAINER_TAG=latest fi # docker/podman problems if ! which docker &>/dev/null; then if which podman &>/dev/null; then function docker() { podman "${@}" ; } else echo "No docker|podman installed :(" >&2 exit 1 fi fi # build case $LOCATION in local) docker build "${@}" -t quay.io/$QUAY_PROJECT/$CONTAINER_IMAGE:$CONTAINER_TAG . ;; quay) # designed to be used by travis-ci, where the docker_* variables are defined if [ -z "$DOCKER_PASSWORD" -o -z "$DOCKER_USERNAME" ]; then echo "Requires DOCKER_USERNAME and DOCKER_PASSWORD variables to be exported." >&2 exit 1 fi echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin quay.io || exit 2 docker build "${@}" -t quay.io/$QUAY_PROJECT/$CONTAINER_IMAGE:$CONTAINER_TAG . || exit 3 docker push quay.io/$QUAY_PROJECT/$CONTAINER_IMAGE:$CONTAINER_TAG || exit 4 ;; *) print_usage >&2 exit 127 ;; esac
1,471
https://github.com/kgullikson88/GSSP_Analyzer/blob/master/gsspy/fitting.py
Github Open Source
Open Source
MIT
null
GSSP_Analyzer
kgullikson88
Python
Code
1,579
6,419
from __future__ import print_function, division, absolute_import import numpy as np import matplotlib.pyplot as plt import os import sys import subprocess from astropy.io import fits from astropy import time import DataStructures from ._utils import combine_orders, read_grid_points, ensure_dir from .analyzer import GSSP_Analyzer import logging import glob home = os.environ['HOME'] GSSP_EXE = '{}/Applications/GSSP/GSSP_single/GSSP_single'.format(home) GSSP_ABUNDANCE_TABLES = '{}/Applications/GSSPAbundance_Tables/'.format(home) GSSP_MODELS = '/media/ExtraSpace/GSSP_Libraries/LLmodels/' class GSSP_Fitter(object): teff_minstep = 100 logg_minstep = 0.1 feh_minstep = 0.1 vsini_minstep = 10 vmicro_minstep = 0.1 def __init__(self, filename, gssp_exe=None, abund_tab=None, models_dir=None): """ A python wrapper to the GSSP code (must already be installed) Parameters: =========== filename: string The filename of the (flattened) fits spectrum to fit. gssp_exe: string (optional) The full path to the gssp executable file abund_tab: string (optional) The full path to the directory containing GSSP abundance tables. models_dir: string: The full path to the directory containing GSSP atmosphere models. Methods: ========== fit: Fit the parameters """ if gssp_exe is None: gssp_exe = GSSP_EXE if abund_tab is None: abund_tab = GSSP_ABUNDANCE_TABLES if models_dir is None: models_dir = GSSP_MODELS # Read in the file and combine the orders orders = self._read_fits_file(filename) combined = combine_orders(orders) #TODO: Cross-correlate the data to get it close. GSSP might have trouble with huge RVs... # Get the object name/date header = fits.getheader(filename) star = header['OBJECT'] date = header['DATE-OBS'] try: jd = time.Time(date, format='isot', scale='utc').jd except TypeError: jd = time.Time('{}T{}'.format(date, header['UT']), format='isot', scale='utc').jd # Save the data to an ascii file output_basename = '{}-{}'.format(star.replace(' ', ''), jd) np.savetxt('data_sets/{}.txt'.format(output_basename), np.transpose((combined.x, combined.y)), fmt='%.10f') # Save some instance variables self.data = combined self.jd = jd self.starname = star self.output_basename = output_basename self.gssp_exe = os.path.abspath(gssp_exe) self.abundance_table = abund_tab self.model_dir = models_dir self.gssp_gridpoints = read_grid_points(models_dir) def _run_gssp(self, teff_lims=(7000, 30000), teff_step=1000, logg_lims=(3.0, 4.5), logg_step=0.5, feh_lims=(-0.5, 0.5), feh_step=0.5, vsini_lims=(50, 350), vsini_step=50, vmicro_lims=(1, 5), vmicro_step=1, R=80000, ncores=1): """ Coarsely fit the parameters Teff, log(g), and [Fe/H]. """ # First, make sure the inputs are reasonable. teff_step = max(teff_step, self.teff_minstep) logg_step = max(logg_step, self.logg_minstep) feh_step = max(feh_step, self.feh_minstep) vsini_step = max(vsini_step, self.vsini_minstep) vmicro_step = max(vmicro_step, self.vmicro_minstep) teff_lims = (min(teff_lims), max(teff_lims)) logg_lims = (min(logg_lims), max(logg_lims)) feh_lims = (min(feh_lims), max(feh_lims)) vsini_lims = (min(vsini_lims), max(vsini_lims)) vmicro_lims = (min(vmicro_lims), max(vmicro_lims)) teff_lims, logg_lims, feh_lims = self._check_grid_limits(teff_lims, logg_lims, feh_lims) # Make the input file for GSSP inp_file=self._make_input_file(teff_lims=teff_lims, teff_step=teff_step, logg_lims=logg_lims, logg_step=logg_step, feh_lims=feh_lims, feh_step=feh_step, vsini_lims=vsini_lims, vsini_step=vsini_step, vmicro_lims=vmicro_lims, vmicro_step=vmicro_step, resolution=R) # Run GSSP subprocess.check_call(['mpirun', '-n', '{}'.format(ncores), '{}'.format(self.gssp_exe), '{}'.format(inp_file)]) # Move the output directory to a new name that won't be overridden output_dir = '{}_output'.format(self.output_basename) ensure_dir(output_dir) for f in glob.glob('output_files/*'): subprocess.check_call(['mv', f, '{}/'.format(output_dir)]) return def fit(self, teff_lims=(7000, 30000), teff_step=1000, logg_lims=(3.0, 4.5), logg_step=0.5, feh_lims=(-0.5, 0.5), feh_step=0.5, vsini_lims=(50, 350), vsini_step=50, vmicro_lims=(1, 5), vmicro_step=1, R=80000, ncores=1, refine=True): """ Fit the stellar parameters with GSSP Parameters: ============= par_lims: iterable with (at least) two objects The limits on the given parameter. 'par' can be one of: 1. teff: The effective temperature 2. logg: The surface gravity 3. feh: The metallicity [Fe/H] 4. vsini: The rotational velocity 5. vmicro: The microturbulent velocity The default values are a very large, very course grid. Consider refining based on spectral type first! par_step: float The initial step size to take in the given parameter. 'par' can be from the same list as above. R: float The spectrograph resolving power (lambda/delta-lambda) ncores: integer, default=1 The number of cores to use in the GSSP run. refine: boolean Should we run GSSP again with a smaller grid after the initial fit? If yes, the best answers will probably be better. Returns: ========= A pd.Series object with the best parameters """ # Run GSSP self._run_gssp(teff_lims=teff_lims, teff_step=teff_step, logg_lims=logg_lims, logg_step=logg_step, feh_lims=feh_lims, feh_step=feh_step, vsini_lims=vsini_lims, vsini_step=vsini_step, vmicro_lims=vmicro_lims, vmicro_step=vmicro_step, R=R, ncores=ncores) # Look at the output and save the figures output_dir = '{}_output'.format(self.output_basename) best_pars, figs = GSSP_Analyzer(output_dir).estimate_best_parameters() for par in figs.keys(): fig = figs[par] fig.savefig(os.path.join(output_dir, '{}_course.pdf'.format(par))) plt.close('all') if not refine: return best_pars # If we get here, we should restrict the grid near the # best solution and fit again teff_lims = self._get_refined_limits(lower=best_pars['1sig_CI_lower_Teff'], upper=best_pars['1sig_CI_upper_Teff'], values=self.gssp_gridpoints.teff) logg_lims = self._get_refined_limits(lower=best_pars['1sig_CI_lower_logg'], upper=best_pars['1sig_CI_upper_logg'], values=self.gssp_gridpoints.logg) feh_lims = self._get_refined_limits(lower=best_pars['1sig_CI_lower_feh'], upper=best_pars['1sig_CI_upper_feh'], values=self.gssp_gridpoints.feh) vsini_lower = best_pars.best_vsini*(1-1.5) + 1.5*best_pars['1sig_CI_lower_vsini'] vsini_upper = best_pars.best_vsini*(1-1.5) + 1.5*best_pars['1sig_CI_upper_vsini'] vsini_lims = (max(10, vsini_lower), min(400, vsini_upper)) vsini_step = max(self.vsini_minstep, (vsini_lims[1] - vsini_lims[0])/10) vmicro_lims = (best_pars.micro_turb, best_pars.micro_turb) # Rename the files in the output directory so they don't get overwritten file_list = ['CCF.dat', 'Chi2_table.dat', 'Observed_spectrum.dat', 'Synthetic_best_fit.rgs'] ensure_dir(os.path.join(output_dir, 'course_output', '')) for f in file_list: original_fname = os.path.join(output_dir, f) new_fname = os.path.join(output_dir, 'course_output', f) subprocess.check_call(['mv', original_fname, new_fname]) # Run GSSP on the refined grid self._run_gssp(teff_lims=teff_lims, teff_step=self.teff_minstep, logg_lims=logg_lims, logg_step=self.logg_minstep, feh_lims=feh_lims, feh_step=self.feh_minstep, vsini_lims=vsini_lims, vsini_step=round(vsini_step), vmicro_lims=vmicro_lims, vmicro_step=vmicro_step, R=R, ncores=ncores) best_pars, figs = GSSP_Analyzer(output_dir).estimate_best_parameters() for par in figs.keys(): fig = figs[par] fig.savefig(os.path.join(output_dir, '{}_fine.pdf'.format(par))) fig.close() return best_pars def _check_grid_limits_old(self, teff_lims, logg_lims, feh_lims): df = self.gssp_gridpoints[['teff', 'logg', 'feh']].drop_duplicates() # First, check if the limits are do-able lower = df.loc[(df.teff <= teff_lims[0]) & (df.logg <= logg_lims[0]) & (df.feh <= feh_lims[0])] upper = df.loc[(df.teff >= teff_lims[1]) & (df.logg >= logg_lims[1]) & (df.feh >= feh_lims[1])] if len(upper) >= 1 and len(lower) >= 1: return teff_lims, logg_lims, feh_lims # If we get here, there is a problem... # Check temperature first: if not (len(df.loc[df.teff <= teff_lims[0]]) >= 1 and len(df.loc[df.teff >= teff_lims[1]]) >= 1): # Temperature grid is no good. low_teff, high_teff = df.teff.min(), df.teff.max() print('The temperature grid is not available in the model library!') print('You wanted temperatures from {} - {}'.format(*teff_lims)) print('The model grid extends from {} - {}'.format(low_teff, high_teff)) new_teff_lims = (max(low_teff, teff_lims[0]), min(high_teff, teff_lims[1])) print('Resetting temperature limits to {} - {}'.format(*new_teff_lims)) return self._check_grid_limits(new_teff_lims, logg_lims, feh_lims) # Check log(g) next: teff_df = df.loc[(df.teff >= teff_lims[0]) & (df.teff <= teff_lims[1])] if not (len(teff_df.loc[df.logg <= logg_lims[0]]) >= 1 and len(teff_df.loc[df.logg >= logg_lims[1]]) >= 1): # Temperature grid is no good. low_logg, high_logg = df.logg.min(), df.logg.max() print('The log(g) grid is not available in the model library!') print('You wanted log(g) from {} - {}'.format(*logg_lims)) print('The model grid extends from {} - {}'.format(low_logg, high_logg)) new_logg_lims = (max(low_logg, logg_lims[0]), min(high_logg, logg_lims[1])) print('Resetting log(g) limits to {} - {}'.format(*new_logg_lims)) return self._check_grid_limits(teff_lims, new_logg_lims, feh_lims) # Finally, check [Fe/H]: subset_df = df.loc[(df.teff >= teff_lims[0]) & (df.teff <= teff_lims[1]) * (df.logg >= logg_lims[0]) & (df.logg <= logg_lims[1])] if not (len(subset_df.loc[df.feh <= feh_lims[0]]) >= 1 and len(subset_df.loc[df.feh >= feh_lims[1]]) >= 1): # Temperature grid is no good. low_feh, high_feh = df.feh.min(), df.feh.max() print('The [Fe/H] grid is not available in the model library!') print('You wanted [Fe/H] from {} - {}'.format(*feh_lims)) print('The model grid extends from {} - {}'.format(low_feh, high_feh)) new_feh_lims = (max(low_feh, feh_lims[0]), min(high_feh, feh_lims[1])) print('Resetting [Fe/H] limits to {} - {}'.format(*new_feh_lims)) return self._check_grid_limits(teff_lims, logg_lims, new_feh_lims) # We should never get here raise ValueError('Something weird happened while checking limits!') def _check_grid_limits(self, teff_lims, logg_lims, feh_lims): df = self.gssp_gridpoints[['teff', 'logg', 'feh']].drop_duplicates() # First, check if the limits are do-able as is lower = df.loc[(df.teff == teff_lims[0]) & (df.feh == feh_lims[0])] upper = df.loc[(df.teff == teff_lims[1]) & (df.feh == feh_lims[1])] if (lower.logg.min() <= logg_lims[0] and lower.logg.max() >= logg_lims[1] and upper.logg.min() <= logg_lims[0] and upper.logg.max() >= logg_lims[1]): return teff_lims, logg_lims, feh_lims # If we get here, there is a problem... # Check temperature first: low_teff, high_teff = df.teff.min(), df.teff.max() if low_teff > teff_lims[0] or high_teff < teff_lims[1]: print('The temperature grid is not available in the model library!') print('You wanted temperatures from {} - {}'.format(*teff_lims)) print('The model grid extends from {} - {}'.format(low_teff, high_teff)) new_teff_lims = (max(low_teff, teff_lims[0]), min(high_teff, teff_lims[1])) print('Resetting temperature limits to {} - {}'.format(*new_teff_lims)) return self._check_grid_limits(new_teff_lims, logg_lims, feh_lims) # Check [Fe/H] next subset_df = df.loc[(df.teff >= teff_lims[0]) & (df.teff <= teff_lims[1])] low_feh, high_feh = subset_df.feh.min(), subset_df.feh.max() if low_feh > feh_lims[0] or high_feh < feh_lims[1]: print('The [Fe/H] grid is not available in the model library!') print('You wanted [Fe/H] from {} - {}'.format(*feh_lims)) print('The model grid extends from {} - {}'.format(low_feh, high_feh)) new_feh_lims = (max(low_feh, feh_lims[0]), min(high_feh, feh_lims[1])) print('Resetting [Fe/H] limits to {} - {}'.format(*new_feh_lims)) return self._check_grid_limits(teff_lims, logg_lims, new_feh_lims) # Finally, check log(g) subset_df = subset_df.loc[(subset_df.feh >= feh_lims[0]) & (subset_df.feh <= feh_lims[1])] low_logg, high_logg = subset_df.logg.min(), subset_df.logg.max() if low_logg > logg_lims[0] or high_logg < logg_lims[1]: print('The log(g) grid is not available in the model library!') print('You wanted log(g) from {} - {}'.format(*logg_lims)) print('The model grid extends from {} - {}'.format(low_logg, high_logg)) new_logg_lims = (max(low_logg, logg_lims[0]), min(high_logg, logg_lims[1])) print('Resetting log(g) limits to {} - {}'.format(*new_logg_lims)) return self._check_grid_limits(teff_lims, new_logg_lims, feh_lims) # We should never get here raise ValueError('Something weird happened while checking limits!') def _get_refined_limits(self, lower, upper, values): """ Get the items in the 'values' array that are just less than lower and just more than upper. """ unique_values = sorted(np.unique(values)) l_idx = np.searchsorted(unique_values, lower, side='left') r_idx = np.searchsorted(unique_values, upper, side='right') if l_idx > 0: l_idx -= 1 if r_idx < len(unique_values) - 1: r_idx += 1 return unique_values[l_idx], unique_values[r_idx] def _read_fits_file(self, fname): orders = [] hdulist = fits.open(fname) for i, hdu in enumerate(hdulist[1:]): xypt = DataStructures.xypoint(x=hdu.data['wavelength'], y=hdu.data['flux'], cont=hdu.data['continuum'], err=hdu.data['error']) xypt.x *= 10 #Convert from nanometers to angstrom orders.append(xypt) return orders def _make_input_file(self, teff_lims, teff_step, logg_lims, logg_step, feh_lims, feh_step, vsini_lims, vsini_step, vmicro_lims, vmicro_step, resolution): """ Make the input file for the given star """ output_string = '{:.1f} {:.0f} {:.1f}\n'.format(teff_lims[0], teff_step, teff_lims[-1]) output_string += '{:.1f} {:.1f} {:.1f}\n'.format(logg_lims[0], logg_step, logg_lims[1]) output_string += '{:.1f} {:.1f} {:.1f}\n'.format(vmicro_lims[0], vmicro_step, vmicro_lims[1]) output_string += '{:.1f} {:.1f} {:.1f}\n'.format(vsini_lims[0], vsini_step, vsini_lims[1]) output_string += "skip 0.03 0.02 0.07 !dilution factor\n" output_string += 'skip {:.1f} {:.1f} {:.1f}\n'.format(feh_lims[0], feh_step, feh_lims[1]) output_string += 'He 0.04 0.005 0.06 ! Individual abundance\n' output_string += '0.0 {:.0f}\n'.format(resolution) output_string += '{}\n{}\n'.format(self.abundance_table, self.model_dir) output_string += '2 1 !atmosphere model vmicro and mass\n' output_string += 'ST ! model atmosphere chemical composition flag\n' dx = self.data.x[1] - self.data.x[0] output_string += '1 {:.5f} fit\n'.format(dx) output_string += 'data_sets/{}.txt\n'.format(self.output_basename) output_string += '0.5 0.99 0.0 adjust ! RV determination stuff\n' xmin, xmax = self.data.x[0]-1, self.data.x[-1]+1 output_string += '{:.1f} {:.1f}\n'.format(xmin, xmax) outfilename = '{}.inp'.format(self.output_basename) with open(outfilename, 'w') as outfile: outfile.write(output_string) return outfilename
3,226
https://github.com/SnoBoarder/CS651-Websites/blob/master/Lecture10/bugui/scripts/controllers/basicCtrl.js
Github Open Source
Open Source
Apache-2.0
2,016
CS651-Websites
SnoBoarder
JavaScript
Code
1,477
4,152
'use strict'; var app = angular.module('app'); // basic controller: show basic grid functionality app.controller('basicCtrl', function appCtrl($scope, $compile, dataSvc) { // data context $scope.ctx = { flex: null, flexInline: null, itemCount: 500, data: dataSvc.getData(500), filter: '', groupBy: '', pageSize: 0, dataMaps: true, formatting: true, alwaysEdit: false, countries: dataSvc.getCountries(), products: dataSvc.getProducts(), colors: dataSvc.getColors(), culture: 'en' }; // update data when 'itemCount' changes $scope.$watch('ctx.itemCount', function () { $scope.ctx.data = dataSvc.getData($scope.ctx.itemCount * 1); $scope.ctx.groupBy = ''; }); // update page size $scope.$watch('ctx.pageSize', function () { var flex = $scope.ctx.flex; if (flex && $scope.ctx.pageSize != null) { var cv = flex.collectionView; cv.pageSize = $scope.ctx.pageSize; } }); // update groups when 'groupBy' changes $scope.$watch('ctx.groupBy', function () { if ($scope.ctx.flex) { // get the collection view, start update var cv = $scope.ctx.flex.collectionView; cv.beginUpdate(); // clear existing groups cv.groupDescriptions.clear(); // add new groups var groupNames = $scope.ctx.groupBy.split('/'), groupDesc; for (var i = 0; i < groupNames.length; i++) { var propName = groupNames[i].toLowerCase(); if (propName == 'amount') { // group amounts in ranges // (could use the mapping function to group countries into continents, // names into initials, etc) groupDesc = new wijmo.collections.PropertyGroupDescription(propName, function (item, prop) { var value = item[prop]; if (value > 1000) return 'Large Amounts'; if (value > 100) return 'Medium Amounts'; if (value > 0) return 'Small Amounts'; return 'Negative'; }); cv.groupDescriptions.push(groupDesc); } else if (propName) { // group other properties by their specific values groupDesc = new wijmo.collections.PropertyGroupDescription(propName); cv.groupDescriptions.push(groupDesc); } } // done updating cv.endUpdate(); } }); // ICollectionView filter function function filterFunction(item) { var f = $scope.ctx.filter; if (f && item) { // split string into terms to enable multi-field searches such as 'us gadget red' var terms = f.toUpperCase().split(' '); // look for any term in any string field for (var i = 0; i < terms.length; i++) { var termFound = false; for (var key in item) { var value = item[key]; if (angular.isString(value) && value.toUpperCase().indexOf(terms[i]) > -1) { termFound = true; break; } } // fail if any of the terms is not found if (!termFound) { return false; } } } // include item in view return true; } // apply filter (applied on a 500 ms timeOut) var toFilter; $scope.$watch('ctx.filter', function () { if (toFilter) { clearTimeout(toFilter); } toFilter = setTimeout(function () { toFilter = null; if ($scope.ctx.flex) { var cv = $scope.ctx.flex.collectionView; if (cv) { if (cv.filter != filterFunction) { cv.filter = filterFunction; } else { cv.refresh(); } $scope.$apply('ctx.flex.collectionView'); } } }, 500); }); // connect to flex when it becomes available to update data maps and formatting // Don't remove this watcher or DataMaps won't work in Templates sample $scope.$watch('ctx.flex', function () { var flex = $scope.ctx.flex; if (flex) { updateDataMaps(); updateFormatting(); } }); // update data maps, formatting, paging now and when the itemsSource changes $scope.itemsSourceChangedHandler = function (sender, args) { var flex = $scope.ctx.flex; updateDataMaps(); updateFormatting(); if (flex.collectionView && $scope.ctx.pageSize != null) { flex.collectionView.pageSize = $scope.ctx.pageSize; } }; // notify AngularJS of selection changes, keep control in edit mode $scope.selectionChangedHandler = function () { var flex = $scope.ctx.flex; // notify AngularJS of selection changes $scope.current = flex.collectionView ? flex.collectionView.currentItem : null; if (!$scope.$$phase) { $scope.$apply('current'); $scope.$apply('ctx.flex.selection'); } // keep the control in edit mode if ($scope.ctx.alwaysEdit == true && flex.containsFocus()) { setTimeout(function () { flex.startEditing(false); }, 50); } }; // when the culture changes, load the new culture, apply, and invalidate $scope.$watch('ctx.culture', function () { $.ajax({ url: 'scripts/vendor/wijmo.culture.' + $scope.ctx.culture + '.js', dataType: 'script', success: function (data) { eval(data); // apply new culture invalidateAll(); // invalidate all controls to show new culture }, }); }); // invalidate all Wijmo controls // using a separate function to handle strange IE9 scope issues function invalidateAll() { wijmo.Control.invalidateAll(); } // update data maps $scope.$watch('ctx.dataMaps', function () { updateDataMaps(); }); // update column formatting $scope.$watch('ctx.formatting', function () { updateFormatting(); }); // apply/remove data maps function updateDataMaps() { var flex = $scope.ctx.flex; if (flex) { var colCountry = flex.columns.getColumn('countryId'); var colProduct = flex.columns.getColumn('productId'); var colColor = flex.columns.getColumn('colorId'); if (colCountry && colProduct && colColor) { if ($scope.ctx.dataMaps == true) { colCountry.dataMap = buildDataMap(dataSvc.getCountries()); colProduct.dataMap = buildDataMap(dataSvc.getProducts()); colColor.dataMap = buildDataMap(dataSvc.getColors()); } else { colCountry.dataMap = null; colProduct.dataMap = null; colColor.dataMap = null; } } } } // build a data map from a string array using the indices as keys function buildDataMap(items) { var map = []; for (var i = 0; i < items.length; i++) { map.push({ key: i, value: items[i] }); } return new wijmo.grid.DataMap(map, 'key', 'value'); } // apply/remove column formatting function updateFormatting() { var flex = $scope.ctx.flex; if (flex) { var fmt = $scope.ctx.formatting; setColumnFormat('amount', fmt ? 'c' : null); setColumnFormat('amount2', fmt ? 'c' : null); setColumnFormat('discount', fmt ? 'p0' : null); setColumnFormat('start', fmt ? 'MMM d yy' : null); setColumnFormat('end', fmt ? 'HH:mm' : null); } } function setColumnFormat(name, format) { var col = $scope.ctx.flex.columns.getColumn(name); if (col) { col.format = format; } } // test grid's object model $scope.toggleColumnVisibility = function () { var flex = $scope.ctx.flex; var col = flex.columns[0]; col.visible = !col.visible; }; $scope.changeColumnSize = function () { var flex = $scope.ctx.flex; var col = flex.columns[0]; col.visible = true; col.width = col.width < 0 ? 60 : -1; col = flex.rowHeaders.columns[0]; col.width = col.width < 0 ? 40 : -1; }; $scope.toggleRowVisibility = function () { var flex = $scope.ctx.flex; var row = flex.rows[0]; row.visible = !row.visible; }; $scope.changeRowSize = function () { var flex = $scope.ctx.flex; var row = flex.rows[0]; row.visible = true; row.height = row.height < 0 ? 80 : -1; row = flex.columnHeaders.rows[0]; row.height = row.height < 0 ? 80 : -1; }; $scope.changeDefaultRowSize = function () { var flex = $scope.ctx.flex; flex.rows.defaultSize = flex.rows.defaultSize == 28 ? 65 : 28; }; $scope.changeScrollPosition = function () { var flex = $scope.ctx.flex; if (flex.scrollPosition.y == 0) { var sz = flex.scrollSize; flex.scrollPosition = new wijmo.Point(-sz.width / 2, -sz.height / 2); } else { flex.scrollPosition = new wijmo.Point(0, 0); } }; $scope.autoSizeColumn = function () { var flex = $scope.ctx.flex; var sel = flex.selection; flex.autoSizeColumns(sel.leftCol, sel.rightCol); }; $scope.autoSizeRow = function () { var flex = $scope.ctx.flex; var sel = flex.selection; flex.autoSizeRows(sel.topRow, sel.bottomRow); }; // ** save/restore column layout $scope.saveColumnLayout = function () { if (localStorage) { var flex = $scope.ctx.flex; localStorage['columns'] = flex.columnLayout; } } $scope.loadColumnLayout = function () { if (localStorage) { var flex = $scope.ctx.flex; flex.columnLayout = localStorage['columns']; } } // ** inline editing $scope.$watch('ctx.flexInline', function () { var flex = $scope.ctx.flexInline; if (flex) { // prevent default editing flex.isReadOnly = true; // make rows taller to accommodate edit buttons and input controls flex.rows.defaultSize = 44; // use formatter to create buttons and custom editors flex.itemFormatter = itemFormatter; // commit row changes when scrolling the grid flex.scrollPositionChanged.addHandler(function () { if ($scope.ctx.editIndex > -1) { $scope.commitRow($scope.ctx.editIndex); } }); } }); function itemFormatter(panel, r, c, cell) { if (panel.cellType == wijmo.grid.CellType.Cell) { var col = panel.columns[c], html = cell.innerHTML; if (r == $scope.ctx.editIndex) { switch (col.name) { case 'buttons': html = '<div>' + '&nbsp;&nbsp;' + '<button class="btn btn-primary btn-sm" ng-click="commitRow(' + r + ')">' + '<span class="glyphicon glyphicon-ok"></span> OK' + '</button>' + '&nbsp;&nbsp;' + '<button class="btn btn-warning btn-sm" ng-click="cancelRow(' + r + ')">' + '<span class="glyphicon glyphicon-ban-circle"></span> Cancel' + '</button>' + '</div>'; break; case 'date': html = '<input id="theDate" class="form-control" value="' + panel.getCellData(r, c, true) + '"/>'; break; case 'product': html = '<input id="theProduct" class="form-control" value="' + panel.getCellData(r, c, true) + '"/>'; break; } } else { switch (col.name) { case 'buttons': cell.style.padding = '3px'; html = '<div>' + '&nbsp;&nbsp;' + '<button class="btn btn-default btn-sm" ng-click="editRow(' + r + ')">' + '<span class="glyphicon glyphicon-pencil"></span> Edit' + '</button>' + '&nbsp;&nbsp;' + '<button class="btn btn-default btn-sm" ng-click="deleteRow(' + r + ')">' + '<span class="glyphicon glyphicon-remove"></span> Delete' + '</button>' + '</div>'; break; } } // update cell and compile its contents into the scope // (required to wire up the ng-click directives) if (html != cell.innerHTML) { cell.innerHTML = html; cell.style.padding = '3px'; $compile(cell)($scope); } } } $scope.editRow = function (row) { $scope.ctx.editIndex = row; $scope.ctx.flexInline.invalidate(); } $scope.deleteRow = function (row) { var ecv = $scope.ctx.flexInline.collectionView; ecv.removeAt(row); } $scope.commitRow = function (row) { // save changes var flex = $scope.ctx.flexInline; flex.setCellData(row, 'start', $("#theDate").val()); flex.setCellData(row, 'product', $("#theProduct").val()); // done editing $scope.cancelRow(row); } $scope.cancelRow = function (row) { $scope.ctx.editIndex = -1; $scope.ctx.flexInline.invalidate(); } // toggle freezing $scope.toggleFreeze = function () { var flex = $scope.flex; if (flex) { if (flex.frozenRows || flex.frozenColumns) { // show all rows/columns and unfreeze for (var i = 0; i < flex.rows.length; i++) { flex.rows[i].visible = true; } for (var i = 0; i < flex.columns.length; i++) { flex.columns[i].visible = true; } flex.frozenRows = flex.frozenColumns = 0; } else { // hide rows/cols before the viewRange and freeze var vr = flex.viewRange; for (var i = 0; i < vr.topRow; i++) { flex.rows[i].visible = false; } for (var i = 0; i < vr.leftCol; i++) { flex.columns[i].visible = false; } flex.frozenRows = flex.selection.topRow; flex.frozenColumns = flex.selection.leftCol; } } } });
8,170
https://github.com/vbillet/Torque3D/blob/master/Templates/Full/game/shaders/common/hlslStructs.h
Github Open Source
Open Source
MIT
2,022
Torque3D
vbillet
C
Code
489
967
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- // The purpose of this file is to get all of our HLSL structures into one place. // Please use the structures here instead of redefining input and output structures // in each shader file. If structures are added, please adhere to the naming convention. //------------------------------------------------------------------------------ // Vertex Input Structures // // These structures map to FVFs/Vertex Declarations in Torque. See gfxStructs.h //------------------------------------------------------------------------------ // Notes // // Position should be specified as a float4. Right now our vertex structures in // the engine output float3s for position. This does NOT mean that the POSITION // binding should be float3, because it will assign 0 to the w coordinate, which // results in the vertex not getting translated when it is transformed. struct VertexIn_P { float4 pos : POSITION; }; struct VertexIn_PT { float4 pos : POSITION; float2 uv0 : TEXCOORD0; }; struct VertexIn_PTTT { float4 pos : POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; float2 uv2 : TEXCOORD2; }; struct VertexIn_PC { float4 pos : POSITION; float4 color : DIFFUSE; }; struct VertexIn_PNC { float4 pos : POSITION; float3 normal : NORMAL; float4 color : DIFFUSE; }; struct VertexIn_PCT { float4 pos : POSITION; float4 color : DIFFUSE; float2 uv0 : TEXCOORD0; }; struct VertexIn_PN { float4 pos : POSITION; float3 normal : NORMAL; }; struct VertexIn_PNT { float4 pos : POSITION; float3 normal : NORMAL; float2 uv0 : TEXCOORD0; }; struct VertexIn_PNTT { float4 pos : POSITION; float3 normal : NORMAL; float3 tangent : TANGENT; float2 uv0 : TEXCOORD0; }; struct VertexIn_PNCT { float4 pos : POSITION; float3 normal : NORMAL; float4 color : DIFFUSE; float2 uv0 : TEXCOORD0; }; struct VertexIn_PNTTTB { float4 pos : POSITION; float3 normal : NORMAL; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; float3 T : TEXCOORD2; float3 B : TEXCOORD3; };
20,379
https://github.com/abdul-qadirdeveloper/fluentpos/blob/master/src/server/Modules/People/Modules.People.Core/Features/Carts/Events/CartCreatedEvent.cs
Github Open Source
Open Source
MIT
2,021
fluentpos
abdul-qadirdeveloper
C#
Code
53
157
using System; using FluentPOS.Modules.People.Core.Entities; using FluentPOS.Shared.Core.Domain; namespace FluentPOS.Modules.People.Core.Features.Carts.Events { public class CartCreatedEvent : Event { public Guid Id { get; } public Guid CustomerId { get; } public new DateTime Timestamp { get; } public CartCreatedEvent(Cart cart) { CustomerId = cart.CustomerId; Timestamp = cart.Timestamp; Id = cart.Id; AggregateId = cart.Id; } } }
16,953
https://github.com/ejoebstl/sGrid/blob/master/sGridServer/Controllers/MasterPageController.cs
Github Open Source
Open Source
MIT
2,015
sGrid
ejoebstl
C#
Code
1,105
3,228
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using sGridServer.Models; using sGridServer.Code.DataAccessLayer.Models; using sGridServer.Code.Security; using sGridServer.Code.Achievements; using sGridServer.Code.CoinExchange; using sGridServer.Code.Utilities; using sGridServer.Code.DataAccessLayer; using sGridServer.Resources.MasterPage; namespace sGridServer.Controllers { /// <summary> /// The master page controller is responsible for controlling the master page. /// Note that almost all views on this page are partial. /// This is because the master page should be as flexible as possible. /// </summary> public class MasterPageController : Controller { /// <summary> /// Returns the AccountBalanceView. /// </summary> /// <returns>The AccountBalanceView.</returns> public PartialViewResult AccountBalance() { return PartialView(); } /// <summary> /// Returns the FooterView using the corresponding MenuItem objects. /// </summary> /// <returns>The FooterView.</returns> public PartialViewResult Footer() { if (SecurityProvider.Context != null) { //the user is logged in return PartialView(new MenuItem[] { new MenuItem() { LinkText = MenuText.Help, LinkUrl = "~/UserHelp/UserHelp" }, new MenuItem() { LinkText = MenuText.FAQ, LinkUrl = "~/UserHelp/UserFAQ" }, new MenuItem() { LinkText = MenuText.Impressum, LinkUrl = "~/Help/Impressum" }, new MenuItem() { LinkText = MenuText.Contact, LinkUrl = "~/Contact/Contact" } }); } else { return PartialView(new MenuItem[] { new MenuItem() { LinkText = MenuText.Help, LinkUrl = "~/Help/Help" }, new MenuItem() { LinkText = MenuText.FAQ, LinkUrl = "~/Help/FAQ" }, new MenuItem() { LinkText = MenuText.Impressum, LinkUrl = "~/Help/Impressum" }, new MenuItem() { LinkText = MenuText.Contact, LinkUrl = "~/Help/Contact" } }); } } /// <summary> /// Returns the state of the current user via json. /// </summary> /// <returns>A UserState object serialized as json, if a user is currently logged in, an empty json object, else. </returns> public JsonResult GetUserState() { User account = SecurityProvider.CurrentUser as User; if (account == null) { return Json(new object()); } //Fetch the user state. UserState userState = new UserState() { CoinBalance = account.CoinAccount.CurrentBalance, Id = account.Id, Username = account.Nickname }; //Fetch the next unshown achievement. Achievement nextUnshownAchievement = new AchievementManager().GetNextUnshownAchievement(account); if (nextUnshownAchievement != null) { //Copy the achievement into the user-state object using all relevant information. userState.NextAchievement = new NextAchievementState() { AchievementId = nextUnshownAchievement.AchievementId, AchievementType = nextUnshownAchievement.AchievementType, BonusCoins = nextUnshownAchievement.BonusCoins, Description = nextUnshownAchievement.Description.Text, Icon = nextUnshownAchievement.Icon, Name = nextUnshownAchievement.Name.Text }; } //Send the data to the user. return Json(userState, JsonRequestBehavior.AllowGet); } /// <summary> /// Shows the partial LanguageSelectionView. /// </summary> /// <returns>LanguageSelectionView.</returns> public PartialViewResult LanguageSelection() { return PartialView(); } /// <summary> /// Shows the partial LoginPartView. /// </summary> /// <returns>LoginPartView.</returns> public PartialViewResult LoginPart() { return PartialView(); } /// <summary> /// Logs out the current user. /// </summary> /// <returns>Returns a redirect result to the frontpage.</returns> public ActionResult Logout() { SecurityProvider.LogOut(); return Redirect("~/"); } /// <summary> /// Returns a partial global helper scripts section. /// </summary> /// <returns>A partial view.</returns> public PartialViewResult HelperScripts() { return PartialView(); } /// <summary> /// Returns the MainMenuView using the corresponding MenuItem objects. /// </summary> /// <returns>The MainMenuView.</returns> public PartialViewResult MainMenu() { if (SecurityProvider.Context != null && SecurityProvider.Context.UserPermissions == SiteRoles.Admin) { //Admins main menu return PartialView(new MenuItem[] { new MenuItem() { LinkText = MenuText.ProfileOverview, LinkUrl = "~/MemberConfiguration/MemberOverview"}, new MenuItem() { LinkText = MenuText.GridProjects, LinkUrl = "~/Project/GridProjectOverview"}, new MenuItem() { LinkText = MenuText.About, LinkUrl = "~/About/About"}, new MenuItem() { LinkText = MenuText.CoinExchange, LinkUrl = "~/CoinExchange/RewardOverview"}, new MenuItem() { LinkText = MenuText.Ranking, LinkUrl = "~/Statistics/Ranking"} }); } else { return PartialView(new MenuItem[] { new MenuItem() { LinkText = MenuText.ProfileOverview, LinkUrl = "~/Profile/ProfileOverview"}, new MenuItem() { LinkText = MenuText.GridProjects, LinkUrl = "~/Project/GridProjectOverview"}, new MenuItem() { LinkText = MenuText.About, LinkUrl = "~/About/About"}, new MenuItem() { LinkText = MenuText.CoinExchange, LinkUrl = "~/CoinExchange/RewardOverview"}, new MenuItem() { LinkText = MenuText.Ranking, LinkUrl = "~/Statistics/Ranking"} }); } } /// <summary> /// Returns the partial ScriptSectionView. /// </summary> /// <returns>The ScriptSectionView.</returns> public PartialViewResult ScriptSection() { return PartialView(); } /// <summary> /// Returns the partial BannerPart view.. /// </summary> /// <returns>The BannerPart view.</returns> public ActionResult BannerPart() { //Select a random Sponsor. MemberManager memberManager = new MemberManager(); Random rand = new Random(); Sponsor sponsorToShow = null; IEnumerable<Sponsor> sponsors = memberManager.Sponsors.Where(x => x.Approved); int count = sponsors.Count(); if (count > 0) { sponsorToShow = sponsors.Skip(rand.Next(0, count)).First(); } //If there is no sponsor, nothing can be shown. if (sponsorToShow != null && sponsorToShow.Banner != null && sponsorToShow.Banner != "") { return PartialView(sponsorToShow); } else { return new EmptyResult(); } } /// <summary> /// Selects the language given for the current user, or if not applicable, for the current session. /// </summary> /// <param name="language">The language to set as given by the model returned by the /// LanguageSelection action method. </param> /// <returns>An empty result.</returns> public EmptyResult SelectLangauge(string language) { LanguageItem newLanguage = LanguageManager.LanguageByCode(language); if (newLanguage != null) { LanguageManager.CurrentLanguage = newLanguage; } return new EmptyResult(); } /// <summary> /// Notifies the controller, that the achievement with the given id has been /// shown to the user and should not been shown again. /// </summary> /// <param name="achievementId">The id of the achievement which has been shown as /// given by the GetUserState action method. </param> /// <returns>An empty result.</returns> [SGridAuthorize(RequiredPermissions = SiteRoles.User)] public ActionResult SetAchievementShown(int achievementId) { AchievementManager achMan = new AchievementManager(); User account = (User)SecurityProvider.CurrentUser; achMan.SetAchievementShown(account, achMan.GetAchievements(account).Where(a => a.AchievementId == achievementId).FirstOrDefault()); return new EmptyResult(); } /// <summary> /// Returns the SubMenuView using the corresponding MenuItem objects. /// </summary> /// <returns>The SubMenuView.</returns> public PartialViewResult SubMenu() { MenuItem[] menu = null; if (SecurityProvider.Context != null) { switch (SecurityProvider.Context.UserPermissions) { case SiteRoles.Admin: //Sub menu for Admins menu = new MenuItem[] { new MenuItem() { LinkText = MenuText.AdminDashboard, LinkUrl = "~/AdminDashboard/AdminDashboard"}, new MenuItem() { LinkText = MenuText.AchievementConfiguration, LinkUrl = "~/AchievementConfiguration/AchievementOverview"}, new MenuItem() { LinkText = MenuText.NewsConfiguration, LinkUrl = "~/AppConfiguration/ConfigureNews"}, new MenuItem() { LinkText = MenuText.ErrorLog, LinkUrl = "~/AppConfiguration/ShowErrors"}, new MenuItem() { LinkText = MenuText.BannerRequests, LinkUrl = "~/PartnerSupport/BannerOverview"}, new MenuItem() { LinkText = MenuText.Rewards, LinkUrl = "~/PartnerSupport/RewardsOverview"}, new MenuItem() { LinkText = MenuText.MessageRequests, LinkUrl = "~/Support/MessageOverview"} }; break; case SiteRoles.CoinPartner: //Sub menu for Coin Partners menu = new MenuItem[] { new MenuItem() { LinkText = MenuText.PartnerDashboard, LinkUrl = "~/Partnership/PartnershipDashboard"}, new MenuItem() { LinkText = MenuText.Rewards, LinkUrl = "~/RewardConfiguration/RewardsOverview"}, new MenuItem() { LinkText = MenuText.PartnerHelp, LinkUrl = "~/Partnership/PartnershipHelp"}, new MenuItem() { LinkText = MenuText.PartnerFAQ, LinkUrl = "~/Partnership/PartnershipFAQ"} }; break; case SiteRoles.Sponsor: //Sub menu for Sponsors menu = new MenuItem[] { new MenuItem() { LinkText = MenuText.SponsorDashboard, LinkUrl = "~/Partnership/SponsorDashboard"}, new MenuItem() { LinkText = MenuText.SponsorHelp, LinkUrl = "~/Partnership/SponsorHelp"} }; break; case SiteRoles.User: //Sub menu for Users menu = new MenuItem[] { new MenuItem() { LinkText = MenuText.UserDashboard, LinkUrl = "~/UserDashboard/UserDashboard"}, new MenuItem() { LinkText = MenuText.Friends, LinkUrl = "~/Friends/FriendsOverview"}, new MenuItem() { LinkText = MenuText.UserAchievement, LinkUrl = "~/UserAchievement/Achievements"}, new MenuItem() { LinkText = MenuText.ProfileSettings, LinkUrl = "~/ProfileSettings/Settings"}, new MenuItem() { LinkText = MenuText.Statistics, LinkUrl = "~/Statistics/UserStatistics"}, new MenuItem() { LinkText = MenuText.Download, LinkUrl = "~/Public/ClientDownload"} }; break; } } if (menu == null) { //Default (empty) sub menu menu = new MenuItem[] { }; } return PartialView(menu); } } }
13,662
https://github.com/elix22/urho/blob/master/Bindings/Portable/Runtime/ReferenceHolder.cs
Github Open Source
Open Source
MIT
2,020
urho
elix22
C#
Code
142
418
using System; namespace Urho { internal class ReferenceHolder<T> where T : class { public ReferenceHolder(T obj, bool weak) { if (weak) WeakRef = new WeakReference<T>(obj); else StrongRef = obj; } public T StrongRef { get; private set; } public WeakReference<T> WeakRef { get; private set; } public bool IsWeak => WeakRef != null; public T Reference { get { if (StrongRef != null) return StrongRef; T wr; WeakRef.TryGetTarget(out wr); return wr; } } /// <summary> /// Change Weak to Strong /// </summary> public bool MakeStrong() { if (StrongRef != null) return true; T strong = null; WeakRef?.TryGetTarget(out strong); StrongRef = strong; WeakRef = null; return StrongRef != null; } /// <summary> /// Change Strong to Weak /// </summary> public bool MakeWeak() { if (StrongRef != null) { WeakRef = new WeakReference<T>(StrongRef); StrongRef = null; return true; } return false; } } }
43,258
https://github.com/DataCompressionPrimitives/DCP-Java/blob/master/src/main/java/org/dcp/io/impl/ChannelBitOutputStream.java
Github Open Source
Open Source
Apache-2.0
2,021
DCP-Java
DataCompressionPrimitives
Java
Code
150
435
/** * Copyright 2019 DataCompressionPrimitives. * * Licensed under the Apache License, Version 2.0 (the "License"); */ package org.dcp.io.impl; import org.dcp.entities.bit.Bit; import org.dcp.io.BitOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; public class ChannelBitOutputStream implements BitOutputStream { private static final int FIRST_BIT = 128; private static final int LAST_BIT = 1; private final WritableByteChannel byteChannel; private final ByteBuffer buffer; private int mask; private byte current; public ChannelBitOutputStream(WritableByteChannel byteChannel) { this.byteChannel = byteChannel; this.buffer = ByteBuffer.allocateDirect(1); this.mask = FIRST_BIT; } protected void writeByte(byte byteWrite) { buffer.put(0, byteWrite); try { byteChannel.write(buffer); } catch (IOException ioException) { throw new IllegalStateException(ioException); } buffer.rewind(); } @Override public void writeBit(Bit bit) { if (bit.value()) { current |= mask; } if (mask != LAST_BIT) { mask >>>= 1; } else { writeByte(current); mask = FIRST_BIT; current = 0; } } @Override public void flushBits() { if(mask != LAST_BIT) { writeByte(current); mask = FIRST_BIT; current = 0; } } }
37,379