text
stringlengths
27
775k
import copy import numpy as np import curiosity.utils.base as base import curiosity.models.normal_encoder_asymmetric_with_bypass as modelsource import curiosity.datasources.images_and_normals as datasource dbname = 'threeworld_normals' colname = 'test' experiment_id = 'test0_longdr' model_func = modelsource.get_model model_func_kwargs = {"host": "18.93.3.135", "port": 23044, "datapath": "/data2/datasource6"} data_func = datasource.getNextBatch data_func_kwargs = copy.deepcopy(model_func_kwargs) num_train_steps = 20480000 batch_size = 128 slippage = 0 cfgfile = '/home/yamins/curiosity/curiosity/configs/normals_config_winner0.cfg' savedir = '/data/normalsopt' erase_earlier = 3 decaystep=1024000 base.run(dbname, colname, experiment_id, model_func, model_func_kwargs, data_func, data_func_kwargs, num_train_steps, batch_size, slippage=slippage, cfgfile=cfgfile, savedir=savedir, erase_earlier=erase_earlier, base_learningrate=1.0, decaystep=decaystep)
# frozen_string_literal: true module Del class SocketConnection def initialize(path:) File.unlink(path) if File.exist?(path) @server = UNIXServer.new(path) end def on_receive socket = @server.accept yield socket rescue StandardError => error Del.logger.error(error) ensure socket&.close end end end
# nodegame-mturk Handles operations with Amazon Mechanical Turk (MTurk), such as approve/reject HITS, grant bonuses, assign qualifications, etc. ## Decription It can be used as an interactive console or can be called programmatically. As an interactive console, it can operate in two modes: - **standalone mode**: import a compatible results file from MTurk; - **nodeGame mode**: automatically scan the data folder of a nodeGame game and import all results files found. ## Installation - **Stable**: ``` npm install nodegame-mturk ``` - **Development**: ``` git clone https://github.com/nodeGame/nodegame-mturk.git cd nodegame-mturk npm install ``` ## Configuration Create file `conf/mturk.conf.js` using the template in the same directory. Add your Amazon Web Service (AWS) Keys in the conf file: - **accessKeyId**: 'XXX', - **secretAccessKey**: 'YYY' If you do not have your keys yet, please read [here](https://aws.amazon.com/kms/). ### Optional Configuration Settings - **region**: the AWS server you want to connect to. Default: 'us-east-1'. - **nodeGamePath**: the absolute path, or relative path from the root folder of the nodegame-mturk directory, to a nodeGame installation directory. Needed only if you want to automatically import results files from nodeGame. - **fields**: object specifiying the names of the fields for non-standard results files (Important! MTurk default separator is ;). - **filter**: a function to filter items before importing them: must return falsy to skip, or truthy to keep. Default: items are skipped if `type` is equal to 'bot' or if 'skip' is truthy. - **autoApprove**: A boolean flag specifying to auto-approve all imported assignments. Default: false. - **maxBonus**: maximum bonus payable, an error will be raised otherwise. Default: 10USD. - **minBonus**: minimum bonus payable, an error will be raised otherwise. Default: 0USD. - **autoApprove**: A boolean flag specifying to auto-approve all imported assignments. Default: false. - **sandbox**: Operates in sandbox mode. Default: false More options available directly in the configuration file. ## Usage ### Launch the program Start the program from the command line: node ng-amt.js These are the main inline options to use when you start the program (the short and long form of each command are equivalent). **-c, --connect**: Opens the connection with MTurk Server **-r, --resultsFile <resultsFile>**: Path to a results file with Exit and Access Codes **-g, --game <gameFolder> [minRoom-maxRoom]**: Path to a nodeGame game and optional room boundaries **-Q, --getQualificationTypeId**: Fetches the last qualification type owned by requester **-H, --getLastHITId**: Fetches the id of the latest HIT **-s, --sandbox**: Activate sandbox mode **-h, --help**: Output usage information #### Other inline options **-C, --config <confFile>**: Specifies a configuration file **-i, --inputCodesFile <inputCodesFile>**: Path to a codes file with Exit and Access Codes **-t, --token [token]**: Unique token for one-time operations **-d, --dry**: Dry-run: does not actually send any request to server **-n, --nRetries <nRetries>**: How many times a request is repeated in case of error (Def: 0) **-l, --retryInterval <rInterval>**: Milliseconds to wait before a request is repeated (Def: 10000) **-o, --throttleInterval <tInterval>**: Milliseconds between two consecutive requests (Def: 500) **-q, --quiet**: No/minimal output printed to console ### Interactive Prompt After the you started the program, you have access to the interactive console with the following commands: **connect**: Creates the AWS client. **uploadResults [options]**: Uploads the results to AMT server (approval+bonus+qualification). **grantBonus [options]**: Grants bonuses as specified in results codes. **assignQualification [options]**: Assigns a Qualification to all results codes. **get <what>**: Fetches and stores the requested info. **load [options] <what> <path>**: Loads a file. **show [options] <what>**: Prints out the requested info. **extendHIT [options]**: Extends the HIT. **expireHIT**: Expires the HIT. **help [command...]**: Provides help for a given command. **exit**: Exits application. Use TAB to autocomplete commands and options. ## Examples - **Start the program with initial options** Here we load a results file, retrieve the last HIT Id and last Qualification Id. ```bash $ node ng-amt -r path/to/results/file.csv -H -Q info: sandbox-mode: on info: results file: path/to/results/file.csv info: validation level: 2 info: result codes: 9 info: creating mturk client... info: done. info: retrieved QualificationTypeId: XXXXXXXXXXXXXXXXXXX ("My Qualification") info: retrieved last HIT id: YYYYYYYYYYYYYYYYYYY ("My Task Name") ``` - **Show a summary** ```bash ng-amt~$ show Summary info: **** Results **** info: tot results: 9 info: to approve: 7 info: to reject: 2 info: **** Bonus **** info: bonuses: 7 info: bonuses tot: 29.75 info: bonuses mean: 3.31 info: bonuses std: 0.55 info: bonuses min: 2.39 info: bonuses max: 4.06 info: **** Qualification **** info: qualifications: 0 info: **** Balance **** info: Your balance is: $1,000 ``` - **Approve/Reject results** ```bash ng-amt$ uploadResults info: tot results: 9 info: to approve: 9 info: to reject: 0 info: results processed: 9/9 info: approved: 7 info: rejected: 2 error: approve/reject failed: 0 info: Original balance: $1,000 New balance: $993 (diff: 7) ``` - **Grant a Bonus** ```bash ng-amt$ grantBonus -r "Thank You" ``` The reason (option -r) is required. - **Assign a Qualification** ```bash ng-amt$ assignQualification -i 1 ``` The option -i is required. It assigns an integer value for the qualification. Any positive value can be specified. You can use different values to differentiate between participants with the same qualifications. - **Get HIT Id** ```bash ng-amt$ get HITId info: retrieved last HIT id: ****************AADIVNV ("Name of the HIT") ng-amt$ get HITStatus info: **** HIT Status **** info: id: ****************AADIVNV info: status: NotReviewed info: pending ass: 0 info: available ass: 49 info: completed ass: 0 info: expiration: Tue Feb 14 2017 10:38:04 GMT-0500 (EST) info: annotation: BatchId:***641;OriginalHitTemplateId:****37243; ``` The command above returns the last created HIT. If your HIT is not the last one, you can search through the list of 10 most recent HITs. ```bash ng-amt$ get HITIdList ? Select a HIT 1) 7/20/2019 - ***********************YYNG27N Label Tweets ($1.00) 2) 7/20/2019 - ***********************JS8T6I3 Ultimatum Game ($1.00) 3) 7/19/2019 - ***********************UC8RXR8 Prisoner Dilemma ($3.00) 4) 7/18/2019 - ***********************0IBHN5N Understanding Others ($0.85) 5) 7/12/2019 - ***********************Z82S7GA Tell a joke ($0.25) 6) 7/11/2019 - ***********************FCXM1KN Estimating product preferences ($1.00) (Move up and down to reveal more choices) Answer: ``` - **Get Qualification Id** ```bash ng-amt$ get QualificationTypeId info: set QualificationTypeId: ***************WZ8QQ6QO ("my_qualification") ``` The command above returns the last qualification. You can search through the list of the 10 most recent Qualifications. ```bash ng-amt$ get QualificationTypeIdList ? Select a QualificationType 1) 4/20/2019 my_qualification 2) 11/20/2018 another_qualification 3) 8/7/2018 what_is_this_for 4) 7/4/2018 you_made_it 5) 6/4/2018 you_are_definitely_qualified 6) 6/3/2018 you_are_unqualifiable (Move up and down to reveal more choices) Answer: ```bash If you still do not find it, you can add a search query. ``` ng-amt$ get QualificationTypeIdList -s Finished ? Select a QualificationType 1) 7/21/2017 Finished_my_study Answer: ``` - **Get the Status of a running HIT** ```bash ng-amt$ get HITStatus info: **** HIT Status **** info: id: ****************AADIVNV info: status: NotReviewed info: pending ass: 0 info: available ass: 49 info: completed ass: 0 info: expiration: Tue Feb 14 2017 10:38:04 GMT-0500 (EST) info: annotation: BatchId:***641;OriginalHitTemplateId:****37243; ``` - **Load all results from nodeGame** ```bash ng-amt$ load Game mygame -l 60-61 info: loading rooms of game mygame info: scanning data folder minRoom=60 maxRoom=61 warn: no results in room room000060 info: loading results file: room000061 info: results file: C:\Users\me\nodegame-v5.0.0-dev\games\mygame\data\room000061\bonus.csv info: result codes: 1 ``` The commands looks for files saved as `bonus.csv`, `results.csv`, or `codes.csv` in each directory and loads them. ## Use programmatically ```javascript // Require ngmt. var ngmt = require('nodegame-mturk')(); // Or with a custom config file // var ngmt = require('nodegame-mturk')({ config: 'path/to/config.js' }); // Connect, fetch last HIT Id (async), and then assign it to a worker. ngmt.api.connect({ getLastHITId: true }, function() { ngmt.modules.qualification.assign({ WorkerId: XXXXXXXXX', QualificationTypeId: ngmt.config.qualificationId, IntegerValue: 1 }); }); ``` ## License [MIT](LICENSE)
module PokeApi module Common # GenerationGameIndex object handling lists of game_index and generation class GenerationGameIndex attr_reader :game_index, :generation def initialize(data) @game_index = data[:game_index] @generation = Generation.new(data[:generation]) end end end end
<?php namespace Orca\Admin\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use Orca\Admin\Http\Controllers\Controller; use Orca\Admin\DataGrids\TestDataGrid; /** * TestDataGrid controller * * @author Nikhil orca <orca@orca.com> @ysmorca * @author <> * */ class DataGridController extends Controller { protected $_config; protected $testgrid; public function __construct(TestDataGrid $testgrid) { $this->middleware('admin'); $this->_config = request('_config'); $this->testgrid = $testgrid; } public function massDelete() { dd(request()->all()); } public function massUpdate() { dd(request()->all()); } public function testGrid() { return $this->testgrid->render(); } }
package com.github.beikern.monoids trait CustomMonoidInstances { val AndInstance = new MonoidCustom[Boolean] { override def empty: Boolean = true override def combine(x: Boolean, y: Boolean): Boolean = x && y } val OrInstance = new MonoidCustom[Boolean] { override def empty: Boolean = false override def combine(x: Boolean, y: Boolean): Boolean = x || y } val xorInstance = new MonoidCustom[Boolean] { def combine(a: Boolean, b: Boolean): Boolean = (a && !b) || (!a && b) def empty: Boolean = false } val xNorInstance = new MonoidCustom[Boolean] { def combine(a: Boolean, b: Boolean) = (!a || b) && (a || !b) def empty = true } def setUnionInstance[A] = new MonoidCustom[Set[A]] { override def empty: Set[A] = Set.empty override def combine(x: Set[A], y: Set[A]): Set[A] = x union y } }
package cn.edu.sdnu.i.livemeeting.profile; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import cn.edu.sdnu.i.livemeeting.R; public class ProfileEdit extends LinearLayout { private ImageView mIconView; private TextView mKeyView; private TextView mValueView; private ImageView mRightArrowView; public ProfileEdit(Context context) { super(context); init(); } public ProfileEdit(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ProfileEdit(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.view_profile_edit, this , true); findAllViews(); } private void findAllViews() { mIconView = (ImageView) findViewById(R.id.profile_icon); mKeyView = (TextView) findViewById(R.id.profile_key); mValueView = (TextView) findViewById(R.id.profile_value); mRightArrowView = (ImageView) findViewById(R.id.right_arrow); } public void set(int iconResId, String key, String value) { mIconView.setImageResource(iconResId); mKeyView.setText(key); mValueView.setText(value); } public void updateValue(String value) { mValueView.setText(value); } public String getValue() { return mValueView.getText().toString(); } protected void disableEdit() { mRightArrowView.setVisibility(GONE); } }
import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { Router } from '@angular/router'; @Component({ // tslint:disable-next-line:component-selector selector: 'new-signal', templateUrl: 'new-signal.component.html', styleUrls: ['new-signal.component.scss'] }) // tslint:disable-next-line:component-class-suffix export class NewSignalDialog { static dialogRes = true; constructor( public dialogRef: MatDialogRef<NewSignalDialog>, private router: Router, @Inject(MAT_DIALOG_DATA) public data: any) { } onSave(): void { } addPhoto(){ } removePhoto(){ } addTP() { } onNoClick(): void { this.dialogRef.close(); } }
import os import typing from urllib.parse import urljoin import requests class _Router: """ Provides generic `get` and `post` methods. Implemented by DoccanoClient. """ def get( self, endpoint: str, params: dict = {}, ) -> requests.models.Response: """ Args: endpoint (str): An API endpoint to query. Returns: requests.models.Response: The request response (JSON). """ request_url = urljoin(self.baseurl, endpoint) return self._get(request_url, params=params).json() def get_file( self, endpoint: str, params: dict = {}, headers: dict = {}, ) -> requests.models.Response: """ Gets a file. """ request_url = urljoin(self.baseurl, endpoint) return self._get(request_url, params=params, headers=headers) def _get( self, url: str, params: dict = {}, headers: dict = {}, ) -> requests.models.Response: return self.session.get(url, params=params, headers=headers) def post( self, endpoint: str, data: dict = {}, json: dict = {}, files: dict = {}, headers: typing.Optional[dict] = None, as_json=True ) -> requests.models.Response: """ Used to POST arbitrary (form) data or explicit JSON. Both will have the correct Content-Type header set. """ if json and data: return "Error: cannot have both data and json" request_url = urljoin(self.baseurl, endpoint) result = self.session.post( request_url, data=data, files=files, json=json, headers=headers) # return json if requested if as_json: return result.json() return result def delete( self, endpoint: str, data: typing.Optional[dict] = None, files: typing.Optional[dict] = None, headers: typing.Optional[dict] = None, ) -> requests.models.Response: """ Deletes something at the given endpoint. """ request_url = urljoin(self.baseurl, endpoint) return self.session.delete(request_url, data=data, files=files, headers=headers) def build_url_parameter( self, url_parameter: dict ) -> str: """ Format url_parameters. Args: url_parameter (dict): Every value must be a list. Returns: A URL parameter string. Ex: `?key1=u1&key1=u2&key2=v1&...` """ return ''.join(['?', '&'.join(['&'.join(['='.join( [tup[0], str(value)]) for value in tup[1]]) for tup in url_parameter.items()])]) class DoccanoClient(_Router): """ TODO: investigate alternatives to plaintext login Args: baseurl (str): The baseurl of a Doccano instance. username (str): The Doccano username to use for the client session. password (str): The respective username's password. Returns: An authorized client instance. """ def __init__(self, baseurl: str, username: str, password: str): self.baseurl = baseurl if baseurl[-1] == '/' else baseurl+'/' self.session = requests.Session() self._login(username, password) def _login( self, username: str, password: str ) -> requests.models.Response: """ Authorizes the DoccanoClient instance. Args: Returns: requests.models.Response: The authorization request response. """ url = 'v1/auth/login/' auth = {'username': username, 'password': password} response = self.post(url, auth) self._set_csrf_header() return response def _set_csrf_header(self): """ Sets the CSRF token required for the POST requests. NB: this function has to be called after the login endpoint. Even if it's the post endpoint too it doesn't require CSRF verification, but the token can be received from the cookies """ csrf = self.session.cookies.get('csrftoken') self.session.headers['X-CSRFToken'] = csrf def get_me(self) -> requests.models.Response: """ Gets this account information. Returns: requests.models.Response: The request response. """ return self.get('v1/me') def get_features(self) -> requests.models.Response: """ Gets features. Returns: requests.models.Response: The request response. """ return self.get('v1/features') def get_project_list(self) -> requests.models.Response: """ Gets projects list. Returns: requests.models.Response: The request response. """ return self.get('v1/projects') def create_project( self, name: str, description: str = "", project_type: str = "DocumentClassification", guideline: str = "", resourcetype: str = "TextClassificationProject", randomize_document_order: bool = False, collaborative_annotation: bool = False ) -> requests.models.Response: """ Creates a new project. Returns: requests.models.Response: The request response. """ payload = { "name": name, "description": description, "project_type": project_type, "guideline": guideline, "resourcetype": resourcetype, "randomize_document_order": randomize_document_order, "collaborative_annotation": collaborative_annotation } return self.post('v1/projects', data=payload) def create_document( self, project_id: int, text: str, annotations: list = [], annotation_approver: str = None ) -> requests.models.Response: """ Creates a document. Args: project_id (int): project identifier text (str): your text annotations (list): annotations annotation_approver (str): account that approved Returns: requests.models.Response: The request response """ url = 'v1/projects/{}/docs'.format(project_id) data = {'text': text, 'annotations': annotations, 'annotation_approver': annotation_approver} return self.post(url, data=data) def delete_document( self, project_id: int, document_id: int, ) -> requests.models.Response: url = 'v1/projects/{}/docs/{}'.format(project_id, document_id) return self.delete(url) def create_label( self, project_id: int, text: str, text_color: str = "#ffffff", background_color: str = "#cdcdcd", prefix_key: str = None, suffix_key: str = None ) -> requests.models.Response: """ Creates a label to be used for annotating a document. """ url = 'v1/projects/{}/labels'.format(project_id) label_payload = { "projectId": project_id, "text": text, "prefix_key": prefix_key, "suffix_key": suffix_key, "background_color": background_color, "text_color": text_color } try: return self.post(url, data=label_payload) except Exception as e: return "Failed (duplicate?): {}".format(e) def add_annotation( self, project_id: int, annotation_id: int, document_id: int, **kwargs ) -> requests.models.Response: """ Adds an annotation to a given document. Variable keyword arguments \*\*kwargs give support to doccano annotations for different project types. For example, for SequenceLabeling one should call using start_offset and end_offset keyword arguments. Args: project_id (int): Project database identifier. annotation_id (int): Annotation identifier. document_id (int): Document identifier. **kwargs: Arbitrary keyword arguments. Returns: requests.models.Response: The request response. """ url = '/v1/projects/{p_id}/docs/{d_id}/annotations'.format( p_id=project_id, d_id=document_id) payload = { "label": annotation_id, "projectId": project_id, **kwargs} return self.post(url, json=payload) def get_user_list(self) -> requests.models.Response: """ Gets user list. Returns: requests.models.Response: The request response. """ return self.get('v1/users') def get_roles(self) -> requests.models.Response: """ Gets available Doccano user roles. Returns: requests.models.Response: The request response. """ return self.get('v1/roles') def get_project_detail( self, project_id: int ) -> requests.models.Response: """ Gets details of a specific project. Args: project_id (int): A project ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}'.format( project_id=project_id ) ) def get_project_statistics( self, project_id: int ) -> requests.models.Response: """ Gets project statistics. Args: project_id (int): A project ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/statistics'.format( project_id=project_id ) ) def get_label_list( self, project_id: int ) -> requests.models.Response: """ Gets a list of labels in a given project. Args: project_id (int): A project ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/labels'.format( project_id=project_id ) ) def get_label_detail( self, project_id: int, label_id: int ) -> requests.models.Response: """ Gets details of a specific label. Args: project_id (int): A project ID to query. label_id (int): A label ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/labels/{label_id}'.format( project_id=project_id, label_id=label_id ) ) def get_document_list( self, project_id: int, url_parameters: dict = {} ) -> requests.models.Response: """ Gets a list of documents in a project. Args: project_id (int): url_parameters (dict): `limit` and `offset` Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/docs{url_parameters}'.format( project_id=project_id, url_parameters=self.build_url_parameter(url_parameters) ) ) def get_document_detail( self, project_id: int, doc_id: int ) -> requests.models.Response: """ Gets details of a given document. Args: project_id (int): A project ID to query. doc_id (int): A document ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/docs/{doc_id}'.format( project_id=project_id, doc_id=doc_id ) ) def get_annotation_list( self, project_id: int, doc_id: int ) -> requests.models.Response: """ Gets a list of annotations in a given project and document. Args: project_id (int): A project ID to query. doc_id (int): A document ID to query. Returns: requests.models.Response: The request response. """ return self.get( 'v1/projects/{project_id}/docs/{doc_id}/annotations'.format( project_id=project_id, doc_id=doc_id ) ) def get_annotation_detail( self, project_id: int, doc_id: int, annotation_id: int ) -> requests.models.Response: """ """ return self.get( 'v1/projects/{p_id}/docs/{d_id}/annotations/{a_id}'.format( p_id=project_id, d_id=doc_id, a_id=annotation_id ) ) def get_doc_download( self, project_id: int, file_format: str = 'json', only_approved: bool = False ) -> requests.models.Response: """ Downloads the dataset in specified format. """ accept_headers = { 'json': 'application/json', 'csv': 'text/csv' } headers = {'accept': accept_headers[file_format]} return self.get_file( 'v1/projects/{project_id}/docs/download'.format( project_id=project_id ), params={'q': file_format, 'onlyApproved': str(only_approved).lower()}, headers=headers ) def get_rolemapping_list( self, project_id: int, ) -> requests.models.Response: """ """ return self.get( 'v1/projects/{project_id}/roles'.format( project_id=project_id ) ) def get_rolemapping_detail( self, project_id: int, rolemapping_id: int, ) -> requests.models.Response: """ Currently broken! """ return self.get( 'v1/projets/{project_id}/roles/{rolemapping_id}'.format( project_id=project_id, rolemapping_id=rolemapping_id ) ) def post_doc_upload_binary( self, project_id: int, files: typing.List[typing.IO], column_data: str = "text", column_label: str = "label", delimiter: str = "", encoding: str = "utf_8", format: str = "JSONL" ) -> dict: """ Upload documents to doccano Args: project_id (int): The project id number. files (typing.List[typing.IO]): List of files to be uploaded column_data (str): Name of the column with data (text for annotation) column_label (str): Name of the column with labels (labels for annotation) delimiter (str): Delimeter for the current dataset encoding (str): Current file encoding format (str): The file format, ex: `plain`, `json`, or `conll`. Returns: requests.models.Response: The request response. """ # upload files with filepond if not isinstance(files, (list, tuple)): # this check is very important # as file object is iterable and this function will # try to upload file line by line raise TypeError("Please provide a list with files") upload_ids = [] for file_ in files: try: fp_resp = self.post("v1/fp/process/", files={"filepond": file_}, as_json=False) fp_resp.raise_for_status() upload_ids.append(fp_resp.text) except Exception as e: # revert previous uploads if we have a problem for upload_id in upload_ids: self.delete("v1/fp/revert/", data=upload_id, headers={'Content-Type': 'text/plain'}) raise e # confirm uploads and run processing upload_data = { "column_data": column_data, "column_label": column_label, "delimiter": delimiter, "encoding": encoding, "format": format, "uploadIds": upload_ids } return self.post("v1/projects/1/upload", json=upload_data) def post_doc_upload( self, project_id: int, file_name: str, file_path: str = './', column_data: str = "text", column_label: str = "label", delimiter: str = "", encoding: str = "utf_8", format: str = "JSONL" ) -> requests.models.Response: """ Uploads a file to a Doccano project. Args: project_id (int): The project id number. file_format (str): The file format, ex: `plain`, `json`, or `conll`. file_name (str): The name of the file. file_path (str): The parent path of the file. Defaults to `./`. column_data (str): Name of the column with data (text for annotation) column_label (str): Name of the column with labels (labels for annotation) delimiter (str): Delimeter for the current dataset encoding (str): Current file encoding format (str): The file format, ex: `plain`, `json`, or `conll`. Returns: requests.models.Response: The request response. """ return self.post_doc_upload_binary( project_id=project_id, files=[open(os.path.join(file_path, file_name), 'rb')], column_data=column_data, column_label=column_label, delimiter=delimiter, encoding=encoding, format=format ) def post_approve_labels( self, project_id: int, doc_id: int ) -> requests.models.Response: """ """ return self.post( 'v1/projects/{project_id}/docs/{doc_id}/approve-labels'.format( project_id=project_id, doc_id=doc_id ) ) def _get_any_endpoint( self, endpoint: str ) -> requests.models.Response: """ """ # project_id: int, # limit: int, # offset: int return self.get(endpoint) def exp_get_doc_list( self, project_id: int, limit: int, offset: int ) -> requests.models.Response: """ """ params = {'limit': limit, 'offset': offset} return self.get( 'v1/projects/{project_id}/docs'.format( project_id=project_id, ), params )
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use App\Models\Asset; class AddNextAutoincrementToSettings extends Migration { /** * Run the migrations. * * @return void */ public function up() { $assets = Asset::select('asset_tag')->whereNull('deleted_at')->get(); if (!$next = Asset::nextAutoIncrement($assets)) { $next = 1; } Schema::table('settings', function (Blueprint $table) use ($next) { $table->bigInteger('next_auto_tag_base')->default('1'); }); //\Log::debug('Setting '.$next.' as default auto-increment'); if ($settings = App\Models\Setting::first()) { $settings->next_auto_tag_base = $next; $settings->save(); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('settings', function ($table) { $table->dropColumn('next_auto_tag_base'); }); } }
package entity func (s *Constellation) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" } func (s *Region) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" } func (s *SolarSystem) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" } func (s *InvCategory) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" } func (s *InvGroup) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" } func (s *InvType) GetName(lang string) string { for _, lt := range s.Names { if *lt.Lang == lang { return *lt.Text } } return "" }
{"score": 7.97, "timestamp": 1562142748.0, "score_count": 74934} {"score": 7.97, "timestamp": 1560745353.0, "score_count": 74728} {"score": 7.98, "timestamp": 1554197497.0, "score_count": 73928} {"score": 7.98, "timestamp": 1554003522.0, "score_count": 73883} {"score": 8.0, "timestamp": 1522339370.0, "score_count": 69506} {"score": 8.03, "timestamp": 1488290430.0, "score_count": 63012} {"score": 8.05, "timestamp": 1478630142.0, "score_count": 61025} {"score": 8.05, "timestamp": 1471626922.0, "score_count": 59506} {"score": 8.06, "timestamp": 1471006817.0, "score_count": 59329} {"score": 8.06, "timestamp": 1468011766.0, "score_count": 58543} {"score": 8.06, "timestamp": 1466106231.0, "score_count": 58038} {"score": 8.07, "timestamp": 1465495025.0, "score_count": 57900} {"score": 8.07, "timestamp": 1465294247.0, "score_count": 57852} {"score": 8.07, "timestamp": 1464877941.0, "score_count": 57742} {"score": 8.07, "timestamp": 1463739025.0, "score_count": 57511} {"score": 7.97, "timestamp": 1561629343.0, "score_count": 74864} {"score": 8.04, "timestamp": 1479403455.0, "score_count": 61151} {"score": 8.1, "timestamp": 1448643257.0, "score_count": 53013} {"score": 8.07, "timestamp": 1463604002.0, "score_count": 57465} {"score": 8.07, "timestamp": 1462451497.0, "score_count": 57178} {"score": 8.07, "timestamp": 1461292535.0, "score_count": 56860} {"score": 8.07, "timestamp": 1460656154.0, "score_count": 56686} {"score": 8.07, "timestamp": 1460639747.0, "score_count": 56684} {"score": 8.07, "timestamp": 1459974036.0, "score_count": 56464} {"score": 8.08, "timestamp": 1459340623.0, "score_count": 56197} {"score": 8.08, "timestamp": 1459037335.0, "score_count": 56082} {"score": 8.08, "timestamp": 1458759186.0, "score_count": 55993} {"score": 8.08, "timestamp": 1458367931.0, "score_count": 55880} {"score": 8.08, "timestamp": 1458190587.0, "score_count": 55837} {"score": 8.08, "timestamp": 1458154575.0, "score_count": 55827} {"score": 8.08, "timestamp": 1458126841.0, "score_count": 55821} {"score": 8.08, "timestamp": 1457477269.0, "score_count": 55627} {"score": 8.09, "timestamp": 1453674524.0, "score_count": 54576} {"score": 8.09, "timestamp": 1453552681.0, "score_count": 54524}
// This file is part of Substrate. // Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //! Client fixed chain specification rules use std::collections::{HashMap, HashSet}; use sp_runtime::traits::{Block as BlockT, NumberFor}; use sc_client_api::{BadBlocks, ForkBlocks}; /// Chain specification rules lookup result. pub enum LookupResult<B: BlockT> { /// Specification rules do not contain any special rules about this block NotSpecial, /// The block is known to be bad and should not be imported KnownBad, /// There is a specified canonical block hash for the given height Expected(B::Hash), } /// Chain-specific block filtering rules. /// /// This holds known bad blocks and known good forks, and /// is usually part of the chain spec. pub struct BlockRules<B: BlockT> { bad: HashSet<B::Hash>, forks: HashMap<NumberFor<B>, B::Hash>, } impl<B: BlockT> BlockRules<B> { /// New block rules with provided black and white lists. pub fn new(fork_blocks: ForkBlocks<B>, bad_blocks: BadBlocks<B>) -> Self { Self { bad: bad_blocks.unwrap_or_else(|| HashSet::new()), forks: fork_blocks.unwrap_or_else(|| vec![]).into_iter().collect(), } } /// Mark a new block as bad. pub fn mark_bad(&mut self, hash: B::Hash) { self.bad.insert(hash); } /// Check if there's any rule affecting the given block. pub fn lookup(&self, number: NumberFor<B>, hash: &B::Hash) -> LookupResult<B> { if let Some(hash_for_height) = self.forks.get(&number) { if hash_for_height != hash { return LookupResult::Expected(hash_for_height.clone()) } } if self.bad.contains(hash) { return LookupResult::KnownBad } LookupResult::NotSpecial } }
# Ubuntu1804InstallCuda ## Step 1 * Reset environment * Install gpu driver ## Step 2 * Install cuda (copied from TF [homepage](https://www.tensorflow.org/install/gpu)) ## Tested 2020/02/23 * TensorFlow 2.1 works * Pytorch 1.4 works
(def nplayers 478) (def last-marble 71240) (defn insert-at [array pos item] (vec (concat (subvec array 0 pos) [item] (subvec array pos)))) (defn remove-at [array pos] (vec (concat (subvec array 0 pos) (subvec array (inc pos))))) (defn max-score [] (loop [circle [0] current-marble 0 current-player -1 scores (vec (repeat nplayers 0)) marbles (drop 1 (range))] (let [marble (first marbles) circle-size (count circle) pos (inc (mod (inc current-marble) circle-size))] (if (zero? (mod marble 23)) (let [removed-pos (mod (- current-marble 7) circle-size)] (recur (remove-at circle removed-pos) (if (>= removed-pos (dec circle-size)) 0 removed-pos) (mod (inc current-player) nplayers) (update scores current-player #(+ % marble (get circle removed-pos))) (rest marbles))) (if (<= marble last-marble) (recur (insert-at circle pos marble) pos (mod (inc current-player) nplayers) scores (rest marbles)) (apply max scores))))))
<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); /* load the MX_Router class */ require APPPATH."third_party/MX/Router.php"; class MY_Router extends MX_Router { /** * Override the default system routing to add the initial module routes */ protected function _set_routing() { // Load the routes.php file. It would be great if we could // skip this for enable_query_strings = TRUE, but then // default_controller would be empty ... if (file_exists(APPPATH.'config/routes.php')) { include(APPPATH.'config/routes.php'); } if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); } /** * Scan and add the initial routes from the module */ /* scan the routes file if any */ $scan = array_merge(glob(APPPATH . 'modules/*/routes.php'), glob(APPPATH . '../modules/*/routes.php')); /* check if there's any routes file found */ if(is_array($scan) && sizeof($scan) > 0) { /* loop the result of file */ foreach($scan as $key => $val) { /* push to route */ require_once($val); } } // Validate & get reserved routes if (isset($route) && is_array($route)) { isset($route['default_controller']) && $this->default_controller = $route['default_controller']; isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes']; unset($route['default_controller'], $route['translate_uri_dashes']); $this->routes = $route; } // Are query strings enabled in the config file? Normally CI doesn't utilize query strings // since URI segments are more search-engine friendly, but they can optionally be used. // If this feature is enabled, we will gather the directory/class/method a little differently if ($this->enable_query_strings) { // If the directory is set at this time, it means an override exists, so skip the checks if ( ! isset($this->directory)) { $_d = $this->config->item('directory_trigger'); $_d = isset($_GET[$_d]) ? trim($_GET[$_d], " \t\n\r\0\x0B/") : ''; if ($_d !== '') { $this->uri->filter_uri($_d); $this->set_directory($_d); } } $_c = trim($this->config->item('controller_trigger')); if ( ! empty($_GET[$_c])) { $this->uri->filter_uri($_GET[$_c]); $this->set_class($_GET[$_c]); $_f = trim($this->config->item('function_trigger')); if ( ! empty($_GET[$_f])) { $this->uri->filter_uri($_GET[$_f]); $this->set_method($_GET[$_f]); } $this->uri->rsegments = array( 1 => $this->class, 2 => $this->method ); } else { $this->_set_default_controller(); } // Routing rules don't apply to query strings and we don't need to detect // directories, so we're done here return; } // Is there anything to parse? if ($this->uri->uri_string !== '') { $this->_parse_routes(); } else { $this->_set_default_controller(); } } }
package com.chenjim.andlibs.demo import android.util.Log import com.chenjim.andlibs.BaseApplication import com.chenjim.andlibs.loadsir.* import com.chenjim.andlibs.preference.SPUtil import com.chenjim.andlibs.utils.Logger import com.kingja.loadsir.core.LoadSir /** * @description: * @fileName: UserApp * @author: jim.chen * @date: 2020/4/16 */ class UserApp : BaseApplication() { override fun onCreate() { super.onCreate() SPUtil.init(this) //ApiBase.setNetworkRequestInfo(new NetworkRequestInfo()); sDebug = BuildConfig.DEBUG LoadSir.beginBuilder() .addCallback(ErrorCallback()) //添加各种状态页 .addCallback(EmptyCallback()) .addCallback(LoadingCallback()) .addCallback(TimeoutCallback()) .addCallback(CustomCallback()) .setDefaultCallback(LoadingCallback::class.java) //设置默认状态页 .commit() Logger.init(this, Log.VERBOSE) // CC.enableDebug(BuildConfig.DEBUG); // CC.enableVerboseLog(BuildConfig.DEBUG); // CC.enableRemoteCC(BuildConfig.DEBUG); } }
/**********************************************************************************************/ /* Copyright (c) 2015 Amanda Randles, John Gounley */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, are */ /* permitted provided that the following conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright notice, this list of */ /* conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright notice, this list of */ /* conditions and the following disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS*/ /* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */ /* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF */ /* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) */ /* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR */ /* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /**********************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> // parameters #define MC 19 // number of discrete velocities #define LX_MAX 81 // number of lattice points, x-direction #define LY_MAX 81 // number of lattice points, y-direction #define LZ_MAX 61 // number of lattice points, z-direction #define T (1.0 / 3.0) // speed of sound squared in LB units #define omega 1.0 // relaxation time for LBM double distr[MC][LX_MAX][LY_MAX][LZ_MAX]; // distribution function double distr_adv[MC][LX_MAX][LY_MAX][LZ_MAX]; // distribution function, to advance // main program int main(int argc, char **argv) { printf("starting setup...\n"); /* SETUP SECTION */ // variable definitions */ int ic[MC][3], idg[MC]; double distr_eq[MC]; int lx, ly, lz; double rho, ux, uy, uz, distr0, distr1, uke; double px, py, pz, delNi; double u0 = 1e-4; double cdotu; FILE *vtk_fp, *fp, *g_fp; int i, ix, iy, iz, is, ik, istate, j, i1, js; // read state vectors */ fp = fopen("states19.i", "r"); if (fp == NULL) { fprintf(stderr, "Error: cannot open file states19.i.\n"); return 1; } for(i = 0; i < MC; i++) { fscanf(fp, "%d %d %d %d %d", &istate, &ic[i][0], &ic[i][1], &ic[i][2], &idg[i]); } fclose(fp); // setup time int n_step; int n_step_max = 1000; int n_step_out = 1000; // setup grid dimensions lx = LX_MAX; ly = LY_MAX; lz = LZ_MAX; double dx = 10.0/( (double) (lx-1)); double dt = dx; // fix // setup initial flow (shear flow) distr1 = 1.0 / 36.0; distr0 = 1.0 / 3.0; for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { rho = 1.0; ux = u0*dx*( iy - (ly-1.0)/2.0 ); uy = 0.0; uz = 0.0; uke = 0.5*(ux*ux + uy*uy + uz*uz); for(is = 0; is < MC-1; is++) { cdotu = ic[is][0]*ux + ic[is][1]*uy + ic[is][2]*uz; distr[is][ix][iy][iz] = rho*distr1*idg[is]*(1.0 + cdotu/T + 0.5*(cdotu/T)*(cdotu/T) - uke/T); } distr[MC-1][ix][iy][iz] = distr0*(1.0 - uke/T); } } } printf("starting loop...\n"); /* THE TIMESTEPPING LOOP */ for(n_step = 1; n_step <= n_step_max; n_step++) { /* collision - vanilla version */ for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { rho = px = py = pz = 0.0; for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; px += distr[is][ix][iy][iz]*ic[is][0]; py += distr[is][ix][iy][iz]*ic[is][1]; pz += distr[is][ix][iy][iz]*ic[is][2]; } ux = px / rho; uy = py / rho; uz = pz / rho; uke = 0.5*(ux*ux + uy*uy + uz*uz); for(is = 0; is < MC-1; is++) { cdotu = ic[is][0]*ux + ic[is][1]*uy + ic[is][2]*uz; distr_eq[is] = rho*distr1*idg[is]*(1.0 + cdotu/T + 0.5*(cdotu/T)*(cdotu/T) - uke/T); } distr_eq[MC-1] = distr0*(1.0 - uke/T); for(is = 0; is < MC; is++) { delNi = -omega * (distr[is][ix][iy][iz] - distr_eq[is]); distr_adv[is][ix][iy][iz] = distr[is][ix][iy][iz] + delNi; } } } } /* advection */ for(ix = 0; ix < lx; ix++) { for(iy = 0; iy < ly; iy++) { for(iz = 0; iz < lz; iz++) { int ixa, iya, iza; for(is = 0; is < MC; is++) { ixa = ix + ic[is][0]; iya = iy + ic[is][1]; iza = iz + ic[is][2]; ixa = (ixa < 0) ? lx-1 : ixa % lx; iza = (iza < 0) ? lz-1 : iza % lz; if (iya >= 0 && iya < ly){ distr[is][ixa][iya][iza] = distr_adv[is][ix][iy][iz]; } } } } } // todo : real bcs // bottom iy = 0; double n[3] = {0.0, -1.0, 0.0}; double umax[3] = {u0*dx*(iy - (ly-1.0)/2.0), 0.0, 0.0}; double cdotn[19]; double cdotu[19]; double tdotu[19]; double t[19][3]; int exitVel[5]; int tangVel[9]; int exitCount = 0; int tangCount = 0; for(is = 0; is < MC; is++) { cdotn[is] = ic[is][0]*n[0] + ic[is][1]*n[1] + ic[is][2]*n[2]; cdotu[is] = ic[is][0]*umax[0] + ic[is][1]*umax[1] + ic[is][2]*umax[2]; t[is][0] = ic[is][0] - cdotn[is]*n[0]; t[is][1] = ic[is][1] - cdotn[is]*n[1]; t[is][2] = ic[is][2] - cdotn[is]*n[2]; tdotu[is] = t[is][0]*umax[0] + t[is][1]*umax[1] + t[is][2]*umax[2]; if (cdotn[is] > 0.5) { exitVel[exitCount] = is; exitCount++; } else if (cdotn[is] > -0.5) { tangVel[tangCount] = is; tangCount++; } } for(ix = 0; ix < lx; ix++) { for(iz = 0; iz < lz; iz++) { double tempRho = 0.0; for (unsigned in=0; in<9; ++in) { is = tangVel[in]; tempRho += distr[is][ix][iy][iz]; } for (unsigned in=0; in<5; ++in) { is = exitVel[in]; tempRho += 2.0*distr[is][ix][iy][iz]; } double rho = tempRho/(1+n[0]*umax[0]+n[1]*umax[1]+n[2]*umax[2]); // compute sum in equation 27 of Hecht, Harting (JSM, 2010) double temp_sum[MC]; for(is = 0; is < MC; is++) { temp_sum[is] = 0.0; for(js = 0; js < MC; js++) { double cdottij = (ic[js][0]*t[is][0] + ic[js][1]*t[is][1] + ic[js][2]*t[is][2]); temp_sum[is] += distr[js][ix][iy][iz]*cdottij*(1.-fabs(cdotn[js])); } } // equation 27 of Hecht, Harting (JSM, 2010), with fix based on stencil weight idg for (unsigned in=0; in<5; ++in) { int is = exitVel[in]; int opp = is-1; distr[opp][ix][iy][iz] = distr[is][ix][iy][iz] - cdotu[is]*rho*(double)idg[is]/6. - tdotu[is]*rho/3. + 0.5*temp_sum[is]; } } } // top iy = ly-1; n[0] = 0.0; n[1] = 1.0; n[2] = 0.0; umax[0] = u0*dx*(iy - (ly-1.0)/2.0); umax[1] = 0.0; umax[2] = 0.0; exitCount = 0; tangCount = 0; for(is = 0; is < MC; is++) { cdotn[is] = ic[is][0]*n[0] + ic[is][1]*n[1] + ic[is][2]*n[2]; cdotu[is] = ic[is][0]*umax[0] + ic[is][1]*umax[1] + ic[is][2]*umax[2]; t[is][0] = ic[is][0] - cdotn[is]*n[0]; t[is][1] = ic[is][1] - cdotn[is]*n[1]; t[is][2] = ic[is][2] - cdotn[is]*n[2]; tdotu[is] = t[is][0]*umax[0] + t[is][1]*umax[1] + t[is][2]*umax[2]; if (cdotn[is] > 0.5) { exitVel[exitCount] = is; exitCount++; } else if (cdotn[is] > -0.5) { tangVel[tangCount] = is; tangCount++; } } for(ix = 0; ix < lx; ix++) { for(iz = 0; iz < lz; iz++) { double tempRho = 0.0; for (unsigned in=0; in<9; ++in) { is = tangVel[in]; tempRho += distr[is][ix][iy][iz]; } for (unsigned in=0; in<5; ++in) { is = exitVel[in]; tempRho += 2.0*distr[is][ix][iy][iz]; } double rho = tempRho/(1+n[0]*umax[0]+n[1]*umax[1]+n[2]*umax[2]); // compute sum in equation 27 of Hecht, Harting (JSM, 2010) double temp_sum[MC]; for(is = 0; is < MC; is++) { temp_sum[is] = 0.0; for(js = 0; js < MC; js++) { double cdottij = (ic[js][0]*t[is][0] + ic[js][1]*t[is][1] + ic[js][2]*t[is][2]); temp_sum[is] += distr[js][ix][iy][iz]*cdottij*(1.-fabs(cdotn[js])); } } // equation 27 of Hecht, Harting (JSM, 2010), with fix based on stencil weight idg for (unsigned in=0; in<5; ++in) { int is = exitVel[in]; int opp = is+1; distr[opp][ix][iy][iz] = distr[is][ix][iy][iz] - cdotu[is]*rho*(double)idg[is]/6. - tdotu[is]*rho/3. + 0.5*temp_sum[is]; } } } /* output */ if (n_step % n_step_out == 0) { printf("%d\n", n_step); char fname[15]; sprintf(fname,"lbe_%d.vtk",n_step); vtk_fp = fopen(fname, "w"); if (vtk_fp == NULL) { fprintf(stderr, "Error: cannot open file lbe.vtk. \n"); return 1; } fprintf(vtk_fp, "# vtk DataFile Version 3.0"); fprintf(vtk_fp, "\nvtk global output\n"); fprintf(vtk_fp, "ASCII\n"); fprintf(vtk_fp, "DATASET STRUCTURED_POINTS\n"); fprintf(vtk_fp, "DIMENSIONS %i %i %i\n", lx, ly, lz); fprintf(vtk_fp, "ORIGIN 0. 0. 0.\n"); fprintf(vtk_fp, "SPACING 1 1 1\n"); fprintf(vtk_fp, "\nPOINT_DATA %d\n",lx*ly*lz); fprintf(vtk_fp, "SCALARS rho double \n"); fprintf(vtk_fp, "LOOKUP_TABLE default\n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { rho = px = py = pz = 0.0; for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; } fprintf(vtk_fp, "%f\n",rho); } } } fprintf(vtk_fp, "VECTORS velocity double \n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { rho = px = py = pz = 0.0; for(is = 0; is < MC; is++) { rho += distr[is][ix][iy][iz]; px += distr[is][ix][iy][iz]*ic[is][0]; py += distr[is][ix][iy][iz]*ic[is][1]; pz += distr[is][ix][iy][iz]*ic[is][2]; } ux = px / rho; uy = py / rho; uz = pz / rho; fprintf(vtk_fp, "%f %f %f\n",ux,uy,uz); } } } fprintf(vtk_fp, "VECTORS coordinates double \n"); for(iz = 0; iz < lz; iz++) { for(iy = 0; iy < ly; iy++) { for(ix = 0; ix < lx; ix++) { fprintf(vtk_fp, "%f %f %f\n",ix*dx,iy*dx,iz*dx); } } } fclose(vtk_fp); } } return 0; }
import AddCommentDialog from './AddCommentDialog.vue' import AddStaffNotationDialog from './AddStaffNotationDialog.vue' import BusinessAuthErrorDialog from './BusinessAuthErrorDialog.vue' import CancelPaymentErrorDialog from './CancelPaymentErrorDialog.vue' import CoaWarningDialog from './CoaWarningDialog.vue' import { ConfirmDialog } from '@bcrs-shared-components/confirm-dialog' import ConfirmDissolution from './ConfirmDissolution.vue' import DashboardUnavailableDialog from './DashboardUnavailableDialog.vue' import DeleteErrorDialog from './DeleteErrorDialog.vue' import DownloadErrorDialog from './DownloadErrorDialog.vue' import FetchErrorDialog from './FetchErrorDialog.vue' import LoadCorrectionDialog from './LoadCorrectionDialog.vue' import NameRequestAuthErrorDialog from './NameRequestAuthErrorDialog.vue' import NameRequestInvalidDialog from './NameRequestInvalidDialog.vue' import NotInGoodStandingDialog from '@/components/dialogs/NotInGoodStandingDialog.vue' import PaymentErrorDialog from './PaymentErrorDialog.vue' import ResumeErrorDialog from './ResumeErrorDialog.vue' import SaveErrorDialog from './SaveErrorDialog.vue' import StaffPaymentDialog from './StaffPaymentDialog.vue' import WarningPopover from './WarningPopover.vue' export { AddCommentDialog, AddStaffNotationDialog, BusinessAuthErrorDialog, CancelPaymentErrorDialog, CoaWarningDialog, ConfirmDialog, ConfirmDissolution, DashboardUnavailableDialog, DeleteErrorDialog, DownloadErrorDialog, FetchErrorDialog, LoadCorrectionDialog, NameRequestAuthErrorDialog, NameRequestInvalidDialog, NotInGoodStandingDialog, PaymentErrorDialog, ResumeErrorDialog, SaveErrorDialog, StaffPaymentDialog, WarningPopover }
#pragma once #include <fstream> class Settings { public: Settings() { soundOn = true; _w = -1; _h = -1; } void setWH(int w, int h) { _w = w; _h = h; } void getWH(int& w, int& h) { w = _w; h = _h; } int getW() { return _w; } int getH() { return _h; } bool isSoundOn() { return soundOn; } void setSoundOn(bool _soundOn) { soundOn = _soundOn; } void write(std::ostream& f) { f.write((char*)&soundOn, sizeof(soundOn)); f.write((char*)&_w, sizeof(_w)); f.write((char*)&_h, sizeof(_h)); } void read(std::ifstream& f) { f.read((char*)&soundOn, sizeof(soundOn)); f.read((char*)&_w, sizeof(_w)); f.read((char*)&_h, sizeof(_h)); } private: bool soundOn; int _w; int _h; };
package de.westermann.kobserve.property import de.westermann.kobserve.base.ObservableProperty import de.westermann.kobserve.base.ObservableValue import kotlin.math.pow import kotlin.test.Test import kotlin.test.assertEquals class FlatMappingObservablePropertyTest { @Test fun flatReceiverTest() { val personProperty = property(Person("John", "Doe", 21)) var person by personProperty val firstNameProperty = personProperty.flatMapMutableBinding(Person::firstNameProperty) val lastNameProperty = personProperty.flatMapBinding(Person::lastNameProperty) val age2xProperty = personProperty.flatMapMutableBinding { it.getAgeMultiplier(2) } val age4xProperty = personProperty.flatMapBinding { it.getAgeMultiplier(4) } val agePowerProperty = personProperty.flatMapBinding { it.getAgeReader(2.0) } assertEquals(person.age * 2, age2xProperty.value) assertEquals(person.age * 4, age4xProperty.value) var firstName by firstNameProperty val lastName by lastNameProperty var age2x by age2xProperty val agePower by agePowerProperty person.age = 22 assertEquals("Doe", lastNameProperty.value) assertEquals("Doe", lastName) assertEquals(person.age * 2, age2xProperty.value) assertEquals(person.age * 2, age2x) assertEquals(person.age * 4, age4xProperty.value) assertEquals(person.age.toDouble().pow(2.0), agePowerProperty.value) assertEquals(person.age.toDouble().pow(2.0), agePower) person = Person("Max", "Mustermann", 25) assertEquals("Max", firstNameProperty.value) assertEquals("Max", firstName) firstName = "Maxa" firstNameProperty.value = "Maxa" assertEquals("Maxa", firstName) assertEquals(person.age * 2, age2xProperty.value) assertEquals(person.age * 4, age4xProperty.value) age2xProperty.value = 26 age2x = 26 assertEquals(13, person.age) assertEquals(52, age4xProperty.value) assertEquals(26, age2x) assertEquals(13.0.pow(2.0), agePowerProperty.value) } @Test fun nullableFlatReceiverTest() { val personProperty = property<Person?>(Person("John", "Doe", 21)) var person by personProperty val firstNameProperty = personProperty.nullableFlatMapBinding(Person::firstNameProperty) val lastNameProperty = personProperty.nullableFlatMapBinding { it?.lastNameProperty } val age2xProperty = personProperty.nullableFlatMapBinding { it?.getAgeMultiplier(2) } val age4xProperty = personProperty.nullableFlatMapBinding { it?.getAgeMultiplier(4) } val agePowerProperty = personProperty.nullableFlatMapBinding { it?.getAgeReader(2.0) } assertEquals((person?.age ?: -1) * 2, age2xProperty.value) assertEquals((person?.age ?: -1) * 4, age4xProperty.value) val firstName by firstNameProperty val lastName by lastNameProperty val age2x by age2xProperty val agePower by agePowerProperty person?.age = 22 assertEquals("Doe", lastNameProperty.value) assertEquals("Doe", lastName) assertEquals((person?.age ?: -1) * 2, age2xProperty.value) assertEquals((person?.age ?: -1) * 2, age2x) assertEquals((person?.age ?: -1) * 4, age4xProperty.value) assertEquals((person?.age ?: -1).toDouble().pow(2.0), agePowerProperty.value) assertEquals((person?.age ?: -1).toDouble().pow(2.0), agePower) person = Person("Max", "Mustermann", 25) assertEquals("Max", firstNameProperty.value) assertEquals("Max", firstName) person?.firstName = "Maxa" person?.firstNameProperty?.value = "Maxa" assertEquals("Maxa", firstName) assertEquals((person?.age ?: -1) * 2, age2xProperty.value) assertEquals((person?.age ?: -1) * 4, age4xProperty.value) person?.getAgeMultiplier(2)?.value = 26 assertEquals(13, person?.age) assertEquals(52, age4xProperty.value) assertEquals(26, age2x) assertEquals(13.0.pow(2.0), agePowerProperty.value) } class Person( firstName: String, lastName: String, age: Int ) { val firstNameProperty = property(firstName) var firstName by firstNameProperty val lastNameProperty: ObservableValue<String> = property(lastName) val lastName by lastNameProperty private val ageProperty = property(age) var age by ageProperty fun getAgeMultiplier(factor: Int): ObservableProperty<Int> { return property(object : DelegatePropertyAccessor<Int> { override fun set(value: Int) { ageProperty.value = value / factor } override fun get(): Int { return ageProperty.value * factor } }, ageProperty) } fun getAgeReader(power: Double): ObservableValue<Double> { return ageProperty.mapBinding { it.toDouble().pow(power) } } } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class PromotionLog extends Model { use softDeletes; protected $fillable = [ 'employee_id', 'grade_code', 'grade_name','position','valid_from','valid_to', 'created_by' ]; public function user() { return $this->belongsTo('App\User', 'created_by')->withTrashed(); } }
# frozen_string_literal: true module XitoliteRepositoryFinder extend ActiveSupport::Concern def find_xitolite_repository @repository = Repository::Xitolite.find find_repository_param rescue ActiveRecord::RecordNotFound render_404 else @project = @repository.project render_404 if @project.nil? end def find_xitolite_repository_by_path repo_path = "#{params[:repo_path]}.git" repository = Repository::Xitolite.find_by_path repo_path, loose: true if repository.nil? RedmineGitHosting.logger.error "GoRedirector : repository not found at path : '#{repo_path}'," \ ' exiting!' render_404 elsif !repository.go_access_available? RedmineGitHosting.logger.error "GoRedirector : GoAccess is disabled for this repository '#{repository.gitolite_repository_name}'," \ ' exiting!' render_403 else RedmineGitHosting.logger.info "GoRedirector : access granted for repository '#{repository.gitolite_repository_name}'" @repository = repository end end end
package io.udash package rest.raw import com.avsystem.commons.serialization.GenCodec import com.avsystem.commons.serialization.json.RawJson /** * Value used as encoding of [[io.udash.rest.Body Body]] parameters of * [[io.udash.rest.JsonBody JsonBody]] methods. Wrapped value MUST be a valid JSON. */ final case class JsonValue(value: String) extends AnyVal object JsonValue extends (String => JsonValue) { implicit val codec: GenCodec[JsonValue] = GenCodec.create( i => JsonValue(i.readCustom(RawJson).getOrElse(i.readSimple().readString())), (o, v) => if (!o.writeCustom(RawJson, v.value)) o.writeSimple().writeString(v.value) ) }
import unittest from katas.beta.list_length_v1 import count class ListLengthTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(count([1, 2, 3, 4]), 4) def test_equals_2(self): self.assertEqual(count([1, 2, 3, 4, 5, 6, 7]), 7)
namespace MediaManager.Media { public interface IMediaExtractorProvider { } }
{-# LANGUAGE OverloadedStrings #-} module SMSAPI.Config (apiCfg) where import System.Directory import System.FilePath.Posix import System.Exit (exitFailure) import qualified Data.Text.IO as TIO import SMSAPI.Types import Data.Ini.Config iniParser :: IniParser APICfg iniParser = section "api" $ APICfg <$> field "user" <*> field "password" parseAPICfg :: FilePath -> IO (Either String APICfg) parseAPICfg fpath = do rs <- TIO.readFile fpath return $ parseIniFile rs iniParser apiCfg :: IO APICfg apiCfg = do hom <- getHomeDirectory let homPth = hom </> ".smsgwapi.conf" tst <- doesFileExist homPth case tst of False -> putStrLn "No config found, please create ~/.smsgwapi.conf" >> exitFailure True -> do res <- parseAPICfg homPth case res of Left err -> putStrLn ("Unable to parse config: " ++ err) >> exitFailure Right cfg -> return cfg
[Back to Guides](../README.md) # Configuration Options You can configure options in **config/secrets.yml** | Option | Definition | |----|----| | `oauth_github_id` | ID of GITHUB application | | `oauth_github_secret` | SECRET of GITHUB application | | `oauth_gitlab_id` | ID of GITLAB application | | `oauth_gitlab_secret` | SECRET of GITLAB application | | `devise_mailer_host` | host for mailer (localhost) | | `devise_mailer_port` | port for mailer(3000) | | `devise_mailer_address` | mailer address (exchange@manageiq.org) |
package machine import ( "runtime/volatile" ) const bufferSize = 128 // RingBuffer is ring buffer implementation inspired by post at // https://www.embeddedrelated.com/showthread/comp.arch.embedded/77084-1.php type RingBuffer struct { rxbuffer [bufferSize]volatile.Register8 head volatile.Register8 tail volatile.Register8 } // NewRingBuffer returns a new ring buffer. func NewRingBuffer() *RingBuffer { return &RingBuffer{} } // Used returns how many bytes in buffer have been used. func (rb *RingBuffer) Used() uint8 { return uint8(rb.head.Get() - rb.tail.Get()) } // Put stores a byte in the buffer. If the buffer is already // full, the method will return false. func (rb *RingBuffer) Put(val byte) bool { if rb.Used() != bufferSize { rb.head.Set(rb.head.Get() + 1) rb.rxbuffer[rb.head.Get()%bufferSize].Set(val) return true } return false } // Get returns a byte from the buffer. If the buffer is empty, // the method will return a false as the second value. func (rb *RingBuffer) Get() (byte, bool) { if rb.Used() != 0 { rb.tail.Set(rb.tail.Get() + 1) return rb.rxbuffer[rb.tail.Get()%bufferSize].Get(), true } return 0, false }
DROP TABLE IF EXISTS atcoder; CREATE TABLE atcoder ( id SERIAL, name VARCHAR(255) NOT NULL, start_time TIMESTAMP WITH TIME ZONE NOT NULL, end_time TIMESTAMP WITH TIME ZONE NOT NULL, range VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); DROP TABLE IF EXISTS codeforces; CREATE TABLE codeforces ( id SERIAL, name VARCHAR(255) NOT NULL, start_time TIMESTAMP WITH TIME ZONE NOT NULL, end_time TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (id) ); DROP TABLE IF EXISTS yukicoder; CREATE TABLE yukicoder ( id SERIAL, name VARCHAR(255) NOT NULL, start_time TIMESTAMP WITH TIME ZONE NOT NULL, end_time TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (id) );
import React from 'react'; import PropTypes from 'prop-types'; import Ripple from 'material-ripple-effects'; const colors = { white: 'bg-white', blueGray: 'bg-blue-gray-500', gray: 'bg-gray-700', brown: 'bg-brown-500', deepOrange: 'bg-deep-orange-500', orange: 'bg-orange-500', amber: 'bg-amber-500', yellow: 'bg-yellow-600', lime: 'bg-lime-500', lightGreen: 'bg-light-green-500', green: 'bg-green-500', teal: 'bg-teal-500', cyan: 'bg-cyan-500', lightBlue: 'bg-light-blue-500', blue: 'bg-blue-500', indigo: 'bg-indigo-500', deepPurple: 'bg-deep-purple-500', purple: 'bg-purple-500', pink: 'bg-pink-500', red: 'bg-red-500', }; const bgHoverColors = { white: 'hover:bg-white hover:bg-opacity-20', blueGray: 'hover:bg-blue-gray-50', gray: 'hover:bg-gray-50', brown: 'hover:bg-brown-50', deepOrange: 'hover:bg-deep-orange-50', orange: 'hover:bg-orange-50', amber: 'hover:bg-amber-50', yellow: 'hover:bg-yellow-50', lime: 'hover:bg-lime-50', lightGreen: 'hover:bg-light-green-50', green: 'hover:bg-green-50', teal: 'hover:bg-teal-50', cyan: 'hover:bg-cyan-50', lightBlue: 'hover:bg-light-blue-50', blue: 'hover:bg-blue-50', indigo: 'hover:bg-indigo-50', deepPurple: 'hover:bg-deep-purple-50', purple: 'hover:bg-purple-50', pink: 'hover:bg-pink-50', red: 'hover:bg-red-50', }; export default function NavbarToggler({ color, ripple, ...rest }) { const rippleEffect = new Ripple(); return ( <button {...rest} className={`cursor-pointer text-xl leading-none py-1 px-1.5 rounded-full border border-solid border-transparent bg-transparent block lg:hidden outline-none focus:outline-none ${bgHoverColors[color]} transition-all duration-300`} type="button" onMouseUp={(e) => { ripple === 'dark' && rippleEffect.create(e, 'dark'); ripple === 'light' && rippleEffect.create(e, 'light'); }} > <span className={`block relative w-6 h-px rounded-sm ${colors[color]}`} ></span> <span className={`block relative w-6 h-px rounded-sm ${colors[color]} mt-1`} ></span> <span className={`block relative w-6 h-px rounded-sm ${colors[color]} mt-1`} ></span> </button> ); } NavbarToggler.defaultProps = { color: 'white', }; NavbarToggler.propTypes = { color: PropTypes.string.isRequired, ripple: PropTypes.string, };
<?php declare(strict_types=1); namespace Kerox\Tmdb\Tests\Api; class TvEpisodesTest extends AbstractApiTest { public function testGet(): void { $response = $this->tmdb->tvEpisodes()->get(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetChanges(): void { $response = $this->tmdb->tvEpisodes()->changes(283988); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetCredits(): void { $response = $this->tmdb->tvEpisodes()->credits(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetExternalIds(): void { $response = $this->tmdb->tvEpisodes()->externalIds(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetImages(): void { $response = $this->tmdb->tvEpisodes()->images(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetTranslations(): void { $response = $this->tmdb->tvEpisodes()->translations(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } public function testGetVideos(): void { $response = $this->tmdb->tvEpisodes()->videos(4087, 1, 1); self::assertSame(200, $response->getStatusCode()); self::assertNotEmpty($response->getBody()->getContents()); } }
/* * Copyright 2017 Australian Digital Health Agency (The Agency) * * Licensed under the Agency’s Open Source (Apache) License; you may not use this * file except in compliance with the License. A copy of the License is in the * ' Source Code Licence and Production Disclaimer.txt' file, which should be * provided with this work. * * 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. */ namespace DigitalHealth.MhrFhirClient.Model { /// <summary> /// Refer to class code table for possible values. /// </summary> public class ClassCode { /// <summary> /// Gets or sets the code. /// </summary> /// <value> /// code. /// </value> public string Code { get; set; } /// <summary> /// Gets or sets the code system. /// </summary> /// <value> /// code system. /// </value> public string CodeSystem { get; set; } /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return $"{Code}^^{CodeSystem}"; } } }
import React, { useState } from 'react'; import { view, store } from '@risingstack/react-easy-state'; import { Collapse, Select } from 'antd'; import { SettingOutlined } from '@ant-design/icons'; import Setting_base from './SettingBarRight/Setting_base'; import Setting_Layout from './SettingBarRight/Setting_Layout'; import { Store_PageOnglets } from './NavigatorTop'; import { Store_layouts } from './ContentPage/PageType_Layout/Layouts'; import Settings from './SettingBarRight/Settings'; import { Store_Grids } from './ContentPage/PageType_Layout/Grids'; const { Panel } = Collapse; const { Option } = Select; function callback(key) { console.log(key); } const text = ` A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world. `; const genExtra = () => ( <SettingOutlined onClick={(event) => { // If you don't want click extra trigger collapse, you can prevent this: event.stopPropagation(); }} /> ); class SettingBarRight extends React.Component { state = { expandIconPosition: 'left', }; onPositionChange = (expandIconPosition) => { this.setState({ expandIconPosition }); }; render() { const { expandIconPosition } = this.state; const { id } = Store_PageOnglets.getCurrentSelected(); // on extract le id (root) de la page afficher return ( <div style={{ width: '0px', minWidth: '100%', height: '0px', minHeight: '100%', overflow: 'auto', }} > <Collapse defaultActiveKey={['0']} onChange={callback} expandIconPosition={expandIconPosition} > <Panel header='Page Settings' key='0' extra={genExtra()}> {/* <Setting_Layout /> */} Global page Setting ? *onglet icon, *preset *min zoom *max zoom *min height *... other shit </Panel> {id && ( <Panel header='Layout Settings' key='1' extra={genExtra()}> {/* <Setting_Layout id={id} /> */} </Panel> )} {Store_Grids._selectedId && ( <Panel header='Selected Settings' key='2' extra={genExtra()}> <Settings id={Store_Grids._selectedId} /> </Panel> )} </Collapse> <br /> <span>Expand Icon Position: </span> <Select value={expandIconPosition} onChange={this.onPositionChange}> <Option value='left'>left</Option> <Option value='right'>right</Option> </Select> </div> ); } } export default view(SettingBarRight);
using System; namespace GraphQLCore.Execution { public interface IContext<T> { T Instance { get; } } }
import React from 'react' import * as R from 'ramda' import * as NodeDef from '@core/survey/nodeDef' import * as NodeDefLayout from '@core/survey/nodeDefLayout' import { NumberFormats } from '@webapp/components/form/Input' import NodeDefEntitySwitch from './components/types/nodeDefEntitySwitch' import NodeDefFile from './components/types/nodeDefFile' import NodeDefTaxon from './components/types/nodeDefTaxon' import NodeDefCoordinate from './components/types/nodeDefCoordinate' import NodeDefCode from './components/types/NodeDefCode' import NodeDefBoolean from './components/types/nodeDefBoolean' import NodeDefText from './components/types/nodeDefText' const { integer, decimal, text, date, time, boolean, code, coordinate, taxon, file, entity } = NodeDef.nodeDefType const propsUI = { [integer]: { icon: <span className="icon-left node_def__icon">123</span>, numberFormat: NumberFormats.integer(), defaultValue: '', }, [decimal]: { icon: <span className="icon-left node_def__icon">1.23</span>, numberFormat: NumberFormats.decimal(), defaultValue: '', }, [text]: { icon: ( <span className="icon-left display-flex"> {R.range(0, 3).map((i) => ( <span key={i} className="icon icon-text-color" style={{ margin: '0 -3px' }} /> ))} </span> ), defaultValue: '', }, [date]: { icon: <span className="icon icon-calendar icon-left" />, numberFormat: NumberFormats.date(), defaultValue: '', }, [time]: { icon: <span className="icon icon-clock icon-left" />, numberFormat: NumberFormats.time(), defaultValue: '', }, [boolean]: { component: NodeDefBoolean, icon: <span className="icon icon-radio-checked2 icon-left" />, defaultValue: '', }, [code]: { component: NodeDefCode, icon: <span className="icon icon-list icon-left" />, defaultValue: '', defaultProps: (cycle) => ({ [NodeDefLayout.keys.layout]: NodeDefLayout.newLayout(cycle, NodeDefLayout.renderType.dropdown), }), }, [coordinate]: { component: NodeDefCoordinate, icon: <span className="icon icon-location2 icon-left" />, defaultValue: { x: '', y: '', srs: '' }, formFields: [ { field: 'x', labelKey: 'surveyForm.nodeDefCoordinate.x' }, { field: 'y', labelKey: 'surveyForm.nodeDefCoordinate.y' }, { field: 'srs', labelKey: 'common.srs' }, ], }, [taxon]: { component: NodeDefTaxon, icon: <span className="icon icon-leaf icon-left" />, defaultValue: { taxonUuid: null, vernacularNameUuid: null, }, formFields: [ { field: 'code', labelKey: 'common.code' }, { field: 'scientific_name', labelKey: 'surveyForm.nodeDefTaxon.scientificName', }, { field: 'vernacular_name', labelKey: 'surveyForm.nodeDefTaxon.vernacularName', }, ], }, [file]: { component: NodeDefFile, icon: <span className="icon icon-file-picture icon-left" />, validations: false, }, [entity]: { component: NodeDefEntitySwitch, icon: <span className="icon icon-table2 icon-left" />, defaultProps: (cycle) => ({ [NodeDef.propKeys.multiple]: true, [NodeDefLayout.keys.layout]: NodeDefLayout.newLayout(cycle, NodeDefLayout.renderType.table), }), }, } const getPropByType = (prop, defaultValue = null) => (nodeDefType) => R.pathOr(defaultValue, [nodeDefType, prop], propsUI) const getProp = (prop, defaultValue = null) => R.pipe(NodeDef.getType, getPropByType(prop, defaultValue)) export const getIconByType = getPropByType('icon') export const getNumberFormat = (nodeDef) => NodeDef.isDecimal(nodeDef) ? NumberFormats.decimal({ decimalScale: NodeDef.getMaxNumberDecimalDigits(nodeDef) }) : getProp('numberFormat')(nodeDef) export const getComponent = getProp('component', NodeDefText) export const getFormFields = getProp('formFields', ['field']) export const getDefaultValue = getProp('defaultValue') export const getValidationsEnabledByType = getPropByType('validations', true) export const getDefaultPropsByType = (type, cycle) => { const fn = getPropByType('defaultProps')(type) return fn ? fn(cycle) : {} }
unit uModeloBaseDados; interface uses SysUtils, Classes, FMTBcd, DB, FireDAC.Comp.Client; type TDSServerModuleBaseDados = class(TDataModule) FCONEXAO: TFDConnection; FQueryGeral: TFDQuery; private public function Conectar:boolean; function Desconectar:boolean; function GetDataSet(AQuery: string): TFDQuery; function ExecSql(AQuery: string): boolean; end; var DSServerModuleBaseDados: TDSServerModuleBaseDados; implementation {$R *.dfm} function TDSServerModuleBaseDados.Conectar:boolean; begin try FCONEXAO.Connected := true; Result := true; except Result := false; end; end; function TDSServerModuleBaseDados.Desconectar:boolean; begin try FCONEXAO.Connected := false; Result := true; except Result := false; end; end; function TDSServerModuleBaseDados.GetDataSet(AQuery: string): TFDQuery; begin FQueryGeral.Close; FQueryGeral.Params.Clear; FQueryGeral.SQL.Text := AQuery; FQueryGeral.Open; Result := FQueryGeral; end; function TDSServerModuleBaseDados.ExecSql(AQuery: string): boolean; begin Result := false; if FQueryGeral.Active then FQueryGeral.Close; FQueryGeral.SQL.Text := AQuery; try FQueryGeral.ExecSQL; Result := true; except on e: Exception do begin raise Exception.Create(e.Message); end; end; end; end.
Prerequisite ============ * `mvn install` my [Spring Boot gRPC Starter](https://github.com/saturnism/spring-boot-starter-grpc) Build ===== * `mvn install` Run === 1. Start Eureka: `java -jar eureka-server/target/eureka-server-1.0-SNAPSHOT.jar` 1. Start gRPC Server #1: `java -jar grpc-server/target/springboot-grpc-server-1.0-SNAPSHOT.jar --server.port=9090` 1. Start gRPC Server #2: `java -jar grpc-server/target/springboot-grpc-server-1.0-SNAPSHOT.jar --server.port=9091` 1. Start gRPC Client: `java -jar target/springboot-grpc-client-1.0-SNAPSHOT.jar`
// --------------------------------------------------------------------------- // File name: Armor.java // Project name: Game Project // --------------------------------------------------------------------------- // Creator’s name and email: Roberto Hernandez, hernandezr@etsu.edu // Course-Section: CSCI-1260-900 // Creation Date: 10-13-2020 // Date of Last Modification: 10-19-2020 // --------------------------------------------------------------------------- /** * Class Name: Armor <br> * Class Purpose: creates Armor object, extends Equipment class<br> * * <hr> * Date created: 10-13-2020 * Date last modified: 10-13-2020 * @author Roberto Hernandez */ public class Armor extends Equipment { private int armorBonus; private boolean acidProtection; private boolean fireProtection; /** * Method Name: Armor <br> * Method Purpose: parameterized constructor <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> */ public Armor(String name, int armorBonus, boolean acidProtection, boolean fireProtection) { super(name, 150 ,.8); this.armorBonus = armorBonus; this.acidProtection = acidProtection; this.fireProtection = fireProtection; this.setPrice(150); this.setDurability(0.8); } /** * Method Name: getName <br> * Method Purpose: return name of Armor <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> * @return name */ @Override public String getName() { String modifiedName = super.getName(); if(acidProtection && fireProtection) { return modifiedName + " of Environmental Protection"; } if(acidProtection) { return modifiedName + " of Ice Protection"; } if(fireProtection) { return modifiedName + " of Fire Protection"; } return modifiedName; } /** * Method Name: getArmorBonus <br> * Method Purpose: return armor bonus modifier <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> * @return armor bonus */ public int getArmorBonus() { return armorBonus; } /** * Method Name: hasFireProtection <br> * Method Purpose: return boolean for fire protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> * @return fire protection boolean */ public boolean hasFireProtection() { return fireProtection; } /** * Method Name: hasIceProtection <br> * Method Purpose: return boolean for ice protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> * @return ice protection boolean */ public boolean hasAcidProtection() { return acidProtection; } /** * Method Name: activateFireProtection <br> * Method Purpose: activates fire protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> */ public void activateFireProtection() { fireProtection = true; } /** * Method Name: activateIceProtection <br> * Method Purpose: activates ice protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> */ public void activateAcidProtection() { acidProtection = true; } /** * Method Name: deactivateFireProtection <br> * Method Purpose: deactivates fire protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> */ public void deactivateFireProtection() { fireProtection = false; } /** * Method Name: deactivateIceProtection <br> * Method Purpose: deactivates ice protection <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> */ public void deactivateAcidProtection() { acidProtection = false; } /** * Method Name: toString <br> * Method Purpose: displays object <br> * * <hr> * Date created: 10-13-2020 <br> * Date last modified: 10-13-2020 <br> * @return object */ @Override public String toString() { return "{name:" + "\"" + getName() + "\"" + ", " + "price:" + getPrice() + ", " + "durability:" + "\"" + getDurabilityStatus() + "\"" + ", " + "acid:" + acidProtection + ", " + "fire:" + fireProtection + "}"; } public boolean use(Actor actor) { actor.equip(this); return true; } }
<head> <link rel='stylesheet' href='/v6/css/experience.css'> <script src='/v6/js/experience.js'></script> </head> <section id='experience' class='home-section'> <div id='timeline'> <div id='line'></div> <template id='timeline-block'> <img class='job' src=''> </template> </div> <div id='job-window'> <div id='job-text'> <h3 id='job-title'></h3> <div class='job-details'> <?php echo file_get_contents('img/map_pin.svg'); ?> <h6 id='job-location'></h6> </div> <div class='job-details'> <?php echo file_get_contents('img/calendar.svg'); ?> <h6 id='job-time'></h6> </div> <ul id='job-description'></ul> </div> </div> <template id='company'> <a href=''><span id='job-company'></span></a> </template> <template id='job-bullet'> <li><p>Work</p></li> </template> </section>
(define-resource complaint-form () :class (s-prefix "ext:ComplaintForm") :properties `((:name :string ,(s-prefix "foaf:name")) (:contact-person-name :string ,(s-prefix "ext:personName")) (:street :string ,(s-prefix "schema:streetAddress")) (:house-number :number ,(s-prefix "schema:postOfficeBoxNumber")) (:address-complement :string ,(s-prefix "ext:addressComplement")) (:locality :string ,(s-prefix "schema:addressLocality")) (:postal-code :number ,(s-prefix "schema:postalCode")) (:telephone :string ,(s-prefix "schema:telephone")) (:email :string ,(s-prefix "schema:email")) (:content :string ,(s-prefix "ext:content")) (:created :datetime ,(s-prefix "dct:created")) (:is-converted-to-email :string ,(s-prefix "ext:isConvertedIntoEmail"))) :has-many `((file :via ,(s-prefix "nmo:hasAttachment") :as "attachments")) :resource-base (s-url "http://data.lblod.info/complaint-forms/") :on-path "complaint-forms")
<?php namespace App\Http\Controllers; use App\Models\Order; use App\Exports\OrderMultipleExport; use App\Exports\OrderExport; use Illuminate\Http\Request; use App\Notifications\OrderDelivery; use Maatwebsite\Excel\Facades\Excel; class OrderController extends Controller { // public function delivery($id) { $order = Order::findOrFail($id); if ($order->is_shipped) { return response(['result' => false]); }else{ $order->update(['result' => true]); // User 本身就有引入 notification,使用推撥函式 notify(),new OrderDelivery 需要引入要檢查一下 $order->user->notify(new OrderDelivery); return response(['result' => true]); } } public function export() { // 第二個參數是檔案名稱 return Excel::download(new OrderExport, 'orders.xlsx'); } public function exportByShipped() { // 第二個參數是檔案名稱 return Excel::download(new OrderMultipleExport, 'orders_by_shipped.xlsx'); } }
-- Creation Date: 2021-04-06 -- Description: telegram chat id added to notification config alter table notification_configs add column telegram_chat_id integer;
#!/usr/bin/perl -w # use strict; use Digest::MD5; use Time::HiRes qw( time gettimeofday tv_interval ); $| = 1; #The URI paths in the DB are: # my $db_root = "/usr/local/apps/ncia/CTP-server/CTP"; # my $fs_root = "/mnt/erlbluearc/systems/cipa-images"; #/usr/local/apps/ncia/CTP-server/CTP/storage #/usr/local/apps/ncia/CTP-server/CTP/storage-acrin # #These map to: #/mnt/erlbluearc/systems/public-lss/data/storage #/mnt/erlbluearc/systems/public-lss/data/storage-acrin # # my $db_root = "/usr/local/apps/ncia/CTP-server/CTP"; my $fs_root = "/mnt/erlbluearc/systems/cipa-images"; my $t0 = [gettimeofday]; while(my $line = <STDIN>){ chomp $line; my($path, $md5, $db_size, $day_time) = split(/\|/, $line); my $l_md5 = length($md5); if($l_md5 < 32){ $md5 = ("0" x (32 - $l_md5)) . $md5; } my $file = $path; $file =~ s/$db_root/$fs_root/o; my($digest, $dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks, $md5_match, $size_match); if(-f $file){ my $ctx = Digest::MD5->new; open FILE, "<$file"; $ctx->addfile(*FILE); close FILE; $digest = $ctx->hexdigest; ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file); $md5_match = ($digest eq $md5) ? "Y" : "N"; $size_match = ($size == $db_size) ? "Y" : "N"; } else { $digest = "-" x 32; $md5_match = "N"; $size_match = "N"; $size = 0; $mtime = "---"; } print "$file|$digest|$size|$md5_match|$size_match|$mtime\n"; }
require 'coveralls' require 'simplecov' if RUBY_ENGINE == 'ruby' if Coveralls.should_run? Coveralls.wear! else SimpleCov.start end end require 'phonetic' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus config.order = 'random' end
package roth.lib.java.mapper; import java.util.Map.Entry; import roth.lib.java.Characters; import roth.lib.java.deserializer.Deserializer; import roth.lib.java.lang.Map; import roth.lib.java.serializer.Serializer; import roth.lib.java.time.TimeZone; import roth.lib.java.util.IdUtil; public class MapperConfig implements Characters { protected static MapperConfig instance; protected boolean serializeNulls = false; protected boolean serializeEmptyArray = true; protected boolean serializeEmptyMap = true; protected boolean tableHeader = true; protected boolean tableTrim = true; protected boolean deserializeColumnOrder = true; protected char delimiter = COMMA; protected char qualifier = QUOTE; protected Map<Class<?>, Serializer<?>> serializerMap = new Map<Class<?>, Serializer<?>>(); protected Map<Class<?>, Deserializer<?>> deserializerMap = new Map<Class<?>, Deserializer<?>>(); protected boolean writeXmlHeader = true; protected String boundary = IdUtil.random(10); protected TimeZone timeZone = TimeZone.DEFAULT; public MapperConfig() { } public static MapperConfig get() { if(instance == null) { instance = new MapperConfig(); } return instance; } public static void set(MapperConfig mapperConfig) { instance = mapperConfig; } public boolean isSerializeNulls() { return serializeNulls; } public boolean isSerializeEmptyArray() { return serializeEmptyArray; } public boolean isSerializeEmptyMap() { return serializeEmptyMap; } public boolean isTableHeader() { return tableHeader; } public boolean isTableTrim() { return tableTrim; } public boolean isDeserializeColumnOrder() { return deserializeColumnOrder; } public char getDelimiter() { return delimiter; } public char getQualifier() { return qualifier; } public boolean isWriteXmlHeader() { return writeXmlHeader; } public String getBoundary() { return boundary; } public Serializer<?> getSerializer(Class<?> klass) { Serializer<?> serializer = serializerMap.get(klass); if(serializer == null) { for(Entry<Class<?>, Serializer<?>> serializerEntry : serializerMap.entrySet()) { if(serializerEntry.getKey().isAssignableFrom(klass)) { serializer = serializerEntry.getValue(); break; } } } return serializer; } public boolean isSerializable(Class<?> klass) { return getSerializer(klass) != null; } public Deserializer<?> getDeserializer(Class<?> klass) { Deserializer<?> deserializer = deserializerMap.get(klass); if(deserializer == null) { if(Enum.class.isAssignableFrom(klass)) { deserializer = deserializerMap.get(Enum.class); } } return deserializer; } public MapperConfig setSerializeNulls(boolean serializeNulls) { this.serializeNulls = serializeNulls; return this; } public MapperConfig setSerializeEmptyArray(boolean serializeEmptyArray) { this.serializeEmptyArray = serializeEmptyArray; return this; } public MapperConfig setSerializeEmptyMap(boolean serializeEmptyMap) { this.serializeEmptyMap = serializeEmptyMap; return this; } public MapperConfig setTableHeader(boolean tableHeader) { this.tableHeader = tableHeader; return this; } public MapperConfig setTableTrim(boolean tableTrim) { this.tableTrim = tableTrim; return this; } public MapperConfig setDeserializeColumnOrder(boolean deserializeColumnOrder) { this.deserializeColumnOrder = deserializeColumnOrder; return this; } public MapperConfig setDelimiter(Character delimiter) { this.delimiter = delimiter; return this; } public MapperConfig setQualifier(Character qualifier) { this.qualifier = qualifier; return this; } public MapperConfig setWriteXmlHeader(boolean writeXmlHeader) { this.writeXmlHeader = writeXmlHeader; return this; } public MapperConfig setBoundary(String boundary) { this.boundary = boundary; return this; } public <T> MapperConfig putSerializer(Class<T> klass, Serializer<T> serializer) { serializerMap.put(klass, serializer); return this; } public <T> MapperConfig putDeserializer(Class<T> klass, Deserializer<T> deserializer) { deserializerMap.put(klass, deserializer); return this; } public TimeZone getTimeZone() { return timeZone; } public MapperConfig setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; return this; } }
SECTION code_l PUBLIC l_small_utob l_small_utob: ; write unsigned binary number to ascii buffer ; ; enter : hl = unsigned integer ; de = char *buffer ; carry set to write leading zeroes ; ; exit : de = char *buffer (one byte past last char written) ; carry set if in write loop ; ; uses : af, b, de, hl ld b,16 jr c, leading_zeroes no_leading_zeroes: add hl,hl jr c, write djnz no_leading_zeroes ld a,'0' ld (de),a inc de ret leading_zeroes: add hl,hl write: ld a,'0' adc a,0 ld (de),a inc de djnz leading_zeroes scf ret
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.dialogue.core; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.codahale.metrics.Gauge; import com.google.common.util.concurrent.SettableFuture; import com.palantir.dialogue.Channel; import com.palantir.dialogue.Endpoint; import com.palantir.dialogue.Request; import com.palantir.dialogue.Response; import com.palantir.logsafe.exceptions.SafeIoException; import com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry; import com.palantir.tritium.metrics.registry.MetricName; import com.palantir.tritium.metrics.registry.TaggedMetricRegistry; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class ConcurrencyLimitedChannelTest { @Mock private Endpoint endpoint; @Mock private Request request; @Mock private Channel delegate; @Mock private AimdConcurrencyLimiter mockLimiter; @Spy private AimdConcurrencyLimiter.Permit permit = new AimdConcurrencyLimiter().acquire().get(); @Mock private Response response; private final TaggedMetricRegistry metrics = new DefaultTaggedMetricRegistry(); private ConcurrencyLimitedChannel channel; private SettableFuture<Response> responseFuture; @BeforeEach public void before() { channel = new ConcurrencyLimitedChannel( new ChannelToLimitedChannelAdapter(delegate), mockLimiter, "channel", 0, metrics); responseFuture = SettableFuture.create(); lenient().when(delegate.execute(endpoint, request)).thenReturn(responseFuture); } @Test public void testLimiterAvailable_successfulRequest() { mockLimitAvailable(); mockResponseCode(200); assertThat(channel.maybeExecute(endpoint, request)).contains(responseFuture); verify(permit).success(); } @Test public void testLimiterAvailable_429isDropped() { mockLimitAvailable(); mockResponseCode(429); assertThat(channel.maybeExecute(endpoint, request)).contains(responseFuture); verify(permit).dropped(); } @Test public void testLimiterAvailable_runtimeExceptionIsIgnored() { mockLimitAvailable(); responseFuture.setException(new IllegalStateException()); assertThat(channel.maybeExecute(endpoint, request)).contains(responseFuture); verify(permit).ignore(); } @Test public void testLimiterAvailable_ioExceptionIsDropped() { mockLimitAvailable(); responseFuture.setException(new SafeIoException("failure")); assertThat(channel.maybeExecute(endpoint, request)).contains(responseFuture); verify(permit).dropped(); } @Test public void testUnavailable() { mockLimitUnavailable(); assertThat(channel.maybeExecute(endpoint, request)).isEmpty(); verifyNoMoreInteractions(permit); } @Test public void testWithDefaultLimiter() { channel = new ConcurrencyLimitedChannel( new ChannelToLimitedChannelAdapter(delegate), ConcurrencyLimitedChannel.createLimiter(), "channel", 0, metrics); assertThat(channel.maybeExecute(endpoint, request)).contains(responseFuture); } @Test void testGauges() { when(mockLimiter.getLimit()).thenReturn(21); assertThat(getMax()).isEqualTo(21); } private void mockResponseCode(int code) { when(response.code()).thenReturn(code); responseFuture.set(response); } private void mockLimitAvailable() { when(mockLimiter.acquire()).thenReturn(Optional.of(permit)); } private void mockLimitUnavailable() { when(mockLimiter.acquire()).thenReturn(Optional.empty()); } private Number getMax() { MetricName metricName = MetricName.builder() .safeName("dialogue.concurrencylimiter.max") .putSafeTags("channel-name", "channel") .putSafeTags("hostIndex", "0") .build(); assertThat(metrics.getMetrics().keySet()).contains(metricName); Gauge<Object> gauge = metrics.gauge(metricName).get(); return (Number) gauge.getValue(); } }
package password import ( "log" "time" argonpass "github.com/dwin/goArgonPass" ) // HashPassword attempts to hash the supplied password func HashPassword(password string) (string, error) { // debug check time start := time.Now() hash, err := argonpass.Hash(password, &argonpass.ArgonParams{ Time: 15, Memory: 48 * 1024, Parallelism: 2, OutputSize: 1, Function: "argon2id", SaltSize: 8, }) elapsed := time.Since(start) log.Printf("Password hash took %s", elapsed) return hash, err }
# ulog server ulog server - маленькое обособленное дополнение для проектов unity3d, позволяющее в редакторе и билде направлять сообщения стандартного лога unity по сети в указанный порт. для выбора порта используйте параметр запуска **--log-server-port (port)**
import 'dart:async'; import 'package:flutter/material.dart'; /// SBB Toast. Use according to documentation. /// /// See also: /// /// * <https://digital.sbb.ch/de/design-system-mobile-new/module/toast> class SBBToast { SBBToast._(this._overlayState); static const durationShort = const Duration(milliseconds: 2000); static const durationLong = const Duration(milliseconds: 3500); static const defaultBottom = 30.0; final OverlayState _overlayState; OverlayEntry? _overlayEntry; StreamController<bool>? _streamController; Timer? _fadeOutTimer; Timer? _removeTimer; static SBBToast of(BuildContext context) { return SBBToast._(Overlay.of(context, rootOverlay: true)!); } void show({ required String message, Duration duration = durationShort, double bottom = defaultBottom, }) { final showToastMessage = () { remove(); _streamController = StreamController<bool>(); _streamController!.add(true); _overlayEntry = _buildToastOverlayEntry( message, duration, _streamController!.stream, bottom, ); _overlayState.insert(_overlayEntry!); _fadeOutTimer = Timer(duration + kThemeAnimationDuration * 2, () { _streamController?.add(false); _removeTimer = Timer(kThemeAnimationDuration, () => remove()); }); }; if (_overlayEntry != null && _removeTimer == null) { _removeTimer?.cancel(); _removeTimer = null; _streamController?.add(false); _removeTimer = Timer(kThemeAnimationDuration, () => showToastMessage()); } else { showToastMessage(); } } void hide() { _streamController?.add(false); _removeTimer = Timer(kThemeAnimationDuration, () => remove()); } void remove() { _overlayEntry?.remove(); _overlayEntry = null; _removeTimer?.cancel(); _removeTimer = null; _fadeOutTimer?.cancel(); _fadeOutTimer = null; _streamController?.close(); _streamController = null; } OverlayEntry _buildToastOverlayEntry( String message, Duration duration, Stream<bool> stream, double bottom, ) { return OverlayEntry(builder: (context) { return Positioned( left: 0.0, right: 0.0, bottom: bottom, child: Align( alignment: Alignment.center, child: IgnorePointer( child: _Toast( message: message, duration: duration, stream: stream, ), ), ), ); }); } } class _Toast extends StatefulWidget { const _Toast({ Key? key, required this.message, required this.duration, required this.stream, }) : super(key: key); final String message; final Duration duration; final Stream<bool> stream; @override _ToastState createState() => _ToastState(); } class _ToastState extends State<_Toast> { bool _visible = false; @override void initState() { widget.stream.listen((visible) => setState(() => _visible = visible)); super.initState(); } @override Widget build(BuildContext context) { final tooltipTheme = Theme.of(context).tooltipTheme; return AnimatedOpacity( opacity: _visible ? 1.0 : 0.0, duration: kThemeAnimationDuration, child: Container( decoration: tooltipTheme.decoration, margin: tooltipTheme.margin, padding: tooltipTheme.padding, child: Text( widget.message, style: tooltipTheme.textStyle?.copyWith( decoration: TextDecoration.none, ), ), ), ); } }
class MainController < ApplicationController def index if params[:id] @current_image = Photo.find(params[:id]) else @current_image = Photo.last end @voted = Vote.already_voted?(request.remote_ip) @image = Photo.new end def create @photo = Photo.new(photo_params) @photo.ip = request.remote_ip if params[:photo][:image] @photo.caption = nil if @photo.caption == "" Vote.clear_votes if @photo.save end redirect_to '/?id='+@photo.id.to_s end def keep Vote.place_vote(true, request.remote_ip) redirect_to '/' end def kill Vote.place_vote(false, request.remote_ip) redirect_to '/' end private def photo_params params.require(:photo).permit(:caption, :image) end end
; RUN: %opt < %s %loadEnzyme -enzyme -enzyme-preopt=false -mem2reg -sroa -simplifycfg -instcombine -adce -S | FileCheck %s source_filename = "submemcpy.c" target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" ; Function Attrs: nounwind readnone uwtable define dso_local zeroext i1 @approx_fp_equality_float(float %f1, float %f2, double %threshold) local_unnamed_addr #0 { entry: %sub = fsub float %f1, %f2 %0 = tail call float @llvm.fabs.f32(float %sub) %1 = fpext float %0 to double %cmp = fcmp ule double %1, %threshold ret i1 %cmp } ; Function Attrs: noinline nounwind uwtable define dso_local void @submemcpy(i8* nocapture %sdst, i8* nocapture readonly %ssrc, i32 %sN) local_unnamed_addr #1 { entry: %conv = sext i32 %sN to i64 tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %sdst, i8* align 1 %ssrc, i64 %conv, i1 false) ret void } ; Function Attrs: argmemonly nounwind declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i1) #2 ; Function Attrs: nounwind uwtable define dso_local void @foo(float* nocapture %fdst, float* nocapture readonly %fsrc, i32 %fN) #3 { entry: %0 = bitcast float* %fdst to i8* %1 = bitcast float* %fsrc to i8* %mul = shl i32 %fN, 2 tail call void @submemcpy(i8* %0, i8* %1, i32 %mul) ret void } ; Function Attrs: nounwind uwtable define dso_local void @call(float* %cdst, float* %cdstp, float* %csrc, float* %csrcp, i32 %cN) local_unnamed_addr #3 { entry: %call = tail call double (i8*, ...) @__enzyme_autodiff(i8* bitcast (void (float*, float*, i32)* @foo to i8*), float* %cdst, float* %cdstp, float* %csrc, float* %csrcp, i32 %cN) #6 ret void } declare dso_local double @__enzyme_autodiff(i8*, ...) local_unnamed_addr #4 ; Function Attrs: nounwind readnone speculatable declare float @llvm.fabs.f32(float) #5 attributes #0 = { nounwind readnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #1 = { noinline nounwind uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #2 = { argmemonly nounwind } attributes #3 = { nounwind uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #4 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #5 = { nounwind readnone speculatable } attributes #6 = { nounwind } !llvm.module.flags = !{!0} !llvm.ident = !{!1} !0 = !{i32 1, !"wchar_size", i32 4} !1 = !{!"clang version 7.1.0 "} ; CHECK: define internal void @diffesubmemcpy(i8* nocapture %sdst, i8* nocapture %"sdst'", i8* nocapture readonly %ssrc, i8* nocapture %"ssrc'", i32 %sN) ; CHECK-NEXT: entry: ; CHECK-NEXT: %conv = sext i32 %sN to i64 ; CHECK-NEXT: tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %sdst, i8* align 1 %ssrc, i64 %conv, i1 false) ; CHECK-NEXT: %0 = bitcast i8* %"sdst'" to float* ; CHECK-NEXT: %1 = bitcast i8* %"ssrc'" to float* ; CHECK-NEXT: %2 = lshr i64 %conv, 2 ; CHECK-NEXT: %3 = {{(icmp eq i64 %2, 0|icmp ult i32 %sN, 4)}} ; CHECK-NEXT: br i1 %3, label %__enzyme_memcpyadd_floatda1sa1.exit, label %for.body.i ; CHECK: for.body.i: ; preds = %for.body.i, %entry ; CHECK-NEXT: %idx.i = phi i64 [ 0, %entry ], [ %idx.next.i, %for.body.i ] ; CHECK-NEXT: %dst.i.i = getelementptr inbounds float, float* %0, i64 %idx.i ; CHECK-NEXT: %dst.i.l.i = load float, float* %dst.i.i, align 1 ; CHECK-NEXT: store float 0.000000e+00, float* %dst.i.i, align 1 ; CHECK-NEXT: %src.i.i = getelementptr inbounds float, float* %1, i64 %idx.i ; CHECK-NEXT: %src.i.l.i = load float, float* %src.i.i, align 1 ; CHECK-NEXT: %4 = fadd fast float %src.i.l.i, %dst.i.l.i ; CHECK-NEXT: store float %4, float* %src.i.i, align 1 ; CHECK-NEXT: %idx.next.i = add nuw i64 %idx.i, 1 ; CHECK-NEXT: %5 = icmp eq i64 %2, %idx.next.i ; CHECK-NEXT: br i1 %5, label %__enzyme_memcpyadd_floatda1sa1.exit, label %for.body.i ; CHECK: __enzyme_memcpyadd_floatda1sa1.exit: ; preds = %entry, %for.body.i ; CHECK-NEXT: ret void ; CHECK-NEXT: }
#!/bin/sh autopoint --force autoreconf --force --install --symlink --warnings=all
/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file thrust/iterator/iterator_traits.h * \brief Traits and metafunctions for reasoning about the traits of iterators */ /* * (C) Copyright David Abrahams 2003. * * Distributed under the Boost Software License, Version 1.0. * (See accompanying NOTICE file for the complete license) * * For more information, see http://www.boost.org */ #pragma once #include <thrust/detail/config.h> #include <iterator> namespace thrust { /*! \p iterator_traits is a type trait class that provides a uniform * interface for querying the properties of iterators at compile-time. */ template<typename T> struct iterator_traits : public std::iterator_traits<T> { }; // end iterator_traits template<typename Iterator> struct iterator_value; template<typename Iterator> struct iterator_pointer; template<typename Iterator> struct iterator_reference; template<typename Iterator> struct iterator_difference; template<typename Iterator> struct iterator_traversal; template<typename Iterator> struct iterator_system; // TODO remove this in Thrust v1.7.0 template<typename Iterator> struct THRUST_DEPRECATED iterator_space { typedef THRUST_DEPRECATED typename iterator_system<Iterator>::type type; }; } // end thrust #include <thrust/iterator/detail/iterator_traversal_tags.h> #include <thrust/iterator/detail/host_system_tag.h> #include <thrust/iterator/detail/device_system_tag.h> #include <thrust/iterator/detail/any_system_tag.h> #include <thrust/iterator/detail/iterator_traits.inl>
# frozen_string_literal: true require_relative '../config/environment' require 'rails/test_help' require 'sidekiq/testing' Sidekiq::Testing.inline! Apartment::Tenant.drop 'default' rescue nil Apartment::Tenant.create 'default' Apartment::Tenant.switch! 'default' class ActiveSupport::TestCase set_fixture_class versions: PaperTrail::Version fixtures :all def assert_error model, attribute, type, options = {} error = model.errors.generate_message attribute, type, options assert_includes model.errors[attribute], error end end class ActionController::TestCase def login user: users(:franco) @controller.send(:cookies).encrypted[:token] = user.auth_token end end class ActionView::TestCase include FontAwesome::Sass::Rails::ViewHelpers include SimpleForm::ActionViewExtensions::FormHelper end class ActiveRecord::FixtureSet class << self alias :old_create_fixtures :create_fixtures end def self.create_fixtures f_dir, fs_names, *args Membership.delete_all Property.delete_all Database.delete_all reset_cache fs_names = %w(public.accounts) | fs_names apartment_models = Apartment.excluded_models.map &:constantize apartment_models.each do |model| alter_sql = "ALTER TABLE #{model.quoted_table_name} DISABLE TRIGGER ALL" ActiveRecord::Base.connection.execute alter_sql end fixtures_result = old_create_fixtures f_dir, fs_names, *args apartment_models.each do |model| alter_sql = "ALTER TABLE #{model.quoted_table_name} ENABLE TRIGGER ALL" ActiveRecord::Base.connection.execute alter_sql end fixtures_result end end
using UnityEngine; using UnityEngine.UI; using DG.Tweening; public class Gallery : MonoBehaviour { [SerializeField] private Image photoImage; [SerializeField] private CanvasGroup canvasGroup; private Photo currentPhoto; public void TakePhoto(Photo photo) { currentPhoto = photo; photoImage.sprite = photo.GetAsSprite(); canvasGroup.DOFade(1, 1f); canvasGroup.interactable = true; canvasGroup.blocksRaycasts = true; } public void GiveUp() { canvasGroup.DOFade(0, 1f); canvasGroup.interactable = false; canvasGroup.blocksRaycasts = false; } }
--- title: "(Qt) 79. GraphicsView 핵심 컴포넌트" date: 2020-03-01 00:00:00 -0000 --- ## 핵심 컴포넌트 * Display : `QGraphicsView` * Store Data Items : `QGraphicsScene` * Item : `QGraphicsItem` ![](/file/image/qt-gdi-s7-79-image-1.png) > 사실 이렇게 봐서 이해가 전혀 안된다. ㅋㅋ<br> > 엄청난 예시들이 기다리고 있으니 다음 장들을 참조하자.
package com.picawen.nano.spring.framework.beans.factory.support; import com.picawen.nano.spring.framework.beans.factory.config.SingletonBeanRegistry; import java.util.HashMap; import java.util.Map; /** * 单例Bean默认实现 */ public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry { private Map<String, Object> singletonObjs = new HashMap<>(); @Override public Object getSingleton(String beanName) { return singletonObjs.get(beanName); } protected void addSingleton(String beanName, Object obj) { singletonObjs.put(beanName, obj); } }
using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Lykke.Service.KucoinAdapter.Services.RestApi.Models { public sealed class ActiveOrdersListResponse { [JsonProperty("SELL")] public IReadOnlyCollection<JArray> Sell { get; set; } [JsonProperty("BUY")] public IReadOnlyCollection<JArray> Buy { get; set; } } }
; NOTE: Assertions have been autogenerated by utils/update_analyze_test_checks.py ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+sse2 | FileCheck %s -check-prefixes=X86,SSE2 ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+sse4.2 | FileCheck %s -check-prefixes=X86,SSE42 ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+avx | FileCheck %s -check-prefixes=X86,AVX1 ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+avx2 | FileCheck %s -check-prefixes=X86,AVX2 ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+avx512f | FileCheck %s -check-prefixes=X86,AVX512,AVX512F ; RUN: opt < %s -mtriple=i686-unknown-linux-gnu -cost-model -analyze -mattr=+avx512vl,avx512bw,avx512dq | FileCheck %s -check-prefixes=X86,AVX512,AVX512BW ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+sse2 | FileCheck %s -check-prefixes=X64,SSE2 ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+sse4.2 | FileCheck %s -check-prefixes=X64,SSE42 ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+avx | FileCheck %s -check-prefixes=X64,AVX1 ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+avx2 | FileCheck %s -check-prefixes=X64,AVX2 ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+avx512f | FileCheck %s -check-prefixes=X64,AVX512,AVX512F ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+avx512vl,+avx512bw,+avx512dq | FileCheck %s -check-prefixes=X64,AVX512,AVX512BW ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+xop | FileCheck %s -check-prefixes=XOP ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+xop,+avx2 | FileCheck %s -check-prefixes=XOP ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+gfni,+ssse3 | FileCheck %s -check-prefixes=GFNISSE ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+gfni,+avx | FileCheck %s -check-prefixes=GFNIAVX ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+gfni,+avx2 | FileCheck %s -check-prefixes=GFNIAVX2 ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+gfni,+avx512f | FileCheck %s -check-prefixes=GFNIAVX512F ; RUN: opt < %s -mtriple=x86_64-unknown-linux-gnu -cost-model -analyze -mattr=+gfni,+avx512bw | FileCheck %s -check-prefixes=GFNIAVX512BW ; Verify the cost of scalar bitreverse instructions. declare i64 @llvm.bitreverse.i64(i64) declare i32 @llvm.bitreverse.i32(i32) declare i16 @llvm.bitreverse.i16(i16) declare i8 @llvm.bitreverse.i8(i8) define i64 @var_bitreverse_i64(i64 %a) { ; X86-LABEL: 'var_bitreverse_i64' ; X86-NEXT: Cost Model: Found an estimated cost of 28 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; X86-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; X64-LABEL: 'var_bitreverse_i64' ; X64-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; X64-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; XOP-LABEL: 'var_bitreverse_i64' ; XOP-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_i64' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_i64' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_i64' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_i64' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_i64' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i64 %bitreverse ; %bitreverse = call i64 @llvm.bitreverse.i64(i64 %a) ret i64 %bitreverse } define i32 @var_bitreverse_i32(i32 %a) { ; X86-LABEL: 'var_bitreverse_i32' ; X86-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; X86-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; X64-LABEL: 'var_bitreverse_i32' ; X64-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; X64-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; XOP-LABEL: 'var_bitreverse_i32' ; XOP-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_i32' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_i32' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_i32' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_i32' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_i32' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i32 %bitreverse ; %bitreverse = call i32 @llvm.bitreverse.i32(i32 %a) ret i32 %bitreverse } define i16 @var_bitreverse_i16(i16 %a) { ; X86-LABEL: 'var_bitreverse_i16' ; X86-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; X86-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; X64-LABEL: 'var_bitreverse_i16' ; X64-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; X64-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; XOP-LABEL: 'var_bitreverse_i16' ; XOP-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_i16' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_i16' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_i16' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_i16' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_i16' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 14 for instruction: %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i16 %bitreverse ; %bitreverse = call i16 @llvm.bitreverse.i16(i16 %a) ret i16 %bitreverse } define i8 @var_bitreverse_i8(i8 %a) { ; X86-LABEL: 'var_bitreverse_i8' ; X86-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; X86-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; X64-LABEL: 'var_bitreverse_i8' ; X64-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; X64-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; XOP-LABEL: 'var_bitreverse_i8' ; XOP-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_i8' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_i8' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_i8' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_i8' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_i8' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 11 for instruction: %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret i8 %bitreverse ; %bitreverse = call i8 @llvm.bitreverse.i8(i8 %a) ret i8 %bitreverse } ; Verify the cost of vector bitreverse instructions. declare <2 x i64> @llvm.bitreverse.v2i64(<2 x i64>) declare <4 x i32> @llvm.bitreverse.v4i32(<4 x i32>) declare <8 x i16> @llvm.bitreverse.v8i16(<8 x i16>) declare <16 x i8> @llvm.bitreverse.v16i8(<16 x i8>) declare <4 x i64> @llvm.bitreverse.v4i64(<4 x i64>) declare <8 x i32> @llvm.bitreverse.v8i32(<8 x i32>) declare <16 x i16> @llvm.bitreverse.v16i16(<16 x i16>) declare <32 x i8> @llvm.bitreverse.v32i8(<32 x i8>) declare <8 x i64> @llvm.bitreverse.v8i64(<8 x i64>) declare <16 x i32> @llvm.bitreverse.v16i32(<16 x i32>) declare <32 x i16> @llvm.bitreverse.v32i16(<32 x i16>) declare <64 x i8> @llvm.bitreverse.v64i8(<64 x i8>) define <2 x i64> @var_bitreverse_v2i64(<2 x i64> %a) { ; SSE2-LABEL: 'var_bitreverse_v2i64' ; SSE2-NEXT: Cost Model: Found an estimated cost of 29 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v2i64' ; SSE42-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v2i64' ; AVX1-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v2i64' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v2i64' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v2i64' ; XOP-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v2i64' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v2i64' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v2i64' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v2i64' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v2i64' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <2 x i64> %bitreverse ; %bitreverse = call <2 x i64> @llvm.bitreverse.v2i64(<2 x i64> %a) ret <2 x i64> %bitreverse } define <4 x i64> @var_bitreverse_v4i64(<4 x i64> %a) { ; SSE2-LABEL: 'var_bitreverse_v4i64' ; SSE2-NEXT: Cost Model: Found an estimated cost of 58 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v4i64' ; SSE42-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v4i64' ; AVX1-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v4i64' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v4i64' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v4i64' ; XOP-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v4i64' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v4i64' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v4i64' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v4i64' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v4i64' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i64> %bitreverse ; %bitreverse = call <4 x i64> @llvm.bitreverse.v4i64(<4 x i64> %a) ret <4 x i64> %bitreverse } define <8 x i64> @var_bitreverse_v8i64(<8 x i64> %a) { ; SSE2-LABEL: 'var_bitreverse_v8i64' ; SSE2-NEXT: Cost Model: Found an estimated cost of 116 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v8i64' ; SSE42-NEXT: Cost Model: Found an estimated cost of 20 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v8i64' ; AVX1-NEXT: Cost Model: Found an estimated cost of 24 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v8i64' ; AVX2-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; AVX512F-LABEL: 'var_bitreverse_v8i64' ; AVX512F-NEXT: Cost Model: Found an estimated cost of 36 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; AVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; AVX512BW-LABEL: 'var_bitreverse_v8i64' ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v8i64' ; XOP-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v8i64' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v8i64' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v8i64' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v8i64' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v8i64' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i64> %bitreverse ; %bitreverse = call <8 x i64> @llvm.bitreverse.v8i64(<8 x i64> %a) ret <8 x i64> %bitreverse } define <4 x i32> @var_bitreverse_v4i32(<4 x i32> %a) { ; SSE2-LABEL: 'var_bitreverse_v4i32' ; SSE2-NEXT: Cost Model: Found an estimated cost of 27 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v4i32' ; SSE42-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v4i32' ; AVX1-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v4i32' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v4i32' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v4i32' ; XOP-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v4i32' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v4i32' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v4i32' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v4i32' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v4i32' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <4 x i32> %bitreverse ; %bitreverse = call <4 x i32> @llvm.bitreverse.v4i32(<4 x i32> %a) ret <4 x i32> %bitreverse } define <8 x i32> @var_bitreverse_v8i32(<8 x i32> %a) { ; SSE2-LABEL: 'var_bitreverse_v8i32' ; SSE2-NEXT: Cost Model: Found an estimated cost of 54 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v8i32' ; SSE42-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v8i32' ; AVX1-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v8i32' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v8i32' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v8i32' ; XOP-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v8i32' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v8i32' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v8i32' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v8i32' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v8i32' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i32> %bitreverse ; %bitreverse = call <8 x i32> @llvm.bitreverse.v8i32(<8 x i32> %a) ret <8 x i32> %bitreverse } define <16 x i32> @var_bitreverse_v16i32(<16 x i32> %a) { ; SSE2-LABEL: 'var_bitreverse_v16i32' ; SSE2-NEXT: Cost Model: Found an estimated cost of 108 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v16i32' ; SSE42-NEXT: Cost Model: Found an estimated cost of 20 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v16i32' ; AVX1-NEXT: Cost Model: Found an estimated cost of 24 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v16i32' ; AVX2-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; AVX512F-LABEL: 'var_bitreverse_v16i32' ; AVX512F-NEXT: Cost Model: Found an estimated cost of 24 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; AVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; AVX512BW-LABEL: 'var_bitreverse_v16i32' ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v16i32' ; XOP-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v16i32' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v16i32' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v16i32' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v16i32' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v16i32' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i32> %bitreverse ; %bitreverse = call <16 x i32> @llvm.bitreverse.v16i32(<16 x i32> %a) ret <16 x i32> %bitreverse } define <8 x i16> @var_bitreverse_v8i16(<8 x i16> %a) { ; SSE2-LABEL: 'var_bitreverse_v8i16' ; SSE2-NEXT: Cost Model: Found an estimated cost of 27 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v8i16' ; SSE42-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v8i16' ; AVX1-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v8i16' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v8i16' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v8i16' ; XOP-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v8i16' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v8i16' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v8i16' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v8i16' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v8i16' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <8 x i16> %bitreverse ; %bitreverse = call <8 x i16> @llvm.bitreverse.v8i16(<8 x i16> %a) ret <8 x i16> %bitreverse } define <16 x i16> @var_bitreverse_v16i16(<16 x i16> %a) { ; SSE2-LABEL: 'var_bitreverse_v16i16' ; SSE2-NEXT: Cost Model: Found an estimated cost of 54 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v16i16' ; SSE42-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v16i16' ; AVX1-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v16i16' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v16i16' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v16i16' ; XOP-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v16i16' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v16i16' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v16i16' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v16i16' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v16i16' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i16> %bitreverse ; %bitreverse = call <16 x i16> @llvm.bitreverse.v16i16(<16 x i16> %a) ret <16 x i16> %bitreverse } define <32 x i16> @var_bitreverse_v32i16(<32 x i16> %a) { ; SSE2-LABEL: 'var_bitreverse_v32i16' ; SSE2-NEXT: Cost Model: Found an estimated cost of 108 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v32i16' ; SSE42-NEXT: Cost Model: Found an estimated cost of 20 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v32i16' ; AVX1-NEXT: Cost Model: Found an estimated cost of 24 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v32i16' ; AVX2-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; AVX512F-LABEL: 'var_bitreverse_v32i16' ; AVX512F-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; AVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; AVX512BW-LABEL: 'var_bitreverse_v32i16' ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v32i16' ; XOP-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v32i16' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v32i16' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v32i16' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v32i16' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v32i16' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i16> %bitreverse ; %bitreverse = call <32 x i16> @llvm.bitreverse.v32i16(<32 x i16> %a) ret <32 x i16> %bitreverse } define <16 x i8> @var_bitreverse_v16i8(<16 x i8> %a) { ; SSE2-LABEL: 'var_bitreverse_v16i8' ; SSE2-NEXT: Cost Model: Found an estimated cost of 20 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v16i8' ; SSE42-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v16i8' ; AVX1-NEXT: Cost Model: Found an estimated cost of 5 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v16i8' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v16i8' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v16i8' ; XOP-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v16i8' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v16i8' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v16i8' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v16i8' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v16i8' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <16 x i8> %bitreverse ; %bitreverse = call <16 x i8> @llvm.bitreverse.v16i8(<16 x i8> %a) ret <16 x i8> %bitreverse } define <32 x i8> @var_bitreverse_v32i8(<32 x i8> %a) { ; SSE2-LABEL: 'var_bitreverse_v32i8' ; SSE2-NEXT: Cost Model: Found an estimated cost of 40 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v32i8' ; SSE42-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v32i8' ; AVX1-NEXT: Cost Model: Found an estimated cost of 12 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v32i8' ; AVX2-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; AVX512-LABEL: 'var_bitreverse_v32i8' ; AVX512-NEXT: Cost Model: Found an estimated cost of 3 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; AVX512-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v32i8' ; XOP-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v32i8' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v32i8' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v32i8' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v32i8' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v32i8' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <32 x i8> %bitreverse ; %bitreverse = call <32 x i8> @llvm.bitreverse.v32i8(<32 x i8> %a) ret <32 x i8> %bitreverse } define <64 x i8> @var_bitreverse_v64i8(<64 x i8> %a) { ; SSE2-LABEL: 'var_bitreverse_v64i8' ; SSE2-NEXT: Cost Model: Found an estimated cost of 80 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; SSE2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; SSE42-LABEL: 'var_bitreverse_v64i8' ; SSE42-NEXT: Cost Model: Found an estimated cost of 20 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; SSE42-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; AVX1-LABEL: 'var_bitreverse_v64i8' ; AVX1-NEXT: Cost Model: Found an estimated cost of 24 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; AVX1-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; AVX2-LABEL: 'var_bitreverse_v64i8' ; AVX2-NEXT: Cost Model: Found an estimated cost of 6 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; AVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; AVX512F-LABEL: 'var_bitreverse_v64i8' ; AVX512F-NEXT: Cost Model: Found an estimated cost of 10 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; AVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; AVX512BW-LABEL: 'var_bitreverse_v64i8' ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; AVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; XOP-LABEL: 'var_bitreverse_v64i8' ; XOP-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; XOP-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; GFNISSE-LABEL: 'var_bitreverse_v64i8' ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; GFNISSE-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; GFNIAVX-LABEL: 'var_bitreverse_v64i8' ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 8 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; GFNIAVX-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; GFNIAVX2-LABEL: 'var_bitreverse_v64i8' ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 2 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; GFNIAVX2-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; GFNIAVX512F-LABEL: 'var_bitreverse_v64i8' ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 4 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; GFNIAVX512F-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; ; GFNIAVX512BW-LABEL: 'var_bitreverse_v64i8' ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 1 for instruction: %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ; GFNIAVX512BW-NEXT: Cost Model: Found an estimated cost of 0 for instruction: ret <64 x i8> %bitreverse ; %bitreverse = call <64 x i8> @llvm.bitreverse.v64i8(<64 x i8> %a) ret <64 x i8> %bitreverse }
#!/bin/bash set -e -x aws iam delete-login-profile --user-name $1 || true aws iam remove-user-from-group --user-name $1 --group-name students || true aws iam delete-user --user-name $1 || true
# More Variety Brings more variety into bots. Includes MoreFactions, ScavVariety, EnhancedPlayerScav and BossesOnAllMaps.
using System.Threading.Tasks; using DSerfozo.RpcBindings.Execution.Model; namespace DSerfozo.RpcBindings.Contract.Execution { public interface IMethodExecutor<TMarshal> { Task<MethodResult<TMarshal>> Execute(MethodExecution<TMarshal> methodExcecution); } }
# Tools for Post-Processing of Nyles output This folder contains tools that can be useful to process the output files created by Nyles after the simulation has finished.
#!/usr/bin/perl # Copyright (c) Xerox Corporation, Codendi Team, 2001-2009. All rights reserved # # This file is a part of Codendi. # # Codendi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Codendi is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Codendi. If not, see <http://www.gnu.org/licenses/>. # ## ## cvs_history_parse.pl ## ## NIGHTLY SCRIPT ## ## Recurses through the /cvsroot directory tree and parses each projects ## '~/CVSROOT/history' file, building agregate stats on the number of ## checkouts, commits, and adds to each project over the past 24 hours. ## ## ## ## #use strict; use Time::Local; use POSIX qw( strftime ); require("../include.pl"); my ($year, $month, $day, $day_begin, $day_end); my ($group, $histline, $daily_log_file, $key, $verbose); my $verbose = 1; my $base_log_dir = $codendi_log."/cvslogs"; $|=0 if $verbose; ## Set the time to collect stats for if ( $ARGV[0] && $ARGV[1] && $ARGV[2] ) { $day_begin = timegm( 0, 0, 0, $ARGV[2], $ARGV[1] - 1, $ARGV[0] - 1900 ); $day_end = timegm( 0, 0, 0, (gmtime( $day_begin + 86400 ))[3,4,5] ); $year = $ARGV[0]; $month = $ARGV[1]; $day = $ARGV[2]; } else { ## Start at midnight last night. $day_end = timegm( 0, 0, 0, (gmtime( time() ))[3,4,5] ); ## go until midnight yesterday. $day_begin = timegm( 0, 0, 0, (gmtime( time() - 86400 ))[3,4,5] ); $year = strftime("%Y", gmtime( $day_begin ) ); $month = strftime("%m", gmtime( $day_begin ) ); $day = strftime("%d", gmtime( $day_begin ) ); } print "Parsing cvs logs looking for traffic on day $day, month $month, year $year.\n" if $verbose; if ( -d $base_log_dir ) { $daily_log_file = $base_log_dir . "/" . sprintf("%04d", $year); if ( ! -d $daily_log_file ) { print "Making dest dir \'$daily_log_file\'\n"; mkdir( $daily_log_file, 0755 ) || die("Could not mkdir $daily_log_file"); } $daily_log_file .= "/" . sprintf("%02d", $month); if ( ! -d $daily_log_file ) { print "Making dest dir \'$daily_log_file\'\n"; mkdir( $daily_log_file, 0755 ) || die("Could not mkdir $daily_log_file"); } $daily_log_file .= "/cvs_traffic_" . sprintf("%04d%02d%02d",$year,$month,$day) . ".log"; } else { print "Base log directory \'$base_log_dir\' does not exist!"; exit; } open(DAYS_LOG, "> $daily_log_file") || die "Unable to open the log file \'$daily_log_file\'"; print "Opened log file at \'$daily_log_file\' for writing...\n"; print "Running tree at $cvs_prefix/\n"; chdir( $cvs_prefix ) || die("Unable to make $cvs_prefix the working directory.\n"); foreach $group ( glob("*") ) { next if ( ! -d "$group" || $group eq 'lost+found' ); my ($cvs_co, $cvs_commit, $cvs_add, %usr_commit, %usr_add); # LJ New variable to keep track of users and number of checkouts my (%usr_names, %usr_co); open(HISTORY, "< $cvs_prefix/$group/CVSROOT/history") or print "E::Unable to open history for $group\n"; while ( <HISTORY> ) { my ($time_parsed, $type, $cvstime, $user, $curdir, $module, $rev, $file ); ## Split the cvs history entry into it's 6 fields. ($cvstime,$user,$curdir,$module,$rev,$file) = split(/\|/, $_, 6 ); $type = substr($cvstime, 0, 1); $time_parsed = hex( substr($cvstime, 1, 8) ); ## If the entry was made in the past 24 hours ## (i.e. - since the last run of this script...) if ( ($time_parsed > $day_begin) && ($time_parsed < $day_end) ) { ## log commits if ( $type eq "M" ) { $cvs_commit++; $usr_commit{$user}++; $usr_names{$user}=1; next; } ## log adds if ( $type eq "A" ) { $cvs_add++; $usr_add{$user}++; $usr_names{$user}=1; next; } ## log checkouts if ( $type eq "O" ) { $cvs_co++; ## we don't care about checkouts on a per-user ## most of them will be anon anyhow. ## LJ Actually we do care on Codendi $usr_co{$user}++; $usr_names{$user}=1; next; } } elsif ( $time_parsed > $day_end ) { if ( $verbose >= 2 ) { print "Short circuting execution, parsed date exceeded current threshold.\n"; } last; } } close( HISTORY ); ## Now, we'll print all of the results for that project, in the following format: ## (G|U|E)::proj_name::user_name::checkouts::commits::adds ## If 'G', then record is group statistics, and field 2 is a space... ## If 'U', then record is per-user stats, and field 2 is the user name... ## If 'E', then record is an error, and field 1 is a description, there are no other fields. if ( $cvs_co || $cvs_commit || $cvs_add ) { print DAYS_LOG "G::" . $group . ":: ::" . ($cvs_co?$cvs_co:"0") . "::" . ($cvs_commit?$cvs_commit:"0") . "::" . ($cvs_add?$cvs_add:"0") . "\n"; foreach $key ( keys %usr_names ) { print DAYS_LOG "U::" . $group . "::" . $key . "::" . ($usr_co{$key}?$usr_co{$key}:"0") . "::" . ($usr_commit{$key}?$usr_commit{$key}:"0") . "::" . ($usr_add{$key}?$usr_add{$key}:"0") . "\n"; } } } print "Done processing cvs history file for this date.\n" if $verbose; ## ## EOF ##
/** * Copyright [2016] [Muhammad Afzal] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uclab.scl.rs; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.uclab.scl.Utilities.ComputationUtilityMethods; import org.uclab.scl.communication.CommunicationManager; import org.uclab.scl.datamodel.Conclusion; import org.uclab.scl.datamodel.Disibilities; import org.uclab.scl.datamodel.FiredRule; import org.uclab.scl.datamodel.PhysiologicalFactors; import org.uclab.scl.datamodel.RecommendationIngredients; import org.uclab.scl.datamodel.RiskFactors; import org.uclab.scl.datamodel.SituationConditions; import org.uclab.scl.datamodel.SituationEvent; import org.uclab.scl.datamodel.SituationNotification; import org.uclab.scl.datamodel.User; import org.uclab.scl.framework.Reasoner; import org.uclab.scl.framework.ReasonerEnum; import org.uclab.scl.framework.recbuilder.RecBuilder; import org.uclab.scl.framework.recbuilder.RecBuilderPacket; import org.uclab.scl.outputModel.SCLResponse; import org.uclab.scl.outputModel.RecModel.PhyActivityRecommendations; /** * REST Web Service * @version MM v2.5 * @author Afzal */ @Path("SCLService") public class SCLServiceResource { private static Logger LOG = LogManager.getRootLogger(); CommunicationManager dclManager = CommunicationManager.getCommunicationManager(); @Context private UriInfo context; /** * Constructor that creates a new instance of SCLServiceResource */ public SCLServiceResource() { } /** * This service method is developed to build rule-based recommendation. * It takes situation notification object as input return the recommendation results accordingly. * @param situationNotification * @return */ @Path("PushPARecommendation") @POST @Produces("application/json") @Consumes("application/json") public SCLResponse buildSituationBasedPARecommendation(SituationNotification situationNotification) { SCLResponse response = new SCLResponse(); List<String> result = new ArrayList<>(); try { Reasoner rbr = Reasoner.getRuleBaseReasoner(); RecBuilder recomBuilder = (RecBuilder) rbr.getMatchedRules(ReasonerEnum.SITUATION_PAREASONER); RecommendationIngredients recIngredients = new RecommendationIngredients(); ComputationUtilityMethods cUtility = ComputationUtilityMethods.getComputationUtilityMethods(); String situationValues = ""; for (SituationConditions sc : situationNotification.getSituationEvent().getListSConditions()) { situationValues = situationValues + sc.getConditionValue() + " "; } LOG.debug("Situation Event Received from Lifelog Monitor (LLM): " + situationValues + "\n*************"); User user = dclManager.getUser(Long.parseLong(situationNotification.getUserID())); List<RiskFactors> riskFactors = dclManager.getRiskFactors(Long.parseLong(situationNotification.getUserID())); List<Disibilities> disibilities = dclManager.getDisibilities(Long.parseLong(situationNotification.getUserID())); List<PhysiologicalFactors> physFactors = dclManager.getPhysiologicalFactors(Long.parseLong(situationNotification.getUserID())); recIngredients.setRiskFactors(riskFactors); recIngredients.setDisibilities(disibilities); recIngredients.setUser(user); recIngredients.setsNotification(situationNotification); recIngredients.setPhysFactors(physFactors); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); Date dob = new Date(); dob = sdf.parse(user.getDateOfBirth()); recIngredients.setAgeGroup(cUtility.getAgeGroup(dob)); LOG.debug("Call for situation reasoner..."); RecBuilderPacket paRecBuilderInputPacket = new RecBuilderPacket(); paRecBuilderInputPacket.setRecommendationInput(recIngredients); recomBuilder.buildRecommendation(paRecBuilderInputPacket); LOG.debug("Sittuation reasoner passed!"); List<FiredRule> rules = paRecBuilderInputPacket.getRecommendationOutput(); List<PhyActivityRecommendations> paRecommendations = new ArrayList<PhyActivityRecommendations>(); PhyActivityRecommendations paRecommendation = new PhyActivityRecommendations(); String currentDate = cUtility.getCurrentDate(); LOG.debug("Final Resolved Rule(s): "); for (FiredRule fr : rules) { result.add("\n*******************************\nRecommendation Builder\n*******************************\nRecommendation(" + fr.getRuleId() + "): " + fr.getRuleConclusion()); LOG.debug(fr.getRuleConclusion()); for (Conclusion c : fr.getConclusionList()) { result.add(c.getConclusionKey() + c.getConclusionOperator() + c.getConclusionValue()); LOG.debug(c.getConclusionKey() + c.getConclusionOperator() + c.getConclusionValue()); } } List<String> resultRecPersistence = null; if (!(paRecommendations.isEmpty())) { resultRecPersistence = dclManager.persistPhysicalRecommendations(paRecommendations); } String recommendationID = resultRecPersistence.get(0); result.add(recommendationID); result.add("No Error"); } catch (Exception e) { result.add("Error:"); result.add(e.getMessage()); } response.setResult(result); return response; } /** * PUT method for updating or creating an instance of SCLServiceResource * * @param content * representation for the resource * @return an HTTP response with content of the updated or created resource. */ @PUT @Consumes("application/json") public void putJson(String content) { } @Path("TestLLMJSONFormat/") @GET @Produces("application/json") public SituationNotification getTestSitNotification() { SituationNotification sNotif = new SituationNotification(); sNotif.setUserID("1"); SituationEvent sEvt = new SituationEvent(); sEvt.setSituationID("112"); Set<SituationConditions> sitCon = new HashSet<>(); SituationConditions sitCon1 = new SituationConditions(); sitCon1.setConditionKey("Activity Level"); sitCon1.setConditionValueOperator("String"); sitCon1.setConditionValue("Sedentary"); sitCon1.setConditionValueOperator("="); sitCon.add(sitCon1); SituationConditions sitCon2 = new SituationConditions(); sitCon2.setConditionKey("Consumed Fat"); sitCon2.setConditionValue("85"); sitCon2.setConditionValueOperator(">"); sitCon2.setConditionType("String"); sitCon.add(sitCon2); sEvt.setListSConditions(sitCon); sNotif.setSituationEvent(sEvt); return sNotif; } }
/*global DateTimeShortcuts, SelectFilter*/ /** * Django admin inlines * * Based on jQuery Formset 1.1 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) * @requires jQuery 1.2.6 or later * * Copyright (c) 2009, Stanislaus Madueke * All rights reserved. * * Spiced up with Code from Zain Memon's GSoC project 2009 * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip. * * Licensed under the New BSD License * See: https://opensource.org/licenses/bsd-license.php */ 'use strict'; { const $ = django.jQuery; $.fn.formset = function(opts) { const options = $.extend({}, $.fn.formset.defaults, opts); const $this = $(this); const $parent = $this.parent(); const updateElementIndex = function(el, prefix, ndx) { const id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); const replacement = prefix + "-" + ndx; if ($(el).prop("for")) { $(el).prop("for", $(el).prop("for").replace(id_regex, replacement)); } if (el.id) { el.id = el.id.replace(id_regex, replacement); } if (el.name) { el.name = el.name.replace(id_regex, replacement); } }; const totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off"); let nextIndex = parseInt(totalForms.val(), 10); const maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off"); const minForms = $("#id_" + options.prefix + "-MIN_NUM_FORMS").prop("autocomplete", "off"); let addButton; /** * The "Add another MyModel" button below the inline forms. */ const addInlineAddButton = function() { if (addButton === null) { if ($this.prop("tagName") === "TR") { // If forms are laid out as table rows, insert the // "add" button in a new table row: const numCols = $this.eq(-1).children().length; $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>"); addButton = $parent.find("tr:last a"); } else { // Otherwise, insert it immediately after the last form: $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>"); addButton = $this.filter(":last").next().find("a"); } } addButton.on('click', addInlineClickHandler); }; const addInlineClickHandler = function(e) { e.preventDefault(); const template = $("#" + options.prefix + "-empty"); const row = template.clone(true); row.removeClass(options.emptyCssClass) .addClass(options.formCssClass) .attr("id", options.prefix + "-" + nextIndex); addInlineDeleteButton(row); row.find("*").each(function() { updateElementIndex(this, options.prefix, totalForms.val()); }); // Insert the new form when it has been fully edited. row.insertBefore($(template)); // Update number of total forms. $(totalForms).val(parseInt(totalForms.val(), 10) + 1); nextIndex += 1; // Hide the add button if there's a limit and it's been reached. if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) { addButton.parent().hide(); } // Show the remove buttons if there are more than min_num. toggleDeleteButtonVisibility(row.closest('.inline-group')); // Pass the new form to the post-add callback, if provided. if (options.added) { options.added(row); } $(document).trigger('formset:added', [row, options.prefix]); }; /** * The "X" button that is part of every unsaved inline. * (When saved, it is replaced with a "Delete" checkbox.) */ const addInlineDeleteButton = function(row) { if (row.is("tr")) { // If the forms are laid out in table rows, insert // the remove button into the last table cell: row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>"); } else if (row.is("ul") || row.is("ol")) { // If they're laid out as an ordered/unordered list, // insert an <li> after the last list item: row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>"); } else { // Otherwise, just insert the remove button as the // last child element of the form's container: row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>"); } // Add delete handler for each row. row.find("a." + options.deleteCssClass).on('click', inlineDeleteHandler.bind(this)); }; const inlineDeleteHandler = function(e1) { e1.preventDefault(); const deleteButton = $(e1.target); const row = deleteButton.closest('.' + options.formCssClass); const inlineGroup = row.closest('.inline-group'); // Remove the parent form containing this button, // and also remove the relevant row with non-field errors: const prevRow = row.prev(); if (prevRow.length && prevRow.hasClass('row-form-errors')) { prevRow.remove(); } row.remove(); nextIndex -= 1; // Pass the deleted form to the post-delete callback, if provided. if (options.removed) { options.removed(row); } $(document).trigger('formset:removed', [row, options.prefix]); // Update the TOTAL_FORMS form count. const forms = $("." + options.formCssClass); $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); // Show add button again once below maximum number. if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) { addButton.parent().show(); } // Hide the remove buttons if at min_num. toggleDeleteButtonVisibility(inlineGroup); // Also, update names and ids for all remaining form controls so // they remain in sequence: let i, formCount; const updateElementCallback = function() { updateElementIndex(this, options.prefix, i); }; for (i = 0, formCount = forms.length; i < formCount; i++) { updateElementIndex($(forms).get(i), options.prefix, i); $(forms.get(i)).find("*").each(updateElementCallback); } }; const toggleDeleteButtonVisibility = function(inlineGroup) { if ((minForms.val() !== '') && (minForms.val() - totalForms.val()) >= 0) { inlineGroup.find('.inline-deletelink').hide(); } else { inlineGroup.find('.inline-deletelink').show(); } }; $this.each(function(i) { $(this).not("." + options.emptyCssClass).addClass(options.formCssClass); }); // Create the delete buttons for all unsaved inlines: $this.filter('.' + options.formCssClass + ':not(.has_original):not(.' + options.emptyCssClass + ')').each(function() { addInlineDeleteButton($(this)); }); toggleDeleteButtonVisibility($this); // Create the add button, initially hidden. addButton = options.addButton; addInlineAddButton(); // Show the add button if allowed to add more items. // Note that max_num = None translates to a blank string. const showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0; if ($this.length && showAddButton) { addButton.parent().show(); } else { addButton.parent().hide(); } return this; }; /* Setup plugin defaults */ $.fn.formset.defaults = { prefix: "form", // The form prefix for your django formset addText: "add another", // Text for the add link deleteText: "remove", // Text for the delete link addCssClass: "add-row", // CSS class applied to the add link deleteCssClass: "delete-row", // CSS class applied to the delete link emptyCssClass: "empty-row", // CSS class applied to the empty row formCssClass: "dynamic-form", // CSS class applied to each form in a formset added: null, // Function called each time a new form is added removed: null, // Function called each time a form is deleted addButton: null // Existing add button to use }; // Tabular inlines --------------------------------------------------------- $.fn.tabularFormset = function(selector, options) { const $rows = $(this); const reinitDateTimeShortCuts = function() { // Reinitialize the calendar and clock widgets by force if (typeof DateTimeShortcuts !== "undefined") { $(".datetimeshortcuts").remove(); DateTimeShortcuts.init(); } }; const updateSelectFilter = function() { // If any SelectFilter widgets are a part of the new form, // instantiate a new SelectFilter instance for it. if (typeof SelectFilter !== 'undefined') { $('.selectfilter').each(function(index, value) { SelectFilter.init(value.id, this.dataset.fieldName, false); }); $('.selectfilterstacked').each(function(index, value) { SelectFilter.init(value.id, this.dataset.fieldName, true); }); } }; const initPrepopulatedFields = function(row) { row.find('.prepopulated_field').each(function() { const field = $(this), input = field.find('input, select, textarea'), dependency_list = input.data('dependency_list') || [], dependencies = []; $.each(dependency_list, function(i, field_name) { dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id')); }); if (dependencies.length) { input.prepopulate(dependencies, input.attr('maxlength')); } }); }; $rows.formset({ prefix: options.prefix, addText: options.addText, formCssClass: "dynamic-" + options.prefix, deleteCssClass: "inline-deletelink", deleteText: options.deleteText, emptyCssClass: "empty-form", added: function(row) { initPrepopulatedFields(row); reinitDateTimeShortCuts(); updateSelectFilter(); }, addButton: options.addButton }); return $rows; }; // Stacked inlines --------------------------------------------------------- $.fn.stackedFormset = function(selector, options) { const $rows = $(this); const updateInlineLabel = function(row) { $(selector).find(".inline_label").each(function(i) { const count = i + 1; $(this).html($(this).html().replace(/(#\d+)/g, "#" + count)); }); }; const reinitDateTimeShortCuts = function() { // Reinitialize the calendar and clock widgets by force, yuck. if (typeof DateTimeShortcuts !== "undefined") { $(".datetimeshortcuts").remove(); DateTimeShortcuts.init(); } }; const updateSelectFilter = function() { // If any SelectFilter widgets were added, instantiate a new instance. if (typeof SelectFilter !== "undefined") { $(".selectfilter").each(function(index, value) { SelectFilter.init(value.id, this.dataset.fieldName, false); }); $(".selectfilterstacked").each(function(index, value) { SelectFilter.init(value.id, this.dataset.fieldName, true); }); } }; const initPrepopulatedFields = function(row) { row.find('.prepopulated_field').each(function() { const field = $(this), input = field.find('input, select, textarea'), dependency_list = input.data('dependency_list') || [], dependencies = []; $.each(dependency_list, function(i, field_name) { // Dependency in a fieldset. let field_element = row.find('.form-row .field-' + field_name); // Dependency without a fieldset. if (!field_element.length) { field_element = row.find('.form-row.field-' + field_name); } dependencies.push('#' + field_element.find('input, select, textarea').attr('id')); }); if (dependencies.length) { input.prepopulate(dependencies, input.attr('maxlength')); } }); }; $rows.formset({ prefix: options.prefix, addText: options.addText, formCssClass: "dynamic-" + options.prefix, deleteCssClass: "inline-deletelink", deleteText: options.deleteText, emptyCssClass: "empty-form", removed: updateInlineLabel, added: function(row) { initPrepopulatedFields(row); reinitDateTimeShortCuts(); updateSelectFilter(); updateInlineLabel(row); }, addButton: options.addButton }); return $rows; }; $(document).ready(function() { $(".js-inline-admin-formset").each(function() { const data = $(this).data(), inlineOptions = data.inlineFormset; let selector; switch(data.inlineType) { case "stacked": selector = inlineOptions.name + "-group .inline-related"; $(selector).stackedFormset(selector, inlineOptions.options); break; case "tabular": selector = inlineOptions.name + "-group .tabular.inline-related tbody:first > tr.form-row"; $(selector).tabularFormset(selector, inlineOptions.options); break; } }); }); }
package com.cjh.eshop.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * 定时任务 * @author 陈建杭 * */ @Component public class ScheduledTast { private static Logger logger = LoggerFactory.getLogger(ScheduledTast.class); /* @Scheduled(fixedDelay = 5000) void doSomethingWithDelay(){ System.out.println("I'm doing with delay now!"); } @Scheduled(fixedRate = 5000) void doSomethingWithRate(){ System.out.println("I'm doing with rate now!"); } */ // 每天 00:00 时做一次数据库备份 @Scheduled(cron = "0 0 0 * * *") void doSomethingWith() { logger.info("开始备份数据库"); // TODO 备份数据库 logger.info("数据库备份完成"); } }
#!/bin/bash cd /dagger install () { npm install } test_install () { if [ -z "$(ls -A node_modules)" ]; then install fi } start () { npm start } build () { npm run-script build } lint () { npx eslint . } version () { RELEASE=`git describe --tags | sed 's|release_||; s|-.*||'` BRANCH=`git rev-parse --abbrev-ref HEAD` COMMIT=`git rev-parse --short HEAD` REVISION_DATE=`git log -n1 --pretty=%at HEAD` VERSION_STRING="v$RELEASE-$BRANCH.$COMMIT" } version export REACT_APP_VERSION_STRING=$VERSION_STRING export REACT_APP_REVISION_DATE=`date -d @$REVISION_DATE +"%y.%m.%d"` development () { install start } production () { if [ "$PUBLIC_URL" = "" ]; then echo 'ERROR: Need to specify a PUBLIC_URL'; fi install build } package_dev () { #production version NAME="dagger-redux_$VERSION_STRING" cd build tar -cf ../$NAME.tar * cd .. chmod 777 $NAME.tar } package_release () { #production version NAME="dagger-redux_$RELEASE" cd build tar -cf ../$NAME.tar * cd .. chmod 777 $NAME.tar } # Prefer parameters to environment case $1 in lint) test_install lint exit;; bash) /bin/bash exit;; development) development exit;; production) production exit;; package_dev) package_dev exit;; package_release) package_release exit;; esac case $REACT_APP_ENVIRONMENT in development) development exit;; production) production exit;; esac
#!/bin/bash set -x PACKAGE_NAME=$(cat package.json | grep name | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | xargs) ELECTRON_VERSION=1.8.3 PACKAGE_VERSION=$(cat package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | xargs) ROOT_DIR=$(cd $(dirname $0)/..; pwd) cd $ROOT_DIR rm -r dist mkdir -p dist/src/assets/fonts mkdir -p zips NODE_ENV=production webpack sed -i '' -e 's/http:\/\/localhost:3000\///g' dist/index.html mv dist/index.html dist/bundle.js dist/src/ cp src/splash.html src/splash.mp4 dist/src/ cp -r assets/images/*.ico assets/images/*.icns .babelrc package.json index.js dist/ cp -r assets/fonts/* dist/src/assets/fonts cp -r src/main dist/src cd dist npm i --prod if [ "$APP_PLATFORM" == "win32-ia32" ]; then npm run rebuild-ia32 electron-packager ./ ${PACKAGE_NAME} --platform=win32 --arch=ia32\ --electron-version="${ELECTRON_VERSION}" --app-version="${PACKAGE_VERSION}" --icon=garchen-logo.ico --no-prune 7z a -tzip -r "./../zips/${PACKAGE_NAME}-win32-ia32-v${PACKAGE_VERSION}.zip" "${PACKAGE_NAME}-win32-ia32" rm -r "${PACKAGE_NAME}-win32-ia32" fi if [ "$APP_PLATFORM" == "win32-x64" ]; then npm run rebuild electron-packager ./ ${PACKAGE_NAME} --platform=win32 --arch=x64\ --electron-version="${ELECTRON_VERSION}" --app-version="${PACKAGE_VERSION}" --icon=garchen-logo.ico --no-prune 7z a -tzip -r "./../zips/${PACKAGE_NAME}-win32-x64-v${PACKAGE_VERSION}.zip" "${PACKAGE_NAME}-win32-x64" rm -r "${PACKAGE_NAME}-win32-x64" fi if [ "$APP_PLATFORM" == "darwin" ]; then npm run rebuild electron-packager ./ ${PACKAGE_NAME} --platform=darwin --arch=x64\ --electron-version="${ELECTRON_VERSION}" --app-version="${PACKAGE_VERSION}" --icon=garchen-logo.icns --no-prune zip -r "./../zips/${PACKAGE_NAME}-darwin-x64-v${PACKAGE_VERSION}.zip" "${PACKAGE_NAME}-darwin-x64" > /dev/null rm -r "${PACKAGE_NAME}-darwin-x64" fi
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.sql.impl.utils; import static org.apache.beam.sdk.schemas.Schema.toSchema; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.stream.IntStream; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.sql.type.SqlTypeName; /** Utility methods for Calcite related operations. */ public class CalciteUtils { private static final long UNLIMITED_ARRAY_SIZE = -1L; // Beam's Schema class has a single DATETIME type, so we need a way to distinguish the different // Calcite time classes. We do this by storing extra metadata in the FieldType so we // can tell which time class this is. // // Same story with CHAR and VARCHAR - they both map to STRING. private static final BiMap<FieldType, SqlTypeName> BEAM_TO_CALCITE_TYPE_MAPPING = ImmutableBiMap.<FieldType, SqlTypeName>builder() .put(FieldType.BYTE, SqlTypeName.TINYINT) .put(FieldType.INT16, SqlTypeName.SMALLINT) .put(FieldType.INT32, SqlTypeName.INTEGER) .put(FieldType.INT64, SqlTypeName.BIGINT) .put(FieldType.FLOAT, SqlTypeName.FLOAT) .put(FieldType.DOUBLE, SqlTypeName.DOUBLE) .put(FieldType.DECIMAL, SqlTypeName.DECIMAL) .put(FieldType.BOOLEAN, SqlTypeName.BOOLEAN) .put(FieldType.BYTES, SqlTypeName.VARBINARY) .put(FieldType.DATETIME.withMetadata("DATE"), SqlTypeName.DATE) .put(FieldType.DATETIME.withMetadata("TIME"), SqlTypeName.TIME) .put( FieldType.DATETIME.withMetadata("TIME_WITH_LOCAL_TZ"), SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE) .put(FieldType.DATETIME.withMetadata("TS"), SqlTypeName.TIMESTAMP) .put( FieldType.DATETIME.withMetadata("TS_WITH_LOCAL_TZ"), SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) .put(FieldType.STRING.withMetadata("CHAR"), SqlTypeName.CHAR) .put(FieldType.STRING.withMetadata("VARCHAR"), SqlTypeName.VARCHAR) .build(); private static final BiMap<SqlTypeName, FieldType> CALCITE_TO_BEAM_TYPE_MAPPING = BEAM_TO_CALCITE_TYPE_MAPPING.inverse(); // The list of field type names used in SQL as Beam field types. public static final FieldType TINY_INT = toFieldType(SqlTypeName.TINYINT); public static final FieldType SMALL_INT = toFieldType(SqlTypeName.SMALLINT); public static final FieldType INTEGER = toFieldType(SqlTypeName.INTEGER); public static final FieldType BIG_INT = toFieldType(SqlTypeName.BIGINT); public static final FieldType FLOAT = toFieldType(SqlTypeName.FLOAT); public static final FieldType DOUBLE = toFieldType(SqlTypeName.DOUBLE); public static final FieldType DECIMAL = toFieldType(SqlTypeName.DECIMAL); public static final FieldType BOOLEAN = toFieldType(SqlTypeName.BOOLEAN); public static final FieldType CHAR = toFieldType(SqlTypeName.CHAR); public static final FieldType VARCHAR = toFieldType(SqlTypeName.VARCHAR); public static final FieldType TIME = toFieldType(SqlTypeName.TIME); public static final FieldType DATE = toFieldType(SqlTypeName.DATE); public static final FieldType TIMESTAMP = toFieldType(SqlTypeName.TIMESTAMP); // Since there are multiple Calcite type that correspond to a single Beam type, this is the // default mapping. private static final Map<FieldType, SqlTypeName> BEAM_TO_CALCITE_DEFAULT_MAPPING = ImmutableMap.of( FieldType.DATETIME, SqlTypeName.TIMESTAMP, FieldType.STRING, SqlTypeName.VARCHAR); /** Generate {@link Schema} from {@code RelDataType} which is used to create table. */ public static Schema toBeamSchema(RelDataType tableInfo) { return tableInfo .getFieldList() .stream() .map(CalciteUtils::toBeamSchemaField) .collect(toSchema()); } public static SqlTypeName toSqlTypeName(FieldType type) { switch (type.getTypeName()) { case ROW: return SqlTypeName.ROW; case ARRAY: return SqlTypeName.ARRAY; case MAP: return SqlTypeName.MAP; default: SqlTypeName typeName = BEAM_TO_CALCITE_TYPE_MAPPING.get(type); if (typeName != null) { return typeName; } else { // This will happen e.g. if looking up a STRING type, and metadata isn't set to say which // type of SQL string we want. In this case, use the default mapping. return BEAM_TO_CALCITE_DEFAULT_MAPPING.get(type); } } } public static FieldType toFieldType(SqlTypeName sqlTypeName) { switch (sqlTypeName) { case MAP: case MULTISET: case ARRAY: case ROW: throw new IllegalArgumentException( String.format( "%s is a type constructor that takes parameters, not a type," + "so it cannot be converted to a %s", sqlTypeName, Schema.FieldType.class.getSimpleName())); default: return CALCITE_TO_BEAM_TYPE_MAPPING.get(sqlTypeName).withMetadata((byte[]) null); } } public static FieldType toFieldType(RelDataType calciteType) { switch (calciteType.getSqlTypeName()) { case ARRAY: case MULTISET: return FieldType.array(toFieldType(calciteType.getComponentType())); case MAP: return FieldType.map( toFieldType(calciteType.getKeyType()), toFieldType(calciteType.getValueType())); case ROW: return FieldType.row(toBeamSchema(calciteType)); default: return toFieldType(calciteType.getSqlTypeName()); } } public static Schema.Field toBeamSchemaField(RelDataTypeField calciteField) { FieldType fieldType = toFieldType(calciteField.getType()); // TODO: We should support Calcite's nullable annotations. return Schema.Field.of(calciteField.getName(), fieldType).withNullable(true); } /** Create an instance of {@code RelDataType} so it can be used to create a table. */ public static RelDataType toCalciteRowType(Schema schema, RelDataTypeFactory dataTypeFactory) { RelDataTypeFactory.Builder builder = new RelDataTypeFactory.Builder(dataTypeFactory); IntStream.range(0, schema.getFieldCount()) .forEach( idx -> builder.add( schema.getField(idx).getName(), toRelDataType(dataTypeFactory, schema, idx))); return builder.build(); } private static RelDataType toRelDataType( RelDataTypeFactory dataTypeFactory, FieldType fieldType) { switch (fieldType.getTypeName()) { case ARRAY: return dataTypeFactory.createArrayType( toRelDataType(dataTypeFactory, fieldType.getCollectionElementType()), UNLIMITED_ARRAY_SIZE); case MAP: RelDataType componentKeyType = toRelDataType(dataTypeFactory, fieldType.getMapKeyType()); RelDataType componentValueType = toRelDataType(dataTypeFactory, fieldType.getMapValueType()); return dataTypeFactory.createMapType(componentKeyType, componentValueType); case ROW: return toCalciteRowType(fieldType.getRowSchema(), dataTypeFactory); default: return dataTypeFactory.createSqlType(toSqlTypeName(fieldType)); } } private static RelDataType toRelDataType( RelDataTypeFactory dataTypeFactory, Schema schema, int fieldIndex) { Schema.Field field = schema.getField(fieldIndex); RelDataType type = toRelDataType(dataTypeFactory, field.getType()); return dataTypeFactory.createTypeWithNullability(type, field.getNullable()); } }
package hemendra.books.model import android.os.Handler import android.os.Looper import hemendra.books.data.Book import hemendra.books.model.listeners.BooksLoaderListener import hemendra.books.model.utils.ConnectionCallback import hemendra.books.model.utils.ContentDownloader import hemendra.books.model.utils.CustomAsyncTask import java.net.HttpURLConnection import java.net.URLEncoder class GetBooks(private val listener: BooksLoaderListener): CustomAsyncTask<Any, Void, ArrayList<Book>?>() { private var connection: HttpURLConnection? = null private var reason = "Unknown" private var disconnectHandler: Handler? = null private val disconnectCallback: Handler.Callback = Handler.Callback { connection?.disconnect() true } override fun cancel(interrupt: Boolean) { disconnectHandler?.sendEmptyMessage(0) super.cancel(true) } override fun doInBackground(vararg params: Any): ArrayList<Book>? { if(Looper.myLooper() == null) Looper.prepare() try { val query = URLEncoder.encode(params[0] as String, "UTF-8") val apiKey = params[1] as String val pageNumber = params[2] as Int val startIndex = (pageNumber - 1) * 10 val url = "https://www.googleapis.com/books/v1/volumes?q=$query&key=$apiKey&startIndex=$startIndex" val json = ContentDownloader.getString(url, object : ConnectionCallback { override fun onConnectionInitialized(conn: HttpURLConnection) { connection = conn disconnectHandler = Handler(disconnectCallback) } override fun onResponseCode(code: Int) { codeToReason(code) } override fun onInterrupted() { reason = "Aborted" } override fun onError() { reason = "Network Error" } }) json?.let { return BooksParser.parseBooks(it) } return null } finally { Looper.myLooper()?.quit() disconnectHandler = null } } override fun onPostExecute(result: ArrayList<Book>?) { result?.let { listener.onSearchResults(it) } ?: listener.onSearchFailed(reason) } fun codeToReason(code: Int) { when (code) { HttpURLConnection.HTTP_NOT_FOUND -> reason = "$code (Not Found)" HttpURLConnection.HTTP_BAD_GATEWAY -> reason = "$code (Bad Gateway)" HttpURLConnection.HTTP_BAD_METHOD -> reason = "$code (Bad Method)" HttpURLConnection.HTTP_BAD_REQUEST -> reason = "$code (Bad Request)" HttpURLConnection.HTTP_CLIENT_TIMEOUT -> reason = "$code (Client Timeout)" HttpURLConnection.HTTP_CONFLICT -> reason = "$code (Conflict)" HttpURLConnection.HTTP_ENTITY_TOO_LARGE -> reason = "$code (Entity Too Large)" HttpURLConnection.HTTP_FORBIDDEN -> reason = "$code (Forbidden)" HttpURLConnection.HTTP_GATEWAY_TIMEOUT -> reason = "$code (Gateway Timeout)" HttpURLConnection.HTTP_GONE -> reason = "$code (Gone)" HttpURLConnection.HTTP_INTERNAL_ERROR -> reason = "$code (Internal Error)" HttpURLConnection.HTTP_NOT_ACCEPTABLE -> reason = "$code (Not Acceptable)" HttpURLConnection.HTTP_NOT_AUTHORITATIVE -> reason = "$code (Not Authoritative)" HttpURLConnection.HTTP_NOT_IMPLEMENTED -> reason = "$code (Not Implemented)" HttpURLConnection.HTTP_OK -> {} HttpURLConnection.HTTP_UNAUTHORIZED -> reason = "$code (Unauthorized)" else -> reason = "HTTP Response Code: $code" } } }
/* * focus.h * starkiller * * Created by Justin on 13/06/09. * Copyright 2009 Monkey Style Games. All rights reserved. * */ #ifndef __LXT_UI_FX_FOCUS_H__ #define __LXT_UI_FX_FOCUS_H__ #include "math/util.h" namespace Lxt { // Apply a "focus" effect, increasing alpha and decreasing size to "focus", // and decreasing alpha and increasing size to "defocus". Just a silly UI effect. class Focus { public: Focus( float a_startAlpha, float a_endAlpha, float a_startSize, float a_endSize, float a_period ) : m_alpha( a_startAlpha ), m_size( a_startSize), m_startAlpha( a_startAlpha ), m_endAlpha( a_endAlpha ), m_startSize( a_startSize ), m_endSize( a_endSize ), m_period( a_period ) { } void Update( float a_secondsElapsed ) { if ( a_secondsElapsed > m_period ) a_secondsElapsed = m_period; const float t = a_secondsElapsed/m_period; m_alpha = Lxt::Lerp( m_startAlpha, m_endAlpha, t ); m_size = Lxt::Lerp( m_startSize, m_endSize, t ); } float Alpha() const { return m_alpha; }; float Size() const { return m_size; }; private: float m_alpha, m_size; const float m_period; const float m_startAlpha, m_endAlpha; const float m_startSize, m_endSize; }; } #endif // __LXT_UI_FX_FOCUS_H__
<?php namespace Craft; class Freeform_BaseController extends BaseController { /** * @return Freeform_FormsService */ protected function getFormService() { return freeform()->forms; } /** * @return Freeform_FieldsService */ protected function getFieldsService() { return freeform()->fields; } /** * @return Freeform_FilesService */ protected function getFilesService() { return freeform()->files; } /** * @return Freeform_NotificationsService */ protected function getNotificationService() { return freeform()->notifications; } /** * @return Freeform_MailingListsService */ protected function getMailingListsService() { return freeform()->mailingLists; } /** * @return Freeform_CrmService */ protected function getCRMService() { return freeform()->crm; } /** * @return Freeform_StatusesService */ protected function getStatusesService() { return freeform()->statuses; } /** * @return Freeform_SettingsService */ protected function getSettingsService() { return freeform()->settings; } /** * @return Freeform_SubmissionsService */ protected function getSubmissionService() { return freeform()->submissions; } /** * @return Freeform_ExportProfilesService */ protected function getExportProfileService() { return freeform()->exportProfiles; } /** * @param mixed $data * * @return string */ protected function getEncodedJson($data) { return json_encode($data, JSON_OBJECT_AS_ARRAY); } }
package service import ( "github.com/echocat/caretakerd/errors" "strings" ) // Environments represents a couple of key value pair environment variables. // @inline type Environments map[string]string func (i Environments) String() string { result := "" for key, value := range i { if len(result) > 0 { result += "\n" } result += key + "=" + value } return result } func evaluate(value string) (map[string]string, error) { result := map[string]string{} lines := strings.Split(value, "\n") for _, line := range lines { parts := strings.SplitN(line, "=", 2) if len(parts) != 2 { return result, errors.New("Illegal environment settings format: %s", line) } result[parts[0]] = parts[1] } return result, nil } // Set sets the given string to a current object from a string. // Returns an error object if there are any problems while transforming the string. func (i *Environments) Set(value string) error { values, err := evaluate(value) if err != nil { return err } *i = values return nil } // Append appends a string with format key=value to this instance. func (i Environments) Append(value string) error { values, err := evaluate(value) if err != nil { return err } for key, value := range values { i[key] = value } return nil } // Put appends a key value pair to this instance. func (i *Environments) Put(key string, value string) error { (*i)[key] = value return nil }
# frozen_string_literal: true module DataTest class Fetcher attr_accessor :s3 def initialize credentials = Aws::Credentials.new(access_key, secret) Aws.config.update(region: S3_REGION, credentials: credentials) @s3 = Aws::S3::Resource.new(region: S3_REGION) end def access_key ENV["ARCHIVAL_S3_ACCESS"] || ENV["FETCHER_S3_ACCESS"] end def secret ENV["ARCHIVAL_S3_KEY"] || ENV["FETCHER_S3_KEY"] end def can_run? !!access_key && !!secret && !!S3_REGION end def self.can_run? return false unless !!S3_REGION return false unless defined?(Aws) new.can_run? end def bucket s3.bucket(S3_BUCKET) end def fetch_config_file if DataTest.has_config_file? puts " -> Config file found" else puts " -> Downloading config file" get("data_test.json", CONFIG_PATH) end end def fetch_all_artefacts get_and_extract_zip(ARTEFACT_DIR) end def get(name, output_path) obj = bucket.object(name) obj.get(response_target: output_path) rescue Aws::S3::Errors::InvalidAccessKeyId => e raise NoS3Configured, e.to_s end def get_and_extract_zip(output_directory, name: "latest.zip") output_file = Tempfile.new("latest.zip") puts " -> Fetching #{name}" get(name, output_file.path) puts " -> Extracting to #{output_directory}" Zip::File.open(output_file.path) do |zip_file| zip_file.each do |entry| output_path = File.join(output_directory, entry.name) File.unlink(output_path) if File.exist?(output_path) entry.extract(output_path) end end output_file.unlink end end end
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', function () { return view('deskpad/baselogin'); }); Route::group(['prefix' => 'deskpad', 'namespace' => 'Deskpad'], function(){ /*for partner*/ Route::get('baselogin', 'PartnerController@login'); Route::post('baselogin', 'PartnerController@login'); Route::get('partners', 'PartnerController@partners'); Route::post('partners', 'PartnerController@AddSubject'); Route::post('partners', 'PartnerController@AddSubSuject'); Route::post('partners', 'PartnerController@AddSetSuject'); Route::post('partners', 'PartnerController@CreateStudent'); Route::get('studentprofile={id}', 'PartnerController@StudentProfile'); Route::get('grade', 'PartnerController@AddGrade'); Route::get('dev/api/subject','PartnerController@getSubject'); Route::get('subject','PartnerController@addSubject'); Route::get('dev/api/getsubject','PartnerController@getSubSubject'); Route::post('grade', 'PartnerController@SaveScore'); }); Route::get('dev/api/allsubjects','Search\SearchDataController@getSubject'); Route::get('dev/api/subsubject','Search\SearchDataController@getExamType'); Route::get('dev/api/allstudents','Search\SearchDataController@getAllStudents'); // Route::post('grade', 'PartnerController@AddSubject'); // Route::post('grade', 'PartnerController@AddSubSuject'); // // Route::post('grade', 'PartnerController@AddSetSuject'); // Route::post('partners', 'PartnerController@CreateStudent');
package BitManipulation; import java.util.Scanner; public class find_one_complement_of_number { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter any number:"); int num = sc.nextInt(); int n = num; // // finding the number of bits in the given number // int number_of_bits = (int) Math.floor(Math.log(n) / Math.log(2))+1; // // // now generating the number which has same number of set bits as total bits present in given number. // int mask = (1 << number_of_bits) - 1; // // // now we have to do XOR operation of given number with mask. // int one_complement_of_number = n ^ mask; // System.out.println("The one's complement of the given number "+num+" is : "+one_complement_of_number); int k = (int) (Math.log(num) / Math.log(2)); for(int i=0 ; i<=k ; i++){ int x = 1 << i; num = num ^ x; } System.out.println(num); } }
--- ms.custom: devx-track-js ms.topic: include ms.date: 04/15/2021 --- If you already use the Azure service extensions, you should already be logged in and can skip this step. Once you've installed an extension in Visual Studio Code, you need to sign into your Azure account. 1. In Visual Studio Code, select the **Azure** explorer icon, then select **Sign in to Azure**, and follow the prompts. ![Sign in to Azure through VS Code](../media/deploy-azure/azure-sign-in.png) 2. After signing in, verify that the email address of your Azure account appears in the Status Bar and your subscription(s) appears in the **Azure** explorer: ![VS Code Azure explorer showing subscriptions](../media/deploy-azure/azure-subscription-view.png) > [!NOTE] > If you see the error **"Cannot find subscription with name [subscription ID]"**, this may be because you are behind a proxy and unable to reach the Azure API. Configure `HTTP_PROXY` and `HTTPS_PROXY` environment variables with your proxy information in your terminal: > > # [bash](#tab/bash) > > ```bash > export HTTPS_PROXY=https://username:password@proxy:8080 > export HTTP_PROXY=http://username:password@proxy:8080 > ``` > > # [PowerShell](#tab/powershell) > > ```powershell > $env: HTTPS_PROXY = "https://username:password@proxy:8080" > $env: HTTP_PROXY = "http://username:password@proxy:8080" > ``` > > # [Cmd](#tab/cmd) > > ```cmd > set HTTPS_PROXY=https://username:password@proxy:8080 > set HTTP_PROXY=http://username:password@proxy:8080 > ``` > > ---
require 'spec_helper' require 'pry' describe ::FFI::Fasttext::Predictor do describe "API" do let(:filename) { ::File.join(::File.dirname(__FILE__), "..", "model.bin") } it "validates #destroy! present" do ::FFI::Fasttext::Predictor.new(filename).must_respond_to :destroy! end it "validates #predict present" do ::FFI::Fasttext::Predictor.new(filename).must_respond_to :predict end it "will not initialize without valid model file" do error = lambda { ::FFI::Fasttext::Predictor.new("derpderp") }.must_raise(RuntimeError) error.message.must_match(/error loading model/i) end it "will output an array with matches on #predict" do ::FFI::Fasttext::Predictor.new(filename).predict("derp").must_be_instance_of Array end it "will include an array of arrays with predictions of category and probability when found" do predictions = ::FFI::Fasttext::Predictor.new(filename).predict("derp", 10) predictions.must_be_instance_of Array predictions.size.must_be :>, 1 predictions.each do |prediction| prediction.must_be_instance_of Array prediction.size.must_equal 2 prediction.first.must_be_instance_of String prediction.last.must_be_instance_of Float end end it "will include an array of arrays with predictions of category and probability when found and default to 1" do predictions = ::FFI::Fasttext::Predictor.new(filename).predict("derp") predictions.must_be_instance_of Array predictions.size.must_equal 1 predictions.each do |prediction| prediction.must_be_instance_of Array prediction.size.must_equal 2 prediction.first.must_be_instance_of String prediction.last.must_be_instance_of Float end end end end
// https://leetcode-cn.com/problems/largest-number/ #include "extern.h" class S0179 { struct StringCompare { inline bool operator()(string& s1, string& s2) { return s1 + s2 > s2 + s1; } }; public: string largestNumber(vector<int>& nums) { if (nums.empty()) return ""; if (*max_element(nums.begin(), nums.end()) == 0) return "0"; vector<string> vec; for (auto n : nums) vec.push_back(to_string(n)); sort(vec.begin(), vec.end(), StringCompare()); string result; for (auto& s : vec) result += s; return result; } }; TEST(e0200, e0179) { vector<int> nums; nums = str_to_vec<int>("[10,2]"); ASSERT_EQ(S0179().largestNumber(nums), "210"); nums = str_to_vec<int>("[3,30,34,5,9]"); ASSERT_EQ(S0179().largestNumber(nums), "9534330"); }
package typingsSlinky.googleapis.servicenetworkingV1betaMod.servicenetworkingV1beta import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * `SourceContext` represents information about the source of a protobuf * element, like the file in which it is defined. */ @js.native trait SchemaSourceContext extends StObject { /** * The path-qualified name of the .proto file that contained the associated * protobuf element. For example: * `&quot;google/protobuf/source_context.proto&quot;`. */ var fileName: js.UndefOr[String] = js.native } object SchemaSourceContext { @scala.inline def apply(): SchemaSourceContext = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[SchemaSourceContext] } @scala.inline implicit class SchemaSourceContextMutableBuilder[Self <: SchemaSourceContext] (val x: Self) extends AnyVal { @scala.inline def setFileName(value: String): Self = StObject.set(x, "fileName", value.asInstanceOf[js.Any]) @scala.inline def setFileNameUndefined: Self = StObject.set(x, "fileName", js.undefined) } }
describe ROM::Kafka::Dataset do let(:gateway_class) { ROM::Kafka::Gateway } let(:consumer_class) { ROM::Kafka::Connection::Consumer } let(:consumer) { double :consumer } before { allow(consumer_class).to receive(:new) { consumer } } let(:dataset) { described_class.new(gateway, topic.to_sym) } let(:gateway) { gateway_class.new client_id: "foo" } let(:topic) { "bar" } describe "#gateway" do subject { dataset.gateway } it "is initialized" do expect(subject).to eql gateway end end describe "#topic" do subject { dataset.topic } it "is initialized" do expect(subject).to eql topic end end describe "#attributes" do subject { dataset.attributes } context "by default" do let(:attributes) do { partition: 0, offset: 0, limit: 0, min_bytes: gateway.min_bytes, max_bytes: gateway.max_bytes, max_wait_ms: gateway.max_wait_ms } end it "is taken from a gateway" do expect(subject).to eql attributes end end context "when options are set" do let(:dataset) { described_class.new(gateway, topic, attributes) } let(:attributes) do { partition: 1, offset: 2, limit: 10, min_bytes: 1_024, max_bytes: 10_240, max_wait_ms: 100 } end it "is initialized" do expect(subject).to eql attributes end end end describe "#producer" do subject { dataset.producer } it "is taken from #gateway" do expect(subject).to eql gateway.producer end end describe "#consumer" do subject { dataset.consumer } let(:dataset) { described_class.new(gateway, topic, attributes) } let(:attributes) do { partition: 1, offset: 2, limit: 0, min_bytes: 1_024, max_bytes: 10_240, max_wait_ms: 100 } end let(:options) do attributes.merge( topic: topic, client_id: gateway.client_id, brokers: gateway.brokers ) end it "is initialized with proper options" do expect(consumer_class).to receive(:new).with(options) expect(subject).to eql consumer end end describe "#using" do subject { dataset.using(update) } let(:dataset) { described_class.new gateway, topic, min_bytes: 8 } let(:update) { { partition: 1, offset: 2 } } it "builds new dataset" do expect(subject).to be_kind_of described_class end it "preserves gateway" do expect(subject.gateway).to eql(gateway) end it "preserves topic" do expect(subject.topic).to eql(topic) end it "updates attributes" do expect(subject.attributes).to eql(dataset.attributes.merge(update)) end end describe "#each" do subject { dataset.to_a } let(:consumer) { double :consumer, each: data.each } let(:data) { %w(foo bar baz qux) } context "when limit isn't set" do it "is delegated to the consumer" do expect(subject).to eql data end it "yields limited number of times" do expect { |b| dataset.each(&b) }.to yield_control.exactly(4).times end end context "when limit is set" do let(:dataset) { described_class.new(gateway, topic, limit: 2) } it "is delegated to the consumer" do expect(subject).to eql data[0..1] end it "yields limited number of times" do expect { |b| dataset.each(&b) }.to yield_control.twice end end context "without a block" do subject { dataset.each } it { is_expected.to be_kind_of Enumerator } end end end
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace sharedcmd.Commands { /// <summary> /// Manages commands on the CLI. /// </summary> public sealed class CommandManager : IManageCommand { private readonly List<string> commands = new(); public IReadOnlyCollection<string> Commands => commands; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddCommand(string command) { commands.Add(command); } public void AddCommands(IEnumerable<string> sequence) { if (sequence.Any()) { commands.AddRange(sequence); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddCommands(params string[] sequence) { AddCommands(sequence.AsEnumerable()); } } }
// Copyright (c) 2021, Janoš Guljaš <janos@resenje.org> // All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package schulze import "sort" // Voting holds voting state in memory for a list of choices and provides // methods to vote, to export current voting state and to calculate the winner // using the Schulze method. type Voting struct { choices []string matrix [][]voteCount } // NewVoting initializes a new voting with provided choices. func NewVoting(choices ...string) *Voting { return &Voting{ choices: choices, matrix: makeVoteCountMatrix(len(choices)), } } // Ballot represents a single vote with ranked choices. Lowest number represents // the highest rank. Not all choices have to be ranked and multiple choices can // have the same rank. Ranks do not have to be in consecutive order. type Ballot map[string]int func (e *Voting) Vote(b Ballot) error { ranks, err := ballotRanks(b, e.choices) if err != nil { return err } for rank, choices1 := range ranks { rest := ranks[rank+1:] for _, i := range choices1 { for _, choices1 := range rest { for _, j := range choices1 { e.matrix[i][j]++ } } } } return nil } // VoteMatrix returns the state of the voting in a form of VoteMatrix with // pairwise number of votes. func (e *Voting) VoteMatrix() VoteMatrix { l := len(e.matrix) matrix := make(VoteMatrix, l) for i := 0; i < l; i++ { for j := 0; j < l; j++ { if _, ok := matrix[e.choices[i]]; !ok { matrix[e.choices[i]] = make(map[string]int, l) } matrix[e.choices[i]][e.choices[j]] = int(e.matrix[i][j]) } } return matrix } // Compute calculates a sorted list of choices with the total number of wins for // each of them. If there are multiple winners, tie boolean parameter is true. func (e *Voting) Compute() (scores []Score, tie bool) { return compute(e.matrix, e.choices) } func ballotRanks(b Ballot, choices []string) ([][]choiceIndex, error) { ballotRanks := make(map[int][]choiceIndex) rankedChoices := make(map[choiceIndex]struct{}) for o, rank := range b { index := getChoiceIndex(o, choices) if index < 0 { return nil, &UnknownChoiceError{o} } ballotRanks[rank] = append(ballotRanks[rank], index) rankedChoices[index] = struct{}{} } rankNumbers := make([]int, 0, len(ballotRanks)) for rank := range ballotRanks { rankNumbers = append(rankNumbers, rank) } sort.Slice(rankNumbers, func(i, j int) bool { return rankNumbers[i] < rankNumbers[j] }) ranks := make([][]choiceIndex, 0) for _, rankNumber := range rankNumbers { ranks = append(ranks, ballotRanks[rankNumber]) } unranked := make([]choiceIndex, 0) for i, l := choiceIndex(0), len(choices); int(i) < l; i++ { if _, ok := rankedChoices[i]; !ok { unranked = append(unranked, i) } } if len(unranked) > 0 { ranks = append(ranks, unranked) } return ranks, nil } type choiceIndex int func getChoiceIndex(choice string, choices []string) choiceIndex { for i, o := range choices { if o == choice { return choiceIndex(i) } } return -1 }
class ReviewAuthorizer < ApplicationAuthorizer # Users may view (preview) published reviews in their own unit. def readable_by?(user) return true if user.has_role?(:admin, resource.customer.unit) return true if user.has_role?(:wizard, resource.customer.unit) resource.published? && user.has_role?(:user, resource.customer.unit) end # Users may edit their own unpublished reviews. # Admins can edit reviews in their unit, published or not. def updatable_by?(user) return true if user.has_role?(:admin, resource.customer.unit) return true if user.has_role?(:wizard, resource.customer.unit) !resource.published? && user == resource.user end end
import { Component, OnInit } from '@angular/core'; import { Order } from 'src/app/models/order'; import { Store } from '@ngrx/store'; import { ApplicationState } from 'src/app/store'; import { getOrderState } from 'src/app/store/selectors'; @Component({ selector: 'app-order-history', templateUrl: './order-history.component.html', styleUrls: ['./order-history.component.css'] }) export class OrderHistoryComponent implements OnInit { constructor(private store: Store<ApplicationState>) {} orderHistory: any; ngOnInit() { this.store.select(getOrderState).subscribe(orderState => { this.orderHistory = orderState.orderHistory; }); } }
# ls aliases alias ll='ls -FGlAhp' alias la='ls -A' # Aliases to protect against overwriting and to correct mistyping alias cp='cp -iv' alias mv='mv -iv' alias mkdir='mkdir -pv' alias dc='cd' # Create a directory and cd into it mcd() { mkdir "${1}" && cd "${1}" } # python aliases alias python='python3.8' alias python3='python3.8'
<?php namespace marionnewlevant\snitch\models; use Craft; use craft\base\Model; class Settings extends Model { const SERVERPOLLINTERVAL = 2; const MESSAGE = 'May also be edited by: {user}.'; const INPUTIDSELECTOR = 'form input[type="hidden"][name="entryId"]' // entry forms .', form input[type="hidden"][name="elementId"]' // modals entry forms .', form input[type="hidden"][name="setId"]' // global set .', form input[type="hidden"][name="categoryId"]' // category .', form input[type="hidden"][name="userId"]'; // user; /** * @var int */ public $serverPollInterval = self::SERVERPOLLINTERVAL; /** * @var string */ public $message = self::MESSAGE; /** * @var string */ public $inputIdSelector = self::INPUTIDSELECTOR; public function rules() { return [ ['serverPollInterval', 'integer', 'min' => 1, 'max' => 5], ['serverPollInterval', 'default', 'value' => self::SERVERPOLLINTERVAL], ['message', 'string'], ['message', 'default', 'value' => self::MESSAGE], ['inputIdSelector', 'string'], ['inputIdSelector', 'default', 'value' => self::INPUTIDSELECTOR], ]; } }
<?php Route::auth(); // Вывод форм Route::get('/', 'HomeController@index'); // Проверяет авторизован ли пользователь Route::group(['middleware' => 'auth'], function(){ // Обмен сообщениями Route::post('/sendMessage', 'MessageController@sendMessage'); Route::get('/viewForm/{id_forms_departments}', 'ViewFormController@viewForm'); // Управление пользователями Route::get('/registration', 'UserControlController@index'); Route::post('/registration', 'UserControlController@registration'); Route::get('/removeUser/{id}', 'UserControlController@removeUser'); Route::get('/editUsers/{id}', 'UserControlController@editUsers'); Route::post('/updateEditUsers/{id}', 'UserControlController@updateEditUsers'); // Управление формамии homeUser Route::post('/submitFillForm', 'ViewFormController@submitFillForm'); Route::post('/submitFillFormRepeatedly', 'ViewFormController@submitFillFormRepeatedly'); // Управление формами homeAdmin Route::post('/rejectForm', 'ViewFormController@rejectForm'); Route::post('/acceptForm', 'ViewFormController@acceptForm'); // Управление завершенными формами Route::get('/doneForm', 'ViewFormController@doneForm'); Route::get('/viewDoneForm/{id_forms_departments}', 'ViewFormController@viewDoneForm'); // Конструктор форм //> Вкладка Собрать форму Route::get('/constructor/addForm', 'ConstructorFormController@addForm'); Route::post('/constructor/getSetElements', 'ConstructorFormController@getSetElements'); Route::post('/constructor/addNewForm', 'ConstructorFormController@addNewForm'); Route::post('/constructor/editForm', 'ConstructorFormController@editForm'); Route::post('/constructor/addEditedNewForm', 'ConstructorFormController@addEditedNewForm'); Route::post('/constructor/reestablishForm', 'ConstructorFormController@reestablishForm'); Route::post('/constructor/removeForms', 'ConstructorFormController@removeFormsToServer'); //> Вкладка Добавить элемент Route::get('/constructor/newElement', 'ConstructorFormController@newElement'); Route::post('/constructor/addNewElement', 'ConstructorFormController@addNewElementToServer'); //// Кнопки редактирования set_elements (вызов из js) Route::post('/editSetElementFromForm', 'ConstructorFormController@editSetElementFromForm'); Route::post('/addEditedNewSetElement', 'ConstructorFormController@addEditedNewSetElement'); Route::post('/removeSetElement', 'ConstructorFormController@removeSetElement'); //> Вкладка Просмотр списка форм Route::get('/constructor/showForms', 'ConstructorFormController@showForms'); Route::get('/viewFormEmpty/{id_forms}', 'ConstructorFormController@viewFormEmpty'); //> Вкладка Связи Route::get('/constructor/formsConnectUsers', 'ConstructorFormController@formsConnectUsers'); Route::post('/constructor/getTableConnectUsers', 'ConstructorFormController@getTableConnectUsers'); Route::post('/constructor/setTableConnectUsers', 'ConstructorFormController@setTableConnectUsers'); Route::post('/constructor/setTableDisconnectUsers', 'ConstructorFormController@setTableDisconnectUsers'); //> Вкладка Отделы Route::get('/constructor/departments', 'ConstructorFormController@getAllDepartments'); Route::post('/constructor/setDepartments', 'ConstructorFormController@setDepartments'); Route::post('/constructor/removeDepartments', 'ConstructorFormController@removeDepartments'); Route::post('/constructor/reestablishDepartments', 'ConstructorFormController@reestablishDepartments'); Route::post('/constructor/editDepartments', 'ConstructorFormController@editDepartments'); });
"use strict"; angular.module("Pin", ["ui.bootstrap", "google-maps", "ngRoute"]). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', {templateUrl: 'partials/splash.html'}); $routeProvider.when('/pin', {templateUrl: 'partials/map.html', controller: 'DropPin'}); $routeProvider.when('/pin/:id', {templateUrl: 'partials/map.html', controller: 'GetPin'}); $routeProvider.otherwise({redirectTo: '/'}); }]) .controller('DropPin', ['$scope', '$http', '$modal', function($scope, $http, $modal) { var coords = null; $scope.map = { center: { lat: 32.77, lng: -79.93 }, markers: [], zoom: 16, clickedLatitude: null, clickedLongitude: null }; $scope.droppedPin = false; $scope.wrongLocation = function() { var modalInstance = $modal.open({ templateUrl: 'partials/message.html', controller: 'Message', resolve: { message: function() { return { title: "Chill Out Bro", message: "This thing is still in alpha, additional features to come soon." }; } } }); } $scope.dropPin = function() { var setExpiration = $modal.open({ templateUrl: 'partials/setExpiration.html', controller: 'SetExpiration' }); setExpiration.result.then(function(expiration) { expiration = expiration * 60; $http.post("api/pin", { location: coords.latitude + ";" + coords.longitude, ttl: expiration }).success(function(data) { var copyCode = $modal.open({ templateUrl: 'partials/copy.html', controller: 'CopyCode', resolve: { code: function() { return "http://pin.dayoftheduck.com/#/pin/" + data.key; } } }); }); }); } navigator.geolocation.getCurrentPosition(function(location) { coords = location.coords; $scope.$apply(function() { $scope.map.center = { lat: coords.latitude, lng: coords.longitude }; $scope.map.markers = [{ latitude: coords.latitude, longitude: coords.longitude }]; }); }); }]) .controller('SetExpiration', ["$scope", "$modalInstance", function($scope, $modalInstance) { $scope.expiration = ""; $scope.close = function() { //redirect to home $modalInstance.close(); } $scope.drop = function() { $scope.expiration = document.getElementById('expiration').value; $modalInstance.close(parseInt($scope.expiration)); } }]) .controller('CopyCode', ["$scope", "$modalInstance", "code", function($scope, $modalInstance, code) { $scope.code = code; $scope.close = function() { //redirect to home $modalInstance.close(); } }]) .controller('GetPin', ['$scope', '$http', '$routeParams', '$modal', function($scope, $http, $params, $modal) { $scope.map = { center: { lat: 45, lng: -73 }, markers: [], zoom: 16, clickedLatitude: null, clickedLongitude: null }; $http.get("api/pin/" + $params.id).success(function(data) { if (data.location) { var location = data.location.split(";"); $scope.map.center = { lat: location[0], lng: location[1] }; $scope.map.markers = [{ latitude: location[0], longitude: location[1] }]; } else { var modalInstance = $modal.open({ templateUrl: 'partials/message.html', controller: 'Message', resolve: { message: function() { return data.message; } } }); } }); }]) .controller('Message', ["$scope", "$modalInstance", "message", function($scope, $modalInstance, message) { $scope.message = message.message; $scope.title = message.title; $scope.close = function() { $modalInstance.close(); } }]);
<?php declare(strict_types=1); namespace PowerSrc\AmazonAdvertisingApi\Concerns; trait HasPropertyCasts { /** * Return an array of types to cast values to on object creation. * * The property to cast is the key and the type to cast to is the value. * * The type to cast should be a PrimitiveType value or fully qualified class name. * If a FQCN is used then the class will be instantiated, passing the value into the constructor. * * @return array|null */ protected function getPropertyCasts(): ?array { return $this->casts; } }
#!/usr/bin/env python # Copyright 2019 Google, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from googleapiclient.discovery import build from googleapiclient.errors import Error # Build the service object, passing in the api name and api version client_service = build('jobs', 'v3') project_id = 'projects/' + os.environ['GOOGLE_CLOUD_PROJECT'] # Specifying details for the company that's going to be created. # These are the only two required fields. # Optional fields are documented at # http://googleapis.github.io/google-api-python-client/docs/dyn/jobs_v3.projects.companies.html#create new_company = { 'display_name': "FooCorp", 'external_id': "foo_llc" } request = {'company': new_company} try: # This is the API call that actually creates the new company. result = client_service.projects().companies().create( parent=project_id, body=request).execute() # You can easily just print the result as a string if you want print('Company created: %s' % result) # Here's how you'd access individual fields. The fields returned depend on # what you specified in the "new_company" object. To see possible fields # in response, see the "create" documentation at: # http://googleapis.github.io/google-api-python-client/docs/dyn/jobs_v3.projects.companies.html#create print('%s, %s, %s' % (result.get('externalId'), result.get('displayName'), result.get('name'))) except Error as e: print('Got exception while creating company') raise e
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:wdb106_sample/model/model.dart'; part 'items_state.freezed.dart'; @freezed abstract class ItemsState implements _$ItemsState { factory ItemsState({ @Default(<ItemStock>[]) List<ItemStock> stocks, @Default(true) bool isLoading, }) = _ItemsState; ItemsState._(); late final Map<int, ItemStock> _map = Map.fromEntries( stocks.map((s) => MapEntry(s.item.id, s)), ); ItemStock stock(int id) => _map[id]!; }
/* * * Copyright 2019 PingCAP, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.spark.sql.types import org.apache.spark.sql.test.generator.DataType._ import org.apache.spark.sql.test.generator.TestDataGenerator._ class MultiColumnDataTypeSuite extends MultiColumnDataTypeTest with RunMultiColumnDataTypeTestAction { override val generator: BaseMultiColumnDataTypeGenerator = BaseMultiColumnDataTypeGenerator( dataTypes, unsignedDataTypes, dataTypeTestDir, dbName, testDesc) override def dataTypes: List[ReflectedDataType] = numeric ::: stringType override def unsignedDataTypes: List[ReflectedDataType] = numeric override def dataTypeTestDir: String = "multi-column-dataType-test" override def dbName: String = "multi_column_data_type_test" override def testDesc: String = "Base test for multi-column data types" def startTest(dataTypes: List[ReflectedDataType]): Unit = { val typeNames = dataTypes.map(getTypeName) val tblName = generator.getTableName(typeNames: _*) val columnNames = typeNames.zipWithIndex.map { x => generator.getColumnNameByOffset(x._2) } for (i <- columnNames.indices) { val col1 = columnNames(i) for (j <- columnNames.indices) { val col2 = columnNames(j) val dataType2 = dataTypes(j) simpleSelect(dbName, tblName, col1, col2, dataType2) } } } def check(): Unit = { if (generateData) { generator.test() } } override def test(): Unit = { startTest(dataTypes) } check() test() }
class Api { //Auth Section... //User Register... static const register = 'https://us-central1-bridge-fd58f.cloudfunctions.net/auth/register'; //User Login... static const login = 'https://us-central1-bridge-fd58f.cloudfunctions.net/auth/login'; //User Logout... static const logout = 'https://us-central1-bridge-fd58f.cloudfunctions.net/auth/logout'; //Anonymous User API Section... static const anonymousPage = 'https://us-central1-bridge-fd58f.cloudfunctions.net/anonymous/home'; //User Profile API Section... static const profile = 'https://us-central1-bridge-fd58f.cloudfunctions.net/user/profile'; //Feeds Section... static const feeds = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/feeds'; //Do the Post... static const post = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/post'; //Like or Dislike the post... static const like = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/like'; //Bookmark or Un-Bookmark the Post... static const bookmark = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/bookmark'; //Delete the specific Comment of a Post... static const delComment = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/deleteComment'; //Edit the specific Comment of a Post... static const editComment = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/editComment'; //Get the Comments of a specific Post... static const getComments = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/getComments'; //Delete the specific Post... static const delPost = 'https://us-central1-bridge-fd58f.cloudfunctions.net/home/deletePost'; }
package scaladays.akka.stream import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler} import akka.stream.{Attributes, FlowShape, Inlet, Outlet} final case class RepeatNTimes[T](n: Int) extends GraphStage[FlowShape[T, T]] { val in = Inlet[T]("RepeatNTimes.in") val out = Outlet[T]("RepeatNTimes.out") override def shape: FlowShape[T, T] = FlowShape(in, out) override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) { var element: T = null.asInstanceOf[T] var remainToBePushed: Int = 0 var terminating: Boolean = false setHandler(in, new InHandler { override def onPush(): Unit = { element = grab(in) if (remainToBePushed > 0) pushElement() } override def onUpstreamFinish(): Unit = { terminating = true if (remainToBePushed == 0) completeStage() } }) setHandler(out, new OutHandler { override def onPull(): Unit = { if (element != null) { pushElement() completeOrReset() } else { pull(in) remainToBePushed = n } } }) private def completeOrReset(): Unit = { if (remainToBePushed == 0) if (terminating) completeStage() else element = null.asInstanceOf[T] } private def pushElement(): Unit = { push(out, element) remainToBePushed -= 1 } } }
#pragma once //------------------------------------------------------------------------------ /** @class Structures::Block @ingroup Block @brief inline Block of dynamic Memory, Self Allocating on heap */ #include "Interfaces/iBlock.h" #include "Table.h" class keyBuilder : public BlockDV{ public: keyBuilder() {}; keyBuilder(const char* key) { Add(key); } void Add(const char* str) { Add((uint8_t* )str, std::strlen(str)); } void Add(const iBlockD& toAdd) { Add(toAdd.begin().Ptr(), toAdd.Size()); } void Add(const uint8_t* str, size_t numElements) { size_t s = Size(); ReserveBack(numElements); std::memcpy(begin(s).Ptr(), str, numElements); } }; struct keyCompare { keyCompare(uint8_t* lhs, uint8_t* rhs, size_t lhsSize, size_t rhsSize); size_t commonPrefix = 0; size_t lhsPostfix = 0; size_t rhsPostfix = 0; bool lhsLesser = false; bool Equal() { return !(lhsPostfix || rhsPostfix); } }; keyCompare::keyCompare(uint8_t* lhs, uint8_t* rhs, size_t lhsSize, size_t rhsSize) { size_t compSize = (lhsSize < rhsSize) ? lhsSize : rhsSize; while (*lhs == *rhs && commonPrefix < compSize) commonPrefix++, lhs++, rhs++; lhsPostfix = lhsSize - commonPrefix; rhsPostfix = rhsSize - commonPrefix; lhsLesser = *(lhs) < *(rhs); } class RadAdapter { public: RadAdapter() {}; RadAdapter(iTableD<>* allocator) : Allocator(allocator) { HeadBlockID = Allocator->Size(); Allocator->PushBack(); //Block(HeadBlockID).begin()[0]= 0; } RadAdapter(iTableD<>* allocator, size_t blockID) : Allocator(allocator), HeadBlockID(blockID) {}; virtual iBlockD* Exists(iBlockD& checkKey); //virtual const iBlockD* Exists(iBlockD& key) const; virtual iBlockD& GetOrCreate(iBlockD& key); virtual iBlockD& operator[](iBlockD& key) { return GetOrCreate(key); } protected: iBlockD& PushDownPostfix(size_t blockID, size_t keyIndex, size_t prefixLen); iBlockD& InsertKey(iBlockD& block, size_t keyIndex, uint8_t* KeyItr, size_t keyLen) ; iBlockD& InsertValue(size_t blockID, size_t keyIndex); //virtual RadAdapter& GetChildNode(size_t index); //uint8_t KeyCount() { return Block().begin()[0]; } inline iBlockD& Block(size_t BlockID) { return Allocator->GetBlock(BlockID); } size_t HeadBlockID = 0; iTableD<>* Allocator = 0; }; iBlockD* RadAdapter::Exists(iBlockD& checkKey) { uint8_t* ktr = checkKey.begin().Ptr(); uint8_t* ktrEnd = checkKey.end().Ptr(); size_t bID = HeadBlockID; if (Block(bID).Empty()) return nullptr; while (true) { uint8_t* itr = Block(bID).begin().Ptr(); if (!itr) return nullptr; uint8_t keyCount = *itr; if (!keyCount) //does not exist return nullptr; itr++; for (uint8_t i = 0; i < keyCount; i++) { size_t keySize = *(size_t*)itr - (2 * sizeof(size_t)); itr += sizeof(size_t); if (*itr <= *ktr) { // checkKey keyCompare cmp(itr, ktr, keySize, ktrEnd -ktr); itr += keySize; if (cmp.Equal()) { if (*(size_t*)itr) return &Block(*(size_t*)(itr)); // value BlockID is first return nullptr;//no value } itr += sizeof(size_t); if (!cmp.lhsPostfix) {//partial match = recurse if (!*(size_t*)itr) //no children return nullptr; bID = *(size_t*)(itr); //childNode BlockID is second break; } return nullptr; } itr += keySize + (2 * sizeof(size_t)); // next key } } return nullptr; } inline iBlockD& RadAdapter::GetOrCreate(iBlockD& checkKey) { uint8_t* ktr = checkKey.begin().Ptr(); uint8_t* ktrEnd = checkKey.end().Ptr(); size_t bID = HeadBlockID; while (true) { uint8_t* itr = Block(bID).begin().Ptr(); if (!itr) //does not exist return InsertKey(Block(bID), 0, ktr, ktrEnd - ktr); uint8_t keyCount = *itr; if (!keyCount) //does not exist return InsertKey(Block(bID), 0, ktr, ktrEnd - ktr); itr++; for (uint8_t i = 0; i < keyCount; i++) { size_t keySize = (*(size_t*)itr)-(2 * sizeof(size_t)); itr += sizeof(size_t); if (*itr >= *ktr) { // checkKey keyCompare cmp(itr, ktr, keySize, ktrEnd - ktr); if (!cmp.commonPrefix) {//insert new here return InsertKey(Block(bID), i, ktr, cmp.rhsPostfix); } if (cmp.Equal()) return Block(*(size_t*)(itr + keySize)); // value BlockID is first ktr += cmp.commonPrefix; //increment key by prefix if (!cmp.lhsPostfix) {//partial match = recurse bID = *(size_t*)(itr + keySize + sizeof(size_t)); //childNode BlockID is second break; } else { //push down postfix iBlockD& nb = PushDownPostfix(bID, i, cmp.commonPrefix); if (ktrEnd - ktr) return InsertKey(nb, (cmp.lhsLesser ? 1 : 0), ktr, ktrEnd - ktr); else //add value to prefix return InsertValue(bID, i); } } itr += keySize + (2 * sizeof(size_t)); // next key } return InsertKey(Block(bID), keyCount, ktr, ktrEnd - ktr); } return Block(bID); } inline iBlockD& RadAdapter::PushDownPostfix(size_t BlockID, size_t keyIndex, size_t prefixLen) { //get key len uint8_t* ins = Block(BlockID).begin().Ptr(); ins++; for (size_t i = 0; i < keyIndex; i++) ins += *(size_t*)ins + sizeof(size_t); size_t keylen = *(size_t*)ins; //ins + sizeof(size_t) + prefixLen; //update childblockID and valuesBlockID // get new block size_t newBlockID = Allocator->Size(); Allocator->PushBack(1+keylen -prefixLen + sizeof(size_t)); iBlockD& newBlock = Block(newBlockID); uint8_t* cpy = newBlock.begin().Ptr(); cpy[0]= 1; //set keycound cpy++; *(size_t*)cpy = keylen - prefixLen;//set keysize //copy postfix std::memcpy(cpy + sizeof(size_t), ins + sizeof(size_t) + prefixLen, *(size_t*)cpy); //remove postfix std::memmove(ins + sizeof(size_t), ins + *(size_t*)ins, Block(BlockID).end().Ptr() - ins + *(size_t*)ins); *(size_t*)ins = prefixLen + (2 * sizeof(size_t)); //set new size ins += prefixLen +sizeof(size_t); *(size_t*)ins = 0; // set value id ins += sizeof(size_t); *(size_t*)ins = newBlockID; // set children id Block(BlockID).Resize(Block(BlockID).Size() - (keylen - prefixLen));//trim excess size return newBlock; } inline iBlockD& RadAdapter::InsertKey(iBlockD& block, size_t keyIndex, uint8_t* KeyItr, size_t keyLen) { //shift remaining if (block.Empty()) { block.ReserveBack(1); block.begin()[0] = 0; } uint8_t* ins = block.begin().Ptr(); (*ins)++; //increas keycount ins++; for (size_t i = 0; i < keyIndex; i++) ins += *(size_t*)ins + sizeof(size_t); size_t s = block.end().Ptr()-ins; size_t tmp = ins - block.begin().Ptr(); block.ReserveBack(keyLen + (3 * sizeof(size_t))); ins = block.begin(tmp).Ptr(); //iterator invalidated if (s) std::memmove(ins + keyLen + (3 * sizeof(size_t)), ins, s); *(size_t*)ins = keyLen+(2*sizeof(size_t)); //set key size ins += sizeof(size_t); std::memcpy(ins, KeyItr, keyLen); ins += keyLen; *(size_t*)ins = Allocator->Size(); Allocator->PushBack(); ins += sizeof(size_t); *(size_t*)ins = 0;//no children return Block(Allocator->Size()-1); } inline iBlockD& RadAdapter::InsertValue(size_t blockID, size_t keyIndex) { //get key len uint8_t* ins = Block(blockID).begin().Ptr(); ins++; for (size_t i = 0; i < keyIndex; i++) ins += *(size_t*)ins + sizeof(size_t); ins += *(size_t*)ins - sizeof(size_t); *(size_t*)ins = Allocator->Size(); Allocator->PushBack(); return Block(*(size_t*)ins); }
namespace Juniper.Input { /// <summary> /// An extension of Unity's UnityEngine.EventSystem.PointerInputModule.InputButton, /// to include a "None" value, for making explicit selections of no support for /// input features while working in the editor. /// </summary> public enum InputEventButton { /// <summary> /// No input selection. /// </summary> None = -1, /// <summary> /// The left mouse button. /// </summary> Left = 0, /// <summary> /// The right mouse button. /// </summary> Right = 1, /// <summary> /// The middle mouse button. /// </summary> Middle = 2 } }