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/MatthewJA/Coffeequate/blob/master/src/operators/Function.coffee
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,016
Coffeequate
MatthewJA
CoffeeScript
Code
1,041
2,287
define [ "nodes" "terminals" "AlgebraError" "parseArgs" "require" "compare" "prettyRender" ], (nodes, terminals, AlgebraError, parseArgs, require, compare, prettyRender) -> INV_SUFFIX = "_inv" # Suffix used to represent an inverse function. # Node in the expression tree representing a symbolic function. class FunctionNode extends nodes.UnaryNode # Make a new function node. # Arguments passed as the child will be parsed as children from whatever # type they are. # # @param name [String] The name of this function, e.g. "f" in f(x). # @param param [Terminal] The independent variable of this function. # This is a general terminal because we also want to be able to write # the function evaluated at some point, e.g. f(1) in addition to f(x). # @return [FunctionNode] A new function node. constructor: (name, param, args...) -> unless param? throw new Error("Function nodes must have a dependent variable") if args.length > 0 throw new Error("Function nodes must have no extra arguments") unless /[a-zA-Z_]+/.test(name) throw new Error("Function name invalid, must be alphanumeric") @cmp = -0.5 super(name, param) # Deep-copy this node. # # @return [FunctionNode] A copy of this node. copy: -> return new FunctionNode(@label, if @child.copy? then @child.copy() else @child) # Sort this node in-place. sort: -> @copy() # Check equality between this and another object. # # @param b [Object] An object to check equality with. # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [Boolean] Whether the objects are equal. equals: (b, equivalencies={}) -> unless b instanceof FunctionNode return false if @child.equals? unless @child.equals(b.child, equivalencies) return false else unless @child == b.child return false return true # Compare this object with another of the same type. # # @param b [FunctionNode] A function to compare to. # @return [Number] The comparison: 1 if this node is greater than the # other, -1 if vice versa, and 0 if they are equal. compareSameType: (b) -> if @label < b.label return -1 if @label > b.label return 1 return compare(@child, b.child) # Map a function over the variables in the child. # # @param fun [Function] A function to map over variables. # @return [FunctionNode] A copy of this node with the given function # mapped over all variables. mapOverVariables: (fun) -> new FunctionNode(@label, @child.mapOverVariables(fun)) # Expand this node. # # @return [FunctionNode] This node, expanded. expand: -> new FunctionNode(@label, @child.expand()) # Simplify this node. # # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [FunctionNode] This node, simplified. simplify: (equivalencies={}) -> new FunctionNode(@label, @child.simplify(equivalencies)) # Expand and then simplify this node. # # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [FunctionNode] This node, expanded and simplified. expandAndSimplify: (equivalencies={}) -> new FunctionNode(@label, @child.expandAndSimplify(equivalencies)) # Get the inverse of this function. # # @param param [Terminal] Parameter of the inverse function. # @return [FunctionNode] Inverse function. inverse: (param=null) -> unless param? param = @child if @label.indexOf(INV_SUFFIX, @label.length - INV_SUFFIX.length) == -1 # This is not an inverse function, so just invert it. return new FunctionNode(@label + INV_SUFFIX, param.copy()) else # This is an inverse function. return new FunctionNode(@label[...-INV_SUFFIX.length], param.copy()) # Solve this node for a variable. # # @param variable [String] The label of the variable to solve for. # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [Array<BasicNode>, Array<Terminal>] The solutions for the # given variable. # @throw [AlgebraError] If the node cannot be solved. solve: (variable, equivalencies={}) -> Add = require("operators/Add") Mul = require("operators/Mul") # Intuition: # Solve f(g(x)) = 0 # <=> Solve g(x) - f_inv(0) = 0 inv0 = @inverse(new terminals.Constant("0")) return (new Add(@child.copy(), new Mul("-1", inv0))).solve( variable, equivalencies) # Substitute values into variables. # # @param substitutions [Object] A map of variable labels to their # values. Values can be any node, terminal, or something interpretable # as a terminal. # @param uncertaintySubstitutions [Object] A map of variable labels to # the values of their uncertainties. # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @param assumeZeroUncertainty [Boolean] Optional. Whether to assume # uncertainties are zero if unknown (default false). # @param evaluateSymbolicConstants [Boolean] Optional. Whether to # evaluate symbolic constants (default false). # @return [BasicNode, Terminal] This node with all substitutions # substituted. sub: (substitutions, uncertaintySubstitutions, equivalencies={}, assumeZeroUncertainty=false, evaluateSymbolicConstants=false) -> new FunctionNode(@label, @child.sub(substitutions, uncertaintySubstitutions, equivalencies, assumeZeroUncertainty, evaluateSymbolicConstants)) # Get all variable labels used in children of this node. # # @return [Array<String>] A list of all labels of variables in children # of this node. getAllVariables: -> @child.getAllVariables() # Replace variable labels. # # @param replacements [Object] A map of variable labels to their # replacement labels. # @return [FunctionNode] This node with variable labels replaced. replaceVariables: (replacements) -> new FunctionNode(@label, @child.replaceVariables(replacements)) # Convert this node into a drawing node. # # @return [DrawingNode] A drawing node representing this node. toDrawingNode: -> FunctionDN = prettyRender.Function return new FunctionDN(@label, @child.toDrawingNode()) # Get the derivative of this function with respect to its independent # variable. # # @param param [Terminal] Parameter of the derivative. Default @child. # @return [FunctionNode] The derivative of this function at param. derivative: (param=null) -> unless param? param = @child return new FunctionNode(@label+"'", @child.copy()) # Differentiate this node with respect to a variable. # Since this is a generic function, the derivative is also a generic # function, possibly with the chain rule applied. # # @param variable [String] The label of the variable to differentiate # with respect to. # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [BasicNode] The derivative of this node. differentiate: (variable, equivalencies={}) -> Mul = require("operators/Mul") return (new Mul(@child.differentiate(variable, equivalencies), @derivative())).expandAndSimplify() # Check if this node contains a given variable. # # @param variable [String] The label of the variable to find. # @param equivalencies [Object] Optional. A map of variable labels to a # list of equivalent variable labels. # @return [Boolean] Whether or not this node contains the given # variable. containsVariable: (variable, equivalencies={}) -> return @child.containsVariable(variable, equivalencies) @approx: -> throw new Error("Can't approximate a symbolic function")
10,575
https://github.com/forki/Gu.Wpf.ValidationScope/blob/master/Gu.Wpf.ValidationScope.Demo/UiTestWindows/NotifyDataErrorInfoWindow.xaml.cs
Github Open Source
Open Source
MIT
2,022
Gu.Wpf.ValidationScope
forki
C#
Code
19
69
namespace Gu.Wpf.ValidationScope.Demo { using System.Windows; public partial class NotifyDataErrorInfoWindow : Window { public NotifyDataErrorInfoWindow() { this.InitializeComponent(); } } }
34,137
https://github.com/arjayW/auda-sa/blob/master/html/struct_reverb__priv__t.js
Github Open Source
Open Source
CECILL-B
null
auda-sa
arjayW
JavaScript
Code
20
135
var struct_reverb__priv__t = [ [ "dry", "struct_reverb__priv__t.html#a651cb32dffc2dbd24d876879508ece08", null ], [ "reverb", "struct_reverb__priv__t.html#a56ccb1fe9621312a67160284fabad562", null ], [ "wet", "struct_reverb__priv__t.html#a2acb868e69006bdad0a970952b03d92b", null ] ];
34,203
https://github.com/intrepidcs/OBD2PRO_WIFI_CC32XX/blob/master/ti_simplelink_sdk/kernel/tirtos/packages/ti/sysbios/timers/timer64/TimestampProvider.xs
Github Open Source
Open Source
Unlicense
null
OBD2PRO_WIFI_CC32XX
intrepidcs
XS
Code
563
1,527
/* * Copyright (c) 2012-2013, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 OWNER 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. */ /* * ======== TimestampProvider.xs ======== * */ var Timer = null; var TimestampProvider = null; var BIOS = null; /* * ======== module$meta$init ======== */ function module$meta$init() { /* Only process during "cfg" phase */ if (xdc.om.$name != "cfg") { return; } TimestampProvider = this; /* set fxntab default */ TimestampProvider.common$.fxntab = false; } /* * ======== module$use ======== */ function module$use() { BIOS = xdc.useModule('ti.sysbios.BIOS'); Timer = xdc.useModule('ti.sysbios.timers.timer64.Timer'); Startup = xdc.useModule('xdc.runtime.Startup'); var Clock = xdc.om['ti.sysbios.knl.Clock']; var Diags = xdc.useModule('xdc.runtime.Diags'); for (var dl in TimestampProvider.common$) { if (dl.match(/^diags_/) && dl != 'diags_ASSERT') { TimestampProvider.common$[dl] = Diags.ALWAYS_OFF; } } } /* * ======== module$static$init ======== */ function module$static$init(mod, params) { if (TimestampProvider.useClockTimer == false) { var timerParams = new Timer.Params(); timerParams.period = Timer.MAX_PERIOD; timerParams.periodType = Timer.PeriodType_COUNTS; timerParams.runMode = Timer.RunMode_CONTINUOUS; timerParams.startMode = Timer.StartMode_USER; mod.timer = Timer.create(TimestampProvider.timerId, TimestampProvider.rolloverFunc, timerParams); Startup.lastFxns.$add(TimestampProvider.startTimer); } else { mod.timer = null; } mod.hi = 0; } /* * ======== module$validate ======== */ function module$validate() { var BIOS = xdc.module('ti.sysbios.BIOS'); var Clock = xdc.module('ti.sysbios.knl.Clock'); if ((!BIOS.clockEnabled || (Clock.tickSource == Clock.TickSource_NULL)) && (this.useClockTimer == true)) { TimestampProvider.$logError("Clock is not enabled, cannot share its Timer", TimestampProvider, "useClockTimer"); } } /* * ======== module$view$init ======== */ function module$view$init(view, mod) { var Program = xdc.useModule('xdc.rov.Program'); var Timer = Program.scanModule('ti.sysbios.timers.timer64.Timer'); view.timer = Timer.$scanHandle(mod.timer).$view; view.usesClockTimer = Program.$modules['ti.sysbios.timers.timer64.TimestampProvider'].useClockTimer; } /* * ======== getFreqMeta ======== */ function getFreqMeta() { var freq = {lo: 0, hi: 0}; var modObj = TimestampProvider.$object; var timer = null; if (TimestampProvider.useClockTimer == false) { timer = modObj.timer; } else { var Clock = xdc.module('ti.sysbios.knl.Clock'); timer = Clock.$object.timer.delegate$; } if (timer) { if (Timer.freqDivisor) { freq = BIOS.getCpuFreqMeta(); freq.lo /= Timer.freqDivisor; freq.hi = 0; // Don't support freqs > 4GHz } else { if (timer.$object.extFreq.lo) { freq.lo = timer.$object.extFreq.lo; } else { freq = Timer.intFreqs[timer.$object.id >> 1]; } } } //print("***** timer64.TimestampProvider.getFreqMeta() freq = " + freq.lo); return (freq); }
45,664
https://github.com/binoculars/osf.io/blob/master/api/metrics/views.py
Github Open Source
Open Source
MIT, BSD-3-Clause, LicenseRef-scancode-free-unknown, LicenseRef-scancode-warranty-disclaimer, AGPL-3.0-only, LGPL-2.0-or-later, LicenseRef-scancode-proprietary-license, MPL-1.1, CPAL-1.0, LicenseRef-scancode-unknown-license-reference, BSD-2-Clause, Apache-2.0
2,022
osf.io
binoculars
Python
Code
1,093
4,412
import json from enum import Enum from django.http import JsonResponse, HttpResponse, Http404 from django.utils import timezone from elasticsearch.exceptions import NotFoundError, RequestError from elasticsearch_dsl.connections import get_connection from rest_framework.exceptions import ValidationError from rest_framework import permissions as drf_permissions from rest_framework.generics import GenericAPIView from framework.auth.oauth_scopes import CoreScopes from api.base.permissions import TokenHasScope from api.metrics.permissions import IsPreprintMetricsUser, IsRawMetricsUser, IsRegistriesModerationMetricsUser from api.metrics.serializers import ( PreprintMetricSerializer, RawMetricsSerializer, CountedUsageSerializer, DailyReportSerializer, ReportNameSerializer, NodeAnalyticsSerializer, ) from api.metrics.utils import parse_datetimes from api.base.views import JSONAPIBaseView from api.base.waffle_decorators import require_switch from api.nodes.permissions import MustBePublic from osf.features import ENABLE_RAW_METRICS from osf.metrics import PreprintDownload, PreprintView, RegistriesModerationMetrics, CountedUsage from osf.metrics import reports from osf.metrics.utils import stable_key from osf.models import AbstractNode class PreprintMetricMixin(JSONAPIBaseView): permission_classes = ( drf_permissions.IsAuthenticated, drf_permissions.IsAdminUser, IsPreprintMetricsUser, TokenHasScope, ) required_read_scopes = [CoreScopes.METRICS_BASIC] required_write_scopes = [CoreScopes.METRICS_RESTRICTED] serializer_class = PreprintMetricSerializer @property def metric_type(self): raise NotImplementedError @property def metric(self): raise NotImplementedError def add_search(self, search, query_params, **kwargs): """ get list of guids from the kwargs use that in a query to narrow down metrics results """ preprint_guid_string = query_params.get('guids') if not preprint_guid_string: raise ValidationError( 'To gather metrics for preprints, you must provide one or more preprint ' + 'guids in the `guids` query parameter.', ) preprint_guids = preprint_guid_string.split(',') return search.filter('terms', preprint_id=preprint_guids) def format_response(self, response, query_params): data = [] if getattr(response, 'aggregations') and response.aggregations: for result in response.aggregations.dates.buckets: guid_results = {} for preprint_result in result.preprints.buckets: guid_results[preprint_result['key']] = preprint_result['total']['value'] # return 0 for the guids with no results for consistent payloads guids = query_params['guids'].split(',') if guid_results.keys() != guids: for guid in guids: if not guid_results.get(guid): guid_results[guid] = 0 result_dict = {result.key_as_string: guid_results} data.append(result_dict) return { 'metric_type': self.metric_type, 'data': data, } def execute_search(self, search, query=None): try: # There's a bug in the ES python library the prevents us from updating the search object, so lets just make # the raw query. If we have it. if query: es = get_connection(search._using) response = search._response_class( search, es.search( index=search._index, body=query, ), ) else: response = search.execute() except NotFoundError: # _get_relevant_indices returned 1 or more indices # that doesn't exist. Fall back to unoptimized query search = search.index().index(self.metric._default_index()) response = search.execute() return response def get(self, *args, **kwargs): query_params = getattr(self.request, 'query_params', self.request.GET) interval = query_params.get('interval', 'day') start_datetime, end_datetime = parse_datetimes(query_params) search = self.metric.search(after=start_datetime) search = search.filter('range', timestamp={'gte': start_datetime, 'lt': end_datetime}) search.aggs.bucket('dates', 'date_histogram', field='timestamp', interval=interval) \ .bucket('preprints', 'terms', field='preprint_id') \ .metric('total', 'sum', field='count') search = self.add_search(search, query_params, **kwargs) response = self.execute_search(search) resp_dict = self.format_response(response, query_params) return JsonResponse(resp_dict) def post(self, request, *args, **kwargs): """ For a bit of future proofing, accept custom elasticsearch aggregation queries in JSON form. Caution - this could be slow if a very large query is executed, so use with care! """ search = self.metric.search() query = request.data.get('query') try: results = self.execute_search(search, query) except RequestError as e: if e.args: raise ValidationError(e.info['error']['root_cause'][0]['reason']) raise ValidationError('Malformed elasticsearch query.') return JsonResponse(results.to_dict()) class PreprintViewMetrics(PreprintMetricMixin): view_category = 'preprint-metrics' view_name = 'preprint-view-metrics' @property def metric_type(self): return 'views' @property def metric(self): return PreprintView class PreprintDownloadMetrics(PreprintMetricMixin): view_category = 'preprint-metrics' view_name = 'preprint-download-metrics' @property def metric_type(self): return 'downloads' @property def metric(self): return PreprintDownload class RawMetricsView(GenericAPIView): permission_classes = ( drf_permissions.IsAuthenticated, IsRawMetricsUser, TokenHasScope, ) required_read_scopes = [CoreScopes.METRICS_BASIC] required_write_scopes = [CoreScopes.METRICS_RESTRICTED] view_category = 'raw-metrics' view_name = 'raw-metrics-view' serializer_class = RawMetricsSerializer @require_switch(ENABLE_RAW_METRICS) def delete(self, request, *args, **kwargs): raise ValidationError('DELETE not supported. Use GET/POST/PUT') @require_switch(ENABLE_RAW_METRICS) def get(self, request, *args, **kwargs): connection = get_connection() url_path = kwargs['url_path'] return JsonResponse(connection.transport.perform_request('GET', f'/{url_path}')) @require_switch(ENABLE_RAW_METRICS) def post(self, request, *args, **kwargs): connection = get_connection() url_path = kwargs['url_path'] body = json.loads(request.body) return JsonResponse(connection.transport.perform_request('POST', f'/{url_path}', body=body)) @require_switch(ENABLE_RAW_METRICS) def put(self, request, *args, **kwargs): connection = get_connection() url_path = kwargs['url_path'] body = json.loads(request.body) return JsonResponse(connection.transport.perform_request('PUT', f'/{url_path}', body=body)) class RegistriesModerationMetricsView(GenericAPIView): permission_classes = ( drf_permissions.IsAuthenticated, IsRegistriesModerationMetricsUser, TokenHasScope, ) required_read_scopes = [CoreScopes.METRICS_BASIC] required_write_scopes = [CoreScopes.METRICS_RESTRICTED] view_category = 'raw-metrics' view_name = 'raw-metrics-view' def get(self, request, *args, **kwargs): return JsonResponse(RegistriesModerationMetrics.get_registries_info()) VIEWABLE_REPORTS = { # 'addon_usage': reports.AddonUsageReport, 'download_count': reports.DownloadCountReport, 'institution_summary': reports.InstitutionSummaryReport, 'node_summary': reports.NodeSummaryReport, 'osfstorage_file_count': reports.OsfstorageFileCountReport, 'preprint_summary': reports.PreprintSummaryReport, 'user_summary': reports.UserSummaryReport, } class ReportNameList(JSONAPIBaseView): permission_classes = ( TokenHasScope, drf_permissions.IsAuthenticatedOrReadOnly, ) required_read_scopes = [CoreScopes.ALWAYS_PUBLIC] required_write_scopes = [CoreScopes.NULL] view_category = 'metrics' view_name = 'report-name-list' serializer_class = ReportNameSerializer def get(self, request, *args, **kwargs): serializer = self.serializer_class( VIEWABLE_REPORTS.keys(), many=True, ) return JsonResponse({'data': serializer.data}) class RecentReportList(JSONAPIBaseView): MAX_COUNT = 1000 DEFAULT_DAYS_BACK = 13 permission_classes = ( TokenHasScope, drf_permissions.IsAuthenticatedOrReadOnly, ) required_read_scopes = [CoreScopes.ALWAYS_PUBLIC] required_write_scopes = [CoreScopes.NULL] view_category = 'metrics' view_name = 'recent-report-list' serializer_class = DailyReportSerializer def get(self, request, *args, report_name): try: report_class = VIEWABLE_REPORTS[report_name] except KeyError: return JsonResponse( {'errors': [{ 'title': 'unknown report name', 'detail': f'unknown report: "{report_name}"', }]}, status=404, ) days_back = request.GET.get('days_back', self.DEFAULT_DAYS_BACK) search_recent = ( report_class.search() .filter('range', report_date={'gte': f'now/d-{days_back}d'}) .sort('-report_date') [:self.MAX_COUNT] ) search_response = search_recent.execute() serializer = self.serializer_class( search_response, many=True, context={'report_name': report_name}, ) return JsonResponse({'data': serializer.data}) class CountedUsageView(JSONAPIBaseView): view_category = 'metrics' view_name = 'counted-usage' serializer_class = CountedUsageSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) session_id = self._get_session_id( request, client_session_id=serializer.validated_data.get('client_session_id'), ) serializer.save(session_id=session_id) return HttpResponse(status=201) def _get_session_id(self, request, client_session_id=None): # get a session id as described in the COUNTER code of practice: # https://cop5.projectcounter.org/en/5.0.2/07-processing/03-counting-unique-items.html # -- different from the "login session" tracked by `osf.models.Session` (which # lasts about a month), this session lasts at most a day and may time out after # minutes or hours of inactivity now = timezone.now() current_date_str = now.date().isoformat() if client_session_id: session_id_parts = [ client_session_id, current_date_str, ] elif request.user.is_authenticated: session_id_parts = [ request.user._id, current_date_str, now.hour, ] else: session_id_parts = [ request.get_host(), request.META.get('HTTP_USER_AGENT', ''), current_date_str, now.hour, ] return stable_key(*session_id_parts) class NodeAnalyticsQuery(JSONAPIBaseView): permission_classes = ( MustBePublic, TokenHasScope, drf_permissions.IsAuthenticatedOrReadOnly, ) required_read_scopes = [CoreScopes.ALWAYS_PUBLIC] required_write_scopes = [CoreScopes.NULL] view_category = 'metrics' view_name = 'node-analytics-query' serializer_class = NodeAnalyticsSerializer class Timespan(Enum): WEEK = 'week' FORTNIGHT = 'fortnight' MONTH = 'month' def get(self, request, *args, node_guid, timespan): try: node = AbstractNode.load(node_guid) except AbstractNode.DoesNotExist: raise Http404 self.check_object_permissions(request, node) analytics_result = self._run_query(node_guid, timespan) serializer = self.serializer_class( analytics_result, context={ 'node_guid': node_guid, 'timespan': timespan, }, ) return JsonResponse({'data': serializer.data}) def _run_query(self, node_guid, timespan): query_dict = self._build_query_payload(node_guid, NodeAnalyticsQuery.Timespan(timespan)) analytics_search = CountedUsage.search().update_from_dict(query_dict) return analytics_search.execute() def _build_query_payload(self, node_guid, timespan): return { 'size': 0, # don't return hits, just the aggregations 'query': { 'bool': { 'minimum_should_match': 1, 'should': [ {'term': {'item_guid': node_guid}}, {'term': {'surrounding_guids': node_guid}}, ], 'filter': [ {'term': {'item_public': True}}, {'term': {'action_labels': 'view'}}, {'term': {'action_labels': 'web'}}, self._build_timespan_filter(timespan), ], }, }, 'aggs': { 'unique-visits': { 'date_histogram': { 'field': 'timestamp', 'interval': 'day', }, }, 'time-of-day': { 'terms': { 'field': 'pageview_info.hour_of_day', 'size': 24, }, }, 'referer-domain': { 'terms': { 'field': 'pageview_info.referer_domain', 'size': 10, }, }, 'popular-pages': { 'terms': { 'field': 'pageview_info.page_path', 'size': 10, }, 'aggs': { 'route-for-path': { 'terms': { 'field': 'pageview_info.route_name', 'size': 1, }, }, 'title-for-path': { 'terms': { 'field': 'pageview_info.page_title', 'size': 1, }, }, }, }, }, } def _build_timespan_filter(self, timespan): if timespan == NodeAnalyticsQuery.Timespan.WEEK: from_date = 'now-1w/d' elif timespan == NodeAnalyticsQuery.Timespan.FORTNIGHT: from_date = 'now-2w/d' elif timespan == NodeAnalyticsQuery.Timespan.MONTH: from_date = 'now-1M/d' else: raise NotImplementedError return { 'range': { 'timestamp': { 'gte': from_date, }, }, }
28,504
https://github.com/PirateRoberts98/capstone-hygeine-managment/blob/master/web/src/Pages/CaregiverPages/UsersAnalysisPage/index.js
Github Open Source
Open Source
MIT
2,020
capstone-hygeine-managment
PirateRoberts98
JavaScript
Code
226
966
import React, {Fragment, useEffect} from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; // Other Components import Alerts from '../../../components/Alert'; // Charts import SensorHumidityChart from '../../../components/charts/SensorHumidity'; import SensorPressureChart from '../../../components/charts/SensorPressure'; import SensorTemperatureChart from '../../../components/charts/SensorTemperature'; // MaterialUI import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } export default function UsersAnalysisPage(props) { const [openPollSnackBar, setPollSnackBarOpen] = React.useState(false); const [pollSnackBarLabel, setPollSnackBarLabel] = React.useState(); const [userData, setUserData] = React.useState(props.userData); const [patientData, setPatientData] = React.useState(''); useEffect(()=>{ setPatientData(props.patientData); }); const sensorPollRateControl = (buttonControlName) => { switch (buttonControlName) { case 'pollUp': setPollSnackBarLabel("Sensor Polled Up."); break; case 'pollDown': setPollSnackBarLabel("Sensor Polled Down."); break; case 'pollStop': setPollSnackBarLabel("Sensor Polling Stopped."); break; } setPollSnackBarOpen(true); } const handlePollSnackBarClose = (event, reason) => { if (reason === 'clickaway') { return; } setPollSnackBarOpen(false); } return ( <Fragment> <ReactCSSTransitionGroup component="div" transitionName="TabsAnimation" transitionAppear={true} transitionAppearTimeout={0} transitionEnter={false} transitionLeave={false}> <Typography variant="h2" gutterBottom> Alerts </Typography> <Alerts /> <Typography variant="h2" gutterBottom> Sensor Control </Typography> <Button onClick={()=>sensorPollRateControl('pollUp')} style={{ marginBottom:"15px", marginRight:"15px" }} variant="contained" color="secondary"> Poll Rate Up </Button> <Button onClick={()=>sensorPollRateControl('pollDown')} style={{ marginBottom:"15px", marginRight:"15px" }} variant="contained" color="secondary"> Poll Rate Down </Button> <Button onClick={()=>sensorPollRateControl('pollStop')} style={{ marginBottom:"15px", marginRight:"15px" }} variant="contained" color="secondary"> Stop Polling </Button> <Typography variant="h2" gutterBottom> Humidity Chart </Typography> <SensorHumidityChart/> <Typography variant="h2" gutterBottom> Pressure Chart </Typography> <SensorPressureChart/> <Typography variant="h2" gutterBottom> Temperature Chart </Typography> <SensorTemperatureChart/> <Snackbar open={openPollSnackBar} autoHideDuration={6000} onClose={handlePollSnackBarClose}> <Alert onClose={handlePollSnackBarClose} severity="info"> {pollSnackBarLabel} </Alert> </Snackbar> </ReactCSSTransitionGroup> </Fragment> ); }
2,994
https://github.com/MatheusCavalari/ArkStudentUFABC/blob/master/Scripts/bola.cs
Github Open Source
Open Source
MIT
null
ArkStudentUFABC
MatheusCavalari
C#
Code
269
1,090
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class bola : MonoBehaviour { public Rigidbody2D rb; public float velBola; public Transform jogador; public float posicaoBolinha; private bool comecou; public GameObject[] powerUps; public float porcentagem; private player scriptPlayer; public GameObject explosao; private gameManager gManagerScript; public Image reprovadoImage; public AudioClip somBloco; public AudioClip somPlayer; // Start is called before the first frame update void Start() { gManagerScript = GameObject.Find("GameManager").GetComponent<gameManager>(); scriptPlayer = GameObject.Find("Player").GetComponent<player>(); rb = GetComponent<Rigidbody2D>(); //rb.velocity = new Vector2(Random.Range(-2, 2), velBola); } void Update() { if (Input.GetKeyDown(KeyCode.Space) && !comecou) { rb.velocity = new Vector2(Random.Range(-2f, 2f), velBola); comecou = true; } if (!comecou) { transform.position = new Vector2(jogador.position.x, transform.position.y); } } void FixedUpdate() { if (comecou) { if (rb.velocity.y < 2 && rb.velocity.y > -2) { rb.gravityScale = 3; } else { rb.gravityScale = 0; } } } float colisaoBolinha(Vector2 posicaoBolinha, Vector2 posicaoJogador, float larguraJogador) { return (posicaoBolinha.x - posicaoJogador.x) / larguraJogador; } void OnCollisionEnter2D(Collision2D outro) { if (outro.gameObject.tag == "bloco_verde" || outro.gameObject.tag == "bloco_vermelho" || outro.gameObject.tag == "bloco_azul" || outro.gameObject.tag == "bloco_amarelo") { if (scriptPlayer.ativaExplosao) Instantiate(explosao, outro.transform.position, Quaternion.identity); //Instantiate() if (Random.Range(0f, 1f) <= porcentagem) { Instantiate(powerUps[Random.Range(0, powerUps.Length)], outro.gameObject.transform.position, Quaternion.identity); } AudioSource.PlayClipAtPoint(somBloco, transform.position); Destroy(outro.gameObject); } if (outro.gameObject.tag == "Player") { float resultadoCalculo = colisaoBolinha(transform.position, outro.transform.position, ((BoxCollider2D)outro.collider).size.x); Vector2 novaDirecao = new Vector2(resultadoCalculo, 1).normalized; rb.velocity = novaDirecao * velBola; AudioSource.PlayClipAtPoint(somPlayer, transform.position); } if (outro.gameObject.tag == "colisorBaixo") { if (gManagerScript.vidas < 3) { gManagerScript.vidas += 1; transform.position = new Vector2(jogador.position.x, jogador.position.y + posicaoBolinha); comecou = false; rb.velocity = Vector2.zero; //Adc gManagerScript.pontuacao = gManagerScript.pontuacao * 0.7; } else { reprovadoImage.enabled = true; gManagerScript.vidas += 1; Destroy(gameObject); if (Input.GetKey(KeyCode.R)) { Application.LoadLevel("Cena1"); } } } } }
22,979
https://github.com/dumbNickname/platform-frontend/blob/master/app/modules/web3/__tests__/sagas.spec.ts
Github Open Source
Open Source
MIT
null
platform-frontend
dumbNickname
TypeScript
Code
121
444
import { expect } from "chai"; import { delay } from "redux-saga"; import { call, put } from "redux-saga/effects"; import { createMock } from "../../../../test/testUtils"; import { LIGHT_WALLET_PASSWORD_CACHE_TIME } from "../../../config/constants"; import { TGlobalDependencies } from "../../../di/setupBindings"; import { noopLogger } from "../../../lib/dependencies/Logger"; import { Web3Manager } from "../../../lib/web3/Web3Manager"; import { actions } from "../../actions"; import { autoLockLightWallet } from "../sagas"; describe("Web3 sagas", () => { describe("light wallet password", () => { it("should reset password after timeout", () => { const personalWalletMock = { password: "some dummy pass", } as any; const web3ManagerMock = createMock(Web3Manager, { personalWallet: personalWalletMock, }); const saga = autoLockLightWallet(({ web3Manager: web3ManagerMock, logger: noopLogger, } as any) as TGlobalDependencies); expect(saga.next().value).to.be.deep.eq(call(delay, LIGHT_WALLET_PASSWORD_CACHE_TIME)); expect(saga.next().value).to.be.deep.eq(put(actions.web3.walletLocked())); expect(saga.next().value).to.be.deep.eq(put(actions.web3.clearSeedFromState())); expect(saga.next().value).to.be.undefined; expect(personalWalletMock.password).to.be.undefined; }); }); });
23,734
https://github.com/Coke67/coke.js/blob/master/src/functions/Funcs/info/roleName.js
Github Open Source
Open Source
Apache-2.0
2,021
coke.js
Coke67
JavaScript
Code
59
231
const {Role} = require('../../../utils/helpers/functions.js'); module.exports = async d => { const data = d.util.openFunc(d); if (data.err) return d.error(data.err); const [roleId, guildId = d.guild?.id] = data.inside.splits; const guild = await d.util.getGuild(d, guildId); if (!guild) return d.aoiError.fnError(d, 'guild', {inside: data.inside}); const role = await guild.roles.fetch(roleId).catch(err => { d.aoiError.fnError(d, 'role', {inside: data.inside}); }); data.result = role.name.deleteBrackets(); return { code: d.util.setCode(data) } }
24,718
https://github.com/fond-of/spryker-product-list-conditional-availability-page-search/blob/master/tests/FondOfSpryker/Client/ProductListConditionalAvailabilityPageSearch/ProductListConditionalAvailabilityPageSearchFactoryTest.php
Github Open Source
Open Source
MIT
null
spryker-product-list-conditional-availability-page-search
fond-of
PHP
Code
84
625
<?php namespace FondOfSpryker\Client\ProductListConditionalAvailabilityPageSearch; use Codeception\Test\Unit; use FondOfSpryker\Client\ProductListConditionalAvailabilityPageSearch\Dependency\Client\ProductListConditionalAvailabilityPageSearchToCustomerClientInterface; use Spryker\Client\Kernel\Container; class ProductListConditionalAvailabilityPageSearchFactoryTest extends Unit { /** * @var \FondOfSpryker\Client\ProductListConditionalAvailabilityPageSearch\ProductListConditionalAvailabilityPageSearchFactory */ protected $productListConditionalAvailabilityPageSearchFactory; /** * @var \PHPUnit\Framework\MockObject\MockObject|\Spryker\Client\Kernel\Container */ protected $containerMock; /** * @var \PHPUnit\Framework\MockObject\MockObject|\FondOfSpryker\Client\ProductListConditionalAvailabilityPageSearch\Dependency\Client\ProductListConditionalAvailabilityPageSearchToCustomerClientInterface */ protected $productListConditionalAvailabilityPageSearchToCustomerClientInterfaceMock; /** * @return void */ protected function _before(): void { $this->containerMock = $this->getMockBuilder(Container::class) ->disableOriginalConstructor() ->getMock(); $this->productListConditionalAvailabilityPageSearchToCustomerClientInterfaceMock = $this->getMockBuilder(ProductListConditionalAvailabilityPageSearchToCustomerClientInterface::class) ->disableOriginalConstructor() ->getMock(); $this->productListConditionalAvailabilityPageSearchFactory = new ProductListConditionalAvailabilityPageSearchFactory(); $this->productListConditionalAvailabilityPageSearchFactory->setContainer($this->containerMock); } /** * @return void */ public function testGetCustomerClient(): void { $this->containerMock->expects($this->atLeastOnce()) ->method('has') ->willReturn(true); $this->containerMock->expects($this->atLeastOnce()) ->method('get') ->with(ProductListConditionalAvailabilityPageSearchDependencyProvider::CLIENT_CUSTOMER) ->willReturn($this->productListConditionalAvailabilityPageSearchToCustomerClientInterfaceMock); $this->assertInstanceOf( ProductListConditionalAvailabilityPageSearchToCustomerClientInterface::class, $this->productListConditionalAvailabilityPageSearchFactory->getCustomerClient() ); } }
39,958
https://github.com/monadli/ftl/blob/master/src/ts/ftl-builder.ts
Github Open Source
Open Source
MIT
null
ftl
monadli
TypeScript
Code
3,206
9,512
import fs from 'fs' import fpath from 'path' import * as ftl from './ftl-core' import * as ftl_parser from './ftl-parser' const OPERATOR_SYMBOLS = '!%&*+\-./:;<=>?^|×÷∏∑∕²³⁴√∛∜∗∙∧∨∩∪∼≤≥⊂⊃¬∀' type BuildInfo = ftl_parser.BuildInfo var libPath: string var runPath: string var optimization = false var currentBuildModules = new Set<string>() Error.stackTraceLimit = Infinity export function setRunPath(path: string) { runPath = path } export function setLibPath(path: string) { libPath = path } export function setOptimization(val: boolean) { optimization = val } /** * Error for module not found. */ export class ModuleNotFoundError extends Error { moduleName: string constructor(moduleName: string) { super() this.moduleName = moduleName this.message = 'Module not exist!' } } function buildingFor(context:string) { let stack = new Error().stack return stack?.includes(`at build${context} (`) } /** * Wraps an expression into NamedExprFn if name is not a selector. * * @param name expression name * @param expr expression * @returns NamedExprFn or expr itself */ function createNamedExpr(name: string, expr: ftl.Fn): ftl.NamedExprFn | ftl.Fn { if (ftl.RefFn.isInputSelector(name)) { if (expr instanceof ftl.RefFn) return expr throw new FtlBuildError(`${name} is researved key word and cannot be used as name.`) } return new ftl.NamedExprFn(name, expr) } export function buildModuleWithContent(path:string, content:string) { let module = new ftl.Module(path) return buildToModule(content, module) } export function buildModule(path: string, ftlFile: string) { if (currentBuildModules.has(ftlFile)) throw new FtlBuildError(`cyclic referencing to ${ftlFile}`) let content = fs.readFileSync(`${path}/${ftlFile}.ftl`, 'utf-8') currentBuildModules.add(ftlFile) return buildModuleWithContent(ftlFile, content) } export function buildToModule(ftl_content:string, module:ftl.Module) { let parsed = ftl_parser.peg$parse(ftl_content) if (!parsed) return undefined buildElement(parsed, module) return module } function buildElement(buildInfo:any, module:any, input:any=null):any { if (buildInfo instanceof ftl_parser.BuildInfo) { let builder = getBuilder(buildInfo.name) return builder(buildInfo.details, module, input) } else if (Array.isArray(buildInfo) && buildInfo.some(e => e instanceof ftl_parser.BuildInfo)) { return buildInfo.map(e => buildElement(e, module, input)) } else return buildInfo } function getBuilder(name:string) { let builder = eval(`build${name}`) //buildElements[name] if (!builder) throw new Error(`Builder for ${name} not found!`) return builder } function buildDeclarations(details:any, module:any) { return details.declarations.map((declaration:BuildInfo) => { return buildElement(declaration, module) }) } function buildImportDeclaration(details:any, module:any) { buildElement(details.items, module) } function buildImportList(details:any, module:any) { buildElement(details.list, module, details) } function buildImportMultiItems(details:any, module:any, prev:any) { details.items.map((item:any) => { if (!item.details.path) item.details.path = details.path || (prev && prev.path) buildElement(item, module) }) } function buildImportSingleItem(details: any, module: any) { function getModulePath() { let last_slash = module._name.lastIndexOf('/') let mod_path = last_slash == -1 ? '' : module._name.substring(0, last_slash + 1) return mod_path == './' ? '' : mod_path } let name_elm = buildElement(details.name, module) var name:string|null = name_elm.name || name_elm let path: string = details.path if (path.endsWith('.')) { path = path.substring(0, path.length - 1) // wildcard, not * operator if (name == '*') { name = null } } let asName = buildElement(details.item, module)?.name if (path.endsWith('/')) { path += name name = null } // relative import if (path.startsWith('.')) { let mod_path = getModulePath() path = getModulePath() + path path = `./${fpath.normalize(path).replace(/\\/g, '/') }` } // absolute import else { path = `lib/${path}` } var mod = ftl.getModule(path) if (!mod) { try { mod = buildModule(runPath, path) } catch (e) { currentBuildModules.delete(path) if (!path.startsWith('./')) { mod = buildModule(libPath, path) } else { throw e } } ftl.addModule(mod as ftl.Module) } // import all if (!name) { if (asName != null) throw new Error("Importing * (all) can not have alias name!"); (mod as ftl.Module).functionNames.forEach((n: string) => { module.addImport(n, mod!.getExportableFn(n)) }) } else module.addImport(asName || name, (mod as ftl.Module).getExportableFn(name)) } function buildExecutable(details:any, module:any) { let executable = new ftl.ExecutableFn(buildElement(details.executable, module)) module.addExecutable(executable) return executable } function buildMapExpression(details:any, module:any, input?:any) { let prev:any = input let map_expr = details.elements.map((element:BuildInfo) => { return prev = buildElement(element, module, prev) }) return map_expr.length == 1 ? map_expr[0] : new ftl.PipeFn(... map_expr) } function buildMapOperand(details:any, module:any, prev:any=null) { var built var sideffect var raise = false try { sideffect = buildElement(details.annotations, module, prev) built = buildElement(details.expr, module, prev) } catch (e) { if (e instanceof N_aryOperatorBuildError && (e.op == '.' || e.op == '. .')) { return new ftl.PropertyAccessorFn(e.operands[0], ... e.operands.slice(1).map(o => o.name)) } // raise operator else if (e instanceof PrefixOperatorNotFoundError && e.op == '. ') { raise = true built = e.operand } else { throw e } } let sideffects = sideffect.map((d:ftl.Fn) => { if (d instanceof ftl.RefFn) { let f = module.getAvailableFn(d.name) if (!f) { throw new FtlBuildError(`Sideffect function ${d.name} not found!`) } return new ftl.SideffectFn(d.name, f, new ftl.TupleFn()) } else if (d instanceof ftl.CallExprFn) { if (d.params.length > 1) { throw new Error('Curry not supported in sideffect!') } if (!(d.f instanceof ftl.FunctionBaseFn)) { throw new FtlBuildError('Sideffect has to be a function!') } return new ftl.SideffectFn(d.name, d.f, d.params[0] as ftl.TupleFn) } else { throw new Error('Not supported sideffect definition!') } }) if (built instanceof ftl.RefFn) { let name = built.name if (!name.startsWith('_') && (!(prev instanceof ftl.TupleFn) || !prev.hasName(name)) && !buildingFor('FunctionSignature')) { built = module.getAvailableFn(name) || built } } if (raise) { built = new ftl.RaiseFunctionForArrayFn(built) } if (sideffect.length > 0) { let sideffects = sideffect.map((d:ftl.Fn) => { if (d instanceof ftl.RefFn) { let f = module.getAvailableFn(d.name) if (!f) { throw new FtlBuildError(`Sideffect function ${d.name} not found!`) } return new ftl.SideffectFn(d.name, f, new ftl.TupleFn()) } else if (d instanceof ftl.CallExprFn) { if (d.params.length > 1) { throw new Error('Curry not supported in sideffect!') } if (!(d.f instanceof ftl.FunctionBaseFn)) { throw new FtlBuildError('Sideffect has to be a function!') } return new ftl.SideffectFn(d.name, d.f, d.params[0] as ftl.TupleFn) } else { throw new Error('Not supported sideffect definition!') } }) return new ftl.SideffectedFn(built, sideffects) } else { return built } } function buildOperatorExpression(details:any, module:any, input?:any) { try { return buildElement(details.unit, module, input) } catch (e) { // array initializer if (e instanceof N_aryOperatorBuildError && (e.op == ':' || e.op == ': :')) { let start = e.operands[0] if (start instanceof ftl.RefFn) { throw new FtlBuildError(`It seems a sideffect is in front of tuple element name '${start.name}'`) } let interval = e.op == ':' ? new ftl.ConstFn(1) : e.operands[1] let end = e.op == ':' ? e.operands[1] : e.operands[2] if (end == undefined) { end = new ftl.ConstFn(-1) } return new ftl.ArrayInitializerWithRangeFn(start, end, interval) } // array selector else if (e instanceof PostfixOperatorBuildError && e.op == ' :') { let start = e.operand let interval = new ftl.ConstFn(1) let end = new ftl.ConstFn(-1) return new ftl.ArrayInitializerWithRangeFn(start, end, interval) } // tuple element selector else if (e instanceof N_aryOperatorBuildError && (e.op == '.' || e.op == '. .')) { return new ftl.PropertyAccessorFn(e.operands[0], ... e.operands.slice(1).map(o => o.name)) } else { throw e } } } /** * Builds n-ary operator expression. * * During the build, when two operators are next to each other, it will make sure * to parse them correctly. * * For example: * 1 + 2-- - 3 * * It will first treat it as * 1 + 2 -- (-3) * * However once it finds that prefix operator '-' does not exist, it will try * 1 + (2--) - 3 * * This allows writing simpler operator expressions without precedence wrapping with prantheses. * @param details * @param module * @param input */ function buildN_aryOperatorExpression(details:any, module:ftl.Module, input:any=null) { let operands = [] for (let i = 0; i < details.operands.length; i++) { let operand = details.operands[i] try { let operand_build = buildElement(operand, module, input) if (operand_build instanceof ftl.RefFn && module && (!input || (input instanceof ftl.NamedExprFn && input.name != operand_build.name) || (input instanceof ftl.TupleFn && !input.hasName(operand_build.name))) ) { let f = module.getAvailableFn(operand_build.name) if (f) { operands.push(f) continue } } operands.push(operand_build) } catch (e) { if (!(e instanceof PrefixOperatorNotFoundError)) { if (e instanceof PostfixOperatorBuildError) { operands.push(e.operand) throw new N_aryOperatorBuildError(e.message, `${details.ops.join(' ')}${e.op}`, operands) } } // try postfix operator let post_op = details.ops[i - 1] if (!module.getAvailableFn(` ${post_op}`)) { throw e } operands.pop() operands.push(buildElement(new ftl_parser.BuildInfo( "PostfixOperatorExpression", { operator: post_op, expr: details.operands[i - 1] }), module, input) ) operands.push(buildElement(operand.details.expr, module, input)) details.ops[i - 1] = (e as PrefixOperatorNotFoundError).op.trim() } } return ( // This is used to parse operators and operands recursively. // It is called from index = length of operators down to 1. function parse_operators(module:ftl.Module, inputFn:any, ops:string[], operands:any[], index:number, full:boolean, extra:any): any { // operand at index 1 is for operator at var op = index == 1 ? ops[0] : ops.slice(0, index).join(' ') var f = module.getAvailableFn(op) var raise = false // no corresponding function found for single op if (!f && index == 1 && op.length > 1 && op.startsWith('.')) { op = op.substring(1) raise = true f = module.getAvailableFn(op) } if (!f) { if (index == 1) { throw new N_aryOperatorBuildError(`N-ary operator ${ops} not found!`, op, operands) } index-- try { var reduced = parse_operators(module, inputFn, ops, operands, index, false, extra) if (extra.current_index == extra.stop_index) return reduced ops = ops.slice(index, ops.length) operands = [reduced].concat(operands.slice(index + 1, operands.length)) return parse_operators(module, inputFn, ops, operands, ops.length, true, extra) } catch(e) { throw new N_aryOperatorBuildError(`N-ary operator ${ops} not found!`, op, operands) } } for (var i = 0; i < f.params.size; i++) { var fn = f.params.getFnAt(i) if (fn instanceof ftl.NamedExprFn && fn.wrapped instanceof ftl.FunctionInterfaceFn) { //fnode.wrapped.isNative = f instanceof ftl.NativeFunctionFn // wrap functional interface and input function with ExprRefFn. // This can be done only here with inputFn available operands[i] = new ftl.ExprRefFn(fn.wrapped, operands[i]) } } extra.current_index += index var operands_tuple = new ftl.TupleFn(... operands.slice(0, f.params.size)) return new ftl.PipeFn(operands_tuple, raise ? new ftl.RaiseBinaryOperatorForArrayFn(f) : f) } )(module, input, details.ops, operands, details.ops.length, true, {current_index:0, stop_index:details.ops.length}) } function buildPrefixOperatorDeclaration(details:any, module:any) { return { operator: details.operator, operand: buildElement(details.operand, module) } } function buildInfixOperatorDeclaration(details:any, module:any) { let operators = details.operators.join(' ') let operands = [] for (let i = 0; i < details.operands.length; i++) { let operand = buildElement(details.operands[i], module) if (operand instanceof ftl.FunctionInterfaceFn) operand.seq = i operands.push(operand) } return { operators: operators, operands: operands } } function buildOperandFunctionDeclaration(details:any, module:any, prevElm:any=null):ftl.Fn { let name = buildElement(details.name, module).name if (name == '$') { throw new Error('No name provided!') } let is_tail = false if (name.endsWith('$')) { is_tail = true name = name.substr(0, name.length - 1) } let params = buildElement(details.params, module, prevElm) // functional interface // its sequence is detemined in buildInfixOperatorDeclaration(...) var fn = new ftl.FunctionInterfaceFn(name, params) if (is_tail) fn.setAsTail() return fn } function buildFunctionSignature(details:any, module:any) { let name = buildElement(details.name, module).name let params = build_function_parameters(buildElement(details.params, module)) return {name: name, params: params} } function buildFunctionDeclaration(details:any, module:any) { let signature = buildElement(details.signature, module, null) let f_name let params:ftl.TupleFn // prefix operator or infix operator if (signature.operator || signature.operators) { params = signature.operand && build_function_parameters(new ftl.TupleFn(signature.operand)) || build_function_parameters(new ftl.TupleFn(... signature.operands)) f_name = signature.postfix ? ` ${signature.operator}` : signature.operators || (params.size == 1 ? `${signature.operator} ` : signature.operator) } else { f_name = signature.name params = signature.params } let body = details.body let param_list = params.map((p:any) => p.name) let fn if (body.script) { try { let script = eval("(function(" + param_list.join(',') + ")" + body.script + ")") fn = new ftl.NativeFunctionFn(f_name, params, script) } catch (e:any) { if (e.message.startsWith('Unexpected token')) { throw new Error(e.message + '. Most likely a javascript reserved key word is used as an identifier!') } else throw e } } else { module.addFn(new ftl.FunctionHolder(f_name, params)) let arrow = body.map((arrow:any) => buildElement(arrow, module, params)) // TODO arrow extract from pipe fn fn = new ftl.FunctionFn(f_name, params, new ftl.PipeFn(params, ... arrow)) } module.addFn(fn) return fn } function buildPrefixOperatorExpression(details:any, module:any) { let op = `${details.operator} ` let f = module.getAvailableFn(op) let expr = buildElement(details.expr, module) if (!f) { throw new PrefixOperatorNotFoundError(`Prefix operator "${op}" not found!`, op, expr) } if (expr instanceof ftl.TupleFn && expr.size == 1) { return new ftl.PipeFn(expr.first, f) } else { return new ftl.PipeFn(expr, f) } } function buildPostfixOperatorExpression(details:any, module:any) { let operator = ` ${details.operator}` let f = module.getAvailableFn(operator) let expr = buildElement(details.expr, module) if (!f) { throw new PostfixOperatorBuildError(`Postfix operator "${operator}" not found!`, operator, expr) } return new ftl.PipeFn(expr, f) } function buildPostfixOperatorDeclaration(details:any, module:any, prev:any) { let operand = buildElement(details.operand, module) return { operator: details.operator, operand: buildElement(details.operand, module), postfix: true } } function buildCallExpression(details:any, module:any, prev:any) { let name = buildElement(details.name, module).name if (!Array.isArray(details.params)) { details.params = [details.params] } let call_args: ftl.TupleFn[] = details.params.map((p: any) => buildElement(p, module, prev)) // lambda calculus if (name == '$') { if (call_args.length == 1) { return build_function_parameters(call_args[0]) } else { throw new FtlBuildError('Lambda calculus not supporting curry yet') } } let f:ftl.FunctionBaseFn|ftl.RefFn = module.getAvailableFn(name) if (!f) { f = prev && prev.hasName(name) && new ftl.RefFn(name, module) if (!f) { if (!buildingFor('FunctionDeclaration')) { throw new Error(`${name} not found!`) } return new ftl.FunctionInterfaceFn(name, call_args) } } if (f instanceof ftl.FunctionBaseFn && f.params.size == 0) { if (call_args.length > 1) { throw new FtlBuildError(`${name} has no parameters and more than one calls is found!`) } if (call_args[0].size > 0) { throw new FtlBuildError(`${name} has no parameters and ${call_args[0].size} arguments are provided!`) } return new ftl.CallExprFn(name, f, [new ftl.TupleFn()]) } let new_params:any[] if (f instanceof ftl.FunctionBaseFn) { new_params = Array.from(f.params.fns) var positional_args = new Set<string>() var named_args = new Set<string>() var unproced_named_args = new Map<string, any>() if (call_args[0].size == 0 && (f.params.first! as any).wrapped instanceof ftl.TupleSelectorFn) { throw new FtlBuildError(`At least 1 argument is needed to call ${f.name}`) } for (var n = 0; n < call_args.length; n++) { if (n > 0 && call_args[n].size == 0) { throw new Error('Currying with no arguments!') } let left_params = new_params.filter((p:ftl.Fn) => p instanceof ftl.NamedExprFn && p.wrapped instanceof ftl.TupleSelectorFn) if (left_params.length == 0) { throw new Error('Currying with excessive arguments!') } let index = 0 for (var i = 0; i < new_params.length; i++) { if (!(new_params[i] instanceof ftl.NamedExprFn)) continue if (index == call_args[n].size) { break } let param = new_params[i] let arg = call_args[n].getFnAt(index) // named arg // excluding simple RefFn wrapped as NamedExprFn which share the smae name if (arg instanceof ftl.NamedExprFn && (!(arg.wrapped instanceof ftl.RefFn) || arg.wrapped.name != arg.name)) { named_args.add(param.name) if (arg.name == param.name) { new_params[i] = arg } else if (positional_args.has(arg.name)) { throw new FtlBuildError(`${name} is already taken as positional argument!`) } else { unproced_named_args.set(arg.name, arg) let existing_named = unproced_named_args.get(param.name) if (existing_named) { new_params[i] = existing_named unproced_named_args.delete(param.name) } } } // non-named /positional arg else { if (named_args.size > 0) { throw new FtlBuildError(`positional argument after named argument!`) } positional_args.add(new_params[i].name) new_params[i] = arg } index++ } } if (unproced_named_args.size > 0) { for (var i = 0; i < new_params.length; i++) { let param = new_params[i] if (param instanceof ftl.NamedExprFn && param.wrapped instanceof ftl.TupleSelectorFn) { let existing_named = unproced_named_args.get(param.name) if (existing_named) { new_params[i] = existing_named unproced_named_args.delete(param.name) if (unproced_named_args.size == 0) break } } } if (unproced_named_args.size > 0) throw new FtlBuildError(`Some names do not match parameter names`) } } // recursive function call with function not resolved yet // assume the calling is correct // TODO passing parameters to check else if (f instanceof ftl.FunctionHolder) { new_params = call_args } else { // function is passing from prev let f_def = prev.getNamedFn(name).wrapped if (f_def instanceof ftl.FunctionInterfaceFn && call_args.length < f_def.paramSize) { throw new Error(`Reference for ${name} is not a fucntional interface!`) } if (call_args.length < f_def.params.length) { throw new Error(`Parameter counts for ${name} is less than expected!`) } new_params = call_args } // re-sequence unresolved parameters let newSeq = 0 for (var i = 0; i < new_params.length; i++) { let param = new_params[i] if (param instanceof ftl.NamedExprFn && param.wrapped instanceof ftl.TupleSelectorFn) { if (param.wrapped instanceof ftl.SeqSelectorOrDefault) { new_params[i] = createNamedExpr(param.name, new ftl.SeqSelectorOrDefault(newSeq++, new ftl.ConstFn(param.wrapped.defaultValue))) } else { new_params[i] = createNamedExpr(param.name, new ftl.TupleSelectorFn(newSeq++)) } } } return new ftl.CallExprFn(name, f, [new ftl.TupleFn(... new_params)]) } function buildFunctionCurrying(details:any, module:any, prev?:any) { return buildCallExpression({ name: details.call.details.name, params: [details.call.details.params, ... details.extra_params] }, module, prev) } function buildArrayLiteral(details:any, module:any) { let elms = buildElement(details.list, module) let consts = elms.filter((e:any) => { e instanceof ftl.ConstFn }) if (consts.length == elms.length) { var res:any[] = [] for (let i = 0; i < elms.length; i++) { if (elms[i] instanceof ftl.ConstFn) { var val = elms[i].apply() if (Array.isArray(val)) { res.splice(res.length, 0, ... val) } else { res.push(val) } } else { } } return new ftl.ConstFn(res) } else { return new ftl.ArrayInitializerFn(... elms) } } function buildListLiteral(details:any, module:any) { return !details ? [] : details.list.map((elm:any) => { return buildElement(elm, module) }) } function buildStringLiteral(details:any, module:any) { return new ftl.ConstFn(details.value) } function buildNumericLiteral(details:any, module:any) { return new ftl.ConstFn(details.value) } function buildTrueToken(details:any, module:any) { return new ftl.ConstFn(details.value) } function buildFalseToken(details:any, module:any) { return new ftl.ConstFn(details.value) } function buildNullToken(details:any, module:any) { return new ftl.ConstFn(null) } function buildArrayElementSelector(details: any, module: any) { let name = buildElement(details.id, module).name let index = typeof details.index == 'string' ? parseInt(details.index) : buildElement(details.index, module) if (index instanceof ftl.ArrayInitializerFn) { // TODO allow ArrayElementSelectorFn takes multiple values if (index.size != 1) { throw new Error('ArrayElementSelectorFn not supporting multiple values yet!') } let index_info = index.first if (index_info instanceof ftl.ArrayInitializerWithRangeFn) { return new ftl.ArrayRangeSelectorFn(name, index_info.startValue.apply(), index_info.endValue.apply(), index_info.interval.apply()) } return new ftl.ArrayElementSelectorFn(name, index_info) } return new ftl.ArrayElementSelectorFn(name, index) } function buildTuple(details:any, module:any, prev?:any) { let all_elms = details.elements.map((element:BuildInfo) => { return buildElement(element, module, prev) }) let all_names = new Set<string>() all_elms.forEach((element:any) => { if (element instanceof ftl.NamedExprFn) { let name = element.name if (all_names.has(name)) { throw new FtlBuildError(`${name} already exists!`) } all_names.add(element.name) } }) for (var i = 0; i < all_elms.length; i++) { let elm = all_elms[i] if (elm instanceof ftl.RefFn && !all_names.has(elm.name) || elm instanceof ftl.SideffectedFn && elm.wrapped instanceof ftl.RefFn && !all_names.has(elm.wrapped.name)) { all_elms[i] = createNamedExpr(elm.name!, elm) } else if (elm instanceof ftl.FunctionInterfaceFn) { elm.seq = i } } return new ftl.TupleFn(... all_elms) } function buildTupleElement(details:any, module:any, prev?:any) { let name = buildElement(details.name, module) let expr = buildElement(details.expr, module, prev) return name && createNamedExpr(name.name, expr) || expr } function buildIdentifier(details:any, module:any) { return new ftl.RefFn(details.name, module) } function buildTupleCurrying(details:any, module:any, prev?:any) { let expr = buildElement(details.expr, module, prev) let params_list = buildElement(details.list, module) params_list.forEach((params:ftl.TupleFn) => { if (params.size == 0) { throw new FtlBuildError('At least one argument for expression currying has to be provided!') } if (params.filter(param => param instanceof ftl.NamedExprFn).length != params.size) { throw new FtlBuildError('All arguments for expression currying have to be named!') } }) let ret = expr if (optimization) { params_list.forEach((params: ftl.TupleFn) => { ret = ret.apply(params.apply(null)) if (ret instanceof ftl.Tuple) { ret = ret.toTupleFn() } }) } else { ret = new ftl.CurryExprFn(expr, params_list) } return ret instanceof ftl.Fn ? ret : new ftl.ConstFn(ret) } // builds function parameter function build_function_parameters(params:ftl.TupleFn) { let fns = params.map((p:any, i:number) => { if (p instanceof ftl.RefFn) { return createNamedExpr(p.name, new ftl.TupleSelectorFn(i)) } else if (p instanceof ftl.NamedExprFn) { return createNamedExpr(p.name, p.wrapped instanceof ftl.RefFn ? new ftl.TupleSelectorFn(i) : new ftl.SeqSelectorOrDefault(i, p.wrapped)) } else if (p instanceof ftl.FunctionInterfaceFn) return createNamedExpr(p.name, p) else return p }) var has_default = false fns.forEach((p:ftl.NamedExprFn, i:number) => { if (p.wrapped instanceof ftl.SeqSelectorOrDefault) { has_default = true } else if (has_default) { throw new FtlBuildError(`Parameter ${p.name} is after a parameter with default value!`) } }) return new ftl.TupleFn(... fns) } function validate_tuple_elements(elms:any[]) { } //function addbuilder<D extends FtlBuilder>(builder:new(props?:any) => D) { // buildElements[builder.name] = builder //} // this is for building function / operator parameters var dummy_param_tuple = new ftl.TupleFn() // The following functions are used for parsing function join(value:any) { return Array.isArray(value) ? value.join("") : value } function optionalList(value:any) { if (value == null) throw new Error('catching null') return value || [] } class FtlBuildError extends Error { constructor(message:string) { super(message) } } class PrefixOperatorNotFoundError extends FtlBuildError { op:string operand:any constructor(message:string, op:string, operand:any) { super(message) this.op = op this.operand = operand } } class N_aryOperatorBuildError extends FtlBuildError { op:string operands:any[] constructor(message:string, op:string, operands:any[]) { super(message) this.op = op this.operands = operands } } class PostfixOperatorBuildError extends FtlBuildError { op:string operand:any constructor(message:string, op:string, operand:any) { super(message) this.op = op this.operand = operand } }
23,101
https://github.com/hectorsegarra/yii2-advanced-start/blob/master/modules/conversacion/views/frontend/default/index.php
Github Open Source
Open Source
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference, MIT
2,023
yii2-advanced-start
hectorsegarra
PHP
Code
41
160
<?php use yii\helpers\Html; use modules\conversacion\Conversacion; $this->title = Conversacion::translate('module', 'Conversacion'); $this->params['breadcrumbs'][] = $this->title; ?> <div class="conversacion-frontend-default-index"> <h1><?= Html::decode($this->title) ?></h1> <p> This is the module conversacion frontend page. You may modify the following file to customize its content: </p> <code><?= __FILE__ ?></code> </div>
41,597
https://github.com/enterstudio/generator-jhipster/blob/master/generators/rancher-compose/files.js
Github Open Source
Open Source
Apache-2.0
2,019
generator-jhipster
enterstudio
JavaScript
Code
39
218
module.exports = { writeFiles }; function writeFiles() { return { writeRancherCompose() { this.template('_rancher-compose.yml', 'rancher-compose.yml'); }, writeDockerCompose() { this.template('_docker-compose.yml', 'docker-compose.yml'); }, writeRegistrySidekickFiles() { if (this.serviceDiscoveryType === 'eureka' || this.serviceDiscoveryType === 'consul') { this.copy('registry-config-sidekick/Dockerfile', 'registry-config-sidekick/Dockerfile'); this.template('registry-config-sidekick/_application.yml', 'registry-config-sidekick/application.yml'); } } }; }
34,315
https://github.com/Pfuster12/code-link/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,020
code-link
Pfuster12
Ignore List
Code
4
19
node_modules .env main.js .vscode
8,246
https://github.com/ProdexOne/agro-rent-backend/blob/master/src/routes/rent.route.js
Github Open Source
Open Source
MIT
null
agro-rent-backend
ProdexOne
JavaScript
Code
12
59
const rentController = require("../controllers/rent.controller"); const router = require("express").Router(); router.route("/").get(rentController.getRents).post(rentController.createRent); module.exports = router;
23,041
https://github.com/MIPT-ILab/mipt-mips-old-branches/blob/master/ysamarin_task_1/func_sim/func_memory/func_memory.cpp
Github Open Source
Open Source
MIT
2,018
mipt-mips-old-branches
MIPT-ILab
C++
Code
247
732
/** * func_memory.cpp - the module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // Generic C #include <cassert> #include <cstring> #include <cerrno> #include <unistd.h> #include <cstdlib> #include <cstdio> // Generic C++ #include <string> #include <sstream> #include <map> // uArchSim modules #include <func_memory.h> using namespace std; typedef map<uint64, ElfSection& >::const_iterator my_iter_const; typedef map<uint64, ElfSection& >::iterator my_iter; FuncMemory::FuncMemory( const char* executable_file_name, const char* const elf_sections_names[], short num_of_elf_sections) { assert( executable_file_name); func_memory_name = executable_file_name; //remember the name of executable file for ( short i = 0; i < num_of_elf_sections; ++i) { assert( elf_sections_names[i]); ElfSection *tmp = new ElfSection( executable_file_name, elf_sections_names[i]); pair<my_iter, bool> insert_ret = sect_stor.insert ( pair<uint64, ElfSection& >( tmp->startAddr(), *tmp)); if ( insert_ret.second == false) { perror( "twice written sections in the list of names!"); exit( EXIT_FAILURE); } } } FuncMemory::~FuncMemory() { for ( my_iter it = sect_stor.begin(); it != sect_stor.end(); ++it) { delete &( it->second); } } uint64 FuncMemory::read( uint64 addr, short num_of_bytes) const { my_iter_const it = sect_stor.upper_bound( addr); if ( it != sect_stor.begin()) { return (--it)->second.read( addr, num_of_bytes); //read from elf_parser check addr itself } perror( "right section isn't found!"); exit( EXIT_FAILURE); } string FuncMemory::dump( string indent) const { ostringstream oss; oss << indent << endl << "Dump FuncMemory of file\t\"" << this->func_memory_name << "\"" << endl; for( my_iter_const it = sect_stor.begin(); it != sect_stor.end(); it++) { oss << indent << it->second.dump( indent) << endl; } return oss.str(); }
18,024
https://github.com/johnvonlzf/simulacra/blob/master/src/simulacra/utils/arrays.py
Github Open Source
Open Source
MIT
2,018
simulacra
johnvonlzf
Python
Code
192
515
import collections import logging from typing import Optional, Union, NamedTuple, Callable, Iterable, Tuple import numpy as np logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) KeyValueArrays = collections.namedtuple('KeyValueArrays', ('key_array', 'value_array')) def dict_to_arrays(dct: dict, key: Optional[Callable] = None) -> KeyValueArrays: """ Return the keys and values of a dictionary as two numpy arrays, in key-sorted order. Parameters ---------- dct The dictionary to array-ify. key An optional function to use as the ``key`` for ``sorted``. It is passed each element of ``dct.items()``. Returns ------- """ key_list = [] val_list = [] for key, val in sorted(dct.items(), key = key): key_list.append(key) val_list.append(val) return KeyValueArrays(np.array(key_list), np.array(val_list)) NearestEntry = collections.namedtuple('NearestEntry', ('index', 'value', 'target')) def find_nearest_entry(array: np.ndarray, target: Union[float, int]) -> NearestEntry: """ Returns the ``(index, value, target)`` of the `array` entry closest to the given `target`. Parameters ---------- array : :class:`numpy.ndarray` The array to for `target` in. target The value to search for in `array`. Returns ------- :class:`tuple` A tuple containing the index of the nearest value to the target, that value, and the original target value. """ array = np.array(array) # turn the array into a numpy array index = np.argmin(np.abs(array - target)) value = array[index] return NearestEntry(index, value, target)
19,690
https://github.com/codebenj/leado/blob/master/resources/js/partials/NotificationWidget.vue
Github Open Source
Open Source
MIT
2,021
leado
codebenj
Vue
Code
136
601
<template> <div class="notification-dropdown dropdown-menu dropdown-menu-right"> <div class="arrow_box_right"> <div class="notif-wrapper noti-list"> <div v-if="notifications.length"> <NotificationWidgetItem v-for="notification in notifications" :notification="notification" :key="notification.id" /> </div> <div class="d-flex mt-4 mb-4 jc-center ai-center no-notif" v-else> <h6><strong>No Notification</strong></h6> </div> </div> <div v-if="this.$store.state.auth.user['role_id']==1 ||this.$store.state.auth.user['role_id']==2"> <router-link :to="{ name: 'admin.notifications' }" class="noti-footer primary text-center d-block border-top border-top-blue-grey border-top-lighten-4 text-bold-400 py-1"> <small>Read All Notifications</small> </router-link> </div> <div v-if="this.$store.state.auth.user['role_id']==3 ||this.$store.state.auth.user['role_id']==4"> <router-link :to="{ name: 'organisation.notifications' }" class="noti-footer primary text-center d-block border-top border-top-blue-grey border-top-lighten-4 text-bold-400 py-1"> <small>Read All Notifications</small> </router-link> </div> </div> </div> </template> <script> import Card from '~/components/Card' import NotificationWidgetItem from '~/partials/NotificationWidgetItem' import { mapGetters } from 'vuex' export default { name: 'NotificationWidget', components: { NotificationWidgetItem, }, data: () => ({ notifications: [ { id: '1', color: 'red', status: 'Declined-Lapsed', title: '', message: '“confirm contacted” status getting no response from installer', created_at: '07/08/2020', is_read: '0', } ] }), } </script>
472
https://github.com/Nkoroi254/androidroombasicsample/blob/master/app/src/main/java/com/example/android/persistence/util/DateFormatUtil.java
Github Open Source
Open Source
Apache-2.0
2,021
androidroombasicsample
Nkoroi254
Java
Code
43
133
package com.example.android.persistence.util; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by nkoroi on 01/06/17. */ public class DateFormatUtil { private final Date date; String form; public DateFormatUtil(Date date) { this.date = date; } public String getForm() { return new SimpleDateFormat("yyyy-dd-MM hh:mm a").format(date); } }
13,262
https://github.com/tanshu321/v1/blob/master/completestocktake.php
Github Open Source
Open Source
MIT
null
v1
tanshu321
PHP
Code
890
3,274
<?php include("includes/webfunctions.php"); include('includes/agent.php'); $agent->init(); //SECURITY $ThisClientID = $_SESSION["ClientID"]; $ThisUser = $_SESSION["ClientName"]; $ThisSecret = $_SESSION["SiteSecret"]; if ($ThisClientID > 0 && $ThisUser != "" && $ThisSecret == "E2A_crm_S5gdbh6nnj_usr_9898") { $WarehouseID = $_REQUEST["w"]; $StockTake = GetStockTakeDetails($WarehouseID); while ($Val = mysqli_fetch_array($StockTake)) { $StockTakeDate = $Val["StockTakeDate"]; $WarehouseName = $Val["WarehouseName"]; $StockTakeID = $Val["StockTakeID"]; } $StockProducts = GetAllStockProducts(); } else { echo "<script type='text/javascript'>alert('Your session has expired, please login again'); parent.location = 'logout.php';</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Business CRM</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- MetisMenu CSS --> <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet"> <!-- DataTables CSS --> <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet"> <!-- DataTables Responsive CSS --> <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet"> <!-- Custom CSS --> <link href="dist/css/sb-admin-2.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <script type="text/javascript"> function AdjustStock(StockLeft, ProductID, WarehouseID) { bootbox.prompt({ title: "Please change the current stock below", value: StockLeft, callback: function(result) { var NewStock = result; if (NewStock != "" && NewStock != null && parseFloat(NewStock) >= 0 && $.isNumeric(NewStock)) { var Difference = parseFloat(NewStock) - parseFloat(StockLeft); bootbox.confirm("This will result in a " + Difference + " in current stock, please confirm", function(result) { if (result === true) { var AdjustStock = agent.call('', 'AdjustStockLevel','', StockLeft, NewStock, Difference, ProductID, WarehouseID); if (AdjustStock == "OK") { document.location.reload(); } else { bootbox.alert(AdjustStock); } } }); } else { if ($.isNumeric(NewStock)) { } else { bootbox.alert({ message: "Please enter a numeric value for your stock", callback: function () { } }) } } } }); } </script> </head> <body> <div id="wrapper"> <?php include("navigation.php") ?> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Stock Take - <?php echo $WarehouseName ?></h1> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <strong><i class="fa fa-info-circle fa-fw" style="font-size: 16px"></i></strong> Please enter the stock take values captured for <?php echo $WarehouseName ?>. Please note the capture has to happen all at once. </div> <div class="row"> <div class="col-lg-12"> <div class="col-lg-12"> <h4>Stock Items</h4> <table width="100%" class="table table-striped table-bordered table-hover" id="warehouse<?php echo $WarehouseID ?>" style="font-size: 12px"> <thead> <tr> <th>Product</th> <th>Product Group</th> <th>Theoretical Stock</th> <th>Actual Stock</th> </tr> </thead> <tbody> <?php while ($Val = mysqli_fetch_array($StockProducts)) { $ProductID = $Val["ProductID"]; $ProductName = $Val["ProductName"]; $ProductGroupID = $Val["ProductGroupID"]; $ProductSubGroupID = $Val["ProductSubGroupID"]; $GroupName = $Val["GroupName"]; $MinimumStock = $Val["MinimumStock"]; $AllProductID .= $ProductID . ","; $StockIn = 0; $StockOut = 0; if ($ProductSubGroupID != 0) { $SubGroup = GetProductSubGroup($ProductSubGroupID); $ProductGroup .= " - " . $SubGroup; } $StockIn = GetStockInDated($ProductID, $WarehouseID, $StockTakeDate); if ($StockIn == "") { $StockIn = 0; } $StockOut = GetStockOutDated($ProductID, $WarehouseID, $StockTakeDate); if ($StockOut == "") { $StockOut = 0; } $StockLeft = $StockIn + $StockOut; if ($MinimumStock == 0) { $ShowStatus = "N/A"; } else { $Buffer = $StockLeft - $MinimumStock; if ($Buffer > 0) { $ShowStatus = '<span class="label label-success">' . $Buffer . ' Above Min</span>'; } else { $ShowStatus = '<span class="label label-danger">Below Min</span>'; } } if ($StockLeft <= 0) { $ShowStatus = '<span class="label label-danger">Out of Stock</span>'; } ?> <tr class="odd gradeX"> <td><?php echo $ProductName ?></td> <td><?php echo $GroupName ?></td> <td><span id="stockleft<?php echo $ProductID ?>"><?php echo $StockLeft ?></span></td> <td class="center"><input type="text" class="form-control" style="width: 90px" value="<?php echo $StockLeft ?>" id="stock<?php echo $ProductID ?>"></td> </tr> <?php } $AllProductID = rtrim($AllProductID, ","); ?> </tbody> </table> <!-- /.table-responsive --> </div> <div class="row"> <div class="form-group row col-md-12"> <button class="btn btn-success pull-right" onClick="javascript: CompleteStockTake();">Complete Stock Take</button> </div> <!-- /.col-lg-8 --> </div> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="vendor/metisMenu/metisMenu.min.js"></script> <!-- DataTables JavaScript --> <script src="vendor/datatables/js/jquery.dataTables.min.js"></script> <script src="vendor/datatables-plugins/dataTables.bootstrap.min.js"></script> <script src="vendor/datatables-responsive/dataTables.responsive.js"></script> <!-- Custom Theme JavaScript --> <script src="dist/js/sb-admin-2.js"></script> <script src="js/bootbox.js"></script> <!-- Page-Level Demo Scripts - Tables - Use for reference --> <script type="text/javascript"> function CompleteStockTake() { var AllProductID = '<?php echo $AllProductID ?>'; var AllProductIDArray = AllProductID.split(","); var Error = 0; for (i = 0; i < AllProductIDArray.length; i++) { var ThisID = AllProductIDArray[i]; var NewStock = document.getElementById("stock" + ThisID).value; NewStock = NewStock.replace(/\s+/g, ''); if ($.isNumeric( NewStock) && NewStock >= 0 && NewStock != "") { } else { Error = 1; } } if (Error == 0) { bootbox.confirm("Are you sure all values are correct, this action cannot be undone and the stock take will be completed? Please note this may take a while, please wait for confirmation of completion.", function(result) { if (result === true) { for (i = 0; i < AllProductIDArray.length; i++) { var ThisID = AllProductIDArray[i]; var NewStock = document.getElementById("stock" + ThisID).value; var CurrentStock = document.getElementById("stockleft" + ThisID).innerHTML; var Difference = parseFloat(NewStock) - parseFloat(CurrentStock); if (Difference != 0) { var AdjustStock = agent.call('', 'AdjustStockLevelStockTake','', CurrentStock, NewStock, Difference, ThisID, '<?php echo $WarehouseID ?>', '<?php echo $StockTakeID ?>'); } } //THEN WHEN IT COMPLETES, COMPLETE STOCK TAKE AND GO BACK TO STOCK SYSTEM var DoCompleteStockTake = agent.call('','CompleteStockTake','', '<?php echo $StockTakeID ?>'); if (DoCompleteStockTake == "OK") { bootbox.alert("The stock take has been completed successfully", function() { document.location = 'stockcontrol.php'; }); } } }); } else { bootbox.alert("Please make sure you have entered all the values and that all values are numeric"); } } </script> </body> </html>
7,038
https://github.com/mickaelpol/try_laravel/blob/master/resources/views/posts/index.blade.php
Github Open Source
Open Source
MIT
null
try_laravel
mickaelpol
PHP
Code
59
237
@extends('layouts.default') @section('content') <div class="container"> <p> <a class="btn btn-primary" href="{{ route('news.create') }}"> Creer un Nouvel article </a> </p> @foreach($posts as $post) <div class="col-lg-6"> <h1>{{ $post->title }}</h1> <p>{{ $post->content }}</p> <p> <a class="btn btn-primary" href="{{ route('news.edit', $post) }}"> Editer </a> </p> {{-- bouton de validation du formulaire --}} <a href="{{ route('news.destroy', $post) }}" class="btn btn-danger btn-md">Supprimer l'article</a> </div> @endforeach </div> @endsection
18,307
https://github.com/BlackBoxAM/Lean/blob/master/Indicators/RelativeDailyVolume.cs
Github Open Source
Open Source
Apache-2.0
2,022
Lean
BlackBoxAM
C#
Code
610
1,373
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Collections.Generic; using QuantConnect.Data.Market; namespace QuantConnect.Indicators { /// <summary> /// The Relative Daily Volume indicator is an indicator that compares current /// cumulative volume to the cumulative volume for a given /// time of day, measured as a ratio. /// /// Current volume from open to current time of day / Average over the past x days from open to current time of day /// </summary> public class RelativeDailyVolume : TradeBarIndicator, IIndicatorWarmUpPeriodProvider { private readonly SortedDictionary<TimeSpan, SimpleMovingAverage> _relativeData; private readonly Dictionary<DateTime, decimal> _currentData; private int _previousDay; private int _days; /// <summary> /// Gets a flag indicating when the indicator is ready and fully initialized /// </summary> public override bool IsReady => _days >= WarmUpPeriod; /// <summary> /// Required period, in data points, for the indicator to be ready and fully initialized. /// </summary> public int WarmUpPeriod { get; } /// <summary> /// Initializes a new instance of the RelativeDailyVolume class using the specified period /// </summary> /// <param name="period">The period over which to perform the computation</param> public RelativeDailyVolume(int period = 2) : this($"RDV({period})", period) { } /// <summary> /// Creates a new RelativeDailyVolume indicator with the specified period /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The period of this indicator</param> public RelativeDailyVolume(string name, int period) : base(name) { _relativeData = new SortedDictionary<TimeSpan, SimpleMovingAverage>(); _currentData = new Dictionary<DateTime, decimal>(); WarmUpPeriod = period; _previousDay = -1; // No calendar day can be -1, thus default is not a calendar day _days = -1; // Will increment by one after first TradeBar, then will increment by one every new day } /// <summary> /// Computes the next value for this indicator from the given state. /// </summary> /// <param name="input">The input value to this indicator on this time step</param> /// <returns>A a value for this indicator</returns> protected override decimal ComputeNextValue(TradeBar input) { if (input.Time.Day != _previousDay) { var cumulativeVolume = 0.0m; foreach (var pair in _currentData) { var timeBar = pair.Key.TimeOfDay; SimpleMovingAverage daysAverage; cumulativeVolume += pair.Value; if (!_relativeData.TryGetValue(timeBar, out daysAverage)) { daysAverage = _relativeData[timeBar] = new SimpleMovingAverage(WarmUpPeriod); } daysAverage.Update(pair.Key, cumulativeVolume); } _currentData.Clear(); _previousDay = input.Time.Day; _days += 1; // _days is starting from -1, to reach IsReady => _days == WarmUpPeriod; also means WarmUpPeriod+1 } _currentData[input.Time] = input.Volume; if (!IsReady) { return 0; } var currentTimeBar = input.Time.TimeOfDay; var denominator = 0.0m; SimpleMovingAverage currentAverage; if (_relativeData.TryGetValue(currentTimeBar, out currentAverage)) { denominator = currentAverage.Current.Value; } else { // If there is no historical data for the current time, get most recent historical data // This may come into play for crypto assets or a circuit breaker event var relativeDataKeys = _relativeData.Keys.ToList(); for (int i = 1; i < relativeDataKeys.Count; i++) { if (relativeDataKeys[i] > currentTimeBar) { denominator = _relativeData[relativeDataKeys[i - 1]].Current.Value; } } } if (denominator == 0) { return 0; } var relativeDailyVolume = _currentData.Values.Sum() / denominator; return relativeDailyVolume; } /// <summary> /// Resets this indicator to its initial state /// </summary> public override void Reset() { _relativeData.Clear(); _currentData.Clear(); _previousDay = -1; _days = -1; base.Reset(); } } }
36,002
https://github.com/fleetyards/app/blob/master/app/packs/frontend/pages/Stations/index.vue
Github Open Source
Open Source
Apache-2.0
2,019
app
fleetyards
Vue
Code
125
531
<template> <router-view v-if="isSubRoute" /> <section v-else class="container"> <div class="row"> <div class="col-12"> <h1 class="sr-only"> {{ $t('headlines.stations') }} </h1> </div> </div> <FilteredList key="stations" :collection="collection" :name="$route.name" :route-query="$route.query" :hash="$route.hash" :paginated="true" > <FilterForm slot="filter" /> <template #default="{ filterVisible, records }"> <transition-group name="fade-list" class="row" tag="div" :appear="true"> <div v-for="(record, index) in records" :key="`${record.id}-${index}`" :class="{ 'col-3xl-6': !filterVisible, }" class="col-12 fade-list-item" > <StationPanel :station="record" /> </div> </transition-group> </template> </FilteredList> </section> </template> <script lang="ts"> import Vue from 'vue' import { Component } from 'vue-property-decorator' import MetaInfo from 'frontend/mixins/MetaInfo' import FilteredList from 'frontend/core/components/FilteredList' import StationPanel from 'frontend/components/Stations/Panel' import FilterForm from 'frontend/components/Stations/FilterForm' import stationsCollection from 'frontend/api/collections/Stations' @Component<Stations>({ components: { FilteredList, StationPanel, FilterForm, }, mixins: [MetaInfo], }) export default class Stations extends Vue { collection: StationsCollection = stationsCollection get isSubRoute() { return this.$route.name !== 'stations' } } </script>
9,240
https://github.com/ololx/cranberry/blob/master/cranberry-commons/src/main/java/io/github/ololx/cranberry/commons/handler/AbstractCompilationHandler.java
Github Open Source
Open Source
Apache-2.0
2,022
cranberry
ololx
Java
Code
268
653
/** * Copyright 2019 the project cranberry authors * and the original author or authors annotated by {@author} * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.github.ololx.cranberry.commons.handler; import com.sun.source.util.TaskEvent; import java.util.Set; import java.util.function.Consumer; /** * The type Abstract compilation handler. * * @param <T> the type parameter * @param <K> the type parameter * @author Alexander A. Kropotin * project cranberry * created 2019 -12-23 12:52 */ public abstract class AbstractCompilationHandler<T extends TaskEvent, K extends TaskEvent.Kind> implements CompilationHandler<T> { /** * The Start handling. */ protected Consumer<T> startHandling; /** * The Finish handling. */ protected Consumer<T> finishHandling; /** * The Phases types. */ protected Set<K> phasesTypes; /** * Instantiates a new Abstract compilation handler. */ public AbstractCompilationHandler() { } @Override public void started(TaskEvent event) { if (this.startHandling == null) return; this.acceptHandling(this.startHandling, (T) event); } @Override public void finished(TaskEvent event) { if (this.finishHandling == null) return; this.acceptHandling(this.finishHandling, (T) event); } @Override public void setStartHandling(Consumer<T> startHandling) { this.startHandling = startHandling; } @Override public void setFinishHandling(Consumer<T> finishHandling) { this.finishHandling = finishHandling; } private void acceptHandling(Consumer<T> processing, T event) { if (phasesTypes.contains(event.getKind())) processing.accept(event); } }
34,102
https://github.com/lonphy/micropython/blob/master/ports/stm32f1/sram.c
Github Open Source
Open Source
MIT
2,020
micropython
lonphy
C
Code
947
3,070
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * 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. */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include "py/runtime.h" #include "py/mphal.h" #include "sram.h" #ifdef MICROPY_HW_SRAM_BANK #define MEM_1K (1024) #define MEM_SIZE_256K ((256U << 0U) * MEM_1K) #define MEM_SIZE_512K ((256U << 1U) * MEM_1K) #define MEM_SIZE_1M ((256U << 2U) * MEM_1K) #define MEM_SIZE_2M ((256U << 3U) * MEM_1K) #define MEM_SIZE_4M ((256U << 4U) * MEM_1K) #define MEM_SIZE_8M ((256U << 5U) * MEM_1K) #define MEM_SIZE_16M ((256U << 6U) * MEM_1K) #define MEM_SIZE_32M ((256U << 7U) * MEM_1K) #define MEM_SIZE_64M ((256U << 8U) * MEM_1K) #define SRAM_FSMC_BCR (0x00001011U) /* control register, [ WREN=1, MWID=16bit, MBKEN=1]*/ #define SRAM_FSMC_BTR (((MICROPY_HW_SRAM_TIMING_DATAST & 0xffU) << 8U) | \ ((MICROPY_HW_SRAM_TIMING_ADDHLD & 0x0fU) << 4U) | \ ((MICROPY_HW_SRAM_TIMING_ADDSET & 0x0fU) << 0U) ) /* timing register, [DATAST, ADDHLD, ADDSET] */ #define PCFG_OFFSET(n) (((n)%8U) * 4U ) #define PIN_ALT_CFG(n) (0x0BU << PCFG_OFFSET(n)) /* Alternate Output with push-pull, max speed */ #define PIN_MASK(n) (0x0FU << PCFG_OFFSET(n)) bool sram_init(void) { RCC->AHBENR = 0x114; // FSMC_NE1 -- PD7 FSMC_NE2 -- PG9 FSMC_NE3 -- PG10 FSMC_NE4 -- PG12 // FSMC_NOE -- PD4 FSMC_NWE -- PD5 // FSMC_NBL1 -- PE1 FSMC_NBL0 -- PE0 // FSMC_D0 -- PD15 FSMC_D1 -- PD14 FSMC_D2 -- PD0 FSMC_D3 -- PD1 // FSMC_D4 -- PE7 FSMC_D5 -- PE8 FSMC_D6 -- PE9 FSMC_D7 -- PE10 // FSMC_D8 -- PE11 FSMC_D9 -- PE12 FSMC_D10 -- PE13 FSMC_D11 -- PE14 // FSMC_D12 -- PE15 FSMC_D13 -- PD8 FSMC_D14 -- PD9 FSMC_D15 -- PD10 // FSMC_A0 -- PF0 FSMC_A1 -- PF1 FSMC_A2 -- PF2 FSMC_A3 -- PF3 // FSMC_A4 -- PF4 FSMC_A5 -- PF5 FSMC_A6 -- PF12 FSMC_A7 -- PF13 // FSMC_A8 -- PF14 FSMC_A9 -- PF15 FSMC_A10 -- PG0 FSMC_A11 -- PG1 // FSMC_A12 -- PG2 FSMC_A13 -- PG3 FSMC_A14 -- PG4 FSMC_A15 -- PG5 // FSMC_A16 -- PD11 GPIOD->CRL = 0x44BB44BBU; /* fixed: PD0, PD1, PD4, PD5 */ GPIOD->CRH = 0xBB00BBBBU; /* PD8 ~ PD11, PD14, PD15 */ GPIOE->CRL = 0xB44444BBU; /* PE0, PE1, PE7 */ GPIOE->CRH = 0xBBBBBBBBU; /* PE8 ~ PE15 */ GPIOF->CRL = 0x44BBBBBBU; /* PF0 ~ PF5 */ GPIOF->CRH = 0xBBBB4444U; /* PF12 ~ PF15 */ GPIOG->CRL = 0x44BBBBBBU; /* PG0 ~ PG5 */ #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_512K) /* A17 -- PD12 */ MODIFY_REG(GPIOD->CRH, PIN_MASK(12), PIN_ALT_CFG(12)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_1M) /* A18 -- PD13 */ MODIFY_REG(GPIOD->CRH, PIN_MASK(13), PIN_ALT_CFG(13)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_2M) /* A19 -- PE3 */ MODIFY_REG(GPIOE->CRL, PIN_MASK(3), PIN_ALT_CFG(3)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_4M) /* A20 -- PE4 */ MODIFY_REG(GPIOE->CRL, PIN_MASK(4), PIN_ALT_CFG(4)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_8M) /* A21 -- PE5 */ MODIFY_REG(GPIOE->CRL, PIN_MASK(5), PIN_ALT_CFG(5)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_16M) /* A22 -- PE6 */ MODIFY_REG(GPIOE->CRL, PIN_MASK(6), PIN_ALT_CFG(6)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_32M) /* A23 -- PE2 */ MODIFY_REG(GPIOE->CRL, PIN_MASK(2), PIN_ALT_CFG(2)); #endif #if (MICROPY_HW_SRAM_SIZE >= MEM_SIZE_64M) /* A24 -- PG13 */ MODIFY_REG(GPIOG->CRH, PIN_MASK(13), PIN_ALT_CFG(13)); #endif /* FSMC Register Config to SRAM */ #if (MICROPY_HW_SRAM_BANK == FSMC_BANK1_1) /* NE1 -- PD7 */ MODIFY_REG(GPIOD->CRL, PIN_MASK(7), PIN_ALT_CFG(7)); FSMC_Bank1->BTCR[1U] = SRAM_FSMC_BTR; FSMC_Bank1->BTCR[0U] = SRAM_FSMC_BCR; #elif (MICROPY_HW_SRAM_BANK == FSMC_BANK1_2) /* NE2 -- PG9 */ MODIFY_REG(GPIOG->CRH, PIN_MASK(9), PIN_ALT_CFG(9)); FSMC_Bank1->BTCR[3U] = SRAM_FSMC_BTR; FSMC_Bank1->BTCR[2U] = SRAM_FSMC_BCR; #elif (MICROPY_HW_SRAM_BANK == FSMC_BANK1_3) /* NE3 -- PG10 */ MODIFY_REG(GPIOG->CRH, PIN_MASK(10), PIN_ALT_CFG(10)); FSMC_Bank1->BTCR[5U] = SRAM_FSMC_BTR; FSMC_Bank1->BTCR[4U] = SRAM_FSMC_BCR; #elif (MICROPY_HW_SRAM_BANK == FSMC_BANK1_4) /* NE4 -- PG12 */ MODIFY_REG(GPIOG->CRH, PIN_MASK(12), PIN_ALT_CFG(12)); FSMC_Bank1->BTCR[7U] = SRAM_FSMC_BTR; FSMC_Bank1->BTCR[6U] = SRAM_FSMC_BCR; #endif return true; } void *sram_start(void) { return (void*)MICROPY_HW_SRAM_BANK; } void *sram_end(void) { return (void*)(MICROPY_HW_SRAM_BANK + MICROPY_HW_SRAM_SIZE); } bool __attribute__((optimize("O0"))) sram_test(bool fast) { uint8_t const pattern = 0xaa; uint8_t const antipattern = 0x55; uint8_t *const mem_base = (uint8_t*)sram_start(); uint16_t *const mem16_base = (uint16_t*)sram_start(); /* test data bus */ for (uint16_t i = 1; i; i <<= 1) { *mem16_base = i; __DSB(); if (*mem16_base != i) { printf("data bus lines test failed! data (%d)\n", i); __asm__ volatile ("BKPT"); } } /* test address bus */ /* Check individual address lines */ for (uint32_t i = 1; i < MICROPY_HW_SRAM_SIZE; i <<= 1) { mem_base[i] = pattern; __DSB(); if (mem_base[i] != pattern) { printf("address bus lines test failed! address (%p)\n", &mem_base[i]); __asm__ volatile ("BKPT"); } } /* Check for aliasing (overlaping addresses) */ mem_base[0] = antipattern; for (uint32_t i = 1; i < MICROPY_HW_SRAM_SIZE; i <<= 1) { if (mem_base[i] != pattern) { printf("address bus overlap %p\n", &mem_base[i]); __asm__ volatile ("BKPT"); } } /* test all ram cells */ if (!fast) { for (uint32_t i = 0; i < MICROPY_HW_SRAM_SIZE; ++i) { mem_base[i] = pattern; __DSB(); if (mem_base[i] != pattern) { printf("address bus test failed! address (%p)\n", &mem_base[i]); __asm__ volatile ("BKPT"); } } } else { memset(mem_base, pattern, MICROPY_HW_SRAM_SIZE); } return true; } #endif
31,617
https://github.com/nbclark/flipper/blob/master/FlipperPlugins/POutlook.cpp
Github Open Source
Open Source
Apache-2.0
null
flipper
nbclark
C++
Code
1,650
5,199
#include "StdAfx.h" #include "POutlook.h" #include <initguid.h> #define INITGUID #include <imaging.h> #include <windowsx.h> #define _ErrorLabel Error #define CHR(hResult) \ if(FAILED(hResult)) { hr = (hResult); goto _ErrorLabel;} #define CPR(pPointer) \ if(NULL == (pPointer)) { hr = (E_OUTOFMEMORY); goto _ErrorLabel;} #define CBR(fBool) \ if(!(fBool)) { hr = (E_FAIL); goto _ErrorLabel;} #define ARRAYSIZE(s) (sizeof(s) / sizeof(s[0])) #define RELEASE_OBJ(s) \ if (s != NULL) \ { \ s->Release(); \ s = NULL; \ } HRESULT GetStreamSize(IStream* pStream, ULONG* pulSize); HBITMAP HBITMAPFromImage(IImage * pImage, COLORREF crBackColor); HRESULT GetBitmapFromStream(IStream* pStream, HBITMAP* phBitmap, UINT* iWidth, UINT* iHeight, bool bStretch); void DrawRect(HDC hdc, LPRECT prc, COLORREF clr); CPOutlook::CPOutlook(void) { m_pOutlookApp = NULL; } CPOutlook::~CPOutlook(void) { } // ************************************************************************** // Function Name: CPictureDial::EnsurePOOM // // Purpose: Instantiate the POOM object if necessary // // Arguments: // NONE // // Return Values: // HRESULT - S_OK if success, failure code if not // HRESULT CPOutlook::EnsurePOOM() { HRESULT hr; if (m_pOutlookApp == NULL) { hr = CoCreateInstance(__uuidof(Application), NULL, CLSCTX_INPROC_SERVER, __uuidof(IPOutlookApp2), (LPVOID*) &m_pOutlookApp); CHR(hr); hr = m_pOutlookApp->Logon(NULL); CHR(hr); } hr = S_OK; Error: if (FAILED(hr)) { // If we failed to log on, don't keep the object around RELEASE_OBJ(m_pOutlookApp); } return hr; } HRESULT CPOutlook::CreateSMS(WCHAR* wzPhone, WCHAR* wzSubject) { HRESULT hr = E_FAIL; if (SUCCEEDED(EnsurePOOM())) { } return hr; } // ************************************************************************** // Function Name: CPictureDial::DrawBitmap // // Purpose: Draws the bitmap within the entry square // // Arguments: // IN HDC hdc - DC for drawing // IN int x - horizontal location of upper left hand corner of drawing area // IN int y - vertical location of upper left hand corner of drawing area // IN CONTACTINFO pContact - contains bitmap info for the contact to draw // IN int nItem - index of current item // // Return Values: // NONE // void CPOutlook::DrawBitmap(HDC hdc, int x, int y, CONTACTINFO* pContact, int nItem) { // HRESULT hr; // HBITMAP hOldBitmap = NULL; // HDC hdcSrc = NULL; // RECT rc = {x, y, x+m_uItemWidth, y+m_uItemHeight}; // COLORREF clrBack; // UINT uItemWidth = m_uItemWidth-BORDERSIZE-CXGUTTER*2; // UINT uItemHeight = m_uItemHeight-BORDERSIZE-CYGUTTER*2; // UINT xOffset = (uItemWidth >= pContact->dxBitmap ? (uItemWidth-pContact->dxBitmap)/2 : 0); // UINT yOffset = (uItemHeight >= pContact->dyBitmap ? (uItemHeight-pContact->dyBitmap)/2 : 0); // // hdcSrc = CreateCompatibleDC(hdc); // CBR(hdcSrc != NULL); // // hOldBitmap = SelectBitmap(hdcSrc, pContact->hBitmap); // CBR(hOldBitmap != NULL); // // // Select the color depending on if we're drawing the active entry // clrBack = (m_iSel == nItem ? GetSysColor(COLOR_HIGHLIGHT) : GetSysColor(COLOR_WINDOW)); // // // Color the background first // DrawRect(hdc, &rc, clrBack); // // // Draw the image // BitBlt(hdc, x+CXGUTTER+xOffset, y+CYGUTTER+yOffset, pContact->dxBitmap, pContact->dyBitmap, hdcSrc, 0, 0, SRCCOPY); // //Error: // if (hOldBitmap) // { // SelectBitmap(hdcSrc, hOldBitmap); // } // // if (hdcSrc) // { // DeleteDC(hdcSrc); // } return; } // ************************************************************************** // Function Name: CPictureDial::FindBitmap // // Purpose: Given an oid, find the bitmap and its dimensions // // Arguments: // IN CEOID oid - oid of the contact // IN HBITMAP* phBitmap - bitmap of the contact's picture // OUT UINT* puWidth - width of the bitmap // OUT UINT* puHeight - height of the bitmap // // Return Values: // HRESULT - S_OK if success, failure code if not // HRESULT CPOutlook::UpdateContact(CEOID oid, WCHAR* wzName, size_t cchName, HBITMAP* phBmp, UINT* puiWidth, UINT* puiHeight) { IItem* pItem = NULL; CEPROPVAL *rgVals = NULL; ULONG cbBuffer = 0; HANDLE hHeap = GetProcessHeap(); CEPROPID rgPropID[] = { PIMPR_DISPLAY_NAME }; const WORD cProps = ARRAYSIZE(rgPropID); HRESULT hr = E_FAIL; hr = EnsurePOOM(); CHR(hr); hr = m_pOutlookApp->GetItemFromOidEx(oid, 0, &pItem); CHR(hr); hr = pItem->GetProps(rgPropID, CEDB_ALLOWREALLOC, cProps, &rgVals, &cbBuffer, hHeap); CHR(hr); StringCchCopy(wzName, cchName, rgVals[0].val.lpwstr); FindBitmap(oid, phBmp, puiWidth, puiHeight); Error: if (NULL != rgVals) { // Free the memory POOM alloced on the heap for the props we got. HeapFree(hHeap, 0, rgVals); } RELEASE_OBJ(pItem); return hr; } HRESULT CPOutlook::FindBitmap ( CEOID oid, HBITMAP* phBitmap, UINT* puWidth, UINT* puHeight ) { HRESULT hr; IItem* pItem = NULL; IStream* pStream = NULL; ULONG ulSize; // Make sure we can access POOM hr = EnsurePOOM(); CHR(hr); hr = m_pOutlookApp->GetItemFromOidEx(oid, 0, &pItem); CHR(hr); // Extract the picture from the contact hr = pItem->OpenProperty(PIMPR_PICTURE, GENERIC_READ, &pStream); CHR(hr); hr = GetStreamSize(pStream, &ulSize); CHR(hr); // In some cases, the property may exist even if there is no picture. // Make sure we can access the stream and don't have a 0 byte stream CBR(ulSize > 0); hr = GetBitmapFromStream(pStream, phBitmap, puWidth, puHeight, false); CHR(hr); Error: RELEASE_OBJ(pItem); RELEASE_OBJ(pStream); return hr; } HRESULT CPOutlook::SelectContact(HWND hWnd, WCHAR* wzName, DWORD dwName, WCHAR* wzPhone, DWORD dwPhone, CEOID* pOid) { HRESULT hr; CHOOSECONTACT chooserData = {0}; CEPROPID propid[2]; propid[0] = PIMPR_ALL_VOICE; propid[1] = PIMPR_DISPLAY_NAME; chooserData.cbSize = sizeof(chooserData); chooserData.dwFlags = CCF_RETURNPROPERTYVALUE | CCF_RETURNCONTACTNAME; chooserData.rgpropidRequiredProperties = propid; chooserData.cRequiredProperties = 1; chooserData.hwndOwner = hWnd; // Pop up the contact chooser hr = ChooseContact(&chooserData); if (SUCCEEDED(hr)) { StringCchCopy(wzName, dwName, chooserData.bstrContactName); StringCchCopy(wzPhone, dwPhone, chooserData.bstrPropertyValueSelected); SysFreeString(chooserData.bstrPropertyValueSelected); SysFreeString(chooserData.bstrContactName); *pOid = chooserData.oidContactID; } return hr; } // ************************************************************************** // Function Name: CPictureDial::ShowContact // // Purpose: Load a single contact from the registry // // Arguments: // IN int nItem - index of the contact to load // // Return Values: // HRESULT - S_OK if success, failure code if not // HRESULT CPOutlook::ShowContact(CEOID oid, HWND hwndParent) { IItem* pItem = NULL; CEPROPVAL *rgVals = NULL; ULONG cbBuffer = 0; HANDLE hHeap = GetProcessHeap(); CEPROPID rgPropID[] = { PIMPR_DISPLAY_NAME }; const WORD cProps = ARRAYSIZE(rgPropID); HRESULT hr = E_FAIL; hr = EnsurePOOM(); CHR(hr); hr = m_pOutlookApp->GetItemFromOidEx(oid, 0, &pItem); CHR(hr); hr = pItem->Display(hwndParent); Error: RELEASE_OBJ(pItem); return hr; } // ************************************************************************** // Function Name: GetStreamSize // // Purpose: Given an IStream, returns the size of the stream. This is needed // for streams that do not support the Stat method // // Arguments: // IN IStream* pStream - stream to determine size for // OUT ULONG* pulSize - size of stream // // Return Values: // HRESULT - S_OK if success, failure code if not // // Side Effects: // The stream pointer always resets to the beginning // HRESULT GetStreamSize(IStream* pStream, ULONG* pulSize) { HRESULT hr; LARGE_INTEGER li = {0}; ULARGE_INTEGER uliZero = {0}; ULARGE_INTEGER uli; CBR(pStream != NULL && pulSize != NULL); hr = pStream->Seek(li, STREAM_SEEK_END, &uli); CHR(hr); *pulSize = uli.LowPart; hr = S_OK; Error: if (SUCCEEDED(hr)) { // Move the stream back to the beginning of the file hr = pStream->Seek(li, STREAM_SEEK_SET, &uliZero); } return hr; } // ************************************************************************** // Function Name: HBITMAPFromImage // // Purpose: Convert IImage to HBITMAP. If bitmap has transparency, the // background will be filled with the color passed in // // Arguments: // IN IImage* pImage - pointer to the IImage // IN COLORREF crBackColor - color of the background // // Return Values: // HRESULT - S_OK if success, failure code if not // HBITMAP HBITMAPFromImage ( IN IImage * pImage, IN COLORREF crBackColor ) { HRESULT hr; HBITMAP hbmResult = NULL; ImageInfo ii; HDC hDC = NULL; RECT rc = { 0 }; HBITMAP hbmNew = NULL; void * pv; BITMAPINFO bmi = { 0 }; HBITMAP hbmOld = NULL; CBR(pImage != NULL); // Get image width/height hr = pImage->GetImageInfo(&ii); CHR(hr); // Create HDC hDC = CreateCompatibleDC(NULL); CBR(hDC != NULL); // Create DIB section bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = ii.Width; bmi.bmiHeader.biHeight = ii.Height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = (SHORT) max(16, GetDeviceCaps(hDC, BITSPIXEL)); bmi.bmiHeader.biCompression = BI_RGB; hbmNew = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, &pv, NULL, 0); CBR(hbmNew != NULL); // Select DIB into DC hbmOld = (HBITMAP)SelectObject(hDC, hbmNew); rc.right = ii.Width; rc.bottom = ii.Height; // Clear the bitmap using the background color //DrawRect(hDC, &rc, crBackColor); // Draw into DC/DIB hr = pImage->Draw(hDC, &rc, NULL); CHR(hr); hbmResult = hbmNew; hbmNew = NULL; Error: if (hbmNew) { DeleteObject(hbmNew); } if (hDC) { if (hbmOld) { SelectObject(hDC, hbmOld); } DeleteDC(hDC); } return hbmResult; } // ************************************************************************** // Function Name: GetBitmapFromStream // // Purpose: Convert an IStream to an HBITMAP and return the new dimensions // // Arguments: // IN UINT uFitToWidth - width of source image // IN UINT uFitToHeight - height of source image // OUT UINT* puWidth - width of image to scale to // OUT UINT* puHeight - height of image to scale to // // Return Values: // HRESULT - S_OK if success, failure code if not // HRESULT GetBitmapFromStream(IStream* pStream, HBITMAP* phBitmap, UINT* puWidth, UINT* puHeight, bool bStretch) { HRESULT hr; HBITMAP hBitmap = NULL; IImagingFactory* pFactory = NULL; IImage* pImage = NULL; IImage* pThumbnail = NULL; ImageInfo imgInfo = {0}; CBR(pStream != NULL && phBitmap != NULL && puWidth != NULL && puHeight != NULL); // Use a little imaging help hr = CoCreateInstance(CLSID_ImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IImagingFactory, (void**) &pFactory); CHR(hr); hr = pFactory->CreateImageFromStream(pStream, &pImage); CHR(hr); hr = pImage->GetImageInfo(&imgInfo); CHR(hr); CBR(imgInfo.Width > 0 && imgInfo.Height > 0); if (!bStretch) { *puHeight = min(*puHeight, imgInfo.Height); *puWidth = min(*puWidth, imgInfo.Width); } // Scale to the new size ScaleProportional(*puWidth, *puHeight, &imgInfo.Width, &imgInfo.Height); // Get the new image hr = pImage->GetThumbnail(imgInfo.Width, imgInfo.Height, &pThumbnail); CHR(hr); // Convert this to HBITMAP, our target format hBitmap = HBITMAPFromImage(pThumbnail, RGB(255,255,255)); CBR(hBitmap != NULL); *puWidth = imgInfo.Width; *puHeight = imgInfo.Height; *phBitmap = hBitmap; hBitmap = NULL; Error: RELEASE_OBJ(pFactory); RELEASE_OBJ(pImage); RELEASE_OBJ(pThumbnail); if (hBitmap) { DeleteBitmap(hBitmap); } return hr; } HBITMAP LoadImageFromFile(WCHAR* wzFile, UINT width, UINT height) { IImagingFactory* pFactory = NULL; IImage* pImage = NULL; HBITMAP hbmResult = NULL; HBITMAP hbmOld = NULL; ImageInfo ii; HDC hDC = NULL; RECT rc = { 0 }; void * pv; BITMAPINFO bmi = { 0 }; bool bSuccess = false; CoCreateInstance(CLSID_ImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IImagingFactory, (void**) &pFactory); if (SUCCEEDED(pFactory->CreateImageFromFile(wzFile, &pImage))) { if (SUCCEEDED(pImage->GetImageInfo(&ii))) { hDC = CreateCompatibleDC(NULL); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = ii.Width; bmi.bmiHeader.biHeight = ii.Height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = (SHORT) max(32, GetDeviceCaps(hDC, BITSPIXEL)); bmi.bmiHeader.biCompression = BI_RGB; hbmResult = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, &pv, NULL, 0); hbmOld = (HBITMAP)SelectObject(hDC, hbmResult); if (SUCCEEDED(pImage->Draw(hDC, &rc, NULL))) { bSuccess = true; } } } if (pFactory) { pFactory->Release(); } if (pImage) { pImage->Release(); } if (!bSuccess) { if (hbmResult) { DeleteObject(hbmResult); hbmResult = NULL; } } if (hDC) { if (hbmOld) { SelectObject(hDC, hbmOld); } DeleteDC(hDC); } return hbmResult; }
42,161
https://github.com/rfay/ddev/blob/master/pkg/archive/testdata/TestArchiveTar/.test.sh
Github Open Source
Open Source
Apache-2.0
2,023
ddev
rfay
Shell
Code
7
17
#!/bin/bash echo "this is a test script"
17,692
https://github.com/jtianesq/protein-prediction-nmt-evo/blob/master/Neural Machine Translation/nn/dropout.py
Github Open Source
Open Source
MIT
null
protein-prediction-nmt-evo
jtianesq
Python
Code
48
142
# dropout.py import ops def dropout(x, keep_prob, noise_shape=None, seed=None): if keep_prob > 1.0 or keep_prob <= 0: raise ValueError("keep_prob must be in range (0, 1]") if noise_shape: shape = noise_shape else: shape = x.shape mask = ops.random.binomial(shape, keep_prob, dtype=x.dtype, seed=seed) return x * (1.0 / keep_prob) * mask
21,088
https://github.com/mamontov-cpp/saddy/blob/master/include/db/save.h
Github Open Source
Open Source
BSD-2-Clause
2,022
saddy
mamontov-cpp
C
Code
1,545
5,655
/*! \file db/save,h Describes a save operations for a type */ #pragma once #include "dberror.h" #include "dbtypename.h" #include "../sadstring.h" #include "../sadrect.h" #include "../sadcolor.h" #include "../sadsize.h" #include "../sadvector.h" #include "../sadpair.h" #include "../layouts/lengthvalue.h" namespace sad { namespace db { /*! Saves a value of specified type \param[in] ptr a value to be saved */ template<typename _Type> inline picojson::value Save<_Type>::perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); if (sad::db::TypeName<_Type>::isSadObject()) { picojson::value v; static_cast<sad::Object *>(ptr)->save(v); return v; } throw sad::db::NotImplemented("sad::db::Save<_Type>::perform"); //return picojson::value(); } /*! Specification for saving bool values */ template<> class Save<bool> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { return picojson::value(*static_cast<bool*>(ptr)); } }; /*! Generates specification for saving to type via casting pointer to it */ #define SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE( TYPENAME ) \ template<> \ class Save< TYPENAME > \ { \ public: \ static inline picojson::value perform(void * ptr) \ { \ if (!ptr) \ throw sad::db::InvalidPointer(); \ return picojson::value((double)(*( TYPENAME *)ptr)); \ } \ }; SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(char) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(signed char) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(unsigned char) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(short) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(unsigned short) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(int) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(unsigned int) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(long) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(unsigned long) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(long long) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(unsigned long long) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(float) SPECIFY_SAVE_AS_CASTING_TO_DOUBLE_FOR_TYPE(double) /*! Specification for saving string values */ template<> class Save<std::string> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); return picojson::value(*static_cast<std::string*>(ptr)); } }; /*! Specification for saving string values */ template<> class Save<sad::String> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); return picojson::value(static_cast<sad::String>(*static_cast<sad::String*>(ptr))); } }; /*! Specification for saving point values */ template<> class Save<sad::Point2D> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Point2D & p = *(static_cast<sad::Point2D *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("x", picojson::value(static_cast<double>(p.x()))); v.insert("y", picojson::value(static_cast<double>(p.y()))); return v; } }; /*! Specification for saving point values */ template<> class Save<sad::Point2I> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Point2I & p = *(static_cast<sad::Point2I *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("x", picojson::value(static_cast<double>(p.x()))); v.insert("y", picojson::value(static_cast<double>(p.y()))); return v; } }; /*! Specification for saving point values */ template<> class Save<sad::Point3D> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Point3D & p = *(static_cast<sad::Point3D *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("x", picojson::value(static_cast<double>(p.x()))); v.insert("y", picojson::value(static_cast<double>(p.y()))); v.insert("z", picojson::value(static_cast<double>(p.z()))); return v; } }; /*! Specification for saving point values */ template<> class Save<sad::Point3I> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Point3I & p = *(static_cast<sad::Point3I *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("x", picojson::value(static_cast<double>(p.x()))); v.insert("y", picojson::value(static_cast<double>(p.y()))); v.insert("z", picojson::value(static_cast<double>(p.z()))); return v; } }; /*! Specification for saving rectangle values */ template<> class Save<sad::Rect2D> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Rect2D & p = *(static_cast<sad::Rect2D *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("p1", sad::db::Save<sad::Point2D>::perform(&(p[0]))); v.insert("p2", sad::db::Save<sad::Point2D>::perform(&(p[1]))); v.insert("p3", sad::db::Save<sad::Point2D>::perform(&(p[2]))); v.insert("p4", sad::db::Save<sad::Point2D>::perform(&(p[3]))); return v; } }; /*! Specification for saving color values */ template<> class Save<sad::Color> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Color & p = *(static_cast<sad::Color *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("r", picojson::value(static_cast<double>(p.r()))); v.insert("g", picojson::value(static_cast<double>(p.g()))); v.insert("b", picojson::value(static_cast<double>(p.b()))); return v; } }; /*! Specification for saving values of type color with alpha-channel */ template<> class Save<sad::AColor> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::AColor & p = *(static_cast<sad::AColor *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("r", picojson::value(static_cast<double>(p.r()))); v.insert("g", picojson::value(static_cast<double>(p.g()))); v.insert("b", picojson::value(static_cast<double>(p.b()))); v.insert("a", picojson::value(static_cast<double>(p.a()))); return v; } }; /*! Specification for saving values of type vector of vectors of color with alpha-channel */ template<> class Save<sad::Vector<sad::Vector<sad::AColor> > > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Vector<sad::Vector<sad::AColor> > & p = *(static_cast<sad::Vector<sad::Vector<sad::AColor> > *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { picojson::value tmp(picojson::array_type, false); for(size_t j = 0; j < p[i].size(); j++) { tmp.push_back(sad::db::Save<sad::AColor>::perform(&(p[i][j]))); } v.push_back(tmp); } return v; } }; /*! Specification for saving size values */ template<> class Save<sad::Size2D> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Size2D & p = *(static_cast<sad::Size2D *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("width", picojson::value(static_cast<double>(p.Width))); v.insert("height", picojson::value(static_cast<double>(p.Height))); return v; } }; /*! Specification for saving size values */ template<> class Save<sad::Size2I> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Size2I & p = *(static_cast<sad::Size2I *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("width", picojson::value(static_cast<double>(p.Width))); v.insert("height", picojson::value(static_cast<double>(p.Height))); return v; } }; /*! Specification for saving values of type vector of 2-dimensional points */ template<> class Save<sad::Vector<sad::Point2D> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Vector<sad::Point2D> & p = *(static_cast<sad::Vector<sad::Point2D> *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { v.push_back(sad::db::Save<sad::Point2D>::perform(&(p[i]))); } return v; } }; /*! Specification for saving dialogue phrase values */ template<> class Save<sad::dialogue::Phrase> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::dialogue::Phrase & p = *(static_cast<sad::dialogue::Phrase *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("name", sad::db::Save<sad::String>::perform(const_cast<sad::String*>(&(p.actorName())))); v.insert("portrait", sad::db::Save<sad::String>::perform(const_cast<sad::String*>(&(p.actorPortrait())))); v.insert("phrase", sad::db::Save<sad::String>::perform(const_cast<sad::String*>(&(p.phrase())))); double duration = p.duration(); v.insert("duration", sad::db::Save<double>::perform(&duration)); v.insert("viewhint", sad::db::Save<sad::String>::perform(const_cast<sad::String*>(&(p.viewHint())))); return v; } }; /*! Specification for saving values of type vector of phrases */ template<> class Save<sad::Vector<sad::dialogue::Phrase*> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Vector<sad::dialogue::Phrase*> & p = *(static_cast<sad::Vector<sad::dialogue::Phrase*> *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { v.push_back(sad::db::Save<sad::dialogue::Phrase>::perform(p[i])); } return v; } }; /*! Specification for saving values of type vector of unsigned long long */ template<> class Save<sad::Vector<unsigned long long> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Vector<unsigned long long> & p = *(static_cast<sad::Vector<unsigned long long> *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { v.push_back(sad::db::Save<unsigned long long>::perform(&(p[i]))); } return v; } }; /*! Specification for saving values of type vector of unsigned long long */ template<> class Save<sad::Vector<sad::String> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Vector<sad::String> & p = *(static_cast<sad::Vector<sad::String> *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { v.push_back(sad::db::Save<sad::String>::perform(&(p[i]))); } return v; } }; /*! Specification for saving values of type sad::layouts::LengthValue */ template<> class Save<sad::layouts::LengthValue> { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::layouts::LengthValue & p = *(static_cast<sad::layouts::LengthValue *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("unit", picojson::value(static_cast<double>(p.Unit))); v.insert("value", picojson::value(static_cast<double>(p.Value))); return v; } }; /*! Specification for saving pair */ template<typename T1, typename T2> class Save<sad::Pair<T1, T2> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Pair<T1, T2> & p = *(static_cast<sad::Pair<T1, T2> *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("field1", sad::db::Save<T1>::perform(&(p._1()))); v.insert("field2", sad::db::Save<T2>::perform(&(p._2()))); return v; } }; /*! Specification for saving triplet */ template<typename T1, typename T2, typename T3> class Save<sad::Triplet<T1, T2, T3> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Triplet<T1, T2, T3> & p = *(static_cast<sad::Triplet<T1, T2, T3> *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("field1", sad::db::Save<T1>::perform(&(p._1()))); v.insert("field2", sad::db::Save<T2>::perform(&(p._2()))); v.insert("field3", sad::db::Save<T2>::perform(&(p._3()))); return v; } }; /*! Specification for saving quadruplet */ template<typename T1, typename T2, typename T3, typename T4> class Save<sad::Quadruplet<T1, T2, T3, T4> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); sad::Quadruplet<T1, T2, T3, T4> & p = *(static_cast<sad::Quadruplet<T1, T2, T3, T4> *>(ptr)); picojson::value v(picojson::object_type, false); v.insert("field1", sad::db::Save<T1>::perform(&(p._1()))); v.insert("field2", sad::db::Save<T2>::perform(&(p._2()))); v.insert("field3", sad::db::Save<T2>::perform(&(p._3()))); v.insert("field4", sad::db::Save<T2>::perform(&(p._4()))); return v; } }; /*! Specification for saving quadruplet */ template<typename T> class Save<sad::Vector<T> > { public: /*! Saves a value of specified type \param[in] ptr a value to be saved */ static picojson::value perform(void * ptr) { if (!ptr) throw sad::db::InvalidPointer(); const sad::Vector<T> & p = *(static_cast<sad::Vector<T> *>(ptr)); picojson::value v(picojson::array_type, false); for(size_t i = 0; i < p.size(); i++) { const void* vpi = &(p[i]); void* pi = const_cast<void*>(vpi); v.push_back(sad::db::Save<T>::perform(pi)); } return v; } }; } }
35,389
https://github.com/MilitaryIntelligence6/TerraLegion/blob/master/res/shaders/invert.fsh
Github Open Source
Open Source
MIT
2,022
TerraLegion
MilitaryIntelligence6
GLSL
Code
41
129
#ifdef GL_ES precision mediump float; #endif varying vec4 v_color; varying vec2 v_texCoord0; uniform sampler2D u_sampler2D; void main() { vec4 color = v_color * texture2D(u_sampler2D, v_texCoord0); color = vec4(1 - color.x, 1 - color.y, 1 - color.z, color.a); gl_FragColor = color; }
25,874
https://github.com/roscopecoltran/SniperKit-Core/blob/master/.References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/face/drishti_face.h
Github Open Source
Open Source
MIT
null
SniperKit-Core
roscopecoltran
C
Code
57
189
/*! @file drishti_face.h @author David Hirvonen @brief Declaration of drishti face namespace \copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved. \license{This project is released under the 3 Clause BSD License.} */ #ifndef __drishti_face_drishti_face_h__ #define __drishti_face_drishti_face_h__ // clang-format off #define DRISHTI_FACE_NAMESPACE_BEGIN namespace drishti { namespace face { #define DRISHTI_FACE_NAMESPACE_END } } // clang-format on #define DRISHTI_FACE drishti::face #endif
10,030
https://github.com/l1228911525/sem-spring/blob/master/sem-spring-aop/src/main/java/org/semspringframework/aop/framework/BeanMethodInterceptor.java
Github Open Source
Open Source
Apache-2.0
2,021
sem-spring
l1228911525
Java
Code
123
413
package org.semspringframework.aop.framework; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; /** * the concrete realization of the proxy class */ public class BeanMethodInterceptor implements MethodInterceptor { private List<BeanAdvice> beanAdviceList = new LinkedList<>(); @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { // run pre-enhanced method for (BeanAdvice beanAdvice : beanAdviceList) { List<Method> beforeMethods = beanAdvice.getBeforeMethod(); for (Method beforeMethod : beforeMethods) { beforeMethod.invoke(beanAdvice.getAdviceObj()); } } // proxyed bean method Object o = methodProxy.invokeSuper(obj, args); // run post-enhanced method for (BeanAdvice beanAdvice : beanAdviceList) { List<Method> afterMethods = beanAdvice.getAfterMethod(); for (Method afterMethod : afterMethods) { afterMethod.invoke(beanAdvice.getAdviceObj()); } } return o; } public List<BeanAdvice> getBeanAdviceList() { return beanAdviceList; } public void setBeanAdviceList(List<BeanAdvice> beanAdviceList) { this.beanAdviceList = beanAdviceList; } }
3,679
https://github.com/YuriiHoliuk/mateacademy-react-test-task/blob/master/src/utils/case-formatter.js
Github Open Source
Open Source
MIT
null
mateacademy-react-test-task
YuriiHoliuk
JavaScript
Code
151
403
const Cases = { KebabCase: 'kebab', CamelCase: 'camel', SnakeCase: 'snake', NormalCase: 'normal', }; /** * Has static methods for transforming strings from one case to another * * TODO: implements rest methods * */ export class CaseFormatter { /** * Determines case type of string * * @param {string} word * * @return {string} ```'kebab' | 'camel' | 'snake' | 'normal'``` * */ static getCase(word) { if (/ /.test(word)) { return Cases.NormalCase; } else if (/-/.test(word)) { return Cases.KebabCase; } else if (/[A-Z]/.test(word)) { return Cases.CamelCase; } else if (/_/.test(word)) { return Cases.SnakeCase; } } /** * Convert camelCase to normal Case * * @param {string} word * @param {boolean} capitalize capitalize first letter if true (default = true) * * @return {string} * */ static camelToNormal(word, capitalize = true) { const withSpaces = word.replace(/([A-Z])+/g, ' $1'); return capitalize ? withSpaces.replace(/^[a-z]/, (res) => res.toUpperCase()) : withSpaces; } } CaseFormatter.Cases = Cases;
43,804
https://github.com/jaeykim/DDL-simulator/blob/master/client.py
Github Open Source
Open Source
MIT
null
DDL-simulator
jaeykim
Python
Code
611
2,327
import torch.optim as optim import torch.nn.functional as F import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms import os.path import os from utils import recursive_mkdir from net import Net class Client: def __init__(self, trainset, testset, net, _id=None, # TODO: multiple GPU ): self.trainset = trainset if self.trainset is not None: self.trainloader = torch.utils.data.DataLoader(dataset=self.trainset, batch_size=4, shuffle=True, num_workers=2) self.testset = testset if self.testset is not None: self.testloader = torch.utils.data.DataLoader(dataset=self.testset, batch_size=4, shuffle=False, num_workers=2) self.net = net self.criterion = nn.CrossEntropyLoss() self.optimizer = optim.SGD(self.net.parameters(), lr=0.001, momentum=0.9) assert(_id != None) self._id = _id # TODO: assert error, global_id self.PATH = "clients/" + str(self._id) + "/" # TODO: the other PATH for log recursive_mkdir(self.PATH) """ML""" def set_dataset(self, trainset, testset): # TODO: not None self.trainset = trainset self.trainloader = torch.utils.data.DataLoader(dataset=self.trainset, batch_size=4, shuffle=True, num_workers=2) self.testset = testset self.testloader = torch.utils.data.DataLoader(dataset=self.testset, batch_size=4, shuffle=False, num_workers=2) def train(self, r: int, epochs: int = 1, logs: int = 2000, log_flag=False): for epoch in range(epochs): # 데이터셋을 수차례 반복합니다. running_loss = 0.0 for i, data in enumerate(self.trainloader, 0): # [inputs, labels]의 목록인 data로부터 입력을 받은 후; inputs, labels = data # inputs, labels = data[0].to(device), data[1].to(device) # TODO: GPU # 변화도(Gradient) 매개변수를 0으로 만들고 self.optimizer.zero_grad() # 순전파 + 역전파 + 최적화를 한 후 outputs = self.net(inputs) loss = self.criterion(outputs, labels) loss.backward() self.optimizer.step() # 통계를 출력합니다. if log_flag: running_loss += loss.item() if i % logs == logs - 1: # print every 2000 mini-batches # print('[%d, %5d] loss: %.3f' % # (epoch + 1, i + 1, running_loss / logs)) name = "train_loss_" + str(r) + "_" + str(epoch) + "_" + str(i) + ".log" self.log(name, running_loss / logs) running_loss = 0.0 def save_net(self): name = self.PATH + "cifar_net_" + str(self._id) + ".pth" torch.save(self.net.state_dict(), name) def load_net(self): name = self.PATH + "cifar_net_" + str(self._id) + ".pth" if os.path.isfile(name): print("Load net:", name) self.net.load_state_dict(torch.load(name)) else: print("Pre-trained net does not exist") def eval(self, r: int, log_flag=False): correct = 0 total = 0 loss = 0 with torch.no_grad(): for data in self.testloader: images, labels = data outputs = self.net(images) # loss += self.criterion(outputs, labels).item() _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() # print('Accuracy of the network on the 10000 test images: %d %%' % ( # 100 * correct / total)) # name = "test_loss_" + str(r) + ".log" # self.log(name, loss / total) # TODO: check acc = 100 * correct / total if log_flag: name = "test_acc_" + str(r) + ".log" self.log(name, acc) return acc def predict(self): pass def get_weights(self): # return self.net.state_dict() params = self.net.named_parameters() dict_params = dict(params) return dict_params def set_weights(self, params): # self.net.load_state_dict(state_dict) my_params = self.net.named_parameters() dict_my_params = dict(my_params) for name, param in params.items(): if name in dict_my_params: dict_my_params[name].data.copy_(param.data) self.net.load_state_dict(dict_my_params) def average_weights(self): pass def set_average_weights(self, paramses: list, repus: list): # TODO: norm. my_params = self.net.named_parameters() dict_my_params = dict(my_params) # set zeros for name in paramses[0].keys(): if name in dict_my_params: dict_my_params[name].data.zero_() for i, repu in enumerate(repus): params = paramses[i] for name, param in params.items(): if name in dict_my_params: dict_my_params[name].data.add_(repu * param.data) self.net.load_state_dict(dict_my_params) """DAG""" def select_node(self): pass def test_node(self): pass def create_node(self): pass """Vis""" def log(self, name: str, data): with open(self.PATH + name, "w") as f: f.write("%f" % data) if __name__ == "__main__": """Preprocess""" transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) # print(len(trainset)) # 50000 # print(len(testset)) # 10000 """random split""" splited_trainset = torch.utils.data.random_split(trainset, [15000, 25000, 10000]) splited_testset = torch.utils.data.random_split(testset, [2000, 6000, 2000]) # print(len(splited_trainset[0]), len(splited_trainset[1]), len(splited_trainset[2])) clients = [] for i in range(3): clients.append(Client( trainset=splited_trainset[i], testset=splited_testset[i], net=Net(), _id=i )) clients[0].train(r=0, epochs=1) clients[1].set_weights(clients[0].get_weights()) clients[2].set_weights(clients[0].get_weights()) clients[0].eval(r=0) clients[1].eval(r=0) clients[2].eval(r=0) clients[0].set_average_weights( [clients[1].get_weights(), clients[2].get_weights()], [0.9, 0.1]) clients[0].eval(r=1) clients[1].eval(r=1) clients[2].eval(r=1)
43,219
https://github.com/vnopenroads/openroads-vn-tiler/blob/master/scripts/districts.sql
Github Open Source
Open Source
MIT
null
openroads-vn-tiler
vnopenroads
SQL
Code
26
89
-- Dump all districts as line delimeted GeoJSON features. \copy (SELECT JSONB_BUILD_OBJECT('type', 'Feature', 'geometry', ST_AsGEOJSON(geom)::JSONB, 'properties', JSONB_BUILD_OBJECT('id', id, 'type', type)) FROM admin_boundaries WHERE type='district') to .tmp/districts.json
40,882
https://github.com/Sagiri/dawn-stone/blob/master/constants.s
Github Open Source
Open Source
0BSD
null
dawn-stone
Sagiri
GAS
Code
6
21
MON_DATA_HELD_ITEM equ 0xC EVO_ITEM equ 7
26,087
https://github.com/kelvinluime/hkn-member-portal/blob/master/src/services/api/apis/EventApi.ts
Github Open Source
Open Source
MIT
2,020
hkn-member-portal
kelvinluime
TypeScript
Code
1,717
5,798
/* tslint:disable */ /* eslint-disable */ /** * HKN API * HKN API * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import * as runtime from '../runtime'; import { AppUserEventRequest, AppUserEventRequestFromJSON, AppUserEventRequestToJSON, AttendanceCheckOffRequest, AttendanceCheckOffRequestFromJSON, AttendanceCheckOffRequestToJSON, AttendanceResponse, AttendanceResponseFromJSON, AttendanceResponseToJSON, EventRequest, EventRequestFromJSON, EventRequestToJSON, EventResponse, EventResponseFromJSON, EventResponseToJSON, MultipleAttendanceResponse, MultipleAttendanceResponseFromJSON, MultipleAttendanceResponseToJSON, MultipleEventResponse, MultipleEventResponseFromJSON, MultipleEventResponseToJSON, MultipleRSVPResponse, MultipleRSVPResponseFromJSON, MultipleRSVPResponseToJSON, RSVPResponse, RSVPResponseFromJSON, RSVPResponseToJSON, } from '../models'; export interface EventControllerAffiliateEventRSVPRequest { eventID: number; } export interface EventControllerAffiliateEventSigninRequest { eventID: number; } export interface EventControllerCheckOffEventAttendanceRequest { eventID: number; attendanceCheckOffRequest?: AttendanceCheckOffRequest; } export interface EventControllerCreateEventRequest { eventRequest?: EventRequest; } export interface EventControllerDeleteEventRequest { eventID: number; } export interface EventControllerGetEventRequest { eventID: number; } export interface EventControllerGetEventAttendanceRequest { eventID: number; unchecked?: boolean; inductee?: boolean; } export interface EventControllerGetEventRSVPRequest { eventID: number; } export interface EventControllerGetMultipleEventsRequest { pending?: boolean; ready?: boolean; complete?: boolean; } export interface EventControllerRsvpForEventRequest { eventID: number; appUserEventRequest?: AppUserEventRequest; } export interface EventControllerSignInToEventRequest { eventID: number; appUserEventRequest?: AppUserEventRequest; } export interface EventControllerUpdateEventRequest { eventID: number; eventRequest?: EventRequest; } /** * */ export class EventApi extends runtime.BaseAPI { /** * Affiliate event rsvp */ async eventControllerAffiliateEventRSVPRaw( requestParameters: EventControllerAffiliateEventRSVPRequest ): Promise<runtime.ApiResponse<RSVPResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerAffiliateEventRSVP.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/rsvp/affiliate`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => RSVPResponseFromJSON(jsonValue) ); } /** * Affiliate event rsvp */ async eventControllerAffiliateEventRSVP( requestParameters: EventControllerAffiliateEventRSVPRequest ): Promise<RSVPResponse> { const response = await this.eventControllerAffiliateEventRSVPRaw( requestParameters ); return await response.value(); } /** * Affiliate event signin */ async eventControllerAffiliateEventSigninRaw( requestParameters: EventControllerAffiliateEventSigninRequest ): Promise<runtime.ApiResponse<AttendanceResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerAffiliateEventSignin.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/signin/affiliate`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => AttendanceResponseFromJSON(jsonValue) ); } /** * Affiliate event signin */ async eventControllerAffiliateEventSignin( requestParameters: EventControllerAffiliateEventSigninRequest ): Promise<AttendanceResponse> { const response = await this.eventControllerAffiliateEventSigninRaw( requestParameters ); return await response.value(); } /** * Check off event attendance */ async eventControllerCheckOffEventAttendanceRaw( requestParameters: EventControllerCheckOffEventAttendanceRequest ): Promise<runtime.ApiResponse<AttendanceResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerCheckOffEventAttendance.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/attendance`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, body: AttendanceCheckOffRequestToJSON( requestParameters.attendanceCheckOffRequest ), }); return new runtime.JSONApiResponse(response, jsonValue => AttendanceResponseFromJSON(jsonValue) ); } /** * Check off event attendance */ async eventControllerCheckOffEventAttendance( requestParameters: EventControllerCheckOffEventAttendanceRequest ): Promise<AttendanceResponse> { const response = await this.eventControllerCheckOffEventAttendanceRaw( requestParameters ); return await response.value(); } /** * Create event */ async eventControllerCreateEventRaw( requestParameters: EventControllerCreateEventRequest ): Promise<runtime.ApiResponse<EventResponse>> { const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/`, method: 'POST', headers: headerParameters, query: queryParameters, body: EventRequestToJSON(requestParameters.eventRequest), }); return new runtime.JSONApiResponse(response, jsonValue => EventResponseFromJSON(jsonValue) ); } /** * Create event */ async eventControllerCreateEvent( requestParameters: EventControllerCreateEventRequest ): Promise<EventResponse> { const response = await this.eventControllerCreateEventRaw( requestParameters ); return await response.value(); } /** * Delete event */ async eventControllerDeleteEventRaw( requestParameters: EventControllerDeleteEventRequest ): Promise<runtime.ApiResponse<EventResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerDeleteEvent.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'DELETE', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => EventResponseFromJSON(jsonValue) ); } /** * Delete event */ async eventControllerDeleteEvent( requestParameters: EventControllerDeleteEventRequest ): Promise<EventResponse> { const response = await this.eventControllerDeleteEventRaw( requestParameters ); return await response.value(); } /** * Get event */ async eventControllerGetEventRaw( requestParameters: EventControllerGetEventRequest ): Promise<runtime.ApiResponse<EventResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerGetEvent.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; const response = await this.request({ path: `/api/events/{eventID}`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => EventResponseFromJSON(jsonValue) ); } /** * Get event */ async eventControllerGetEvent( requestParameters: EventControllerGetEventRequest ): Promise<EventResponse> { const response = await this.eventControllerGetEventRaw(requestParameters); return await response.value(); } /** * Get event attendance */ async eventControllerGetEventAttendanceRaw( requestParameters: EventControllerGetEventAttendanceRequest ): Promise<runtime.ApiResponse<MultipleAttendanceResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerGetEventAttendance.' ); } const queryParameters: any = {}; if (requestParameters.unchecked !== undefined) { queryParameters['unchecked'] = requestParameters.unchecked; } if (requestParameters.inductee !== undefined) { queryParameters['inductee'] = requestParameters.inductee; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/attendance`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => MultipleAttendanceResponseFromJSON(jsonValue) ); } /** * Get event attendance */ async eventControllerGetEventAttendance( requestParameters: EventControllerGetEventAttendanceRequest ): Promise<MultipleAttendanceResponse> { const response = await this.eventControllerGetEventAttendanceRaw( requestParameters ); return await response.value(); } /** * Get event rsvp */ async eventControllerGetEventRSVPRaw( requestParameters: EventControllerGetEventRSVPRequest ): Promise<runtime.ApiResponse<MultipleRSVPResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerGetEventRSVP.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/rsvp`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => MultipleRSVPResponseFromJSON(jsonValue) ); } /** * Get event rsvp */ async eventControllerGetEventRSVP( requestParameters: EventControllerGetEventRSVPRequest ): Promise<MultipleRSVPResponse> { const response = await this.eventControllerGetEventRSVPRaw( requestParameters ); return await response.value(); } /** * Get multiple events */ async eventControllerGetMultipleEventsRaw( requestParameters: EventControllerGetMultipleEventsRequest ): Promise<runtime.ApiResponse<MultipleEventResponse>> { const queryParameters: any = {}; if (requestParameters.pending !== undefined) { queryParameters['pending'] = requestParameters.pending; } if (requestParameters.ready !== undefined) { queryParameters['ready'] = requestParameters.ready; } if (requestParameters.complete !== undefined) { queryParameters['complete'] = requestParameters.complete; } const headerParameters: runtime.HTTPHeaders = {}; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/`, method: 'GET', headers: headerParameters, query: queryParameters, }); return new runtime.JSONApiResponse(response, jsonValue => MultipleEventResponseFromJSON(jsonValue) ); } /** * Get multiple events */ async eventControllerGetMultipleEvents( requestParameters: EventControllerGetMultipleEventsRequest ): Promise<MultipleEventResponse> { const response = await this.eventControllerGetMultipleEventsRaw( requestParameters ); return await response.value(); } /** * Rsvp for event */ async eventControllerRsvpForEventRaw( requestParameters: EventControllerRsvpForEventRequest ): Promise<runtime.ApiResponse<RSVPResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerRsvpForEvent.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/rsvp`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, body: AppUserEventRequestToJSON(requestParameters.appUserEventRequest), }); return new runtime.JSONApiResponse(response, jsonValue => RSVPResponseFromJSON(jsonValue) ); } /** * Rsvp for event */ async eventControllerRsvpForEvent( requestParameters: EventControllerRsvpForEventRequest ): Promise<RSVPResponse> { const response = await this.eventControllerRsvpForEventRaw( requestParameters ); return await response.value(); } /** * Sign in to event */ async eventControllerSignInToEventRaw( requestParameters: EventControllerSignInToEventRequest ): Promise<runtime.ApiResponse<AttendanceResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerSignInToEvent.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}/signin`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, body: AppUserEventRequestToJSON(requestParameters.appUserEventRequest), }); return new runtime.JSONApiResponse(response, jsonValue => AttendanceResponseFromJSON(jsonValue) ); } /** * Sign in to event */ async eventControllerSignInToEvent( requestParameters: EventControllerSignInToEventRequest ): Promise<AttendanceResponse> { const response = await this.eventControllerSignInToEventRaw( requestParameters ); return await response.value(); } /** * Update event */ async eventControllerUpdateEventRaw( requestParameters: EventControllerUpdateEventRequest ): Promise<runtime.ApiResponse<EventResponse>> { if ( requestParameters.eventID === null || requestParameters.eventID === undefined ) { throw new runtime.RequiredError( 'eventID', 'Required parameter requestParameters.eventID was null or undefined when calling eventControllerUpdateEvent.' ); } const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; headerParameters['Content-Type'] = 'application/json'; if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; const tokenString = typeof token === 'function' ? token('TokenAuth', []) : token; if (tokenString) { headerParameters['Authorization'] = `Bearer ${tokenString}`; } } const response = await this.request({ path: `/api/events/{eventID}`.replace( `{${'eventID'}}`, encodeURIComponent(String(requestParameters.eventID)) ), method: 'POST', headers: headerParameters, query: queryParameters, body: EventRequestToJSON(requestParameters.eventRequest), }); return new runtime.JSONApiResponse(response, jsonValue => EventResponseFromJSON(jsonValue) ); } /** * Update event */ async eventControllerUpdateEvent( requestParameters: EventControllerUpdateEventRequest ): Promise<EventResponse> { const response = await this.eventControllerUpdateEventRaw( requestParameters ); return await response.value(); } }
13,289
https://github.com/philipsorst/example.wicket.authroles-spring-security-hibernate.java/blob/master/src/main/java/net/dontdrinkandroot/example/wassh/wicket/page/HomePage.java
Github Open Source
Open Source
Apache-2.0
null
example.wicket.authroles-spring-security-hibernate.java
philipsorst
Java
Code
29
123
package net.dontdrinkandroot.example.wassh.wicket.page; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; /** * @author Philip Washington Sorst <philip@sorst.net> */ public class HomePage extends DecoratorPage<Void> { @Override protected IModel<String> getTitleModel() { return Model.of("HomePage"); } }
10,618
https://github.com/AP2021Fall/Project-team-01/blob/master/Jira/src/main/java/view/PendingOptionsGraphics.java
Github Open Source
Open Source
MIT
null
Project-team-01
AP2021Fall
Java
Code
48
232
package view; import controller.MainMenuController; import javafx.event.ActionEvent; import java.sql.SQLException; public class PendingOptionsGraphics { public SceneController sceneController = new SceneController(); public void accept(ActionEvent actionEvent) throws SQLException { MainMenuController.acceptTeams(MainMenuController.pendingTeam.split(" ")); sceneController.switchScene(MenusFxml.PENDING_TEAMS.getLabel()); } public void reject(ActionEvent actionEvent) throws SQLException { MainMenuController.rejectTeams(MainMenuController.pendingTeam.split(" ")); sceneController.switchScene(MenusFxml.PENDING_TEAMS.getLabel()); } public void back(ActionEvent actionEvent) { sceneController.switchScene(MenusFxml.PENDING_TEAMS.getLabel()); } }
41,280
https://github.com/lucasrcdias/controle-pontos/blob/master/db/migrate/20160307103242_create_periods.rb
Github Open Source
Open Source
MIT
2,016
controle-pontos
lucasrcdias
Ruby
Code
28
99
class CreatePeriods < ActiveRecord::Migration def change create_table :periods do |t| t.time :start_at t.time :finish_at t.time :interval_start t.time :interval_finish t.belongs_to :company, index: true t.timestamps null: false end end end
216
https://github.com/clockzhong/WrapLAMP/blob/master/Mysql/storage/ndb/include/kernel/signaldata/DictSignal.hpp
Github Open Source
Open Source
Apache-2.0
2,015
WrapLAMP
clockzhong
C++
Code
550
1,348
/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef DICT_SIGNAL_HPP #define DICT_SIGNAL_HPP #include <Bitmask.hpp> #define JAM_FILE_ID 187 struct DictSignal { // DICT transaction and operation REQs include Uint32 requestInfo // implementation signals have only requestType // requestInfo format should be as follows // byte 0: requestType (usually enum) static Uint32 getRequestType(const Uint32& info) { return BitmaskImpl::getField(1, &info, 0, 8); } static void setRequestType(Uint32& info, Uint32 val) { assert(val < (1 << 8)); BitmaskImpl::setField(1, &info, 0, 8, val); } // byte 1: extra case-dependent usage within DICT static Uint32 getRequestExtra(const Uint32& info) { return BitmaskImpl::getField(1, &info, 8, 8); } static void setRequestExtra(Uint32& info, Uint32 val) { assert(val < (1 << 8)); BitmaskImpl::setField(1, &info, 8, 8, val); } static void addRequestExtra(Uint32& dst_info, const Uint32& src_info) { Uint32 val = getRequestExtra(src_info); setRequestExtra(dst_info, val); } // byte 2: global flags: passed everywhere // byte 3: local flags: consumed by current op private: // flag bits are defined relative to entire requestInfo word enum { RequestFlagsMask = 0xffff0000 }; enum { RequestFlagsGlobalMask = 0x00ff0000 }; public: enum RequestFlags { // global /* * This node is transaction coordinator and the only participant. * Used by node doing NR to activate each index. */ RF_LOCAL_TRANS = (1 << 16), /* * Activate index but do not build it. On SR, the build is done * in a later start phase (for non-logged index). On NR, the build * on this node takes place automatically during data copy. */ RF_NO_BUILD = (1 << 17) }; static void addRequestFlags(Uint32& dst_info, const Uint32& src_info) { dst_info |= src_info & RequestFlagsMask; } static void addRequestFlagsGlobal(Uint32& dst_info, const Uint32& src_info) { dst_info |= src_info & RequestFlagsGlobalMask; } static const char* getRequestFlagsText(const Uint32& info) { static char buf[100]; buf[0] = buf[1] = 0; if (info & RF_LOCAL_TRANS) strcat(buf, " LOCAL_TRANS"); if (info & RF_NO_BUILD) strcat(buf, " NO_BUILD"); return &buf[1]; } static const char* getRequestInfoText(const Uint32& info) { static char buf[100]; sprintf(buf, "type: %u extra: %u flags: %s", getRequestType(info), (info >> 8) & 0xff, getRequestFlagsText(info)); return buf; } // these match Dbdict.hpp static const char* getTransModeName(Uint32 val) { static const char* name[] = { "Undef", "Normal", "Rollback", "Abort" }; Uint32 size = sizeof(name)/sizeof(name[0]); return val < size ? name[val] : "?"; } static const char* getTransPhaseName(Uint32 val) { static const char* name[] = { "Undef", "Begin", "Parse", "Prepare", "Commit", "Complete", "End" }; Uint32 size = sizeof(name)/sizeof(name[0]); return val < size ? name[val] : "?"; } static const char* getTransStateName(Uint32 val) { static const char* name[] = { "Undef", "Ok", "Error", "NodeFail", "NeedTrans", "NoTrans", "NeedOp", "NoOp" }; Uint32 size = sizeof(name)/sizeof(name[0]); return val < size ? name[val] : "?"; } }; #undef JAM_FILE_ID #endif
8,790
https://github.com/slawekjaranowski/artifactory-cleaner/blob/master/src/main/java/com/payu/artifactory/tools/snapshot/SnapshotCleaner.java
Github Open Source
Open Source
Apache-2.0
2,019
artifactory-cleaner
slawekjaranowski
Java
Code
351
1,315
/* * Copyright 2019 PayU * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.payu.artifactory.tools.snapshot; import io.github.resilience4j.retry.Retry; import io.vavr.control.Try; import lombok.extern.slf4j.Slf4j; import org.apache.maven.artifact.versioning.ComparableVersion; import org.jfrog.artifactory.client.Artifactory; import org.jfrog.artifactory.client.ArtifactoryRequest; import org.jfrog.artifactory.client.impl.ArtifactoryRequestImpl; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @Slf4j public class SnapshotCleaner { private static final String SNAPSHOT = "-SNAPSHOT"; private final Artifactory artifactory; private final Retry retry; private final String snapshotRepo; private final String releaseRepo; public SnapshotCleaner(Artifactory artifactory, Retry retry, String snapshotRepo, String releaseRepo) { Objects.requireNonNull(artifactory, "artifactory must be set"); Objects.requireNonNull(retry, "retry must be set"); this.artifactory = artifactory; this.retry = retry; this.snapshotRepo = snapshotRepo; this.releaseRepo = releaseRepo; } public void execute() { String itemsQuery = getItemsQuery(); LOGGER.info("Finding maven items with query: {}", itemsQuery); ArtifactoryRequest request = new ArtifactoryRequestImpl() .method(ArtifactoryRequest.Method.POST) .apiUrl("api/search/aql") .requestType(ArtifactoryRequest.ContentType.TEXT) .responseType(ArtifactoryRequest.ContentType.JSON) .requestBody(itemsQuery); AQLItems items = Try.of( Retry.decorateCheckedSupplier( retry, () -> artifactory .restCall(request) .parseBody(AQLItems.class) ) ).get(); Map<String, List<String>> pv = items.getResults().stream().collect( Collectors.groupingBy(AQLItem::getPath, Collectors.mapping(AQLItem::getVersion, Collectors.toList())) ); pv.replaceAll((k, v) -> getSnapshotsToDelete(v)); pv.entrySet().stream().forEach(e -> deleteSnapshots(e.getKey(), e.getValue())); } private static List<String> getSnapshotsToDelete(List<String> input) { List<String> result = null; Optional<ComparableVersion> newestRelease = input.stream() .filter(c -> !c.endsWith(SNAPSHOT)) .max((v1, v2) -> new ComparableVersion(v1).compareTo(new ComparableVersion(v2))) .map(s -> new ComparableVersion(s)); if (newestRelease.isPresent()) { ComparableVersion newest = newestRelease.get(); result = input.stream() .filter(c -> c.endsWith(SNAPSHOT) && newest.compareTo(new ComparableVersion(c)) > 0) .collect(Collectors.toList()); } else { result = Collections.emptyList(); } return result; } private String getItemsQuery() { StringBuilder result = new StringBuilder(100); result.append("items.find({"); if (snapshotRepo.equals(releaseRepo)) { result.append("\"repo\":\"").append(snapshotRepo).append('"'); } else { result.append("\"$or\":[{\"repo\":\"").append(snapshotRepo); result.append("\",\"repo\":\"").append(releaseRepo); result.append("\"}]"); } result.append(",\"name\":{\"$match\":\"*.pom\"}}).include(\"repo\",\"path\",\"name\")"); return result.toString(); } private void deleteSnapshots(String path, List<String> versions) { for (String version: versions) { String fp = path + "/" + version; LOGGER.info("Delete: {}/{}", snapshotRepo, fp); artifactory.repository(snapshotRepo).delete(fp); } } }
27,057
https://github.com/matiboux/discord-mel/blob/master/src/config/Options.ts
Github Open Source
Open Source
MIT
2,021
discord-mel
matiboux
TypeScript
Code
86
228
import IOptions from './IOptions' import Logger from '../logger/Logger' import unserialize from '../functions/unserialize' import IConfig from './IConfig' class Options implements IOptions { [x: string]: any public absPath: string = __dirname public token?: string public config?: IConfig public configPath?: string public configFile?: string public logger?: Logger public logPath?: string public logFile?: string public logLevel?: string public statePath?: string public stateFile?: string public translationsDir?: string public defaultLanguage?: string public commandsDir?: string public prefix?: string public constructor(...optionsArray: IOptions[]) { optionsArray.forEach(options => { unserialize(this, options) }) } } export default Options
49,309
https://github.com/viridi19/covimath-front/blob/master/src/views/Dashboard/components/GlobalMapCard/components/SearchAutoComplete/index.js
Github Open Source
Open Source
MIT
2,020
covimath-front
viridi19
JavaScript
Code
177
614
// *https://www.registers.service.gov.uk/registers/country/use-the-api* import React from 'react'; import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/Autocomplete'; import CircularProgress from '@material-ui/core/CircularProgress'; function sleep(delay = 0) { return new Promise((resolve) => { setTimeout(resolve, delay); }); } export default function Asynchronous() { const [open, setOpen] = React.useState(false); const [options, setOptions] = React.useState([]); const loading = open && options.length === 0; React.useEffect(() => { let active = true; if (!loading) { return undefined; } (async () => { const response = await fetch('https://country.register.gov.uk/records.json?page-size=5000'); await sleep(1e3); // For demo purposes. const countries = await response.json(); if (active) { setOptions(Object.keys(countries).map((key) => countries[key].item[0])); } })(); return () => { active = false; }; }, [loading]); React.useEffect(() => { if (!open) { setOptions([]); } }, [open]); return ( <Autocomplete id="asynchronous-demo" fullWidth style={{ width: 300 }} open={open} onOpen={() => { setOpen(true); }} onClose={() => { setOpen(false); }} getOptionSelected={(option, value) => option.name === value.name} getOptionLabel={(option) => option.name} options={options} loading={loading} renderInput={(params) => ( <TextField fullWidth {...params} label="Asynchronous" variant="outlined" InputProps={{ ...params.InputProps, endAdornment: ( <React.Fragment> {loading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </React.Fragment> ), }} /> )} /> ); }
9,483
https://github.com/Tubt/gooddata-ui-sdk/blob/master/libs/sdk-ui-kit/src/typings.d.ts
Github Open Source
Open Source
MIT
2,020
gooddata-ui-sdk
Tubt
TypeScript
Code
20
60
// (C) 2020 GoodData Corporation declare module "react-native-listener"; declare module "@gooddata/goodstrap/lib/core/immutable" { export function propsEqual(props: any, nextProps: any): boolean; }
12,878
https://github.com/LuizFernandesOliveira/java-cli-codenation-fibonacci/blob/master/DesafioApplication.java
Github Open Source
Open Source
MIT
null
java-cli-codenation-fibonacci
LuizFernandesOliveira
Java
Code
104
326
import java.util.ArrayList; import java.util.List; public class DesafioApplication { ArrayList<Integer> listFibonacci = new ArrayList<>(); private void addNumber(int number) { this.listFibonacci.add(number); } private void generator(int value) { int f1, f2 = 0, f3; for (f3 = 1; f2 <= value; f3 = f1 + f2) { this.addNumber(f2); f1 = f2; f2 = f3; } this.addNumber(f2); } public List<Integer> getNumbers(int value) { generator(value); return this.listFibonacci; } public static List<Integer> fibonacci() { DesafioApplication fibonacci = new DesafioApplication(); return fibonacci.getNumbers(350); } public static Boolean isFibonacci(Integer a) { DesafioApplication fibonacci = new DesafioApplication(); for (Integer number : fibonacci.getNumbers(a)) { if (a.equals(number)) { return true; } } return false; } }
26,811
https://github.com/kmisrano/butiran/blob/master/zpp/bneast/run.sh
Github Open Source
Open Source
MIT
2,019
butiran
kmisrano
Shell
Code
241
687
# # Run asteroids-collapse related program and script # # Sparisoma Viridi | dudung@fi.itb.ac.id # # Execute: ./run # # 20160427 # Create this script for asteroids-collapse program. # # Define script name sname="run.sh" # Verbose usage if [ $# -lt 3 ] then echo "Usage: $name [inum fnum digit]" echo -e "inum\tinitial number" echo -e "fnum\tfinal number" echo -e "digit\tnumber of digit" exit fi # Get arguments inum=$1 fnum=$2 digit=$3 # Set format of number sequence format="%0.$digit""i" # Check existing txt files and remove them txt=($(ls *.txt)) Ntxt=${#txt[@]} echo "Removing" for (( i=0; i<=$Ntxt; i++ )) do n=$(printf $format $i) txtfile="$n.txt" if [ -f $txtfile ] then echo "$txtfile" rm "$txtfile" fi done echo # Check existing png files and remove them png=($(ls *.png)) Npng=${#png[@]} echo "Removing" for (( i=0; i<=$Npng; i++ )) do n=$(printf $format $i) pngfile="$n.png" if [ -f $pngfile ] then echo "$pngfile" rm "$pngfile" fi done echo # Define executable cmd1="./asteroids-collapse" cmd2="./txt2png.sh" # Prepare initial data cp particles.data 0000.txt # Generate number sequence and execute other script echo "Creating" for(( i=inum; i<fnum; i++ )) do # Generate number sequence n1=$(printf $format $i) j=$(expr $i + 1) n2=$(printf $format $j) # Create related filenames itxt="$n1.txt" ftxt="$n2.txt" ipng="$n1.png" fpng="$n2.png" # Perform simulation $cmd1 $itxt $ftxt echo -n $itxt" " # Draw particles position $cmd2 $itxt echo $ipng done # Draw last particles position $cmd2 $ftxt echo -n $ftxt" " echo $fpng # Make gif file convert *.png data.gif
23,828
https://github.com/poncele1/RSS_Sinatra/blob/master/app/app.rb
Github Open Source
Open Source
MIT
null
RSS_Sinatra
poncele1
Ruby
Code
224
620
require 'sinatra' require 'sinatra/base' require 'sinatra/activerecord' require './config/environments' require 'sinatra/flash' require 'sinatra/redirect_with_flash' require 'rss' class Post < ActiveRecord::Base validates :title, presence: true, length: { minimum: 5 } validates :body, presence: true end # nodoc class App < Sinatra::Base register Sinatra::Flash helpers Sinatra::RedirectWithFlash #allow for sessions to save state in a client-local cookie enable :sessions #enable modular application to actually send delete and put requests in browsers that don't understand these REST methods enable :method_override helpers do def title if @title "#{@title}" else "Welcome." end end end helpers do include Rack::Utils alias_method :h, :escape_html end module RssItems RSS_ITEMS = RSS::Parser.parse('https://news.ycombinator.com/rss', false) end # get all posts get '/' do @posts = Post.order("created_at DESC") @title = "Welcome." erb :"posts/index" end # create new post get "/posts/create" do @title = "Create post" @post = Post.new erb :"posts/create" end post "/posts" do @post = Post.new(params[:post]) if @post.save redirect "/", :notice => 'Congrats! New favorite added. (This message will vanish in 4 seconds.)' else redirect "posts/create", :error => 'Something went wrong. Title and URL must both not be empty. (This message will vanish in 4 seconds.)' end end # view post get "/posts/:id" do @post = Post.find(params[:id]) @title = @post.title erb :"posts/view" end # delete post get "/posts/:id/delete" do @post = Post.find(params[:id]) @title = "Delete Form" erb :"posts/delete" end delete "/posts/:id" do @post = Post.delete(params[:id]) redirect "/" end end
18,197
https://github.com/falmar/react-admin-lte/blob/master/src/components/ContentWrapper/__tests__/content-test.js
Github Open Source
Open Source
MIT
2,018
react-admin-lte
falmar
JavaScript
Code
93
279
import React from 'react' import {shallow} from 'enzyme' import Content from '../Content' describe('Content Content', () => { it('should be a <section> element', () => { const wrapper = shallow(<Content />) expect( wrapper.is('section') ).toBeTruthy() }) it('should have basic classNames', () => { const wrapper = shallow(<Content />) expect( wrapper.hasClass('content') ).toBeTruthy() }) it('should not have children by default', () => { const wrapper = shallow(<Content />) expect( wrapper.children().exists() ).toBeFalsy() }) it('should pass down children if provided', () => { const wrapper = shallow( <Content> <div>Children</div> </Content> ) expect( wrapper.children().exists() ).toBeTruthy() expect( wrapper.contains(<div>Children</div>) ).toBeTruthy() }) })
44,161
https://github.com/PeterZhouSZ/mandoline/blob/master/include/mandoline/construction/adaptive_grid_factory.hpp
Github Open Source
Open Source
MIT
2,021
mandoline
PeterZhouSZ
C++
Code
408
1,440
#pragma once #include <mtao/geometry/grid/staggered_grid.hpp> #include <mtao/geometry/grid/grid_data.hpp> #include "mandoline/adaptive_grid.hpp" #include <set> #include "cutmesh.pb.h" #include <mtao/eigen/stl2eigen.hpp> #include <optional> namespace mandoline::construction { class AdaptiveGridFactory { public: constexpr static int logwidth = 1; constexpr static int width = 1 << logwidth; using Edge = std::array<int, 2>; using GridData3i = mtao::geometry::grid::GridDataD<int, 3>; using ActiveMask = std::bitset<1 << logwidth * 3>; using GridData3 = mtao::geometry::grid::GridDataD<bool, 3>; using GridData3b = mtao::geometry::grid::GridDataD<ActiveMask, 3>; using coord_type = std::array<int, 3>; using Cell = AdaptiveGrid::Cell; using AxialBEdgeMap = std::array<std::map<int, std::set<Edge>>, 3>; //cell mask AdaptiveGridFactory(const GridData3 &mask); std::tuple<std::array<std::set<Edge>, 3>, AxialBEdgeMap> compute_axial_edges(const std::optional<int> &max_level = {}) const; std::tuple<std::set<Edge>, AxialBEdgeMap> compute_edges(const std::optional<int> &max_level = {}) const; void make_cells(const std::optional<int> &max_level = {}); using Indexer = mtao::geometry::grid::indexing::OrderedIndexer<3>; const static Indexer cmask_indexer; const static Indexer vmask_indexer; const static std::array<Indexer, 3> mask_edge_indexers; const static std::array<coord_type, 3> mask_edge_shapes; Indexer vertex_indexer; static int cmask_index(const coord_type &c) { return cmask_indexer.index(c); } static int cmask_index(int a, int b, int c) { return cmask_indexer.index(a, b, c); } static int vmask_index(const coord_type &c) { return vmask_indexer.index(c); } static int vmask_index(int a, int b, int c) { return vmask_indexer.index(a, b, c); } static int emask_index(int dim, const coord_type &c) { return mask_edge_indexers[dim].index(c); } static int emask_index(int dim, int a, int b, int c) { return mask_edge_indexers[dim].index(a, b, c); } int vertex_index(const coord_type &c) const { return vertex_indexer.index(c); } int vertex_index(int a, int b, int c) const { return vertex_indexer.index(a, b, c); } void make_edges(const std::optional<int> &max_level = {}); void make_cells(const ActiveMask &mask, int level, const coord_type &coord); void make_cells(const GridData3 &mask, int level); void add_cell(const coord_type &corner, int jump); GridData3i grid_from_cells(const std::map<int, Cell> &cells) const; std::tuple<std::array<std::set<Edge>, 3>, AxialBEdgeMap> get_edges(const std::array<GridData3, 3> &edge_masks, int level, const coord_type &offset = {}) const; Edge get_edge(const coord_type &start, int jump, int dim) const; int get_jump(int level) const { return 1 << (level * logwidth); } int get_parent_jump(int level) const { return 1 << ((level + 1) * logwidth); } std::array<coord_type, 3> make_edge_shapes(const coord_type &coord) const; std::array<GridData3, 3> empty_edge_masks(const coord_type &shape, bool value = false) const; std::array<GridData3, 3> empty_edge_masks(int level, bool value = false) const; std::array<GridData3, 3> make_edge_mask(const GridData3 &mask, int level) const; std::array<GridData3, 3> make_edge_mask(const GridData3b &mask, int level) const; std::tuple<std::array<std::set<Edge>, 3>, AxialBEdgeMap> make_edges(const GridData3 &mask, int level) const; std::tuple<std::array<std::set<Edge>, 3>, AxialBEdgeMap> make_edges(const GridData3b &mask, int level) const; AdaptiveGrid create() const; public: mtao::ColVecs2i edges; mtao::ColVecs2i boundary_edges; std::vector<GridData3b> levels; std::vector<GridData3> levels_mask; GridData3 original; std::map<int, Cell> cells; private: template<typename GridAccessor> void set_edge_masks(const coord_type &shape, const coord_type &corner, std::array<GridData3, 3> &edge_mask, const GridAccessor &accessor) const; }; }// namespace mandoline::construction
9,125
https://github.com/ipbm/ipbm/blob/master/ipbm/src/apps/ipbm-ql/app/serve.ts
Github Open Source
Open Source
BSD-3-Clause
null
ipbm
ipbm
TypeScript
Code
115
287
import Web3 from 'web3' import { ApolloServer, gql } from 'apollo-server' import debug from 'debug' import resolvers from './resolvers' import typeDefs from './schema/type-defs' export default (web3: Web3): void => { // In the most basic sense, the ApolloServer can be started // by passing type definitions (typeDefs) and the resolvers // responsible for fetching the data for those types. const server = new ApolloServer({ typeDefs, resolvers: resolvers(web3), }); // This `listen` method launches a web-server. Existing apps // can utilize middleware options, which we'll discuss later. server.listen({ port: 6500, }) .then( ({ url }): void => { debug('catapillarql:serve')(`🚀 Server ready at ${url}`) }, ) .catch( (ex): void => { debug('catapillarql:serve')('error', ex) global.process.exit(1) }, ) }
43,983
https://github.com/azu/lerna-to-typescript-project-references/blob/master/cli.ts
Github Open Source
Open Source
MIT
2,020
lerna-to-typescript-project-references
azu
TypeScript
Code
283
748
#!/usr/bin/env node import arg from 'arg'; import { execSync, exec } from 'child_process'; import { error, log, warn } from 'console'; import { readFileSync, writeFileSync, existsSync } from 'fs'; import { join, dirname } from 'path'; import { format } from 'prettier'; import { TsConfig, Package } from './types'; const args = arg({ '--update': Boolean, '--tsConfigFileName': String }); const tsConfigFileName = args['--tsConfigFileName'] || 'tsconfig.json'; const packages: Package[] = JSON.parse(execSync(`lerna ls --json --loglevel silent`).toString()); const packagesDirectory = dirname(packages[0].location); packages.forEach(({ name, location }) => { exec('npm ls --depth 0 --json --silent', { cwd: location }, (_error, stdout, _stderror) => { const dependencyNames = Object.keys(JSON.parse(stdout).dependencies || {}); const paths = dependencyNames.map(getPathForDependency).filter(x => !!x); if (paths.length == 0) { return log(`${name} - 0 dependencies found.`); } const configFilePath = join(location, tsConfigFileName); const config: TsConfig = JSON.parse(readFileSync(configFilePath).toString()); const { references = [] } = config; const existingPaths = references.map(r => r.path); if (paths.sort().toString() === existingPaths.sort().toString()) { log(`${name} - ${paths.length} dependencies found. All match project references in ${tsConfigFileName}.`); } else if (args['--update']) { warn(`*UPDATE* - ${name} - Some dependencies didn't match. Writing ${paths.length} to ${tsConfigFileName}.`); const newJsonConfig = JSON.stringify({ ...config, references: paths.map(path => ({ path })) }); writeFileSync(configFilePath, format(newJsonConfig, { parser: 'json' })); } else { error(`**FAIL** - ${name} - Some dependencies didn't match.`); error(`**FAIL** - ${name} - From npm packages: ${paths}`); error(`**FAIL** - ${name} - From ${tsConfigFileName}: ${existingPaths}`); process.exit(1); } }); }); const doesTsConfigFileExist = ({ location }: Package) => existsSync(join(location, tsConfigFileName)); function getRelativeTsConfigFilePath({ location }: Package) { const relativePath = location.replace(packagesDirectory, '..'); const file = tsConfigFileName == 'tsconfig.json' ? '' : tsConfigFileName; return join(relativePath, file); } function getPathForDependency(name: string) { const pkg = packages.find(p => p.name === name); return pkg && doesTsConfigFileExist(pkg) ? getRelativeTsConfigFilePath(pkg) : ''; }
15,689
https://github.com/saschazar21/openidconnect-client/blob/master/index.js
Github Open Source
Open Source
MIT
2,018
openidconnect-client
saschazar21
JavaScript
Code
276
825
/** * Require necessary modules */ const argv = require('yargs').argv; const bodyParser = require('body-parser'); const express = require('express'); const debug = require('debug')('openidconnect'); const fs = require('fs'); const hbs = require('express-handlebars'); const https = require('https'); const log = require('morgan'); const path = require('path'); const session = require('express-session'); /** * Parse environment variables from the .env file */ try { require('dotenv').config({ path: path.resolve(__dirname, '.env'), }); } catch (e) { debug(`Something went wrong while parsing the .env file: ${e.message || e}\nBe sure to have all necessary environment variables set!`); } /** * Require passport config including OpenID Connect Strategy */ const passport = require('./lib/passport'); /** * Instantiate Express.js server */ const app = express(); /** * Express.js middlewares */ app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, })); app.use(passport.initialize()); app.use(passport.session()); app.use(log('common')); app.engine('hbs', hbs()); app.set('view engine', 'hbs'); /** * Routes for OpenID Connect service */ app.get('/auth/callback', (req, res, next) => { if (process.env.RESPONSE_TYPE && process.env.RESPONSE_TYPE.includes('token')) { // implicit but form_post is not used res.render('repost'); } else { next(); } }, passport.authenticate('oidc', { failureRedirect: '/', successRedirect: '/profile', })); app.post('/auth/callback', passport.authenticate('oidc', { failureRedirect: '/', successRedirect: '/profile', })); app.get('/auth', passport.authenticate('oidc', { failureRedirect: '/', successRedirect: '/profile', })); app.get('/profile', passport.isAuthenticated, (req, res) => res.render('profile', req.user)); app.get('/', (req, res) => res.render('login')); /** * Listen for connections on given PORT variable, or use port 3000 as fallback */ if (process.env.FORCE_SSL && fs.existsSync(process.env.KEY || './https.key') && fs.existsSync(process.env.CERT || './https.crt')) { https.createServer({ key: fs.readFileSync(process.env.KEY || './https.key'), cert: fs.readFileSync(process.env.CERT || './https.crt'), }, app).listen(process.env.PORT || 3000, () => { debug(`HTTPS enabled, listening on port ${process.env.PORT || 3000}`); }); } else { app.listen(process.env.PORT || 3000, () => { debug(`App listening on port ${process.env.PORT || 3000}`); }); }
34,063
https://github.com/dentalwings/omaha-server/blob/master/.gitignore
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-warranty-disclaimer
2,021
omaha-server
dentalwings
Ignore List
Code
40
129
### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] venv* # Unit test / coverage reports htmlcov/ .coverage .cache nosetests.xml coverage.xml # Sphinx documentation docs/_build/ # PyBuilder target/ # Static files omaha_server/static omaha_server/media *.zip # CUP_PEM_KEYS cups_pem_keys/
4,983
https://github.com/ayessetova/codeW/blob/master/7-kyu/Reverse list/index.js
Github Open Source
Open Source
MIT
2,022
codeW
ayessetova
JavaScript
Code
37
138
/* Title: Reverse list Description: Write reverseList function that simply reverses lists. Kata Link: https://www.codewars.com/kata/reverse-list Discuss Link: https://www.codewars.com/kata/reverse-list/discuss Solutions Link: https://www.codewars.com/kata/reverse-list/solutions */ // Long Solution const reverseList = array => [...array].reverse() // Function Export module.exports = reverseList
21,465
https://github.com/Azure/azure-signalr/blob/master/test/Microsoft.Azure.SignalR.Tests/TestServiceConnectionContainer.cs
Github Open Source
Open Source
LicenseRef-scancode-generic-cla, MIT
2,023
azure-signalr
Azure
C#
Code
256
754
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Microsoft.Azure.SignalR.Protocol; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.Azure.SignalR.Tests { internal sealed class TestServiceConnectionContainer : ServiceConnectionContainerBase { public bool IsOffline { get; set; } = false; public bool MockOffline { get; set; } = false; public TestServiceConnectionContainer(List<IServiceConnection> serviceConnections, HubServiceEndpoint endpoint = null, AckHandler ackHandler = null, IServiceConnectionFactory factory = null, ILogger logger = null) : base(factory, 0, endpoint, serviceConnections, ackHandler: ackHandler, logger: logger ?? NullLogger.Instance) { } public List<IServiceConnection> Connections { get => ServiceConnections; } public void ShutdownForTest() { var prop = typeof(ServiceConnectionContainerBase).GetField("_terminated", BindingFlags.NonPublic | BindingFlags.Instance); prop.SetValue(this, true); } public override async Task OfflineAsync(GracefulShutdownMode mode) { if (MockOffline) { await Task.Delay(100); IsOffline = true; } else { await base.OfflineAsync(mode); } } public override Task HandlePingAsync(PingMessage pingMessage) { return Task.CompletedTask; } public Task BaseHandlePingAsync(PingMessage pingMessage) { return base.HandlePingAsync(pingMessage); } protected override Task OnConnectionComplete(IServiceConnection connection) { return Task.CompletedTask; } public Task OnConnectionCompleteForTestShutdown(IServiceConnection connection) { return base.OnConnectionComplete(connection); } public Task MockReceivedServersPing(string serversTag) { var ping = new PingMessage { Messages = new[] { "servers", $"{DateTime.UtcNow.Ticks}:{serversTag}" } }; return base.HandlePingAsync(ping); } public Task MockReceivedStatusPing(bool isActive) { var ping = new PingMessage { Messages = new[] { "status", isActive ? "1" : "0" } }; return base.HandlePingAsync(ping); } public Task MockReceivedStatusPing(bool isActive, int clientCount) { var ping = new PingMessage { Messages = new[] { "status", isActive ? "1" : "0" , "clientcount", clientCount.ToString()} }; return base.HandlePingAsync(ping); } } }
4,229
https://github.com/zhmu/ananas/blob/master/external/gcc-12.1.0/gcc/testsuite/gfortran.dg/pr89574.f90
Github Open Source
Open Source
LGPL-2.1-only, GPL-3.0-only, GCC-exception-3.1, GPL-2.0-only, LGPL-3.0-only, LGPL-2.0-or-later, FSFAP, Zlib, LicenseRef-scancode-public-domain
2,022
ananas
zhmu
Fortran Free Form
Code
68
170
! { dg-do compile } ! PR fortran/89574 - ICE in conv_function_val, at fortran/trans-expr.c:3792 module mod1 contains subroutine init end subroutine end module module mod2 contains subroutine init end subroutine end module module init use mod1, only : test_init1 => init use mod2, only : test_init2 => init implicit none contains subroutine sub call test_init1 call test_init2 call init contains subroutine init end subroutine end subroutine end module
20,143
https://github.com/hermntech/FMB920Parser/blob/master/SimpleDisplayMap/Models/GPSData.cs
Github Open Source
Open Source
Apache-2.0
2,019
FMB920Parser
hermntech
C#
Code
59
117
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SimpleDisplayMap.Models { public class GPSData { public string Name { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public string Speed { get; set; } public int ignition { get; set; } public string Location { get; set; } } }
4,562
https://github.com/wojiaoyanmin/oot/blob/master/add_sharefeature_20_BCE/tools/convert_datasets/mhp/get_apr_label.py
Github Open Source
Open Source
Apache-2.0
2,021
oot
wojiaoyanmin
Python
Code
329
1,476
import argparse import glob import os.path as osp import pdb from PIL import Image import mmcv import numpy as np import pycocotools.mask as maskUtils from tqdm import trange, tqdm import numpy import cv2 import matplotlib.pyplot as plt import time mhp_id2label = {0: 'Background', 1: 'Cap/hat', 2: 'Helmet', 3: 'Face', 4: 'Hair', 5: 'Left-arm', 6: 'Right-arm', 7: 'Left-hand', 8: 'Right-hand', 9: 'Protector', 10: 'Bikini/bra', 11: 'Jacket/windbreaker/hoodie ', 12: 'Tee-shirt', 13: 'Polo-shirt', 14: 'Sweater', 15: 'Singlet', 16: 'Torso-skin', 17: 'Pants', 18: 'Shorts/swim-shorts', 19: 'Skirt', 20: 'Stockings', 21: 'Socks', 22: 'Left-boot', 23: 'Right-boot', 24: 'Left-shoe', 25: 'Right-shoe', 26: 'Left-highheel', 27: 'Right-highheel', 28: 'Left-sandal', 29: 'Right-sandal', 30: 'Left-leg', 31: 'Right-leg', 32: 'Left-foot', 33: 'Right-foot', 34: 'Coat', 35: 'Dress', 36: 'Robe', 37: 'Jumpsuit', 38: 'Other-full-body-clothes', 39: 'Headwear', 40: 'Backpack', 41: 'Ball', 42: 'Bats', 43: 'Belt', 44: 'Bottle', 45: 'Carrybag', 46: 'Cases', 47: 'Sunglasses', 48: 'Eyewear', 49: 'Glove', 50: 'Scarf', 51: 'Umbrella', 52: 'Wallet/purse', 53: 'Watch', 54: 'Wristband', 55: 'Tie', 56: 'Other-accessary', 57: 'Other-upper-body-clothes', 58: 'Other-lower-body-clothes', } def collect_files(text_dir, instance_dir, out_dir): files = [] print("collencting files") flist = [line.strip() for line in open(text_dir).readlines()] for add in tqdm(flist, desc='Loading %s ..' % ('val')): file_single=[] for instance_file in glob.glob(osp.join(instance_dir, '*.png')): instance_name = osp.basename(instance_file)[:-len('.png')] instance_index, totoal_num, human_index = instance_name.split('_') if instance_index == add: num_human=totoal_num img = mmcv.imread(instance_file, 'unchanged')[:, :, 2] Category_id=numpy.unique(img) img[img>0]=( 60*(int(human_index)-1)+img[img>0]) file_single.append(img) for id in Category_id: if id == 0: continue with open(osp.join(out_dir, instance_index + ".txt"),'a') as f: f.write('%d %d %d\n'%((int(human_index)-1)*60+id,int(id), int(human_index))) after_img = numpy.stack(file_single) after_img = numpy.max(after_img,axis=0) if numpy.max(after_img)>=int(num_human)*60: print('add:',add) print('max:',numpy.max(after_img)) print('total:',int(num_human)*60) cv2.imwrite(osp.join(out_dir, add + ".png"), after_img) time.sleep(0.5) return None def parse_args(): parser = argparse.ArgumentParser( description='Convert mhp annotations to COCO format') #parser.add_argument('mhp_path', help='mhp data path') parser.add_argument('--Images', default='images', type=str) parser.add_argument('--Categoriy-dir', default='Category_ids', type=str) parser.add_argument('--Human-dir', default='Human_ids', type=str) parser.add_argument('--Instance-dir', default='parsing_annos', type=str) #parser.add_argument('-o', '--out-dir', help='output path') parser.add_argument( '--nproc', default=1, type=int, help='number of process') args = parser.parse_args() return args def main(): text_dir = 'data/MHP/list/val.txt' instance_dir = 'data/MHP/val/parsing_annos/' out_dir = 'data/MHP/val/instance_part_val' mmcv.mkdir_or_exist(out_dir) with mmcv.Timer( print_tmpl='It tooks {}s to convert MHP annotation'): files = collect_files( text_dir, instance_dir, out_dir) if __name__ == '__main__': main()
13,869
https://github.com/nahuef/require-indexjs/blob/master/test/mocks/modules/secondModule/index.js
Github Open Source
Open Source
MIT
2,019
require-indexjs
nahuef
JavaScript
Code
7
16
'use strict' module.exports = class SecondModule {}
40,264
https://github.com/naumenko-sa/bioscripts/blob/master/paml/fasta2phy.pl
Github Open Source
Open Source
MIT
2,022
bioscripts
naumenko-sa
Perl
Code
42
169
#!/usr/bin/perl #converts fasta to relaxed phylip format (without 10 base limit for name) open(IN, $ARGV[0]); %align; @names; while(<IN>) { chomp; $name = $_; push(@names,$name); $dna = <IN>; chomp $dna; $align{$name}=$dna; } print @names."\t".length($dna)."\n"; foreach $name (@names) { print substr($name,1,length($name)-1)." ".$align{$name}."\n"; } close(IN);
11,310
https://github.com/rmendoza83/minesweeper-API/blob/master/server/app/Utils/APIResponseResult.php
Github Open Source
Open Source
MIT
2,020
minesweeper-API
rmendoza83
PHP
Code
44
154
<?php namespace Utils; use Constants\ApiResponseStatusCode as API_RESPONSE_STATUS_CODE; class APIResponseResult { public static function OK($data = null) { return response()->json([ 'statusCode' => API_RESPONSE_STATUS_CODE::OK, 'data' => $data ]); } public static function ERROR($error) { return response()->json([ 'statusCode' => API_RESPONSE_STATUS_CODE::BAD_REQUEST, 'errorMessage' => $error ]); } } ?>
39,197
https://github.com/paser4se/XCoLab/blob/master/view/src/main/java/org/xcolab/view/pages/modeling/admin/actions/UpdateModelInputWidgetsAction.java
Github Open Source
Open Source
MIT
2,021
XCoLab
paser4se
Java
Code
127
865
package org.xcolab.view.pages.modeling.admin.actions; import edu.mit.cci.roma.client.Simulation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.xcolab.client.modeling.IModelingClient; import org.xcolab.client.modeling.models.ui.IllegalUIConfigurationException; import org.xcolab.client.modeling.models.ui.ModelDisplay; import org.xcolab.client.modeling.models.ui.ModelInputDisplayItem; import org.xcolab.client.modeling.models.ui.ModelInputIndividualDisplayItem; import org.xcolab.client.modeling.models.ui.ModelUIFactory; import org.xcolab.client.modeling.pojo.IModelGlobalPreference; import org.xcolab.client.modeling.roma.RomaClientUtil; import org.xcolab.view.pages.modeling.admin.ModelsAdminController; import org.xcolab.view.pages.modeling.admin.form.UpdateModelInputWidgetsBean; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/admin/modeling") public class UpdateModelInputWidgetsAction { private final IModelingClient modelingClient; @Autowired public UpdateModelInputWidgetsAction(IModelingClient modelingClient) { this.modelingClient = modelingClient; } @PostMapping("model/{modelId}/updateInputs") public void update(HttpServletRequest request, HttpServletResponse response, UpdateModelInputWidgetsBean updateModelWidgetsBean, @PathVariable long modelId) throws IllegalUIConfigurationException, IOException { IModelGlobalPreference modelPreferences = modelingClient.getModelPreference(modelId); if (modelPreferences.isUsesCustomInputs()) { modelPreferences .setCustomInputsDefinition(updateModelWidgetsBean.getCustomInputWidgets()); modelingClient.updatePreferences(modelPreferences); } else { Simulation simulation = RomaClientUtil.client().getSimulation(modelId); ModelDisplay modelDisplay = ModelUIFactory.getInstance().getDisplay(simulation); for (ModelInputDisplayItem item : modelDisplay.getAllIndividualInputs()) { if (updateModelWidgetsBean.getWidgets().containsKey(item.getMetaData().getId())) { item.setType( updateModelWidgetsBean.getWidgets().get(item.getMetaData().getId())); } if (updateModelWidgetsBean.getGroups().containsKey(item.getMetaData().getId())) { ((ModelInputIndividualDisplayItem) item).setGroupId( updateModelWidgetsBean.getGroups().get(item.getMetaData().getId())); } if (updateModelWidgetsBean.getOrders().containsKey(item.getMetaData().getId())) { item.setOrder( updateModelWidgetsBean.getOrders().get(item.getMetaData().getId())); } } } response.sendRedirect(ModelsAdminController.getTabMapping(modelId, "inputWidgets")); } }
50,143
https://github.com/anshumang/cp-snucl/blob/master/src/compiler/test/FrontendAda/placeholder.adb
Github Open Source
Open Source
NCSA, BSD-2-Clause
2,014
cp-snucl
anshumang
Ada
Code
76
140
-- RUN: %llvmgcc -S %s procedure Placeholder is subtype Bounded is Integer range 1 .. 5; type Vector is array (Bounded range <>) of Integer; type Interval (Length : Bounded := 1) is record Points : Vector (1 .. Length); end record; An_Interval : Interval := (Length => 1, Points => (1 => 1)); generic The_Interval : Interval; package R is end; package body R is end; package S is new R (An_Interval); begin null; end;
33,136
https://github.com/hcfman/stalkedbythestate/blob/master/src/main/webapp/js/system-settings/controller.js
Github Open Source
Open Source
Apache-2.0
2,021
stalkedbythestate
hcfman
JavaScript
Code
550
2,494
SystemSettingsController = function () { this.load = function () { JSNotificationCenter.addObserver(this, 'initialise', 'LoadedJSON'); JSNotificationCenter.addObserver(this, 'checkUpdates', 'CheckUpdates'); }; this.initialise = function (note) { this.applySettings(note.data); }; this.checkUpdates = function() { ShowActivity(true, 'Check for updates...'); jQuery.ajax( { url : 'checkupdates', type : 'POST', data : {'timestamp': new Date().getTime()}, contentType: 'application/json', dataType: 'json', error: function (xhr) { ShowActivity(false); // var reason = xhr.status + ' ' + xhr.statusText.toUpperCaseFirst(); // JSPostNotification('OnError', 'Failed to save actions<br>Reason: ' + reason ); // TODO: do stuff with response... }, success: function (response) { if (response.result == true && response.description) { CheckUpdates.setCheckUpdatesJSON(response); JSDialog.setController(CheckUpdates); JSDialog.openDialog( 'jsp/content/forms/updates-available.html', CheckUpdates, null, { buttonName : 'Update', width : '300px' }); }else{ JSPostNotification('OnError', response.messages.join('<br>') ); } ShowActivity(false); // JSPostNotification('OnInfo', 'Saved actions'); // TODO: do stuff with response... } }); }; this.applySettings = function (settings) { // Timezone jQuery('#timeZone > option').each( function () { if (this.value == settings.dateTime.timeZone) { this.selected = true; } }); // Date & Time jQuery('#manualDate').val(settings.dateTime.date); jQuery('#timeHour > option').each( function () { if (this.value == settings.dateTime.timeHour) { this.selected = true; } }); jQuery('#timeMinute > option').each( function () { if (this.value == settings.dateTime.timeMinute) { this.selected = true; } }); // NTP if (settings.dateTime.useNtp) { jQuery('#manualTime').attr('checked', false); jQuery('#dynamicTime').attr('checked', true); }else{ jQuery('#manualTime').attr('checked', true); jQuery('#dynamicTime').attr('checked', false); } jQuery('#ntpServer').val(settings.dateTime.ntpServer); // Network jQuery('#dhcp').attr('checked', settings.network.dhcp); jQuery('#hostname').val(settings.network.hostname); jQuery('#address').val(settings.network.address); jQuery('#mask').val(settings.network.mask); jQuery('#defaultRoute').val(settings.network.defaultRoute); // Nameservers jQuery('#nameServer1').val(settings.network.nameServer1); jQuery('#nameServer2').val(settings.network.nameServer2); jQuery('#nameServer3').val(settings.network.nameServer3); // Protocol Descriptor jQuery('#protocolDescriptor > option').each( function () { if (this.value == settings.network.protocolDescriptor) { this.selected = true; } }); jQuery('#httpPort').val(settings.network.httpPort); jQuery('#httpsPort').val(settings.network.httpsPort); // Preferences var prefs = settings.preferences; console.log(prefs); jQuery('#webPrefix').val(prefs.webPrefix); jQuery('#x10Delay').val(prefs.x10Delay); jQuery('#connectTimeout').val(prefs.connectTimeout); jQuery('#freeSpace').val(prefs.freeSpace); jQuery('#daysJpeg').val(prefs.daysJpeg); jQuery('#cleanRate').val(prefs.cleanRate); jQuery('#phonehomeUrl').val(prefs.phonehomeUrl); }; this.saveDateTimeSettings = function () { ShowActivity(true, 'Saving Date &amp; Time...'); var settings = { timeZone :jQuery('#timeZone').val(), date :jQuery('#manualDate').val(), timeHour :jQuery('#timeHour').val(), timeMinute :jQuery('#timeMinute').val(), useNtp :jQuery('#dynamicTime').attr('checked'), ntpServer :jQuery('#ntpServer').val() }; var data = Configuration.toJSON( settings ); jQuery.ajax( { url : 'datetime', type : 'POST', data : data, contentType: 'application/json', dataType: 'json', error: function (xhr) { ShowActivity(false); var reason = xhr.status + ' ' + xhr.statusText.toUpperCaseFirst(); JSPostNotification('OnError', 'Failed to save date &amp; time<br>Reason: ' + reason ); }, success: function (response) { ShowActivity(false); if (response.result === true) { Reboot('Restarting the system', 30); JSPostNotification('OnInfo', 'Saved date &amp; time'); }else{ JSPostNotification('OnError', response.messages.join('<br>') ); } } }); }; this.saveNetworkSettings = function () { ShowActivity(true, 'Saving network settings...'); var settings = { dhcp :jQuery('#dhcp').attr('checked'), address :jQuery('#address').val(), mask :jQuery('#mask').val(), defaultRoute :jQuery('#defaultRoute').val(), nameServer1 :jQuery('#nameServer1').val(), nameServer2 :jQuery('#nameServer2').val(), nameServer3 :jQuery('#nameServer3').val(), protocolDescriptor :jQuery('#protocolDescriptor').val(), httpPort :jQuery('#httpPort').val(), httpsPort :jQuery('#httpsPort').val(), hostname :jQuery('#hostname').val() }; var data = Configuration.toJSON( settings ); jQuery.ajax( { url : 'network', type : 'POST', data : data, contentType: 'application/json', dataType: 'json', error: function (xhr) { ShowActivity(false); var reason = xhr.status + ' ' + xhr.statusText.toUpperCaseFirst(); JSPostNotification('OnError', 'Failed to save network settings<br>Reason: ' + reason ); }, success: function (response) { ShowActivity(false); if (response.result === true) { Reboot('Restarting the system', 30); JSPostNotification('OnInfo', 'Saved network settings'); }else{ JSPostNotification('OnError', response.messages.join('<br>') ); } } }); }; this.savePreferences = function () { ShowActivity(true, 'Saving preferences...'); var settings = { webPrefix :jQuery('#webPrefix').val(), x10Delay :jQuery('#x10Delay').val(), connectTimeout :jQuery('#connectTimeout').val(), freeSpace :jQuery('#freeSpace').val(), daysJpeg :jQuery('#daysJpeg').val(), cleanRate :jQuery('#cleanRate').val(), phonehomeUrl :jQuery('#phonehomeUrl').val() }; var data = Configuration.toJSON( settings ); jQuery.ajax( { url : 'preferences', type : 'POST', data : data, contentType: 'application/json', dataType: 'json', error: function (xhr) { ShowActivity(false); var reason = xhr.status + ' ' + xhr.statusText.toUpperCaseFirst(); JSPostNotification('OnError', 'Failed to save preferences<br>Reason: ' + reason ); }, success: function (response) { ShowActivity(false); JSPostNotification('OnInfo', 'Saved preferences'); } }); }; this.load(); }; // singleton SystemSettingsController = new SystemSettingsController();
6,998
https://github.com/actioncy/io-landing/blob/master/js/actioncy-landing.js
Github Open Source
Open Source
MIT
2,019
io-landing
actioncy
JavaScript
Code
58
204
$(document).ready(function() { // Menu Control Overlay $('#mastheadCTA').visibility({ once: false, onOnScreen: function() { $('nav').hide(); }, onOffScreen: function() { $('nav').show(); }, }); //Mailchimp sign-up overlay $('button').on('click', function() { $('.ui.modal').modal('show'); }); $('#mc-embedded-subscribe-form') .form({ fields: { email: { identifier: 'mce-EMAIL', rules: [ { type : 'email', prompt : 'Please enter a valid email address. Thank you.' } ] } } }); });
36,037
https://github.com/mugabe/couchbase-cbforest/blob/master/CBForest/RevID.hh
Github Open Source
Open Source
Apache-2.0
null
couchbase-cbforest
mugabe
C++
Code
279
677
// // RevID.hh // CBForest // // Created by Jens Alfke on 6/2/14. // Copyright (c) 2014 Couchbase. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. #ifndef __CBForest__RevID__ #define __CBForest__RevID__ #include "slice.hh" namespace cbforest { /** A compressed revision ID. Since this is based on slice, it doesn't own the memory it points to. */ class revid : public slice { public: revid() :slice() {} revid(const void* b, size_t s) :slice(b,s) {} explicit revid(slice s) :slice(s) {} bool isCompressed() const {return !isdigit((*this)[0]);} alloc_slice expanded() const; size_t expandedSize() const; bool expandInto(slice &dst) const; unsigned generation() const; slice digest() const; bool operator< (const revid&) const; explicit operator std::string() const; #ifdef __OBJC__ explicit operator NSString*() const; // overrides slice method #endif private: uint64_t getGenAndDigest(slice &digest) const; void _expandInto(slice &dst) const; }; /** A self-contained revid that includes its own data buffer. */ class revidBuffer : public revid { public: revidBuffer() :revid(&_buffer, 0) {} explicit revidBuffer(slice s) :revid(&_buffer, 0) {parse(s);} revidBuffer(unsigned generation, slice digest); revidBuffer(const revidBuffer&); /** Parses a regular (uncompressed) revID and compresses it. Throws BadRevisionID if the revID isn't in the proper format.*/ void parse(slice); #ifdef __OBJC__ explicit revidBuffer(NSString* str); #endif private: uint8_t _buffer[42]; }; } #endif /* defined(__CBForest__RevID__) */
41,275
https://github.com/oncesk/ddiff/blob/master/src/Model/DescriptionAwareInterface.php
Github Open Source
Open Source
MIT
2,017
ddiff
oncesk
PHP
Code
25
64
<?php namespace DDiff\Model; /** * Class DescriptionAwareInterface * @package DDiff\Model */ interface DescriptionAwareInterface { /** * @return string */ public function getDescription() : string; }
36,726
https://github.com/CreativeBulma/collapsible/blob/master/docs/_sass/bulma-custom/components/media/_custom.sass
Github Open Source
Open Source
MIT
2,022
collapsible
CreativeBulma
Sass
Code
13
41
/** * ------------------------------------- * MEDIA COMPONENT CUSTOMIZATION * ------------------------------------- */ .media-content padding-top: .5em
36,184
https://github.com/itscark/shopware6-tailwind-theme/blob/master/src/Resources/views/storefront/layout/header/actions/service-menu-widget.html.twig
Github Open Source
Open Source
MIT
null
shopware6-tailwind-theme
itscark
Twig
Code
162
583
{% sw_extends '@Storefront/storefront/layout/header/actions/service-menu-widget.html.twig' %} {% block layout_header_actions_service_menu_widget %} {% if position is empty %} {% set position = 'top-bar' %} {% endif %} {% if page.header.serviceMenu|length > 0 %} <div class="top-bar-nav-item top-bar-menu"> {% block layout_header_actions_service_menu_list %} <div class="service-menu relative"> <button class="inline-block align-middle text-center select-none border font-normal whitespace-no-wrap rounded py-1 px-3 leading-normal no-underline inline-block w-0 h-0 ml-1 align border-b-0 border-t-1 border-r-1 border-l-1 top-bar-nav-btn" type="button" id="serviceMenuDropdown-{{ position }}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% sw_icon 'help' %} <span class="top-bar-nav-text">{{ "header.indexLinkService"|trans|sw_sanitize }}</span> </button> {% block layout_header_actions_service_menu_items %} <div class=" absolute left-0 z-50 float-left hidden list-reset py-2 mt-1 text-base bg-white border border-gray-300 rounded dropdown-menu-right" aria-labelledby="serviceMenuDropdown-{{ position }}"> {% for category in page.header.serviceMenu %} {% set externalLink = category.translated.externalLink %} <a class="top-bar-list-item block w-full py-1 px-6 font-normal text-gray-900 whitespace-no-wrap border-0" href="{% if externalLink %}{{ externalLink }}{% else %}{{ seoUrl('frontend.navigation.page', { navigationId: category.id }) }}{% endif %}" title="{{ category.translated.name }}">{{ category.translated.name }}</a> {% endfor %} </div> {% endblock %} </div> {% endblock %} </div> {% endif %} {% endblock %}
47,960
https://github.com/WaCoDiS/wps-client-lib/blob/master/src/main/java/org/n52/geoprocessing/wps/client/model/Address.java
Github Open Source
Open Source
Apache-2.0
2,022
wps-client-lib
WaCoDiS
Java
Code
284
793
/* * Copyright (C) 2020 52°North Initiative for Geospatial Open Source * Software GmbH * * 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.n52.geoprocessing.wps.client.model; public class Address { private String deliveryPoint; private String city; private String administrativeArea; private String postalCode; private String country; private String electronicMailAddress; public String getDeliveryPoint() { return deliveryPoint; } public void setDeliveryPoint(String deliveryPoint) { this.deliveryPoint = deliveryPoint; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAdministrativeArea() { return administrativeArea; } public void setAdministrativeArea(String administrativeArea) { this.administrativeArea = administrativeArea; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getElectronicMailAddress() { return electronicMailAddress; } public void setElectronicMailAddress(String electronicMailAddress) { this.electronicMailAddress = electronicMailAddress; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("DeliveryPoint: " + getDeliveryPoint() + StringConstants.LINE_SEPARATOR); stringBuilder.append("\t\t\t\t\t\t\t\t PostalCode: " + getPostalCode() + StringConstants.LINE_SEPARATOR); stringBuilder.append("\t\t\t\t\t\t\t\t City: " + getCity() + StringConstants.LINE_SEPARATOR); stringBuilder.append( "\t\t\t\t\t\t\t\t Administrative area: " + getAdministrativeArea() + StringConstants.LINE_SEPARATOR); stringBuilder.append("\t\t\t\t\t\t\t\t Country: " + getCountry() + StringConstants.LINE_SEPARATOR); stringBuilder.append("\t\t\t\t\t\t\t\t Electronic mail address: " + getElectronicMailAddress() + StringConstants.LINE_SEPARATOR); return stringBuilder.toString(); } }
21,554
https://github.com/daqiangge/SiJiWuYou/blob/master/YouChengTire/YouChengTire/LQ_MVC/MainClass/找货/V/LQFahuoCell1.m
Github Open Source
Open Source
Apache-2.0
2,016
SiJiWuYou
daqiangge
Objective-C
Code
75
351
// // LQFahuoCell1.m // YouChengTire // // Created by liqiang on 16/4/30. // Copyright © 2016年 WangZhipeng. All rights reserved. // #import "LQFahuoCell1.h" @interface LQFahuoCell1()<UITextFieldDelegate> @end @implementation LQFahuoCell1 + (LQFahuoCell1 *)cellWithTableView:(UITableView *)tableView { UINib *nib = [UINib nibWithNibName:@"LQFahuoCell1" bundle:nil]; [tableView registerNib:nib forCellReuseIdentifier:@"LQFahuoCell1"]; LQFahuoCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"LQFahuoCell1"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (self.textFieldChange) { self.textFieldChange(str); } return YES; } @end
29,876
https://github.com/mbellabah/riaps-pycom/blob/master/bin/riaps-mn.node
Github Open Source
Open Source
Apache-2.0
2,019
riaps-pycom
mbellabah
Shell
Code
83
206
#!/bin/sh # Set up a virtual host # To be run 'non-lead' nodes # For riaps developers - NOT APP DEVELOPERS # Add default gateway (mininet) route add default gw 192.168.57.1 # Add route to outer net ip route add 192.168.56.0/24 via 192.168.57.126 # Launch deplo as root echo "source setup.node; export PYTHONPATH=`pwd`/src; cd src; python3 riaps/riaps_deplo.py" | sudo -s -u root # Deprecated: change to (non-privileged) user # echo "source setup.node; export PYTHONPATH=`pwd`/src; cd src; python3 riaps/riaps_deplo.py" | sudo -s -u riaps
30,810
https://github.com/Arquitectura-de-Software-UFPS-2022-I/Java-AppCore/blob/master/src/services/impl/SignatureRequestServiceImpl.java
Github Open Source
Open Source
MIT
null
Java-AppCore
Arquitectura-de-Software-UFPS-2022-I
Java
Code
127
452
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package services.impl; import java.util.List; import models.SignatureRequestDto; import services.SignatureRequestService; import utils.ServiceHttp; /** * * @author USUARIO */ public class SignatureRequestServiceImpl extends ServiceHttp implements SignatureRequestService{ @Override public List<SignatureRequestDto> getRequest() throws Exception { return HttpGetList("/api/v1/signature_requests/?format=json", SignatureRequestDto[].class); } @Override public List<SignatureRequestDto> getRequestUser(int id) throws Exception { return HttpGetList("/api/v1/signature_requests_by_user/"+id+"/?format=json", SignatureRequestDto[].class); } @Override public SignatureRequestDto getRequestId(int id) throws Exception { return HttpGetOne("/api/v1/signature_requests/"+id+"/?format=json", SignatureRequestDto.class); } @Override public SignatureRequestDto saveRequest(SignatureRequestDto user) throws Exception { return HttpPost("/api/v1/signature_requests/?format=json", SignatureRequestDto.class, user); } @Override public SignatureRequestDto updateRequest(SignatureRequestDto user) throws Exception { return HttpPut("/api/v1/signature_requests/"+user.getId()+"?format=json", SignatureRequestDto.class, user); } @Override public void deleteRequest(int id) throws Exception { HttpDelete("/api/v1/signature_requests/"+id+"?format=json"); } }
33,129
https://github.com/Rudracool/MotherCareBackend-/blob/master/SuiteCommerce Advanced/SC_21.1_Live/Advanced/SCA/JavaScript/SC.Environment.Component.ts
Github Open Source
Open Source
MIT
null
MotherCareBackend-
Rudracool
TypeScript
Code
260
818
/* © 2020 NetSuite Inc. User may not copy, modify, distribute, or re-bundle or otherwise make available this code; provided, however, if you are an authorized user with a NetSuite account or log-in, you may use this code subject to the terms that govern your access and use. */ /// <amd-module name="SC.Environment.Component"/> /// <reference path="../../../Commons/Utilities/JavaScript/GlobalDeclarations.d.ts" /> import * as _ from 'underscore'; import * as Utils from '../../../Commons/Utilities/JavaScript/Utils'; import { Configuration } from '../../../Commons/Utilities/JavaScript/Configuration'; import { SCBaseComponent } from '../../../Commons/SC/JavaScript/SC.BaseComponent'; import Tracker = require('../../../Commons/Tracker/JavaScript/Tracker'); // Environment component. see APIdocs/JavaScript/EnvironmentComponent.js for documentation const SCEnvironmentComponent: any = { /** @param {ComponentContainer} container */ mountToApp: function(container) { container.registerComponent(this.componentGenerator(container)); }, componentGenerator: function(container) { return SCBaseComponent.extend({ componentName: 'Environment', application: container, getConfig: function getConfig(key) { return Utils.deepCopy(Utils.getPathFromObject(Configuration, key)); }, isPageGenerator: function isPageGenerator() { return typeof nsglobal !== 'undefined'; }, getSiteSetting: function getSiteSettings(key) { return Utils.deepCopy(Utils.getPathFromObject(SC.ENVIRONMENT.siteSettings, key)); }, getSession: function getSession() { if (this.isPageGenerator()) { return null; } const data = Utils.deepCopy(SC.SESSION); delete data.touchpoints; return data; }, setTranslation: function setTranslation(locale, keys) { const session = this.getSession(); if (session && session.language && session.language.locale === locale) { _.each(keys, function(entry: any) { SC.Translations[entry.key] = entry.value; }); } }, addTracker: function addTracker(tracker) { if (!_.isObject(tracker)) { this._reportError( 'INVALID_PARAM', 'Invalid parameter "tracker". It must be a valid object' ); } Tracker.getInstance().registerExtensibilityTracker(tracker); }, triggerEvent: function triggerEvent(event, data) { if (!event || !_.isString(event)) { this._reportError( 'INVALID_PARAM', 'Invalid parameter "event". It must be a valid string' ); } if (!_.isEmpty(data) && !_.isObject(data)) { this._reportError( 'INVALID_PARAM', 'Invalid parameter "data". It must be a valid object' ); } Tracker.getInstance().triggerCustomEventForExtensibilityTrackers(event, data); } }); } }; export = SCEnvironmentComponent;
25,654
https://github.com/subinsoman/seahorse/blob/master/seahorse-workflow-executor/commons/src/main/scala/ai/deepsense/commons/utils/ConfigWithDirListsImplicits.scala
Github Open Source
Open Source
Apache-2.0
2,021
seahorse
subinsoman
Scala
Code
128
281
/** * Copyright 2016 deepsense.ai (CodiLime, Inc) * * 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 ai.deepsense.commons.utils import java.io.File import scala.collection.JavaConversions._ import com.typesafe.config.Config object ConfigWithDirListsImplicits { implicit class ConfigWithDirLists(val config: Config) { def getDirList(path: String): Seq[File] = { config.getStringList(path).toList .map(new File(_)) .filter(_.isDirectory) } } }
2,005
https://github.com/Prajithp/aws-sdk-perl/blob/master/auto-lib/Paws/DynamoDB/ArchivalSummary.pm
Github Open Source
Open Source
Apache-2.0
2,022
aws-sdk-perl
Prajithp
Perl
Code
300
670
# Generated by default/object.tt package Paws::DynamoDB::ArchivalSummary; use Moose; has ArchivalBackupArn => (is => 'ro', isa => 'Str'); has ArchivalDateTime => (is => 'ro', isa => 'Str'); has ArchivalReason => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::DynamoDB::ArchivalSummary =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::DynamoDB::ArchivalSummary object: $service_obj->Method(Att1 => { ArchivalBackupArn => $value, ..., ArchivalReason => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::DynamoDB::ArchivalSummary object: $result = $service_obj->Method(...); $result->Att1->ArchivalBackupArn =head1 DESCRIPTION Contains details of a table archival operation. =head1 ATTRIBUTES =head2 ArchivalBackupArn => Str The Amazon Resource Name (ARN) of the backup the table was archived to, when applicable in the archival reason. If you wish to restore this backup to the same table name, you will need to delete the original table. =head2 ArchivalDateTime => Str The date and time when table archival was initiated by DynamoDB, in UNIX epoch time format. =head2 ArchivalReason => Str The reason DynamoDB archived the table. Currently, the only possible value is: =over =item * C<INACCESSIBLE_ENCRYPTION_CREDENTIALS> - The table was archived due to the table's AWS KMS key being inaccessible for more than seven days. An On-Demand backup was created at the archival time. =back =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::DynamoDB> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
43,384
https://github.com/flying8824315/json-mock/blob/master/src/style/defaults.scss
Github Open Source
Open Source
MIT
null
json-mock
flying8824315
SCSS
Code
959
3,345
@import "./variables"; /* icon font path, required */ $--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index"; /** overrides */ .el-table--small { font-size: 14px; } /* flex layout */ html, body { margin: 0; padding: 0; height: 100%; box-sizing: border-box; background: #F2F2F2; } /* position */ .absolute { position: absolute; } .relative { position: relative; } .fixed { position: fixed; } .static { position: static; } .fixed-full { position: fixed; top: 0; right: 0; bottom: 0; left: 0; } .absolute-full { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } .fixed-center { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); } .absolute-center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } /* flex layout */ .flex { display: flex; } .flex-col { display: flex; flex-direction: column; } .flex-reverse { display: flex; flex-direction: row-reverse; } .flex-col-reverse { display: flex; flex-direction: column-reverse; } .keep-flex { display: flex !important; } .inline-flex { display: inline-flex; } .keep-inline-flex { display: inline-flex !important; } .flex-h-center { display: flex; justify-content: center; } .flex-v-center { display: flex; align-items: center; } .flex-center { display: flex; align-items: center; justify-content: center; } .justify-space-between { display: flex; justify-content: space-between; } $flex-values: (1, 2, 3, 4, 5, 6, 7, 8, 9); @each $value in $flex-values { .flex-#{$value} { flex: #{$value}; } } /* block layout */ .block { display: block; } .keep-block { display: block !important; } .inline { display: inline; } .keep-inline { display: inline !important; } .inline-block { display: inline-block; } .keep-inline-block { display: inline-block !important; } .border-box { box-sizing: border-box; } .display-none { display: none; } .keep-display-none { display: none !important; } /* align */ .align-center { text-align: center; } .align-right { text-align: right; } .align-left { text-align: left; } .align-middle { vertical-align: middle; } .align-top { vertical-align: top; } .align-bottom { vertical-align: bottom; } .align-baseline { vertical-align: baseline; } /* font */ $font-size-values: (10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40); @each $value in $font-size-values { .font-size-#{$value} { font-size: #{$value}px; } } .font-bolder { font-weight: bolder; } .text-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .text-justify { text-align: justify; } .text-justify-last { text-align-last: justify; } .text-justify-all { text-align: justify; text-align-last: justify; } // ~ height // =============================================================================== .height-full { height: 100%; } .float-right { float: right; } .float-left { float: left; } .float-none { float: none; } // ~ width // =============================================================================== $width-values: ( 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 48, 50, 52, 54, 60, 64, 70, 72, 80, 81, 84, 90, 92, 96, 100, 120, 125, 130, 140, 150, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 350, 360, 380, 400, 420, 450, 480, 500, 540, 550, 600, 640, 650, 720, 750, 810, 840, 850, 900, 950, 980, 1000); @each $value in $width-values { .width-#{$value} { width: #{$value}px; } } $height-values: (10, 20, 24, 30, 32, 34, 36, 38, 40, 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 220, 240, 250, 260, 280, 300, 320, 350, 400); @each $value in $height-values { .height-#{$value} { height: #{$value}px; } } .width-full { width: 100%; } .width-half { width: 50%; } .width-zero { width: 0; } .keep-width-full { width: 100% !important; } .keep-width-half { width: 50% !important; } .keep-width-zero { width: 0 !important; } $line-height-values: (12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 52, 54, 56, 58, 60, 62, 64); @each $value in $line-height-values { .line-height-#{$value} { line-height: #{$value}px; } } // ~ margin // =============================================================================== $margin-values: (0, 2, 5, 8, 10, 12, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 50, 60, 80, 100, 200); @each $val in $margin-values { .margin-left-#{$val} { margin-left: #{$val}px; } .margin-right-#{$val} { margin-right: #{$val}px; } .margin-h-#{$val} { margin-left: #{$val}px; margin-right: #{$val}px; } .margin-top-#{$val} { margin-top: #{$val}px; } .margin-bottom-#{$val} { margin-bottom: #{$val}px; } .margin-v-#{$val} { margin-top: #{$val}px; margin-bottom: #{$val}px; } .margin-#{$val} { margin: #{$val}px; } .padding-left-#{$val} { padding-left: #{$val}px; } .padding-right-#{$val} { padding-right: #{$val}px; } .padding-h-#{$val} { padding-left: #{$val}px; padding-right: #{$val}px; } .padding-top-#{$val} { padding-top: #{$val}px; } .padding-bottom-#{$val} { padding-bottom: #{$val}px; } .padding-v-#{$val} { padding-top: #{$val}px; padding-bottom: #{$val}px; } .padding-#{$val} { padding: #{$val}px; } } .margin-h-auto, .margin-center { margin-left: auto; margin-right: auto; } // ~ transparent // =============================================================================== .transparent-bg { background-color: transparent; } .keep-transparent-bg { background-color: transparent !important; } $bd-directions: ('left', 'bottom', 'right', 'top'); .transparent-bd { border-color: transparent; } .keep-transparent-bd { border-color: transparent !important; } @each $value in $bd-directions { .transparent-bd-#{$value} { border-#{$value}-color: transparent; } .keep-transparent-bd-#{$value} { border-#{$value}-color: transparent !important; } } // ~ border-radius // =============================================================================== .border-radius-8 { border-radius: 8px; } .border-radius-base { border-radius: $--border-radius-base; } .border-radius-small { border-radius: $--border-radius-small; } // color .color-primary { color: $--color-primary; &.light { color: rgba($--color-primary, .6); } } .bg-primary { background: $--color-primary; &.bg-light { background: rgba($--color-primary, .6); } } .color-success { color: $--color-success; &.light { color: rgba($--color-success, .6); } } .bg-success { background: $--color-success; &.bg-light { background: rgba($--color-success, .6); } } .color-warning { color: $--color-warning; &.light { color: rgba($--color-warning, .6); } } .bg-warning { background: $--color-warning; &.bg-light { background: rgba($--color-warning, .6); } } .color-danger { color: $--color-danger; &.light { color: rgba($--color-danger, .6); } } .bg-danger { background: $--color-danger; &.bg-light { background: rgba($--color-danger, .6); } } .color-violet { color: $--color-violet; &.light { color: rgba($--color-violet, .6); } } .bg-violet { background: $--color-violet; &.bg-light { background: rgba($--color-violet, .6); } } .bg-white { background: #FFF; } /* 半透明 */ .opacity-0, .opacity-hide { opacity: 0; } .opacity-half { opacity: .5; } .opacity-1, .opacity-show { opacity: 0; } .keep-opacity-0, .keep-opacity-hide { opacity: 0; } .keep-opacity-half { opacity: .5; } .keep-opacity-1, .keep-opacity-show { opacity: 0; } // other .mouse-pointer { cursor: pointer; } .mouse-default { cursor: default; } .none-select { user-select: none; } .none-events { pointer-events: none; } .anim-default { transition-duration: $-default-duration; }
15,101
https://github.com/ThinkmanWang/thinkutils_plus/blob/master/thinkutils_plus/eventbus/sample/myeventbus.py
Github Open Source
Open Source
MIT
null
thinkutils_plus
ThinkmanWang
Python
Code
32
153
__author__ = 'Xsank' import time from thinkutils_plus.eventbus.eventbus import EventBus from myevent import GreetEvent from myevent import ByeEvent from mylistener import MyListener if __name__=="__main__": eventbus=EventBus() eventbus.register(MyListener()) ge=GreetEvent('world') be=ByeEvent('world') eventbus.async_post(be) eventbus.post(ge) time.sleep(0.1) eventbus.unregister(MyListener()) eventbus.destroy()
6,348
https://github.com/debeat/AudioSegment/blob/master/tests/full.py
Github Open Source
Open Source
MIT
2,019
AudioSegment
debeat
Python
Code
115
399
import sys sys.path.insert(0, '../') import audiosegment as asg import os #testsuites import casa import fft import filterbank import normalize import read_from_file import resample import serde import silence import spectrogram import trim import vad import visualize if __name__ == "__main__": if len(sys.argv) != 2: print("USAGE:", sys.argv[0], os.sep.join("path to wave file.wav".split(' '))) exit(1) os.makedirs("results", exist_ok=True) seg = read_from_file.test(sys.argv[1]) # Print some information about the AudioSegment print("Information:") print(seg) print("Channels:", seg.channels) print("Bits per sample:", seg.sample_width * 8) print("Sampling frequency:", seg.frame_rate) print("Length:", seg.duration_seconds, "seconds") #casa.test(seg) # Test takes too long, so you should really only run this one manually resampled = resample.test(seg) #normalized = normalize.test(resampled) # Currently broken normalized = resampled serde.test(normalized) slices = trim.test(normalized) fft.test(normalized) filterbank.test(normalized) spectrogram.test(normalized) silence.test(normalized) vad.test(normalized)
13,580
https://github.com/minecraftbardev/SinoCraft/blob/master/src/main/java/cx/rain/mc/forgemod/sinocraft/entity/passive/EntityBuffalo.java
Github Open Source
Open Source
MIT
2,021
SinoCraft
minecraftbardev
Java
Code
192
944
package cx.rain.mc.forgemod.sinocraft.entity.passive; import cx.rain.mc.forgemod.sinocraft.entity.ModEntities; import net.minecraft.block.BlockState; import net.minecraft.entity.*; import net.minecraft.entity.ai.goal.*; import net.minecraft.entity.passive.AnimalEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Items; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.DamageSource; import net.minecraft.util.SoundEvent; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import javax.annotation.Nullable; public class EntityBuffalo extends AnimalEntity { public EntityBuffalo(World worldIn) { super(ModEntities.ENTITY_BUFFALO.get(), worldIn); } public EntityBuffalo(EntityType<? extends EntityBuffalo> type, World worldIn) { super(type, worldIn); } @Override protected void registerGoals() { this.goalSelector.addGoal(0, new SwimGoal(this)); this.goalSelector.addGoal(1, new PanicGoal(this, 2.0D)); this.goalSelector.addGoal(2, new BreedGoal(this, 1.0D)); this.goalSelector.addGoal(3, new TemptGoal(this, 1.25D, Ingredient.fromItems(Items.WHEAT), false)); this.goalSelector.addGoal(4, new FollowParentGoal(this, 1.25D)); this.goalSelector.addGoal(5, new WaterAvoidingRandomWalkingGoal(this, 1.0D)); this.goalSelector.addGoal(6, new LookAtGoal(this, PlayerEntity.class, 6.0F)); this.goalSelector.addGoal(7, new LookRandomlyGoal(this)); } // Fixme: Change to static method. // @Override // protected void registerAttributes() { // super.registerAttributes(); // this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(20.0D); // this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue((double) 0.2F); // } @Override protected SoundEvent getAmbientSound() { return SoundEvents.ENTITY_COW_AMBIENT; } @Override protected SoundEvent getHurtSound(DamageSource damageSourceIn) { return SoundEvents.ENTITY_COW_HURT; } @Override protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_COW_DEATH; } @Override protected void playStepSound(BlockPos pos, BlockState blockIn) { this.playSound(SoundEvents.ENTITY_COW_STEP, 0.15F, 1.0F); } @Override protected float getSoundVolume() { return 0.4F; } @Override protected float getStandingEyeHeight(Pose poseIn, EntitySize sizeIn) { return this.isChild() ? sizeIn.height * 0.95F : 1.3F; } @Nullable @Override public AgeableEntity func_241840_a(ServerWorld p_241840_1_, AgeableEntity p_241840_2_) { return ModEntities.ENTITY_BUFFALO.get().create(this.world); } }
37,523
https://github.com/ben-garcia/stack-client/blob/master/src/store/channelDetails/__tests__/reducer.test.ts
Github Open Source
Open Source
MIT
null
stack-client
ben-garcia
TypeScript
Code
148
431
import ChannelDetailsReducer from '../reducer'; describe('ChannelDetailsReducer', () => { const initialState = { isOpen: false, }; it('should return initial state when action.type doesnt match a valid type', () => { const action: any = { type: 'INVALID' }; const result = ChannelDetailsReducer(initialState, action); expect(result).toEqual(initialState); }); it('should return new state when action.type === "OPEN_CHANNEL_DETAILS"', () => { const action: any = { type: 'OPEN_CHANNEL_DETAILS' }; const result = ChannelDetailsReducer(initialState, action); const expected = { isOpen: true, withMembers: false, }; expect(result).toEqual(expected); }); it('should return new state when action.type === "OPEN_CHANNEL_DETAILS_WITH_MEMBERS"', () => { const action: any = { type: 'OPEN_CHANNEL_DETAILS_WITH_MEMBERS' }; const result = ChannelDetailsReducer(initialState, action); const expected = { isOpen: true, withMembers: true, }; expect(result).toEqual(expected); }); it('should return new state when action.type === "CLOSE_CHANNEL_DETAILS"', () => { const action: any = { type: 'CLOSE_CHANNEL_DETAILS_WITH_MEMBERS' }; const result = ChannelDetailsReducer(initialState, action); const expected = { isOpen: false, }; expect(result).toEqual(expected); }); });
31,271
https://github.com/BaihakiTanjung/CrudLaravel/blob/master/resources/views/Kategori/index.blade.php
Github Open Source
Open Source
MIT
2,020
CrudLaravel
BaihakiTanjung
PHP
Code
560
2,680
@extends('layouts.main') @section('content') <div class="row"> <div class="col-md"> <!-- Table with panel --> <div class="card card-cascade narrower"> <!--Card image--> <div class="view view-cascade gradient-card-header blue-gradient narrower py-2 mx-4 mb-3 d-flex justify-content-between align-items-center"> <div> <button type="button" class="btn btn-outline-white btn-rounded btn-sm px-2"> <i class="far fa-file-pdf"></i> </button> <button type="button" class="btn btn-outline-white btn-rounded btn-sm px-2"> <i class="far fa-file-excel"></i> </button> </div> <a href="" class="white-text mx-3">Data Kategori</a> <div> <button type="button" class="btn btn-outline-white btn-rounded btn-sm px-2" data-toggle="modal" data-target="#modalSubscriptionForm"> <i class="fas fa-plus mt-0"></i> </button> <button type="button" class="btn btn-outline-white btn-rounded btn-sm px-2"> <i class="fas fa-info-circle mt-0"></i> </button> </div> </div> <!--/Card image--> <div class="px-4"> <div class="table-wrapper"> <!--Table--> <table id="dtBasicExample" class="table table-hover table-responsive-md"> {{-- <table class="table table-hover mb-0"> --}} <thead> <tr> <th class="th-sm">No </th> <th class="th-sm">Nama </th> <th class="th-sm">Action </th> </tr> </thead> <tbody> @foreach ($tk as $k) <tr> <td>{{$loop->iteration}}</td> <td>{{$k ->nama}}</td> <td> {{-- <a class="btn peach-gradient btn-sm" data-myid="{{$k ->id}}" data-myname="{{$k->nama}}" data-toggle="modal" data-target="#modalSubscriptionFormedit"><i class="fas fa-edit mr-1"></i>Edit</a> <a href="#" class="btn purple-gradient btn-sm hapus" link="kategori" hapus-id="{{$k ->id}}"><i class="fas fa-trash mr-1"></i> Delete</a> --}} <!-- Split button --> <!--Dropdown primary--> <div class="dropdown"> <!--Trigger--> <button class="btn btn-primary dropdown-toggle btn-md" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action</button> <!--Menu--> <div class="dropdown-menu dropdown-primary"> <a class="dropdown-item" href="#" data-myid="{{$k ->id}}" data-myname="{{$k->nama}}" data-toggle="modal" data-target="#modalSubscriptionFormshow">Show</a> <a class="dropdown-item" href="#" data-myid="{{$k ->id}}" data-myname="{{$k->nama}}" data-toggle="modal" data-target="#modalSubscriptionFormedit">Edit</a> <a class="dropdown-item hapus" href="#" link="kategori" hapus-id="{{$k ->id}}">Delete</a> </div> </div> <!--/Dropdown primary--> {{-- <div class="btn-group"> <button type="button" class="btn blue-gradient btn-sm">Action</button> <button type="button" class="btn btn-primary dropdown-toggle btn-sm" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Show</a> <a class="dropdown-item" href="#" data-myid="{{$k ->id}}" data-myname="{{$k->nama}}" data-toggle="modal" data-target="#modalSubscriptionFormedit">Edit</a> <a class="dropdown-item hapus" href="#" link="kategori" hapus-id="{{$k ->id}}">Delete</a> <div class="dropdown-divider"></div> </div> </div> --}} </td> </tr> @endforeach </tbody> </table> <!--Table--> </div> </div> </div> <!-- Table with panel --> </div> </div> <div class="modal fade" id="modalSubscriptionFormshow" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Detail Kategori</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mx-3"> <div class="md-form mb-5"> <i class="fas fa-key prefix grey-text"></i> <input type="text" placeholder="{{time()}}" id="id" class="form-control validate" disabled> <label data-error="wrong" data-success="right" for="form3">Id</label> </div> <div class="md-form mb-4"> <i class="fas fa-database prefix grey-text"></i> <input type="text" name="nama" placeholder="{{time()}}" id="nama" class="form-control validate" disabled> <label data-error="wrong" data-success="right" for="form2">Nama Kategori</label> </div> </div> <div class="modal-footer d-flex justify-content-center"> <button type="button" class="btn blue-gradient waves-effect ml-auto" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="modalSubscriptionForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <form action="{{route('kategori.store')}}" method="POST"> @csrf <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Tambah Kategori</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mx-3"> <div class="md-form mb-5"> <i class="fas fa-key prefix grey-text"></i> <input type="text" placeholder="{{time()}}" id="form3" class="form-control validate" disabled> <label data-error="wrong" data-success="right" for="form3">Id</label> </div> <div class="md-form mb-4"> <i class="fas fa-database prefix grey-text"></i> <input type="text" name="nama" id="form2" class="form-control validate" autofocus> <label data-error="wrong" data-success="right" for="form2">Nama Kategori</label> </div> </div> <div class="modal-footer d-flex justify-content-center"> <button type="submit" class="btn blue-gradient">Send <i class="fas fa-paper-plane-o ml-1"></i></button> </div> </div> </form> </div> </div> <div class="modal fade" id="modalSubscriptionFormedit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <form action="{{route('kategori.update', 'Update')}}" method="POST"> @csrf @method('put') <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Edit Kategori</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mx-3"> {{-- <div class="md-form mb-5"> --}} {{-- <i class="fas fa-key prefix grey-text"></i> --}} <input type="hidden" id="id" name="id" class="form-control validate"> {{-- <label data-error="wrong" data-success="right" for="form3">Id</label> --}} {{-- </div> --}} <div class="md-form mb-4"> <i class="fas fa-database prefix grey-text"></i> <input type="text" name="nama" id="nama" class="form-control validate" autofocus> <label data-error="wrong" data-success="right" for="form2">Nama Kategori</label> </div> </div> <div class="modal-footer d-flex justify-content-center"> <button type="submit" class="btn blue-gradient">Send <i class="fas fa-paper-plane-o ml-1"></i></button> </div> </div> </form> </div> </div> @endsection
25,293
https://github.com/LIARALab/java-activity-recognition-platform/blob/master/src/main/java/org/liara/api/data/entity/TagRelation.java
Github Open Source
Open Source
MIT
null
java-activity-recognition-platform
LIARALab
Java
Code
247
833
package org.liara.api.data.entity; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.liara.api.relation.RelationFactory; import org.liara.api.validation.ApplicationEntityReference; import org.liara.collection.operator.Operator; import org.liara.collection.operator.filtering.Filter; import org.liara.collection.operator.joining.Join; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "tag_relations") public class TagRelation extends ApplicationEntity { @RelationFactory(Tag.class) public static @NonNull Operator tags () { return ApplicationEntity.tags(TagRelation.class); } public static @NonNull Operator tags (@NonNull final TagRelation relation) { return ApplicationEntity.tags(TagRelation.class, relation); } @RelationFactory(TagRelation.class) public static @NonNull Operator tagRelations () { return ApplicationEntity.tagRelations(TagRelation.class); } public static @NonNull Operator tagRelations (@NonNull final TagRelation relation) { return ApplicationEntity.tagRelations(TagRelation.class, relation); } @RelationFactory(Tag.class) public static @NonNull Operator tag () { return Join.inner(Tag.class) .filter(Filter.expression(":this.identifier = :super.tagIdentifier")); } public static @NonNull Operator tag (@NonNull final TagRelation relation) { return Filter.expression(":this.identifier = :tagIdentifier") .setParameter("tagIdentifier", relation.getTagIdentifier()); } @Nullable private Long _entityIdentifier; @Nullable private Class<? extends ApplicationEntity> _entityType; @Nullable private Long _tagIdentifier; public TagRelation () { _entityIdentifier = null; _entityType = null; _tagIdentifier = null; } public TagRelation (@NonNull final TagRelation toCopy) { _entityIdentifier = toCopy.getEntityIdentifier(); _entityType = toCopy.getEntityType(); _tagIdentifier = toCopy.getTagIdentifier(); } @Column(name = "entity_identifier", nullable = false) public @Nullable Long getEntityIdentifier () { return _entityIdentifier; } public void setEntityIdentifier ( @Nullable final Long entityIdentifier ) { _entityIdentifier = entityIdentifier; } @Column(name = "entity_type", nullable = false) public @Nullable Class<? extends ApplicationEntity> getEntityType () { return _entityType; } public void setEntityType (@Nullable final Class<? extends ApplicationEntity> entityType) { _entityType = entityType; } @Column(name = "tag_identifier", nullable = false) @ApplicationEntityReference(Tag.class) public @Nullable Long getTagIdentifier () { return _tagIdentifier; } public void setTagIdentifier (@Nullable final Long tagIdentifier) { _tagIdentifier = tagIdentifier; } }
6,860
https://github.com/gracecompany/develop/blob/master/app/Http/Controllers/ProductCategoryController.php
Github Open Source
Open Source
MIT
null
develop
gracecompany
PHP
Code
178
655
<?php namespace app\Http\Controllers; use App\Category; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use \Ecommerce\helperFunctions; class CategoryController extends Controller { public function __construct() { $this->middleware('isAdmin', ['except' => [ 'show', ]]); } /** * @param $id * @param Request $request */ public function show($id, Request $request) { $category = Category::find($id); if (strtoupper($request->sort) == 'NEWEST') { $products = $category->products()->orderBy('created_at', 'desc')->paginate(40); } elseif (strtoupper($request->sort) == 'HIGHEST') { $products = $category->products()->orderBy('price', 'desc')->paginate(40); } elseif (strtoupper($request->sort) == 'LOWEST') { $products = $category->products()->orderBy('price', 'asc')->paginate(40); } else { $products = $category->products()->paginate(40); } helperFunctions::getCartInfo($cart,$total); return view('site.category', compact('cart', 'total', 'category', 'products')); } /** * @param $id */ public function delete($id) { Category::destroy($id); return \Redirect('/admin/categories')->with([ 'flash_message' => 'Category has been Successfully removed', 'flash-warning' => true, ]); } /** * @param Request $request */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required', 'section_id' => 'required', ]); Category::create($request->all()); return \Redirect('/admin/categories')->with([ 'flash_message' => 'Category successfully Created', ]); } /** * @param $id * @param Request $request */ public function edit($id, Request $request) { $this->validate($request, [ 'name' => 'required', 'section_id' => 'required', ]); Category::find($id)->update($request->all()); return \Redirect()->back()->with([ 'flash_message' => 'Category Successfully Edited', ]); } }
41,953
https://github.com/boostermbkking/https-github.com-danimahardhika-candybar-library/blob/master/core/src/main/java/com/dm/material/dashboard/candybar/databases/Database.java
Github Open Source
Open Source
Apache-2.0
null
https-github.com-danimahardhika-candybar-library
boostermbkking
Java
Code
1,235
4,025
package com.dm.material.dashboard.candybar.databases; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.danimahardhika.android.helpers.core.TimeHelper; import com.dm.material.dashboard.candybar.items.Request; import com.dm.material.dashboard.candybar.items.Wallpaper; import com.dm.material.dashboard.candybar.items.WallpaperJSON; import com.dm.material.dashboard.candybar.utils.LogUtil; import java.util.ArrayList; import java.util.List; /* * CandyBar - Material Dashboard * * Copyright (c) 2014-2016 Dani Mahardhika * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Database extends SQLiteOpenHelper { private static final String DATABASE_NAME = "candybar_database"; private static final int DATABASE_VERSION = 5; private static final String TABLE_REQUEST = "icon_request"; private static final String TABLE_PREMIUM_REQUEST = "premium_request"; private static final String TABLE_WALLPAPERS = "wallpapers"; private static final String KEY_ID = "id"; private static final String KEY_ORDER_ID = "order_id"; private static final String KEY_PRODUCT_ID = "product_id"; private static final String KEY_NAME = "name"; private static final String KEY_ACTIVITY = "activity"; private static final String KEY_REQUESTED_ON = "requested_on"; private static final String KEY_AUTHOR = "author"; private static final String KEY_THUMB_URL = "thumbUrl"; private static final String KEY_URL = "url"; private static final String KEY_ADDED_ON = "added_on"; @NonNull public static Database get(@NonNull Context context) { return new Database(context); } private Database(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE_REQUEST = "CREATE TABLE IF NOT EXISTS " +TABLE_REQUEST+ "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NAME + " TEXT NOT NULL, " + KEY_ACTIVITY + " TEXT NOT NULL, " + KEY_REQUESTED_ON + " DATETIME DEFAULT CURRENT_TIMESTAMP, " + "UNIQUE (" +KEY_ACTIVITY+ ") ON CONFLICT REPLACE)"; String CREATE_TABLE_PREMIUM_REQUEST = "CREATE TABLE IF NOT EXISTS " +TABLE_PREMIUM_REQUEST+ "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_ORDER_ID + " TEXT NOT NULL, " + KEY_PRODUCT_ID + " TEXT NOT NULL, " + KEY_NAME + " TEXT NOT NULL, " + KEY_ACTIVITY + " TEXT NOT NULL, " + KEY_REQUESTED_ON + " DATETIME DEFAULT CURRENT_TIMESTAMP, " + "UNIQUE (" +KEY_ACTIVITY+ ") ON CONFLICT REPLACE)"; String CREATE_TABLE_WALLPAPER = "CREATE TABLE IF NOT EXISTS " +TABLE_WALLPAPERS+ "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NAME+ " TEXT NOT NULL, " + KEY_AUTHOR + " TEXT NOT NULL, " + KEY_URL + " TEXT NOT NULL, " + KEY_THUMB_URL + " TEXT NOT NULL, " + KEY_ADDED_ON + " TEXT NOT NULL, " + "UNIQUE (" +KEY_URL+ ") ON CONFLICT REPLACE)"; db.execSQL(CREATE_TABLE_REQUEST); db.execSQL(CREATE_TABLE_PREMIUM_REQUEST); db.execSQL(CREATE_TABLE_WALLPAPER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { resetDatabase(db, oldVersion); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { resetDatabase(db, oldVersion); } private void resetDatabase(SQLiteDatabase db, int oldVersion) { Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type=\'table\'", null); List<String> tables = new ArrayList<>(); if (cursor.moveToFirst()) { do { tables.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); List<Request> requests = getRequestedApps(db); List<Request> premiumRequest = getPremiumRequest(db); for (int i = 0; i < tables.size(); i++) { try { String dropQuery = "DROP TABLE IF EXISTS " + tables.get(i); if (!tables.get(i).equalsIgnoreCase("SQLITE_SEQUENCE")) db.execSQL(dropQuery); } catch (Exception ignored) {} } onCreate(db); for (int i = 0; i < requests.size(); i++) { addRequest(db, requests.get(i).getName(), requests.get(i).getPackageName(), requests.get(i).getActivity()); } if (oldVersion <= 3) return; for (int i = 0; i < premiumRequest.size(); i++) { addPremiumRequest(db, premiumRequest.get(i).getOrderId(), premiumRequest.get(i).getProductId(), premiumRequest.get(i).getName(), premiumRequest.get(i).getActivity(), premiumRequest.get(i).getRequestedOn()); } } public void addRequest(String name, String activity, String requestedOn) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, name); values.put(KEY_ACTIVITY, activity); if (requestedOn != null) values.put(KEY_REQUESTED_ON, requestedOn); db.insert(TABLE_REQUEST, null, values); db.close(); } private void addRequest(SQLiteDatabase db, String name, String activity, String requestedOn) { if (db == null) return; try { ContentValues values = new ContentValues(); values.put(KEY_NAME, name); values.put(KEY_ACTIVITY, activity); if (requestedOn != null) values.put(KEY_REQUESTED_ON, requestedOn); db.insert(TABLE_REQUEST, null, values); } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); } } public boolean isRequested(String activity) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_REQUEST, null, KEY_ACTIVITY + " = ?", new String[]{activity}, null, null, null, null); int rowCount = cursor.getCount(); cursor.close(); db.close(); return rowCount > 0; } private List<Request> getRequestedApps(@Nullable SQLiteDatabase db) { List<Request> requests = new ArrayList<>(); if (db == null) db = this.getReadableDatabase(); try { Cursor cursor = db.query(TABLE_REQUEST, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Request request = new Request( cursor.getString(1), cursor.getString(2), cursor.getString(3), true); requests.add(request); } while (cursor.moveToNext()); } cursor.close(); } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); } return requests; } public void addPremiumRequest(@Nullable SQLiteDatabase db, String orderId, String productId, String name, String activity, String requestedOn) { if (db == null) db = this.getWritableDatabase(); try { ContentValues values = new ContentValues(); values.put(KEY_ORDER_ID, orderId); values.put(KEY_PRODUCT_ID, productId); values.put(KEY_NAME, name); values.put(KEY_ACTIVITY, activity); if (requestedOn != null) values.put(KEY_REQUESTED_ON, requestedOn); db.insert(TABLE_PREMIUM_REQUEST, null, values); } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); } } public List<Request> getPremiumRequest(@Nullable SQLiteDatabase db) { List<Request> requests = new ArrayList<>(); if (db == null) db = this.getReadableDatabase(); try { Cursor cursor = db.query(TABLE_PREMIUM_REQUEST, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Request request = new Request( cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)); requests.add(request); } while (cursor.moveToNext()); } cursor.close(); } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); } return requests; } public void addWallpapers(WallpaperJSON wallpaper) { String query = "INSERT INTO " +TABLE_WALLPAPERS+ " (" +KEY_NAME+ "," +KEY_AUTHOR+ "," +KEY_URL+ "," +KEY_THUMB_URL+ "," +KEY_ADDED_ON+ ") VALUES (?,?,?,?,?);"; SQLiteDatabase db = this.getWritableDatabase(); SQLiteStatement statement = db.compileStatement(query); db.beginTransaction(); for (int i = 0; i < wallpaper.getWalls.size(); i++) { statement.clearBindings(); statement.bindString(1, wallpaper.getWalls.get(i).name); statement.bindString(2, wallpaper.getWalls.get(i).author); statement.bindString(3, wallpaper.getWalls.get(i).url); statement.bindString(4, wallpaper.getWalls.get(i).thumbUrl == null ? wallpaper.getWalls.get(i).url : wallpaper.getWalls.get(i).thumbUrl); statement.bindString(5, TimeHelper.getLongDateTime()); statement.execute(); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); } public void addWallpapers(List<Wallpaper> wallpapers) { String query = "INSERT INTO " +TABLE_WALLPAPERS+ " (" +KEY_NAME+ "," +KEY_AUTHOR+ "," +KEY_URL+ "," +KEY_THUMB_URL+ "," +KEY_ADDED_ON+ ") VALUES (?,?,?,?,?);"; SQLiteDatabase db = this.getWritableDatabase(); SQLiteStatement statement = db.compileStatement(query); db.beginTransaction(); for (int i = 0; i < wallpapers.size(); i++) { statement.clearBindings(); statement.bindString(1, wallpapers.get(i).getName()); statement.bindString(2, wallpapers.get(i).getAuthor()); statement.bindString(3, wallpapers.get(i).getURL()); statement.bindString(4, wallpapers.get(i).getThumbUrl() == null ? wallpapers.get(i).getURL() : wallpapers.get(i).getThumbUrl()); statement.bindString(5, TimeHelper.getLongDateTime()); statement.execute(); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); } public int getWallpapersCount() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, null, null); int rowCount = cursor.getCount(); cursor.close(); db.close(); return rowCount; } public List<Wallpaper> getWallpapers() { List<Wallpaper> wallpapers = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, KEY_ADDED_ON + " DESC, " +KEY_ID); if (cursor.moveToFirst()) { do { Wallpaper wallpaper = new Wallpaper( cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)); wallpapers.add(wallpaper); } while (cursor.moveToNext()); } cursor.close(); db.close(); return wallpapers; } public Wallpaper getRandomWallpaper() { Wallpaper wallpaper = null; SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " +TABLE_WALLPAPERS+ " ORDER BY RANDOM() LIMIT 1"; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { wallpaper = new Wallpaper( cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)); } while (cursor.moveToNext()); } cursor.close(); db.close(); return wallpaper; } public void deleteIconRequestData() { SQLiteDatabase db = this.getWritableDatabase(); db.delete("SQLITE_SEQUENCE", "NAME = ?", new String[]{TABLE_REQUEST}); db.delete(TABLE_REQUEST, null, null); db.close(); } public void deleteWallpapers(List<Wallpaper> wallpapers) { SQLiteDatabase db = this.getWritableDatabase(); for (int i = 0; i < wallpapers.size(); i++) { db.delete(TABLE_WALLPAPERS, KEY_URL +" = ?", new String[]{wallpapers.get(i).getURL()}); } db.close(); } public void deleteWallpapers() { SQLiteDatabase db = this.getWritableDatabase(); db.delete("SQLITE_SEQUENCE", "NAME = ?", new String[]{TABLE_WALLPAPERS}); db.delete(TABLE_WALLPAPERS, null, null); db.close(); } }
10,117
https://github.com/TheDragonCode/laravel-cache/blob/master/tests/Concerns/Userable.php
Github Open Source
Open Source
MIT
2,023
laravel-cache
TheDragonCode
PHP
Code
48
176
<?php declare(strict_types=1); namespace Tests\Concerns; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Support\Facades\Auth; use Tests\Fixtures\Models\User; trait Userable { protected $user_id = 123; protected $user_name = 'John Doe'; protected function auth(): void { Auth::setUser( $this->createUser() ); } protected function createUser(): Authenticatable { return new User([ 'id' => $this->user_id, 'name' => $this->user_name, ]); } }
13,548
https://github.com/sidrockzz/web-search-flask/blob/master/run.sh
Github Open Source
Open Source
Apache-2.0
2,020
web-search-flask
sidrockzz
Shell
Code
3
14
#!/bin/bash python project/app.py
18,534
https://github.com/WoN-Hackathon-2019/won-airqualitybot/blob/master/src/main/java/won/bot/airquality/dto/LocationMeasurements.java
Github Open Source
Open Source
Apache-2.0
null
won-airqualitybot
WoN-Hackathon-2019
Java
Code
77
217
package won.bot.airquality.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.Setter; import won.protocol.model.Coordinate; import java.util.List; @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) public class LocationMeasurements { private String location; private Coordinates coordinates; private String city; private String country; private List<Measurement> measurements; @Override public String toString() { return "LocationMeasurements{" + "location='" + location + '\'' + ", coordinates=" + coordinates + ", city='" + city + '\'' + ", country='" + country + '\'' + ", measurements=" + measurements + '}'; } }
34,130
https://github.com/olliemath/pypy/blob/master/pypy/module/__pypy__/test/test_stderrprinter.py
Github Open Source
Open Source
Apache-2.0, OpenSSL
2,021
pypy
olliemath
Python
Code
49
154
def app_test_stderrprinter(): from __pypy__ import StdErrPrinter p = StdErrPrinter(2) assert repr(p).startswith("<StdErrPrinter(fd=2) object at") p.close() # this should be a no-op p.flush() # this should be a no-op assert p.fileno() == 2 assert p.write('foo') == 3 raises(TypeError, p.write, b'foo') assert not p.closed assert p.encoding is None assert p.mode == 'w'
30,128
https://github.com/tensorflow/docs-l10n/blob/master/site/ko/guide/effective_tf2.ipynb
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-generic-cla
2,023
docs-l10n
tensorflow
Jupyter Notebook
Code
2,548
12,331
{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "Tce3stUlHN0L" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "tuOe1ymfHZPu" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "qFdPvlXBOdUN" }, "source": [ "# 효과적인 Tensorflow 2" ] }, { "cell_type": "markdown", "metadata": { "id": "MfBg1C5NB3X0" }, "source": [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n", " <td><a target=\"_blank\" href=\"https://www.tensorflow.org/guide/effective_tf2\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\">TensorFlow.org에서보기</a></td>\n", " <td> <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/guide/effective_tf2.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\">Google Colab에서 실행하기</a> </td>\n", " <td> <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ko/guide/effective_tf2.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\">GitHub에서 소스 보기</a> </td>\n", " <td> <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/guide/effective_tf2.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\">노트북 다운로드하기</a> </td>\n", "</table>" ] }, { "cell_type": "markdown", "metadata": { "id": "xHxb-dlhMIzW" }, "source": [ "## 개요\n", "\n", "이 가이드는 TensorFlow 2(TF2)를 사용하여 코드를 작성하기 위한 모범 사례 목록을 제공하며 최근에 TensorFlow 1(TF1)에서 전환한 사용자를 위해 작성되었습니다. TF1 코드를 TF2로 마이그레이션하는 방법에 대한 자세한 내용은 [가이드의 마이그레이션 섹션](https://tensorflow.org/guide/migrate)을 참고하세요." ] }, { "cell_type": "markdown", "metadata": { "id": "MUXex9ctTuDB" }, "source": [ "## 설치하기\n", "\n", "이 가이드의 예제에서 사용하는 TensorFlow 및 기타 종속 항목을 가져옵니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IqR2PQG4ZaZ0" }, "outputs": [], "source": [ "import tensorflow as tf\n", "import tensorflow_datasets as tfds" ] }, { "cell_type": "markdown", "metadata": { "id": "Ngds9zateIY8" }, "source": [ "## 관용적 텐서플로우 2.0 권장 사항" ] }, { "cell_type": "markdown", "metadata": { "id": "B3RdHaroMAi4" }, "source": [ "### 코드를 더 작은 모듈로 리팩토링\n", "\n", "필요에 따라 호출되는 더 작은 함수로 코드를 리팩토링하는 것이 좋습니다. 최고의 성능을 위해서는 `tf.function`에서 가능한 가장 큰 계산 블록을 장식해야 합니다(`tf.function`로 호출하여 중첩한 Python 함수는 `tf.function`에 다른 `jit_compile` 설정을 사용하려는 경우가 아니면 별도의 장식이 필요하지 않음). 사용 사례에 따라 여러 훈련 단계 또는 전체 훈련 루프가 될 수도 있습니다. 추론 사용 사례는 단일 모델 전달 경로일 수 있습니다." ] }, { "cell_type": "markdown", "metadata": { "id": "Rua1l8et3Evd" }, "source": [ "### 일부 `tf.keras.optimizer`의 기본 훈련률 조정하기\n", "\n", "<a name=\"optimizer_defaults\"></a>\n", "\n", "일부 Keras 옵티마이저는 TF2에서 다른 훈련률을 갖습니다. 모델의 수렴 동작이 변경되면 기본 훈련률을 확인해야 합니다.\n", "\n", "`optimizers.SGD`, `optimizers.Adam` 또는 `optimizers.RMSprop`에는 변경사항이 없습니다.\n", "\n", "다음 기본 훈련률이 변경되었습니다.\n", "\n", "- `0.01`에서 `0.001`까지 `optimizers.Adagrad`\n", "- `1.0`에서 `0.001`까지 `optimizers.Adadelta`\n", "- `0.002`에서 `0.001`까지 `optimizers.Adamax`\n", "- `0.002`에서 `0.001`까지 `optimizers.Nadam`" ] }, { "cell_type": "markdown", "metadata": { "id": "z6LfkpsEldEV" }, "source": [ "### `tf.Module` 및 Keras 레이어를 사용하여 변수 관리\n", "\n", "`tf.Module` 및 `tf.keras.layers.Layer`는 편리한 `variables` 및 `trainable_variables` 속성을 제공하고, 이는 모든 종속 변수를 재귀적으로 수집합니다. 이렇게 하면 변수가 사용되는 위치에서 로컬로 변수를 쉽게 관리할 수 있습니다." ] }, { "cell_type": "markdown", "metadata": { "id": "WQ2U0rj1oBlc" }, "source": [ "Keras 레이어와 모델은 tf.train.Checkpointable로부터 상속하고 @tf.function과 통합되어 Keras 객체에서 저장 모델을 직접 검사하거나 내보낼 수 있도록 합니다. 이러한 통합을 활용하기 위해 반드시 Keras의 Model.fit API를 사용해야 하는 것은 아닙니다.\n", "\n", "Keras를 사용하여 관련 변수의 하위 집합을 수집하는 방법을 알아보려면 Keras 가이드의 [전이 학습 및 미세 조정](https://www.tensorflow.org/guide/keras/transfer_learning#transfer_learning_fine-tuning_with_a_custom_training_loop) 섹션을 읽어보세요." ] }, { "cell_type": "markdown", "metadata": { "id": "j34MsfxWodG6" }, "source": [ "### `tf.data.Dataset`와 `tf.function` 결합하기\n", "\n", "[TensorFlow 데이터세트](https://tensorflow.org/datasets) 패키지(`tfds`)에는 사전 정의된 데이터세트를 `tf.data.Dataset` 객체로 로드하는 유틸리티가 포함되어 있습니다. 이 예제에서는 `tfds`를 사용하여 MNIST 데이터세트를 로드할 수 있습니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BMgxaLH74_s-" }, "outputs": [], "source": [ "datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)\n", "mnist_train, mnist_test = datasets['train'], datasets['test']" ] }, { "cell_type": "markdown", "metadata": { "id": "hPJhEuvj5VfR" }, "source": [ "그런 다음 훈련에 사용할 데이터를 준비합니다.\n", "\n", "- 각 이미지의 크기를 다시 조정합니다.\n", "- 예제의 순서를 셔플링합니다.\n", "- 이미지 및 레이블 배치를 수집합니다.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "StBRHtJM2S7o" }, "outputs": [], "source": [ "BUFFER_SIZE = 10 # Use a much larger value for real code\n", "BATCH_SIZE = 64\n", "NUM_EPOCHS = 5\n", "\n", "\n", "def scale(image, label):\n", " image = tf.cast(image, tf.float32)\n", " image /= 255\n", "\n", " return image, label" ] }, { "cell_type": "markdown", "metadata": { "id": "SKq14zKKFAdv" }, "source": [ "이 예제를 짧게 유지하려면 5개의 배치만 반환하도록 데이터세트를 자릅니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_J-o4YjG2mkM" }, "outputs": [], "source": [ "train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\n", "test_data = mnist_test.map(scale).batch(BATCH_SIZE)\n", "\n", "STEPS_PER_EPOCH = 5\n", "\n", "train_data = train_data.take(STEPS_PER_EPOCH)\n", "test_data = test_data.take(STEPS_PER_EPOCH)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XEqdkH54VM6c" }, "outputs": [], "source": [ "image_batch, label_batch = next(iter(train_data))" ] }, { "cell_type": "markdown", "metadata": { "id": "loTPH2Pz4_Oj" }, "source": [ "메모리에 맞는 훈련 데이터를 반복하려면 일반 Python 반복을 사용해야 합니다. 그렇지 않을때 이 디스크에서 훈련 데이터를 스트리밍하는 가장 좋은 방법은 `tf.data.Dataset`입니다. 데이터세트는 [반복할 수 있으며(반복기는 아님)](https://docs.python.org/3/glossary.html#term-iterable) 즉시 실행에서 다른 Python 반복기처럼 동작합니다. 코드를 `tf.function`로 래핑하여 데이터세트 비동기 프리페치/스트리밍 기능을 온전히 활용할 수 있습니다. 이는 AutoGraph를 사용하여 Python 반복기를 동등한 그래프 연산으로 교체합니다.\n", "\n", "```python\n", "@tf.function\n", "def train(model, dataset, optimizer):\n", " for x, y in dataset:\n", " with tf.GradientTape() as tape:\n", " # training=True is only needed if there are layers with different\n", " # behavior during training versus inference (e.g. Dropout).\n", " prediction = model(x, training=True)\n", " loss = loss_fn(prediction, y)\n", " gradients = tape.gradient(loss, model.trainable_variables)\n", " optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n", "```\n", "\n", "Keras Model.fit API를 사용하면 데이터세트 반복에 대해 신경 쓸 필요가 없습니다.\n", "\n", "```python\n", "model.compile(optimizer=optimizer, loss=loss_fn)\n", "model.fit(dataset)\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "mSev7vZC5GJB" }, "source": [ "<a name=\"keras_training_loops\"></a>\n", "\n", "### Keras 훈련 루프 사용하기\n", "\n", "훈련 과정을 세부적으로 제어할 필요가 없다면 케라스의 내장 메서드인 fit, evaluate, predict를 사용하는 것이 좋습니다. 이 메서드들은 모델 구현(Sequential, 함수형 API, 클래스 상속)에 상관없이 일관된 훈련 인터페이스를 제공합니다.\n", "\n", "이 메소드의 장점은 다음과 같습니다.\n", "\n", "- Numpy 배열, Python 제너레이터, `tf.data.Datasets`를 사용할 수 있습니다.\n", "- 정규화 및 활성화 손실을 자동으로 적용합니다.\n", "- [하드웨어 구성에 관계 없이](distributed_training.ipynb) 훈련 코드가 동일하게 유지되는 `tf.distribute`를 지원합니다.\n", "- 손실 및 메트릭으로 임의의 호출 가능 항목을 지원합니다.\n", "- `tf.keras.callbacks.TensorBoard`와 같은 콜백과 사용자 정의 콜백을 지원합니다.\n", "- TensorFlow 그래프를 사용하여 자동으로 성능 기준을 맞춥니다.\n", "\n", "다음은 `Dataset`를 사용하여 모델을 훈련하는 예제입니다. 작동 방식에 대한 자세한 내용은 [튜토리얼](https://tensorflow.org/tutorials)을 확인합니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "uzHFCzd45Rae" }, "outputs": [], "source": [ "model = tf.keras.Sequential([\n", " tf.keras.layers.Conv2D(32, 3, activation='relu',\n", " kernel_regularizer=tf.keras.regularizers.l2(0.02),\n", " input_shape=(28, 28, 1)),\n", " tf.keras.layers.MaxPooling2D(),\n", " tf.keras.layers.Flatten(),\n", " tf.keras.layers.Dropout(0.1),\n", " tf.keras.layers.Dense(64, activation='relu'),\n", " tf.keras.layers.BatchNormalization(),\n", " tf.keras.layers.Dense(10)\n", "])\n", "\n", "# Model is the full model w/o custom layers\n", "model.compile(optimizer='adam',\n", " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " metrics=['accuracy'])\n", "\n", "model.fit(train_data, epochs=NUM_EPOCHS)\n", "loss, acc = model.evaluate(test_data)\n", "\n", "print(\"Loss {}, Accuracy {}\".format(loss, acc))" ] }, { "cell_type": "markdown", "metadata": { "id": "LQTaHTuK5S5A" }, "source": [ "<a name=\"custom_loop\"></a>\n", "\n", "### 훈련 루프 사용자 정의하기 및 자체 루프 작성하기\n", "\n", "Keras 모델이 적합하지만 훈련 단계 또는 외부 훈련 루프에 더 많은 유연성과 제어가 필요한 경우 자체 훈련 단계 또는 전체 훈련 루프를 구현할 수 있습니다. 자세한 내용은 [`fit` 사용자 정의하기](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit)의 Keras 가이드를 참조해 주세요.\n", "\n", "`tf.keras.callbacks.Callback`으로 많은 것을 구현할 수도 있습니다.\n", "\n", "이 메서드에는 [이전에 언급한](#keras_training_loops) 많은 장점 외에도 훈련 단계와 외부 루프까지 제어할 수 있다는 장점도 있습니다.\n", "\n", "표준 훈련 루프에는 세 단계가 있습니다.\n", "\n", "1. Python 생성기 또는 `tf.data.Dataset`를 반복하여 예제 배치를 가져옵니다.\n", "2. `tf.GradientTape`를 사용하여 그래디언트를 수집합니다.\n", "3. `tf.keras.optimizers` 중 하나를 사용하여 모델 변수에 가중치 업데이트를 적용합니다.\n", "\n", "기억해야 하는 사항:\n", "\n", "- 서브 클래화된 레이어 및 모델의 `call` 메서드에 항상 `training` 인수를 포함합니다.\n", "- `training` 인수가 올바르게 설정된 모델을 호출하는지 확인합니다.\n", "- 사용법에 따라 데이터 배치에서 모델을 실행할 때까지 모델 변수가 존재하지 않을 수 있습니다.\n", "- 모델의 정규화 손실 등은 수동으로 처리해야 합니다.\n", "\n", "변수 이니셜라이저를 실행하거나 수동 제어 종속성을 추가할 필요가 없습니다. `tf.function`은 생성 시 자동 제어 종속성과 변수 초기화를 처리합니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gQooejfYlQeF" }, "outputs": [], "source": [ "model = tf.keras.Sequential([\n", " tf.keras.layers.Conv2D(32, 3, activation='relu',\n", " kernel_regularizer=tf.keras.regularizers.l2(0.02),\n", " input_shape=(28, 28, 1)),\n", " tf.keras.layers.MaxPooling2D(),\n", " tf.keras.layers.Flatten(),\n", " tf.keras.layers.Dropout(0.1),\n", " tf.keras.layers.Dense(64, activation='relu'),\n", " tf.keras.layers.BatchNormalization(),\n", " tf.keras.layers.Dense(10)\n", "])\n", "\n", "optimizer = tf.keras.optimizers.Adam(0.001)\n", "loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n", "\n", "@tf.function\n", "def train_step(inputs, labels):\n", " with tf.GradientTape() as tape:\n", " predictions = model(inputs, training=True)\n", " regularization_loss=tf.math.add_n(model.losses)\n", " pred_loss=loss_fn(labels, predictions)\n", " total_loss=pred_loss + regularization_loss\n", "\n", " gradients = tape.gradient(total_loss, model.trainable_variables)\n", " optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n", "\n", "for epoch in range(NUM_EPOCHS):\n", " for inputs, labels in train_data:\n", " train_step(inputs, labels)\n", " print(\"Finished epoch\", epoch)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "WikxMFGgo3oZ" }, "source": [ "### Python 제어 흐름으로 `tf.function` 활용하기\n", "\n", "`tf.function`은 데이터에 따라 결정되는 제어 흐름을 `tf.cond`와 `tf.while_loop`와 같은 그래프 모드로 변환하는 방법을 제공합니다.\n", "\n", "데이터에 의존하는 제어 흐름이 나타나는 대표적인 곳은 시퀀스 모델입니다. `tf.keras.layers.RNN`은 RNN 셀을 래핑하여 반복을 정적으로 또는 동적으로 전개할 수 있도록 합니다. 예를 들어 다음과 같은 동적 언롤을 다시 구현할 수 있습니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "n5UebfChRu4T" }, "outputs": [], "source": [ "class DynamicRNN(tf.keras.Model):\n", "\n", " def __init__(self, rnn_cell):\n", " super(DynamicRNN, self).__init__(self)\n", " self.cell = rnn_cell\n", "\n", " @tf.function(input_signature=[tf.TensorSpec(dtype=tf.float32, shape=[None, None, 3])])\n", " def call(self, input_data):\n", "\n", " # [batch, time, features] -> [time, batch, features]\n", " input_data = tf.transpose(input_data, [1, 0, 2])\n", " timesteps = tf.shape(input_data)[0]\n", " batch_size = tf.shape(input_data)[1]\n", " outputs = tf.TensorArray(tf.float32, timesteps)\n", " state = self.cell.get_initial_state(batch_size = batch_size, dtype=tf.float32)\n", " for i in tf.range(timesteps):\n", " output, state = self.cell(input_data[i], state)\n", " outputs = outputs.write(i, output)\n", " return tf.transpose(outputs.stack(), [1, 0, 2]), state" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NhBI_SGKQVIB" }, "outputs": [], "source": [ "lstm_cell = tf.keras.layers.LSTMCell(units = 13)\n", "\n", "my_rnn = DynamicRNN(lstm_cell)\n", "outputs, state = my_rnn(tf.random.normal(shape=[10,20,3]))\n", "print(outputs.shape)" ] }, { "cell_type": "markdown", "metadata": { "id": "du7bn3NX7iIr" }, "source": [ "자세한 정보는 [`tf.function` 가이드](https://www.tensorflow.org/guide/function)를 참고합니다." ] }, { "cell_type": "markdown", "metadata": { "id": "SUAYhgL_NomT" }, "source": [ "### 새로운 스타일의 메트릭 및 손실\n", "\n", "메트릭과 손실은 모두 `tf.function`에서 즉시 작동하는 객체입니다.\n", "\n", "손실 객체는 호출할 수 있으며 (`y_true`, `y_pred`)를 인수로 예상합니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Pf5gcwMzNs8F" }, "outputs": [], "source": [ "cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n", "cce([[1, 0]], [[-1.0,3.0]]).numpy()" ] }, { "cell_type": "markdown", "metadata": { "id": "a89m-wRfxyfV" }, "source": [ "#### 메트릭을 사용하여 데이터를 수집하고 표시하기\n", "\n", "`tf.metrics`를 사용하여 데이터를 집계하고 `tf.summary`를 사용하여 요약문을 기록하고 컨텍스트 관리자를 사용하여 작성자에게 리디렉션할 수 있습니다. 요약문은 작성자에게 직접 내보내지므로 호출 사이트에서 `step` 값을 제공해야 합니다.\n", "\n", "```python\n", "summary_writer = tf.summary.create_file_writer('/tmp/summaries')\n", "with summary_writer.as_default():\n", " tf.summary.scalar('loss', 0.1, step=42)\n", "```\n", "\n", "요약문으로 기록하기 전에 `tf.metrics`를 사용하여 데이터를 집계합니다. 메트릭은 정적(Stateful)이기에 `result` 메서드(예: `Mean.result`)를 호출하면 값이 누적되고 누적 결과가 반환됩니다. `Model.reset_states`로 누적된 값을 삭제합니다.\n", "\n", "```python\n", "def train(model, optimizer, dataset, log_freq=10):\n", " avg_loss = tf.keras.metrics.Mean(name='loss', dtype=tf.float32)\n", " for images, labels in dataset:\n", " loss = train_step(model, optimizer, images, labels)\n", " avg_loss.update_state(loss)\n", " if tf.equal(optimizer.iterations % log_freq, 0):\n", " tf.summary.scalar('loss', avg_loss.result(), step=optimizer.iterations)\n", " avg_loss.reset_states()\n", "\n", "def test(model, test_x, test_y, step_num):\n", " # training=False is only needed if there are layers with different\n", " # behavior during training versus inference (e.g. Dropout).\n", " loss = loss_fn(model(test_x, training=False), test_y)\n", " tf.summary.scalar('loss', loss, step=step_num)\n", "\n", "train_summary_writer = tf.summary.create_file_writer('/tmp/summaries/train')\n", "test_summary_writer = tf.summary.create_file_writer('/tmp/summaries/test')\n", "\n", "with train_summary_writer.as_default():\n", " train(model, optimizer, dataset)\n", "\n", "with test_summary_writer.as_default():\n", " test(model, test_x, test_y, optimizer.iterations)\n", "```\n", "\n", "텐서보드(TensorBoard)에서 요약문 로그 디렉터리를 지정하여 생성된 요약문을 시각화합니다.\n", "\n", "```shell\n", "tensorboard --logdir /tmp/summaries\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "0tx7FyM_RHwJ" }, "source": [ "텐서보드에서 시각화를 생성할 수 있도록 `tf.summary` API를 사용하여 요약문 데이터를 작성합니다. 자세한 정보는 <a data-md-type=\"raw_html\" href=\"https://www.tensorflow.org/tensorboard/migrate#in_tf_2x\">`tf.summary` 가이드</a>를 참고합니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HAbA0fKW58CH" }, "outputs": [], "source": [ "# Create the metrics\n", "loss_metric = tf.keras.metrics.Mean(name='train_loss')\n", "accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n", "\n", "@tf.function\n", "def train_step(inputs, labels):\n", " with tf.GradientTape() as tape:\n", " predictions = model(inputs, training=True)\n", " regularization_loss=tf.math.add_n(model.losses)\n", " pred_loss=loss_fn(labels, predictions)\n", " total_loss=pred_loss + regularization_loss\n", "\n", " gradients = tape.gradient(total_loss, model.trainable_variables)\n", " optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n", " # Update the metrics\n", " loss_metric.update_state(total_loss)\n", " accuracy_metric.update_state(labels, predictions)\n", "\n", "\n", "for epoch in range(NUM_EPOCHS):\n", " # Reset the metrics\n", " loss_metric.reset_states()\n", " accuracy_metric.reset_states()\n", "\n", " for inputs, labels in train_data:\n", " train_step(inputs, labels)\n", " # Get the metric results\n", " mean_loss=loss_metric.result()\n", " mean_accuracy = accuracy_metric.result()\n", "\n", " print('Epoch: ', epoch)\n", " print(' loss: {:.3f}'.format(mean_loss))\n", " print(' accuracy: {:.3f}'.format(mean_accuracy))\n" ] }, { "cell_type": "markdown", "metadata": { "id": "bG9AaMzih3eh" }, "source": [ "#### 저장과 복원\n", "\n", "<a name=\"keras_metric_names\"></a>\n", "\n", "Keras 모델은 메트릭 이름을 일관성 있게 처리합니다. 메트릭 목록의 문자열을 전달하면 *일치하는* 문자열을 메트릭의 `name`으로 사용합니다. 이러한 이름은 `model.fit`로 반환한 기록 객체와 `keras.callbacks`에 전달된 로그에서 볼 수 있습니다. 메트릭 목록에서 전달한 문자열로 설정됩니다. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1iODIsGDgyYd" }, "outputs": [], "source": [ "model.compile(\n", " optimizer = tf.keras.optimizers.Adam(0.001),\n", " loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name=\"my_accuracy\")])\n", "history = model.fit(train_data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8oGzs_TlisKJ" }, "outputs": [], "source": [ "history.history.keys()" ] }, { "cell_type": "markdown", "metadata": { "id": "JaB2z2XIyhcr" }, "source": [ "### 디버깅\n", "\n", "즉시 실행을 사용하여 코드를 단계별로 실행하고 형상, 데이터 유형 및 값을 검사할 수 있습니다. `tf.function`, `tf.keras` 등과 같은 특정 API는 성능 및 이식성을 위해 그래프 실행을 사용하도록 설계되었습니다. 디버깅할 때 이 코드 내에서 즉시 실행을 사용하려면 `tf.config.run_functions_eagerly(True)`를 사용합니다.\n", "\n", "예제:\n", "\n", "```python\n", "@tf.function\n", "def f(x):\n", " if x > 0:\n", " import pdb\n", " pdb.set_trace()\n", " x = x + 1\n", " return x\n", "\n", "tf.config.run_functions_eagerly(True)\n", "f(tf.constant(1))\n", "```\n", "\n", "```\n", ">>> f()\n", "-> x = x + 1\n", "(Pdb) l\n", " 6 @tf.function\n", " 7 def f(x):\n", " 8 if x > 0:\n", " 9 import pdb\n", " 10 pdb.set_trace()\n", " 11 -> x = x + 1\n", " 12 return x\n", " 13\n", " 14 tf.config.run_functions_eagerly(True)\n", " 15 f(tf.constant(1))\n", "[EOF]\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "gdvGF2FvbBXZ" }, "source": [ "이는 Keras 모델 및 즉시 실행을 지원하는 기타 API에서도 작동합니다.\n", "\n", "```python\n", "class CustomModel(tf.keras.models.Model):\n", "\n", " @tf.function\n", " def call(self, input_data):\n", " if tf.reduce_mean(input_data) > 0:\n", " return input_data\n", " else:\n", " import pdb\n", " pdb.set_trace()\n", " return input_data // 2\n", "\n", "\n", "tf.config.run_functions_eagerly(True)\n", "model = CustomModel()\n", "model(tf.constant([-2, -4]))\n", "```\n", "\n", "```\n", ">>> call()\n", "-> return input_data // 2\n", "(Pdb) l\n", " 10 if tf.reduce_mean(input_data) > 0:\n", " 11 return input_data\n", " 12 else:\n", " 13 import pdb\n", " 14 pdb.set_trace()\n", " 15 -> return input_data // 2\n", " 16\n", " 17\n", " 18 tf.config.run_functions_eagerly(True)\n", " 19 model = CustomModel()\n", " 20 model(tf.constant([-2, -4]))\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "S0-F-bvJXKD8" }, "source": [ "참고 사항:\n", "\n", "- `fit`, `evaluate`, `predict`와 같은 `tf.keras.Model` 메서드는 관련된 `tf.function`을 사용하여 [그래프](https://www.tensorflow.org/guide/intro_to_graphs)로 실행합니다.\n", "\n", "- `tf.keras.Model.compile`을 사용할 경우 `run_eagerly = True`를 설정하여 `Model` 로직이 `tf.function`으로 래핑되지 않도록 합니다.\n", "\n", "- `tf.data.experimental.enable_debug_mode`를 사용하여 `tf.data`에 대해 디버그 모드를 사용하도록 설정합니다. 자세한 내용은 [API 문서](https://www.tensorflow.org/api_docs/python/tf/data/experimental/enable_debug_mode)를 참고합니다.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "wxa5yKK7bym0" }, "source": [ "### 객체에 `tf.Tensors` 유지 금지\n", "\n", "이러한 텐서 객체는 `tf.function` 또는 Eager 컨텍스트에서 생성될 수 있으며 이러한 텐서는 다르게 동작합니다. 중간 값에는 항상 `tf.Tensor`를 사용합니다.\n", "\n", "상태를 추적하려면 양쪽 컨텍스트에서 항상 사용할 수 있는 `tf.Variable`을 사용합니다. 자세히 알아보려면<a data-md-type=\"raw_html\" href=\"https://www.tensorflow.org/guide/variable\">`tf.Variable` 가이드</a>를 읽어보세요.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "FdXLLYa2uAyx" }, "source": [ "## 리소스 및 추가 읽을거리\n", "\n", "- TF2 사용 방법에 대해 자세히 알아보려면 TF2 [가이드](https://tensorflow.org/guide) 및 [튜토리얼](https://tensorflow.org/tutorials)을 읽어보세요.\n", "\n", "- 이전에 TF1.x를 사용한 경우 코드를 TF2로 마이그레이션하는 것이 좋습니다. 자세히 알아보려면 [마이그레이션 가이드](https://tensorflow.org/guide/migrate)를 읽어보세요." ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "effective_tf2.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
34,143
https://github.com/XiaoXiangWang/ADSDKCoreKit/blob/master/PGFoundationKit/PGFoundationKit/NSBundle/NSBundle+PGSDKCommon.h
Github Open Source
Open Source
Apache-2.0
null
ADSDKCoreKit
XiaoXiangWang
C
Code
33
132
// // NSBundle+PGSDKCommon.h // PGFoundationKit // // Created by 汪潇翔 on 15/5/8. // Copyright (c) 2015年 PGSDK. All rights reserved. // #import <Foundation/Foundation.h> #define APP_VERSION [NSBundle PGSDK_AppVersion] @interface NSBundle (PGSDKCommon) +(NSString*)PGSDK_AppVersion; +(NSDictionary*)PGSDK_infoDictionary; @end
28,908
https://github.com/spurti-chopra/Autoport/blob/master/chef-repo/cookbooks/buildServer/recipes/protobuf_source_remove.rb
Github Open Source
Open Source
Apache-2.0
2,016
Autoport
spurti-chopra
Ruby
Code
85
355
# Recipe would uninstall/remove protobuf package installed via source. include_recipe 'buildServer::get_log' version = node['buildServer']['protobuf']['version'] source_dir = node['buildServer']['protobuf']['source_dir'] install_prefix = "#{node['buildServer']['protobuf']['install_prefix']}-#{version}" protobuf_pkg = "protobuf-#{version}" ext = node['buildServer']['protobuf']['ext'] archive_dir = node['buildServer']['download_location'] arch = node['kernel']['machine'] if ext.empty? ext = ArchiveLog.getExtension('protobuf', version) end [ "#{install_prefix}/bin/protoc", "/etc/profile.d/protobuf.sh" ].each do |fil| file fil do action :delete ignore_failure true end end directory "#{source_dir}/#{protobuf_pkg}" do action :delete recursive true notifies :delete, "file[#{install_prefix}/bin/protoc]", :immediately ignore_failure true end record = "protobuf,#{version},protobuf_source,protobuf,#{arch},#{ext},#{protobuf_pkg}#{ext}" buildServer_log "protobuf" do name "protobuf" log_location node['log_location'] log_record record action :remove ignore_failure true end
19,284
https://github.com/jjsingh/Udm-Base/blob/master/udm-plugin/index.php
Github Open Source
Open Source
Apache-2.0
2,018
Udm-Base
jjsingh
PHP
Code
2,379
12,659
<?php ################################################################################ # //Admin Panel Functions Start ################################################################################ //Admin Scripts add_action( 'admin_head', 'wp_admin_header_scripts' ); function wp_admin_header_scripts( $hook_suffix ) { wp_enqueue_style( 'udm-bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' ); wp_enqueue_style( 'udm-fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css' ); wp_enqueue_style( 'udm-admin', get_template_directory_uri() . '/udm-plugin/css/udm-admin.css' ); wp_enqueue_script( 'udm-popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js'); wp_enqueue_script( 'udm-bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js' ); } add_action( 'admin_enqueue_scripts', 'wp_enqueue_color_picker' ); function wp_enqueue_color_picker( $hook_suffix ) { wp_enqueue_media(); wp_enqueue_script( 'wp-color-picker-script-handle', get_template_directory_uri() . '/udm-plugin/js/wp-color-picker-script.js', array( 'wp-color-picker' )); } // Add menus to admin side navigation function add_theme_menu_item(){ add_menu_page('UDM Options', 'UDM Options', 'manage_options', 'udm-options-panel', 'udm_base_options_page_func', null, 99); add_submenu_page('udm-options-panel', 'UDM Options', 'Base Options', 'manage_options', 'udm-options-panel', 'udm_base_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Company Info','manage_options', 'udm-companyinfo-panel','udm_companyinfo_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Social Settings','manage_options', 'udm-social-panel','udm_social_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Header Options','manage_options', 'udm-header-panel','udm_header_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Submenu Options','manage_options', 'udm-submenu-panel','udm_submenu_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'M Header Options','manage_options', 'udm-mobile-header-panel','udm_mobile_header_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'M Nav Options','manage_options', 'udm-mobile-nav-panel','udm_mobile_nav_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Hero Options','manage_options', 'udm-hero-panel','udm_hero_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Footer Options','manage_options', 'udm-footer-panel','udm_footer_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Footer CTA Options','manage_options', 'udm-footer-cta-panel','udm_footer_cta_options_page_func'); add_submenu_page('udm-options-panel', 'UDM Options', 'Blog Options','manage_options', 'udm-blog-panel','udm_blog_options_page_func'); } add_action("admin_menu", "add_theme_menu_item"); // Dashboard Page function udm_dashboard_page_func(){ include(dirname(__FILE__) .'/pages/udm-dashboard-page.php'); } // Base Option Page function udm_base_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-base-options-page.php'); } // Header Options Page function udm_header_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-header-options-page.php'); } // Submenu Options Page function udm_submenu_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-submenu-options-page.php'); } // Header Options Page function udm_footer_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-footer-options-page.php'); } // Social Options Page function udm_social_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-social-options-page.php'); } // Company Info Options Page function udm_companyinfo_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-companyinfo-options-page.php'); } // Hero Options Page function udm_hero_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-hero-options-page.php'); } // Blog Options Page function udm_blog_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-blog-options-page.php'); } // Mobile Header Options Page function udm_mobile_header_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-mobile-header-options-page.php'); } // Mobile Nav Options Page function udm_mobile_nav_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-mobile-nav-options-page.php'); } // Footer CTA Options Page function udm_footer_cta_options_page_func(){ include(dirname(__FILE__) .'/pages/udm-footer-cta-options-page.php'); } //Register Settings of Base Options register_setting("section", "udm_header_default"); register_setting("section", "udm_submenu_default"); register_setting("section", "udm_footer_default"); register_setting("section", "udm_hero_default"); register_setting("section", "udm_mobile_nav_default"); register_setting("section", "udm_mobile_header_default"); register_setting("section", "udm_footer_cta_default"); register_setting("section", "udm_bloglayout_default"); register_setting("section", "udm_gallery_layout_default"); register_setting("section", "udm_logo_default"); register_setting("section", "udm_primary_color"); register_setting("section", "udm_secondary_color"); register_setting("section", "udm_global_dark"); register_setting("section", "udm_global_light"); register_setting("section", "udm_button_background"); register_setting("section", "udm_button_text_color"); register_setting("section", "udm_button_custom_background"); register_setting("section", "udm_button_text_custom_color"); //Register Settings of Social Icons Options register_setting("socail_icons", "udm_facebook_link"); register_setting("socail_icons", "udm_googleplus_link"); register_setting("socail_icons", "udm_linkedin_link"); register_setting("socail_icons", "udm_instagram_link"); register_setting("socail_icons", "udm_pinterest_link"); register_setting("socail_icons", "udm_twitter_link"); //Register Settings of Company Info Options register_setting("companyinfo", "udm_company_logo"); register_setting("companyinfo", "udm_logo_size"); register_setting("companyinfo", "udm_company_name"); register_setting("companyinfo", "udm_email_address"); register_setting("companyinfo", "udm_phone_number"); register_setting("companyinfo", "udm_fax_number"); register_setting("companyinfo", "udm_license_number"); // action to add meta boxes add_action( 'add_meta_boxes', 'udm_specific_header' ); // action on saving post add_action( 'save_post', 'udm_specific_header_save' ); // function that creates the new metabox that will show on post function udm_specific_header() { add_meta_box( 'udm_specific_header', // unique id __( 'Select header', 'udm' ), // metabox title 'udm_specific_header_display', // callback to show the dropdown 'page' // post type ); } // voodoo dropdown display function udm_specific_header_display( $post ) { // Use nonce for verification wp_nonce_field( basename( __FILE__ ), 'udm_specific_header_nonce' ); // get current value $dropdown_value = get_post_meta( get_the_ID(), 'udm_specific_header', true ); ?> <select name="udm_specific_header" id="udm_specific_header"> <option value="">Default Header</option> <?php global $wpdb; $layouts=$wpdb->get_col( "SELECT option_name FROM ".$wpdb->prefix."options WHERE option_name LIKE 'header_layout_%'"); foreach($layouts as $layout){ ?> <option value="<?php echo str_replace("header_layout_","",$layout); ?>" <?php selected(str_replace("header_layout_","",$layout),$dropdown_value); ?>><?php echo str_replace("_"," ", str_replace("header_layout_","",$layout)); ?></option> <?php } ?> </select> <?php } // dropdown saving function udm_specific_header_save( $post_id ) { // if doing autosave don't do nothing if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // verify nonce if ( !wp_verify_nonce( $_POST['udm_specific_header_nonce'], basename( __FILE__ ) ) ) return; // Check permissions if ( 'page' == $_POST['post_type'] ) { if ( !current_user_can( 'edit_page', $post_id ) ) return; } else { if ( !current_user_can( 'edit_post', $post_id ) ) return; } // save the new value of the dropdown $new_value = $_POST['udm_specific_header']; update_post_meta( $post_id, 'udm_specific_header', $new_value ); } // action to add meta boxes add_action( 'add_meta_boxes', 'udm_specific_hero' ); // action on saving post add_action( 'save_post', 'udm_specific_hero_save' ); // function that creates the new Hero metabox that will show on post function udm_specific_hero() { add_meta_box( 'udm_specific_hero', // unique id __( 'Select hero', 'udm' ), // metabox title 'udm_specific_hero_display', // callback to show the dropdown 'page' // post type ); } // Hero dropdown display function udm_specific_hero_display( $post ) { // Use nonce for verification wp_nonce_field( basename( __FILE__ ), 'udm_specific_hero_nonce' ); // get current value $dropdown_value = get_post_meta( get_the_ID(), 'udm_specific_hero', true ); ?> <select name="udm_specific_hero" id="udm_specific_hero"> <option value="">Default Hero</option> <?php global $wpdb; $layouts=$wpdb->get_col( "SELECT option_name FROM ".$wpdb->prefix."options WHERE option_name LIKE 'featured_layout_%'"); foreach($layouts as $layout){ ?> <option value="<?php echo str_replace("featured_layout_","",$layout); ?>" <?php selected(str_replace("featured_layout_","",$layout),$dropdown_value); ?>><?php echo str_replace("_"," ", str_replace("featured_layout_","",$layout)); ?></option> <?php } ?> </select> <script> jQuery(document).ready(function ($) { $('.inside #udm_specific_hero').change(function(){ var selval = $(this).val(); if(selval.indexOf("Basic") >= 0) { $('#basic_hero_meta').show(); $('#fulwidth_hero_meta').hide(); $('#splitscreen_hero_meta').hide(); $('#leftright_hero_meta').hide(); $('#leadgen_hero_meta').hide(); } else if(selval.indexOf("Fulwidth") >= 0) { $('#basic_hero_meta').hide(); $('#fulwidth_hero_meta').show(); $('#splitscreen_hero_meta').hide(); $('#leftright_hero_meta').hide(); $('#leadgen_hero_meta').hide(); } else if(selval.indexOf("Splitscreen") >= 0) { $('#basic_hero_meta').hide(); $('#fulwidth_hero_meta').hide(); $('#splitscreen_hero_meta').show(); $('#leftright_hero_meta').hide(); $('#leadgen_hero_meta').hide(); } else if(selval.indexOf("Leftrightelement") >= 0) { $('#basic_hero_meta').hide(); $('#fulwidth_hero_meta').hide(); $('#splitscreen_hero_meta').hide(); $('#leftright_hero_meta').show(); $('#leadgen_hero_meta').hide(); } else if(selval.indexOf("Leadgen") >= 0) { $('#basic_hero_meta').hide(); $('#fulwidth_hero_meta').hide(); $('#splitscreen_hero_meta').hide(); $('#leftright_hero_meta').hide(); $('#leadgen_hero_meta').show(); } else { <?php if(strpos(get_option('udm_hero_default'), 'Basic_Hero') !== false){ ?> $('#basic_hero_meta').show(); <?php } ?> <?php if(strpos(get_option('udm_hero_default'), 'Fulwidth_Hero') !== false){ ?> $('#fulwidth_hero_meta').show(); <?php } ?> <?php if(strpos(get_option('udm_hero_default'), 'Splitscreen_Hero') !== false){ ?> $('#splitscreen_hero_meta').show(); <?php } ?> <?php if(strpos(get_option('udm_hero_default'), 'Leftrightelement_Hero') !== false){ ?> $('#leftright_hero_meta').show(); <?php } ?> <?php if(strpos(get_option('udm_hero_default'), 'Leadgen_Hero') !== false){ ?> $('#leadgen_hero_meta').show(); <?php } ?> } }); }); </script> <?php } // Hero dropdown saving function udm_specific_hero_save( $post_id ) { // if doing autosave don't do nothing if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // verify nonce if ( !wp_verify_nonce( $_POST['udm_specific_hero_nonce'], basename( __FILE__ ) ) ) return; // Check permissions if ( 'page' == $_POST['post_type'] ) { if ( !current_user_can( 'edit_page', $post_id ) ) return; } else { if ( !current_user_can( 'edit_post', $post_id ) ) return; } // save the new value of the dropdown $new_value = $_POST['udm_specific_hero']; update_post_meta( $post_id, 'udm_specific_hero', $new_value ); } function add_hero_fields_meta_box() { add_meta_box( 'hero_fields', // $id 'Hero Options', // $title 'show_hero_fields_meta_box', // $callback 'page' // $screen ); } add_action( 'add_meta_boxes', 'add_hero_fields_meta_box' ); function show_hero_fields_meta_box() { global $post; if(is_home() || is_archive()) { $pid = get_option( 'page_for_posts' ); } else { $pid = $post->ID; } $meta = get_post_meta( $pid, 'hero_fields', true ); ?> <input type="hidden" name="hero_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>"> <p> <label for="hero_fields[hero_image_show]">Hero Section Hide</label> <br> <span class="switch"> <input type="checkbox" name="hero_fields[hero_image_show]" class="switch" id="hero_fields[hero_image_show]" value="yes" <?php checked('yes', $meta['hero_image_show']); ?>> <label for="hero_fields[hero_image_show]">Show/Hide</label> </span> </p> <div id="basic_hero_meta" <?php if(strpos(get_post_meta( get_the_ID(), 'udm_specific_hero', true ), 'Basic_Hero') !== false){ ?> <?php }else if(get_post_meta( get_the_ID(), 'udm_specific_hero', true )=="" && strpos(get_option('udm_hero_default'), 'Basic_Hero') !== false){}else{ ?> style="display:none;" <?php } ?>> <p> <label for="hero_fields[udm_basic_header_text]">Header Text</label> <br> <input type="text" name="hero_fields[udm_basic_header_text]" id="hero_fields[udm_basic_header_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_basic_header_text'])) { echo $meta['udm_basic_header_text']; } ?>"> </p> </div> <div id="fulwidth_hero_meta" <?php if(strpos(get_post_meta( get_the_ID(), 'udm_specific_hero', true ), 'Fulwidth_Hero') !== false){ ?> <?php }else if(get_post_meta( get_the_ID(), 'udm_specific_hero', true )=="" && strpos(get_option('udm_hero_default'), 'Fulwidth_Hero') !== false){}else{ ?> style="display:none;" <?php } ?>> <?php if (is_array($meta) && isset($meta['udm_fullwidth_eyebrow_text_show'])) { $smalltextshow=$meta['udm_fullwidth_eyebrow_text_show']; } ?> <p> <label for="hero_fields[udm_fullwidth_eyebrow_text_show]">Eybrow Text Hide</label> <br> <span class="switch"> <input type="checkbox" name="hero_fields[udm_fullwidth_eyebrow_text_show]" class="switch" id="hero_fields[udm_fullwidth_eyebrow_text_show]" value="no" <?php checked('no', $smalltextshow); ?>> <label for="hero_fields[udm_fullwidth_eyebrow_text_show]">Show/Hide</label> </span> </p> <p> <label for="hero_fields[udm_fullwidth_eyebrow_text]">Eybrow Text</label> <br> <input type="text" name="hero_fields[udm_fullwidth_eyebrow_text]" id="hero_fields[udm_fullwidth_eyebrow_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_fullwidth_eyebrow_text'])) { echo $meta['udm_fullwidth_eyebrow_text']; } ?>"> </p> <p> <label for="hero_fields[udm_fullwidth_header_text]">Header Text</label> <br> <input type="text" name="hero_fields[udm_fullwidth_header_text]" id="hero_fields[udm_fullwidth_header_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_fullwidth_header_text'])) { echo $meta['udm_fullwidth_header_text']; } ?>"> </p> <p> <label for="hero_fields[udm_fullwidth_description]">Description</label> <br> <textarea name="hero_fields[udm_fullwidth_description]" id="hero_fields[udm_fullwidth_description]" rows="5" cols="30" style="width:500px;"><?php echo $meta['udm_fullwidth_description']; ?></textarea> </p> </div> <div id="splitscreen_hero_meta" <?php if(strpos(get_post_meta( get_the_ID(), 'udm_specific_hero', true ), 'Splitscreen_Hero') !== false){ ?> <?php }else if(get_post_meta( get_the_ID(), 'udm_specific_hero', true )=="" && strpos(get_option('udm_hero_default'), 'Splitscreen_Hero') !== false){}else{ ?> style="display:none;" <?php } ?>> <?php if (is_array($meta) && isset($meta['udm_splitscreen_eyebrow_text_show'])) { $smalltextshow=$meta['udm_splitscreen_eyebrow_text_show']; } ?> <p> <label for="hero_fields[udm_splitscreen_eyebrow_text_show]">Eybrow Text Hide</label> <br> <span class="switch"> <input type="checkbox" name="hero_fields[udm_splitscreen_eyebrow_text_show]" class="switch" id="hero_fields[udm_splitscreen_eyebrow_text_show]" value="no" <?php checked('no', $smalltextshow); ?>> <label for="hero_fields[udm_splitscreen_eyebrow_text_show]">Show/Hide</label> </span> </p> <p> <label for="hero_fields[udm_splitscreen_eyebrow_text]">Eybrow Text</label> <br> <input type="text" name="hero_fields[udm_splitscreen_eyebrow_text]" id="hero_fields[udm_splitscreen_eyebrow_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_splitscreen_eyebrow_text'])) { echo $meta['udm_splitscreen_eyebrow_text']; } ?>"> </p> <p> <label for="hero_fields[udm_splitscreen_header_text]">Header Text</label> <br> <input type="text" name="hero_fields[udm_splitscreen_header_text]" id="hero_fields[udm_splitscreen_header_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_splitscreen_header_text'])) { echo $meta['udm_splitscreen_header_text']; } ?>"> </p> <p> <label for="hero_fields[udm_splitscreen_description]">Description</label> <br> <textarea name="hero_fields[udm_splitscreen_description]" id="hero_fields[udm_splitscreen_description]" rows="5" cols="30" style="width:500px;"><?php echo $meta['udm_splitscreen_description']; ?></textarea> </p> </div> <div id="leftright_hero_meta" <?php if(strpos(get_post_meta( get_the_ID(), 'udm_specific_hero', true ), 'Leftrightelement_Hero') !== false){ ?> <?php }else if(get_post_meta( get_the_ID(), 'udm_specific_hero', true )=="" && strpos(get_option('udm_hero_default'), 'Leftrightelement_Hero') !== false){}else{ ?> style="display:none;" <?php } ?>> <?php if (is_array($meta) && isset($meta['udm_leftrightelement_eyebrow_text_show'])) { $smalltextshow=$meta['udm_leftrightelement_eyebrow_text_show']; } ?> <p> <label for="hero_fields[udm_leftrightelement_eyebrow_text_show]">Eybrow Text Hide</label> <br> <span class="switch"> <input type="checkbox" name="hero_fields[udm_leftrightelement_eyebrow_text_show]" class="switch" id="hero_fields[udm_leftrightelement_eyebrow_text_show]" value="no" <?php checked('no', $smalltextshow); ?>> <label for="hero_fields[udm_leftrightelement_eyebrow_text_show]">Show/Hide</label> </span> </p> <p> <label for="hero_fields[udm_leftrightelement_eyebrow_text]">Eybrow Text</label> <br> <input type="text" name="hero_fields[udm_leftrightelement_eyebrow_text]" id="hero_fields[udm_leftrightelement_eyebrow_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_leftrightelement_eyebrow_text'])) { echo $meta['udm_leftrightelement_eyebrow_text']; } ?>"> </p> <p> <label for="hero_fields[udm_leftrightelement_header_text]">Header Text</label> <br> <input type="text" name="hero_fields[udm_leftrightelement_header_text]" id="hero_fields[udm_leftrightelement_header_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_leftrightelement_header_text'])) { echo $meta['udm_leftrightelement_header_text']; } ?>"> </p> <p> <label for="hero_fields[udm_leftrightelement_description]">Description</label> <br> <textarea name="hero_fields[udm_leftrightelement_description]" id="hero_fields[udm_leftrightelement_description]" rows="5" cols="30" style="width:500px;"><?php echo $meta['udm_leftrightelement_description']; ?></textarea> </p> <p id="element"> <label for="hero_fields[udm_leftrightelement_element]">Element</label> <br> <select name="hero_fields[udm_leftrightelement_element]" id="hero_fields[udm_leftrightelement_element]"> <option value="">Select Element Type</option> <option value="image" <?php selected( $meta['udm_leftrightelement_element'], 'image' ); ?>>Image</option> <option value="video" <?php selected( $meta['udm_leftrightelement_element'], 'video' ); ?>>Video</option> </select> </p> <p id="imageurl" <?php if (is_array($meta) && $meta['udm_leftrightelement_element']!="image") { ?>style="display:none;"<?php } ?>> <label for="hero_fields[udm_leftrightelement_image]">Image Url</label><br> <input type="text" name="hero_fields[udm_leftrightelement_image]" id="hero_fields[udm_leftrightelement_image]" class="meta-image regular-text main-image" value="<?php echo $meta['udm_leftrightelement_image']; ?>"> <input class="btn upload-image" my-attr="main-image" type="button" value="Upload Image" /> </p> <p id="videourl" <?php if (is_array($meta) && $meta['udm_leftrightelement_element']!="video") { ?>style="display:none;"<?php } ?>> <label for="hero_fields[udm_leftrightelement_video]">Youtube/Vimeo Video Url</label><br> <input type="text" name="hero_fields[udm_leftrightelement_video]" id="hero_fields[udm_leftrightelement_video]" class="meta-image regular-text" value="<?php echo $meta['udm_leftrightelement_video']; ?>"> </p> </div> <div id="leadgen_hero_meta" <?php if(strpos(get_post_meta( get_the_ID(), 'udm_specific_hero', true ), 'Leadgen_Hero') !== false){ ?> <?php }else if(get_post_meta( get_the_ID(), 'udm_specific_hero', true )=="" && strpos(get_option('udm_hero_default'), 'Leadgen_Hero') !== false){}else{ ?> style="display:none;" <?php } ?>> <?php if (is_array($meta) && isset($meta['udm_leadgen_eyebrow_text_show'])) { $smalltextshow=$meta['udm_leadgen_eyebrow_text_show']; } ?> <p> <label for="hero_fields[udm_leadgen_eyebrow_text_show]">Eybrow Text Show/Hide</label> <br> <span class="switch"> <input type="checkbox" name="hero_fields[udm_leadgen_eyebrow_text_show]" class="switch" id="hero_fields[udm_leadgen_eyebrow_text_show]" value="yes" <?php checked('yes', $smalltextshow); ?>> <label for="hero_fields[udm_leadgen_eyebrow_text_show]">Show/Hide</label> </span> </p> <p> <label for="hero_fields[udm_leadgen_eyebrow_text]">Eybrow Text</label> <br> <input type="text" name="hero_fields[udm_leadgen_eyebrow_text]" id="hero_fields[udm_leadgen_eyebrow_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_leadgen_eyebrow_text'])) { echo $meta['udm_leadgen_eyebrow_text']; } ?>"> </p> <p> <label for="hero_fields[udm_leadgen_header_text]">Header Text</label> <br> <input type="text" name="hero_fields[udm_leadgen_header_text]" id="hero_fields[udm_leadgen_header_text]" class="regular-text" value="<?php if (is_array($meta) && isset($meta['udm_leadgen_header_text'])) { echo $meta['udm_leadgen_header_text']; } ?>"> </p> <p> <label for="hero_fields[udm_leadgen_description]">Description</label> <br> <textarea name="hero_fields[udm_leadgen_description]" id="hero_fields[udm_leadgen_description]" rows="5" cols="30" style="width:500px;"><?php echo $meta['udm_leadgen_description']; ?></textarea> </p> </div> <script> jQuery(document).ready(function ($) { $('.udm_color_picker').wpColorPicker(); //Add color picker $('.upload-image').click(function() { var mediaUploader; var myvar = $(this).attr('my-attr'); //e.preventDefault(); // If the uploader object has already been created, reopen the dialog if (mediaUploader) { mediaUploader.open(); return; } // Extend the wp.media object mediaUploader = wp.media.frames.file_frame = wp.media({ title: 'Choose Image', button: { text: 'Choose Image' }, multiple: false }); // When a file is selected, grab the URL and set it as the text field's value mediaUploader.on('select', function() { attachment = mediaUploader.state().get('selection').first().toJSON(); $('.'+myvar).val(attachment.url); }); // Open the uploader dialog mediaUploader.open(); }); $('#element select').change(function(){ if($(this).val() == "video") { $('#videourl').show(); $('#imageurl').hide(); } else if($(this).val() == "image") { $('#videourl').hide(); $('#imageurl').show(); } else { $('#videourl').hide(); $('#imageurl').hide(); } }); }); </script> <?php } function save_hero_fields_meta( $post_id ) { // verify nonce if ( isset($_POST['hero_meta_box_nonce']) && !wp_verify_nonce( $_POST['hero_meta_box_nonce'], basename(__FILE__) ) ) { return $post_id; } // check autosave if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; } // check permissions if (isset($_POST['post_type'])) { //Fix 2 if ( 'page' === $_POST['post_type'] ) { if ( !current_user_can( 'edit_page', $post_id ) ) { return $post_id; } elseif ( !current_user_can( 'edit_post', $post_id ) ) { return $post_id; } } } $old = get_post_meta( $post_id, 'hero_fields', true ); if (isset($_POST['hero_fields'])) { //Fix 3 $new = $_POST['hero_fields']; if ( $new && $new !== $old ) { update_post_meta( $post_id, 'hero_fields', $new ); } elseif ( '' === $new && $old ) { delete_post_meta( $post_id, 'hero_fields', $old ); } } } add_action( 'save_post', 'save_hero_fields_meta' ); // action to add meta boxes add_action( 'add_meta_boxes', 'udm_specific_galley' ); // action on saving post add_action( 'save_post', 'udm_specific_galley_save' ); // function that creates the new metabox that will show on post function udm_specific_galley() { add_meta_box( 'udm_specific_galley', // unique id __( 'Select Galley', 'udm' ), // metabox title 'udm_specific_galley_display', // callback to show the dropdown 'page' // post type ); } // Dropdown display function udm_specific_galley_display( $post ) { // Use nonce for verification wp_nonce_field( basename( __FILE__ ), 'udm_specific_galley_nonce' ); // get current value $dropdown_value = get_post_meta( get_the_ID(), 'udm_specific_galley', true ); ?> <select name="udm_specific_galley" id="udm_specific_galley"> <option value="">Default Gallery</option> <?php query_posts('post_type=gallery&posts_per_page=-1'); while(have_posts()):the_post(); ?> <option value="<?php echo get_the_id(); ?>" <?php selected(get_the_id(),$dropdown_value); ?>><?php the_title(); ?></option> <?php endwhile; wp_reset_query(); ?> </select> <?php } // dropdown saving function udm_specific_galley_save( $post_id ) { // if doing autosave don't do nothing if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // verify nonce if ( !wp_verify_nonce( $_POST['udm_specific_galley_nonce'], basename( __FILE__ ) ) ) return; // Check permissions if ( 'page' == $_POST['post_type'] ) { if ( !current_user_can( 'edit_page', $post_id ) ) return; } else { if ( !current_user_can( 'edit_post', $post_id ) ) return; } // save the new value of the dropdown $new_value = $_POST['udm_specific_galley']; update_post_meta( $post_id, 'udm_specific_galley', $new_value ); } //Admin Panel Functions End ################################################################################ # //Frontend Functions Start ################################################################################ add_action( 'wp_enqueue_scripts', 'theme_custom_style_script', 11 ); function theme_custom_style_script() { global $post; if(is_home() || is_archive()) { $pid = get_option( 'page_for_posts' ); } else { $pid = $post->ID; } wp_enqueue_style( 'default-css', admin_url('admin-ajax.php').'?action=default_css', '', VERSION); wp_enqueue_style( 'header-css', admin_url('admin-ajax.php').'?action=header_css&id='.$pid, '', VERSION); wp_enqueue_style( 'mobile-nav-css', admin_url('admin-ajax.php').'?action=mobile_nav_css&id='.$pid, '', VERSION); wp_enqueue_style( 'hero-css', admin_url('admin-ajax.php').'?action=hero_css&id='.$pid, '', VERSION); wp_enqueue_style( 'footer-cta-css', admin_url('admin-ajax.php').'?action=footer_cta_css&id='.$pid, '', VERSION); wp_enqueue_style( 'blog-css', admin_url('admin-ajax.php').'?action=blog_css&id='.$pid, '', VERSION); wp_enqueue_style( 'footer-css', admin_url('admin-ajax.php').'?action=footer_css&id='.$pid, '', VERSION); } //Header Css add_action('wp_ajax_default_css', 'default_css'); add_action('wp_ajax_nopriv_default_css', 'default_css'); add_action('wp_ajax_header_css', 'header_css'); add_action('wp_ajax_nopriv_header_css', 'header_css'); add_action('wp_ajax_mobile_nav_css', 'mobile_nav_css'); add_action('wp_ajax_nopriv_mobile_nav_css', 'mobile_nav_css'); add_action('wp_ajax_hero_css', 'hero_css'); add_action('wp_ajax_nopriv_hero_css', 'hero_css'); add_action('wp_ajax_footer_cta_css', 'footer_cta_css'); add_action('wp_ajax_nopriv_footer_cta_css', 'footer_cta_css'); add_action('wp_ajax_blog_css', 'blog_css'); add_action('wp_ajax_nopriv_blog_css', 'blog_css'); function default_css() { require( get_template_directory().'/style.php' ); exit; } function header_css() { require( get_template_directory().'/udm-plugin/headers/custom_style.php' ); exit; } function mobile_nav_css() { require( get_template_directory().'/udm-plugin/mobile-headers/custom_style.php' ); exit; } function hero_css() { require( get_template_directory().'/udm-plugin/featured/custom_style.php' ); exit; } function footer_cta_css() { require( get_template_directory().'/udm-plugin/footer-cta/custom_style.php' ); exit; } function blog_css() { require( get_template_directory().'/udm-plugin/blog/custom_style.php' ); exit; } //Footer Css add_action('wp_ajax_footer_css', 'footer_css'); add_action('wp_ajax_nopriv_footer_css', 'footer_css'); function footer_css() { require( get_template_directory().'/udm-plugin/footers/custom_style.php' ); exit; } // Enqueue Theme Files function uglyduck_header_scripts() { if(get_post_meta( get_the_ID(), 'udm_specific_mobile_nav', true )!="") { $mobilenavlayout=get_post_meta( get_the_ID(), 'udm_specific_mobile_nav', true ); } else if(get_option('udm_mobile_nav_default')!="") { $mobilenavlayout=get_option('udm_mobile_nav_default'); } else { $mobilenavlayout=""; } if(strpos($mobilenavlayout, 'Slide_In') !== false){ wp_enqueue_script( 'slim-js', 'https://code.jquery.com/jquery-3.2.1.slim.min.js' ); } } function uglyduck_footer_scripts() { wp_enqueue_script( 'ratingyo-jquery-js', get_template_directory_uri() . '/udm-plugin/js/jquery.min.js' ); wp_enqueue_script( 'ratingyo-js', get_template_directory_uri() . '/udm-plugin/js/jquery.rateyo.js'); if(get_post_meta( get_the_ID(), 'udm_specific_mobile_nav', true )!="") { $mobilenavlayout=get_post_meta( get_the_ID(), 'udm_specific_mobile_nav', true ); } else if(get_option('udm_mobile_nav_default')!="") { $mobilenavlayout=get_option('udm_mobile_nav_default'); } else { $mobilenavlayout=""; } if(strpos($mobilenavlayout, 'Slide_In') !== false){ wp_enqueue_script( 'slide-menu-js', get_template_directory_uri() . '/udm-plugin/js/slide-menu.js'); } } function uglyduck_scripts() { // CSS wp_enqueue_style( 'base-css','//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"' ); wp_enqueue_style( 'font-awesome-css','https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"' ); wp_enqueue_style( 'base-icons','//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"' ); wp_enqueue_style( 'proxima-nova', get_template_directory_uri() . '/fonts/proxima-nova/fonts.min.css' ); wp_enqueue_style( 'component-css', get_template_directory_uri() . '/css/component.css' ); wp_enqueue_style( 'slide-menu-css', get_template_directory_uri() . '/udm-plugin/css/slide-menu.css' ); wp_enqueue_style( 'preview-css', get_template_directory_uri() . '/udm-plugin/css/preview.css' ); wp_enqueue_style( 'rating-css', get_template_directory_uri() . '/udm-plugin/css/jquery.rateyo.min.css' ); // JAVASCRIPT wp_enqueue_script( 'udm-ajax-js', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); wp_enqueue_script( 'uglyduck-js', get_template_directory_uri() . '/js/app.js' ); wp_enqueue_script( 'modernizr-js', get_template_directory_uri() . '/js/modernizr.custom.js'); wp_enqueue_script( 'bootsrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js'); wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js' ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'uglyduck_scripts' ); add_action( 'wp_footer', 'uglyduck_footer_scripts' ); add_action( 'wp_head', 'uglyduck_header_scripts' ); //Frontend Functions End ?>
49,103
https://github.com/AtlasOfLivingAustralia/spatial-hub/blob/master/grails-app/assets/javascripts/spApp/directive/googlePlaces.js
Github Open Source
Open Source
MIT
2,023
spatial-hub
AtlasOfLivingAustralia
JavaScript
Code
86
314
(function (angular) { 'use strict'; /** * @memberof spApp * @ngdoc directive * @name googlePlaces * @description * Location search using Google places */ angular.module('google-places-directive', []).directive('googlePlaces', function () { return { restrict: 'E', replace: true, scope: { _location: '=location', _area: '=area' }, template: '<input style="width:300px" id="google_places_ac" name="google_places_ac" type="text" class="input-block-level"/>', link: function ($scope, elm, attrs) { var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], {}); google.maps.event.addListener(autocomplete, 'place_changed', function () { var place = autocomplete.getPlace(); $scope._location = place.geometry.location.lat() + ',' + place.geometry.location.lng(); $scope._area = place.formatted_address; $scope.$apply(); }); } } }) }(angular));
48,729
https://github.com/j2cey/adminitlte31/blob/master/app/Http/Controllers/Auth/LoginController.php
Github Open Source
Open Source
MIT
null
adminitlte31
j2cey
PHP
Code
424
1,303
<?php namespace App\Http\Controllers\Auth; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Http\Response; use Adldap\Laravel\Facades\Adldap; use Illuminate\Contracts\View\View; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Contracts\View\Factory; use App\Providers\RouteServiceProvider; use Illuminate\Validation\ValidationException; use Illuminate\Contracts\Foundation\Application; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = RouteServiceProvider::HOME; /** * Create a new controller instance. * * @return void */ public function __construct() { session(['url.intended' => url()->previous()]); $this->redirectTo = session()->get('url.intended'); $this->middleware('guest')->except('logout'); } /** * Show the application's login form. * * @return Application|Factory|View|Response */ public function showLoginForm() { // Get URLs $urlPrevious = url()->previous(); $urlBase = url()->to('/'); // Set the previous url that we came from to redirect to after successful login but only if is internal if(($urlPrevious != $urlBase . '/login') && (substr($urlPrevious, 0, strlen($urlBase)) === $urlBase)) { session()->put('url.intended', $urlPrevious); } return view('auth.login'); } protected function attemptLogin(Request $request) { //if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { $input = $request->input(); $username = explode('@', $input['email'])[0]; // Get the user details from database and check if user is exist and active. if (filter_var($input['email'], FILTER_VALIDATE_EMAIL)) { $user = User::where('email',$input['email'])->first(); } else { $user = User::where('username',$input['email'])->first(); } if($user){ if (!$user->isActive()) { throw ValidationException::withMessages([$this->username() => __('User has been desactivated.')]); } } else { throw ValidationException::withMessages([$this->username() => __('Infos de connexion non valides !')]); } $credentials = [ 'username' => $user->username, 'email' => $user->username . '' . config('app.ldap_domain'), 'password' => $input['password'] ]; if ($user->is_ldap) { if ( $this->attemptLdap($credentials) ) { $this->saveLoginType($user,"ldap"); Auth::login($user); // Update du PWD LDAP local $ldapaccount = $user->ldapaccount; $ldapaccount->password = Hash::make($credentials['password']); $ldapaccount->saveQuietly(); //return redirect()->intended('/'); return redirect(session('url.intended')); } } // Or using the default guard you've configured, likely "users" if ($user->is_local) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $this->saveLoginType($user,"local"); return redirect(session('url.intended')); } } /*if (Auth::attempt(['email' => $input['email'], 'password' => $input['password'] ])) { // Authentication passed... return redirect()->intended('/'); }*/ } private function attemptLdap($credentials) { try { Adldap::connect(); } catch (\Exception $e) { // Can't connect. // By default, the timeout for connectivity is 5 seconds. A user // will have to wait this length of time if there is issues // connecting to your AD server. You can configure // this in your `config/adldap.php` file. // Try connect with ldap locally stored password return Auth::guard('ldaplocal')->attempt($credentials); } return Auth::guard('ldap')->attempt($credentials); } private function saveLoginType($user, $login_type) { $user->login_type = $login_type; $user->saveQuietly(); } }
19,744
https://github.com/backwardn/imds-filterd/blob/master/imds-filterd/netconfig.c
Github Open Source
Open Source
BSD-2-Clause
null
imds-filterd
backwardn
C
Code
1,027
3,037
#define __BSD_VISIBLE 1 /* Needed for net/ headers. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/sysctl.h> #include <net/if.h> #include <net/if_dl.h> #include <net/route.h> #include <netinet/in.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include "warnp.h" #include "imds-filterd.h" static int sysctldump(int mib[], size_t miblen, char ** buf, size_t * len) { /* Loop until we manage to dump the table. */ while (1) { /* How large a buffer do we need? */ if (sysctl(mib, miblen, NULL, len, NULL, 0)) { warnp("sysctl"); goto err0; } /* Allocate a buffer based on the size the kernel reported. */ if ((*buf = malloc(*len)) == NULL) { warnp("malloc"); goto err0; } /* Try to dump the table. */ if (sysctl(mib, miblen, *buf, len, NULL, 0)) { if (errno == ENOMEM) { /* * The table we're dumping must have grown; * free our buffer and start over. */ free(*buf); continue; } warnp("sysctl"); goto err1; } /* It worked this time. */ break; } /* Success! */ return (0); err1: free(*buf); err0: /* Failure! */ return (-1); } static int extractaddrs(char * p, struct sockaddr * sas[RTAX_MAX]) { struct rt_msghdr * rt = (struct rt_msghdr *)p; struct sockaddr * sa; char * p2; int i; /* No addresses yet. */ for (i = 0; i < RTAX_MAX; i++) sas[i] = NULL; /* Move through the buffer recording pointers to addresses. */ for (i = 0, p2 = &p[sizeof(struct rt_msghdr)]; p2 < &p[rt->rtm_msglen]; p2 += SA_SIZE(sa)) { sa = (struct sockaddr *)p2; if (p2 + SA_SIZE(sa) > &p[rt->rtm_msglen]) { warn0("Socket address overflows routing message!"); goto err0; } /* Which address type is this? */ if ((i = ffs(rt->rtm_addrs & ((-1) << i))) == 0) { warn0("Routing message contains wrong number of addresses!"); goto err0; } sas[i - 1] = sa; } if ((rt->rtm_addrs & ((-1) << i)) != 0) { warn0("Routing message contains wrong number of addresses!"); goto err0; } /* Success! */ return (0); err0: /* Failure! */ return (-1); } /** * netconfig_getif(srcaddr, gwaddr, host, ifname): * Find the IPv4 route used for sending packets to ${host}; return via * ${ifname}, ${gwaddr}, and ${srcaddr} the name of the network interface, * the gateway, and the appropriate source IPv4 address. */ int netconfig_getif(struct sockaddr_in * srcaddr, struct sockaddr_in * gwaddr, in_addr_t imdsaddr, char ** ifname) { struct sockaddr * sas[RTAX_MAX]; int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0}; in_addr_t rtdst, rtmsk; int64_t best_rtmsk = -1; u_short best_index; struct sockaddr * best_addr; struct sockaddr * best_gwaddr; char * buf; char * p; struct rt_msghdr * rt; size_t len; /* Dump the routing table. */ if (sysctldump(mib, sizeof(mib) / sizeof(mib[0]), &buf, &len)) goto err0; /* * Walk through the routing table we just dumped, looking for the * best route to the Instance Metadata Service. */ for (p = buf; p < &buf[len]; p += rt->rtm_msglen) { /* We have a routing message. */ rt = (struct rt_msghdr *)p; if ((&p[sizeof(struct rt_msghdr)] > &buf[len]) || (&p[rt->rtm_msglen] > &buf[len])) { warn0("Routing message overflows sysctl buffer!"); goto err1; } /* It should be an RTM_GET message. */ if (rt->rtm_type != RTM_GET) { warn0("Unexpected routing message type: %d", (int)rt->rtm_type); continue; } /* Extract addresses from the message. */ if (extractaddrs(p, sas)) goto err1; /* We only care about IPv4 destinations. */ if ((sas[RTAX_DST] == NULL) || (sas[RTAX_DST]->sa_family != AF_INET)) continue; rtdst = ((struct sockaddr_in *)(sas[RTAX_DST]))->sin_addr.s_addr; /* Ignore any route which doesn't match the netmask. */ if (sas[RTAX_NETMASK] != NULL) { /* Sanity-check. */ if (sas[RTAX_NETMASK]->sa_family != AF_INET) { warn0("Interface has IPv4 address" " but non-IPv4 netmask!"); continue; } rtmsk = ((struct sockaddr_in *)(sas[RTAX_NETMASK]))->sin_addr.s_addr; } else { rtmsk = (in_addr_t)0xffffffff; } if (((imdsaddr ^ rtdst) & rtmsk) != 0) continue; /* Pick the most specific route. */ if (ntohl(rtmsk) >= best_rtmsk) { best_rtmsk = ntohl(rtmsk); best_index = rt->rtm_index; best_gwaddr = sas[RTAX_GATEWAY]; best_addr = sas[RTAX_IFA]; } } /* Did we find a route? */ if (best_rtmsk == -1) { warn0("No route to Instance Metadata Service found!"); goto err1; } /* Does that interface have a local address? */ if (best_addr == NULL) { warn0("Best route has no local address!"); goto err1; } if (best_addr->sa_family != AF_INET) { warn0("IPv4 route has non-IPv4 interface address!"); goto err1; } /* Is there a gateway? */ if (best_gwaddr == NULL) { warn0("Best route has no gateway address!"); goto err1; } if (best_gwaddr->sa_family != AF_INET) { warn0("IPv4 route has non-IPv4 gateway address!"); goto err1; } /* Allocate space for the interface name. */ if ((*ifname = malloc(IFNAMSIZ)) == NULL) goto err1; /* Return the local address and interface name. */ memcpy(srcaddr, best_addr, best_addr->sa_len); memcpy(gwaddr, best_gwaddr, best_gwaddr->sa_len); if_indextoname(best_index, *ifname); /* Success! */ return (0); err1: free(buf); err0: /* Failure! */ return (-1); } /* * netconfig_getmac(host, mac): * Look up the MAC address associated with the IPv4 address ${host} and * return it via ${mac}. Note that this can fail if ${host} is not in the * operating system's ARP cache. */ int netconfig_getmac(struct sockaddr_in * host, uint8_t mac[6]) { struct sockaddr * sas[RTAX_MAX]; int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO}; char * buf; char * p; struct rt_msghdr * rt; size_t len; /* Dump the ARP table. */ if (sysctldump(mib, sizeof(mib) / sizeof(mib[0]), &buf, &len)) goto err0; /* * Walk through the ARP table we just dumped, looking for the entry * corresponding to the IPv4 address we have. */ for (p = buf; p < &buf[len]; p += rt->rtm_msglen) { /* We have a routing message. */ rt = (struct rt_msghdr *)p; if ((&p[sizeof(struct rt_msghdr)] > &buf[len]) || (&p[rt->rtm_msglen] > &buf[len])) { warn0("Routing message overflows sysctl buffer!"); goto err1; } /* It should be an RTM_GET message. */ if (rt->rtm_type != RTM_GET) { warn0("Unexpected routing message type: %d", (int)rt->rtm_type); continue; } /* Extract addresses from the message. */ if (extractaddrs(p, sas)) goto err1; /* Is this the one we're looking for? */ if (sas[RTAX_DST] == NULL) continue; if (sas[RTAX_DST]->sa_family != AF_INET) continue; if (((struct sockaddr_in *)(sas[RTAX_DST]))->sin_addr.s_addr != host->sin_addr.s_addr) continue; /* Do we have a link-layer address? */ if (sas[RTAX_GATEWAY] == NULL) continue; if (sas[RTAX_GATEWAY]->sa_family != AF_LINK) continue; /* Copy the address out. */ memcpy(mac, LLADDR((struct sockaddr_dl *)sas[RTAX_GATEWAY]), 6); break; } /* Success! */ return (0); err1: free(buf); err0: /* Failure! */ return (-1); }
38,095
https://github.com/werselio/pipeline/blob/master/cdap-data-fabric/src/main/java/co/cask/cdap/data2/dataset2/lib/timeseries/FactTable.java
Github Open Source
Open Source
Apache-2.0
2,018
pipeline
werselio
Java
Code
2,185
6,005
/* * Copyright © 2014 Cask Data, Inc. * * 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 co.cask.cdap.data2.dataset2.lib.timeseries; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.api.dataset.lib.cube.DimensionValue; import co.cask.cdap.api.dataset.lib.cube.MeasureType; import co.cask.cdap.api.dataset.lib.cube.Measurement; import co.cask.cdap.api.dataset.table.Row; import co.cask.cdap.api.dataset.table.Scanner; import co.cask.cdap.api.metrics.MetricsCollector; import co.cask.cdap.common.utils.ImmutablePair; import co.cask.cdap.data2.dataset2.lib.table.FuzzyRowFilter; import co.cask.cdap.data2.dataset2.lib.table.MetricsTable; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import javax.annotation.Nullable; /** * Table for storing {@link Fact}s. * * Thread safe as long as the passed into the constructor datasets are thread safe (usually is not the case). */ public final class FactTable implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(FactTable.class); private static final int MAX_ROLL_TIME = 0xfffe; // hard limits on some ops to stay on safe side private static final int MAX_RECORDS_TO_SCAN_DURING_SEARCH = 10 * 1000 * 1000; private static final int MAX_SCANS_DURING_SEARCH = 10 * 1000; private static final Function<byte[], Long> BYTES_TO_LONG = new Function<byte[], Long>() { @Override public Long apply(byte[] input) { return Bytes.toLong(input); } }; private static final Function<NavigableMap<byte[], byte[]>, NavigableMap<byte[], Long>> TRANSFORM_MAP_BYTE_ARRAY_TO_LONG = new Function<NavigableMap<byte[], byte[]>, NavigableMap<byte[], Long>>() { @Override public NavigableMap<byte[], Long> apply(NavigableMap<byte[], byte[]> input) { return Maps.transformValues(input, BYTES_TO_LONG); } }; private final MetricsTable timeSeriesTable; private final EntityTable entityTable; private final FactCodec codec; private final int resolution; // todo: should not be used outside of codec private final int rollTime; private final String putCountMetric; private final String incrementCountMetric; @Nullable private MetricsCollector metrics; /** * Creates an instance of {@link FactTable}. * * @param timeSeriesTable A table for storing facts information. * @param entityTable The table for storing dimension encoding mappings. * @param resolution Resolution in seconds * @param rollTime Number of resolution for writing to a new row with a new timebase. * Meaning the differences between timebase of two consecutive rows divided by * resolution seconds. It essentially defines how many columns per row in the table. * This value should be < 65535. */ public FactTable(MetricsTable timeSeriesTable, EntityTable entityTable, int resolution, int rollTime) { // Two bytes for column name, which is a delta timestamp Preconditions.checkArgument(rollTime <= MAX_ROLL_TIME, "Rolltime should be <= " + MAX_ROLL_TIME); this.entityTable = entityTable; this.timeSeriesTable = timeSeriesTable; this.codec = new FactCodec(entityTable, resolution, rollTime); this.resolution = resolution; this.rollTime = rollTime; this.putCountMetric = "factTable." + resolution + ".put.count"; this.incrementCountMetric = "factTable." + resolution + ".increment.count"; } public void setMetricsCollector(MetricsCollector metrics) { this.metrics = metrics; } public void add(List<Fact> facts) { // Simply collecting all rows/cols/values that need to be put to the underlying table. NavigableMap<byte[], NavigableMap<byte[], byte[]>> gaugesTable = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); NavigableMap<byte[], NavigableMap<byte[], byte[]>> incrementsTable = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); for (Fact fact : facts) { for (Measurement measurement : fact.getMeasurements()) { byte[] rowKey = codec.createRowKey(fact.getDimensionValues(), measurement.getName(), fact.getTimestamp()); byte[] column = codec.createColumn(fact.getTimestamp()); if (MeasureType.COUNTER == measurement.getType()) { inc(incrementsTable, rowKey, column, measurement.getValue()); } else { set(gaugesTable, rowKey, column, Bytes.toBytes(measurement.getValue())); } } } NavigableMap<byte[], NavigableMap<byte[], Long>> convertedIncrementsTable = Maps.transformValues(incrementsTable, TRANSFORM_MAP_BYTE_ARRAY_TO_LONG); NavigableMap<byte[], NavigableMap<byte[], Long>> convertedGaugesTable = Maps.transformValues(gaugesTable, TRANSFORM_MAP_BYTE_ARRAY_TO_LONG); // todo: replace with single call, to be able to optimize rpcs in underlying table timeSeriesTable.put(convertedGaugesTable); timeSeriesTable.increment(convertedIncrementsTable); if (metrics != null) { metrics.increment(putCountMetric, convertedGaugesTable.size()); metrics.increment(incrementCountMetric, convertedIncrementsTable.size()); } } private class MeasureNameComparator implements Comparator<String> { private final Map<String, Long> measureNameToEntityIdMap; private MeasureNameComparator(Map<String, Long> measureNameToEntityIdMap) { this.measureNameToEntityIdMap = measureNameToEntityIdMap; } @Override public int compare(String first, String second) { return Long.compare(measureNameToEntityIdMap.get(first), measureNameToEntityIdMap.get(second)); } } public FactScanner scan(FactScan scan) { return new FactScanner(getScanner(scan), codec, scan.getStartTs(), scan.getEndTs(), scan.getMeasureNames()); } private List<String> getSortedMeasures(Collection<String> measures) { Map<String, Long> measureToEntityMap = new HashMap<>(); List<String> measureNames = new ArrayList<>(); for (String measureName : measures) { measureNames.add(measureName); measureToEntityMap.put(measureName, codec.getMeasureEntityId(measureName)); } // sort the list Collections.sort(measureNames, new MeasureNameComparator(measureToEntityMap)); return measureNames; } private Scanner getScanner(FactScan scan) { // sort the measures based on their entity ids and based on that get the start and end row key metric names List<String> measureNames = getSortedMeasures(scan.getMeasureNames()); byte[] startRow = codec.createStartRowKey(scan.getDimensionValues(), measureNames.isEmpty() ? null : measureNames.get(0), scan.getStartTs(), false); byte[] endRow = codec.createEndRowKey(scan.getDimensionValues(), measureNames.isEmpty() ? null : measureNames.get(measureNames.size() - 1), scan.getEndTs(), false); byte[][] columns; if (Arrays.equals(startRow, endRow)) { // If on the same timebase, we only need subset of columns long timeBase = scan.getStartTs() / rollTime * rollTime; int startCol = (int) (scan.getStartTs() - timeBase) / resolution; int endCol = (int) (scan.getEndTs() - timeBase) / resolution; columns = new byte[endCol - startCol + 1][]; for (int i = 0; i < columns.length; i++) { columns[i] = Bytes.toBytes((short) (startCol + i)); } } endRow = Bytes.stopKeyForPrefix(endRow); FuzzyRowFilter fuzzyRowFilter = measureNames.isEmpty() ? createFuzzyRowFilter(scan, startRow) : createFuzzyRowFilter(scan, measureNames); if (LOG.isTraceEnabled()) { LOG.trace("Scanning fact table {} with scan: {}; constructed startRow: {}, endRow: {}, fuzzyRowFilter: {}", timeSeriesTable, scan, toPrettyLog(startRow), toPrettyLog(endRow), fuzzyRowFilter); } return timeSeriesTable.scan(startRow, endRow, fuzzyRowFilter); } /** * Delete entries in fact table. * @param scan specifies deletion criteria */ public void delete(FactScan scan) { try (Scanner scanner = getScanner(scan)) { Row row; while ((row = scanner.next()) != null) { List<byte[]> columns = Lists.newArrayList(); boolean exhausted = false; for (byte[] column : row.getColumns().keySet()) { long ts = codec.getTimestamp(row.getRow(), column); if (ts < scan.getStartTs()) { continue; } if (ts > scan.getEndTs()) { exhausted = true; break; } columns.add(column); } // todo: do deletes efficiently, in batches, not one-by-one timeSeriesTable.delete(row.getRow(), columns.toArray(new byte[columns.size()][])); if (exhausted) { break; } } } } /** * Searches for first non-null valued dimensions in records that contain given list of dimensions and match given * dimension values in given time range. Returned dimension values are those that are not defined in given * dimension values. * @param allDimensionNames list of all dimension names to be present in the record * @param dimensionSlice dimension values to filter by, {@code null} means any non-null value. * @param startTs start of the time range, in seconds * @param endTs end of the time range, in seconds * @return {@link Set} of {@link DimensionValue}s */ // todo: pass a limit on number of dimensionValues returned // todo: kinda not cool API when we expect null values in a map... public Set<DimensionValue> findSingleDimensionValue(List<String> allDimensionNames, Map<String, String> dimensionSlice, long startTs, long endTs) { // Algorithm, briefly: // We scan in the records which have given allDimensionNames. We use dimensionSlice as a criteria for scan. // If record from the scan has non-null values in the dimensions which are not specified in dimensionSlice, // we use first of such dimension as a value to return. // When we find value to return, since we only fill a single dimension, we are not interested in drilling down // further and instead attempt to fast-forward (jump) to a record that has different value in that dimension. // Thus we find all results. List<DimensionValue> allDimensions = Lists.newArrayList(); List<DimensionValue> filledDimension = Lists.newArrayList(); List<Integer> dimToFillIndexes = Lists.newArrayList(); for (int i = 0; i < allDimensionNames.size(); i++) { String dimensionName = allDimensionNames.get(i); if (!dimensionSlice.containsKey(dimensionName)) { dimToFillIndexes.add(i); allDimensions.add(new DimensionValue(dimensionName, null)); } else { DimensionValue dimensionValue = new DimensionValue(dimensionName, dimensionSlice.get(dimensionName)); filledDimension.add(dimensionValue); allDimensions.add(dimensionValue); } } // If provided dimensions contain all values filled in, there's nothing to look for if (dimToFillIndexes.isEmpty()) { return Collections.emptySet(); } Set<DimensionValue> result = Sets.newHashSet(); int scans = 0; int scannedRecords = 0; // build a scan byte[] startRow = codec.createStartRowKey(allDimensions, null, startTs, false); byte[] endRow = codec.createEndRowKey(allDimensions, null, endTs, false); endRow = Bytes.stopKeyForPrefix(endRow); FuzzyRowFilter fuzzyRowFilter = createFuzzyRowFilter(new FactScan(startTs, endTs, ImmutableList.<String>of(), allDimensions), startRow); Scanner scanner = timeSeriesTable.scan(startRow, endRow, fuzzyRowFilter); scans++; try { Row rowResult; while ((rowResult = scanner.next()) != null) { scannedRecords++; // todo: make configurable if (scannedRecords > MAX_RECORDS_TO_SCAN_DURING_SEARCH) { break; } byte[] rowKey = rowResult.getRow(); // filter out columns by time range (scan configuration only filters whole rows) if (codec.getTimestamp(rowKey, codec.createColumn(startTs)) < startTs) { continue; } if (codec.getTimestamp(rowKey, codec.createColumn(endTs)) > endTs) { // we're done with scanner break; } List<DimensionValue> dimensionValues = codec.getDimensionValues(rowResult.getRow()); // At this point, we know that the record is in right time range and its dimensions matches given. // We try find first non-null valued dimension in the record that was not in given dimensions: we use it to form // next drill down suggestion int filledIndex = -1; for (int index : dimToFillIndexes) { // todo: it may be not efficient, if dimensionValues is not array-backed list: i.e. if access by index is // not fast DimensionValue dimensionValue = dimensionValues.get(index); if (dimensionValue.getValue() != null) { result.add(dimensionValue); filledIndex = index; break; } } // Ss soon as we find dimension to fill, we are not interested into drilling down further (by contract, we fill // single dimension value). Thus, we try to jump to the record that has greater value in that dimension. // todo: fast-forwarding (jumping) should be done on server-side (CDAP-1421) if (filledIndex >= 0) { scanner.close(); scanner = null; scans++; if (scans > MAX_SCANS_DURING_SEARCH) { break; } startRow = codec.getNextRowKey(rowResult.getRow(), filledIndex); scanner = timeSeriesTable.scan(startRow, endRow, fuzzyRowFilter); } } } finally { if (scanner != null) { scanner.close(); } } LOG.trace("search for dimensions completed, scans performed: {}, scanned records: {}", scans, scannedRecords); return result; } /** * Finds all measure names of the facts that match given {@link DimensionValue}s and time range. * @param allDimensionNames list of all dimension names to be present in the fact record * @param dimensionSlice dimension values to filter by, {@code null} means any non-null value. * @param startTs start timestamp, in sec * @param endTs end timestamp, in sec * @return {@link Set} of measure names */ // todo: pass a limit on number of measures returned public Set<String> findMeasureNames(List<String> allDimensionNames, Map<String, String> dimensionSlice, long startTs, long endTs) { List<DimensionValue> allDimensions = Lists.newArrayList(); for (String dimensionName : allDimensionNames) { allDimensions.add(new DimensionValue(dimensionName, dimensionSlice.get(dimensionName))); } byte[] startRow = codec.createStartRowKey(allDimensions, null, startTs, false); byte[] endRow = codec.createEndRowKey(allDimensions, null, endTs, false); endRow = Bytes.stopKeyForPrefix(endRow); FuzzyRowFilter fuzzyRowFilter = createFuzzyRowFilter(new FactScan(startTs, endTs, ImmutableList.<String>of(), allDimensions), startRow); Set<String> measureNames = Sets.newHashSet(); int scannedRecords = 0; // todo: make configurable try (Scanner scanner = timeSeriesTable.scan(startRow, endRow, fuzzyRowFilter)) { Row rowResult; while ((rowResult = scanner.next()) != null) { scannedRecords++; if (scannedRecords > MAX_RECORDS_TO_SCAN_DURING_SEARCH) { break; } byte[] rowKey = rowResult.getRow(); // filter out columns by time range (scan configuration only filters whole rows) if (codec.getTimestamp(rowKey, codec.createColumn(startTs)) < startTs) { continue; } if (codec.getTimestamp(rowKey, codec.createColumn(endTs)) > endTs) { // we're done with scanner break; } measureNames.add(codec.getMeasureName(rowResult.getRow())); } } LOG.trace("search for measures completed, scanned records: {}", scannedRecords); return measureNames; } @Override public void close() throws IOException { timeSeriesTable.close(); entityTable.close(); } public static byte[][] getSplits(int aggGroupsCount) { return FactCodec.getSplits(aggGroupsCount); } private FuzzyRowFilter createFuzzyRowFilter(FactScan scan, List<String> measureNames) { List<ImmutablePair<byte[], byte[]>> fuzzyPairsList = new ArrayList<>(); for (String measureName : measureNames) { // add exact fuzzy keys for all the measure names provided in the scan, when constructing fuzzy row filter // its okay to use startTs as timebase part of rowKey is always fuzzy in fuzzy filter byte[] startRow = codec.createStartRowKey(scan.getDimensionValues(), measureName, scan.getStartTs(), false); byte[] fuzzyRowMask = codec.createFuzzyRowMask(scan.getDimensionValues(), measureName); fuzzyPairsList.add(new ImmutablePair<>(startRow, fuzzyRowMask)); } return new FuzzyRowFilter(fuzzyPairsList); } private FuzzyRowFilter createFuzzyRowFilter(FactScan scan, byte[] startRow) { // we need to always use a fuzzy row filter as it is the only one to do the matching of values // if we are querying only one measure, we will use fixed measureName for filter, // if there are no measures or more than one measures to query we use `ANY` fuzzy filter. String measureName = (scan.getMeasureNames().size() == 1) ? scan.getMeasureNames().iterator().next() : null; byte[] fuzzyRowMask = codec.createFuzzyRowMask(scan.getDimensionValues(), measureName); // note: we can use startRow, as it will contain all "fixed" parts of the key needed return new FuzzyRowFilter(ImmutableList.of(new ImmutablePair<>(startRow, fuzzyRowMask))); } // todo: shouldn't we aggregate "before" writing to FactTable? We could do it really efficient outside // also: the underlying datasets will do aggregation in memory anyways private static void inc(NavigableMap<byte[], NavigableMap<byte[], byte[]>> incrementsTable, byte[] rowKey, byte[] column, long value) { byte[] oldValue = get(incrementsTable, rowKey, column); long newValue = value; if (oldValue != null) { if (Bytes.SIZEOF_LONG == oldValue.length) { newValue = Bytes.toLong(oldValue) + value; } else if (Bytes.SIZEOF_INT == oldValue.length) { // In 2.4 and older versions we stored it as int newValue = Bytes.toInt(oldValue) + value; } else { // should NEVER happen, unless the table is screwed up manually throw new IllegalStateException( String.format("Could not parse measure @row %s @column %s value %s as int or long", Bytes.toStringBinary(rowKey), Bytes.toStringBinary(column), Bytes.toStringBinary(oldValue))); } } set(incrementsTable, rowKey, column, Bytes.toBytes(newValue)); } private static byte[] get(NavigableMap<byte[], NavigableMap<byte[], byte[]>> table, byte[] row, byte[] column) { NavigableMap<byte[], byte[]> rowMap = table.get(row); return rowMap == null ? null : rowMap.get(column); } private static void set(NavigableMap<byte[], NavigableMap<byte[], byte[]>> table, byte[] row, byte[] column, byte[] value) { NavigableMap<byte[], byte[]> rowMap = table.get(row); if (rowMap == null) { rowMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); table.put(row, rowMap); } rowMap.put(column, value); } private String toPrettyLog(byte[] key) { StringBuilder sb = new StringBuilder("{"); for (byte b : key) { String enc = String.valueOf((int) b) + " "; sb.append(enc.substring(0, 5)); } sb.append("}"); return sb.toString(); } }
5,466
https://github.com/conseweb/farmer/blob/master/storage/indexer/fileinfo.go
Github Open Source
Open Source
Apache-2.0
null
farmer
conseweb
Go
Code
233
741
package indexer import ( "fmt" "io" "net/url" "os" "path/filepath" "time" "github.com/go-xorm/xorm" ) type FileInfo struct { ID int64 `xorm:"pk autoincr 'id'" json:"id"` DeviceID string `xorm:"notnull index 'device_id'" json:"device_id"` Path string `xorm:"notnull index 'path'" json:"path"` Hash string `xorm:"notnull index 'hash'" json:"hash"` Size int64 `xorm:"'size'" json:"hash"` Created time.Time `xorm:"created" json:"created"` Updated time.Time `xorm:"updated" json:"updated"` } /// For API server func (fi *FileInfo) Insert(orm *xorm.Engine) error { n, err := orm.Insert(fi) return checkOrmRet(n, err) } func (fi *FileInfo) Update(orm *xorm.Engine) error { n, err := orm.Where("id = ?", fi.ID).Update(fi) return checkOrmRet(n, err) } func (fi *FileInfo) Remove(orm *xorm.Engine) error { n, err := orm.Where("id = ?", fi.ID).Delete(fi) return checkOrmRet(n, err) } /// For Client // func (fi *FileInfo) Download(idx *Indexer) error { fp := filepath.Join(idx.chroot, fi.Path) u, _ := url.Parse(idx.addr) u.Path = filepath.Join("/api/fs/cat/", fi.Path) resp, err := idx.cli.Get(u.String()) if err != nil { return err } if resp.StatusCode >= 300 { return fmt.Errorf(resp.Status) } _ = os.Remove(fp) f, err := os.OpenFile(fp, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer func() { resp.Body.Close() f.Close() }() _, err = io.Copy(f, resp.Body) if err != nil { return err } return nil } func (fi *FileInfo) RemoveLocal(idx *Indexer) error { fp := filepath.Join(idx.chroot, fi.Path) return os.Remove(fp) } func checkOrmRet(n int64, err error) error { if err != nil { return err } if n == 0 { return fmt.Errorf("control xorm not found") } return nil }
1,813
https://github.com/rgrannell1/mood/blob/master/server/routes/shared/config.ts
Github Open Source
Open Source
MIT
2,019
mood
rgrannell1
TypeScript
Code
191
540
import * as errors from '@rgrannell/errors' /** * Ensure required variables are present * * @param {Array<string>} names an array of variable names */ const expectVariables = (names:string[]) => { const vars = Object.keys(process.env).join('\n') for (const name of names) { const val = process.env[name] if (!val) { throw new Error(`environmental variable ${name} was missing. Available variables are:\n${vars}`) } if (val.startsWith('"') || val.startsWith("'")) { throw new Error(`environmental variable ${name} started with a quote`) } } } /** * Read and parse a Google private key * * @param {Buffer} content */ const parseGooglePrivateKey = (content:string) => { return JSON.parse(Buffer.from(content, 'base64') as any) } /** * Read an environmental variable * * @param {string} name the name of the environmental variable */ const readVariable = (name:string): string => { const value = process.env[name] || process.env[name.toLowerCase()] if (typeof value === 'undefined') { throw errors.internalServerError(`configuration variable ${name} absent`, 500) } return value } /** * Application configuration */ export default () => { expectVariables([ 'COOKIE_KEY', 'ENCRYPTION_KEY', 'GOOGLE_PRIVATE_KEY', 'TEST_ACCOUNT_CREDENTIAL' ]) return { test: { credential: readVariable('TEST_ACCOUNT_CREDENTIAL') }, cookies: { keys: [readVariable('COOKIE_KEY')] }, google: { db: 'https://mood-251413.firebaseio.com', privateKey: parseGooglePrivateKey(readVariable('GOOGLE_PRIVATE_KEY')) }, encryption: { key: readVariable('ENCRYPTION_KEY') } } }
26,139