text
stringlengths
27
775k
#!/bin/bash # Steps to set-up 64-bit cross compilation (for Windows under Linux): # - install mingw-w64 (this will provide all kinds of executable named x86_64-w64-mingw32-*) # - add a nim.cfg with the following content: # # amd64.windows.gcc.path = "/usr/bin" # amd64.windows.gcc.exe = "x86_64-w64-mingw32-gcc" # amd64.windows.gcc.linkerexe = "x86_64-w64-mingw32-gcc" # # note 1: Apparently the linkerexe has to be "x86_64-w64-mingw32-gcc" # and not "x86_64-w64-mingw32-ld" # note 2: The nim.cfg does not have to be specified explicitly in the compilation command. # The nim compiler searches for a file called "nim.cfg" (according to the rules # mentioned here: http://nim-lang.org/docs/nimc.html#compiler-usage-configuration-files) # and uses it automatically. # - use "--cpu: amd64 --os:windows" in the compilation command below. # echo -e "\n *** compiling 64 bit version" nim c -d:release \ --cpu:amd64 --os:windows \ --parallelBuild:1 --verbosity:3 \ -o:../bin/HiCS_x64.exe src/main.nim # # I didn't test 32-bit cross compilation but basically it should work by: # - installing mingw32 (probably not needed, see below) # - using `--cpu:i386` in the above compilation # - checking the exact name of the mingw32-gcc binary (probably just i686-w64-mingw32-gcc, see below) # - adding this name to i386.windows.gcc.* in the nim.cfg # # # Some resources on cross compilation: # - http://forum.nim-lang.org/t/1132#6973 # - http://forum.nim-lang.org/t/1251#7712 # - http://forum.nim-lang.org/t/251#1278 # - http://stackoverflow.com/questions/19690504/how-do-i-compile-and-link-a-32-bit-windows-executable-using-mingw-w64 # # Interestingly mingw-w64 does not only create the binaries "x86_64-w64-..." but also "i686-w64-...". # Explanation from this answer: # # "Don't be put off by the rather confusing executable names: # i686-w64-mingw32-gcc is the 32-bit compiler and # x86_64-w64-mingw32-gcc is the 64-bit one." # # # echo -e "\n *** compiling 32 bit version" nim c -d:release \ --cpu:i386 --os:windows \ --parallelBuild:1 --verbosity:3 \ -o:../bin/HiCS_x86.exe src/main.nim
<?php namespace App\Tests\Behat\v2\Common; trait INavigateToAdminTrait { /** * @When I navigate to the admin clients search page */ public function iNavigateToAdminClientsSearchPage() { $this->clickLink('Clients'); $this->iAmOnAdminClientsSearchPage(); } /** * @When I navigate to the admin add user page */ public function iNavigateToAdminAddUserPage() { $this->pressButton('Add new user'); $this->iAmOnAdminAddUserPage(); } /** * @When I navigate to my admin user profile page */ public function iNavigateToAdminUserProfilePage() { $this->clickLink('Your details'); $mainElement = $this->getSession()->getPage()->find('xpath', '//main'); $mainElement->clickLink('Your details'); } /** * @When I navigate to the add a new user page */ public function iNavigateToAddNewUser() { $this->iAmOnAdminUsersSearchPage(); $this->clickBasedOnText('Add new user'); } /** * @When I navigate to the admin analytics page */ public function iNavigateToAdminAnalyticsSearchPage() { $this->clickLink('Analytics'); $this->iAmOnAdminAnalyticsPage(); } /** * @When I navigate to the upload users page */ public function iNavigateToAdminUploadUsersPage() { $this->clickLink('Upload users'); } /** * @When I navigate to the organisations page */ public function iNavigateToOrganisationsPage() { $this->clickLink('Organisations'); $this->iAmOnAdminOrganisationSearchPage(); } /** * @When I navigate to the add organisation page */ public function iNavigateToAddOrganisationPage() { $this->pressButton('Add a new organisation'); $this->iAmOnAdminAddOrganisationPage(); } /** * @When I navigate to the report checklist page */ public function iNavigateToTheReportChecklistPage() { $this->clickLink('Checklist'); $this->iAmOnAdminReportChecklistPage(); } /** * @When I navigate to the admin report submissions page */ public function iNavigateToAdminReportSubmissionsPage() { $this->clickLink('Submissions'); $this->iAmOnAdminReportSubmissionsPage(); } }
module Named.Parser where import Named.Data import Text.ParserCombinators.Parsec import Control.Applicative ((<*),(*>)) parseNamed = parse parseLambda "Lambda" lexeme :: Parser a -> Parser a lexeme a = a <* spaces variable :: Parser String variable = do first <- letter rest <- many (letter <|> digit) return (first:rest) variableExp :: Parser Expression variableExp = Var <$> variable call :: Parser Expression call = chainl1 (lexeme parseExprExceptCall) (return Call) func :: Parser Expression func = do char '\\' <|> char 'λ' v <- lexeme variable char '.' spaces e <- parseExprTotal return $ Func v e parseExprExceptCall :: Parser Expression parseExprExceptCall = func <|> variableExp <|> (between (char '(') (char ')') parseExprTotal) parseExprTotal :: Parser Expression parseExprTotal = lexeme call <|> lexeme parseExprExceptCall parseLambda :: Parser Expression parseLambda = do spaces result <- parseExprTotal return result
import React from 'react' import { useTranslation } from 'react-i18next' import PropTypes from 'prop-types' import './Article.scss' export const Article = ({title, text, link, imageUrl}) => { const { t } = useTranslation(); return ( <article className="article" style={{backgroundImage: `url(${imageUrl})` }}> <h4 className="article__title">{title}</h4> <p className="article__text">{text}</p> <a className="article__link" href={link} target="_blank" rel="noreferrer noopener">{t('article.cta')}</a> </article> ) } Article.propTypes = { imageUrl: PropTypes.string.isRequired, title: PropTypes.string.isRequired, text: PropTypes.string, link: PropTypes.string.isRequired, } Article.displayName = 'Article' export default Article
import type { Document, Logger, Transform } from '@gltf-transform/core'; import { Packet, XMP } from '@gltf-transform/extensions'; import inquirer from 'inquirer'; import { check as validateLanguage } from 'language-tags'; import validateSPDX from 'spdx-correct'; import fs from 'fs/promises'; import path from 'path'; import { formatXMP, XMPContext } from '../util'; const DEFAULT_LANG = 'en-US'; export interface XMPOptions { packet?: string; reset?: boolean; } export const XMP_DEFAULTS = { packet: '', reset: false, }; enum Prompt { CREATOR, DESCRIPTION, LANGUAGE, TITLE, RELATED, PREFERRED_SURFACE, CREATE_DATE, RIGHTS, } async function* generateQuestions(results: Record<string, unknown>): AsyncGenerator<inquirer.Question> { let lang = (results['dc:language'] as string) || DEFAULT_LANG; yield { type: 'checkbox', name: '_prompts', message: 'Select XMP metadata:', loop: false, pageSize: 15, choices: [ { value: Prompt.CREATOR, name: 'Creator' }, { value: Prompt.TITLE, name: 'Title' }, { value: Prompt.DESCRIPTION, name: 'Description' }, { value: Prompt.RELATED, name: 'Related links' }, new inquirer.Separator(), { value: Prompt.CREATE_DATE, name: 'Date created' }, new inquirer.Separator(), { value: Prompt.LANGUAGE, name: 'Language' }, new inquirer.Separator(), { value: Prompt.RIGHTS, name: 'License and rights' }, new inquirer.Separator(), { value: Prompt.PREFERRED_SURFACE, name: 'Preferred surfaces (AR)' }, ], } as inquirer.Question; const prompts = new Set<Prompt>(results._prompts as Prompt[]); // Prompt for 'dc:language' first, used as the default for Language Alternative entries. if (prompts.has(Prompt.LANGUAGE)) { yield { type: 'input', name: 'dc:language', message: 'Language?', suffix: ' (dc:language)', validate: (input: string) => (validateLanguage(input) ? true : 'Invalid language; refer to IETF RFC 3066.'), default: DEFAULT_LANG, }; lang = results['dc:language'] as string; } if (prompts.has(Prompt.CREATOR)) { yield { type: 'input', name: 'dc:creator', message: 'Creator of the model?', suffix: ' (dc:creator)', filter: (input: string) => createList([input]), transformer: formatXMP, } as inquirer.Question; } if (prompts.has(Prompt.TITLE)) { yield { type: 'input', name: 'dc:title', message: 'Title of the model?', suffix: ' (dc:title)', filter: (input: string) => createLanguageAlternative(input, lang), transformer: formatXMP, } as inquirer.Question; } if (prompts.has(Prompt.DESCRIPTION)) { yield { type: 'input', name: 'dc:description', message: 'Description of the model?', suffix: ' (dc:description)', filter: (input: string) => createLanguageAlternative(input, lang), transformer: formatXMP, } as inquirer.Question; } if (prompts.has(Prompt.RELATED)) { yield { type: 'input', name: 'dc:relation', message: 'Related links?', suffix: ' Comma-separated URLs. (dc:relation)', filter: (input: string) => createList(input.split(/[,\n]/).map((url) => url.trim())), transformer: formatXMP, } as inquirer.Question; } if (prompts.has(Prompt.RIGHTS)) { yield { type: 'list', name: '_rights', message: 'Is the model rights-managed?', suffix: ' (dc:rights, xmpRights:Marked, model3d:spdxLicense)', loop: false, pageSize: 15, choices: [ // Common SPDX license identifiers applicable to creative works. { value: '', name: 'Unspecified' }, { value: 'UNLICENSED', name: 'Restricted by copyright, trademark, or other marking' }, { value: 'CC0-1.0', name: 'Public domain (CC0-1.0)' }, { value: 'CC-BY-4.0', name: 'Creative Commons Attribution (CC-BY-4.0)' }, { value: 'CC-BY-ND-4.0', name: 'Creative Commons Attribution-NoDerivs (CC-BY-ND-4.0)' }, { value: 'CC-BY-SA-4.0', name: 'Creative Commons Attribution-ShareAlike (CC-BY-SA-4.0)' }, { value: 'CC-BY-NC-4.0', name: 'Creative Commons Attribution-NonCommercial (CC-BY-NC-4.0)' }, { value: 'CC-BY-NC-ND-4.0', name: 'Creative Commons Attribution-NonCommercial-NoDerivs (CC-BY-NC-ND-4.0)', }, { value: 'CC-BY-NC-SA-4.0', name: 'Creative Commons Attribution-NonCommercial-ShareAlike (CC-BY-NC-SA-4.0)', }, { value: 'OTHER', name: 'Other license' }, ], } as inquirer.Question; if (results._rights === 'UNLICENSED') { results['xmpRights:Marked'] = true; yield { type: 'input', name: 'xmpRights:Owner', message: 'Who is the intellectual property (IP) owner?', suffix: ' (xmpRights:Owner)', filter: (input: string) => createList([input]), transformer: formatXMP, } as inquirer.Question; yield { type: 'input', name: '_usage', message: 'Other usage instructions?', suffix: ' Plain text or URL. (xmpRights:UsageTerms, xmpRights:WebStatement)', }; const usage = results._usage as string; if (/^https?:\/\//.test(usage)) { results['xmpRights:WebStatement'] = usage; } else if (usage) { results['xmpRights:UsageTerms'] = createLanguageAlternative(usage, lang); } } if (results._rights === 'OTHER') { yield { type: 'confirm', name: '_isLicenseSPDX', message: 'Does the license have an SPDX ID?', suffix: ' See https://spdx.dev/.', }; if (results._isLicenseSPDX) { yield { type: 'input', name: 'model3d:spdxLicense', message: 'What is the SPDX license ID?', suffix: ' (model3d:spdxLicense)', validate: (input: string) => validateSPDX(input) ? true : 'Invalid SPDX ID; refer to https://spdx.dev/.', }; } else { yield { type: 'input', name: 'dc:rights', message: 'What is the plain text license or rights statement?', suffix: ' (dc:rights)', filter: (input: string) => createLanguageAlternative(input, lang), transformer: formatXMP, } as inquirer.Question; } } } if (prompts.has(Prompt.CREATE_DATE)) { yield { type: 'input', name: 'xmp:CreateDate', message: 'Date created?', suffix: ' (xmp:CreateDate)', default: new Date().toISOString().substring(0, 10), validate: validateDate, }; } if (prompts.has(Prompt.PREFERRED_SURFACE)) { yield { type: 'checkbox', name: 'model3d:preferredSurfaces', message: 'Preferred surfaces for augmented reality (AR)? Select all that apply.', suffix: ' (model3d:preferredSurfaces)', loop: false, pageSize: 15, choices: [ { value: 'horizontal_up', short: 'horizontal_up', name: 'horizontal_up (rests on top of horizontal surfaces)', }, { value: 'horizontal_down', short: 'horizontal_down', name: 'horizontal_down (suspended from horizonal surfaces)', }, { value: 'vertical', short: 'vertical', name: 'vertical (attaches to vertical surfaces)', }, { value: 'human_face', short: 'human_face', name: 'human_face (worn or displayed on a human face)', }, ], filter: (input: string[]) => createList(input), transformer: formatXMP, } as inquirer.Question; } } export const xmp = (_options: XMPOptions = XMP_DEFAULTS): Transform => { const options = { ...XMP_DEFAULTS, ..._options } as Required<XMPOptions>; return async (document: Document): Promise<void> => { const logger = document.getLogger(); const root = document.getRoot(); const xmpExtension = document.createExtension(XMP); if (options.reset) { xmpExtension.dispose(); logger.info('[xmp]: Reset XMP metadata.'); logger.debug('[xmp]: Complete.'); return; } if (options.packet) { const packetPath = path.resolve(options.packet); logger.info(`[xmp]: Loading "${packetPath}"...`); const packetJSON = await fs.readFile(packetPath, 'utf-8'); const packetDef = validatePacket(JSON.parse(packetJSON)); const packet = xmpExtension.createPacket().fromJSONLD(packetDef); root.setExtension('KHR_xmp_json_ld', packet); logger.debug('[xmp]: Complete.'); return; } const inquirer = require('inquirer'); const packet = root.getExtension<Packet>('KHR_xmp_json_ld') || xmpExtension.createPacket(); const results = packet.toJSONLD(); try { for await (const question of generateQuestions(results)) { Object.assign(results, await inquirer.prompt(question)); } } catch (e) { checkTTY(e, logger); throw e; } // Context. packet.setContext({ ...packet.getContext(), ...createContext(results), xmp: XMPContext.xmp, // required for xmp:MetadataDate below. }); // Properties. let numProperties = 0; for (const name in results) { // NOTICE: Calling 'continue' in this context hits a Babel bug. if (!name.startsWith('_') && !name.startsWith('@') && results[name]) { packet.setProperty(name, results[name] as string); numProperties++; } } if (numProperties === 0) { throw new Error('xmp: No properties added.'); } // xmp:MetadataDate should be the same as, or more recent than, xmp:ModifyDate. packet.setProperty('xmp:MetadataDate', new Date().toISOString().substring(0, 10)); root.setExtension('KHR_xmp_json_ld', packet); logger.debug(`[xmp]: Packet contents: ${JSON.stringify(packet.toJSONLD(), null, 2)}`); logger.debug('[xmp]: Complete.'); }; }; /** Validates a JSON-LD XMP packet for basic expectations. */ function validatePacket(packetDef: Record<string, unknown>): Record<string, unknown> { // Check context. const context = packetDef['@context'] as Record<string, unknown>; if (!context) { throw new Error('Missing @context in packet.'); } // Check properties. for (const name in packetDef) { if (name.startsWith('@')) continue; const prefix = name.split(':')[0]; if (!prefix) { throw new Error(`Invalid property, "${name}"`); } if (!(prefix in context)) { throw new Error(`Missing context definition, "${prefix}"`); } } return packetDef; } /** * The 'inquirer' library supports most terminal clients, but won't run in non-interactive * environments. Check errors and try to provide a useful warning to the user. * See: https://github.com/SBoudrias/Inquirer.js#Support. */ function checkTTY(error: unknown, logger: Logger) { if ((error as { isTtyError?: boolean }).isTtyError) { logger.warn( 'Unable to run "inquirer" session in this terminal environment.' + ' Try another terminal or provide a --packet JSON-LD input.' ); } } /** Creates a Language Alternative entry with a single language. */ function createLanguageAlternative(value: string, language: string): Record<string, unknown> | null { if (!value) return null; return { '@type': 'rdf:Alt', 'rdf:_1': { '@language': language, '@value': value, }, }; } /** Creates a List entry. */ function createList(list: string[]): Record<string, unknown> | null { list = list.filter((value) => !!value); if (!list.length) return null; return { '@list': list }; } function validateDate(input: string): boolean | string { const [date] = input.split('T'); if (!/\d{4}-\d{2}-\d{2}/.test(date) || new Date(date).toISOString().substring(0, 10) !== date) { return 'Invalid ISO date string.'; } return true; } function createContext(_object: unknown, acc: Record<string, string> = {}): Record<string, string> { if (Object.prototype.toString.call(_object) !== '[object Object]') return acc; const object = _object as Record<string, unknown>; for (const key in object) { const value = object[key]; const [prefix, suffix] = key.split(':'); if (prefix && suffix && prefix in XMPContext) { acc[prefix] = XMPContext[prefix]; createContext(value, acc); } } return acc; }
# FriendlyId Globalize [Globalize](https://github.com/globalize/globalize) support for [FriendlyId](https://github.com/norman/friendly_id).
rm -rf dist/plugins/DefaultPlugin rm -rf dist/plugins/PluginBase (git co $1 && git merge $2) git submodule foreach git fetch --tags git submodule update --init --recursive (cd dist/plugins/DefaultPlugin && git co develop) (cd dist/plugins/PluginBase && git co develop)
using System; using System.Linq; namespace AcademyPopcorn { public class ConsoleInterface { } }
using System; /// <summary> /// The face attributes class that holds Age/Gender/Head Pose/Smile/Facial Hair information. /// </summary> [Serializable] public class FaceAttributes { /// <summary> /// Gets or sets the age value. /// </summary> /// <value> /// The age value. /// </value> public float age; /// <summary> /// Gets or sets the gender. /// </summary> /// <value> /// The gender. /// </value> public string gender; /// <summary> /// Gets or sets the head pose. /// </summary> /// <value> /// The head pose. /// </value> public HeadPose headPose; /// <summary> /// Gets or sets the smile value. Represents the confidence of face is smiling. /// </summary> /// <value> /// The smile value. /// </value> public float smile; /// <summary> /// Gets or sets the facial hair. /// </summary> /// <value> /// The facial hair. /// </value> public FacialHair facialHair; }
<?php namespace Mapp\Connect\Framework\Mail; use Magento\Framework\Exception\MailException; use Magento\Framework\Phrase; class Transport implements \Magento\Framework\Mail\TransportInterface { protected $parameters; protected $messageId; protected $mappconnect; public function __construct($mappconnect, $messageId, $parameters) { $this->mappconnect = $mappconnect; $this->messageId = $messageId; $this->parameters = $parameters; } public function sendMessage() { if (!$this->messageId) { return 0; } foreach ($this->parameters['to'] as $to) { $data = $this->parameters['params']; $data['messageId'] = strval($this->messageId); $data['email'] = $to; try { $this->mappconnect->event('email', $data); } catch(\Exception $e) { $this->logger->error('MappConnect: cannot sent email event', ['exception' => $e]); } } } public function getMessage() { return $this->messageId; } }
package watch.craft.scrapers import watch.craft.Scraper import watch.craft.Scraper.Job.Leaf import watch.craft.Scraper.ScrapedItem import watch.craft.shopify.extractShopifyOffers import watch.craft.utils.* import java.net.URI class OrbitScraper : Scraper { override val jobs = forPaginatedRootUrl(ROOT_URL) { root -> root .selectMultipleFrom("#Collection .grid__item") .map { el -> val title = el.textFrom(".product-card__title") Leaf(title, el.hrefFrom("a.grid-view-item__link")) { doc -> val desc = doc.formattedTextFrom(".product-single__description") // Remove all the dross val name = title .replace("NEW: ", "") .replace("\\S+%".toRegex(), "") // ABV .replace("WLS\\d+".toRegex(), "") // Some weird code .split("-")[0] .trim() ScrapedItem( name = name, summary = null, desc = desc, mixed = title.contains("mixed", ignoreCase = true), abv = title.maybe { abvFrom() }, available = ".price--sold-out" !in el, offers = doc.orSkip("Can't extract offers, so assume not a beer") { extractShopifyOffers(desc.maybe { sizeMlFrom() }) }, thumbnailUrl = el.srcFrom("noscript img.grid-view-item__image") ) } } } companion object { val ROOT_URL = URI("https://orbit-beers.myshopify.com/collections/all") } }
--- layout: post title: " [LINE] Refresh 휴가를 받다 ! " categories: E.T.C author: goodGid --- * content {:toc} ## Prolouge * 재직 중인 LINE 회사에서 신규 입사자는 만 2년 근무를 하면 Refresh 휴가를 받을 수 있다. * 그리고 오늘(=1월2일) 기준으로 입사한 지 만 2년이 되었다. <p>2019. 01. 02 ~ 2021. 01. 02</p> --- ## Refresh 휴가 ![](/assets/img/posts/LINE-Refresh-Welfare_1.png) ![](/assets/img/posts/LINE-Refresh-Welfare_2.png) ![](/assets/img/posts/LINE-Refresh-Welfare_3.png) * LINE Refresh 제도는 기존에도 있었지만 작년에 변경되었다. 물론 좋은 방향으로 변경되었다. * 변경된 제도는 다음과 같다. **10일 휴가**를 주고 **100만 원**을 준다. 단 100만 원에 대해서는 1일 20만 원으로 계산하여 추가 휴가를 받을 수 있다. > Example ``` 10일 휴가 + 100만 원 10일 휴가 + (추가) 1일 휴가 + 80만 원 10일 휴가 + (추가) 2일 휴가 + 60만 원 10일 휴가 + (추가) 5일 휴가 + 0만 원 ``` * 결론적으로 21년도에는 기존 연차 15일 + Refresh 휴가 10일 + @ 최소 25일의 휴가가 생겼다. (든든함++) --- ## Summary * 벌써 2년이라니 !!! 2년 동안 쉼 없이 달려왔고 빠르게 시간이 흘러갔구나. * 그동안 난 무엇을 배웠고 어떻게 성장했고 얼마나 발전했을까? 어제보다 더 성장한 내가 되었기를 기도한다. 21년도 화이팅하자 : )
use syntax::ext::base::{self, ExtCtxt}; use syntax::feature_gate; use syntax::symbol::{kw, sym}; use syntax_pos::Span; use syntax::tokenstream::TokenTree; pub fn expand_trace_macros(cx: &mut ExtCtxt<'_>, sp: Span, tt: &[TokenTree]) -> Box<dyn base::MacResult + 'static> { if !cx.ecfg.enable_trace_macros() { feature_gate::emit_feature_err(&cx.parse_sess, sym::trace_macros, sp, feature_gate::GateIssue::Language, feature_gate::EXPLAIN_TRACE_MACROS); } match tt { [TokenTree::Token(token)] if token.is_keyword(kw::True) => { cx.set_trace_macros(true); } [TokenTree::Token(token)] if token.is_keyword(kw::False) => { cx.set_trace_macros(false); } _ => cx.span_err(sp, "trace_macros! accepts only `true` or `false`"), } base::DummyResult::any_valid(sp) }
package money._07_apples_and_oranges class Dollar(override protected val amount: Int) extends Money(amount) { def times(mul: Int): Dollar = { new Dollar(amount * mul) } }
#!/usr/bin/env bash # Domain - DNS entry must be created and point to the namespace of the ingress. D=${1:-control.istio.webinf.info} # Namespace of the gateway. INGRESS=${2:-istio-ingress} export ISTIOIP=$(kubectl get -n $INGRESS service ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') echo "Ingress IP: $ISTIOIP, DOMAIN: $D" kubectl create ns istio-debug 2>/dev/null cat test/k8s/istio-debug/pilot-gateway.yaml | \ sed s/control.istio.webinf.info/$D/ | \ sed s,istio-ingress,${INGRESS}, | \ kubectl apply --grace-period=4 -f -
# sub toSec { my ($h,$m,$s) = split /:/,@_[0]; return $s + 60 * ($m + (60 * $h)); return ($result < 0) ? $result + 86400 : $result; } sub fixDate { my $months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'; my ($month, $day, $hh, $mm, $ss, $year) = split "[ \:]+",shift; return "$year-". sprintf("%02d",1+index($months,$month)/4) . "-$day $hh:$mm:$ss"; } my %stats; my %dates; my %apps; my $count = 0; my %labels = ( 'barcodeprint' => 'barcode print', 'bedlist' => 'bed list', 'bulkedit' => 'bulk edit', 'check' => 'server check', 'collectionstats' => 'coll stats', 'createobjects' => 'create objs', 'governmentholdings' => 'govt hldngs', 'hierarchyviewer' => 'hrrchy viewer', 'holdings' => 'hold ings', 'inventory' => 'invent ory', 'keyinfo' => 'key info', 'grpinfo' => 'group info', 'grpmove' => 'group move', 'locreport' => 'loc report', 'movecrate' => 'move crate', 'moveobject' => 'move objs', 'objdetails' => 'obj dets', 'objinfo' => 'object info', 'objnamecleaning' => 'name cleaning', 'packinglist' => 'pckng list', 'powermove' => 'power move', 'upload' => 'tricdr upload' ); open APPDATA,"<@ARGV[0]"; while (<APPDATA>) { chomp; $count++; s/ *\t */\t/g; my ($date,$ip,$app,$action,$end,$sec,$sys,$loc1,$loc2,$parms) = split "\t"; #$date = fixDate($date); $sys = 'production'; # override what was in the log $app =~ s/check server/check/; $app =~ s/'//g; next if $sys =~ /PROTOTYPE/; next if $sys =~ /\*/; next if $sys eq ''; next if $app =~ / /; next if $app =~ /^(move|objnamecleaning)$/; $stats{$sys}{$app}{uses}++; $stats{$sys}{$app}{time}+=$sec; $date = substr($date,0,10); #print $date; $dates{$sys}{$date}{$app}++; $apps{$app}++; } print << "EOF"; <html> <head> <link rel="stylesheet" type="text/css" href="css/reset.css"> <link rel="stylesheet" type="text/css" href="css/base.css"> </head> <a name="top"/> <h2>Legacy Webapp Utilization Report</h2> EOF print "\n<h4>" . scalar localtime() . "</h4>\n<table border=\"1\">"; foreach my $sys (sort keys %stats) { # print "\n<h2>system: $sys</h2>\n"; print '<p style="height: 10px;"/>'; print "\n<h2>Overall use for each webapp</h2>\n"; print "\n<table border=\"1\" cellpadding=\"4px\">\n"; # my @header = ('app','uses','response time (s.)','average (s.)'); my @header = ('app','uses','average response time (s.)'); print '<tr><th>' . join('<th>',@header) . '</tr>' . "\n"; my %usage = %{ $stats{$sys} }; my %myapps; my $totaluse = 0; foreach my $app (sort keys %usage) { $myapps{$app}+=$usage{$app}{uses}; my $appuses = $usage{$app}{uses}; $totaluse += $appuses; $labels{$app} = $app unless $labels{$app}; my $avgtime = $appuses > 0 ? $usage{$app}{'time'}/$appuses : 0; # printf "<tr><td>%s</td><td>%s</td><td>%.1f</td><td>%.1f</td>\n",$app,$usage{$app}{uses},$usage{$app}{time},$avgtime; printf "<tr><td>%s</td><td>%s</td><td>%.1f</td>\n",$labels{$app},$usage{$app}{uses},$avgtime; } printf "<tr><td>%s</td><td>%s</td><td>%s</td>\n",'Total',$totaluse,'--'; print "</table>\n"; print '<p style="height: 30px;"/>'; print "\n<h2>Daily Use for each webapp</h2>\n"; print "\n<table style=\"table-layout: fixed;\" cellpadding=\"4px\">\n"; print '<tr><th style="min-width: 70px;">date<th>' . join('<th>',map($labels{$_},sort keys %myapps)) ; print '<th>daily</th><th>cumulative</th></tr>' . "\n"; my %sysdates = %{ $dates{$sys} }; my $dailytotal; my $cumtotal; foreach my $date (sort keys %sysdates) { printf "<tr><td>%s</td>",$date; foreach my $app (sort keys %myapps) { printf "<td>%s</td>",$sysdates{$date}{$app}; $dailytotal += $sysdates{$date}{$app}; $cumtotal += $sysdates{$date}{$app}; } printf "<td>%s</td>",$dailytotal; printf "<td>%s</td>",$cumtotal; $dailytotal = 0; print "</tr>\n"; } print "</table>\n"; } print "<hr><h5>Written by jblowe\@berkeley.edu on 20 Feb 2012.</h5>"; print "</html>\n"; exit(0); my $reports; print "</table>\n"; print "<hr><h2>Details</h2><hr>"; print $reports; print "</html>\n";
RSpec.describe ABBYY::Cloud::Models::Direction do let(:data) { { source: "en-Br", target: "ru" } } subject { described_class.new(data) } it { is_expected.to be_kind_of ABBYY::Cloud::Model } its(:to_h) { is_expected.to eq data } context "with invalid source:" do before { data[:source] = "2" } it "fails" do expect { subject }.to raise_error(StandardError) end end context "without source:" do before { data.delete :source } it "fails" do expect { subject }.to raise_error(StandardError) end end context "with invalid target:" do before { data[:target] = "r" } it "fails" do expect { subject }.to raise_error(StandardError) end end context "without target:" do before { data.delete :target } it "fails" do expect { subject }.to raise_error(StandardError) end end end
module Circuitdata class ExposedArea def initialize(product) @product = product end def final_finish_total_area return nil if board_area.nil? layer_final_finish_area + barrel_area end def barrel_area return 0 if board_thickness.nil? plated_holes.map { |hole| sum_holes_area(hole) }.sum end private def layer_final_finish_area coverage = final_finish_layers.map { |layer| layer[:coverage] }.compact coverage.map { |percent| percent / 100.0 * board_area }.sum end def sum_holes_area(hole) diameter = hole[:function_attributes][:finished_size] number_of_holes = hole[:function_attributes][:number_of_holes] hole_area(diameter) * number_of_holes end def hole_area(finished_size) (finished_size / 1000) * Math::PI * board_thickness end def board_thickness @product.question_answer([:metrics, :board, :thickness]) end def board_area @product.question_answer([:metrics, :board, :area]) end def plated_holes holes.select { |process| requires_final_finish?(process) } .select { |process| has_necessary_data?(process) } end def requires_final_finish?(process) process[:function_attributes][:plated] == true && process[:function_attributes][:covered] == false end def has_necessary_data?(process) process[:function_attributes][:number_of_holes].present? && process[:function_attributes][:finished_size].present? end def holes @product.processes .select { |process| process[:function] == "holes" } end def layers @product.layers end def final_finish_layers layers.select { |layer| layer[:function] == "final_finish" } end end end
package scuff import org.junit._, Assert._ import java.io._ class TestMediaType { @Test def `remove parm`(): Unit = { val mt = MediaType("application/json;encoding=UTF-8") assertEquals("UTF-8", mt.parm("encoding").get) val mt2 = mt.removeParm("encoding") assertEquals("UTF-8", mt.parm("encoding").get) assertEquals(None, mt2.parm("encoding")) val mt3 = mt.addParm("foo", 42) assertEquals("UTF-8", mt3.parm("encoding").get) assertEquals(42, mt3.parm("foo", _.toInt).get) val mt4 = mt3.removeParm("encoding") assertEquals(None, mt4.parm("encoding")) assertEquals(42, mt4.parm("foo", _.toInt).get) } @Test def `add parm`(): Unit = { val mt = MediaType("text/html") assertEquals(None, mt.parm("foo")) val mt2 = mt.addParm("foo", 42) assertEquals(None, mt.parm("foo")) assertEquals(42, mt2.parms("foo").toInt) val mt3 = mt2.addParm("foo", 43) assertEquals(None, mt.parm("foo")) assertEquals(42, mt2.parms("foo").toInt) assertEquals(43, mt3.parms("foo").toInt) val mt4 = mt3.addParm("bar", "Hello") assertEquals(None, mt.parm("bar")) assertEquals(None, mt2.parm("bar")) assertEquals(None, mt3.parm("bar")) assertEquals("Hello", mt4.parms("bar")) } @Test def tree(): Unit = { val html = MediaType("text/html") assertEquals(None, html.treeType) val xhtml = MediaType("text/xhtml+xml;charset=utf8") assertEquals(None, xhtml.treeType.get.prefix) assertEquals("xhtml", xhtml.treeType.get.typeName) assertEquals("xml", xhtml.treeType.get.suffixType) val vendor = MediaType("application/vnd.scuff.foo+json;charset=utf8") assertEquals("vnd", vendor.treeType.get.prefix.get) assertEquals("scuff.foo", vendor.treeType.get.typeName) assertEquals("json", vendor.treeType.get.suffixType) assertTrue(MediaType("application/*").matches(vendor)) assertFalse(MediaType("application/json").matches(vendor)) assertTrue(MediaType("application/json").matches(vendor.pruned)) } @Test def serialization() = { val mt1 = MediaType("application", "json", "encoding" -> "UTF-8") val baOut = new ByteArrayOutputStream val out = new ObjectOutputStream(baOut) out.writeObject(mt1) val arr = baOut.toByteArray() val baInp = new ByteArrayInputStream(arr) val inp = new ObjectInputStream(baInp) val mt2 = inp.readObject().asInstanceOf[MediaType] assertFalse(mt1 eq mt2) assertTrue(mt1 matches mt2) assertTrue(mt2 matches mt1) assertEquals(mt1.##, mt2.##) assertEquals(mt1, mt2) val mt3 = mt1.removeParm("encoding") assertNotEquals(mt1, mt3) assertTrue(mt1 matches mt3) } }
using System; namespace BuildingBlocks.Core.Domain.DomainEventNotifications { public abstract class DomainNotificationEventBase<TEventType> : IDomainEventNotification<TEventType> where TEventType : IDomainEvent { protected DomainNotificationEventBase(TEventType domainEvent, Guid id, Guid correlationId) { CorrelationId = correlationId; Id = id; DomainEvent = domainEvent; } public Guid Id { get; set; } public Guid CorrelationId { get; set; } public TEventType DomainEvent { get; set; } } }
package com.eusecom.samshopersung import android.content.Intent import android.content.SharedPreferences import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.CollapsingToolbarLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ProgressBar import co.zsmb.materialdrawerkt.builders.accountHeader import co.zsmb.materialdrawerkt.builders.drawer import co.zsmb.materialdrawerkt.draweritems.badgeable.primaryItem import co.zsmb.materialdrawerkt.draweritems.divider import co.zsmb.materialdrawerkt.draweritems.sectionHeader import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.model.ProfileDrawerItem import dagger.android.AndroidInjection import org.jetbrains.anko.alert import org.jetbrains.anko.noButton import org.jetbrains.anko.yesButton import javax.inject.Inject import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import kotlinx.android.synthetic.main.orplist_activity.* class OrpListKtActivity : AppCompatActivity(), HasSupportFragmentInjector { private lateinit var result: Drawer private lateinit var headerResult: AccountHeader private lateinit var headerProfil: ProfileDrawerItem @Inject lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var prefs: SharedPreferences lateinit var mPagerAdapter: FragmentPagerAdapter lateinit var viewPager: ViewPager private var mProgressBar: ProgressBar? = null var saltype = 0 override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this); super.onCreate(savedInstanceState) val i = intent val extras = i.extras saltype = extras!!.getInt("saltype") setContentView(R.layout.orplist_activity) setSupportActionBar(toolbar) initCollapsingToolbar() Log.d("SharedPreferences", "instx " + prefs.toString()) // Create the adapter that will return a fragment for each section mPagerAdapter = object : FragmentPagerAdapter(supportFragmentManager) { private val mFragments = arrayOf<Fragment>(OrpFragment()) private val mFragmentNames = arrayOf(getString(R.string.orp)) override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } override fun getPageTitle(position: Int): CharSequence { return mFragmentNames[position] } } // Set up the ViewPager with the sections adapter. viewPager = findViewById(R.id.viewPager) viewPager.setAdapter(mPagerAdapter) //kotlin drawer by https://github.com/zsmb13/MaterialDrawerKt result = drawer { toolbar = this@OrpListKtActivity.toolbar hasStableIds = true savedInstance = savedInstanceState showOnFirstLaunch = false headerResult = accountHeader { background = R.drawable.pozadie savedInstance = savedInstanceState translucentStatusBar = true } sectionHeader(getString(R.string.orpekasa)) { divider = false } divider {} primaryItem(getString(R.string.orpekasareqs)) { onClick { _ -> navigateToRequests() false } } divider {} primaryItem(getString(R.string.orploc)) { onClick { _ -> //navigateToRequests() false } } divider {} primaryItem(getString(R.string.orpsettings)) { onClick { _ -> navigateToSettings() false } } divider {} primaryItem(getString(R.string.keystoreekassa)) { onClick { _ -> navigateToKeyStoreDemo() false } } } } /** * Initializing collapsing toolbar * Will show and hide the toolbar title on scroll */ private fun initCollapsingToolbar() { val collapsingToolbar = findViewById<View>(R.id.collapsing_toolbar) as CollapsingToolbarLayout collapsingToolbar.title = " " val appBarLayout = findViewById<View>(R.id.appbar) as AppBarLayout appBarLayout.setExpanded(true) // hiding & showing the title when toolbar expanded & collapsed appBarLayout.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener { internal var isShow = false internal var scrollRange = -1 override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { if (scrollRange == -1) { scrollRange = appBarLayout.totalScrollRange } if (scrollRange + verticalOffset == 0) { collapsingToolbar.title = getString(R.string.orpekasa) isShow = true } else if (isShow) { collapsingToolbar.title = " " isShow = false } } }) } override fun onDestroy() { super.onDestroy() hideProgressBar() } override fun supportFragmentInjector(): AndroidInjector<Fragment> { return fragmentDispatchingAndroidInjector } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.orp_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_request -> consume { navigateToRequests() } R.id.action_settings -> consume { navigateToSettings() } else -> super.onOptionsItemSelected(item) } //consume oncreateoptionmenu inline fun consume(f: () -> Unit): Boolean { f() return true } protected fun showProgressBar() { mProgressBar?.setVisibility(View.VISIBLE) } protected fun hideProgressBar() { mProgressBar?.setVisibility(View.GONE) } fun navigateToRequests(){ val `is` = Intent(this, OrpRequestsActivity::class.java) val extras = Bundle() extras.putInt("saltype", 0) `is`.putExtras(extras) startActivity(`is`) finish() } fun navigateToSettings(){ val `is` = Intent(this, OrpSettingsActivity::class.java) val extras = Bundle() extras.putInt("saltype", 0) `is`.putExtras(extras) startActivity(`is`) finish() } fun navigateToKeyStoreDemo() { val `is` = Intent(this, KeyStoreActivity::class.java) startActivity(`is`) finish() } }
(defproject mml-maastotietokanta-etl "0.1.0-SNAPSHOT" :description "MML Maastotietokanta GML ETL tool" :url "https://github.com/kherrala/mml-maastotietokanta-etl" :license {:name "MIT License" :url ""} :main app.main :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/java.jdbc "0.4.2"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.zip "0.1.1"] [org.clojure/tools.logging "0.3.1"] [org.apache.logging.log4j/log4j-core "2.5"] [org.slf4j/slf4j-log4j12 "1.7.18"] [commons-io/commons-io "2.4"] [com.fasterxml/aalto-xml "0.9.6"] [org.codehaus.woodstox/stax2-api "4.0.0"] [clj-time "0.11.0"] [cljts "0.2.0" :exclusions [midje]] [hikari-cp "1.5.0" :exclusions [org.slf4j/slf4j-nop]] [org.postgresql/postgresql "9.4-1203-jdbc4"] [org.postgis/postgis-jdbc "1.3.3" :exclusions [postgresql]] [org.clojure/tools.nrepl "0.2.10"]] :source-paths ["src"] :target-path "target/" :resource-paths ["resources"] :profiles {:dev {:source-paths ["dev"] :repl-options {:init-ns user}}} :repl {:resource-paths ^:replace ["resources"] :prep-tasks ^:replace [["compile"]]})
-- This query is run at the end of every month to generate the new -- entries for monthly subscriber retention. So this query should be run -- only on the first of every month. SELECT COUNT(user_id) AS active_users, platform, product_type, date_trunc(first_active_date, month) AS cohort_month, date_diff( date_trunc('2022-01-01', month), date_trunc(first_active_date, month), month ) AS _interval FROM sub_growth_daily_granular WHERE accounting_event_date < date_trunc('2022-01-01', month) AND accounting_event_date >= date_add( date_trunc('2022-01-01', month), INTERVAL -1 month ) -- We select only the active users during the last month period. AND user_type IN ("new_user", "resurrected", "churned", "retained") GROUP BY platform, product_type, _interval, cohort_month
class AddNotNullToPositionOnCarrierType < ActiveRecord::Migration[5.2] def change change_column :carrier_types, :position, :integer, null: false, default: 1 change_column :content_types, :position, :integer, null: false, default: 1 change_column :frequencies, :position, :integer, null: false, default: 1 change_column :licenses, :position, :integer, null: false, default: 1 change_column :creates, :position, :integer, null: false, default: 1 change_column :realizes, :position, :integer, null: false, default: 1 change_column :produces, :position, :integer, null: false, default: 1 change_column :owns, :position, :integer, null: false, default: 1 change_column :form_of_works, :position, :integer, null: false, default: 1 change_column :agent_types, :position, :integer, null: false, default: 1 end end
/// <reference types="react" /> export declare function onCancel(history: { push: (location: string) => void; }): void; export declare function PlacementExamples(): JSX.Element; export declare function CreatePlacement(): JSX.Element; export declare function CreatePlacementRule(): JSX.Element; export declare function EditPlacement(): JSX.Element; export declare function EditPlacementRule(): JSX.Element; export declare function EditPlacements(): JSX.Element;
package slinky.reactrouter import slinky.core._ import slinky.core.annotations.react import slinky.web.html.a import org.scalajs.dom.History import scala.scalajs.js import scala.scalajs.js.annotation.JSImport @JSImport("react-router", JSImport.Default) @js.native object ReactRouter extends js.Object { val StaticRouter: js.Object = js.native val MemoryRouter: js.Object = js.native } @JSImport("react-router-dom", JSImport.Default) @js.native object ReactRouterDOM extends js.Object { val Router: js.Object = js.native val BrowserRouter: js.Object = js.native val HashRouter: js.Object = js.native val Route: js.Object = js.native val Switch: js.Object = js.native val Link: js.Object = js.native val NavLink: js.Object = js.native val Redirect: js.Object = js.native val Prompt: js.Object = js.native } @react object StaticRouter extends ExternalComponent { case class Props(location: String, context: js.Object) override val component = ReactRouter.StaticRouter } @react object Router extends ExternalComponent { case class Props(history: History) override val component = ReactRouterDOM.Router } object BrowserRouter extends ExternalComponentNoProps { override val component = ReactRouterDOM.BrowserRouter } object Switch extends ExternalComponentNoProps { override val component = ReactRouterDOM.Switch } @react object Route extends ExternalComponent { case class Props(path: String, component: ReactComponentClass[_], exact: Boolean = false) override val component = ReactRouterDOM.Route } @react object Link extends ExternalComponentWithAttributes[a.tag.type] { case class Props(to: String) override val component = ReactRouterDOM.Link } @react object Redirect extends ExternalComponent { case class Props(to: String, push: Boolean = false) override val component = ReactRouterDOM.Redirect } @react object NavLink extends ExternalComponentWithAttributes[a.tag.type] { case class Props(to: String, activeStyle: Option[js.Dynamic] = None, activeClassName: Option[String] = None) override val component = ReactRouterDOM.NavLink }
#!/usr/bin/env bash # set -x rexx acknak_basic.rex rexx connect_basic.rex rexx frame_basic.rex rexx hdrencdec.rex rexx header_basic.rex rexx headers_basic.rex rexx headers_encdec.rex rexx netconn_basic.rex # STOMP_DEST=/queue/rexx/test/recv/10 STOMP_NMSGS=1 rexx send_basic.rex STOMP_DEST=/queue/rexx/test/recv/10nid STOMP_NMSGS=1 rexx send_basic.rex STOMP_DEST=/queue/rexx/test/recv/11 STOMP_NMSGS=1 rexx send_basic.rex STOMP_DEST=/queue/rexx/test/recv/12 STOMP_NMSGS=1 rexx send_basic.rex rexx recv_basic.rex # STOMP_DEST=/queue/rexx/test/recv/12 STOMP_NMSGS=1 rexx send_basic.rex rexx recvsq_basic.rex # ### rexx send_basic.rex # rexx stc_basic.rex rexx subscription_basic.rex rexx sun_basic.rex rexx trn_basic.rex rexx tstrutls.rex rexx uuid_basic.rex set +x
import React from "react"; import './menu.css'; import Employees from "../employees/employees"; import { NavLink } from "react-router-dom"; function Menu() { return ( <div className="Menu"> <header className="Menu-header">Find information about your company faster!</header> <div className="Menu-body"> <button className="Menu-button"> Show list of Employees </button> <button className="Menu-button">Show list of Projects</button> </div> <footer className="Menu-footer"> <table> <td> <tr>Hello1!</tr> <tr>Hello2!</tr> </td> <td></td> </table> </footer> </div> ); } export default Menu;
# 依赖倒转原则 #### 定义 >* 高层模块不应该依赖底层模块,两者都应该依赖抽象接口 >* 抽象接口不应该依赖于具体实现。而具体实现则应该依赖于抽象接口 #### 中心思想 >面向接口编程 #### 例子 ```java class Person{ public void receive(Email email){ System.out.println(email.getInfo()); } } class Email{ public String getInfo(){ return "Message from Email!"; } } ``` >上面的代码很明显有缺点:当获取的对象不是Email而是短信或者微信时,需新增类和相应接收方法 #### 符合依赖倒转原则依赖关系传递的三种方式 >* 接口传递 >* 构造方法传递 >* setter方法传递 ###### 接口传递 ```java interface IReceiver{ String getInfo(); } class Email1 implements IReceiver{ public String getInfo(){ return "Message from Email!"; } } class WeChat implements IReceiver{ @Override public String getInfo() { return "Message from WeChat!"; } } class Person1{ public void receive(IReceiver receiver){ System.out.println(receiver.getInfo()); } } ``` ###### 构造方法传递 ```java interface IOpenAndClose{ void open(); } interface ITV{ void play(); } class OpenAndClose implements IOpenAndClose{ public ITV tv; public OpenAndClose(ITV tv) { this.tv = tv; } @Override public void open() { this.tv.play(); } } class ChangHong implements ITV{ @Override public void play() { System.out.println("打开了长虹电视机"); } } class Sony implements ITV{ @Override public void play() { System.out.println("打开了索尼电视机"); } } ``` ###### setter方法传递 ```java interface IOpenAndClose1{ void open(); void setTV(ITV tv); } //下列代码已在DIP2.java存在 //interface ITV{ // // void play(); // //} class OpenAndClose1 implements IOpenAndClose1{ private ITV tv; @Override public void open() { this.tv.play(); } @Override public void setTV(ITV tv) { this.tv = tv; } } //下列代码已在DIP2.java存在 //class ChangHong implements ITV{ // // @Override // public void play() { // System.out.println("打开了长虹电视机"); // } // //} // //class Sony implements ITV{ // // @Override // public void play() { // System.out.println("打开了索尼电视机"); // } // //} ``` >很明显以上三种方法传递依赖没有违背依赖倒置原则,所以当需求发生变动时,客户端并没有作多大的改动 #### 代码 ###### [违反依赖倒置原则](../../../src/main/java/org/fade/principle/dip/DIP.java) ###### [接口传递](../../../src/main/java/org/fade/principle/dip/DIP1.java) ###### [构造方法传递](../../../src/main/java/org/fade/principle/dip/DIP2.java) ###### [setter方法传递](../../../src/main/java/org/fade/principle/dip/DIP3.java)
package com.lunatech.iamin.core.idcodec import scalaz.zio.{TaskR, ZIO} package object service extends IdCodec.Service[IdCodec] { override def encodeId(id: Long): TaskR[IdCodec, String] = ZIO.accessM(_.idCodec.encodeId(id)) override def decodeId(s: String): TaskR[IdCodec, Option[Long]] = ZIO.accessM(_.idCodec.decodeId(s)) }
import os from os.path import join as jph import numpy as np from numpy.testing import assert_array_equal from nilabels.tools.aux_methods.utils import eliminates_consecutive_duplicates, lift_list, labels_query, print_and_run from tests.tools.decorators_tools import create_and_erase_temporary_folder, test_dir # TEST tools.aux_methods.utils.py''' def test_lift_list_1(): l_in, l_out = [[0, 1], 2, 3, [4, [5, 6]], 7, [8, [9]]], range(10) assert_array_equal(lift_list(l_in), l_out) def test_lift_list_2(): l_in, l_out = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], range(10) assert_array_equal(lift_list(l_in), l_out) def test_lift_list_3(): l_in, l_out = [], [] assert_array_equal(lift_list(l_in), l_out) def test_eliminates_consecutive_duplicates(): l_in, l_out = [0, 0, 0, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], range(10) assert_array_equal(eliminates_consecutive_duplicates(l_in), l_out) @create_and_erase_temporary_folder def test_print_and_run_create_file(): cmd = 'touch {}'.format(jph(test_dir, 'z_tmp_test', 'tmp.txt')) output_msg = print_and_run(cmd) assert os.path.exists(jph(test_dir, 'z_tmp_test', 'tmp.txt')) assert output_msg == 'touch tmp.txt' @create_and_erase_temporary_folder def test_print_and_run_create_file_safety_on(): cmd = 'touch {}'.format(jph(test_dir, 'z_tmp_test', 'tmp.txt')) output_msg = print_and_run(cmd, safety_on=True) assert not os.path.exists(jph(test_dir, 'z_tmp_test', 'tmp.txt')) assert output_msg == 'touch tmp.txt' @create_and_erase_temporary_folder def test_print_and_run_create_file_safety_off(): cmd = 'touch {}'.format(jph(test_dir, 'z_tmp_test', 'tmp.txt')) output_msg = print_and_run(cmd, safety_on=False, short_path_output=False) assert os.path.exists(jph(test_dir, 'z_tmp_test', 'tmp.txt')) assert output_msg == 'touch {}'.format(jph(test_dir, 'z_tmp_test', 'tmp.txt')) def test_labels_query_int_input(): lab, lab_names = labels_query(1) assert_array_equal(lab, [1]) assert_array_equal(lab_names, ['1']) def test_labels_query_list_input1(): lab, lab_names = labels_query([1, 2, 3]) assert_array_equal(lab, [1, 2, 3]) assert_array_equal(lab_names, ['1', '2', '3']) def test_labels_query_list_input2(): lab, lab_names = labels_query([1, 2, 3, [4, 5, 6]]) assert_array_equal(lift_list(lab), lift_list([1, 2, 3, [4, 5, 6]])) assert_array_equal(lab_names, ['1', '2', '3', '[4, 5, 6]']) def test_labels_query_all_or_tot_input(): v = np.arange(10).reshape(5, 2) lab, lab_names = labels_query('all', v, remove_zero=False) assert_array_equal(lab, np.arange(10)) lab, lab_names = labels_query('tot', v, remove_zero=False) assert_array_equal(lab, np.arange(10)) lab, lab_names = labels_query('tot', v, remove_zero=True) assert_array_equal(lab, np.arange(10)[1:]) if __name__ == '__main__': test_lift_list_1() test_lift_list_2() test_lift_list_3() test_eliminates_consecutive_duplicates() test_print_and_run_create_file() test_print_and_run_create_file_safety_on() test_print_and_run_create_file_safety_off() test_labels_query_int_input() test_labels_query_list_input1() test_labels_query_list_input2() test_labels_query_all_or_tot_input()
import r from "../random"; import faker from "faker"; import { v4 as uuid } from "uuid"; import { servicify } from "../util"; import { DateTime } from "luxon"; import { append, range } from "ramda"; //import { augmentPerson } from "./augmentor"; const bcrypt = require("bcryptjs"); const getGenderForNaming = (gender) => { if (gender === 0 || gender === 1) { return gender; } return undefined; }; const createPerson = () => { const email = faker.internet.email(); const password = bcrypt.hashSync(email, 2); const gender = r.pick([0, 1, 2]); const genderForNaming = getGenderForNaming(gender); return { id: uuid(), firstName: faker.name.firstName(genderForNaming), lastName: faker.name.lastName(genderForNaming), birthDay: faker.date.past(70, "2006-01-01"), gender: gender, handedness: r.pick(["l", "r"]), salary: r.integer(2000, 10000), password, email, isAdmin: false, relatedToCEO: r.pick([ true, false, false, false, false, false, false, false, ]), }; }; const gaylord = { id: uuid(), firstName: "Gaylord", lastName: "Lohiposki", isAdmin: true, handedness: "l", gender: 0, birthDay: faker.date.past(70, "1999-01-01"), salary: 100000, password: bcrypt.hashSync("gaylordpassu", 2), email: "gaylord.lohiposki@dr-kobros.com", relatedToCEO: true, }; const numberOfEmployees = process.env.NUMBER_OF_EMPLOYEES || 50; console.log(numberOfEmployees, "numero"); const personsWithoutGaylord = range(1, parseInt(numberOfEmployees, 10)).map( createPerson ); const persons = append(gaylord, personsWithoutGaylord); console.log({ personsWithoutGaylord, persons, }); const personService = { ...servicify(persons, (p) => { const bd = typeof p.birthDay === "string" ? new Date(p.birthDay) : p.birthDay; return { ...p, birthDay: bd, get age() { const d = DateTime.fromJSDate(this.birthDay); const now = DateTime.local(); const diff = now.diff(d, "years").toObject(); return diff.years; }, }; }), auth: (email, password) => { const person = persons.find((p) => p.email === email); if (!person) { return undefined; } const compared = bcrypt.compareSync(password, person.password); if (!compared) { return undefined; } return person; }, createTokenInstance: (id) => {}, }; export default personService;
import 'package:campus_mobile_experimental/core/providers/parking.dart'; import 'package:campus_mobile_experimental/ui/common/container_view.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:provider/provider.dart'; class ParkingStructureView extends StatefulWidget { _ParkingStructureViewState createState() => _ParkingStructureViewState(); } class _ParkingStructureViewState extends State<ParkingStructureView> { late ParkingDataProvider parkingDataProvider; bool showedScaffold = false; @override Widget build(BuildContext context) { parkingDataProvider = Provider.of<ParkingDataProvider>(context); return ContainerView( child: structureList(context), ); } // builds the listview that will be put into ContainerView Widget structureList(BuildContext context) { List<String> structures = Provider.of<ParkingDataProvider>(context).getStructures(); // creates a list that will hold the list of building names List<Widget> list = []; list.add(ListTile( title: Padding( padding: const EdgeInsets.fromLTRB(8, 0, 0, 0), child: Text( "Parking Structure:", style: TextStyle( color: Theme.of(context).colorScheme.secondary, fontSize: 20, fontWeight: FontWeight.bold), ), ), )); int selectedLots = 0; parkingDataProvider.parkingViewState!.forEach((key, value) { if (value == true) { selectedLots++; } }); // loops through and adds buttons for the user to click on for (var i = 0; i < structures.length; i++) { bool structureState = parkingDataProvider.parkingViewState![structures[i]]!; list.add(ListTile( title: Padding( padding: const EdgeInsets.fromLTRB(8, 0, 0, 0), child: Text( structures[i], style: TextStyle( color: Theme.of(context) .colorScheme .secondary, // structureState ? ColorPrimary : Colors.black, fontSize: 20), ), ), trailing: IconButton( icon: Icon(structureState ? Icons.cancel_rounded : Icons.add_rounded), color: Theme.of(context) .colorScheme .secondary, // structureState ? ColorPrimary : Colors.black, onPressed: () { if (selectedLots == 10 && !structureState && showedScaffold != true) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( 'You have reached the maximum number of lots (10) that can be selected. You need to deselect some lots before you can add any more.'), duration: Duration(seconds: 5), )); showedScaffold = !showedScaffold; } parkingDataProvider.toggleLot(structures[i], selectedLots); }, ), )); } // adds SizedBox to have a grey underline for the last item in the list list.add(SizedBox()); return ListView( physics: BouncingScrollPhysics(), shrinkWrap: true, children: ListTile.divideTiles(tiles: list, context: context).toList(), ); } }
/** * Compiler pass for the service container * It handles tags to register console commands */ module.exports = class CommandCompilerPass { async process(container) { const definition = container.getDefinition("solfege_console_commands_registry"); const serviceIds = container.findTaggedServiceIds("solfege.console.command"); for (const serviceId of serviceIds) { const reference = container.getReference(serviceId); definition.addMethodCall("addCommand", [reference]); } } };
package distributions.discrete import definitions.Global._ import definitions.{Environment, PNum} import distributions.distributions.random0to1 /** * Class: Binomial * Intention(s): Encapsulates a binomial distribution. * Parameter(s): p - success rate * n - number of trials */ class Binomial (p : Double, n : Int) extends PNum(_ => { var count : Double = 0 for (i <- 1 to n) { count += (if (random0to1 < p) 1.0 else 0.0) } count }) { override def expectation(alpha : Double, tolerance : Double, environ : Environment = env) : Double = n*p override def variance(alpha : Double, tolerance : Double, environ : Environment = env) : Double = n*p*(1.0-p) }
# Déroulement de la Formation <br><br> A chaque concept clé : <br><br> - Un excercice d'application <br> - Correction de cet excercice <br> - Un exemple concret (voyons ensemble comment intégrer ce concept dans un vrai projet) <br> - Questions et réponses
> # py-kit:logr > > Read information from logs. ```bash $ virtualenv .virtenv $ v+ $(.virtenv) pip install -r requirements.txt $(.virtenv) ... ```
CREATE TABLE IF NOT EXISTS "job_adverts" ( "job_advert_id" uuid DEFAULT uuid_generate_v4 (), "exp_date" DATE NOT NULL, "description" TEXT NOT NULL, "salary_min" INTEGER NOT NULL, "salary_max" INTEGER NOT NULL, "city" VARCHAR(40), "state" VARCHAR(2), "recruiter_id" uuid REFERENCES users("acc_id") NOT NULL, "company_id" uuid REFERENCES companies("company_id"), PRIMARY KEY ("job_advert_id") );
using Microsoft.AspNetCore.Mvc; namespace ZWave.Server.Controllers; [ApiController] [Route("[controller]")] public class InfoController : ControllerBase { private readonly ILogger<InfoController> _logger; private readonly Driver _driver; public InfoController( ILogger<InfoController> logger, Driver driver) { _logger = logger; _driver = driver; } [HttpGet] public object Get() { var controller = _driver.Controller; return new { HomeId = controller.HomeId, ControllerNodeId = controller.NodeId, FirmwareVersion = controller.FirmwareVersion, ManufacturerId = controller.ManufacturerId, ProductType = controller.ProductType, ProductId = controller.ProductId, SupportedCommandIds = controller.SupportedCommandIds, LibraryVersion = controller.LibraryVersion, LibraryType = controller.LibraryType, SucNodeId = controller.SucNodeId, ApiVersion = controller.ApiVersion, ChipType = controller.ChipType, ChipVersion = controller.ChipVersion, IsPrimary = controller.IsPrimary, NodeIds = controller.Nodes.Select(pair => pair.Value.Id).ToList(), }; } }
#!/bin/bash set -eo pipefail declare -x SENTRY_CACHE_TYPE [[ -z "${SENTRY_CACHE_TYPE}" ]] && SENTRY_CACHE_TYPE="filebased" declare -x SENTRY_CACHE_HOST [[ -z "${SENTRY_CACHE_HOST}" ]] && SENTRY_CACHE_HOST="" true
## Example response in JSON ```json { "aeccar0": "AECCAR0.gz", "aeccar1": "AECCAR1.gz", "aeccar2": "AECCAR2.gz", "chgcar": "CHGCAR.gz", "procar": "PROCAR.gz", "wavecar": "WAVECAR.gz" } ```
__author__ = 'Matt' try: # for Python2 from Tkinter import * except ImportError: try: # for Python3 from tkinter import * except ImportError: exit() from TopDisplay import drawWheelDisplay from RockerBogieSide import drawRockerBogie from UI.ManualControl import drawManualControl, handleDriveClick ## # A class that does high level drawing of the screen # class Application(Frame): def __init__(self, dataBox, uiData, master=None, width=1000, height=1000): Frame.__init__(self, master=master, width=width, height=height) self.dataBox = dataBox self.uiData = uiData self.canvas = Canvas(width=width, height=height) self.canvas.grid() self.canvasElements = [] self.canvasElements.append( CanvasElement(400, 0, 200, lambda c, x, y, s: drawManualControl(c, x, y, s, self.uiData), lambda event, x, y, s: handleDriveClick(event, x, y, s, self.uiData) ) ) def onClick(self, event): print event.x for c in self.canvasElements: if None != c.onClickFunc: # noinspection PyChainedComparisons if event.x > c.x and event.x < c.x+c.size and event.y > c.y and event.y < c.y+c.size: c.onClickFunc(event) return return def redraw(self): self.canvas.delete("all") drawWheelDisplay(self.canvas, 0, 0, 200, self.dataBox[0]) drawRockerBogie(self.canvas, 200, 0, 200, self.dataBox[0].leftArm, True) drawRockerBogie(self.canvas, 200, 200, 200, self.dataBox[0].rightArm, False) for c in self.canvasElements: c.draw(self.canvas) # drawManualControl(self.canvas, 400, 000, 200, self.uiData) self.after(10, self.redraw) return class CanvasElement: def __init__(self, x, y, size, drawFunc, onClickFunc=None): self.x = x self.y = y self.size = size self.drawFunc = drawFunc self.onClickFunc = onClickFunc return def draw(self, canvas): self.drawFunc(canvas, self.x, self.y, self.size) def onClick(self, event): return
<?php namespace MusicBrainz\Helper; use MusicBrainz\Definition\RelationTarget; use MusicBrainz\Definition\RelationTypeId; use MusicBrainz\Relation; use MusicBrainz\Relation\NullType; use MusicBrainz\Relation\Type; use MusicBrainz\Value\Direction; use MusicBrainz\Value\MBID; /** * The relation factory */ class RelationFactory { use \MusicBrainz\Value\Property\AreaTrait; /** * Makes and returns a relation by given information from the webservice. * * @param array $relation Information about the relation * * @return Relation */ public static function make(array $relation = []): Relation { $relationTypeId = ArrayAccess::getString($relation, 'type-id'); /** @var Type $relationType */ $relationType = self::getRelationType(new MBID($relationTypeId)); if ($relationType instanceof NullType) { /** @todo Implement fallback for undefined relation */ } $direction = new Direction(ArrayAccess::getString($relation, 'direction')); $relatedEntityType = (Direction::FORWARD == $direction) ? $relationType::getRelatedEntityType() : $relationType::getBaseEntityType(); $class = RelationTarget::getClassMap()[(string) $relatedEntityType]; if (is_null($relation[(string) $relatedEntityType])) { /** @todo Implement fallback for undefined relation */ die; } return new $class( $relation[(string) $relatedEntityType], $relationType, $direction ); } /** * Returns a relation type by its MusicBrainz Identifier (MBID). * * @param MBID $relationTypeId The MusicBrainz Identifier (MBID) of the relation type. * * @return Type */ private static function getRelationType(MBID $relationTypeId): Type { $classMap = RelationTypeId::getClassMap(); if (array_key_exists((string) $relationTypeId, $classMap)) { $relationType = RelationTypeId::getClassMap()[(string) $relationTypeId]; return new $relationType; } return new NullType; } }
# Savedata Synchronizer ## Install ``` $ git clone https://github.com/sawaken/savedatasync.git $ cd savedatasync $ rake install ``` ## Usage ``` $ sdsync -h ```
const express = require('express') import { isAuthenticated } from '../../../middlewares/auth' import { FilterUsersByRole, GetASingleUser, LoggedInUserDetails } from './user_controller' const router = express.Router() router.get('/users/current-user', isAuthenticated, LoggedInUserDetails) router.get('/users/:id', GetASingleUser) router.get('/users/filter-by-role/:userType', FilterUsersByRole) export default router
procedure Test; require True : 'Invalid string'(; begin end;
package com.moac.android.palettedemo; public enum PaletteOption { VIBRANT, VIBRANT_DARK, VIBRANT_LIGHT, MUTED, MUTED_DARK, MUTED_LIGHT }
require_relative "helpers.rb" LIBSSH2_IOS_INSTALL_PATH = File.expand_path("../External/libssh2-for-iOS/lib/libssh2.a", File.dirname(__FILE__)) LIBGIT2_IOS_INSTALL_PATH = File.expand_path("../External/libgit2-iOS/libgit2-iOS.a", File.dirname(__FILE__)) def sdk_root(arch) if %w(x86_64 i386).include? arch platform = "iphonesimulator" else platform = "iphoneos" end `xcodebuild -version -sdk 2> /dev/null | grep -i #{platform}#{sdk_version} | grep 'Path:' | awk '{ print $2 }'`.chomp end def sdk_version `xcodebuild -version -sdk 2> /dev/null | grep SDKVersion | tail -n 1 | awk '{ print $2 }'`.chomp end namespace "build" do desc "Build libssh2 and libgit2 for iOS" task :ios => ["build:ios:libssh2", "build:ios:libgit2"] namespace :ios do desc "Build OpenSSL and libssh2 for iOS" task :libssh2 do if File.exist? LIBSSH2_IOS_INSTALL_PATH puts "libssh2.a already exists at \"#{LIBSSH2_IOS_INSTALL_PATH}\"." next end run "cd External/libssh2-for-iOS && ./build-all.sh openssl" run "cd External/libssh2-for-iOS && git checkout -- . && git clean -fd" end desc "Build libgit2 for iOS" task :libgit2 do if File.exist? LIBGIT2_IOS_INSTALL_PATH puts "libgit2-iOS.a already exists at \"#{LIBGIT2_IOS_INSTALL_PATH}\"." next end root_path = `pwd`.strip xcode_path = `xcode-select --print-path`.strip %w(x86_64 i386 armv7 armv7s arm64).each do |arch| run "rm -rf External/libgit2/build" run "mkdir External/libgit2/build" install_prefix = "#{root_path}/External/libgit2-iOS/#{arch}" run "mkdir -p #{install_prefix}" run <<-command cd External/libgit2/build && \\ export IPHONEOS_DEPLOYMENT_TARGET=8.0 && \\ export SDKROOT=#{xcode_path}/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator#{sdk_version}.sdk && \\ /usr/local/bin/cmake \\ -DCMAKE_C_COMPILER=clang \\ -DCMAKE_C_COMPILER_WORKS:BOOL=ON \\ -DBUILD_SHARED_LIBS:BOOL=OFF \\ -DOPENSSL_INCLUDE_DIR:PATH=#{root_path}/External/libssh2-for-iOS/include/ \\ -DCMAKE_LIBRARY_PATH:PATH=#{root_path}/External/libssh2-for-iOS/lib/ \\ -DCMAKE_INCLUDE_PATH:PATH=#{root_path}/External/libssh2-for-iOS/include/libssh2/ \\ -DOPENSSL_SSL_LIBRARY:FILEPATH=#{root_path}/External/libssh2-for-iOS/lib/libssl.a \\ -DCMAKE_LIBRARY_PATH:PATH="#{sdk_root(arch)}/usr/lib/" \\ -DOPENSSL_CRYPTO_LIBRARY:FILEPATH=#{root_path}/External/libssh2-for-iOS/lib/libcrypto.a \\ -DCMAKE_INSTALL_PREFIX:PATH="#{install_prefix}" \\ -DBUILD_CLAR:BOOL=OFF \\ -DTHREADSAFE:BOOL=ON \\ #{"-DCMAKE_OSX_SYSROOT=#{sdk_root(arch)}" unless %w(x86_64 i386).include? arch} \\ -DCMAKE_OSX_ARCHITECTURES:STRING="#{arch}" \\ .. command run "cd External/libgit2/build && cmake --build . --target install" end run <<-command lipo -create \\ External/libgit2-iOS/x86_64/lib/libgit2.a \\ External/libgit2-iOS/i386/lib/libgit2.a \\ External/libgit2-iOS/armv7/lib/libgit2.a \\ External/libgit2-iOS/armv7s/lib/libgit2.a \\ External/libgit2-iOS/arm64/lib/libgit2.a \\ -output External/libgit2-iOS/libgit2-iOS.a command end end end
''' Python module for Mopidy Pummeluff shutdown tag. ''' __all__ = ( 'Shutdown', ) from logging import getLogger from os import system from .base import Action LOGGER = getLogger(__name__) class Shutdown(Action): ''' Shutting down the system. ''' @classmethod def execute(cls, core): ''' Shutdown. :param mopidy.core.Core core: The mopidy core instance ''' LOGGER.info('Shutting down') system('sudo /sbin/shutdown -h now')
namespace AP.MobileToolkit.Fonts.Controls { public interface IIconSpan { string GlyphName { get; } } }
import java.util.*; public class FormulaOrtoedro { public static void main(String args[]) { Scanner teclado = new Scanner(System.in); float b, h, a, vol; System.out.print("Ingrese la base: "); b = teclado.nextFloat(); System.out.print("\nIngrese la altura: "); h = teclado.nextFloat(); System.out.println("\nIngrese el ancho: "); a = teclado.nextFloat(); vol = b * h * a; System.out.print("\n\n El volumen es: "+vol); } }
extern crate futures; extern crate tokio; extern crate trust_dns_proto; extern crate trust_dns_server; use std::io; use std::time::Duration; use futures::{Async, Poll}; #[allow(deprecated)] use futures::stream::{iter, Stream}; use tokio::runtime::current_thread::Runtime; use trust_dns_server::server::TimeoutStream; #[test] fn test_no_timeout() { #[allow(deprecated)] let sequence = iter(vec![Ok(1), Err("error"), Ok(2)]).map_err(|e| io::Error::new(io::ErrorKind::Other, e)); let mut core = Runtime::new().expect("could not get core"); let timeout_stream = TimeoutStream::new(sequence, Duration::from_secs(360)); let (val, timeout_stream) = core.block_on(timeout_stream.into_future()) .ok() .expect("first run failed"); assert_eq!(val, Some(1)); let error = core.block_on(timeout_stream.into_future()); assert!(error.is_err()); let (_, timeout_stream) = error.err().unwrap(); let (val, timeout_stream) = core.block_on(timeout_stream.into_future()) .ok() .expect("third run failed"); assert_eq!(val, Some(2)); let (val, _) = core.block_on(timeout_stream.into_future()) .ok() .expect("fourth run failed"); assert!(val.is_none()) } struct NeverStream {} impl Stream for NeverStream { type Item = (); type Error = io::Error; // somehow insert a timeout here... fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { Ok(Async::NotReady) } } #[test] fn test_timeout() { let mut core = Runtime::new().expect("could not get core"); let timeout_stream = TimeoutStream::new(NeverStream {}, Duration::from_millis(1)); assert!(core.block_on(timeout_stream.into_future()).is_err()); }
# Convert TECS style assembly code, to Hack2 assembly ''' @# @label // will need a pass to translate labels to constants... dst = cmp ; jmp (label) ''' ''' A -> r1 D -> r2 ''' # Assumes program only 32k? # Assumes no whitespace in TECS instruction, and # code is compliant (ex valid integers) regs = { 'rA' : 'r1', 'rD' : 'r2', 'rT' : 'r3', # r4 reserved } compLookup = { '0' : [ 'MOV {} r0' ], '1' : [ 'MOV {} r0 1' ], '-1' : [ 'NEG {} r0 1' ], # --- 'D' : [ 'MOV {} rD' ], 'A' : [ 'MOV {} rA' ], # --- '!D' : [ 'NOT {} rD' ], '!A' : [ 'NOT {} rA' ], # --- '-D' : [ 'NEG {} rD' ], '-A' : [ 'NEG {} rA' ], # --- 'D+1' : [ 'MOV {} rD', 'ADD {} r0 1' ], 'A+1' : [ 'MOV {} rA', 'ADD {} r0 1' ], 'D-1' : [ 'MOV {} rD', 'SUB {} r0 1' ], 'A-1' : [ 'MOV {} rA', 'SUB {} r0 1' ], # --- 'D+A' : [ 'MOV {} rD', 'ADD {} rA' ], 'A+D' : None, # order doesn't matter 'D-A' : [ 'MOV {} rD', 'SUB {} rA' ], 'A-D' : [ 'MOV {} rA', 'SUB {} rD' ], 'D&A' : [ 'MOV {} rD', 'AND {} rA' ], 'A&D' : None, # order doesn't matter 'D|A' : [ 'MOV {} rD', 'OR {} rA' ], 'A|D' : None, # order doesn't matter # --- 'M' : [ 'LD {} rA', ], # --- '!M' : [ 'LD {} rA', 'NOT {} {}' ], '-M' : [ 'LD {} rA', 'NEG {} {}' ], # --- 'M+1' : [ 'LD {} rA', 'ADD {} r0 1' ], 'M-1' : [ 'LD {} rA', 'SUB {} r0 1' ], # --- 'D+M' : [ 'LD {} rA', 'ADD {} rD' ], 'M+D' : None, # order doesn't matter 'D-M' : [ 'LD rT rA', 'MOV {} rD', 'SUB {} rT' ], 'M-D' : [ 'LD {} rA', 'SUB {} rD' ], 'D&M' : [ 'LD {} rA', 'AND {} rD' ], 'M&D' : None, # order doesn't matter 'D|M' : [ 'LD {} rA', 'OR {} rD' ], 'M|D' : None, # order doesn't matter } # order doesn't matter compLookup[ 'A+D' ] = compLookup[ 'D+A' ] compLookup[ 'A&D' ] = compLookup[ 'D&A' ] compLookup[ 'A|D' ] = compLookup[ 'D|A' ] compLookup[ 'M+D' ] = compLookup[ 'D+M' ] compLookup[ 'M&D' ] = compLookup[ 'D&M' ] compLookup[ 'M|D' ] = compLookup[ 'D|M' ] jumpLookup = { 'NULL' : [], 'JMP' : [ 'JMP r0 rA' ] 'JEQ' : [ # 'MOV rT {}' # 'SUB rT r0' # 'JZ r0 rA' JEQ( {}, rA ) # <-- TODO: use macros ], 'JNE' : [ 'MOV rT {}' 'SUB rT r0' 'JNZ r0 rA' ], # stackoverflow.com/a/36909033 'JGT' : [ # JC 'MOV rT {}' 'SUB rT r0' 'JC r0 rA' ], 'JLT' : [ # NC & NZ 'MOV rT {}' 'SUB rT r0' 'MOV rT rStatus' # TODO, support 'AND rT r0 0b0000000000000110' # TODO, support 'JZ r0 rA' ], 'JGE' : [ # C | ZR 'MOV rT {}' 'SUB rT r0' 'JC r0 rA' 'JZ r0 rA' ], 'JLE' : [ # NC 'MOV rT {}' 'SUB rT r0' 'JNC r0 rA' ], } def aType ( inst ) new_inst = [] x = int( inst[ 1 : ] ) i0 = 'MOV {} r0 {}'.format( regs[ 'A' ], x ) new_inst.append( i0 ) return new_inst def translateComp ( comp, dest, destIsDirect ): new_inst = compLookup[ comp ] # Replace rA/rD/rT with appropriate register # Note, assuming instructions in uppercase thus won't collide in search/replace for curName, newName in regs: for i in range( len( new_inst ) ): new_inst[ i ] = new_inst[ i ].replace( curName, newName ) # Place r4/rDst if destIsDirect: new_inst[ i ] = new_inst[ i ].replace( '{}', dest ) else: new_inst[ i ] = new_inst[ i ].replace( '{}', 'r4' ) return new_inst def cType ( inst ) # Decode dest, comp, jump = [ None ] * 3 if '=' in inst and ';' in inst: dest, comp, jump = re.split( '=|;', inst ) elif '=' in inst: dest, comp = re.split( '=', inst ) elif ';' in inst: comp, jump = re.split( ';', inst ) # Convert comp destIsDirect = dest and dest in 'AD' new_inst = translateComp( comp, dest, destIsDirect ) # Convert rest of instruction # dst = cmp if dest and comp and ( not jump ): if not destIsDirect: # M i0 = 'STO r4 {}'.format( regs[ 'A' ] ) new_inst.append( i0 ) # cmp ; jmp elif ( not dest ) and comp and jump: # i0 = '{} r0 {}'.format( jump, regs[ 'A' ] ) ... jumpLookup # Replace rA/rD/rT with appropriate register # Place r4/rDst new_inst.append( i0 ) # dst = cmp ; jmp elif dest and comp and jump: # else: raise Exception( 'Error: unkown instruction {}'.format( instr ) )
/************************** INCLUDE APPLICATION SECTION *****************************/ #include "extern.h" #include "protocol.h" // Definizione dei protocolli utilizzati int (* dammi_protocollo(int ))(int, unsigned char *, int, int); void SendPollCmd(int,int,int ) ; void InitChannel(int); void InitConnection(int,struct connectManage *); /************************** FUNCTION DEVELOP SECTION *****************/ int (* dammi_protocollo(int protocollo))() { int (*Interprete)(); switch(protocollo){ case WEBSOCKET: Interprete = WebSocket ; break; case ISO2110: Interprete = SPIso2110 ; break; case ISO2110S: Interprete = SPIso2110S ; break; } return(Interprete); } /************************** FUNCTION DEVELOP SECTION *****************/ /*---------------------------------------------* * Inizializzazione dispositivi dell'impianto * *---------------------------------------------*/ void InitChannel(int id_act) { printf("Init Channel %d = %s\n",id_act,protocol_name[ptr[id_act]->proto_client]); // * In base al protocollo invio il comando di polling relativo * switch(ptr[id_act]->proto_client){ case WEBSOCKET: Init_WebSocket(id_act) ; break; case ISO2110: Init_SPIso2110(id_act) ; break; case ISO2110S: Init_SPIso2110S(id_act) ; break; } } /*---------------------------------------------* * Inizializzazione dispositivi dell'impianto * *---------------------------------------------*/ void InitAreeChannel(int id_act) { printf("Init Aree Channel %d = %s\n",id_act,protocol_name[ptr[id_act]->proto_client]); switch(ptr[id_act]->proto_client){ case WEBSOCKET: InitAree_WebSocket(id_act) ; break; case ISO2110: InitAree_SPIso2110(id_act) ; break; case ISO2110S: InitAree_SPIso2110S(id_act) ; break; } } /*---------------------------------------------* * Inizializzazione dispositivi dell'impianto * *---------------------------------------------*/ void InitConnection(int id_act,struct connectManage * tcpConnect) { printf("Init Connection %d = %s\n",id_act,protocol_name[ptr[id_act]->proto_client]); switch(ptr[id_act]->proto_client){ case WEBSOCKET: Connect_WebSocket(tcpConnect) ; break; case ISO2110: Connect_SPIso2110(tcpConnect) ; break; case ISO2110S: Connect_SPIso2110S(tcpConnect) ; break; } } /* * ************************* Polling sui comandi da inviare ai dispositivi **************** * @param canale, num di connessione del canale, comando da inviare * @return niente */ void SendPollCmd(int linea,int id_act,int opt) { /* In base al protocollo invio il comando di polling relativo */ switch(ptr[id_act]->proto_client){ case WEBSOCKET: SendPoll_WebSocket(linea,id_act,opt); break; case ISO2110: SendPoll_SPIso2110(linea,id_act,opt); break; case ISO2110S: // Non ha polling questo protocollo bisogna mettere a 0 il tempo di polling in taraura break; } } int dammi_canale(int protocollo) { int kk; for(kk = 0 ; kk< act_client ; kk ++ ){ if (ptr[kk]->proto_client == protocollo ) return(kk); } return (-1); }
{-# LANGUAGE GADTs, TypeOperators #-} module SessionCheck.Spec where import Control.Monad import Control.DeepSeq import SessionCheck.Classes import SessionCheck.Predicate -- Specifications of protocols data Spec t a where Get :: (a :< t, NFData a) => Predicate a -> Spec t a Send :: (a :< t, NFData a) => Predicate a -> Spec t a Async :: Spec t a -> Spec t () Stop :: Spec t a Fail :: String -> Spec t a -- Monadic fragment Return :: a -> Spec t a Bind :: Spec t a -> (a -> Spec t b) -> Spec t b -- Monads, Gonads, Applicatives, Functors and all that... instance Monad (Spec t) where return = Return (>>=) = Bind fail = Fail instance Applicative (Spec t) where pure = Return (<*>) = ap instance Functor (Spec t) where fmap = liftM -- Recevie a value which satisfies a predicate get :: (a :< t, NFData a) => Predicate a -> Spec t a get = Get -- Send a value which satisfies a predicate send :: (a :< t, NFData a) => Predicate a -> Spec t a send = Send -- Run a protocol "in parallel" on the same channel async :: Spec t a -> Spec t () async = Async -- Terminate a session (or a sub-session generated by `interleave`) stop :: Spec t a stop = Stop -- The dual of a specification, `dual . dual = id` dual :: Spec t a -> Spec t a dual s = case s of Get p -> Send p Send p -> Get p Async s -> Async (dual s) Stop -> Stop Return a -> Return a Bind s f -> Bind (dual s) (dual . f) -- Representation of threads which hide the intermediate types data Thread t where Hide :: Spec t a -> (a -> Spec t b) -> Thread t -- Simply hide a Spec hide :: Spec t a -> Thread t hide s = Hide s (\_-> Stop) ------- Derived combinators for constructing specifications ------- -- Make a choice of one of the elements in the list choose :: (Eq a, Show a, a :< b, NFData a) => [a] -> Spec b a choose = send . choiceOf -- The other party makes a choice of one of the elements in the list branch :: (Eq a, Show a, a :< b, NFData a) => [a] -> Spec b a branch = dual . choose
Get-Module -Name pstrami | Remove-Module $fullPathIncFileName = $MyInvocation.MyCommand.Definition $currentScriptName = $MyInvocation.MyCommand.Name $currentExecutingPath = $fullPathIncFileName.Replace("\$currentScriptName", "") Import-Module (resolve-path "$currentExecutingPath\..\pstrami\pstrami.psm1") Function Test.Can_load_config_file() { #Arrange #Act Load-Configuration "$currentExecutingPath\..\pstrami\pstrami.config.ps1" $Actual = Get-Environments #NOTE: This only works if there are environments defined #Assert if($Actual -eq $null) { throw ("environment did not load") } } Test.Can_load_config_file
#!/bin/sh for filename in `ls *.out` do sed -e 's/\/[A-Za-z0-9][A-Za-z0-9]*\/vstree\/src\/vstree\/src\/doc\///' $filename > .tmp mv .tmp $filename done
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Messaging.Resource; interface uses System.SysUtils, System.Classes, WiRL.Core.JSON, WiRL.Core.Attributes, WiRL.Core.Auth.Context, WiRL.http.Accept.MediaType, WiRL.Messaging.Message, WiRL.Messaging.Queue; type TWiRLMessagingResourceForToken<T: TWiRLCustomMessage, constructor> = class private protected [Context] Token: TWiRLAuthContext; public [Path('listen'), GET] [Produces(TMediaType.APPLICATION_JSON)] procedure Subscribe; [Path('myqueue'), GET] [Produces(TMediaType.APPLICATION_JSON)] function Consume: TJSONObject; end; implementation uses System.Generics.Collections; { TWiRLMessagingResourceForToken<T> } function TWiRLMessagingResourceForToken<T>.Consume: TJSONObject; var LCount: Integer; LArrayMessaggi: TJSONArray; begin LCount := -1; LArrayMessaggi := TJSONArray.Create; try TWiRLMessagingQueueForToken.Use<T>(Token, procedure (AQueue: TQueue<T>) var LMessage: T; begin LCount := AQueue.Count; while AQueue.Count > 0 do begin LMessage := AQueue.Dequeue; try LArrayMessaggi.Add(LMessage.ToJSON); finally LMessage.Free; end; end; end ); Result := TJSONObject.Create; try Result.AddPair('Count', TJSONNumber.Create(LCount)); Result.AddPair('Messages', LArrayMessaggi); except Result.Free; raise; end; except LArrayMessaggi.Free; raise; end; end; procedure TWiRLMessagingResourceForToken<T>.Subscribe; begin TWiRLMessagingQueueForToken.Create<T>(Token); end; end.
import markdown from django import forms from django.db import models from django.conf import settings from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS from sakkada.admin.editors.markdown import MarkdownTextInput, MarkdownTextarea MARKDOWN_INIT_KWARGS = { 'extensions': [], 'extension_configs': {}, 'output_format': "html", 'tab_length': 2, **getattr(settings, 'MARKDOWN_INIT_KWARGS', {}) } MARKDOWN_HELP_TEXT = ( '<a target="_blank" href="https://en.wikipedia.org/wiki/Markdown">' 'Wikipedia</a>' ' | ' '<a target="_blank" href="https://www.markdownguide.org/">' 'Guide</a>' ' | ' '<a target="_blank" href="https://daringfireball.net/projects/markdown/">' 'Documentation</a>' ' | ' '<a target="_blank" href="https://marked.js.org/demo/">' 'Demo</a>' ) class MarkdownStringValue(str): """Markdown string value container.""" def markdown(self): return markdown.markdown(self, **MARKDOWN_INIT_KWARGS) class MarkdownCharFormField(forms.CharField): """Markdown form CharField.""" markdown_value_class = MarkdownStringValue def __init__(self, *args, **kwargs): self.markdown_value_class = kwargs.pop('value_class', self.markdown_value_class) super().__init__(**kwargs) def to_python(self, value): value = super().to_python(value) return (self.markdown_value_class(value) if isinstance(value, str) else value) class MarkdownAttribute(models.fields.DeferredAttribute): def __set__(self, obj, value): obj.__dict__[self.field.attname] = self.field.to_python(value) class BaseMarkdownModelField: markdown_value_class = MarkdownStringValue markdown_form_class = MarkdownCharFormField markdown_cache_field = None def __init__(self, *args, **kwargs): self.markdown_cache_field = kwargs.pop('cache_field', None) self.markdown_value_class = kwargs.pop('value_class', self.markdown_value_class) super().__init__(*args, **kwargs) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, MarkdownAttribute(self)) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.markdown_cache_field: kwargs['cache_field'] = self.markdown_cache_field if self.markdown_value_class is not MarkdownStringValue: kwargs['value_class'] = self.markdown_value_class return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value return self.markdown_value_class(value) def to_python(self, value): if isinstance(value, MarkdownStringValue) or value is None: return value return self.markdown_value_class(value) def pre_save(self, instance, add): value = getattr(instance, self.name, None) if self.markdown_cache_field and value: setattr(instance, self.markdown_cache_field, value.markdown()) return super().pre_save(instance, add) def formfield(self, **kwargs): return super().formfield(**{ 'form_class': self.markdown_form_class, 'value_class': self.markdown_value_class, **kwargs, }) class MarkdownCharField(BaseMarkdownModelField, models.CharField): pass class MarkdownTextField(BaseMarkdownModelField, models.TextField): pass # Register fields to use custom widgets in the Admin FORMFIELD_FOR_DBFIELD_DEFAULTS.update({ MarkdownCharField: {'widget': MarkdownTextInput,}, MarkdownTextField: {'widget': MarkdownTextarea,}, })
<?php class Detail extends CI_Controller{ public function __construct(){ parent::__construct(); $this->load->model('detail_model'); $this->load->helper('url_helper'); } public function get_urls(){ $slug = $this->uri->segment(3, 0); $data['name'] = urldecode($this->uri->segment(4, 0)); $data['urls'] = $this->detail_model->get_urls($slug); $this->load->view('detail', $data); } } ?>
class Controller def initialize() @style = "" @page_title = "" @title = "" @foot = "" @menu = "" end def main() @menu += $usr.get_logout_form() html = "Controller.main()" return html end def output(html) wk = { "style" => @style, "page_title" => @page_title, "title" => @title, "menu" => @menu, "cont" => html, "foot" => @foot } html = load_template(wk, "page.html") puts html end def index() if $usr.is_login() then html = main() else html = $usr.get_login_form() @title = "ログイン" end output(html) end def make_menu_form(name, caption) html = <<EOF <div onClick="document.#{name}.submit();"> <form method="post" name="#{name}"> <input type="hidden" name="mode" value="#{name}" /> <p onMouseOver="this.style.color='red';" onMouseOut="this.style.color='white';" onClick="this.style.color='white';" >#{caption}</p> </form> </div> EOF return html end end
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VierGewinnt.Utils.Logger { public class MessageLoggedEventArgs { /// <summary> /// Type of the Logged Message /// </summary> public LogLevel Type { get; set; } /// <summary> /// Namespace of the Logged Message /// </summary> public string Namespace { get; set; } /// <summary> /// Message of the Logged Text /// </summary> public string Message { get; set; } /// <summary> /// Event Args of Logger Events /// </summary> /// <param name="Type">Type of the Logged Message</param> /// <param name="Namespace">Namespace of the Logged Message</param> /// <param name="Message">Message of the Logged Text</param> public MessageLoggedEventArgs(LogLevel Type, string Namespace, string Message) { this.Type = Type; this.Namespace = Namespace; this.Message = Message; } } }
package com.example.skillshop.LoginActivities; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import com.example.skillshop.NavigationFragments.FragmentHandler; import com.example.skillshop.R; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.Profile; import com.facebook.ProfileTracker; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.firebase.iid.FirebaseInstanceId; import com.parse.LogInCallback; import com.parse.ParseException; import com.parse.ParseUser; import org.json.JSONException; import org.json.JSONObject; public class LoginActivity extends AppCompatActivity { public static String userId; public static String userName; ProfileTracker mProfileTracker; LoginButton fbLoginButton; TextView welcomeMessage; CallbackManager callbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ParseUser currentUser = ParseUser.getCurrentUser(); FacebookSdk.sdkInitialize(getApplicationContext()); if (currentUser != null) { // continue to next activity if user previously logged in and user has submitted location Intent i = new Intent(LoginActivity.this, FragmentHandler.class); startActivity(i); finish(); } else if (currentUser == null && Profile.getCurrentProfile() != null) { // if user has closed app during signing up without logging out, app will resume at SignupActivity Intent i = new Intent(LoginActivity.this, SignupActivity.class); startActivity(i); } else { setContentView(R.layout.activity_login); fbLoginButton = (LoginButton) findViewById(R.id.login_button); welcomeMessage = findViewById(R.id.welcomeMessage); callbackManager = CallbackManager.Factory.create(); checkLoginStatus(); Log.i("LoginActivity", "Reached here above"); FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { if (Profile.getCurrentProfile() == null) { mProfileTracker = new ProfileTracker() { @Override protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) { nextActivity(currentProfile); Log.i("LoginActivity", "Reached here"); mProfileTracker.stopTracking(); } }; } else { Profile profile = Profile.getCurrentProfile(); nextActivity(profile); Log.v("facebook - profile", profile.getFirstName()); } } @Override public void onCancel() { setResult(RESULT_CANCELED); } @Override public void onError(FacebookException error) { } }; fbLoginButton.registerCallback(callbackManager, callback); } } private void login(String username, String password) { Log.i("LoginActivity", "Reached login method"); ParseUser.logInInBackground(username, password, new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if (e == null) { Log.d("LoginActivity", "Login successful"); final Intent intent = new Intent(LoginActivity.this, FragmentHandler.class); Log.i("LoginActivity", "Reached login success"); startActivity(intent); finish(); } else { Log.e("LoginActivity", "Login failure"); e.printStackTrace(); // continues to sign up activity if does not recognize facebook user Intent main = new Intent(LoginActivity.this, SignupActivity.class); startActivity(main); finish(); } } }); } @Override protected void onActivityResult(int requestCode, int responseCode, @Nullable Intent intent) { callbackManager.onActivityResult(requestCode, responseCode, intent); super.onActivityResult(requestCode, responseCode, intent); } private void loadUserProfile(AccessToken newAccessToken) { GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { try { String first_name = object.getString("first_name"); String last_name = object.getString("last_name"); String email = object.getString("email"); String id = object.getString("id"); String image_url = "https://graph.facebook.com/" + id + "/picture?type=normal"; } catch (JSONException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "first_name,last_name,email,id"); request.setParameters(parameters); request.executeAsync(); } private void checkLoginStatus() { if (AccessToken.getCurrentAccessToken() != null) { loadUserProfile(AccessToken.getCurrentAccessToken()); } } private void nextActivity(Profile profile) { Log.i("LoginActivity", "Reached nextActivity"); if (profile != null) { userId = profile.getId(); userName = profile.getFirstName() + " " + profile.getLastName(); login(userId, userId); } Log.i("LoginActivity", "Profile is null"); } }
# Enforces a maximum depth to nested describe calls (`max-nested-describe`) While it's useful to be able to group your tests together within the same file using `describe()`, having too many levels of nesting throughout your tests make them difficult to read. ## Rule Details This rule enforces a maximum depth to nested `describe()` calls to improve code clarity in your tests. The following patterns are considered warnings (with the default option of `{ "max": 5 } `): ```js describe('foo', () => { describe('bar', () => { describe('baz', () => { describe('qux', () => { describe('quxx', () => { describe('too many', () => { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); }); }); }); }); }); describe('foo', function () { describe('bar', function () { describe('baz', function () { describe('qux', function () { describe('quxx', function () { describe('too many', function () { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); }); }); }); }); }); ``` The following patterns are **not** considered warnings (with the default option of `{ "max": 5 } `): ```js describe('foo', () => { describe('bar', () => { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); describe('qux', () => { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); }); describe('foo2', function () { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); describe('foo', function () { describe('bar', function () { describe('baz', function () { describe('qux', function () { describe('this is the limit', function () { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); }); }); }); }); ``` ## Options ```json { "jest/max-nested-describe": [ "error", { "max": 5 } ] } ``` ### `max` Enforces a maximum depth for nested `describe()`. This has a default value of `5`. Examples of patterns **not** considered warnings with options set to `{ "max": 2 }`: ```js describe('foo', () => { describe('bar', () => { it('should get something', () => { expect(getSomething()).toBe('Something'); }); }); }); describe('foo2', function () { describe('bar2', function () { it('should get something', function () { expect(getSomething()).toBe('Something'); }); it('should get else', function () { expect(getSomething()).toBe('Something'); }); }); }); ```
/** * Copyright 2015-2018 the original author or authors. * * 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 ch.rasc.bsoncodec.test.embedded; import ch.rasc.bsoncodec.annotation.BsonDocument; @BsonDocument public class Address { private String firstName; private String lastName; private String street; private String city; public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.city == null ? 0 : this.city.hashCode()); result = prime * result + (this.firstName == null ? 0 : this.firstName.hashCode()); result = prime * result + (this.lastName == null ? 0 : this.lastName.hashCode()); result = prime * result + (this.street == null ? 0 : this.street.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Address other = (Address) obj; if (this.city == null) { if (other.city != null) { return false; } } else if (!this.city.equals(other.city)) { return false; } if (this.firstName == null) { if (other.firstName != null) { return false; } } else if (!this.firstName.equals(other.firstName)) { return false; } if (this.lastName == null) { if (other.lastName != null) { return false; } } else if (!this.lastName.equals(other.lastName)) { return false; } if (this.street == null) { if (other.street != null) { return false; } } else if (!this.street.equals(other.street)) { return false; } return true; } }
class AddSightingsColumns < ActiveRecord::Migration[5.0] def change add_column :sightings, :animal_id, :integer add_column :sightings, :neighborhood, :string end end
-- depends on {{ ref('my_passing_model') }} This is invalid SQL
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : System.Taffybar.Widget.FSMonitor -- Copyright : (c) José A. Romero L. -- License : BSD3-style (see LICENSE) -- -- Maintainer : José A. Romero L. <escherdragon@gmail.com> -- Stability : unstable -- Portability : unportable -- -- Simple text widget that monitors the current usage of selected disk -- partitions by regularly parsing the output of the df command in Linux -- systems. -- ----------------------------------------------------------------------------- module System.Taffybar.Widget.FSMonitor ( fsMonitorNew ) where import Control.Monad.IO.Class import qualified GI.Gtk import System.Process ( readProcess ) import System.Taffybar.Widget.Generic.PollingLabel ( pollingLabelNew ) import qualified Data.Text as T -- | Creates a new filesystem monitor widget. It contains one 'PollingLabel' -- that displays the data returned by the df command. The usage level of all -- requested partitions is extracted in one single operation. fsMonitorNew :: MonadIO m => Double -- ^ Polling interval (in seconds, e.g. 500) -> [String] -- ^ Names of the partitions to monitor (e.g. [\"\/\", \"\/home\"]) -> m GI.Gtk.Widget fsMonitorNew interval fsList = liftIO $ do label <- pollingLabelNew interval $ showFSInfo fsList GI.Gtk.widgetShowAll label GI.Gtk.toWidget label showFSInfo :: [String] -> IO T.Text showFSInfo fsList = do fsOut <- readProcess "df" ("-kP":fsList) "" let fss = map (take 2 . reverse . words) $ drop 1 $ lines fsOut return $ T.pack $ unwords $ map ((\s -> "[" ++ s ++ "]") . unwords) fss
<?php use Illuminate\Database\Seeder; class NuevosSeeders extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //Flujo Operativo solicitud cambios al presupuesto $this->call(ControlPresupuestoFlujoOperativoSeeder::class); //Flujo Operativo solicitud cambios al presupuesto $this->call(ControlPresupuestoEstatusSeeder::class); $this->call(ControlPresupuestoTarjetasSeeder::class); $this->call(ControlPresupuestoAfectacionOrdenesPresupuestoSeeder::class); } }
mod app; use app::{cli_app::CliApp, ClaveApp, args::get_clap_app}; use std::path::PathBuf; fn main() { let args = get_clap_app().get_matches(); if let Some(file_paths) = args.values_of("files") { let file_paths: Vec<PathBuf> = file_paths.into_iter() .map(|entry| { PathBuf::from(entry) }).collect(); let mut application = CliApp::new(file_paths); application.run(); } }
package interview; import org.junit.Test; /** * Description : 字符串相关 * * @author : JunJiang * @date : 2021-10-23 16:33 */ public class StringRelatedTest { @Test public void test1() { String str = null; StringBuffer sb = new StringBuffer(); /** * StringBuffer的append()方法对于null对象的添加底层调用的是AbstractStringBuilder的appendNull()方法 appendNull方法将null进行拆分在分别添加 */ sb.append(str); System.out.println(sb); System.out.println(sb.length()); // NullPointerException // StringBuffer stringBuffer = new StringBuffer(str); // System.out.println(stringBuffer); } @Test public void test2() { String str = new String("jiang") + new String("zhang"); str.intern(); String str2 = "jiangzhang"; /** * 1.字符串连接符两端存在字符串边量,此时不会向字符串常量池中写入对应的字符串常量 * 2.对于向字符串常量池中写入一个字符串常量,在Java6及以前会在方法区(永久代实现)中的字符串常量池里创建一个字符串常量 * 在Java7及以后只会在字符串常量池中创建一个字符串常量引用指向堆空间中对应的字符串对象,即该字符串常量的地址就为堆空 * 间中对象的地址,这样做可以大大节约存储空间。至于为什么有这样的转变,是因为在Java7及以后版本,字符串常量池的存储位 * 置由方法区移至堆空间,这样字符串常量就与实例对象同在堆空间中,使得字符串常量池中存储指向字符串对象的引用变成可能。 */ // true System.out.println(str == str2); } }
/* create database */ CREATE DATABASE rga; USE rga; /* create data source tables */ -- create EmployeeRoster CREATE TABLE rga.dbo.EmployeeRoster ( User_ID int NOT NULL, Email_ID int NULL, Title int NULL, Fullname varchar(1000) NULL, Department varchar(1000) NULL, Gender varchar(100) NULL, Office int NULL, Region int NULL, Tenure_Yrs float NULL, Seniority int NULL, Salary int NULL, Currency varchar(100) NULL, Rating int NULL, Survey_Score float NULL, Promotion int NULL, Avg_Hrs float NULL, CONSTRAINT EmployeeRoster_PK PRIMARY KEY (User_ID) ) GO -- create Emails CREATE TABLE rga.dbo.Emails ( from_ID int NULL, to_ID int NULL ) GO -- create Hours CREATE TABLE rga.dbo.Hours ( [Date] datetime NULL, UserId int NULL, AdminHrs1 float NULL, AdminHrs2 float NULL, AdminHrs3 float NULL, ClientHrs1 float NULL, ClientHrs2 float NULL, ClientHrs3 float NULL, TargetClientHrs float NULL ) GO -- create Skills CREATE TABLE rga.dbo.Skills ( UserId int NULL, Fullname varchar(1000) NULL, Department varchar(1000) NULL, Gender varchar(100) NULL, [Attribute Group] varchar(1000) NULL, [Attribute Sub-Group] varchar(1000) NULL, [Attribute Type] varchar(100) NULL, [Attribute Name] varchar(1000) NULL, [Attribute Level] int NULL, [Attribute Verified] bit NULL ) GO
from abc import ABCMeta, abstractmethod from enum import Enum class LoadableTypeEnum(Enum): Achievement = "Achievement" Character = "Character" Guild = "Guild" GuildUpgrade = "GuildUpgrade" Item = "Item" ItemStat = "ItemStat" Mastery = "Mastery" MiniPet = "MiniPet" Skill = "Skill" Skin = "Skin" Title = "Title" class LoadableObjectVisitorBase(object, metaclass=ABCMeta): @abstractmethod def collect(self, obj): raise NotImplementedError() class LoadableObjectBase(object, metaclass=ABCMeta): """Base class for all GW2 API objects that can be retreived from API""" @abstractmethod def _populate_inner(self, json): raise NotImplementedError() def populate(self, json): self._populate_inner(json) class LoadableObjectContainer(): """Container for GW2 API object pending loading""" _visitors = [] def register_visitor(visitor: LoadableObjectVisitorBase): LoadableObjectContainer._visitors.append(visitor) def __init__(self, id, type: LoadableTypeEnum): self.id = id self.loadable_type = type self.object = None for visitor in LoadableObjectContainer._visitors: visitor.collect(self) @property def id(self): return self._id @id.setter def id(self, value): self._id = value @property def object(self): return self._object @object.setter def object(self, value: LoadableObjectBase): self._object = value @property def has_loaded(self): return self.object != None class LoadableObjectVisitorBase(object, metaclass=ABCMeta): @abstractmethod def collect(self, obj: LoadableObjectContainer): raise NotImplementedError()
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} -- | This is a wrapper around IO that permits SMT queries module Language.Fixpoint.Solver.Monad ( -- * Type SolveM -- * Execution , runSolverM -- * Get Binds , getBinds -- * SMT Query , filterValid , checkSat, smtEnablrmbqi -- * Debug , Stats , tickIter , stats , numIter ) where import Control.DeepSeq import GHC.Generics import Language.Fixpoint.Utils.Progress import Language.Fixpoint.Misc (groupList) import qualified Language.Fixpoint.Types.Config as C import Language.Fixpoint.Types.Config (Config, solver, linear, SMTSolver(Z3)) import qualified Language.Fixpoint.Types as F import Language.Fixpoint.Types (pprint) import qualified Language.Fixpoint.Types.Errors as E import qualified Language.Fixpoint.Smt.Theories as Thy import Language.Fixpoint.Smt.Serialize (initSMTEnv) import Language.Fixpoint.Types.PrettyPrint () import Language.Fixpoint.Smt.Interface import Language.Fixpoint.Solver.Validate -- import Language.Fixpoint.Solver.Solution import Data.Maybe (isJust, catMaybes) import Text.PrettyPrint.HughesPJ (text) import Control.Monad.State.Strict import qualified Data.HashMap.Strict as M import Control.Exception.Base (bracket) --------------------------------------------------------------------------- -- | Solver Monadic API --------------------------------------------------- --------------------------------------------------------------------------- type SolveM = StateT SolverState IO data SolverState = SS { ssCtx :: !Context -- ^ SMT Solver Context , ssBinds :: !F.BindEnv -- ^ All variables and types , ssStats :: !Stats -- ^ Solver Statistics } data Stats = Stats { numCstr :: !Int -- ^ # Horn Constraints , numIter :: !Int -- ^ # Refine Iterations , numBrkt :: !Int -- ^ # smtBracket calls (push/pop) , numChck :: !Int -- ^ # smtCheckUnsat calls , numVald :: !Int -- ^ # times SMT said RHS Valid } deriving (Show, Generic) instance NFData Stats stats0 :: F.GInfo c b -> Stats stats0 fi = Stats nCs 0 0 0 0 where nCs = M.size $ F.cm fi instance F.PTable Stats where ptable s = F.DocTable [ (text "# Constraints" , pprint (numCstr s)) , (text "# Refine Iterations" , pprint (numIter s)) , (text "# SMT Push & Pops" , pprint (numBrkt s)) , (text "# SMT Queries (Valid)" , pprint (numVald s)) , (text "# SMT Queries (Total)" , pprint (numChck s)) ] --------------------------------------------------------------------------- runSolverM :: Config -> F.GInfo c b -> Int -> SolveM a -> IO a --------------------------------------------------------------------------- runSolverM cfg fi' _ act = do bracket acquire release $ \ctx -> do res <- runStateT (declareInitEnv >> declare fi >> act) (SS ctx be $ stats0 fi) smtWrite ctx "(exit)" return $ fst res where acquire = makeContextWithSEnv lar (solver cfg) file env release = cleanupContext be = F.bs fi file = F.fileName fi -- (inFile cfg) env = F.fromListSEnv ((F.toListSEnv $ F.lits fi) ++ binds) binds = [(x, F.sr_sort t) | (_, x, t) <- F.bindEnvToList $ F.bs fi] -- only linear arithmentic when: linear flag is on or solver /= Z3 lar = linear cfg || Z3 /= solver cfg fi = fi' {F.allowHO = C.allowHO cfg} --------------------------------------------------------------------------- getBinds :: SolveM F.BindEnv --------------------------------------------------------------------------- getBinds = ssBinds <$> get --------------------------------------------------------------------------- getIter :: SolveM Int --------------------------------------------------------------------------- getIter = numIter . ssStats <$> get --------------------------------------------------------------------------- incIter, incBrkt :: SolveM () --------------------------------------------------------------------------- incIter = modifyStats $ \s -> s {numIter = 1 + numIter s} incBrkt = modifyStats $ \s -> s {numBrkt = 1 + numBrkt s} --------------------------------------------------------------------------- incChck, incVald :: Int -> SolveM () --------------------------------------------------------------------------- incChck n = modifyStats $ \s -> s {numChck = n + numChck s} incVald n = modifyStats $ \s -> s {numVald = n + numVald s} withContext :: (Context -> IO a) -> SolveM a withContext k = (lift . k) =<< getContext getContext :: SolveM Context getContext = ssCtx <$> get modifyStats :: (Stats -> Stats) -> SolveM () modifyStats f = modify $ \s -> s { ssStats = f (ssStats s) } --------------------------------------------------------------------------- -- | SMT Interface -------------------------------------------------------- --------------------------------------------------------------------------- filterValid :: F.Expr -> F.Cand a -> SolveM [a] --------------------------------------------------------------------------- filterValid p qs = do qs' <- withContext $ \me -> smtBracket me $ filterValid_ p qs me -- stats incBrkt incChck (length qs) incVald (length qs') return qs' filterValid_ :: F.Expr -> F.Cand a -> Context -> IO [a] filterValid_ p qs me = catMaybes <$> do smtAssert me p forM qs $ \(q, x) -> smtBracket me $ do smtAssert me (F.PNot q) valid <- smtCheckUnsat me return $ if valid then Just x else Nothing smtEnablrmbqi = withContext $ \me -> smtWrite me "(set-option :smt.mbqi true)" checkSat :: F.Expr -> SolveM Bool checkSat p = withContext $ \me -> smtBracket me $ smtCheckSat me p --------------------------------------------------------------------------- declare :: F.GInfo c a -> SolveM () --------------------------------------------------------------------------- declareInitEnv :: SolveM () declareInitEnv = withContext $ \me -> forM_ (F.toListSEnv initSMTEnv) $ uncurry $ smtDecl me declare fi = withContext $ \me -> do xts <- either E.die return $ declSymbols fi let ess = declLiterals fi forM_ xts $ uncurry $ smtDecl me forM_ ess $ smtDistinct me declLiterals :: F.GInfo c a -> [[F.Expr]] declLiterals fi | F.allowHO fi = [es | (_, es) <- tess ] where tess = groupList [(t, F.expr x) | (x, t) <- F.toListSEnv $ F.lits fi, not (isThy x)] isThy = isJust . Thy.smt2Symbol declLiterals fi = [es | (_, es) <- tess ] where notFun = not . F.isFunctionSortedReft . (`F.RR` F.trueReft) tess = groupList [(t, F.expr x) | (x, t) <- F.toListSEnv $ F.lits fi, notFun t] declSymbols :: F.GInfo c a -> Either E.Error [(F.Symbol, F.Sort)] declSymbols = fmap dropThy . symbolSorts where dropThy = filter (not . isThy . fst) isThy = isJust . Thy.smt2Symbol --------------------------------------------------------------------------- stats :: SolveM Stats --------------------------------------------------------------------------- stats = ssStats <$> get --------------------------------------------------------------------------- tickIter :: Bool -> SolveM Int --------------------------------------------------------------------------- tickIter newScc = progIter newScc >> incIter >> getIter progIter :: Bool -> SolveM () progIter newScc = lift $ when newScc progressTick
const form = document.getElementsByTagName('form')[0] const peso1 = form.querySelector('#peso') const altura1 = form.querySelector('#altura') const botao = form.querySelector('button') let resultado1 = form.querySelector('div') form.addEventListener('submit', check) function check(e){ e.preventDefault() let resultado = calcularImc(Number(peso1.value), Number(altura1.value)/100) if(resultado>=0 && resultado!==Infinity){ resultado1.style.backgroundColor="green" resultado1.setAttribute("ativado", "ativado") resultado1.querySelector('p').innerText=`Seu resultado foi ${resultado}` }else{ resultado1.setAttribute("ativado", "ativado") resultado1.style.backgroundColor="gold" resultado1.querySelector('p').innerText=`insira algo válido` } } function calcularImc(peso, altura){ return (peso/(altura*altura)) }
CREATE OR REPLACE FUNCTION "FIND_FAMILYFORGENUS" (genus in varchar2) return varchar2 -- Given a generic name, find the single family this genus is most frequently placed in in MCZbase -- return null if no match is found. -- -- Intended for use with lepidoptera bulkload, to find the family in order to find the -- container (room) into which to place the bulkloaded material. -- @param genus the genus for which to lookup the family. -- @return a family name or an empty string if no family is found for the genus in the taxonomy table. as type rc is ref cursor; l_str varchar2(4000); l_val varchar2(4000); l_cur rc; begin l_str := ''; open l_cur for ' select family from ( select family from taxonomy where genus = :x and family is not null group by family order by count(*) desc ) where rownum < 2 ' using genus; loop fetch l_cur into l_val; exit when l_cur%notfound; l_str := l_val; end loop; close l_cur; return l_str; end;
<?php namespace App\Modules\Admin; use App\Model\Manager\OrgManager; use Markette\Gopay; class ContactsPresenter extends SecurePresenter { public function createComponentForm() { $form = new \Nette\Application\UI\Form(); $form->addGroup(''); $form->addText('contacts', 'presenters.contacts.form.contacts'); $form->addHidden('id'); $form->addSubmit('submit', 'presenters.contacts.form.submit'); $form->onSuccess[] = [$this, 'onSuccess']; $form->setDefaults($this->row); return $form; } }
/* eslint-disable key-spacing */ import { defaultSuggestionListTheme } from '../../src/SuggestionList/theme'; export const defaultMultiSelectTheme = { checkBoxItem: 'multiselect-check-box-item', checkBoxList: 'multiselect-checkbox-list', checkBoxListFooter: 'multiselect-footer', checkBoxListHeader: 'multiselect-header', checkBoxListWrapper: 'multiselect-checkbox-list-wrapper', checkBoxSemi: 'semi', checkBoxTreeList: 'checkboxtree-list', clearIcon: 'multiselect-clear-icon', dropdownIcon: 'multiselect-dropdown-icon', dropdownIconClosed: 'closed', dropdownIconOpened: 'opened', input: 'multiselect-input', inputFocused: 'focused', inputWrapper: 'multiselect-input-wrapper', inputWrapperDisabled: 'disabled', inputWrapperFocused: 'focused', inputWrapperInvalid: 'danger', inputWrapperRequired: 'required', loadingIcon: 'multiselect-loading-icon', placeholder: 'multiselect-placeholder', selectAll: 'select-all', tagsContainer: 'multiselect-tags-container', tagsUnion: 'multiselect-tags-union', wrapper: 'multiselect-wrapper', /** SuggestionList theme */ ...defaultSuggestionListTheme, };
; ModuleID = 'test' source_filename = "test" define void @foobar() { entry: %0 = alloca i32 store i32 1, i32* %0 ret i32* %0 }
<?php $db['db_host']='127.0.0.1'; $db['db_user']='root'; $db['db_pass']=''; $db['db_name']='test'; foreach($db as $key => $value) { define(strtoupper($key),$value); } $con=mysqli_connect(DB_HOST,DB_USER,DB_PASS); mysqli_select_db($con,DB_NAME); ?>
package cz.begera.bitcoin_price_chart.bitcoin_price.data import io.reactivex.functions.Function import javax.inject.Inject /** * Created by Jakub Begera (jakub@begera.cz) on 07/04/2019. */ class BlockchainChartMapper @Inject constructor() : Function<Pair<Timespan, BlockchainChartRaw>, BlockchainChart> { override fun apply(raw: Pair<Timespan, BlockchainChartRaw>): BlockchainChart { return BlockchainChart( raw.first.key, raw.second.unit, raw.second.values.map { ChartValue( it.x, it.y ) } ) } }
/* * Licensed by the author of Time4J-project. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. The copyright owner * licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.time4j.engine; import net.time4j.base.UnixTime; import java.io.Serializable; import java.util.Locale; /** * <p>Abstract base implementation of a chronological element which has * a name and can also define an (unregistered) element rule. </p> * * @param <V> generic type of element values * @author Meno Hochschild */ /*[deutsch] * <p>Abstrakte Basisimplementierung eines chronologischen Elements, das * einen Namen hat und bei Bedarf auch eigene Regeln definieren kann. </p> * * @param <V> generic type of element values * @author Meno Hochschild */ public abstract class BasicElement<V extends Comparable<V>> implements ChronoElement<V>, Serializable { //~ Instanzvariablen -------------------------------------------------- /** * @serial name of this element */ /*[deutsch] * @serial Elementname */ private final String name; /** * @serial identity code */ /*[deutsch] * @serial Identit&auml;tscode */ private final int identity; /** * @serial hash code */ /*[deutsch] * @serial Hash-Code */ private final int hash; //~ Konstruktoren ----------------------------------------------------- /** * <p>Called by subclasses which will usually assign an instance to * a static constant (creating a singleton). </p> * * @param name name of element * @throws IllegalArgumentException if the name is empty or only * contains <i>white space</i> (spaces, tabs etc.) * @see ChronoElement#name() */ /*[deutsch] * <p>Konstruktor f&uuml;r Subklassen, die eine so erzeugte Instanz * in der Regel statischen Konstanten zuweisen und damit Singletons * erzeugen k&ouml;nnen. </p> * * @param name name of element * @throws IllegalArgumentException if the name is empty or only * contains <i>white space</i> (spaces, tabs etc.) * @see ChronoElement#name() */ protected BasicElement(String name) { super(); if (name.trim().isEmpty()) { throw new IllegalArgumentException( "Element name is empty or contains only white space."); } this.name = name; this.hash = name.hashCode(); this.identity = (this.isSingleton() ? ((this.hash == -1) ? ~this.hash : this.hash) : -1); } //~ Methoden ---------------------------------------------------------- @Override public final String name() { return this.name; } @Override public String getDisplayName(Locale language) { return this.name; } /** * <p>Compares the values of this element based on their natural order. </p> * * @throws ChronoException if this element is not registered in any entity * and/or if no element rule exists to extract the element value * @since 3.5/4.3 */ /*[deutsch] * <p>Vergleicht die Werte dieses Elements auf Basis ihrer * nat&uuml;rlichen Ordnung. </p> * * @throws ChronoException if this element is not registered in any entity * and/or if no element rule exists to extract the element value * @since 3.5/4.3 */ @Override public int compare( ChronoDisplay o1, ChronoDisplay o2 ) { return o1.get(this).compareTo(o2.get(this)); } /** * <p>There is no format symbol by default. </p> * * <p>In order to define a format symbol subclasses must override this * methode. In that case such an element instance should be annotated * with the annotation {@code FormattableElement} for documentation * support. </p> * * @return ASCII-0 (placeholder for an undefined format symbol) * @see FormattableElement */ /*[deutsch] * <p>Standardm&auml;&szlig;ig gibt es kein Formatsymbol. </p> * * <p>Um ein Formatsymbol zu definieren, m&uuml;ssen Subklassen diese * Methode geeignet &uuml;berschreiben. Gleichzeitig sollte eine solche * Elementinstanz mittels der Annotation {@code FormattableElement} * das Symbol dokumentieren. </p> * * @return ASCII-0 (placeholder for an undefined format symbol) * @see FormattableElement */ @Override public char getSymbol() { return '\u0000'; } /** * <p>Chronological elements are strict by default. </p> * * @return {@code false} */ /*[deutsch] * <p>Chronologische Elemente verhalten sich standardm&auml;&szlig;ig * strikt und nicht nachsichtig. </p> * * @return {@code false} */ @Override public boolean isLenient() { return false; } /** * <p>Elements are local by default and can therefore not be used * in a global context. </p> * * @return {@code true} * @since 2.0 * @see #getVeto(Chronology) */ /*[deutsch] * <p>Elemente sind normalerweise lokal und k&ouml;nnen deshalb nicht * in einem globalen Kontext verwendet werden. </p> * * @return {@code true} * @since 2.0 * @see #getVeto(Chronology) */ public boolean isLocal() { return true; } /** * <p>Based on equality of element names AND element classes. </p> * * @return {@code true} if this instance and the argument are of same * class and have same names else {@code false} */ /*[deutsch] * <p>Basiert auf der Gleichheit der Elementnamen UND Elementklassen. </p> * * @return {@code true} if this instance and the argument are of same * class and have same names else {@code false} */ @Override public final boolean equals(Object obj) { if (this == obj) { return true; } else if (obj == null) { return false; } else if (this.getClass() == obj.getClass()) { BasicElement<?> that = (BasicElement<?>) obj; int id1 = this.identity; int id2 = that.identity; return ((id1 == id2) && ((id1 != -1) || (this.name().equals(that.name()) && this.doEquals(that)))); } else { return false; } } /** * <p>Based on the element name. </p> * * @return int */ /*[deutsch] * <p>Basiert auf dem Elementnamen. </p> * * @return int */ @Override public final int hashCode() { return this.hash; } /** * <p>Serves mainly for debugging support. </p> * * <p>For display purpose the method {@link #name()} is to be * preferred. </p> * * @return String */ /*[deutsch] * <p>Dient vornehmlich der Debugging-Unterst&uuml;tzung. </p> * * <p>F&uuml;r Anzeigezwecke sollte die Methode {@link #name()} * verwendet werden. </p> * * @return String */ @Override public String toString() { String className = this.getClass().getName(); StringBuilder sb = new StringBuilder(className.length() + 32); sb.append(className); sb.append('@'); sb.append(this.name); return sb.toString(); } /** * <p>Derives an optional element rule for given chronology. </p> * * <p>Note: This implementation yields {@code null}. Subclasses whose * element instances are not registered in a given chronology must * override this method returning a suitable element rule. </p> * * @param <T> generic type of chronology * @param chronology chronology an element rule is searched for * @return element rule or {@code null} if given chronology is unsupported */ /*[deutsch] * <p>Leitet eine optionale Elementregel f&uuml;r die angegebene * Chronologie ab. </p> * * <p>Hinweis: Diese Implementierung liefert {@code null}. Subklassen, * deren Elementinstanzen nicht in einer Chronologie registriert sind, * m&uuml;ssen die Methode geeignet &uuml;berschreiben. </p> * * @param <T> generic type of chronology * @param chronology chronology an element rule is searched for * @return element rule or {@code null} if given chronology is unsupported */ protected <T extends ChronoEntity<T>> ElementRule<T, V> derive(Chronology<T> chronology) { return null; } /** * <p>Points to another element which can have a base unit in a given * chronology. </p> * * <p>This method can be overridden by unregistered extension elements * in order to help a chronology to see which base unit belongs to * this element. </p> * * @return parent element registered on a time axis for helping * retrieving a base unit for this element or {@code null} * @see TimeAxis#getBaseUnit(ChronoElement) */ /*[deutsch] * <p>Verweist auf ein anderes Element, das eine Basiseinheit in einer * Chronologie haben kann. </p> * * <p>Diese Methode kann von nicht-registrierten Erweiterungselementen * &uuml;berschrieben werden, um einer Chronologie zu helfen, welche * Basiseinheit mit diesem Element zu verkn&uuml;pfen ist. </p> * * @return parent element registered on a time axis for helping * retrieving a base unit for this element or {@code null} * @see TimeAxis#getBaseUnit(ChronoElement) */ protected ChronoElement<?> getParent() { return null; } /** * <p>If this element is not registered in given chronology then this method * will be called by Time4J in order to generate a suitable error message * in cases where this element shall not support the chronological context. </p> * * <p>This implementation yields {@code null} to indicate that there is no * veto against usage in given chronology unless this element is local but * the given chronology is global. </p> * * @param chronology chronological context * @return error message as veto or {@code null} * @since 2.0 */ /*[deutsch] * <p>Falls dieses Element in der angegebenen Chronologie nicht registriert * ist, wird diese Methode aufgerufen, um eine passende Veto-Fehlermeldung * zu generieren, wenn dieses Element nicht den Kontext unterst&uuml;tzen * soll. </p> * * <p>Diese Implementierung liefert {@code null}, um anzuzeigen, da&szlig; * per Standard kein Veto gegen den Gebrauch dieses Elements in der * angegebenen Chronologie eingelegt wird, es sei denn, dieses Element * ist lokal und die angegebene Chronologie global. </p> * * @param chronology chronologischer Kontext * @return Fehlermeldung als Veto oder {@code null} * @since 2.0 */ protected String getVeto(Chronology<?> chronology) { if ( this.isLocal() && UnixTime.class.isAssignableFrom(chronology.getChronoType()) ) { return "Accessing the local element [" + this.name + "] from a global type requires a timezone.\n" + "- Try to apply a zonal query like \"" + this.name + ".atUTC()\".\n" + "- Or try to first convert the global type to " + "a zonal timestamp: " + "\"moment.toZonalTimestamp(...)\".\n" + "- If used in formatting then consider " + "\"ChronoFormatter.withTimezone(TZID)\"."; } return null; } /** * <p>Determines if this element only exists one time as constant in the JVM. </p> * * <p>Any override of this method MUST NOT refer directly or indirectly to any state of this object * because it is called during construction of this object at a time where this instance might not * yet be finished. </p> * * @return boolean (default value is {@code false}) * @since 3.15/4.12 */ /*[deutsch] * <p>Bestimmt, ob dieses Element nur einmal als Konstante in der JVM vorhanden ist. </p> * * <p>Jedes &Uuml;berschreiben dieser Methode darf sich NICHT direkt oder indirekt auf den Zustand * dieser Instanz beziehen, weil die Methode zu einem Zeitpunkt aufgerufen wird, zu dem diese * Instanz noch nicht fertig konstruiert ist. </p> * * @return boolean (default value is {@code false}) * @since 3.15/4.12 */ protected boolean isSingleton() { return false; } /** * <p>Will be called by {@code equals(Object)}. </p> * * <p>Subclasses should override this method if other state attributes than just the element name are to * be taken into account when comparing elements. The parameter can be safely casted to an instance of * this class. </p> * * @param obj other element to be compared with * @return boolean (default value is {@code true}) * @since 3.15/4.12 */ /*[deutsch] * <p>Wird von {@code equals(Object)} aufgerufen. </p> * * <p>Subklassen sollten diese Methode &uuml;berschreiben, wenn anderer Zustandsattribute als nur * der Elementname ber&uuml;cksichtigt werden m&uuml;ssen. Der Parameter kann sicher zu einem * Typ dieser Klasse umgewandelt werden. </p> * * @param obj other element to be compared with * @return boolean (default value is {@code true}) * @since 3.15/4.12 */ protected boolean doEquals(BasicElement<?> obj) { return true; } }
package com.github.anicolaspp.maprdbcleaner import com.github.anicolaspp.maprdbcleaner.conf.Configuration import com.github.anicolaspp.maprdbcleaner.db.Db import com.github.anicolaspp.maprdbcleaner.query.QueryBuilder import org.ojai.store.{Connection, DriverManager} object App { implicit lazy val connection: Connection = DriverManager.getConnection("ojai:mapr:") def main(args: Array[String]): Unit = Configuration .parse(args) .map(QueryBuilder.buildFrom) .map(Db.run) .foreach { case Left(error) => println(error) case Right(msg) => println(msg) } }
package io.restassured.module.mockmvc.kotlin.extensions import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import java.util.concurrent.atomic.AtomicLong @Controller class GreetingController { private val template = "Hello, %s!" private val counter = AtomicLong() @RequestMapping( value = ["/greeting"], method = [RequestMethod.GET] ) @ResponseBody fun greeting( @RequestParam( value = "name", required = false, defaultValue = "World" ) name: String ) = Greeting( counter.incrementAndGet(), String.format(template, name) ) @RequestMapping( value = ["/greeting"], method = [RequestMethod.POST], consumes = ["application/json"], produces = ["application/json"] ) @ResponseBody fun greetingWithRequiredContentType( @RequestParam( value = "name", required = false, defaultValue = "World" ) name: String ) = greeting(name) } data class Greeting( val id: Long, val content: String )
package zielu.gittoolbox.extension.projectview import com.intellij.ide.projectView.ProjectViewNode import com.intellij.openapi.extensions.ExtensionPointName import zielu.intellij.java.toSet internal class ViewModuleNodeChildExtension { fun hasChildOfType(nodeType: Class<in ProjectViewNode<*>>): Boolean { val nodeClasses = getNodeClasses() return nodeClasses.contains(nodeType) } private fun getNodeClasses(): Set<Class<in ProjectViewNode<*>>> { return EXTENSION_POINT_NAME.extensionList.stream() .map { it.getNodeClass() } .toSet() } } private val EXTENSION_POINT_NAME: ExtensionPointName<ViewModuleNodeChildEP> = ExtensionPointName.create( "zielu.gittoolbox.viewModuleNodeChild" )
#ifndef CFD_LAB_CONFIGPARSER_HPP #define CFD_LAB_CONFIGPARSER_HPP #include "LBDefinitions.hpp" #include <fstream> #include <iomanip> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> class ConfigParser { using rawConfig_t = std::unordered_map<std::string, std::string>; public: ConfigParser(const std::string &filename, bool isVerbose) : isVerbose(isVerbose) { rawConfig = parseConfig(filename); } template <typename T> T parse(const std::string &paramName) { // We delegate this to the implementation struct because we need to // specialise the parse function // for the boundary flags and C++ doesn't allow this. return parseImpl<T>::parse(*this, paramName); } private: rawConfig_t parseConfig(const std::string &filename) { rawConfig_t map = rawConfig_t(); auto ifs = std::ifstream(filename); if (!ifs) { throw std::logic_error("Failed to open config file " + filename + "."); } // First match is variable name, second match is value. auto format = std::regex(R"(^(\S*)\s*(\S*))", std::regex::ECMAScript); std::string line; while (std::getline(ifs, line)) { // First remove comments line = line.substr(0, line.find('#')); std::smatch match; std::regex_search(line, match, format); if (match.size() == 3) { if (match[0].str().size() == 0) continue; // Skip empty lines map[match[1].str()] = match[2].str(); } } return map; } template <typename R, typename = void> struct parseImpl { static R parse(ConfigParser &config, const std::string &paramName) { const auto it = config.rawConfig.find(paramName); if (it != config.rawConfig.end()) { std::istringstream ss(it->second); R value; ss >> value; if (config.isVerbose) { std::cout << "config: " << std::setw(20) << paramName << ":" << std::setw(25) << value << std::endl; } return value; } else { throw std::runtime_error("Parameter " + paramName + " not found or wrong format."); } } }; template <typename S> struct parseImpl<flag_t, S> { static flag_t parse(ConfigParser &config, const std::string &paramName) { const auto configIt = config.rawConfig.find(paramName); if (configIt != config.rawConfig.end()) { const auto &value = configIt->second; const auto flagIt = stringToFlag.find(value); if (flagIt != stringToFlag.end()) { const flag_t parsed = flagIt->second; if (config.isVerbose) { std::cout << "config: " << std::setw(20) << paramName << ":" << std::setw(25) << value << "( = " << static_cast<int>(parsed) << " )" << std::endl; } return parsed; } { throw std::runtime_error(value + " is not a valid flag field for boundary " + paramName + "."); } } else { throw std::runtime_error("Parameter " + paramName + " not found or wrong format."); } } }; rawConfig_t rawConfig; const bool isVerbose; }; #endif // CFD_LAB_CONFIGPARSER_HPP
package dranjohn.graphics.scene import dranjohn.graphics.Window import dranjohn.graphics.entity.Entity import dranjohn.graphics.entity.Quad import dranjohn.graphics.scene.camera.Camera import dranjohn.graphics.scene.camera.OrthogonalCamera import org.lwjgl.opengl.GL11 private const val DEFAULT_UNITS_PER_SCREEN_WIDTH = 16f class LWJGLScene(window: Window) : Scene { private val renderers: MutableCollection<Renderer<*>> = hashSetOf() override var unitWidth: Float = DEFAULT_UNITS_PER_SCREEN_WIDTH override var unitHeight: Float = unitWidth * window.height / window.width override var camera: Camera = OrthogonalCamera(unitWidth, unitHeight) override fun <EntityType : Entity> getRenderer(shader: Shader<EntityType>): Renderer<EntityType> { return Renderer(shader, this).also { renderers.add(it) } } override fun <EntityType : Entity> addRenderer(renderer: Renderer<EntityType>) { renderers.add(renderer) } override fun renderAll() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT or GL11.GL_DEPTH_BUFFER_BIT) if (!Quad.isBound()) { Quad.bind() } for (renderer in renderers) { renderer.renderStoredEntities() } } override fun setBackgroundColor(r: Float, g: Float, b: Float) { GL11.glClearColor(r, g, b, 0.0f) } }
§align:center ##### §nDraconic Chestplate§n §stack[draconicevolution:draconic_chest]{size:64} §rule{colour:0x606060,height:3,width:100%,top_pad:0} §bStats Flight (Configurable) Removes mining slowdown while in the air Fire immunity +200 Base Shield Capacity +3 Armor Toughness +8 Armor §rule{colour:0x606060,height:3,width:100%,top_pad:0} §recipe[draconicevolution:draconic_chest]{spacing:2} §rule{colour:0x606060,height:3,width:100%,top_pad:3}
#!/bin/sh #################################################################################################### # # FILENAME: local-config.sh # # PURPOSE: Template for creating a personalized local-config.sh file. # # DESCRIPTION: All shell scripts in the dev-tools directory require several configuration values # to run correctly (eg. the path to your project's root directory or the alias of # the DevHub that you want to use. These customizations can be specific to each # individual developer, and therefore should not be tracked by the project's VCS. # # INSTRUCTIONS: 1. Inside of the dev-tools directory, execute the following command # cp local-config-template.sh local-config.sh # 2. Edit the default values in your local-config.sh to meet the needs of your local # environment and project setup. # #################################################################################################### # # ORG_CONFIG_FILE_NAME="settings/org-settings.sh" # Name of the file that contains Org settings PACKAGE_CONFIG_FILE_NAME="settings/package-settings.sh" # Name of the file that contains Org settings SHARED_CONFIG_FILE_NAME="settings/shared-settings.sh" # Name of the file that contains Shared settings USER_CONFIG_FILE_NAME="settings/user-settings.sh" # Name of the file that contains User settings # ## ### #### LOAD SHARED CONFIG VARIABLES ################################################################## ### ## # # Load local configuration variables from shared-settings.sh. If this file is # missing, EXIT from the shell script with an error message. # if [ ! -r `dirname $0`/$SHARED_CONFIG_FILE_NAME ]; then echoErrorMsg "Local setup-tools configuration file not found" tput sgr 0; tput bold; echo "Your project does not have a shared-settings.sh file in your setup-tools/settings" echo "directory. Please log an issue in your GitHub repository for support.\n" exit 1 fi # # The shared-settings.sh file was found and is readable. Source (execute) it. This will # make all the variables defined in that file available to all commands that come after # it in this shell. # source `dirname $0`/$SHARED_CONFIG_FILE_NAME # ## ### #### LOAD USER CONFIG VARIABLES #################################################################### ### ## # # Load local configuration variables from user-settings.sh. If this file is # missing, EXIT from the shell script with an error message. # if [ ! -r `dirname $0`/$USER_CONFIG_FILE_NAME ]; then echoErrorMsg "Local setup-tools configuration file not found" tput sgr 0; tput bold; echo "Your project does not have a user-settings.sh file in your setup-tools/settings" echo "directory. Please log an issue in your GitHub repository for support.\n" exit 1 fi # # The user-settings.sh file was found and is readable. Source (execute) it. This will # make all the variables defined in that file available to all commands that come after # it in this shell. # source `dirname $0`/$USER_CONFIG_FILE_NAME # ## ### #### LOAD ORG CONFIG VARIABLES ##################################################################### ### ## # # Load local configuration variables from org-settings.sh. If this file is # missing, EXIT from the shell script with an error message. # if [ ! -r `dirname $0`/$ORG_CONFIG_FILE_NAME ]; then echoErrorMsg "Local setup-tools configuration file not found" tput sgr 0; tput bold; echo "Your project does not have an org-settings.sh file in your setup-tools/settings" echo "directory. Please log an issue in your GitHub repository for support.\n" exit 1 fi # # The org-settings.sh file was found and is readable. Source (execute) it. This will # make all the variables defined in that file available to all commands that come after # it in this shell. # source `dirname $0`/$ORG_CONFIG_FILE_NAME # ## ### #### LOAD PACKAGE CONFIG VARIABLES ################################################################# ### ## # # Load local configuration variables from package-settings.sh. If this file is # missing, EXIT from the shell script with an error message. # if [ ! -r `dirname $0`/$PACKAGE_CONFIG_FILE_NAME ]; then echoErrorMsg "Local setup-tools configuration file not found" tput sgr 0; tput bold; echo "Your project does not have a package-settings.sh file in your setup-tools/settings" echo "directory. Please log an issue in your GitHub repository for support.\n" exit 1 fi # # The package-settings.sh file was found and is readable. Source (execute) it. This will # make all the variables defined in that file available to all commands that come after # it in this shell. # source `dirname $0`/$PACKAGE_CONFIG_FILE_NAME # ## ### #### ECHO ALL VARIABLES ############################################################################ ### ## # #if [ "$ECHO_LOCAL_CONFIG_VARS" = "true" ]; then # echo "\n`tput setaf 7``tput bold`Local configuration variables set by `dirname $0`/lib/local-config.sh`tput sgr0`\n" # echoConfigVariables #fi ##END##
package cn.edu.fudan.moreinfo.ebook.service; import cn.edu.fudan.moreinfo.ebook.common.ServerResponse; import cn.edu.fudan.moreinfo.ebook.entity.Book; import java.util.List; import org.springframework.stereotype.Service; @Service public interface BookService { Integer addByBook(Book book); Integer addByBookSelective(Book book); Book getByISBN(String ISBN); Integer delByISBN(String ISBN); Integer updateByBookSelective(Book book); Integer updateByBook(Book book); ServerResponse<String> addBooyByInfo(Book book); ServerResponse<String> checkVaild(String str, String type); ServerResponse<String> checkLegal(String str, String type); ServerResponse<String> delISBN(String isbn); ServerResponse<List<String>> selectBookByBookname(String bookName); }
package de.lessvoid.nifty.slick2d; import de.lessvoid.nifty.Nifty; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * This "game" does nothing but showing the Nifty GUI on the screen. For real games the Nifty Overlay Game should be * used. * * @author Martin Karing &lt;nitram@illarion.org&gt; */ public abstract class NiftyGame extends NiftyOverlayGame { /** * The screen that is called when preparing the GUI. */ @Nullable private final String startScreen; /** * The title of the game. */ @Nonnull private final String title; /** * Create a new game that displays the Nifty GUI and set the title that is shown. * * @param gameTitle the title of the game */ protected NiftyGame(@Nonnull final String gameTitle) { this(gameTitle, "start"); } /** * Create a new game that displays the Nifty GUI and set the title and the start screen for this game. * * @param gameTitle the title of the game * @param niftyStartScreen the name of the screen that should be called first */ protected NiftyGame(@Nonnull final String gameTitle, @Nullable final String niftyStartScreen) { title = gameTitle; startScreen = niftyStartScreen; } /** * Was a close requested? */ @Override public boolean closeRequested() { return false; } /** * Get the title of the game. */ @Nonnull @Override public final String getTitle() { return title; } /** * When initializing the game its only needed to prepare the GUI for display. */ @Override protected final void initGameAndGUI(@Nonnull final GameContainer container) { initNifty(container); if (startScreen != null) { Nifty nifty = getNifty(); if (nifty == null) { throw new IllegalStateException("Nifty is not initialized, but it should be."); } nifty.gotoScreen(startScreen); } } /** * Rendering the GUI only requires that the display is cleared before rendering the screen. */ @Override protected final void renderGame(@Nonnull final GameContainer container, @Nonnull final Graphics g) { g.clear(); } /** * Updating the game is not needed in this implementation as only the GUI is displayed. */ @Override protected final void updateGame(@Nonnull final GameContainer container, final int delta) { // nothing to do } }
#ifndef CONV_MESSAGE_H #define CONV_MESSAGE_H #include <support/SupportDefs.h> class BString; class Contact; class ConvMessage // : public MsnMessage { public: ConvMessage(Contact* sender); virtual ~ConvMessage(); Contact* Sender(); void SetSender(Contact* sender); bigtime_t Timestamp(); void SetTimeStamp(bigtime_t timestamp); private: Contact* m_sender; bigtime_t m_timestamp; }; #endif
#include<stdio.h> int main() { int i,p[26]; char c; for(i=0;i<26;++i) p[i]=0; while(((c=getchar())!='\n')&&(c!=EOF)) if((c>='A')&&(c<='Z')) p[c-'A']++; else if((c>='a')&&(c<='z')) p[c-'a']++; for(i=0;i<26;++i) if(!p[i]) break; if(i<26) printf("not pangram\n"); else printf("pangram\n"); return 0; }
package com.imran.validation.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.imran.validation.dto.Laptop; import com.imran.validation.service.laptopService; import io.swagger.annotations.ApiModel; @RestController public class PageController { @Autowired private laptopService laptopService; @GetMapping(path = "/getAllLaptops") public List<Laptop> getAllLaptops() { return laptopService.findAll(); } @PostMapping(path = "/addLaptop") private ResponseEntity<Object> addLaptop(@RequestBody @Valid Laptop laptop) { return laptopService.add(laptop); } @GetMapping(path = "/getById/{id}") public Resource<Laptop> getById(@PathVariable(value = "id") int id) { return laptopService.findById(id); } }
// Copyright 2020 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. import { Supplementable } from 'base/supplementable.js'; // Represents a pickup on the server. They are some of the wackiest entities available as they // pretend to have respawning ability, but actually don't. At least not really. Our JavaScript code // presents a slightly higher level API over them, with consistent and dependable behaviour. export class Pickup extends Supplementable { // Id to represent an invalid pickup. Maps to INVALID_STREAMER_ID, which is (0). static kInvalidId = 0; // The type of pickup, which defines its behaviour. While any of the documented values is // technically possible, we recommend sticking to the following. // https://wiki.sa-mp.com/wiki/PickupTypes static kTypeDefault = 1; static kTypeVehicle = 14; #id_ = null; #manager_ = null; #modelId_ = null; #type_ = null; #position_ = null; #respawnDelay_ = null; #respawnOptions_ = null; #respawnPending_ = null; #streamDistance_ = null; #interiors_ = null; #players_ = null; #virtualWorlds_ = null; constructor(manager) { super(); this.#manager_ = manager; } // Initializes the pickup on the server. Will call the |createInternal| method to actually // create the pickup on the server, through the samp-incognito-streamer plugin. initialize(options) { this.#modelId_ = options.modelId; this.#type_ = options.type; this.#position_ = options.position; this.#respawnDelay_ = options.respawnDelay; this.#respawnOptions_ = options; this.#respawnPending_ = false; this.#streamDistance_ = options.streamDistance; this.#interiors_ = options.interiors; this.#players_ = options.players; this.#virtualWorlds_ = options.virtualWorlds; this.#id_ = this.createInternal(options); } // Actually creates a pickup on the server. Returns the ID of the created pickup. createInternal(options) { return pawnInvoke('CreateDynamicPickupEx', 'iiffffaaaaiiiii', /* modelId= */ options.modelId, /* type= */ options.type, /* x= */ options.position.x, /* y= */ options.position.y, /* z= */ options.position.z, /* streamdistance= */ options.streamDistance, /* worlds= */ options.virtualWorlds, /* interiors= */ options.interiors, /* players= */ options.players, /* areas= */ options.areas, /* priority= */ options.priority, /* maxworlds= */ options.virtualWorlds.length, /* maxinteriors= */ options.interiors.length, /* maxplayers= */ options.players.length, /* maxareas= */ options.areas.length); } // Schedules the pickup to respawn after the configured delay. async respawnInternal() { this.destroyInternal(); this.#id_ = Pickup.kInvalidId; this.#respawnPending_ = true; await wait(this.#respawnDelay_ * 1000); if (!this.#respawnPending_) return; // |this| got disposed of in the interim this.#respawnPending_ = false; this.#id_ = this.createInternal(this.#respawnOptions_); this.#manager_.didRespawnPickup(this); } // Actually destroys this pickup from the server. May be overridden for tests. destroyInternal() { pawnInvoke('DestroyDynamicPickup', 'i', this.#id_); } // --------------------------------------------------------------------------------------------- get id() { return this.#id_; } get modelId() { return this.#modelId_; } get type() { return this.#type_; } get position() { return this.#position_; } get respawnDelay() { return this.#respawnDelay_; } get streamDistance() { return this.#streamDistance_; } get interiors() { return this.#interiors_; } get players() { return this.#players_; } get virtualWorlds() { return this.#virtualWorlds_; } isConnected() { return this.#id_ !== Pickup.kInvalidId || this.#respawnPending_; } // --------------------------------------------------------------------------------------------- dispose() { if (!this.#respawnPending_) this.destroyInternal(); this.#respawnPending_ = false; this.#manager_.didDisposePickup(this); this.#manager_ = null; this.#id_ = Pickup.kInvalidId; } // --------------------------------------------------------------------------------------------- toString() { return `[object Pickup(${this.#id_}, ${this.#modelId_})]`; } }
--- layout: media title: Unsere Fachärzte permalink: /praxis/ share: false --- | Dr. med. Katharina Mecner | Dr. med. Jiri Mecner | | ------------------------- | -------------------- | | Fachärztin für Gynäkologie und Geburtshilfe | Facharzt für Gynäkologie und Geburtshilfe | | Zertifizierte Spezialistin für Anti-Aging und Präventionsmedizin | Konsiliararzt Universität Tübingen | ![Dr. Katharina und Dr. Jiri Mecner](/images/dres-mecner.jpg){:height="400px"}
@extends('layout.master.master_user') @section('title', 'Atur Aplikasi') @section ('content') <!-- Titlebar ================================================== --> <div id="titlebar" class="single"> <div class="container"> <div class="sixteen columns"> <h2>Kelola Aplikasi</h2> <nav id="breadcrumbs"> <ul> <li>You are here:</li> <li>Kelola Aplikasi</li> </ul> </nav> </div> </div> </div> <!-- Content ================================================== --> <div class="container"> <!-- Table --> <div class="sixteen columns"> <p class="margin-bottom-25">List aplikasi pelamar</p> <table class="manage-table resumes responsive-table"> <tr> <th><i class="fa fa-user"></i> Name</th> <th><i class="fa fa-file-text"></i> Title</th> <th><i class="fas fa-map-marker-alt"></i> Location</th> <th><i class="fas fa-calendar-alt"></i> Date Posted</th> <th><i class="fas fa-check-double"></i> Status Pelamar</th> <th><i class="fas fa-clipboard-list"></i>action</th> </tr> <!-- Item #1 --> <tr> <td class="title">Stiawan Jodi</td> <td>Crew store</td> <td>indonesia</td> <td>September 30, 2020</td> <td> Rejected </td> <td class="action"> <a href="/resume-page" class="lihat"><i class="fas fa-eye"></i> Lihat</a> {{-- <a href="#" class="lihat"><i class="fas fa-check-double"></i> Beri keputusan</a> --}} <a href="#" class="delete"><i class="fa fa-remove"></i> Delete</a> </td> </tr> <!-- Item #1 --> </table> </div> </div> <!-- Footer @endsection
require_relative '../../spec_helper' describe "Integer#bit_length" do context "fixnum" do it "returns the position of the leftmost bit of a positive number" do 0.bit_length.should == 0 1.bit_length.should == 1 2.bit_length.should == 2 3.bit_length.should == 2 4.bit_length.should == 3 n = fixnum_max.bit_length fixnum_max[n].should == 0 fixnum_max[n - 1].should == 1 0.bit_length.should == 0 1.bit_length.should == 1 0xff.bit_length.should == 8 0x100.bit_length.should == 9 (2**12 - 1).bit_length.should == 12 (2**12).bit_length.should == 13 (2**12 + 1).bit_length.should == 13 end it "returns the position of the leftmost 0 bit of a negative number" do -1.bit_length.should == 0 -2.bit_length.should == 1 -3.bit_length.should == 2 -4.bit_length.should == 2 -5.bit_length.should == 3 n = fixnum_min.bit_length fixnum_min[n].should == 1 fixnum_min[n - 1].should == 0 (-2**12 - 1).bit_length.should == 13 (-2**12).bit_length.should == 12 (-2**12 + 1).bit_length.should == 12 -0x101.bit_length.should == 9 -0x100.bit_length.should == 8 -0xff.bit_length.should == 8 -2.bit_length.should == 1 -1.bit_length.should == 0 end end context "bignum" do it "returns the position of the leftmost bit of a positive number" do (2**1000-1).bit_length.should == 1000 (2**1000).bit_length.should == 1001 (2**1000+1).bit_length.should == 1001 (2**10000-1).bit_length.should == 10000 (2**10000).bit_length.should == 10001 (2**10000+1).bit_length.should == 10001 (1 << 100).bit_length.should == 101 (1 << 100).succ.bit_length.should == 101 (1 << 100).pred.bit_length.should == 100 (1 << 10000).bit_length.should == 10001 end it "returns the position of the leftmost 0 bit of a negative number" do (-2**10000-1).bit_length.should == 10001 (-2**10000).bit_length.should == 10000 (-2**10000+1).bit_length.should == 10000 (-2**1000-1).bit_length.should == 1001 (-2**1000).bit_length.should == 1000 (-2**1000+1).bit_length.should == 1000 ((-1 << 100)-1).bit_length.should == 101 ((-1 << 100)-1).succ.bit_length.should == 100 ((-1 << 100)-1).pred.bit_length.should == 101 ((-1 << 10000)-1).bit_length.should == 10001 end end end
package identico import ( "image" "image/color" "image/draw" ) func Classic(mask image.Image, bg, fg color.Color) image.Image { bounds := mask.Bounds() bgimg := FillBackground(bounds, bg) fgimg := ReplaceMask(mask, fg) dst := image.NewNRGBA(bounds) draw.Draw(dst, bounds, bgimg, image.ZP, draw.Src) draw.Draw(dst, bounds, fgimg, image.ZP, draw.Over) return dst } func FillBackground(bounds image.Rectangle, col color.Color) image.Image { img := image.NewNRGBA(bounds) draw.Draw(img, bounds, &image.Uniform{col}, image.ZP, draw.Src) return img } func ReplaceMask(mask image.Image, col color.Color) image.Image { bounds := mask.Bounds() dst := image.NewNRGBA(bounds) w, h := bounds.Max.X, bounds.Max.Y r, g, b, _ := col.RGBA() rgba := color.NRGBA{ uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), 0, } for x := 0; x < w; x++ { for y := 0; y < h; y++ { pixel := mask.At(x, y) _, _, _, alpha := pixel.RGBA() if alpha != 0 { rgba.A = uint8(alpha >> 8) dst.Set(x, y, rgba) } else { dst.Set(x, y, pixel) } } } return dst }
drop table if exists `memoryStore`; create table `memoryStore` ( `key` varchar(255) not null, `value` varbinary(4096) not null, `expire` int unsigned ) engine=memory;