repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
rmaldrix/DOC
engine-plugins/giraph-plugins/src/test/scala/org/apache/spark/sql/parquet/atk/giraph/frame/TestingLdaVertexOutputFormat.scala
<gh_stars>0 /* // Copyright (c) 2015 Intel 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. */ package org.apache.spark.sql.parquet.atk.giraph.frame import org.trustedanalytics.atk.giraph.io.{ LdaEdgeData, LdaVertexData, LdaVertexId } import org.apache.giraph.graph.Vertex import org.apache.giraph.io.{ VertexOutputFormat, VertexWriter } import org.apache.hadoop.mapreduce.{ JobContext, OutputCommitter, TaskAttemptContext } import org.apache.mahout.math.Vector import scala.collection.mutable import scala.collection.JavaConversions._ /** * Object holds global values for tests */ object TestingLdaOutputResults { val docResults = mutable.Map[String, Vector]() val wordResults = mutable.Map[String, Vector]() val topicGivenWord = mutable.Map[String, Vector]() } /** * OutputFormat for LDA testing */ class TestingLdaVertexOutputFormat extends VertexOutputFormat[LdaVertexId, LdaVertexData, LdaEdgeData] { override def createVertexWriter(context: TaskAttemptContext): VertexWriter[LdaVertexId, LdaVertexData, LdaEdgeData] = { new VertexWriter[LdaVertexId, LdaVertexData, LdaEdgeData] { override def initialize(context: TaskAttemptContext): Unit = {} override def writeVertex(vertex: Vertex[LdaVertexId, LdaVertexData, LdaEdgeData]): Unit = { if (vertex.getId.isDocument) { TestingLdaOutputResults.docResults += vertex.getValue.getOriginalId -> vertex.getValue.getLdaResult } else { TestingLdaOutputResults.wordResults += vertex.getValue.getOriginalId -> vertex.getValue.getLdaResult TestingLdaOutputResults.topicGivenWord += vertex.getValue.getOriginalId -> vertex.getValue.getTopicGivenWord } } override def close(context: TaskAttemptContext): Unit = {} } } override def checkOutputSpecs(context: JobContext): Unit = {} override def getOutputCommitter(context: TaskAttemptContext): OutputCommitter = new DummyOutputCommitter }
lemankk/bootstrap-styled-v4
src/Container/index.js
import styled from 'styled-components'; import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import omit from 'lodash.omit'; import { makeContainer, makeContainerMaxWidths } from '@bootstrap-styled/css-mixins/lib/grid'; export const defaultProps = { theme: { '$grid-gutter-width': '30px', '$container-max-widths': { sm: '540px', md: '720px', lg: '960px', xl: '1140px', }, '$enable-grid-classes': true, }, fluid: false, }; export const propTypes = { /** * @ignore */ className: PropTypes.string, /** Theme variables. Can be: */ theme: PropTypes.shape({ '$grid-gutter-width': PropTypes.string, '$container-max-widths': PropTypes.object, '$enable-grid-classes': PropTypes.bool, }), /** Use a responsive container */ fluid: PropTypes.bool, }; class ContainerUnstyled extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = propTypes; static defaultProps = defaultProps; render() { const { className, fluid, ...attributes } = omit(this.props, ['theme']); return ( <div className={cn(className, { container: !fluid, 'container-fluid': fluid, })} {...attributes} /> ); } } /** * Use our `<Container />` component, to affect common layout to your components. */ const Container = styled(ContainerUnstyled)` ${(props) => ` ${makeContainer( props.theme['$enable-grid-classes'], props.theme['$grid-gutter-width'] )} ${!props.fluid ? makeContainerMaxWidths( props.theme['$enable-grid-classes'], props.theme['$container-max-widths'], props.theme['$grid-breakpoints'] ) : ''} `} `; Container.defaultProps = defaultProps; Container.propTypes = propTypes; /** @component */ export default Container;
merobal/angular-formio-deploy
resource/formio-resource.js
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { FormioResourceConfig, FormioResources, FormioResourceService, FormioResourceComponent, FormioResourceViewComponent, FormioResourceEditComponent, FormioResourceDeleteComponent, FormioResourceCreateComponent, FormioResourceIndexComponent, FormioResourceRoutes, FormioResource } from './index'; export { FormioAuthConfig as ɵc } from '../auth/auth.config'; export { FormioAuthService as ɵa } from '../auth/auth.service'; export { FormioAlerts as ɵj } from '../components/alerts/formio.alerts'; export { FormioAlertsComponent as ɵi } from '../components/alerts/formio.alerts.component'; export { FormBuilderComponent as ɵg } from '../components/formbuilder/formbuilder.component'; export { FormioComponent as ɵf } from '../components/formio/formio.component'; export { FormioLoader as ɵd } from '../components/loader/formio.loader'; export { FormioLoaderComponent as ɵh } from '../components/loader/formio.loader.component'; export { FormioAppConfig as ɵb } from '../formio.config'; export { FormioModule as ɵe } from '../formio.module'; export { extendRouter as ɵv } from '../formio.utils'; export { GridBodyComponent as ɵp } from '../grid/GridBodyComponent'; export { GridFooterComponent as ɵr } from '../grid/GridFooterComponent'; export { GridHeaderComponent as ɵn } from '../grid/GridHeaderComponent'; export { FormGridBodyComponent as ɵo } from '../grid/form/FormGridBody.component'; export { FormGridFooterComponent as ɵq } from '../grid/form/FormGridFooter.component'; export { FormGridHeaderComponent as ɵm } from '../grid/form/FormGridHeader.component'; export { FormioGridComponent as ɵl } from '../grid/grid.component'; export { FormioGrid as ɵk } from '../grid/grid.module'; export { SubmissionGridBodyComponent as ɵt } from '../grid/submission/SubmissionGridBody.component'; export { SubmissionGridFooterComponent as ɵu } from '../grid/submission/SubmissionGridFooter.component'; export { SubmissionGridHeaderComponent as ɵs } from '../grid/submission/SubmissionGridHeader.component';
bonarhyme/rhymebet
src/reducers/referralReducer.js
import { GET_USER_REFS_REQUEST, GET_USER_REFS_SUCCESS, GET_USER_REFS_FAIL, } from "../constants/referralConstants"; import { USER_LOGOUT } from "../constants/userConstants"; export const getUserRefsReducer = (state = {}, action) => { switch (action.type) { case GET_USER_REFS_REQUEST: return { loading: true, }; case GET_USER_REFS_SUCCESS: return { loading: false, success: true, serverReply: action.payload, }; case GET_USER_REFS_FAIL: return { loading: false, success: false, error: action.payload }; case USER_LOGOUT: return {}; default: return state; } };
mattrunyon/deephaven-core
engine/table/src/main/java/io/deephaven/engine/util/ScriptFinder.java
<filename>engine/table/src/main/java/io/deephaven/engine/util/ScriptFinder.java package io.deephaven.engine.util; import io.deephaven.base.verify.Assert; import io.deephaven.base.verify.Require; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Optional; class ScriptFinder { final private String defaultScriptPath; static class FileOrStream { FileOrStream(File file) { this.file = Require.neqNull(file, "file"); this.stream = null; this.isFile = true; } FileOrStream(InputStream stream) { this.file = null; this.stream = Require.neqNull(stream, "stream"); this.isFile = false; } Optional<File> getFile() { if (isFile) { return Optional.of(Require.neqNull(file, "file")); } else { return Optional.empty(); } } Optional<InputStream> getStream() { if (isFile) { return Optional.empty(); } else { return Optional.of(Require.neqNull(stream, "stream")); } } private final boolean isFile; private final File file; private final InputStream stream; } ScriptFinder(String defaultScriptPath) { this.defaultScriptPath = defaultScriptPath; } InputStream findScript(final String script) throws IOException { return findScript(script, null); } FileOrStream findScriptEx(final String script) throws IOException { return findScriptEx(script, null); } InputStream findScript(final String script, final String dbScriptPath) throws IOException { final FileOrStream fileOrStream = findScriptEx(script, dbScriptPath); final Optional<InputStream> streamOptional = fileOrStream.getStream(); if (streamOptional.isPresent()) { return streamOptional.get(); } else { final Optional<File> fileOptional = fileOrStream.getFile(); Assert.assertion(fileOptional.isPresent(), "fileOptional.isPresent()"); // noinspection ConstantConditions,OptionalGetWithoutIsPresent -- if we don't have a stream we must have a // file return new FileInputStream(fileOptional.get()); } } private FileOrStream findScriptEx(final String script, final String dbScriptPath) throws IOException { /* * NB: This code is overdue for some cleanup. In practice, there are two modes: (1) local - a user runs a local * groovy session from IntelliJ or otherwise, and needs to find scripts under their devroot. (2) deployed - a * groovy session is created from deployed code, in which case scripts are only found via the classpath. I had * hopes for being able to do everything via the classpath, but that doesn't allow for runtime changes without * additional work. */ final String[] paths = (dbScriptPath == null ? defaultScriptPath : dbScriptPath).split(";"); for (String path : paths) { final File file = new File(path + "/" + script); if (file.exists() && file.isFile()) { return new FileOrStream(file); } } InputStream result = ScriptFinder.class.getResourceAsStream(script); if (result == null) { result = ScriptFinder.class.getResourceAsStream("/" + script); } if (result != null) { return new FileOrStream(result); } throw new IOException("Can not find script: script=" + script + ", dbScriptPath=" + (Arrays.toString(paths)) + ", classpath=" + System.getProperty("java.class.path")); } }
OpenMPDK/SMDK
lib/linux-5.18-rc3-smdk/drivers/iio/chemical/atlas-ezo-sensor.c
<reponame>OpenMPDK/SMDK // SPDX-License-Identifier: GPL-2.0+ /* * atlas-ezo-sensor.c - Support for Atlas Scientific EZO sensors * * Copyright (C) 2020 Konsulko Group * Author: <NAME> <<EMAIL>> */ #include <linux/init.h> #include <linux/delay.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/property.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/iio/iio.h> #define ATLAS_EZO_DRV_NAME "atlas-ezo-sensor" #define ATLAS_INT_TIME_IN_MS 950 #define ATLAS_INT_HUM_TIME_IN_MS 350 enum { ATLAS_CO2_EZO, ATLAS_O2_EZO, ATLAS_HUM_EZO, }; struct atlas_ezo_device { const struct iio_chan_spec *channels; int num_channels; int delay; }; struct atlas_ezo_data { struct i2c_client *client; const struct atlas_ezo_device *chip; /* lock to avoid multiple concurrent read calls */ struct mutex lock; u8 buffer[8]; }; #define ATLAS_CONCENTRATION_CHANNEL(_modifier) \ { \ .type = IIO_CONCENTRATION, \ .modified = 1,\ .channel2 = _modifier, \ .info_mask_separate = \ BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE), \ .scan_index = 0, \ .scan_type = { \ .sign = 'u', \ .realbits = 32, \ .storagebits = 32, \ .endianness = IIO_CPU, \ }, \ } static const struct iio_chan_spec atlas_co2_ezo_channels[] = { ATLAS_CONCENTRATION_CHANNEL(IIO_MOD_CO2), }; static const struct iio_chan_spec atlas_o2_ezo_channels[] = { ATLAS_CONCENTRATION_CHANNEL(IIO_MOD_O2), }; static const struct iio_chan_spec atlas_hum_ezo_channels[] = { { .type = IIO_HUMIDITYRELATIVE, .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE), .scan_index = 0, .scan_type = { .sign = 'u', .realbits = 32, .storagebits = 32, .endianness = IIO_CPU, }, }, }; static struct atlas_ezo_device atlas_ezo_devices[] = { [ATLAS_CO2_EZO] = { .channels = atlas_co2_ezo_channels, .num_channels = 1, .delay = ATLAS_INT_TIME_IN_MS, }, [ATLAS_O2_EZO] = { .channels = atlas_o2_ezo_channels, .num_channels = 1, .delay = ATLAS_INT_TIME_IN_MS, }, [ATLAS_HUM_EZO] = { .channels = atlas_hum_ezo_channels, .num_channels = 1, .delay = ATLAS_INT_HUM_TIME_IN_MS, }, }; static void atlas_ezo_sanitize(char *buf) { char *ptr = strchr(buf, '.'); if (!ptr) return; memmove(ptr, ptr + 1, strlen(ptr)); } static int atlas_ezo_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask) { struct atlas_ezo_data *data = iio_priv(indio_dev); struct i2c_client *client = data->client; if (chan->type != IIO_CONCENTRATION) return -EINVAL; switch (mask) { case IIO_CHAN_INFO_RAW: { int ret; long tmp; mutex_lock(&data->lock); tmp = i2c_smbus_write_byte(client, 'R'); if (tmp < 0) { mutex_unlock(&data->lock); return tmp; } msleep(data->chip->delay); tmp = i2c_master_recv(client, data->buffer, sizeof(data->buffer)); if (tmp < 0 || data->buffer[0] != 1) { mutex_unlock(&data->lock); return -EBUSY; } /* removing floating point for fixed number representation */ atlas_ezo_sanitize(data->buffer + 2); ret = kstrtol(data->buffer + 1, 10, &tmp); *val = tmp; mutex_unlock(&data->lock); return ret ? ret : IIO_VAL_INT; } case IIO_CHAN_INFO_SCALE: switch (chan->type) { case IIO_HUMIDITYRELATIVE: *val = 10; return IIO_VAL_INT; case IIO_CONCENTRATION: break; default: return -EINVAL; } /* IIO_CONCENTRATION modifiers */ switch (chan->channel2) { case IIO_MOD_CO2: *val = 0; *val2 = 100; /* 0.0001 */ return IIO_VAL_INT_PLUS_MICRO; case IIO_MOD_O2: *val = 100; return IIO_VAL_INT; } return -EINVAL; } return 0; } static const struct iio_info atlas_info = { .read_raw = atlas_ezo_read_raw, }; static const struct i2c_device_id atlas_ezo_id[] = { { "atlas-co2-ezo", (kernel_ulong_t)&atlas_ezo_devices[ATLAS_CO2_EZO] }, { "atlas-o2-ezo", (kernel_ulong_t)&atlas_ezo_devices[ATLAS_O2_EZO] }, { "atlas-hum-ezo", (kernel_ulong_t)&atlas_ezo_devices[ATLAS_HUM_EZO] }, {} }; MODULE_DEVICE_TABLE(i2c, atlas_ezo_id); static const struct of_device_id atlas_ezo_dt_ids[] = { { .compatible = "atlas,co2-ezo", .data = &atlas_ezo_devices[ATLAS_CO2_EZO], }, { .compatible = "atlas,o2-ezo", .data = &atlas_ezo_devices[ATLAS_O2_EZO], }, { .compatible = "atlas,hum-ezo", .data = &atlas_ezo_devices[ATLAS_HUM_EZO], }, {} }; MODULE_DEVICE_TABLE(of, atlas_ezo_dt_ids); static int atlas_ezo_probe(struct i2c_client *client, const struct i2c_device_id *id) { const struct atlas_ezo_device *chip; struct atlas_ezo_data *data; struct iio_dev *indio_dev; indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data)); if (!indio_dev) return -ENOMEM; if (dev_fwnode(&client->dev)) chip = device_get_match_data(&client->dev); else chip = (const struct atlas_ezo_device *)id->driver_data; if (!chip) return -EINVAL; indio_dev->info = &atlas_info; indio_dev->name = ATLAS_EZO_DRV_NAME; indio_dev->channels = chip->channels; indio_dev->num_channels = chip->num_channels; indio_dev->modes = INDIO_DIRECT_MODE; data = iio_priv(indio_dev); data->client = client; data->chip = chip; mutex_init(&data->lock); return devm_iio_device_register(&client->dev, indio_dev); }; static struct i2c_driver atlas_ezo_driver = { .driver = { .name = ATLAS_EZO_DRV_NAME, .of_match_table = atlas_ezo_dt_ids, }, .probe = atlas_ezo_probe, .id_table = atlas_ezo_id, }; module_i2c_driver(atlas_ezo_driver); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("Atlas Scientific EZO sensors"); MODULE_LICENSE("GPL");
CharNing/program_zol
ZOL/src/script/registry.js
<gh_stars>0 require(['config'], function () { require(['jquery','jqcookie'], function () { registry(); }) }) // 表单注册 function registry() { const $form = $('#registry-form');// 表单 const $phone = $('#userphone'); // 手机号码 const $incode = $('#incode');// 验证码输入框 const $code = $('#code') // 验证码 const $password = $('#password');//密码 const $repass = $('#repeat');// 确认密码 const $wrophone = $('#registry-form .wrophone'); // 手机错误提示 const $wrocode = $('#registry-form .wrocode'); // 验证码错误提示 const $wropass = $('#registry-form .wropass');// 密码错误提示 const $wrorepeat = $('#registry-form .wrorepeat');// 再次确认密码错误提示 const $agree = $('.agree .chose'); // 阅读协议复选框 const $btn = $('#registry-form')// 提交按钮 let passlock = true; let tellock = true; let paswdlock = true; let codelock = true; let agreelock = true; code($code); // 生成验证码 // 手机号码验证 $phone.on('focus', function () { $(this).css('border-color', '#CC0000') }) $phone.on('blur', function () { let reg = /^1[3456789]\d{9}$/; if ($(this).val() !== '') { if (reg.test($(this).val())) { $.ajax({ type:'post', url:'http://10.31.155.61/program_zol/ZOL/php/registry.php', data:{ userphone:$phone.val() } }).done(function(isExist){ if(!isExist){ $wrophone.css({ 'background-position-y': '-148px', 'display': 'block' }) .html(''); tellock = true; }else{ $wrophone.css({ 'background-position-y': '-184px', 'display': 'block', }).html('手机号已注册'); tellock = false; } }) } else { $wrophone.css({ 'background-position-y': '-184px', 'display': 'block', }).html('请填写有效的11位手机号码'); tellock = false; } } else { $wrophone.css({ 'background-position-y': '-184px', 'display': 'block' }) .html('手机号码不能为空'); tellock = false; } $(this).css('border-color', '#CCC'); }) // 点击刷新验证码 $code.on('click',function(){ code($(this)); $wrocode.css({ 'display': 'none' }).html(''); }) // 验证验证码 $incode.on('focus', function () { $(this).css('border-color', '#c00000'); }) $incode.on('blur', function () { if ($(this).val() !== '') { if($code.html() === $incode.val()){ $wrocode.css({ 'background-position-y': '-148px', 'display': 'block' }).html(''); codelock = true; }else{ $wrocode.css({ 'background-position-y': '-184px', 'display': 'block' }) .html('验证码错误,请重新输入'); codelock = false; } } else { $wrocode.css({ 'background-position-y': '-184px', 'display': 'block' }) .html('请填写验证码'); codelock = false; } $(this).css('border-color', '#CCC'); }) // 设置密码 $password.on('focus', function () { $(this).css('border-color', '#c00000'); }) $password.on('blur', function () { let regNum = /^[0-9]+$/g; if ($(this).val() !== '') { if ($(this).val().length >= 6 && $(this).val().length <= 16) { if (regNum.test($(this).val())) { $wropass.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }).html('密码不能全是数字'); paswdlock = false; } else { $wropass.css({ 'background-position-y': '-148px', 'display': 'block', 'color': '#ff3333' }).html(''); paswdlock = true; } } else { $wropass.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }).html('6-16位字符,可使用字母、数字或符号的组合'); paswdlock = false; } } else { $wropass.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }) .html('请填写密码'); paswdlock = false; } $(this).css('border-color', '#CCC'); }) // 确认密码 $repass.on('focus', function () { $(this).css('border-color', '#c00000'); }) $repass.on('blur', function () { if ($(this).val() !== '') { if ($(this).val() === $password.val()) { $wrorepeat.css({ 'background-position-y': '-148px', 'display': 'block', }) .html(''); paswdlock = true; } else { $wrorepeat.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }) .html('两次填写的密码不一致'); paswdlock = false; } } else { $wrorepeat.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }) .html('请填写确认密码'); paswdlock = false; } $(this).css('border-color', '#CCC'); }) // 用户协议是否打钩 $agree.on('click',function(){ if($agree.prop('checked')){ agreelock =true; }else{ agreelock=false; } }) // 点击提交 $btn.on('submit',function(){ // 判断手机号码是否为空 if($phone.val()===''){ $wrophone.css({ 'background-position-y': '-184px', 'display': 'block' }) .html('手机号码不能为空'); tellock = false; } // 判断验证码是否为空 if($incode.val()===''){ $wrocode.css({ 'background-position-y': '-184px', 'display': 'block' }) .html('请填写验证码'); codelock = false; } // 判断密码是否为空 if($password.val()===''){ $wropass.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }) .html('请填写密码'); paswdlock = false; } //判断确认密码是否为空 if($repass.val()===''){ $wrorepeat.css({ 'background-position-y': '-184px', 'display': 'block', 'color': '#ff3333' }) .html('请填写确认密码'); paswdlock = false; } //判断阅读协议是否打钩 if(!agreelock){ alert('请先阅读用户协议'); return false; }else{ if(!passlock || !tellock || !paswdlock || !codelock || !agreelock){ return false; } } }) } // 包装生成验证码函数 function code(box) { let arr = []; for (let i = 48; i <= 57; i++) { arr.push(String.fromCharCode(i)); } for (let i = 97; i <= 122; i++) { arr.push(String.fromCharCode(i)); } let codehtml = ''; for (let i = 1; i <= 6; i++) { let index = parseInt(Math.random() * (arr.length)); if (index > 9) { let bstop = Math.random() > 0.5 ? true : false; if (bstop) { codehtml += arr[index].toUpperCase(); } else { codehtml += arr[index]; } } else { codehtml += arr[index]; } } box.html(codehtml); }
JuanOriana/TP2-SO-NEW
Userland/SampleCodeModule/libraries/processes.c
// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include <processes.h> int createProcess(void (*entryPoint)(int, char **), int argc, char **argv, int fg, int *fd) { return syscall(CREATE_PROC, (uint64_t)entryPoint, argc, (uint64_t)argv, (int)fg, (uint64_t)fd, 0); } int killProcess(uint64_t pid) { return syscall(KILL, pid, 0, 0, 0, 0, 0); } int blockProcess(uint64_t pid) { return syscall(BLOCK, pid, 0, 0, 0, 0, 0); } int unblockProcess(uint64_t pid) { return syscall(UNBLOCK, pid, 0, 0, 0, 0, 0); } int getPID() { return syscall(GET_PID, 0, 0, 0, 0, 0, 0); } void nice(uint64_t pid, int priority) { syscall(NICE, pid, priority, 0, 0, 0, 0); } void yield(uint64_t pid) { syscall(YIELD, 0, 0, 0, 0, 0, 0); } void wait(uint64_t pid) { syscall(WAIT, pid, 0, 0, 0, 0, 0); }
whitebear0909/asb_laravel_vue
public/js/resources_js_views_plugins_Notifications_vue.js
<reponame>whitebear0909/asb_laravel_vue "use strict"; (self["webpackChunk"] = self["webpackChunk"] || []).push([["resources_js_views_plugins_Notifications_vue"],{ /***/ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js&": /*!***********************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js& ***! \***********************************************************************************************************************************************************************************************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { __webpack_require__.r(__webpack_exports__); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ methods: { // Trigger a new toast toast: function toast(title, content) { var variant = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var append = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var toaster = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'b-toaster-top-right'; var autoHideDelay = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5000; this.$bvToast.toast(content, { title: title, toaster: toaster, variant: variant, autoHideDelay: autoHideDelay, appendToast: append }); } } }); /***/ }), /***/ "./resources/js/views/plugins/Notifications.vue": /*!******************************************************!*\ !*** ./resources/js/views/plugins/Notifications.vue ***! \******************************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Notifications.vue?vue&type=template&id=d1ab2eac& */ "./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac&"); /* harmony import */ var _Notifications_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Notifications.vue?vue&type=script&lang=js& */ "./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js&"); /* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! !../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); /* normalize component */ ; var component = (0,_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])( _Notifications_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__.render, _Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__.staticRenderFns, false, null, null, null ) /* hot reload */ if (false) { var api; } component.options.__file = "resources/js/views/plugins/Notifications.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ "./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js&": /*!*******************************************************************************!*\ !*** ./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js& ***! \*******************************************************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Notifications_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!../../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./Notifications.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=script&lang=js&"); /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Notifications_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /***/ "./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac&": /*!*************************************************************************************!*\ !*** ./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac& ***! \*************************************************************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "render": function() { return /* reexport safe */ _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__.render; }, /* harmony export */ "staticRenderFns": function() { return /* reexport safe */ _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__.staticRenderFns; } /* harmony export */ }); /* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Notifications_vue_vue_type_template_id_d1ab2eac___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./Notifications.vue?vue&type=template&id=d1ab2eac& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac&"); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac&": /*!****************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/views/plugins/Notifications.vue?vue&type=template&id=d1ab2eac& ***! \****************************************************************************************************************************************************************************************************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "render": function() { return /* binding */ render; }, /* harmony export */ "staticRenderFns": function() { return /* binding */ staticRenderFns; } /* harmony export */ }); var render = function () { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", [ _c("base-page-heading", { attrs: { title: "Notifications", subtitle: "Powerful alerts for your application.", }, scopedSlots: _vm._u([ { key: "extra", fn: function () { return [ _c( "b-breadcrumb", { staticClass: "breadcrumb-alt" }, [ _c( "b-breadcrumb-item", { attrs: { href: "javascript:void(0)" } }, [_vm._v("Plugins")] ), _vm._v(" "), _c("b-breadcrumb-item", { attrs: { active: "" } }, [ _vm._v("Notifications"), ]), ], 1 ), ] }, proxy: true, }, ]), }), _vm._v(" "), _c( "div", { staticClass: "content" }, [ _c( "base-block", { attrs: { rounded: "", title: "Bootstrap Toasts" } }, [ _c("h4", { staticClass: "border-bottom pb-2" }, [ _vm._v("Default"), ]), _vm._v(" "), _c( "b-row", { staticClass: "items-push" }, [ _c("b-col", { attrs: { lg: "4" } }, [ _c("p", { staticClass: "font-size-sm text-muted" }, [ _vm._v( "\n A nice toast with a message\n " ), ]), ]), _vm._v(" "), _c( "b-col", { attrs: { lg: "8" } }, [ _c( "b-button", { staticClass: "push", attrs: { variant: "alt-secondary" }, on: { click: function ($event) { return _vm.toast("Prepend Toast", "Toast content") }, }, }, [_vm._v("\n Prepend Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [_vm._v("this.toast('Title', 'Content')")]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-secondary" }, on: { click: function ($event) { return _vm.toast( "Append Toast", "Toast content", null, true ) }, }, }, [_vm._v("\n Append Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v("this.toast('Title', 'Content', null, true)"), ]), ]), ], 1 ), ], 1 ), _vm._v(" "), _c("h4", { staticClass: "border-bottom pb-2" }, [ _vm._v("Position"), ]), _vm._v(" "), _c( "b-row", { staticClass: "items-push" }, [ _c("b-col", { attrs: { lg: "4" } }, [ _c("p", { staticClass: "font-size-sm text-muted" }, [ _vm._v( "\n You can show your notification in multiple screen positions\n " ), ]), ]), _vm._v(" "), _c( "b-col", { attrs: { lg: "8" } }, [ _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Top Right Toast", "Toast content", null, false, "b-toaster-top-right" ) }, }, }, [_vm._v("\n Top Right Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-top-right')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Top Left Toast", "Toast content", null, false, "b-toaster-top-left" ) }, }, }, [_vm._v("\n Top Left Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-top-left')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Top Center Toast", "Toast content", null, false, "b-toaster-top-center" ) }, }, }, [_vm._v("\n Top Center Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-top-center')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Top Full Toast", "Toast content", null, false, "b-toaster-top-full" ) }, }, }, [_vm._v("\n Top Full Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-top-full')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Bottom Right Toast", "Toast content", null, false, "b-toaster-bottom-right" ) }, }, }, [_vm._v("\n Bottom Right Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-bottom-right')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Bottom Left Toast", "Toast content", null, false, "b-toaster-bottom-left" ) }, }, }, [_vm._v("\n Bottom Left Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-bottom-left')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Bottom Center Toast", "Toast content", null, false, "b-toaster-bottom-center" ) }, }, }, [ _vm._v( "\n Bottom Center Toast\n " ), ] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-bottom-center')" ), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-primary" }, on: { click: function ($event) { return _vm.toast( "Bottom Full Toast", "Toast content", null, false, "b-toaster-bottom-full" ) }, }, }, [_vm._v("\n Bottom Full Toast\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v( "this.toast('Title', 'Content', null, false, 'b-toaster-bottom-full')" ), ]), ]), ], 1 ), ], 1 ), _vm._v(" "), _c("h4", { staticClass: "border-bottom pb-2" }, [ _vm._v("Variants"), ]), _vm._v(" "), _c( "b-row", { staticClass: "items-push" }, [ _c("b-col", { attrs: { lg: "4" } }, [ _c("p", { staticClass: "font-size-sm text-muted" }, [ _vm._v( "\n You can also specify color variations\n " ), ]), ]), _vm._v(" "), _c( "b-col", { attrs: { lg: "8" } }, [ _c( "b-button", { staticClass: "push", attrs: { variant: "alt-success" }, on: { click: function ($event) { return _vm.toast( "Success Toast", "Toast content", "success" ) }, }, }, [_vm._v("\n Success\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v("this.toast('Title', 'Content', 'success')"), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-info" }, on: { click: function ($event) { return _vm.toast( "Info Toast", "Toast content", "info" ) }, }, }, [_vm._v("\n Info\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v("this.toast('Title', 'Content', 'info')"), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-warning" }, on: { click: function ($event) { return _vm.toast( "Warning Toast", "Toast content", "warning" ) }, }, }, [_vm._v("\n Warning\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v("this.toast('Title', 'Content', 'warning')"), ]), ]), _vm._v(" "), _c( "b-button", { staticClass: "push", attrs: { variant: "alt-danger" }, on: { click: function ($event) { return _vm.toast( "Danger Toast", "Toast content", "danger" ) }, }, }, [_vm._v("\n Danger\n ")] ), _vm._v(" "), _c("p", { staticClass: "font-w600 mb-0" }, [ _vm._v("\n JS code:\n "), ]), _vm._v(" "), _c("p", { staticClass: "mb-5" }, [ _c("code", [ _vm._v("this.toast('Title', 'Content', 'danger')"), ]), ]), ], 1 ), ], 1 ), ], 1 ), ], 1 ), ], 1 ) } var staticRenderFns = [] render._withStripped = true /***/ }) }]);
gdickey273/hiking-app
client/src/components/Banner/Banner.js
import React from "react"; import './Banner.css'; import Trails from '../Trails'; // import Detail from "../../pages/Detail"; // import NoMatch from "../../pages/NoMatch"; // import { Route, Switch } from 'react-router-dom'; function Banner(props){ return ( <div className="banner"> <h3>Find Trails:</h3> <Trails renderTrailById={props.renderTrailById}/> </div> ) }; export default Banner;
gosailing/MVVMArms
arms/src/main/java/me/xiaobailong24/mvvmarms/mvvm/binding/BaseBindHolder.java
<reponame>gosailing/MVVMArms package me.xiaobailong24.mvvmarms.mvvm.binding; import android.databinding.ViewDataBinding; import android.view.View; import com.chad.library.adapter.base.BaseViewHolder; import me.xiaobailong24.mvvmarms.R; /** * @author xiaobailong24 * @date 2017/6/30 * DataBinding BaseBindHolder */ public class BaseBindHolder extends BaseViewHolder { public BaseBindHolder(View view) { super(view); } public ViewDataBinding getBinding() { return (ViewDataBinding) itemView.getTag(R.id.BaseQuickAdapter_databinding_support); } }
ikovac/boutique
server/enrollment/enrollment.controller.js
<reponame>ikovac/boutique 'use strict'; const { createError } = require('../common/errors'); const { Enrollment, User, Sequelize } = require('../common/database'); const HttpStatus = require('http-status'); const map = require('lodash/map'); const { CONFLICT } = HttpStatus; const Op = Sequelize.Op; const processOutput = model => ({ ...model.toJSON(), learner: model.learner.profile }); function list({ query: { programId, learnerId, filter }, options }, res) { const cond = []; const include = [{ model: User.match(filter), as: 'learner' }]; if (programId) cond.push({ programId }); if (learnerId) cond.push({ learnerId }); const opts = { where: { [Op.and]: cond }, include, ...options }; return Enrollment.findAndCountAll(opts).then(({ rows, count }) => { res.jsend.success({ items: map(rows, processOutput), total: count }); }); } async function create({ body }, res) { const { learnerId, programId } = body; if (!Array.isArray(learnerId)) { const [result] = await Enrollment.restoreOrCreate(learnerId, programId); if (result.isRejected()) return createError(CONFLICT); const enrollment = await result.value().reload({ include: ['learner'] }); return res.jsend.success(enrollment); } const [learners, enrollments] = await bulkCreate(learnerId, programId); const failed = learners.map(it => ({ programId, learnerId: it.id, learner: it.profile })); const created = map(enrollments, processOutput); res.jsend.success({ failed, created }); } function destroy({ params }, res) { return Enrollment.destroy({ where: { id: params.id } }) .then(() => res.end()); } module.exports = { list, create, destroy }; async function bulkCreate(learnerIds, programId, options = {}) { const enrollmentIds = []; const failedLearnerIds = []; const results = await Enrollment.restoreOrCreate(learnerIds, programId, options); results.forEach((it, index) => { if (it.isRejected()) return failedLearnerIds.push(learnerIds[index]); enrollmentIds.push(it.value().id); }); return Promise.all([ User.findAll({ where: { id: failedLearnerIds } }), Enrollment.findAll({ where: { id: enrollmentIds }, include: ['learner'] }) ]); }
fabriciocgf/IOT_LoRa_Dashboard
src/DashboardServices/PlainTextWidgetFactory.js
import { UserEvents } from "../UserEvents/UserEvents.js"; let _plainTextWidgetFactory = null; let _userEvents = null; //The default template for a widget using the canvas let htmlTemplate = ` <div id="templateWidget" class="grid-stack-item-content"> <div class="widget-header"> <div class="widget-title"> Widget-Title & Info </div> <button type="button" class="btn btn-danger remove-widget-button" id="removeWidgetButton">X</button> </div> <div class="widget-footer"> <button class="btn btn-sm btn-default configureWidgetButton" id="configureWidgetButton" aria-label="Settings"> <span class="glyphicon glyphicon-cog" aria-hidden="true"></span> </button> </div> </div>`; /** * Plaintext Widgets display static text and are not updated by any Servers. */ export class PlainTextWidgetFactory { //Implements singleton constructor(widgetFactory) { if (!_plainTextWidgetFactory) { _plainTextWidgetFactory = this; _userEvents = new UserEvents(); } return _plainTextWidgetFactory; } /** * This will return a properly formated Object, that return a propper array at config.key.value * Arrays will be real array containing their data * @param configurable Data that should be formated * @return formated data */ _formatConfigurableData(configurable) { let formattedObject = {}; for (let key in configurable) { if (configurable[key].type == TYPE_ARRAY) { formattedObject[key] = { data: configurable[key].data.map(function(d) { for (let k in d.data) { return d.data[k].data; } }) }; } else { formattedObject[key] = configurable[key]; } } return formattedObject; } /** * Creates a new PlainText widget * @param id The id of the new widget * @param callback The function which will be called once the widget is all set up. Follow arguments will be passed: * 1. The id the widget has within the DOM * 2. The function to call when new data has arrived, with the new data as an argument * @return The html of the Widget which should be inserted into the DOM **/ create(id, callback) { let html = $('<div/>').prepend(htmlTemplate); //create the id to be set in html let htmlId = "iotdbWidget" + id; let htmlIdSelector = `#${htmlId}`; //When html of widget is loaded, set up template in canvas $("#templateWidgetCanvas").ready(() => { //Replace dummy ids with real ones html.find("#templateWidget").attr("id", htmlId); let textContainer = document.createElement("DIV"); textContainer.className = "widget-text-container"; let textElement = document.createElement("SPAN"); textElement.className = "widget-text-element"; textElement.id = htmlId + "-textElement"; textContainer.appendChild(textElement); textElement.innerText = window.iotlg.textWidgetDefaultText; textContainer.style.fontSize = "27px"; let widget = html.find("#" + htmlId)[0]; widget.insertBefore(textContainer, html.find(".widget-footer")[0]); // Set correct language for title html.find(htmlIdSelector).find(".widget-title").text(window.iotlg.widgetPlainTextTitle); // Set remove callback html.find(htmlIdSelector).find("#removeWidgetButton").click(function(e) { e.preventDefault(); _userEvents.removeWidget(htmlId); }); // Set config callback html.find(htmlIdSelector).find("#configureWidgetButton").click(function(e) { e.preventDefault(); _userEvents.configureWidget(htmlId); }); let configUpdate = (config) => { // format config properly config = this._formatConfigurableData(config); $(htmlIdSelector).find(".widget-text-element").text(config.text.data); $(htmlIdSelector).find(".widget-title").text(config.title.data); $(htmlIdSelector).find(".widget-text-element").css("font-size", config.fontSize.data.toString() + "px"); }; callback(htmlId, null, configUpdate); }); return html; } }
JimSeker/AudioVideio
videoCapture2_1/app/src/main/java/edu/cs4730/videocapture2_1/CameraFragment.java
<reponame>JimSeker/AudioVideio<filename>videoCapture2_1/app/src/main/java/edu/cs4730/videocapture2_1/CameraFragment.java package edu.cs4730.videocapture2_1; import android.Manifest; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.util.Size; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; /** * Note, this uses camera2, not androidx.CameraX or the older camera v1. */ public class CameraFragment extends Fragment implements SurfaceHolder.Callback { String TAG = "CameraFragment"; SurfaceView preview; public SurfaceHolder mHolder; Button btn_takevideo; Context context; //used for the camera String cameraId; public CameraDevice mCameraDevice; boolean mIsRecordingVideo = false; private Size mVideoSize; CaptureRequest.Builder captureBuilder; private MediaRecorder mMediaRecorder; CameraCharacteristics characteristics; List<Surface> outputSurfaces; Handler backgroundHandler; //File file; Uri mFileUri; CameraCaptureSession mSession; private videoViewModel myViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { myViewModel = new ViewModelProvider(requireActivity()).get(videoViewModel.class); View myView = inflater.inflate(R.layout.fragment_camera, container, false); context = getContext(); preview = myView.findViewById(R.id.camera2_preview); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = preview.getHolder(); mHolder.addCallback(this); btn_takevideo = myView.findViewById(R.id.btn_takevideo); btn_takevideo.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (!mIsRecordingVideo) { //about to take a video mIsRecordingVideo = true; btn_takevideo.setText("Stop Recording"); startRecordingVideo(); } else { stopRecordingVideo(); mIsRecordingVideo = false; btn_takevideo.setText("Start Recording"); } } } ); return myView; } //start recording public void startRecordingVideo() { mMediaRecorder.start(); } @Override public void onPause() { if (mIsRecordingVideo) { stopRecordingVideo(); mIsRecordingVideo = false; } super.onPause(); } public void stopRecordingVideo() { // Stop recording mMediaRecorder.stop(); mMediaRecorder.reset(); try { mSession.stopRepeating(); } catch (CameraAccessException e) { e.printStackTrace(); } String[] filePathColumn = {MediaStore.Video.Media.DATA}; Cursor cursor = requireActivity().getContentResolver().query(mFileUri, filePathColumn, null, null, null); String file; if (cursor != null) { //sdcard cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); file = cursor.getString(columnIndex); cursor.close(); } else { //local file = mFileUri.toString(); } Toast.makeText(context, "Video saved: " + file, Toast.LENGTH_SHORT).show(); myViewModel.add(file); Log.v(TAG, "Video saved: " + file); //reset the preview screen. setup2Record(); } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surfaceview Created"); openCamera(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "Surfaceview Changed"); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surfaceview Destroyed"); if (mCameraDevice != null) { mCameraDevice.close(); } } //now setup the preview code //setup the camera objects private void openCamera() { CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); Log.d(TAG, "openCamera Start"); if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { try { cameraId = manager.getCameraIdList()[0]; // setup the camera perview. should wrap this in a checkpermissions, which studio is bitching about // except it has been done before this fragment is called. manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { e.printStackTrace(); } } else { Log.e(TAG, "Don't have permission to camera!"); } Log.d(TAG, "openCamera End"); } /* This is the callback necessary for the manager.openCamera Call back needed above. */ private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice camera) { Log.d(TAG, "onOpened"); mCameraDevice = camera; setup2Record(); } @Override public void onDisconnected(CameraDevice camera) { Log.d(TAG, "onDisconnected"); } @Override public void onError(CameraDevice camera, int error) { Log.d(TAG, "onError from mStateCallback from opencamera listener."); } }; /////////////////////// /// Now the methods to take a video //////////////////// //everything to setup to record a video public void setup2Record() { if (mCameraDevice == null) { //camera must be setup first! Log.e(TAG, "mCameraDevice is null!!"); return; } mMediaRecorder = new MediaRecorder(); CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); //setup for video recording. try { characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); try { setUpMediaRecorder(); } catch (IOException e) { Log.e(TAG, "Failed to get a MediaRecorder setup. done now"); e.printStackTrace(); return; } try { captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); } catch (CameraAccessException e) { Log.e(TAG, "Failed to get a TEMPLATE_RECORD. done now"); e.printStackTrace(); return; } outputSurfaces = new ArrayList<Surface>(2); outputSurfaces.add(mMediaRecorder.getSurface()); outputSurfaces.add(mHolder.getSurface()); HandlerThread thread = new HandlerThread("CameraVideo"); thread.start(); backgroundHandler = new Handler(thread.getLooper()); captureBuilder.addTarget(mMediaRecorder.getSurface()); captureBuilder.addTarget(mHolder.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); mCameraDevice.createCaptureSession(outputSurfaces, mCaptureStateCallback, backgroundHandler); } catch (CameraAccessException e) { Log.e(TAG, "Well something failed in setup record"); e.printStackTrace(); } } /** * In this sample, we choose a video size with 3x4 aspect ratio. Also, we don't use sizes * larger than 1080p, since MediaRecorder cannot handle such a high-resolution video. * * @param choices The list of available sizes * @return The video size */ private static Size chooseVideoSize(Size[] choices) { for (Size size : choices) { if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) { return size; } } //Log.d(TAG, "Couldn't find any suitable video size"); return choices[choices.length - 1]; } private void setUpMediaRecorder() throws IOException { mFileUri = getOutputMediaFile(MainActivity.MEDIA_TYPE_VIDEO, false); //setup a new filename for every record. mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); ParcelFileDescriptor pfd = requireActivity().getContentResolver().openFileDescriptor(mFileUri, "w"); mMediaRecorder.setOutputFile(pfd.getFileDescriptor()); mMediaRecorder.setVideoEncodingBitRate(10000000); mMediaRecorder.setVideoFrameRate(30); mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight()); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); int deviceorientation = context.getResources().getConfiguration().orientation; mMediaRecorder.setOrientationHint(getJpegOrientation(characteristics, deviceorientation)); mMediaRecorder.prepare(); } CameraCaptureSession.StateCallback mCaptureStateCallback = new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { try { mSession = session; //null for capture listener, because mrecoder does the work here! session.setRepeatingRequest(captureBuilder.build(), null, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) { } }; //helper method so set the picture orientation correctly. This doesn't set the header in jpeg // instead it just makes sure the picture is the same way as the phone is when it was taken. private int getJpegOrientation(CameraCharacteristics c, int deviceOrientation) { if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN) return 0; int sensorOrientation = c.get(CameraCharacteristics.SENSOR_ORIENTATION); // Round device orientation to a multiple of 90 deviceOrientation = (deviceOrientation + 45) / 90 * 90; // Reverse device orientation for front-facing cameras boolean facingFront = c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT; if (facingFront) deviceOrientation = -deviceOrientation; // Calculate desired JPEG orientation relative to camera orientation to make // the image upright relative to the device orientation return (sensorOrientation + deviceOrientation + 360) % 360; } /** * Create a File for saving an image or video */ public Uri getOutputMediaFile(int type, boolean local) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()); ContentValues values = new ContentValues(); File mediaFile; File storageDir; Uri returnUri = null; if (type == MainActivity.MEDIA_TYPE_IMAGE) { if (local) { storageDir = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); if (!storageDir.exists()) { storageDir.mkdirs(); } mediaFile = new File(storageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); returnUri = Uri.fromFile(mediaFile); } else { //onto the sdcard //values.put(MediaStore.Images.Media.TITLE, "IMG_" + timeStamp + ".jpg"); //not needed? values.put(MediaStore.Images.Media.DISPLAY_NAME, "IMG_" + timeStamp + ".jpg"); //file name. values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg"); returnUri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } } else if (type == MainActivity.MEDIA_TYPE_VIDEO) { if (local) { storageDir = requireActivity().getExternalFilesDir(Environment.DIRECTORY_MOVIES); if (!storageDir.exists()) { storageDir.mkdirs(); } mediaFile = new File(storageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); returnUri = Uri.fromFile(mediaFile); } else { //values.put(MediaStore.Images.Media.TITLE, "VID_" + timeStamp + ".mp4"); //not needed? values.put(MediaStore.Video.Media.DISPLAY_NAME, "VID_" + timeStamp + ".mp4"); //file name. values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4"); returnUri = requireActivity().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values); } } else if (type == MainActivity.MEDIA_TYPE_AUDIO) { if (local) { storageDir = requireActivity().getExternalFilesDir(Environment.DIRECTORY_MUSIC); if (!storageDir.exists()) { storageDir.mkdirs(); } mediaFile = new File(storageDir.getPath() + File.separator + "AUD_" + timeStamp + ".mp4"); returnUri = Uri.fromFile(mediaFile); } else { values.put(MediaStore.Audio.Media.DISPLAY_NAME, "AUD_" + timeStamp + ".mp3"); //file name. values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3"); returnUri = requireActivity().getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values); } } return returnUri; } }
barthez/pact_broker
lib/pact_broker/db/clean.rb
require "sequel" require "pact_broker/project_root" require "pact_broker/logging" require "pact_broker/db/clean/selector" module PactBroker module DB class Clean include PactBroker::Logging class Unionable < Array def union(other) Unionable.new(self + other) end end def self.call database_connection, options = {} new(database_connection, options).call end def initialize database_connection, options = {} @db = database_connection @options = options end def keep @keep ||= if options[:keep] # Could be a Matrix::UnresolvedSelector from the docker image, convert it options[:keep].collect { | unknown_thing | Selector.from_hash(unknown_thing.to_hash) } else [Selector.new(tag: true, latest: true), Selector.new(branch: true, latest: true), Selector.new(latest: true), Selector.new(deployed: true), Selector.new(released: true)] end end def resolve_ids(query, column_name = :id) # query Unionable.new(query.collect { |h| h[column_name] }) end def pact_publication_ids_to_keep @pact_publication_ids_to_keep ||= pact_publication_ids_to_keep_for_version_ids_to_keep .union(latest_pact_publication_ids_to_keep) .union(latest_tagged_pact_publications_ids_to_keep) end def pact_publication_ids_to_keep_for_version_ids_to_keep @pact_publication_ids_to_keep_for_version_ids_to_keep ||= resolve_ids(db[:pact_publications].select(:id).where(consumer_version_id: version_ids_to_keep)) end def latest_tagged_pact_publications_ids_to_keep @latest_tagged_pact_publications_ids_to_keep ||= resolve_ids(keep.select(&:tag).select(&:latest).collect do | selector | PactBroker::Pacts::PactPublication.select(:id).latest_by_consumer_tag_for_clean_selector(selector) end.reduce(&:union) || []) end def latest_pact_publication_ids_to_keep @latest_pact_publication_ids_to_keep ||= resolve_ids(db[:latest_pact_publications].select(:id)) end def pact_publication_ids_to_delete @pact_publication_ids_to_delete ||= resolve_ids(db[:pact_publications].select(:id).where(id: pact_publication_ids_to_keep).invert) end # because they belong to the versions to keep def verification_ids_to_keep_for_version_ids_to_keep @verification_ids_to_keep_for_version_ids_to_keep ||= resolve_ids(db[:verifications].select(:id).where(provider_version_id: version_ids_to_keep)) end def verification_ids_to_keep_because_latest_verification_for_latest_pact @verification_ids_to_keep_because_latest_verification ||= resolve_ids( db[:latest_verification_ids_for_pact_versions] .select(:latest_verification_id) .where(pact_version_id: db[:latest_pact_publications].select(:pact_version_id) ), :latest_verification_id ) end def verification_ids_to_keep_for_pact_publication_ids_to_keep @verification_ids_to_keep_for_pact_publication_ids_to_keep ||= resolve_ids( db[:latest_verification_id_for_pact_version_and_provider_version] .select(:verification_id) .where(pact_version_id: db[:pact_publications] .select(:pact_version_id) .where(id: pact_publication_ids_to_keep_for_version_ids_to_keep) ) ) end def verification_ids_to_keep @verification_ids_to_keep ||= verification_ids_to_keep_for_version_ids_to_keep.union(verification_ids_to_keep_because_latest_verification_for_latest_pact) end def verification_ids_to_delete @verification_ids_to_delete ||= db[:verifications].select(:id).where(id: verification_ids_to_keep).invert end def version_ids_to_keep @version_ids_to_keep ||= keep.collect do | selector | PactBroker::Domain::Version.select(:id).for_selector(selector) end.reduce(&:union) end def call deleted_counts = {} kept_counts = {} deleted_counts[:pact_publications] = pact_publication_ids_to_delete.count kept_counts[:pact_publications] = pact_publication_ids_to_keep.count # Work out how to keep the head verifications for the provider tags. deleted_counts[:verification_results] = verification_ids_to_delete.count kept_counts[:verification_results] = verification_ids_to_keep.count delete_webhook_data(verification_triggered_webhook_ids_to_delete) delete_verifications delete_webhook_data(pact_publication_triggered_webhook_ids_to_delete) delete_pact_publications delete_orphan_pact_versions overwritten_delete_counts = delete_overwritten_verifications deleted_counts[:verification_results] = deleted_counts[:verification_results] + overwritten_delete_counts[:verification_results] kept_counts[:verification_results] = kept_counts[:verification_results] - overwritten_delete_counts[:verification_results] delete_orphan_tags delete_orphan_versions { kept: kept_counts, deleted: deleted_counts } end private attr_reader :db, :options def verification_triggered_webhook_ids_to_delete db[:triggered_webhooks].select(:id).where(verification_id: verification_ids_to_delete) end def pact_publication_triggered_webhook_ids_to_delete db[:triggered_webhooks].select(:id).where(pact_publication_id: pact_publication_ids_to_delete) end def referenced_version_ids db[:pact_publications].select(:consumer_version_id).union(db[:verifications].select(:provider_version_id)) end def verification_ids_for_pact_publication_ids_to_delete @verification_ids_for_pact_publication_ids_to_delete ||= db[:verifications].select(:id).where(pact_version_id: db[:pact_publications].select(:pact_version_id).where(id: pact_publication_ids_to_delete)) end def delete_webhook_data(triggered_webhook_ids) db[:webhook_executions].where(triggered_webhook_id: triggered_webhook_ids).delete db[:triggered_webhooks].where(id: triggered_webhook_ids).delete end def delete_pact_publications db[:pact_publications].where(id: pact_publication_ids_to_delete).delete end def delete_verifications db[:verifications].where(id: verification_ids_to_delete).delete end def delete_orphan_pact_versions referenced_pact_version_ids = db[:pact_publications].select(:pact_version_id).union(db[:verifications].select(:pact_version_id)) db[:pact_versions].where(id: referenced_pact_version_ids).invert.delete end def delete_orphan_tags db[:tags].where(version_id: referenced_version_ids).invert.delete end def delete_orphan_versions db[:versions].where(id: referenced_version_ids).invert.delete end def delete_overwritten_verifications verification_ids = db[:verifications].select(:id).where(id: db[:latest_verification_id_for_pact_version_and_provider_version].select(:verification_id)).invert deleted_counts = { verification_results: verification_ids.count } delete_webhook_data(db[:triggered_webhooks].where(verification_id: verification_ids).select(:id)) verification_ids.delete deleted_counts end end end end
bornio/chorus
app/assets/javascripts/views/dashboard/dashboard_workspace_list_view.js
<filename>app/assets/javascripts/views/dashboard/dashboard_workspace_list_view.js chorus.views.DashboardWorkspaceList = chorus.views.Base.extend({ constructorName: "DashboardWorkspaceListView", templateName: "dashboard/workspace_list", tagName: "ul", additionalClass: "list", useLoadingSection: true, setup: function() { chorus.PageEvents.subscribe("insight:promoted", this.fetchWorkspaces, this); }, fetchWorkspaces: function() { this.collection.attributes.active = true; this.collection.fetch(); }, collectionModelContext: function(model) { var comments = model.comments().models; var numComments = model.get("numberOfComments"); var numInsights = model.get("numberOfInsights"); var insightCountString; if (numComments > 0) { if (numInsights > 0) { insightCountString = t("dashboard.workspaces.recent_comments_and_insights", { recent_comments: t("dashboard.workspaces.recent_comments", {count: numComments}), recent_insights: t("dashboard.workspaces.recent_insights", {count: numInsights}) }) } else { insightCountString = t("dashboard.workspaces.recent_comments", {count: numComments}) } } else if (numInsights > 0) { insightCountString = t("dashboard.workspaces.recent_insights", {count: numInsights}) } else { insightCountString = t("dashboard.workspaces.no_recent_comments_or_insights") } return { imageUrl: model.defaultIconUrl(), showUrl: model.showUrl(), insightCountString: insightCountString, insightCount: numInsights, latestComment: comments[0] && { timestamp: comments[0].get("timestamp"), author: comments[0].author().displayName() } } }, cleanupCommentLists: function() { _.each(this.commentLists, function(commentList) { commentList.teardown(); }); }, removeOldLis: function() { _.each(this.lis, function(li) { $(li).remove(); }); }, postRender: function() { this.cleanupCommentLists(); this.commentLists = []; this.removeOldLis(); this.lis = []; this.collection.each(function(workspace) { var comments = workspace.comments(); comments.comparator = function(comment) { return -(new Date(comment.get('timestamp')).valueOf()); }; comments.sort(); comments.loaded = true; var commentList = new chorus.views.ActivityList({ collection: comments, initialLimit: 5, displayStyle: 'without_workspace', isReadOnly: true }); this.registerSubView(commentList); this.commentLists.push(commentList); var el = $(commentList.render().el); el.find("ul").addClass("tooltip activity"); // reassign the offset function so that when qtip calls it, qtip correctly positions the tooltips // with regard to the fixed-height header. var viewport = $(window); var top = $("#header").height(); viewport.offset = function() { return { left: 0, top: top }; }; var li = this.$("li[data-id=" + workspace.get("id") + "]"); this.lis.push(li); li.find(".comment .count").qtip({ content: el, show: { event: 'mouseover', solo: true }, hide: { delay: 500, fixed: true, event: 'mouseout' }, position: { viewport: viewport, my: "right center", at: "left center" }, style: { classes: "tooltip-white recent_comments_list", tip: { width: 15, height: 20 } }, events: { show: function(e) { commentList.render(); commentList.show(); } } }); }, this); } });
reduf/Headquarter
code/client/party.c
<filename>code/client/party.c<gh_stars>1-10 #ifdef CORE_PARTY_C #error "party.c included more than once" #endif #define CORE_PARTY_C Player *get_player_safe(GwClient *client, uint32_t player_id) { if (!(client && client->ingame && client->world.hash)) return NULL; ArrayPlayer *players = &client->world.players; if (!array_inside(players, player_id)) return NULL; return array_at(players, player_id); } Party *get_party_safe(GwClient *client, uint32_t party_id) { if (!(client && client->ingame && client->world.hash)) return NULL; ArrayParty *parties = &client->world.parties; if (!array_inside(parties, party_id)) return NULL; return &array_at(parties, party_id); } PartyPlayer *get_party_player(Party *party, uint32_t player_id) { assert(party); PartyPlayer *it; array_foreach(it, &party->players) { if (it->player_id == player_id) return it; } return NULL; } PartyHero *get_party_hero_agent(Party *party, AgentId agent_id) { assert(party); PartyHero *it; array_foreach(it, &party->heroes) { if (it->agent_id == agent_id) return it; } return NULL; } void HandlePartySetDifficulty(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint8_t mode; } SetMode; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SET_DIFFICULTY); assert(psize == sizeof(SetMode)); GwClient *client = cast(GwClient *)conn->data; SetMode *pack = cast(SetMode *)packet; assert(client && client->game_srv.secured); if (!(client->player && client->player->party)) { LogError("The player is not int a party yet."); return; } Party *party = client->player->party; switch ((Difficulty)pack->mode) { case Difficulty_Normal: case Difficulty_Hard: break; default: LogError("Invalid 'Difficulty' value %hhu", pack->mode); return; } party->difficulty = (Difficulty)pack->mode; } void HandlePartyHeroAdd(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; uint16_t player_id; // owner uint16_t agent_id; uint8_t hero_id; uint8_t level; } HeroAdd; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_HERO_ADD); assert(psize == sizeof(HeroAdd)); GwClient *client = cast(GwClient *)conn->data; HeroAdd *pack = cast(HeroAdd *)packet; assert(client && client->game_srv.secured); assert(array_inside(&client->world.parties, pack->party_id)); Party *party = &array_at(&client->world.parties, pack->party_id); PartyHero *p_hero = array_push(&party->heroes, 1); if (!p_hero) { LogError("HandlePartyHeroAdd: Couldn't array_push"); return; } p_hero->agent_id = pack->agent_id; p_hero->owner_id = pack->player_id; p_hero->hero_id = pack->hero_id; p_hero->level = pack->level; } void HandlePartyHeroRemove(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; uint16_t player_id; uint16_t agent_id; } HeroRemove; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_HERO_REMOVE); assert(psize == sizeof(HeroRemove)); GwClient *client = cast(GwClient *)conn->data; HeroRemove *pack = cast(HeroRemove *)packet; assert(client && client->game_srv.secured); Party *party = get_party_safe(client, pack->party_id); if (!party) { LogError("Party %d doesn't exist.", pack->party_id); return; } PartyHero *p_hero = get_party_hero_agent(party, pack->agent_id); if (!p_hero) { LogError("Couldn't find hero '%d' from party '%d' (owner_id: %d)", pack->agent_id, pack->player_id, pack->agent_id); return; } // @Cleanup: Check if it's standard. (e.g. diff between 2 ptr of same type) size_t index = p_hero - party->heroes.data; array_remove_ordered(&party->heroes, index); } void HandlePartyInviteAdd(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } InviteAdd; #pragma pack(pop) // This packet is received when we send an invite and it is confirmed by the server. assert(packet->header == GAME_SMSG_PARTY_INVITE_ADD); assert(psize == sizeof(InviteAdd)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartyJoinRequest(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } JoinRequest; #pragma pack(pop) // This packet is received when we receive an invite. assert(packet->header == GAME_SMSG_PARTY_JOIN_REQUEST); assert(psize == sizeof(JoinRequest)); GwClient *client = cast(GwClient *)conn->data; JoinRequest *pack = cast(JoinRequest *)packet; assert(client && client->game_srv.secured); Party *party = get_party_safe(client, pack->party_id); if (party == NULL) { LogError("Received a party invite from unknow party. (party_id: %d)", pack->party_id); return; } Event event; Event_Init(&event, EventType_PartyInviteRequest); event.PartyInviteRequest.party_id = pack->party_id; broadcast_event(&client->event_mgr, &event); } void HandlePartyInviteCancel(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } InviteCancel; #pragma pack(pop) // This packet is received when we cancel an invite and it is confirmed by the server. assert(packet->header == GAME_SMSG_PARTY_HERO_REMOVE); assert(psize == sizeof(InviteCancel)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartyRequestCancel(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } RequestCancel; #pragma pack(pop) // This packet is received when we cancel an invite. assert(packet->header == GAME_SMSG_PARTY_REQUEST_CANCEL); assert(psize == sizeof(RequestCancel)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartyYouAreLeader(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint8_t is_loaded; } YouAreLeader; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_YOU_ARE_LEADER); assert(psize == sizeof(YouAreLeader)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); Event event; Event_Init(&event, EventType_PartyLeaderChanged); broadcast_event(&client->event_mgr, &event); } void HandlePartyPlayerAdd(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; uint16_t player_id; uint8_t is_loaded; } PlayerAdd; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_PLAYER_ADD); assert(psize == sizeof(PlayerAdd)); GwClient *client = cast(GwClient *)conn->data; PlayerAdd *pack = cast(PlayerAdd *)packet; assert(client && client->game_srv.secured); Party *party = get_party_safe(client, pack->party_id); Player *player = get_player_safe(client, pack->player_id); assert(player && party); player->party = party; PartyPlayer *party_player = array_push(&party->players, 1); if (!party_player) { LogError("HandlePartyPlayerAdd: Couldn't array_push"); return; } party_player->agent_id = player->agent_id; party_player->player_id = pack->player_id; party_player->connected = pack->is_loaded == 1; party->player_count++; Event event; Event_Init(&event, EventType_PartyMembersChanged); event.PartyMembersChanged.party_id = pack->party_id; broadcast_event(&client->event_mgr, &event); } void HandlePartyPlayerRemove(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; uint16_t player_id; } PlayerRemove; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_PLAYER_REMOVE); assert(psize == sizeof(PlayerRemove)); GwClient *client = cast(GwClient *)conn->data; PlayerRemove *pack = cast(PlayerRemove *)packet; assert(client && client->game_srv.secured); Party *party = get_party_safe(client, pack->party_id); Player *player = get_player_safe(client, pack->player_id); assert(player && party); size_t index = 0; PartyPlayer *it; array_foreach(it, &party->players) { if (it->player_id == player->player_id) break; index++; } array_remove_ordered(&party->players, index); player->party = NULL; party->player_count--; Event event; Event_Init(&event, EventType_PartyMembersChanged); event.PartyMembersChanged.party_id = pack->party_id; broadcast_event(&client->event_mgr, &event); } void HandlePartyPlayerReady(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; uint16_t player_id; uint8_t is_ready; } PlayerReady; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_PLAYER_READY); assert(psize == sizeof(PlayerReady)); GwClient *client = cast(GwClient *)conn->data; PlayerReady *pack = cast(PlayerReady *)packet; assert(client && client->game_srv.secured); Player *player = get_player_safe(client, pack->player_id); assert(player && player->party); PartyPlayer *p_player = get_party_player(player->party, pack->player_id); assert(p_player); p_player->ready = true; } void HandlePartyCreate(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } PartyInfo; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_CREATE); assert(psize == sizeof(PartyInfo)); GwClient *client = cast(GwClient *)conn->data; PartyInfo *pack = cast(PartyInfo *)packet; assert(client && client->game_srv.secured); ArrayParty *parties = &client->world.parties; if (!array_inside(parties, pack->party_id)) { array_resize(parties, pack->party_id + 1); parties->size = parties->capacity; } Party *party = &array_at(parties, pack->party_id); memzero(party, sizeof(*party)); party->party_id = pack->party_id; array_init(&party->heroes); array_init(&party->players); array_init(&party->henchmans); } void HandlePartyMemberStreamEnd(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } MemberStreamEnd; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_MEMBER_STREAM_END); assert(psize == sizeof(MemberStreamEnd)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartyDefeated(Connection *conn, size_t psize, Packet *packet) { assert(packet->header == GAME_SMSG_PARTY_DEFEATED); assert(psize == sizeof(Packet)); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); if (!(client->player && client->player->party)) { LogError("Player party got defeated before it was created."); return; } client->player->party->defeated = true; } void GameSrv_FlagHero(GwClient *client, Vec2f pos, AgentId hero_agent_id) { #pragma pack(push, 1) typedef struct { Header header; AgentId agent_id; Vec2f pos; int32_t plane; // need confirmation } FlagHero; #pragma pack(pop) assert(client && client->game_srv.secured); FlagHero packet = NewPacket(GAME_CMSG_HERO_FLAG_SINGLE); packet.agent_id = hero_agent_id; packet.pos = pos; packet.plane = 0; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_FlagAllHero(GwClient *client, Vec2f pos) { #pragma pack(push, 1) typedef struct { Header header; Vec2f pos; int32_t plane; // need confirmation } FlagHero; #pragma pack(pop) assert(client && client->game_srv.secured); FlagHero packet = NewPacket(GAME_CMSG_HERO_FLAG_ALL); packet.pos = pos; packet.plane = 0; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_AcceptInvite(GwClient *client, int party_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } AcceptInvite; #pragma pack(pop) assert(client && client->game_srv.secured); AcceptInvite packet = NewPacket(GAME_CMSG_PARTY_ACCEPT_INVITE); packet.party_id = (int16_t)party_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_LeaveParty(GwClient *client) { assert(client && client->game_srv.secured); Packet packet = NewPacket(GAME_CMSG_PARTY_LEAVE_GROUP); SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_RefuseInvite(GwClient *client, int party_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t party_id; } RefuseInvite; #pragma pack(pop) assert(client && client->game_srv.secured); RefuseInvite packet = NewPacket(GAME_CMSG_PARTY_ACCEPT_REFUSE); packet.party_id = (int16_t)party_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_PartySetTick(GwClient *client, bool ticked) { #pragma pack(push, 1) typedef struct { Header header; uint8_t ticked; } SetTick; #pragma pack(pop) assert(client && client->game_srv.secured); SetTick packet = NewPacket(GAME_CMSG_PARTY_READY_STATUS); packet.ticked = ticked; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_SetDifficulty(GwClient *client, Difficulty mode) { #pragma pack(push, 1) typedef struct { Header header; uint8_t mode; } SetDifficulty; #pragma pack(pop) assert(client && client->game_srv.secured); SetDifficulty packet = NewPacket(GAME_CMSG_PARTY_SET_DIFFICULTY); packet.mode = mode; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_AddHero(GwClient *client, HeroID hero_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t hero_id; } HeroPacket; #pragma pack(pop) assert(client && client->game_srv.secured); HeroPacket packet = NewPacket(GAME_CMSG_HERO_ADD); packet.hero_id = hero_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_KickHero(GwClient *client, HeroID hero_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t hero_id; } HeroPacket; #pragma pack(pop) assert(client && client->game_srv.secured); HeroPacket packet = NewPacket(GAME_CMSG_HERO_KICK); packet.hero_id = hero_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } /* * Party Search */ void HandlePartySearchRequestJoin(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_from; uint16_t ps_host; } RequestJoin; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_REQUEST_JOIN); assert(sizeof(RequestJoin) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartySearchRequestDone(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_from; uint16_t ps_host; } RequestDone; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_REQUEST_DONE); assert(sizeof(RequestDone) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartySearchAdvertisement(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; uint16_t district; uint8_t unk1; uint8_t party_size; uint8_t hero_count; uint8_t search_type; uint8_t unk2; uint16_t message[32]; uint16_t player_name[20]; uint8_t unk3; uint8_t unk4; uint8_t unk5; uint32_t unk6; } PacketType; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_ADVERTISEMENT); assert(sizeof(PacketType) == psize); GwClient *client = cast(GwClient *)conn->data; PacketType *pack = cast(PacketType *)packet; assert(client && client->game_srv.secured); Event params; Event_Init(&params, EventType_PartySearchAdvertisement); params.PartySearchAdvertisement.party_id = pack->ps_id; params.PartySearchAdvertisement.district = pack->district; params.PartySearchAdvertisement.party_size = pack->party_size; params.PartySearchAdvertisement.hero_count = pack->hero_count; params.PartySearchAdvertisement.search_type = pack->search_type; params.PartySearchAdvertisement.sender.buffer = pack->player_name; params.PartySearchAdvertisement.sender.length = u16len(pack->player_name, ARRAY_SIZE(pack->player_name)); params.PartySearchAdvertisement.message.buffer = pack->message; params.PartySearchAdvertisement.message.length = u16len(pack->message, ARRAY_SIZE(pack->message)); broadcast_event(&client->event_mgr, &params); } void HandlePartySearchSeek(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; } SeekParty; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_SEEK); assert(sizeof(SeekParty) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartySearchRemove(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; } PacketType; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_REMOVE); assert(sizeof(PacketType) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartySearchSize(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; uint8_t party_size; uint8_t hero_count; } PacketType; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_SIZE); assert(sizeof(PacketType) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void HandlePartySearchType(Connection *conn, size_t psize, Packet *packet) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; uint8_t type; // 0=hunting, 1=mission, 2=quest, 3=trade, 4=guild uint8_t difficulty; // 0=normal, 1=hard } PacketType; #pragma pack(pop) assert(packet->header == GAME_SMSG_PARTY_SEARCH_TYPE); assert(sizeof(PacketType) == psize); GwClient *client = cast(GwClient *)conn->data; assert(client && client->game_srv.secured); } void GameSrv_PS_SeekParty(GwClient *client, PartySearchType type, struct kstr *msg) { #pragma pack(push, 1) typedef struct { Header header; uint8_t type; uint16_t msg[32]; uint16_t unk2; } PacketSeekParty; #pragma pack(pop) assert(client && client->game_srv.secured); PacketSeekParty packet = NewPacket(GAME_CMSG_PARTY_SEARCH_SEEK); packet.type = type; kstr_write(msg, packet.msg, ARRAY_SIZE(packet.msg)); SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_PS_CancelSeek(GwClient *client) { assert(client && client->game_srv.secured); Packet packet = NewPacket(GAME_CMSG_PARTY_SEARCH_CANCEL); SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_PS_RequestJoin(GwClient *client, uint16_t party_search_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; } PacketType; #pragma pack(pop) assert(client && client->game_srv.secured); PacketType packet = NewPacket(GAME_CMSG_PARTY_SEARCH_REQUEST_JOIN); packet.ps_id = party_search_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_PS_RequestReply(GwClient *client, uint16_t party_search_id) { #pragma pack(push, 1) typedef struct { Header header; uint16_t ps_id; } PacketType; #pragma pack(pop) assert(client && client->game_srv.secured); PacketType packet = NewPacket(GAME_CMSG_PARTY_SEARCH_REQUEST_REPLY); packet.ps_id = party_search_id; SendPacket(&client->game_srv, sizeof(packet), &packet); } void GameSrv_PS_ChangeType(GwClient *client, PartySearchType type) { #pragma pack(push, 1) typedef struct { Header header; uint8_t type; } PacketType; #pragma pack(pop) assert(client && client->game_srv.secured); PacketType packet = NewPacket(GAME_CMSG_PARTY_SEARCH_TYPE); packet.type = type; SendPacket(&client->game_srv, sizeof(packet), &packet); }
stas-vilchik/bdd-ml
data/2355.js
<filename>data/2355.js { var _this2 = this; (function() { babelHelpers.newArrowCheck(this, _this2); }.bind(this)); }
Thraix/Greet-Engine
Greet-core/src/graphics/Skybox.cpp
#include "Skybox.h" #include <graphics/models/MeshFactory.h> #include <graphics/shaders/ShaderFactory.h> #include <graphics/RenderCommand.h> namespace Greet { Skybox::Skybox(const Ref<CubeMap>& cubemap) : Skybox{cubemap, ShaderFactory::ShaderSkybox()} { } Skybox::Skybox(const Ref<CubeMap>& map, const Ref<Shader>& shader) : m_map(map), m_shader(shader) { MeshData data{MeshFactory::Cube()}; m_mesh = NewRef<Mesh>(data); m_mesh->SetClockwiseRender(true); } Skybox::~Skybox() {} void Skybox::Render(const Ref<Camera3D>& camera) const { RenderCommand::EnableDepthTest(false); m_shader->Enable(); camera->SetShaderUniforms(m_shader); m_map->Enable(0); m_mesh->Bind(); m_mesh->Render(); m_mesh->Unbind(); m_map->Disable(); m_shader->Disable(); RenderCommand::ResetDepthTest(); } }
shoaib-a-khan/iConA
ICONA_WRAPPERPACKAGE_AND_DB/com/icona/wrapper/View.java
package com.icona.wrapper; //Mapping of UIView API public class View extends Responder { }
li-boxuan/stargate
sgv2-service-common/src/main/java/io/stargate/sgv2/common/cql/builder/Replication.java
<gh_stars>0 /* * Copyright DataStax, Inc. and/or The Stargate Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.stargate.sgv2.common.cql.builder; import static java.lang.String.format; import java.util.Map; /** * Represents a keyspace replication string. * * <p>So something like "{ 'class': 'SimpleStrategy', 'replication_factor': 1}". */ public class Replication { private final String replication; private Replication(String replication) { this.replication = replication; } public static Replication simpleStrategy(int replicationFactor) { return new Replication( format("{ 'class': 'SimpleStrategy', 'replication_factor': %d }", replicationFactor)); } public static Replication networkTopologyStrategy( Map<String, Integer> dataCenterReplicationFactors) { StringBuilder sb = new StringBuilder(); sb.append("{ 'class': 'NetworkTopologyStrategy'"); for (Map.Entry<String, Integer> entry : dataCenterReplicationFactors.entrySet()) { String dcName = entry.getKey(); int dcReplication = entry.getValue(); sb.append(", '").append(dcName).append("': ").append(dcReplication); } sb.append(" }"); return new Replication(sb.toString()); } @Override public String toString() { return replication; } }
path64/assembler
lib/yasmx/IncbinBytecode.cpp
<gh_stars>1-10 /// /// Incbin bytecode implementation /// /// Copyright (C) 2001-2007 <NAME> /// /// 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 AUTHOR AND OTHER 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 AUTHOR OR OTHER 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 "yasmx/BytecodeContainer.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/system_error.h" #include "yasmx/Basic/Diagnostic.h" #include "yasmx/Support/scoped_ptr.h" #include "yasmx/BytecodeOutput.h" #include "yasmx/Bytecode.h" #include "yasmx/Bytes.h" #include "yasmx/Expr.h" #include "yasmx/IntNum.h" #include "yasmx/Value.h" using namespace yasm; namespace { class IncbinBytecode : public Bytecode::Contents { public: IncbinBytecode(StringRef filename, std::auto_ptr<Expr> start, std::auto_ptr<Expr> maxlen); ~IncbinBytecode(); /// Finalizes the bytecode after parsing. bool Finalize(Bytecode& bc, DiagnosticsEngine& diags); /// Calculates the minimum size of a bytecode. bool CalcLen(Bytecode& bc, /*@out@*/ unsigned long* len, const Bytecode::AddSpanFunc& add_span, DiagnosticsEngine& diags); /// Convert a bytecode into its byte representation. bool Output(Bytecode& bc, BytecodeOutput& bc_out); StringRef getType() const; IncbinBytecode* clone() const; #ifdef WITH_XML /// Write an XML representation. For debugging purposes. pugi::xml_node Write(pugi::xml_node out) const; #endif // WITH_XML private: std::string m_filename; ///< file to include data from OwningPtr<MemoryBuffer> m_buf; ///< Buffer for file data /// starting offset to read from (NULL=0) /*@null@*/ util::scoped_ptr<Expr> m_start; /// maximum number of bytes to read (NULL=no limit) /*@null@*/ util::scoped_ptr<Expr> m_maxlen; }; } // anonymous namespace IncbinBytecode::IncbinBytecode(StringRef filename, std::auto_ptr<Expr> start, std::auto_ptr<Expr> maxlen) : m_filename(filename), m_start(start.release()), m_maxlen(maxlen.release()) { } IncbinBytecode::~IncbinBytecode() { } bool IncbinBytecode::Finalize(Bytecode& bc, DiagnosticsEngine& diags) { if (llvm::error_code err = MemoryBuffer::getFile(m_filename, m_buf)) { diags.Report(bc.getSource(), diag::err_file_read) << m_filename << err.message(); return false; } if (m_start) { Value val(0, Expr::Ptr(m_start->clone())); if (!val.Finalize(diags, diag::err_incbin_start_too_complex)) return false; if (val.isRelative()) { diags.Report(bc.getSource(), diag::err_incbin_start_not_absolute); return false; } m_start.reset(val.getAbs()->clone()); } if (m_maxlen) { Value val(0, Expr::Ptr(m_maxlen->clone())); if (!val.Finalize(diags, diag::err_incbin_maxlen_too_complex)) return false; if (val.isRelative()) { diags.Report(bc.getSource(), diag::err_incbin_maxlen_not_absolute); return false; } m_maxlen.reset(val.getAbs()->clone()); } return true; } bool IncbinBytecode::CalcLen(Bytecode& bc, /*@out@*/ unsigned long* len, const Bytecode::AddSpanFunc& add_span, DiagnosticsEngine& diags) { unsigned long start = 0, maxlen = 0xFFFFFFFFUL; // Try to convert start to integer value if (m_start) { if (m_start->isIntNum()) start = m_start->getIntNum().getUInt(); else { // FIXME diags.Report(bc.getSource(), diag::err_incbin_start_not_const); return false; } } // Try to convert maxlen to integer value if (m_maxlen) { if (m_maxlen->isIntNum()) maxlen = m_maxlen->getIntNum().getUInt(); else { // FIXME diags.Report(bc.getSource(), diag::err_incbin_maxlen_not_const); return false; } } // Compute length of incbin from start, maxlen, and len unsigned long flen = m_buf->getBufferSize(); if (start > flen) { diags.Report(bc.getSource(), diag::warn_incbin_start_after_eof); start = flen; } flen -= start; if (m_maxlen) { if (maxlen < flen) flen = maxlen; } *len = flen; return true; } bool IncbinBytecode::Output(Bytecode& bc, BytecodeOutput& bc_out) { unsigned long start = 0; // Convert start to integer value if (m_start) { assert(m_start->isIntNum() && "could not determine start in incbin::output"); start = m_start->getIntNum().getUInt(); } // Copy len bytes Bytes& bytes = bc_out.getScratch(); bytes.WriteString(m_buf->getBuffer().substr(start, bc.getTailLen())); bc_out.OutputBytes(bytes, bc.getSource()); return true; } StringRef IncbinBytecode::getType() const { return "yasm::IncbinBytecode"; } IncbinBytecode* IncbinBytecode::clone() const { return new IncbinBytecode(m_filename, std::auto_ptr<Expr>(m_start->clone()), std::auto_ptr<Expr>(m_maxlen->clone())); } #ifdef WITH_XML pugi::xml_node IncbinBytecode::Write(pugi::xml_node out) const { pugi::xml_node root = out.append_child("Incbin"); append_child(root, "Filename", m_filename); if (m_start) append_child(root, "Start", *m_start); if (m_maxlen) append_child(root, "MaxLen", *m_maxlen); return root; } #endif // WITH_XML void yasm::AppendIncbin(BytecodeContainer& container, StringRef filename, /*@null@*/ std::auto_ptr<Expr> start, /*@null@*/ std::auto_ptr<Expr> maxlen, SourceLocation source) { Bytecode& bc = container.FreshBytecode(); bc.Transform(Bytecode::Contents::Ptr( new IncbinBytecode(filename, start, maxlen))); bc.setSource(source); }
thomcz/aurora
app/src/main/java/hrv/band/app/ui/presenter/IMeasuringPresenter.java
<reponame>thomcz/aurora package hrv.band.app.ui.presenter; import java.util.Date; import java.util.List; import hrv.band.app.model.Measurement; /** * Copyright (c) 2017 * Created by <NAME> on 23.04.2017 */ public interface IMeasuringPresenter { int getDuration(); Measurement createMeasurement(List<Double> rrInterval, Date time); }
grinisrit/tnl-dev
Documentation/Tutorials/ReductionAndScan/UpdateAndResidueExample.cpp
#include <iostream> #include <cstdlib> #include <TNL/Containers/Vector.h> #include <TNL/Algorithms/reduce.h> using namespace TNL; using namespace TNL::Containers; using namespace TNL::Algorithms; template< typename Device > double updateAndResidue( Vector< double, Device >& u, const Vector< double, Device >& delta_u, const double& tau ) { auto u_view = u.getView(); auto delta_u_view = delta_u.getConstView(); auto fetch = [=] __cuda_callable__ ( int i ) mutable ->double { const double& add = delta_u_view[ i ]; u_view[ i ] += tau * add; return add * add; }; auto reduction = [] __cuda_callable__ ( const double& a, const double& b ) { return a + b; }; return sqrt( reduce< Device >( 0, u_view.getSize(), fetch, reduction, 0.0 ) ); } int main( int argc, char* argv[] ) { const double tau = 0.1; Vector< double, Devices::Host > host_u( 10 ), host_delta_u( 10 ); host_u = 0.0; host_delta_u = 1.0; std::cout << "host_u = " << host_u << std::endl; std::cout << "host_delta_u = " << host_delta_u << std::endl; double residue = updateAndResidue( host_u, host_delta_u, tau ); std::cout << "New host_u is: " << host_u << "." << std::endl; std::cout << "Residue is:" << residue << std::endl; #ifdef HAVE_CUDA Vector< double, Devices::Cuda > cuda_u( 10 ), cuda_delta_u( 10 ); cuda_u = 0.0; cuda_delta_u = 1.0; std::cout << "cuda_u = " << cuda_u << std::endl; std::cout << "cuda_delta_u = " << cuda_delta_u << std::endl; residue = updateAndResidue( cuda_u, cuda_delta_u, tau ); std::cout << "New cuda_u is: " << cuda_u << "." << std::endl; std::cout << "Residue is:" << residue << std::endl; #endif return EXIT_SUCCESS; }
futugyou/goproject
design-pattern/behavioral-pattern/07-state-pattern/statecontext.go
<filename>design-pattern/behavioral-pattern/07-state-pattern/statecontext.go package main type statecontext struct { state istate } func (s *statecontext) set(state istate) { s.state = state } func (s *statecontext) doexec() { s.state.exec(*s) }
gthulei/java-p2p
core/src/main/java/com/hl/p2p/server/imlp/AccountServerImpl.java
<gh_stars>1-10 package com.hl.p2p.server.imlp; import com.hl.p2p.mapper.AccountMapper; import com.hl.p2p.pojo.Account; import com.hl.p2p.server.IAccountServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 账户信息 */ @Service public class AccountServerImpl implements IAccountServer{ @Autowired private AccountMapper accountMapper; @Override public void updateAccount(Account account) { int result = accountMapper.updateByPrimaryKey(account); //表示乐观锁失败 if (result == 0) { throw new RuntimeException("乐观锁失败,Account:" + account.getId()); } } @Override public boolean addAccount(Account account) { int result = accountMapper.insert(account); return result > 0; } @Override public Account getAccountInfoById(long id) { Account result = accountMapper.selectByPrimaryKey(id); return result; } }
cloner1984/shogun
src/shogun/multiclass/ecoc/ECOCDecoder.h
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: <NAME>, <NAME>, <NAME> */ #ifndef ECOCDECODER_H__ #define ECOCDECODER_H__ #include <shogun/lib/config.h> #include <shogun/base/SGObject.h> #include <shogun/lib/SGMatrix.h> #include <shogun/lib/SGVector.h> namespace shogun { /** An ECOC decoder describe how to decode the * classification results of the binary classifiers * into a multiclass label according to the ECOC * codebook. */ class CECOCDecoder: public CSGObject { public: /** constructor */ CECOCDecoder() {} /** destructor */ ~CECOCDecoder() {} /** get name */ const char* get_name() const { return "ECOCDecoder"; } /** decide label. * @param outputs outputs by classifiers * @param codebook ECOC codebook */ virtual int32_t decide_label(const SGVector<float64_t> outputs, const SGMatrix<int32_t> codebook)=0; protected: /** turn 2-class labels into binary */ SGVector<float64_t> binarize(const SGVector<float64_t> query); }; } #endif /* end of include guard: ECOCDECODER_H__ */
igorlev91/DemoEngine
Include/Engine.hpp
#pragma once #include "EnginePublic.hpp" #include "System/Platform.hpp" #include "System/Window.hpp" #include "System/Timer.hpp" #include "System/InputState.hpp" #include "System/ResourceManager.hpp" #include "Graphics/RenderContext.hpp" #include "Graphics/SpriteRenderer.hpp" #include "Game/EntitySystem.hpp" #include "Game/ComponentSystem.hpp" #include "Game/IdentitySystem.hpp" #include "Game/SceneSystem.hpp" #include "Editor/Editor.hpp" /* Game Engine */ namespace Engine { // Root class. class Root { public: Root(); ~Root(); // Disallow copying and moving. Root(const Root& other) = delete; Root& operator=(const Root& other) = delete; // Moving constructor and assignment. Root(Root&& other); Root& operator=(Root&& other); // Initializes the engine instance. bool Initialize(); // Run the main game loop. int Run(); // Checks if the engine instance is initialized. bool IsInitialized() const; public: // Platform systems. System::Platform platform; System::Window window; System::Timer timer; System::InputState inputState; System::ResourceManager resourceManager; // Graphics systems. Graphics::RenderContext renderContext; Graphics::SpriteRenderer spriteRenderer; // Game systems. Game::EntitySystem entitySystem; Game::ComponentSystem componentSystem; Game::IdentitySystem identitySystem; Game::SceneSystem sceneSystem; // Engine systems. Engine::Editor editor; private: // Initialization state. bool m_initialized; }; }
kyeonghopark/jgt-code
Volume_11/Number_2/Jones2006/clip.c
/* clip.c - */ // Example code for "Efficient Generatino of Poisson-Disk Sampling // Patterns," <NAME>, JGT vol. 11, No. 2, pp. 27-36 // // Copyright 2004-2006, <NAME> // This code is distributed under the terms of the LGPL. #include "gts.h" #include "clip.h" #define printf #define g_assert(x) #define linear(alpha,a,b) (alpha*((a)-(b))+(b)) GtsPoint *intersect_y1(GtsPoint *p1, GtsPoint *p2) { double alpha = (1.0 - p2->y) / (p1->y - p2->y); return (gts_point_new(gts_point_class(), linear(alpha, p1->x, p2->x), 1.0, 0.0)); } GtsPoint *intersect_y0(GtsPoint *p1, GtsPoint *p2) { double alpha = (-p2->y) / (p1->y - p2->y); return (gts_point_new(gts_point_class(), linear(alpha, p1->x, p2->x), 0.0, 0.0)); } GtsPoint *intersect_x1(GtsPoint *p1, GtsPoint *p2) { double alpha = (1.0 - p2->x) / (p1->x - p2->x); return (gts_point_new(gts_point_class(), 1.0, linear(alpha, p1->y, p2->y), 0.0)); } GtsPoint *intersect_x0(GtsPoint *p1, GtsPoint *p2) { double alpha = (-p2->x) / (p1->x - p2->x); return (gts_point_new(gts_point_class(), 0.0, linear(alpha, p1->y, p2->y), 0.0)); } GSList *add_to_tri_list(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { GtsVertex *v1, *v2, *v3; GtsEdge *e1, *e2, *e3; GtsTriangle *t; v1 = gts_vertex_new(gts_vertex_class(), p1->x, p1->y, 0.0); v2 = gts_vertex_new(gts_vertex_class(), p2->x, p2->y, 0.0); v3 = gts_vertex_new(gts_vertex_class(), p3->x, p3->y, 0.0); e1 = gts_edge_new(gts_edge_class(), v1, v2); e2 = gts_edge_new(gts_edge_class(), v2, v3); e3 = gts_edge_new(gts_edge_class(), v3, v1); t = gts_triangle_new(gts_triangle_class(), e1, e2, e3); return (g_slist_prepend(tris, t)); } GSList *clip_y1(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { g_assert(p1->y <= 1.0); // clip at y = 1.0 int num_clipped = ((p2->y > 1.0) ? 1 : 0) + ((p3->y > 1.0) ? 1 : 0); if (num_clipped == 0) return (add_to_tri_list(tris, p1, p2, p3)); if (num_clipped == 2) { GtsPoint *intersect12, *intersect13; intersect12 = intersect_y1(p1, p2); intersect13 = intersect_y1(p1, p3); tris = add_to_tri_list(tris, p1, intersect12, intersect13); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect13)); return (tris); } // one vertex clipped // keep p1 as first vertex if (p2->y > 1.0) { GtsPoint *intersect12, *intersect23; intersect12 = intersect_y1(p1, p2); intersect23 = intersect_y1(p2, p3); tris = add_to_tri_list(tris, p1, intersect12, intersect23); tris = add_to_tri_list(tris, p1, intersect23, p3); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } else { GtsPoint *intersect31, *intersect23; intersect31 = intersect_y1(p3, p1); intersect23 = intersect_y1(p2, p3); tris = add_to_tri_list(tris, p1, p2, intersect23); tris = add_to_tri_list(tris, p1, intersect23, intersect31); gts_object_destroy(GTS_OBJECT(intersect31)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } } GSList *clip_y0(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { g_assert(p1->y >= 0.0); // clip at y = 0.0 int num_clipped = ((p2->y < 0.0) ? 1 : 0) + ((p3->y < 0.0) ? 1 : 0); if (num_clipped == 0) return (clip_y1(tris, p1, p2, p3)); if (num_clipped == 2) { GtsPoint *intersect12, *intersect13; intersect12 = intersect_y0(p1, p2); intersect13 = intersect_y0(p1, p3); tris = clip_y1(tris, p1, intersect12, intersect13); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect13)); return (tris); } // one vertex clipped // keep p1 as first vertex if (p2->y < 0.0) { GtsPoint *intersect12, *intersect23; intersect12 = intersect_y0(p1, p2); intersect23 = intersect_y0(p2, p3); tris = clip_y1(tris, p1, intersect12, intersect23); tris = clip_y1(tris, p1, intersect23, p3); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } else { GtsPoint *intersect31, *intersect23; intersect31 = intersect_y0(p3, p1); intersect23 = intersect_y0(p2, p3); tris = clip_y1(tris, p1, p2, intersect23); tris = clip_y1(tris, p1, intersect23, intersect31); gts_object_destroy(GTS_OBJECT(intersect31)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } } GSList *clip_x1(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { g_assert(p1->x <= 1.0); // clip at x = 1.0 int num_clipped = ((p2->x > 1.0) ? 1 : 0) + ((p3->x > 1.0) ? 1 : 0); if (num_clipped == 0) return (clip_y0(tris, p1, p2, p3)); if (num_clipped == 2) { GtsPoint *intersect12, *intersect13; intersect12 = intersect_x1(p1, p2); intersect13 = intersect_x1(p1, p3); tris = clip_y0(tris, p1, intersect12, intersect13); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect13)); return (tris); } // one vertex clipped // keep p1 as first vertex if (p2->x > 1.0) { GtsPoint *intersect12, *intersect23; intersect12 = intersect_x1(p1, p2); intersect23 = intersect_x1(p2, p3); tris = clip_y0(tris, p1, intersect12, intersect23); tris = clip_y0(tris, p1, intersect23, p3); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } else { GtsPoint *intersect31, *intersect23; intersect31 = intersect_x1(p3, p1); intersect23 = intersect_x1(p2, p3); tris = clip_y0(tris, p1, p2, intersect23); tris = clip_y0(tris, p1, intersect23, intersect31); gts_object_destroy(GTS_OBJECT(intersect31)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } } GSList *clip_x0(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { g_assert(p1->x >= 0.0); // clip at x = 0.0 int num_clipped = ((p2->x < 0.0) ? 1 : 0) + ((p3->x < 0.0) ? 1 : 0); if (num_clipped == 0) return (clip_x1(tris, p1, p2, p3)); if (num_clipped == 2) { GtsPoint *intersect12, *intersect13; intersect12 = intersect_x0(p1, p2); intersect13 = intersect_x0(p1, p3); tris = clip_x1(tris, p1, intersect12, intersect13); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect13)); return (tris); } // one vertex clipped // keep p1 as first vertex if (p2->x < 0.0) { GtsPoint *intersect12, *intersect23; intersect12 = intersect_x0(p1, p2); intersect23 = intersect_x0(p2, p3); tris = clip_x1(tris, p1, intersect12, intersect23); tris = clip_x1(tris, p1, intersect23, p3); gts_object_destroy(GTS_OBJECT(intersect12)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } else { GtsPoint *intersect31, *intersect23; intersect31 = intersect_x0(p3, p1); intersect23 = intersect_x0(p2, p3); tris = clip_x1(tris, p1, p2, intersect23); tris = clip_x1(tris, p1, intersect23, intersect31); gts_object_destroy(GTS_OBJECT(intersect31)); gts_object_destroy(GTS_OBJECT(intersect23)); return (tris); } } GSList *clip(GSList *tris, GtsPoint *p1, GtsPoint *p2, GtsPoint *p3) { return (clip_x0(tris, p1, p2, p3)); }
swchoi1994/Project
pin-2.11/source/tools/Tests/cp-pin.cpp
<filename>pin-2.11/source/tools/Tests/cp-pin.cpp /*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2012 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS 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. END_LEGAL */ #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; int main(int argc, char** argv) { if (argc != 3) { cerr << "Usage: " << argv[0] << " input-file output-file" << endl; exit(1); } char* ifn = argv[1]; char* ofn = argv[2]; ifstream* i = new ifstream(ifn, ios::in|ios::binary); if (!i) { cerr << "Could not open input file " << ifn << endl; exit(1); } ofstream* o = new ofstream(ofn, ios::out|ios::trunc|ios::binary); if (!o) { cerr << "Could not open output file " << ofn << endl; exit(1); } char ch; while(i->get(ch)) { *o << ch; } i->close(); o->close(); //cerr << "Exiting..." << endl; exit(0); //return 0; }
darbyjack/Hangar
src/main/java/io/papermc/hangar/model/db/ProjectIdentified.java
package io.papermc.hangar.model.db; public interface ProjectIdentified { long getProjectId(); }
hitsub2/elk_kibana
src/server/kbn_server.js
<gh_stars>1-10 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { var callNext = step.bind(null, 'next'); var callThrow = step.bind(null, 'throw'); function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(callNext, callThrow); } } callNext(); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _lodash = require('lodash'); var _bluebird = require('bluebird'); var _cluster = require('cluster'); var _utils = require('../utils'); var _configConfig = require('./config/config'); var _configConfig2 = _interopRequireDefault(_configConfig); var _loggingConfiguration = require('./logging/configuration'); var _loggingConfiguration2 = _interopRequireDefault(_loggingConfiguration); var rootDir = (0, _utils.fromRoot)('.'); module.exports = (function () { function KbnServer(settings) { var _this = this; _classCallCheck(this, KbnServer); this.name = _utils.pkg.name; this.version = _utils.pkg.version; this.build = _utils.pkg.build || false; this.rootDir = rootDir; this.settings = settings || {}; this.ready = (0, _lodash.constant)(this.mixin(require('./config/setup'), // sets this.config, reads this.settings require('./http'), // sets this.server require('./logging'), require('./warnings'), require('./status'), // writes pid file require('./pid'), // find plugins and set this.plugins require('./plugins/scan'), // disable the plugins that are disabled through configuration require('./plugins/check_enabled'), // disable the plugins that are incompatible with the current version of Kibana require('./plugins/check_version'), // tell the config we are done loading plugins require('./config/complete'), // setup this.uiExports and this.bundles require('../ui'), // setup server.uiSettings require('../ui/settings'), // ensure that all bundles are built, or that the // lazy bundle server is running require('../optimize'), // finally, initialize the plugins require('./plugins/initialize'), function () { if (_this.config.get('server.autoListen')) { _this.ready = (0, _lodash.constant)((0, _bluebird.resolve)()); return _this.listen(); } })); this.listen = (0, _lodash.once)(this.listen); } /** * Extend the KbnServer outside of the constraits of a plugin. This allows access * to APIs that are not exposed (intentionally) to the plugins and should only * be used when the code will be kept up to date with Kibana. * * @param {...function} - functions that should be called to mixin functionality. * They are called with the arguments (kibana, server, config) * and can return a promise to delay execution of the next mixin * @return {Promise} - promise that is resolved when the final mixin completes. */ _createClass(KbnServer, [{ key: 'mixin', value: _asyncToGenerator(function* () { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) { fns[_key] = arguments[_key]; } for (var _iterator = (0, _lodash.compact)((0, _lodash.flatten)(fns))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var fn = _step.value; yield fn.call(this, this, this.server, this.config); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator['return']) { _iterator['return'](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }) /** * Tell the server to listen for incoming requests, or get * a promise that will be resolved once the server is listening. * * @return undefined */ }, { key: 'listen', value: _asyncToGenerator(function* () { var server = this.server; var config = this.config; yield this.ready(); yield (0, _bluebird.fromNode)(function (cb) { return server.start(cb); }); if (_cluster.isWorker) { // help parent process know when we are ready process.send(['WORKER_LISTENING']); } server.log(['listening', 'info'], 'Server running at ' + server.info.uri); return server; }) }, { key: 'close', value: _asyncToGenerator(function* () { var _this2 = this; yield (0, _bluebird.fromNode)(function (cb) { return _this2.server.stop(cb); }); }) }, { key: 'inject', value: _asyncToGenerator(function* (opts) { var _this3 = this; if (!this.server) yield this.ready(); return yield (0, _bluebird.fromNode)(function (cb) { try { _this3.server.inject(opts, function (resp) { cb(null, resp); }); } catch (err) { cb(err); } }); }) }, { key: 'applyLoggingConfiguration', value: function applyLoggingConfiguration(settings) { var config = _configConfig2['default'].withDefaultSchema(settings); var loggingOptions = (0, _loggingConfiguration2['default'])(config); var subset = { ops: config.get('ops'), logging: config.get('logging') }; var plain = JSON.stringify(subset, null, 2); this.server.log(['info', 'config'], 'New logging configuration:\n' + plain); this.server.plugins['even-better'].monitor.reconfigure(loggingOptions); } }]); return KbnServer; })();
migueref/educational-app
node_modules/gulp-slash/index.js
var slash = require('slash'); var through = require('through2'); /** * Convert given text using node slash, or where no text is given, return a stream * that similarly converts gulp (vinyl) file paths in place. * @param {string|File} [candidate] Text or a vinyl file to convert * @returns {string|Transform} Converted text or file where given, else a transform stream for gulp */ module.exports = function gulpSlash(candidate) { 'use strict'; // no arguments implies stream if (arguments.length === 0) { return through.obj(function(file, encoding, done) { this.push(gulpSlash(file)); // requires named method done(); }); // text implies direct conversion } else if (typeof candidate === typeof '') { return slash(candidate); // object implies path,cwd,base fields are converted } else if (typeof candidate === typeof { }) { [ 'path', 'cwd', 'base' ].forEach(function (field) { var isValid = (field in candidate) && (typeof candidate[field] === typeof ''); if (isValid) { candidate[field] = slash(candidate[field]); } }); return candidate; } }
pytf/intelligent-protector
test/src/inc/common/UniqueIDTest.h
<filename>test/src/inc/common/UniqueIDTest.h<gh_stars>1-10 /******************************************************************************* * Copyright @ Huawei Technologies Co., Ltd. 2017-2018. All rights reserved. ********************************************************************************/ #ifndef _UNIQUEIDTEST_H_ #define _UNIQUEIDTEST_H_ #include <sstream> #include "common/UniqueId.h" #include "gtest/gtest.h" #include "stub.h" class UniqueIdTest: public testing::Test{ protected: }; #endif
TimScriptov/NMOD-Examples
ICPE/jni/core/blocks/cblockentity/CBlockEntityManager.cpp
#include "CBlockEntityManager.h" #include "CEntityBlock.h" #include "CBlockEntity.h" #include "mcpe/util/Util.h" #include "mcpe/level/BlockSource.h" #include "mcpe/util/ChunkPos.h" #include "mcpe/level/chunk/LevelChunk.h" #include "mcpe/block/Block.h" CBlockEntityManager::CBlockEntityManager(std::string const&path) { filePath=path; } CBlockEntityManager::~CBlockEntityManager() { } std::string CBlockEntityManager::getPathFor(BlockPos const&pos,DimensionId id) { std::string key=filePath+"/"+"mcacbe_"+Util::toString(pos.x)+"-"+Util::toString(pos.y)+"-"+Util::toString(pos.z)+"-"+Util::toString((int)id)+".mcadb"; return key; } void CBlockEntityManager::loadAll(LevelChunk&c,BlockSource&s) { ChunkPos base_pos=c.getPosition(); for(int x=base_pos.x*16;x<base_pos.x*16+16;++x) { for(int z=base_pos.z*16;z<base_pos.z*16+16;++z) { for(int y=0;y<256;++y) { if(((int)s.getBlock(x,y,z)->getBlockEntityType())==100) { CEntityBlock* ceb=(CEntityBlock*) s.getBlock(x,y,z); std::unique_ptr<CBlockEntity> be=createBlockEntity(ceb,BlockPos(x,y,z)); be->setNotAutoDelete(); c._placeBlockEntity(std::move(be)); } } } } } std::unique_ptr<CBlockEntity> CBlockEntityManager::createBlockEntity(CEntityBlock*b,BlockPos const&pos) { std::unique_ptr<CBlockEntity> be = b->createBlockEntity(pos); return be; }
alexakuzin/GUCEF-1
platform/gucefCOMCORE/src/gucefCOMCORE_CPubSubClientTopic.cpp
/* * gucefCOMCORE: GUCEF module providing basic communication facilities * * Copyright (C) 1998 - 2020. <NAME> * * 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. */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef GUCEF_MT_COBJECTSCOPELOCK_H #include "gucefMT_CObjectScopeLock.h" #define GUCEF_MT_COBJECTSCOPELOCK_H #endif /* GUCEF_MT_COBJECTSCOPELOCK_H ? */ #ifndef GUCEF_CORE_LOGGING_H #include "gucefCORE_Logging.h" #define GUCEF_CORE_LOGGING_H #endif /* GUCEF_CORE_LOGGING_H ? */ #include "gucefCOMCORE_CPubSubClientTopic.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace COMCORE { /*-------------------------------------------------------------------------// // // // GLOBAL VARS // // // //-------------------------------------------------------------------------*/ const CORE::CEvent CPubSubClientTopic::ConnectedEvent = "GUCEF::COMCORE::CPubSubClientTopic::ConnectedEvent"; const CORE::CEvent CPubSubClientTopic::DisconnectedEvent = "GUCEF::COMCORE::CPubSubClientTopic::DisconnectedEvent"; const CORE::CEvent CPubSubClientTopic::ConnectionErrorEvent = "GUCEF::COMCORE::CPubSubClientTopic::ConnectionErrorEvent"; const CORE::CEvent CPubSubClientTopic::InternalErrorEvent = "GUCEF::COMCORE::CPubSubClientTopic::InternalErrorEvent"; const CORE::CEvent CPubSubClientTopic::MsgsRecievedEvent = "GUCEF::COMCORE::CPubSubClientTopic::MsgsRecievedEvent"; const CORE::CEvent CPubSubClientTopic::MsgsPublishedEvent = "GUCEF::COMCORE::CPubSubClientTopic::MsgsPublishedEvent"; const CORE::CEvent CPubSubClientTopic::MsgsPublishFailureEvent = "GUCEF::COMCORE::CPubSubClientTopic::MsgsPublishFailureEvent"; const CORE::CEvent CPubSubClientTopic::LocalPublishQueueFullEvent = "GUCEF::COMCORE::CPubSubClientTopic::LocalPublishQueueFullEvent"; const CORE::CEvent CPubSubClientTopic::PublishThrottleEvent = "GUCEF::COMCORE::CPubSubClientTopic::PublishThrottleEvent"; /*-------------------------------------------------------------------------// // // // IMPLEMENTATION // // // //-------------------------------------------------------------------------*/ void CPubSubClientTopic::RegisterEvents( void ) {GUCEF_TRACE; ConnectedEvent.Initialize(); DisconnectedEvent.Initialize(); ConnectionErrorEvent.Initialize(); InternalErrorEvent.Initialize(); MsgsRecievedEvent.Initialize(); MsgsPublishedEvent.Initialize(); MsgsPublishFailureEvent.Initialize(); LocalPublishQueueFullEvent.Initialize(); PublishThrottleEvent.Initialize(); } /*-------------------------------------------------------------------------*/ CPubSubClientTopic::CPubSubClientTopic( void ) : CORE::CObservingNotifier() , CORE::CTSharedPtrCreator< CPubSubClientTopic, MT::CMutex >( this ) {GUCEF_TRACE; RegisterEvents(); } /*-------------------------------------------------------------------------*/ CPubSubClientTopic::~CPubSubClientTopic() {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::AcknowledgeReceipt( const CIPubSubMsg& msg ) {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::AcknowledgeReceipt( const CPubSubBookmark& bookmark ) {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::RequestMaxSubscriptionMsgsPerSecRate( CORE::Int64 maxMsgsPerSec ) {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ const CPubSubClient* CPubSubClientTopic::GetClient( void ) const {GUCEF_TRACE; return const_cast< CPubSubClientTopic* >( this )->GetClient(); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::DeriveBookmarkFromMsg( const CIPubSubMsg& msg, CPubSubBookmark& bookmark ) const {GUCEF_TRACE; bookmark.SetBookmarkType( CPubSubBookmark::BOOKMARK_TYPE_NOT_APPLICABLE ); bookmark.SetBookmarkData( CORE::CVariant::Empty ); return false; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CDynamicBuffer& payload, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.GetPrimaryPayload().LinkTo( payload ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CString& payload, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.GetPrimaryPayload().LinkTo( payload ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CVariant& msgId, const CORE::CVariant& payload, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.GetPrimaryPayload().LinkTo( payload ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CString& key, const CORE::CString& value, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.AddLinkedKeyValuePair( key, value ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CString& key, const CORE::CDynamicBuffer& value, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.AddLinkedKeyValuePair( key, value ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CDynamicBuffer& key, const CORE::CDynamicBuffer& value, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.AddLinkedKeyValuePair( key, value ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CVariant& msgId, const CORE::CDynamicBuffer& key, const CORE::CDynamicBuffer& value, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.AddLinkedKeyValuePair( key, value ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionId& publishActionId, const CORE::CString& msgId, const CORE::CValueList& kvPairs, bool notify ) {GUCEF_TRACE; CBasicPubSubMsg msg; msg.GetMsgId().LinkTo( msgId ); msg.AddLinkedKeyValuePairs( kvPairs ); return Publish( publishActionId, msg, notify ); } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionIdVector& publishActionIds, const CBasicPubSubMsg::TBasicPubSubMsgVector& msgs, bool notify ) {GUCEF_TRACE; bool totalSuccess = true; size_t preExistingActionIds = publishActionIds.size(); size_t n=0; CBasicPubSubMsg::TBasicPubSubMsgVector::const_iterator i = msgs.begin(); while ( i != msgs.end() ) { CORE::UInt64 publishActionId = 0; if ( preExistingActionIds > n ) { publishActionId = publishActionIds[ n ]; } totalSuccess = totalSuccess && Publish( publishActionId, (*i), false ); if ( preExistingActionIds > n ) publishActionIds[ n ] = publishActionId; else publishActionIds.push_back( publishActionId ); ++i; ++n; } return totalSuccess; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionIdVector& publishActionIds, const TIPubSubMsgConstRawPtrVector& msgs, bool notify ) {GUCEF_TRACE; bool totalSuccess = true; size_t preExistingActionIds = publishActionIds.size(); size_t n=0; CIPubSubMsg::TIPubSubMsgConstRawPtrVector::const_iterator i = msgs.begin(); while ( i != msgs.end() ) { CORE::UInt64 publishActionId = 0; if ( preExistingActionIds > n ) { publishActionId = publishActionIds[ n ]; } const CIPubSubMsg* rawMsgPtr = (*i); if ( GUCEF_NULL != rawMsgPtr ) totalSuccess = totalSuccess && Publish( publishActionId, *rawMsgPtr, notify ); else totalSuccess = false; if ( preExistingActionIds > n ) publishActionIds[ n ] = publishActionId; else publishActionIds.push_back( publishActionId ); ++i; ++n; } return totalSuccess; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionIdVector& publishActionIds, const TIPubSubMsgRawPtrVector& msgs, bool notify ) {GUCEF_TRACE; bool totalSuccess = true; size_t preExistingActionIds = publishActionIds.size(); size_t n=0; CIPubSubMsg::TIPubSubMsgRawPtrVector::const_iterator i = msgs.begin(); while ( i != msgs.end() ) { CORE::UInt64 publishActionId = 0; if ( preExistingActionIds > n ) { publishActionId = publishActionIds[ n ]; } const CIPubSubMsg* rawMsgPtr = (*i); if ( GUCEF_NULL != rawMsgPtr ) totalSuccess = totalSuccess && Publish( publishActionId, *rawMsgPtr, notify ); else totalSuccess = false; if ( preExistingActionIds > n ) publishActionIds[ n ] = publishActionId; else publishActionIds.push_back( publishActionId ); ++i; ++n; } return totalSuccess; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionIdVector& publishActionIds, const TIPubSubMsgSPtrVector& msgs, bool notify ) {GUCEF_TRACE; bool totalSuccess = true; size_t preExistingActionIds = publishActionIds.size(); size_t n=0; CIPubSubMsg::TIPubSubMsgSPtrVector::const_iterator i = msgs.begin(); while ( i != msgs.end() ) { CORE::UInt64 publishActionId = 0; if ( preExistingActionIds > n ) { publishActionId = publishActionIds[ n ]; } if ( !(*i).IsNULL() ) totalSuccess = totalSuccess && Publish( publishActionId, *(*i).GetPointerAlways(), notify ); else totalSuccess = false; if ( preExistingActionIds > n ) publishActionIds[ n ] = publishActionId; else publishActionIds.push_back( publishActionId ); ++i; ++n; } return totalSuccess; } /*-------------------------------------------------------------------------*/ bool CPubSubClientTopic::Publish( TPublishActionIdVector& publishActionIds, const TPubSubMsgsRefVector& msgs, bool notify ) {GUCEF_TRACE; bool totalSuccess = true; size_t preExistingActionIds = publishActionIds.size(); size_t n=0; TPubSubMsgsRefVector::const_iterator i = msgs.begin(); while ( i != msgs.end() ) { CORE::UInt64 publishActionId = 0; if ( preExistingActionIds > n ) { publishActionId = publishActionIds[ n ]; } const CIPubSubMsg* rawMsgPtr = (*i); if ( GUCEF_NULL != rawMsgPtr ) totalSuccess = totalSuccess && Publish( publishActionId, *rawMsgPtr, notify ); else totalSuccess = false; if ( preExistingActionIds > n ) publishActionIds[ n ] = publishActionId; else publishActionIds.push_back( publishActionId ); ++i; ++n; } return totalSuccess; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace COMCORE */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/
ZackMurry/nottte-me
frontend/components/navbar/SmallScreenNavbar.js
<reponame>ZackMurry/nottte-me<filename>frontend/components/navbar/SmallScreenNavbar.js import { ClickAwayListener, Collapse, Link, Paper, Typography } from '@material-ui/core' import { useEffect, useState } from 'react' import theme from '../theme' export default function SmallScreenNavbar({ jwt }) { const [ menuOpen, setMenuOpen ] = useState(false) const [ prevScrollPos, setPrevScrollPos ] = useState(0) const [ showing, setShowing ] = useState(true) const handleMenuClick = () => { setMenuOpen(!menuOpen) } const handleScroll = () => { const currentScrollPos = window.pageYOffset if (prevScrollPos < currentScrollPos) { console.log('down: ' + currentScrollPos + ' - ' + prevScrollPos) if (showing) { setTimeout(() => setShowing(false), 250) console.log('hiding') } } else if (!showing) { setTimeout(() => setShowing(true), 250) //todo animate console.log('showing') } setPrevScrollPos(currentScrollPos) console.log(showing + '; ' + currentScrollPos) } useEffect(() => { window.addEventListener('scroll', handleScroll) return () => window.removeEventListener('scroll', handleScroll) }, [ showing, prevScrollPos, setPrevScrollPos ]) return ( <ClickAwayListener onClickAway={() => setMenuOpen(false)}> <div style={{ width: '100%', position: 'fixed', top: showing ? 0 : -100, left: 0, zIndex: 10, backgroundColor: theme.palette.secondary.main, height: '10vh', justifyContent: 'space-between', visibility: showing ? undefined : 'hidden' }} className={showing ? 'show-nav' : 'hide-nav'} > <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: 80, height: 80, cursor: 'pointer', transition: 'all .5s ease-in-out' }} onClick={handleMenuClick} className={menuOpen ? 'navbar-menu-open' : undefined} > <div className='navbar-burger' style={!showing ? { visibility: 'hidden' } : undefined} /> </div> <Collapse in={menuOpen} timeout={750} style={{ boxShadow: '0 15px 25px -12.5px black' }}> <Paper elevation={0} style={{ borderRadius: 0 }}> <Paper elevation={0} style={{ backgroundColor: theme.palette.secondary.main, height: '5vh', borderRadius: 0, padding: 15, cursor: 'pointer' }} > <Link href='/'> <Typography variant='h5' color='primary'> home </Typography> </Link> </Paper> <Paper elevation={0} style={{ backgroundColor: theme.palette.secondary.main, height: '5vh', borderRadius: 0, padding: 15, cursor: 'pointer' }} > <Link href='/notes'> <Typography variant='h5' color='primary'> notes </Typography> </Link> </Paper> <Paper elevation={0} style={{ backgroundColor: theme.palette.secondary.main, height: '5vh', borderRadius: 0, padding: 15, cursor: 'pointer' }} > <Link href='/shortcuts'> <Typography variant='h5' color='primary'> shortcuts </Typography> </Link> </Paper> <Paper elevation={0} style={{ backgroundColor: theme.palette.secondary.main, height: '7vh', borderRadius: 0, padding: 15, cursor: 'pointer' }} > <Link href={jwt ? '/account' : '/login'}> <Typography variant='h5' color='primary'> {jwt ? 'account' : 'login'} </Typography> </Link> </Paper> </Paper> </Collapse> <Link href='/'> <Typography color='primary' style={{ position: 'fixed', top: '1.5vh', right: 30, fontWeight: 100, fontSize: 36, cursor: 'pointer' }} > nottte.me </Typography> </Link> </div> </ClickAwayListener> ) }
ilinksolutionsbr/kettle-beam
src/main/java/org/kettle/beam/pipeline/handler/BeamSubscriberStepHandler.java
<filename>src/main/java/org/kettle/beam/pipeline/handler/BeamSubscriberStepHandler.java package org.kettle.beam.pipeline.handler; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.values.PCollection; import org.apache.commons.lang.StringUtils; import org.kettle.beam.core.KettleRow; import org.kettle.beam.core.transform.BeamSubscribeTransform; import org.kettle.beam.core.util.JsonRowMeta; import org.kettle.beam.metastore.BeamJobConfig; import org.kettle.beam.steps.pubsub.BeamSubscribeMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.metastore.api.IMetaStore; import java.util.List; import java.util.Map; public class BeamSubscriberStepHandler extends BeamBaseStepHandler implements BeamStepHandler { public BeamSubscriberStepHandler( BeamJobConfig beamJobConfig, IMetaStore metaStore, TransMeta transMeta, List<String> stepPluginClasses, List<String> xpPluginClasses ) { super( beamJobConfig, true, false, metaStore, transMeta, stepPluginClasses, xpPluginClasses ); } @Override public void handleStep( LogChannelInterface log, StepMeta stepMeta, Map<String, PCollection<KettleRow>> stepCollectionMap, Pipeline pipeline, RowMetaInterface rowMeta, List<StepMeta> previousSteps, PCollection<KettleRow> input ) throws KettleException { // A Beam subscriber step // BeamSubscribeMeta inputMeta = (BeamSubscribeMeta) stepMeta.getStepMetaInterface(); RowMetaInterface outputRowMeta = transMeta.getStepFields( stepMeta ); String rowMetaJson = JsonRowMeta.toJson( outputRowMeta ); // Verify some things: // if ( StringUtils.isEmpty( inputMeta.getTopic() ) ) { throw new KettleException( "Please specify a topic to read from in Beam Pub/Sub Subscribe step '" + stepMeta.getName() + "'" ); } BeamSubscribeTransform subscribeTransform = new BeamSubscribeTransform( stepMeta.getName(), stepMeta.getName(), transMeta.environmentSubstitute( inputMeta.getSubscription() ), transMeta.environmentSubstitute( inputMeta.getTopic() ), inputMeta.getMessageType(), rowMetaJson, stepPluginClasses, xpPluginClasses ); PCollection<KettleRow> afterInput = pipeline.apply( subscribeTransform ); stepCollectionMap.put( stepMeta.getName(), afterInput ); log.logBasic( "Handled step (SUBSCRIBE) : " + stepMeta.getName() ); } }
Achterhoeker/XChange
xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/dto/BTCChinaError.java
<reponame>Achterhoeker/XChange<filename>xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/dto/BTCChinaError.java package com.xeiam.xchange.btcchina.dto; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author ObsessiveOrange */ public class BTCChinaError { private final int code; private final String message; private final String id; /** * Constructor */ public BTCChinaError(@JsonProperty("code") int code, @JsonProperty("message") String message, @JsonProperty("id") String id) { this.code = code; this.message = message; this.id = id; } /** * @return the code */ public int getCode() { return code; } /** * @return the message */ public String getMessage() { return message; } /** * @return the id */ public String getID() { return id; } @Override public String toString() { return String.format("BTCChinaError{code=%s, result=%s, id=%s}", code, message, id); } }
billwert/azure-sdk-for-java
sdk/spring/spring-messaging-azure-servicebus/src/main/java/com/azure/spring/messaging/servicebus/core/properties/ProcessorProperties.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.messaging.servicebus.core.properties; import com.azure.spring.cloud.service.implementation.servicebus.properties.ServiceBusProcessorClientProperties; /** * A service bus processor related properties. */ public class ProcessorProperties extends ConsumerProperties implements ServiceBusProcessorClientProperties { private Integer maxConcurrentCalls = 1; private Integer maxConcurrentSessions = null; @Override public Integer getMaxConcurrentCalls() { return maxConcurrentCalls; } /** * Set the max concurrent call number. * @param maxConcurrentCalls the max concurrent call number. */ public void setMaxConcurrentCalls(Integer maxConcurrentCalls) { this.maxConcurrentCalls = maxConcurrentCalls; } @Override public Integer getMaxConcurrentSessions() { return maxConcurrentSessions; } /** * Set the max concurrent session number. * @param maxConcurrentSessions the max concurrent session number. */ public void setMaxConcurrentSessions(Integer maxConcurrentSessions) { this.maxConcurrentSessions = maxConcurrentSessions; } }
sunzhen086/springbootvue
springboot/src/main/java/org/dev/framework/modules/sys/service/impl/SysSequenceQueueServiceImpl.java
<reponame>sunzhen086/springbootvue package org.dev.framework.modules.sys.service.impl; import org.dev.framework.modules.sys.entity.SysSequenceQueue; import org.dev.framework.modules.sys.mapper.SysSequenceQueueMapper; import org.dev.framework.modules.sys.service.SysSequenceQueueService; import org.dev.framework.modules.sys.entity.SysSequenceQueue; import org.dev.framework.modules.sys.mapper.SysSequenceQueueMapper; import org.dev.framework.modules.sys.service.SysSequenceQueueService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 生成的队列号 服务实现类 * </p> * * @author dean.x.liu * @since 2020-07-20 */ @Service public class SysSequenceQueueServiceImpl extends ServiceImpl<SysSequenceQueueMapper, SysSequenceQueue> implements SysSequenceQueueService { }
AmrMaghraby/challenge-Instabug
db/migrate/20191129014257_add_column1.rb
<filename>db/migrate/20191129014257_add_column1.rb class AddColumn1 < ActiveRecord::Migration[5.2] def change add_column :rooms, :room_id, :int end end
MentorBot/Webhook
mentorbot/bot/urls.py
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from .views import FacebookMessengerWebhook, SlackWebhook, TwitterWebhook urlpatterns = { url(r'^messenger_webhook/?$', FacebookMessengerWebhook.as_view(), name="Facebook Messenger Webhook"), url(r'^slack_webhook$', SlackWebhook.as_view(), name="Slack Webhook"), url(r'^twitter_webhook$', TwitterWebhook.as_view(), name="Twitter Webhook") } urlpatterns = format_suffix_patterns(urlpatterns)
aicas/s2n-tls
tests/cbmc/proofs/s2n_digest_allow_md5_for_fips_boringssl_awslc/s2n_digest_allow_md5_for_fips_harness.c
<gh_stars>1-10 /* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <cbmc_proof/make_common_datastructures.h> #include "api/s2n.h" #include "crypto/s2n_evp.h" void s2n_digest_allow_md5_for_fips_harness() { /* Non-deterministic inputs. */ struct s2n_evp_digest *evp_digest = cbmc_allocate_s2n_evp_digest(); /* Save previous state. */ unsigned long old_flags; if (evp_digest != NULL && evp_digest->ctx != NULL) old_flags = evp_digest->ctx->flags; /* Operation under verification. */ if (s2n_digest_allow_md5_for_fips(evp_digest) == S2N_SUCCESS) { /* Post-conditions. */ assert(evp_digest != NULL); assert(evp_digest->ctx != NULL); assert(s2n_is_in_fips_mode()); } }
ErmirioABonfim/Exercicos-Python
Exercios Em Python/ex058.py
import random import emoji from time import sleep NumPC = random.randrange(0,10,1) print('\033[1;31;47m -=-'*10) Rungame = '' tried = 0 while Rungame != 'f': NumUsuario= int(input('\033[1;33;42m Pense em um número e quando estiver pronto digite ')) print('-=-'*10) print('\033[1;31;47m Processando...'.upper()) sleep(1) if NumPC == NumUsuario: print(emoji.emojize('\033[1;33;42m Parabéns você acertou :thumbsup:', use_aliases=True)) Rungame = 'f' else: print(emoji.emojize('Você errou :hankey:', use_aliases=True)) tried += 1 print('Você acertou com {} tentativas'. format(tried + 1 )) print('Eu pensei no {}, Obrigado por jogar'.format(NumPC))
KG2013/springboot-framework
springboot-framework/src/main/java/com/codingapi/springboot/framework/persistence/IPersistenceEvent.java
package com.codingapi.springboot.framework.persistence; import com.codingapi.springboot.framework.event.ISyncEvent; /** * * 持久化同步事件 * 相比于ISyncEvent在IPersistenceEvent执行出现异常的时候会直接抛出 * @see com.codingapi.springboot.framework.persistence.IPersistence */ interface IPersistenceEvent extends ISyncEvent { }
TUDSSL/TICS
msp430-gcc-tics/msp430-gcc-7.3.1.24-source-full/gcc/gcc/fortran/match.c
<reponame>TUDSSL/TICS /* Matching subroutines in all sizes, shapes and colors. Copyright (C) 2000-2017 Free Software Foundation, Inc. Contributed by <NAME> This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "options.h" #include "gfortran.h" #include "match.h" #include "parse.h" int gfc_matching_ptr_assignment = 0; int gfc_matching_procptr_assignment = 0; bool gfc_matching_prefix = false; /* Stack of SELECT TYPE statements. */ gfc_select_type_stack *select_type_stack = NULL; /* For debugging and diagnostic purposes. Return the textual representation of the intrinsic operator OP. */ const char * gfc_op2string (gfc_intrinsic_op op) { switch (op) { case INTRINSIC_UPLUS: case INTRINSIC_PLUS: return "+"; case INTRINSIC_UMINUS: case INTRINSIC_MINUS: return "-"; case INTRINSIC_POWER: return "**"; case INTRINSIC_CONCAT: return "//"; case INTRINSIC_TIMES: return "*"; case INTRINSIC_DIVIDE: return "/"; case INTRINSIC_AND: return ".and."; case INTRINSIC_OR: return ".or."; case INTRINSIC_EQV: return ".eqv."; case INTRINSIC_NEQV: return ".neqv."; case INTRINSIC_EQ_OS: return ".eq."; case INTRINSIC_EQ: return "=="; case INTRINSIC_NE_OS: return ".ne."; case INTRINSIC_NE: return "/="; case INTRINSIC_GE_OS: return ".ge."; case INTRINSIC_GE: return ">="; case INTRINSIC_LE_OS: return ".le."; case INTRINSIC_LE: return "<="; case INTRINSIC_LT_OS: return ".lt."; case INTRINSIC_LT: return "<"; case INTRINSIC_GT_OS: return ".gt."; case INTRINSIC_GT: return ">"; case INTRINSIC_NOT: return ".not."; case INTRINSIC_ASSIGN: return "="; case INTRINSIC_PARENTHESES: return "parens"; case INTRINSIC_NONE: return "none"; /* DTIO */ case INTRINSIC_FORMATTED: return "formatted"; case INTRINSIC_UNFORMATTED: return "unformatted"; default: break; } gfc_internal_error ("gfc_op2string(): Bad code"); /* Not reached. */ } /******************** Generic matching subroutines ************************/ /* Matches a member separator. With standard FORTRAN this is '%', but with DEC structures we must carefully match dot ('.'). Because operators are spelled ".op.", a dotted string such as "x.y.z..." can be either a component reference chain or a combination of binary operations. There is no real way to win because the string may be grammatically ambiguous. The following rules help avoid ambiguities - they match some behavior of other (older) compilers. If the rules here are changed the test cases should be updated. If the user has problems with these rules they probably deserve the consequences. Consider "x.y.z": (1) If any user defined operator ".y." exists, this is always y(x,z) (even if ".y." is the wrong type and/or x has a member y). (2) Otherwise if x has a member y, and y is itself a derived type, this is (x->y)->z, even if an intrinsic operator exists which can handle (x,z). (3) If x has no member y or (x->y) is not a derived type but ".y." is an intrinsic operator (such as ".eq."), this is y(x,z). (4) Lastly if there is no operator ".y." and x has no member "y", it is an error. It is worth noting that the logic here does not support mixed use of member accessors within a single string. That is, even if x has component y and y has component z, the following are all syntax errors: "x%y.z" "x.y%z" "(x.y).z" "(x%y)%z" */ match gfc_match_member_sep(gfc_symbol *sym) { char name[GFC_MAX_SYMBOL_LEN + 1]; locus dot_loc, start_loc; gfc_intrinsic_op iop; match m; gfc_symbol *tsym; gfc_component *c = NULL; /* What a relief: '%' is an unambiguous member separator. */ if (gfc_match_char ('%') == MATCH_YES) return MATCH_YES; /* Beware ye who enter here. */ if (!flag_dec_structure || !sym) return MATCH_NO; tsym = NULL; /* We may be given either a derived type variable or the derived type declaration itself (which actually contains the components); we need the latter to search for components. */ if (gfc_fl_struct (sym->attr.flavor)) tsym = sym; else if (gfc_bt_struct (sym->ts.type)) tsym = sym->ts.u.derived; iop = INTRINSIC_NONE; name[0] = '\0'; m = MATCH_NO; /* If we have to reject come back here later. */ start_loc = gfc_current_locus; /* Look for a component access next. */ if (gfc_match_char ('.') != MATCH_YES) return MATCH_NO; /* If we accept, come back here. */ dot_loc = gfc_current_locus; /* Try to match a symbol name following the dot. */ if (gfc_match_name (name) != MATCH_YES) { gfc_error ("Expected structure component or operator name " "after '.' at %C"); goto error; } /* If no dot follows we have "x.y" which should be a component access. */ if (gfc_match_char ('.') != MATCH_YES) goto yes; /* Now we have a string "x.y.z" which could be a nested member access (x->y)->z or a binary operation y on x and z. */ /* First use any user-defined operators ".y." */ if (gfc_find_uop (name, sym->ns) != NULL) goto no; /* Match accesses to existing derived-type components for derived-type vars: "x.y.z" = (x->y)->z */ c = gfc_find_component(tsym, name, false, true, NULL); if (c && (gfc_bt_struct (c->ts.type) || c->ts.type == BT_CLASS)) goto yes; /* If y is not a component or has no members, try intrinsic operators. */ gfc_current_locus = start_loc; if (gfc_match_intrinsic_op (&iop) != MATCH_YES) { /* If ".y." is not an intrinsic operator but y was a valid non- structure component, match and leave the trailing dot to be dealt with later. */ if (c) goto yes; gfc_error ("%qs is neither a defined operator nor a " "structure component in dotted string at %C", name); goto error; } /* .y. is an intrinsic operator, overriding any possible member access. */ goto no; /* Return keeping the current locus consistent with the match result. */ error: m = MATCH_ERROR; no: gfc_current_locus = start_loc; return m; yes: gfc_current_locus = dot_loc; return MATCH_YES; } /* This function scans the current statement counting the opened and closed parenthesis to make sure they are balanced. */ match gfc_match_parens (void) { locus old_loc, where; int count; gfc_instring instring; gfc_char_t c, quote; old_loc = gfc_current_locus; count = 0; instring = NONSTRING; quote = ' '; for (;;) { c = gfc_next_char_literal (instring); if (c == '\n') break; if (quote == ' ' && ((c == '\'') || (c == '"'))) { quote = c; instring = INSTRING_WARN; continue; } if (quote != ' ' && c == quote) { quote = ' '; instring = NONSTRING; continue; } if (c == '(' && quote == ' ') { count++; where = gfc_current_locus; } if (c == ')' && quote == ' ') { count--; where = gfc_current_locus; } } gfc_current_locus = old_loc; if (count > 0) { gfc_error ("Missing %<)%> in statement at or before %L", &where); return MATCH_ERROR; } if (count < 0) { gfc_error ("Missing %<(%> in statement at or before %L", &where); return MATCH_ERROR; } return MATCH_YES; } /* See if the next character is a special character that has escaped by a \ via the -fbackslash option. */ match gfc_match_special_char (gfc_char_t *res) { int len, i; gfc_char_t c, n; match m; m = MATCH_YES; switch ((c = gfc_next_char_literal (INSTRING_WARN))) { case 'a': *res = '\a'; break; case 'b': *res = '\b'; break; case 't': *res = '\t'; break; case 'f': *res = '\f'; break; case 'n': *res = '\n'; break; case 'r': *res = '\r'; break; case 'v': *res = '\v'; break; case '\\': *res = '\\'; break; case '0': *res = '\0'; break; case 'x': case 'u': case 'U': /* Hexadecimal form of wide characters. */ len = (c == 'x' ? 2 : (c == 'u' ? 4 : 8)); n = 0; for (i = 0; i < len; i++) { char buf[2] = { '\0', '\0' }; c = gfc_next_char_literal (INSTRING_WARN); if (!gfc_wide_fits_in_byte (c) || !gfc_check_digit ((unsigned char) c, 16)) return MATCH_NO; buf[0] = (unsigned char) c; n = n << 4; n += strtol (buf, NULL, 16); } *res = n; break; default: /* Unknown backslash codes are simply not expanded. */ m = MATCH_NO; break; } return m; } /* In free form, match at least one space. Always matches in fixed form. */ match gfc_match_space (void) { locus old_loc; char c; if (gfc_current_form == FORM_FIXED) return MATCH_YES; old_loc = gfc_current_locus; c = gfc_next_ascii_char (); if (!gfc_is_whitespace (c)) { gfc_current_locus = old_loc; return MATCH_NO; } gfc_gobble_whitespace (); return MATCH_YES; } /* Match an end of statement. End of statement is optional whitespace, followed by a ';' or '\n' or comment '!'. If a semicolon is found, we continue to eat whitespace and semicolons. */ match gfc_match_eos (void) { locus old_loc; int flag; char c; flag = 0; for (;;) { old_loc = gfc_current_locus; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); switch (c) { case '!': do { c = gfc_next_ascii_char (); } while (c != '\n'); /* Fall through. */ case '\n': return MATCH_YES; case ';': flag = 1; continue; } break; } gfc_current_locus = old_loc; return (flag) ? MATCH_YES : MATCH_NO; } /* Match a literal integer on the input, setting the value on MATCH_YES. Literal ints occur in kind-parameters as well as old-style character length specifications. If cnt is non-NULL it will be set to the number of digits. */ match gfc_match_small_literal_int (int *value, int *cnt) { locus old_loc; char c; int i, j; old_loc = gfc_current_locus; *value = -1; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); if (cnt) *cnt = 0; if (!ISDIGIT (c)) { gfc_current_locus = old_loc; return MATCH_NO; } i = c - '0'; j = 1; for (;;) { old_loc = gfc_current_locus; c = gfc_next_ascii_char (); if (!ISDIGIT (c)) break; i = 10 * i + c - '0'; j++; if (i > 99999999) { gfc_error ("Integer too large at %C"); return MATCH_ERROR; } } gfc_current_locus = old_loc; *value = i; if (cnt) *cnt = j; return MATCH_YES; } /* Match a small, constant integer expression, like in a kind statement. On MATCH_YES, 'value' is set. */ match gfc_match_small_int (int *value) { gfc_expr *expr; match m; int i; m = gfc_match_expr (&expr); if (m != MATCH_YES) return m; if (gfc_extract_int (expr, &i, 1)) m = MATCH_ERROR; gfc_free_expr (expr); *value = i; return m; } /* This function is the same as the gfc_match_small_int, except that we're keeping the pointer to the expr. This function could just be removed and the previously mentioned one modified, though all calls to it would have to be modified then (and there were a number of them). Return MATCH_ERROR if fail to extract the int; otherwise, return the result of gfc_match_expr(). The expr (if any) that was matched is returned in the parameter expr. */ match gfc_match_small_int_expr (int *value, gfc_expr **expr) { match m; int i; m = gfc_match_expr (expr); if (m != MATCH_YES) return m; if (gfc_extract_int (*expr, &i, 1)) m = MATCH_ERROR; *value = i; return m; } /* Matches a statement label. Uses gfc_match_small_literal_int() to do most of the work. */ match gfc_match_st_label (gfc_st_label **label) { locus old_loc; match m; int i, cnt; old_loc = gfc_current_locus; m = gfc_match_small_literal_int (&i, &cnt); if (m != MATCH_YES) return m; if (cnt > 5) { gfc_error ("Too many digits in statement label at %C"); goto cleanup; } if (i == 0) { gfc_error ("Statement label at %C is zero"); goto cleanup; } *label = gfc_get_st_label (i); return MATCH_YES; cleanup: gfc_current_locus = old_loc; return MATCH_ERROR; } /* Match and validate a label associated with a named IF, DO or SELECT statement. If the symbol does not have the label attribute, we add it. We also make sure the symbol does not refer to another (active) block. A matched label is pointed to by gfc_new_block. */ match gfc_match_label (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; match m; gfc_new_block = NULL; m = gfc_match (" %n :", name); if (m != MATCH_YES) return m; if (gfc_get_symbol (name, NULL, &gfc_new_block)) { gfc_error ("Label name %qs at %C is ambiguous", name); return MATCH_ERROR; } if (gfc_new_block->attr.flavor == FL_LABEL) { gfc_error ("Duplicate construct label %qs at %C", name); return MATCH_ERROR; } if (!gfc_add_flavor (&gfc_new_block->attr, FL_LABEL, gfc_new_block->name, NULL)) return MATCH_ERROR; return MATCH_YES; } /* See if the current input looks like a name of some sort. Modifies the passed buffer which must be GFC_MAX_SYMBOL_LEN+1 bytes long. Note that options.c restricts max_identifier_length to not more than GFC_MAX_SYMBOL_LEN. */ match gfc_match_name (char *buffer) { locus old_loc; int i; char c; old_loc = gfc_current_locus; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); if (!(ISALPHA (c) || (c == '_' && flag_allow_leading_underscore))) { /* Special cases for unary minus and plus, which allows for a sensible error message for code of the form 'c = exp(-a*b) )' where an extra ')' appears at the end of statement. */ if (!gfc_error_flag_test () && c != '(' && c != '-' && c != '+') gfc_error ("Invalid character in name at %C"); gfc_current_locus = old_loc; return MATCH_NO; } i = 0; do { buffer[i++] = c; if (i > gfc_option.max_identifier_length) { gfc_error ("Name at %C is too long"); return MATCH_ERROR; } old_loc = gfc_current_locus; c = gfc_next_ascii_char (); } while (ISALNUM (c) || c == '_' || (flag_dollar_ok && c == '$')); if (c == '$' && !flag_dollar_ok) { gfc_fatal_error ("Invalid character %<$%> at %L. Use %<-fdollar-ok%> to " "allow it as an extension", &old_loc); return MATCH_ERROR; } buffer[i] = '\0'; gfc_current_locus = old_loc; return MATCH_YES; } /* Match a symbol on the input. Modifies the pointer to the symbol pointer if successful. */ match gfc_match_sym_tree (gfc_symtree **matched_symbol, int host_assoc) { char buffer[GFC_MAX_SYMBOL_LEN + 1]; match m; m = gfc_match_name (buffer); if (m != MATCH_YES) return m; if (host_assoc) return (gfc_get_ha_sym_tree (buffer, matched_symbol)) ? MATCH_ERROR : MATCH_YES; if (gfc_get_sym_tree (buffer, NULL, matched_symbol, false)) return MATCH_ERROR; return MATCH_YES; } match gfc_match_symbol (gfc_symbol **matched_symbol, int host_assoc) { gfc_symtree *st; match m; m = gfc_match_sym_tree (&st, host_assoc); if (m == MATCH_YES) { if (st) *matched_symbol = st->n.sym; else *matched_symbol = NULL; } else *matched_symbol = NULL; return m; } /* Match an intrinsic operator. Returns an INTRINSIC enum. While matching, we always find INTRINSIC_PLUS before INTRINSIC_UPLUS. We work around this in matchexp.c. */ match gfc_match_intrinsic_op (gfc_intrinsic_op *result) { locus orig_loc = gfc_current_locus; char ch; gfc_gobble_whitespace (); ch = gfc_next_ascii_char (); switch (ch) { case '+': /* Matched "+". */ *result = INTRINSIC_PLUS; return MATCH_YES; case '-': /* Matched "-". */ *result = INTRINSIC_MINUS; return MATCH_YES; case '=': if (gfc_next_ascii_char () == '=') { /* Matched "==". */ *result = INTRINSIC_EQ; return MATCH_YES; } break; case '<': if (gfc_peek_ascii_char () == '=') { /* Matched "<=". */ gfc_next_ascii_char (); *result = INTRINSIC_LE; return MATCH_YES; } /* Matched "<". */ *result = INTRINSIC_LT; return MATCH_YES; case '>': if (gfc_peek_ascii_char () == '=') { /* Matched ">=". */ gfc_next_ascii_char (); *result = INTRINSIC_GE; return MATCH_YES; } /* Matched ">". */ *result = INTRINSIC_GT; return MATCH_YES; case '*': if (gfc_peek_ascii_char () == '*') { /* Matched "**". */ gfc_next_ascii_char (); *result = INTRINSIC_POWER; return MATCH_YES; } /* Matched "*". */ *result = INTRINSIC_TIMES; return MATCH_YES; case '/': ch = gfc_peek_ascii_char (); if (ch == '=') { /* Matched "/=". */ gfc_next_ascii_char (); *result = INTRINSIC_NE; return MATCH_YES; } else if (ch == '/') { /* Matched "//". */ gfc_next_ascii_char (); *result = INTRINSIC_CONCAT; return MATCH_YES; } /* Matched "/". */ *result = INTRINSIC_DIVIDE; return MATCH_YES; case '.': ch = gfc_next_ascii_char (); switch (ch) { case 'a': if (gfc_next_ascii_char () == 'n' && gfc_next_ascii_char () == 'd' && gfc_next_ascii_char () == '.') { /* Matched ".and.". */ *result = INTRINSIC_AND; return MATCH_YES; } break; case 'e': if (gfc_next_ascii_char () == 'q') { ch = gfc_next_ascii_char (); if (ch == '.') { /* Matched ".eq.". */ *result = INTRINSIC_EQ_OS; return MATCH_YES; } else if (ch == 'v') { if (gfc_next_ascii_char () == '.') { /* Matched ".eqv.". */ *result = INTRINSIC_EQV; return MATCH_YES; } } } break; case 'g': ch = gfc_next_ascii_char (); if (ch == 'e') { if (gfc_next_ascii_char () == '.') { /* Matched ".ge.". */ *result = INTRINSIC_GE_OS; return MATCH_YES; } } else if (ch == 't') { if (gfc_next_ascii_char () == '.') { /* Matched ".gt.". */ *result = INTRINSIC_GT_OS; return MATCH_YES; } } break; case 'l': ch = gfc_next_ascii_char (); if (ch == 'e') { if (gfc_next_ascii_char () == '.') { /* Matched ".le.". */ *result = INTRINSIC_LE_OS; return MATCH_YES; } } else if (ch == 't') { if (gfc_next_ascii_char () == '.') { /* Matched ".lt.". */ *result = INTRINSIC_LT_OS; return MATCH_YES; } } break; case 'n': ch = gfc_next_ascii_char (); if (ch == 'e') { ch = gfc_next_ascii_char (); if (ch == '.') { /* Matched ".ne.". */ *result = INTRINSIC_NE_OS; return MATCH_YES; } else if (ch == 'q') { if (gfc_next_ascii_char () == 'v' && gfc_next_ascii_char () == '.') { /* Matched ".neqv.". */ *result = INTRINSIC_NEQV; return MATCH_YES; } } } else if (ch == 'o') { if (gfc_next_ascii_char () == 't' && gfc_next_ascii_char () == '.') { /* Matched ".not.". */ *result = INTRINSIC_NOT; return MATCH_YES; } } break; case 'o': if (gfc_next_ascii_char () == 'r' && gfc_next_ascii_char () == '.') { /* Matched ".or.". */ *result = INTRINSIC_OR; return MATCH_YES; } break; case 'x': if (gfc_next_ascii_char () == 'o' && gfc_next_ascii_char () == 'r' && gfc_next_ascii_char () == '.') { if (!gfc_notify_std (GFC_STD_LEGACY, ".XOR. operator at %C")) return MATCH_ERROR; /* Matched ".xor." - equivalent to ".neqv.". */ *result = INTRINSIC_NEQV; return MATCH_YES; } break; default: break; } break; default: break; } gfc_current_locus = orig_loc; return MATCH_NO; } /* Match a loop control phrase: <LVALUE> = <EXPR>, <EXPR> [, <EXPR> ] If the final integer expression is not present, a constant unity expression is returned. We don't return MATCH_ERROR until after the equals sign is seen. */ match gfc_match_iterator (gfc_iterator *iter, int init_flag) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_expr *var, *e1, *e2, *e3; locus start; match m; e1 = e2 = e3 = NULL; /* Match the start of an iterator without affecting the symbol table. */ start = gfc_current_locus; m = gfc_match (" %n =", name); gfc_current_locus = start; if (m != MATCH_YES) return MATCH_NO; m = gfc_match_variable (&var, 0); if (m != MATCH_YES) return MATCH_NO; if (var->symtree->n.sym->attr.dimension) { gfc_error ("Loop variable at %C cannot be an array"); goto cleanup; } /* F2008, C617 & C565. */ if (var->symtree->n.sym->attr.codimension) { gfc_error ("Loop variable at %C cannot be a coarray"); goto cleanup; } if (var->ref != NULL) { gfc_error ("Loop variable at %C cannot be a sub-component"); goto cleanup; } gfc_match_char ('='); var->symtree->n.sym->attr.implied_index = 1; m = init_flag ? gfc_match_init_expr (&e1) : gfc_match_expr (&e1); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_char (',') != MATCH_YES) goto syntax; m = init_flag ? gfc_match_init_expr (&e2) : gfc_match_expr (&e2); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_char (',') != MATCH_YES) { e3 = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1); goto done; } m = init_flag ? gfc_match_init_expr (&e3) : gfc_match_expr (&e3); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) { gfc_error ("Expected a step value in iterator at %C"); goto cleanup; } done: iter->var = var; iter->start = e1; iter->end = e2; iter->step = e3; return MATCH_YES; syntax: gfc_error ("Syntax error in iterator at %C"); cleanup: gfc_free_expr (e1); gfc_free_expr (e2); gfc_free_expr (e3); return MATCH_ERROR; } /* Tries to match the next non-whitespace character on the input. This subroutine does not return MATCH_ERROR. */ match gfc_match_char (char c) { locus where; where = gfc_current_locus; gfc_gobble_whitespace (); if (gfc_next_ascii_char () == c) return MATCH_YES; gfc_current_locus = where; return MATCH_NO; } /* General purpose matching subroutine. The target string is a scanf-like format string in which spaces correspond to arbitrary whitespace (including no whitespace), characters correspond to themselves. The %-codes are: %% Literal percent sign %e Expression, pointer to a pointer is set %s Symbol, pointer to the symbol is set %n Name, character buffer is set to name %t Matches end of statement. %o Matches an intrinsic operator, returned as an INTRINSIC enum. %l Matches a statement label %v Matches a variable expression (an lvalue) % Matches a required space (in free form) and optional spaces. */ match gfc_match (const char *target, ...) { gfc_st_label **label; int matches, *ip; locus old_loc; va_list argp; char c, *np; match m, n; void **vp; const char *p; old_loc = gfc_current_locus; va_start (argp, target); m = MATCH_NO; matches = 0; p = target; loop: c = *p++; switch (c) { case ' ': gfc_gobble_whitespace (); goto loop; case '\0': m = MATCH_YES; break; case '%': c = *p++; switch (c) { case 'e': vp = va_arg (argp, void **); n = gfc_match_expr ((gfc_expr **) vp); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 'v': vp = va_arg (argp, void **); n = gfc_match_variable ((gfc_expr **) vp, 0); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 's': vp = va_arg (argp, void **); n = gfc_match_symbol ((gfc_symbol **) vp, 0); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 'n': np = va_arg (argp, char *); n = gfc_match_name (np); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 'l': label = va_arg (argp, gfc_st_label **); n = gfc_match_st_label (label); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 'o': ip = va_arg (argp, int *); n = gfc_match_intrinsic_op ((gfc_intrinsic_op *) ip); if (n != MATCH_YES) { m = n; goto not_yes; } matches++; goto loop; case 't': if (gfc_match_eos () != MATCH_YES) { m = MATCH_NO; goto not_yes; } goto loop; case ' ': if (gfc_match_space () == MATCH_YES) goto loop; m = MATCH_NO; goto not_yes; case '%': break; /* Fall through to character matcher. */ default: gfc_internal_error ("gfc_match(): Bad match code %c", c); } default: /* gfc_next_ascii_char converts characters to lower-case, so we shouldn't expect an upper case character here! */ gcc_assert (TOLOWER (c) == c); if (c == gfc_next_ascii_char ()) goto loop; break; } not_yes: va_end (argp); if (m != MATCH_YES) { /* Clean up after a failed match. */ gfc_current_locus = old_loc; va_start (argp, target); p = target; for (; matches > 0; matches--) { while (*p++ != '%'); switch (*p++) { case '%': matches++; break; /* Skip. */ /* Matches that don't have to be undone */ case 'o': case 'l': case 'n': case 's': (void) va_arg (argp, void **); break; case 'e': case 'v': vp = va_arg (argp, void **); gfc_free_expr ((struct gfc_expr *)*vp); *vp = NULL; break; } } va_end (argp); } return m; } /*********************** Statement level matching **********************/ /* Matches the start of a program unit, which is the program keyword followed by an obligatory symbol. */ match gfc_match_program (void) { gfc_symbol *sym; match m; m = gfc_match ("% %s%t", &sym); if (m == MATCH_NO) { gfc_error ("Invalid form of PROGRAM statement at %C"); m = MATCH_ERROR; } if (m == MATCH_ERROR) return m; if (!gfc_add_flavor (&sym->attr, FL_PROGRAM, sym->name, NULL)) return MATCH_ERROR; gfc_new_block = sym; return MATCH_YES; } /* Match a simple assignment statement. */ match gfc_match_assignment (void) { gfc_expr *lvalue, *rvalue; locus old_loc; match m; old_loc = gfc_current_locus; lvalue = NULL; m = gfc_match (" %v =", &lvalue); if (m != MATCH_YES) { gfc_current_locus = old_loc; gfc_free_expr (lvalue); return MATCH_NO; } rvalue = NULL; m = gfc_match (" %e%t", &rvalue); if (m != MATCH_YES) { gfc_current_locus = old_loc; gfc_free_expr (lvalue); gfc_free_expr (rvalue); return m; } gfc_set_sym_referenced (lvalue->symtree->n.sym); new_st.op = EXEC_ASSIGN; new_st.expr1 = lvalue; new_st.expr2 = rvalue; gfc_check_do_variable (lvalue->symtree); return MATCH_YES; } /* Match a pointer assignment statement. */ match gfc_match_pointer_assignment (void) { gfc_expr *lvalue, *rvalue; locus old_loc; match m; old_loc = gfc_current_locus; lvalue = rvalue = NULL; gfc_matching_ptr_assignment = 0; gfc_matching_procptr_assignment = 0; m = gfc_match (" %v =>", &lvalue); if (m != MATCH_YES) { m = MATCH_NO; goto cleanup; } if (lvalue->symtree->n.sym->attr.proc_pointer || gfc_is_proc_ptr_comp (lvalue)) gfc_matching_procptr_assignment = 1; else gfc_matching_ptr_assignment = 1; m = gfc_match (" %e%t", &rvalue); gfc_matching_ptr_assignment = 0; gfc_matching_procptr_assignment = 0; if (m != MATCH_YES) goto cleanup; new_st.op = EXEC_POINTER_ASSIGN; new_st.expr1 = lvalue; new_st.expr2 = rvalue; return MATCH_YES; cleanup: gfc_current_locus = old_loc; gfc_free_expr (lvalue); gfc_free_expr (rvalue); return m; } /* We try to match an easy arithmetic IF statement. This only happens when just after having encountered a simple IF statement. This code is really duplicate with parts of the gfc_match_if code, but this is *much* easier. */ static match match_arithmetic_if (void) { gfc_st_label *l1, *l2, *l3; gfc_expr *expr; match m; m = gfc_match (" ( %e ) %l , %l , %l%t", &expr, &l1, &l2, &l3); if (m != MATCH_YES) return m; if (!gfc_reference_st_label (l1, ST_LABEL_TARGET) || !gfc_reference_st_label (l2, ST_LABEL_TARGET) || !gfc_reference_st_label (l3, ST_LABEL_TARGET)) { gfc_free_expr (expr); return MATCH_ERROR; } if (!gfc_notify_std (GFC_STD_F95_OBS, "Arithmetic IF statement at %C")) return MATCH_ERROR; new_st.op = EXEC_ARITHMETIC_IF; new_st.expr1 = expr; new_st.label1 = l1; new_st.label2 = l2; new_st.label3 = l3; return MATCH_YES; } /* The IF statement is a bit of a pain. First of all, there are three forms of it, the simple IF, the IF that starts a block and the arithmetic IF. There is a problem with the simple IF and that is the fact that we only have a single level of undo information on symbols. What this means is for a simple IF, we must re-match the whole IF statement multiple times in order to guarantee that the symbol table ends up in the proper state. */ static match match_simple_forall (void); static match match_simple_where (void); match gfc_match_if (gfc_statement *if_type) { gfc_expr *expr; gfc_st_label *l1, *l2, *l3; locus old_loc, old_loc2; gfc_code *p; match m, n; n = gfc_match_label (); if (n == MATCH_ERROR) return n; old_loc = gfc_current_locus; m = gfc_match (" if ( %e", &expr); if (m != MATCH_YES) return m; old_loc2 = gfc_current_locus; gfc_current_locus = old_loc; if (gfc_match_parens () == MATCH_ERROR) return MATCH_ERROR; gfc_current_locus = old_loc2; if (gfc_match_char (')') != MATCH_YES) { gfc_error ("Syntax error in IF-expression at %C"); gfc_free_expr (expr); return MATCH_ERROR; } m = gfc_match (" %l , %l , %l%t", &l1, &l2, &l3); if (m == MATCH_YES) { if (n == MATCH_YES) { gfc_error ("Block label not appropriate for arithmetic IF " "statement at %C"); gfc_free_expr (expr); return MATCH_ERROR; } if (!gfc_reference_st_label (l1, ST_LABEL_TARGET) || !gfc_reference_st_label (l2, ST_LABEL_TARGET) || !gfc_reference_st_label (l3, ST_LABEL_TARGET)) { gfc_free_expr (expr); return MATCH_ERROR; } if (!gfc_notify_std (GFC_STD_F95_OBS, "Arithmetic IF statement at %C")) return MATCH_ERROR; new_st.op = EXEC_ARITHMETIC_IF; new_st.expr1 = expr; new_st.label1 = l1; new_st.label2 = l2; new_st.label3 = l3; *if_type = ST_ARITHMETIC_IF; return MATCH_YES; } if (gfc_match (" then%t") == MATCH_YES) { new_st.op = EXEC_IF; new_st.expr1 = expr; *if_type = ST_IF_BLOCK; return MATCH_YES; } if (n == MATCH_YES) { gfc_error ("Block label is not appropriate for IF statement at %C"); gfc_free_expr (expr); return MATCH_ERROR; } /* At this point the only thing left is a simple IF statement. At this point, n has to be MATCH_NO, so we don't have to worry about re-matching a block label. From what we've got so far, try matching an assignment. */ *if_type = ST_SIMPLE_IF; m = gfc_match_assignment (); if (m == MATCH_YES) goto got_match; gfc_free_expr (expr); gfc_undo_symbols (); gfc_current_locus = old_loc; /* m can be MATCH_NO or MATCH_ERROR, here. For MATCH_ERROR, a mangled assignment was found. For MATCH_NO, continue to call the various matchers. */ if (m == MATCH_ERROR) return MATCH_ERROR; gfc_match (" if ( %e ) ", &expr); /* Guaranteed to match. */ m = gfc_match_pointer_assignment (); if (m == MATCH_YES) goto got_match; gfc_free_expr (expr); gfc_undo_symbols (); gfc_current_locus = old_loc; gfc_match (" if ( %e ) ", &expr); /* Guaranteed to match. */ /* Look at the next keyword to see which matcher to call. Matching the keyword doesn't affect the symbol table, so we don't have to restore between tries. */ #define match(string, subr, statement) \ if (gfc_match (string) == MATCH_YES) { m = subr(); goto got_match; } gfc_clear_error (); match ("allocate", gfc_match_allocate, ST_ALLOCATE) match ("assign", gfc_match_assign, ST_LABEL_ASSIGNMENT) match ("backspace", gfc_match_backspace, ST_BACKSPACE) match ("call", gfc_match_call, ST_CALL) match ("close", gfc_match_close, ST_CLOSE) match ("continue", gfc_match_continue, ST_CONTINUE) match ("cycle", gfc_match_cycle, ST_CYCLE) match ("deallocate", gfc_match_deallocate, ST_DEALLOCATE) match ("end file", gfc_match_endfile, ST_END_FILE) match ("error stop", gfc_match_error_stop, ST_ERROR_STOP) match ("event post", gfc_match_event_post, ST_EVENT_POST) match ("event wait", gfc_match_event_wait, ST_EVENT_WAIT) match ("exit", gfc_match_exit, ST_EXIT) match ("fail image", gfc_match_fail_image, ST_FAIL_IMAGE) match ("flush", gfc_match_flush, ST_FLUSH) match ("forall", match_simple_forall, ST_FORALL) match ("go to", gfc_match_goto, ST_GOTO) match ("if", match_arithmetic_if, ST_ARITHMETIC_IF) match ("inquire", gfc_match_inquire, ST_INQUIRE) match ("lock", gfc_match_lock, ST_LOCK) match ("nullify", gfc_match_nullify, ST_NULLIFY) match ("open", gfc_match_open, ST_OPEN) match ("pause", gfc_match_pause, ST_NONE) match ("print", gfc_match_print, ST_WRITE) match ("read", gfc_match_read, ST_READ) match ("return", gfc_match_return, ST_RETURN) match ("rewind", gfc_match_rewind, ST_REWIND) match ("stop", gfc_match_stop, ST_STOP) match ("wait", gfc_match_wait, ST_WAIT) match ("sync all", gfc_match_sync_all, ST_SYNC_CALL); match ("sync images", gfc_match_sync_images, ST_SYNC_IMAGES); match ("sync memory", gfc_match_sync_memory, ST_SYNC_MEMORY); match ("unlock", gfc_match_unlock, ST_UNLOCK) match ("where", match_simple_where, ST_WHERE) match ("write", gfc_match_write, ST_WRITE) if (flag_dec) match ("type", gfc_match_print, ST_WRITE) /* The gfc_match_assignment() above may have returned a MATCH_NO where the assignment was to a named constant. Check that special case here. */ m = gfc_match_assignment (); if (m == MATCH_NO) { gfc_error ("Cannot assign to a named constant at %C"); gfc_free_expr (expr); gfc_undo_symbols (); gfc_current_locus = old_loc; return MATCH_ERROR; } /* All else has failed, so give up. See if any of the matchers has stored an error message of some sort. */ if (!gfc_error_check ()) gfc_error ("Unclassifiable statement in IF-clause at %C"); gfc_free_expr (expr); return MATCH_ERROR; got_match: if (m == MATCH_NO) gfc_error ("Syntax error in IF-clause at %C"); if (m != MATCH_YES) { gfc_free_expr (expr); return MATCH_ERROR; } /* At this point, we've matched the single IF and the action clause is in new_st. Rearrange things so that the IF statement appears in new_st. */ p = gfc_get_code (EXEC_IF); p->next = XCNEW (gfc_code); *p->next = new_st; p->next->loc = gfc_current_locus; p->expr1 = expr; gfc_clear_new_st (); new_st.op = EXEC_IF; new_st.block = p; return MATCH_YES; } #undef match /* Match an ELSE statement. */ match gfc_match_else (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; if (gfc_match_eos () == MATCH_YES) return MATCH_YES; if (gfc_match_name (name) != MATCH_YES || gfc_current_block () == NULL || gfc_match_eos () != MATCH_YES) { gfc_error ("Unexpected junk after ELSE statement at %C"); return MATCH_ERROR; } if (strcmp (name, gfc_current_block ()->name) != 0) { gfc_error ("Label %qs at %C doesn't match IF label %qs", name, gfc_current_block ()->name); return MATCH_ERROR; } return MATCH_YES; } /* Match an ELSE IF statement. */ match gfc_match_elseif (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_expr *expr; match m; m = gfc_match (" ( %e ) then", &expr); if (m != MATCH_YES) return m; if (gfc_match_eos () == MATCH_YES) goto done; if (gfc_match_name (name) != MATCH_YES || gfc_current_block () == NULL || gfc_match_eos () != MATCH_YES) { gfc_error ("Unexpected junk after ELSE IF statement at %C"); goto cleanup; } if (strcmp (name, gfc_current_block ()->name) != 0) { gfc_error ("Label %qs at %C doesn't match IF label %qs", name, gfc_current_block ()->name); goto cleanup; } done: new_st.op = EXEC_IF; new_st.expr1 = expr; return MATCH_YES; cleanup: gfc_free_expr (expr); return MATCH_ERROR; } /* Free a gfc_iterator structure. */ void gfc_free_iterator (gfc_iterator *iter, int flag) { if (iter == NULL) return; gfc_free_expr (iter->var); gfc_free_expr (iter->start); gfc_free_expr (iter->end); gfc_free_expr (iter->step); if (flag) free (iter); } /* Match a CRITICAL statement. */ match gfc_match_critical (void) { gfc_st_label *label = NULL; if (gfc_match_label () == MATCH_ERROR) return MATCH_ERROR; if (gfc_match (" critical") != MATCH_YES) return MATCH_NO; if (gfc_match_st_label (&label) == MATCH_ERROR) return MATCH_ERROR; if (gfc_match_eos () != MATCH_YES) { gfc_syntax_error (ST_CRITICAL); return MATCH_ERROR; } if (gfc_pure (NULL)) { gfc_error ("Image control statement CRITICAL at %C in PURE procedure"); return MATCH_ERROR; } if (gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement CRITICAL at %C in DO CONCURRENT " "block"); return MATCH_ERROR; } gfc_unset_implicit_pure (NULL); if (!gfc_notify_std (GFC_STD_F2008, "CRITICAL statement at %C")) return MATCH_ERROR; if (flag_coarray == GFC_FCOARRAY_NONE) { gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to " "enable"); return MATCH_ERROR; } if (gfc_find_state (COMP_CRITICAL)) { gfc_error ("Nested CRITICAL block at %C"); return MATCH_ERROR; } new_st.op = EXEC_CRITICAL; if (label != NULL && !gfc_reference_st_label (label, ST_LABEL_TARGET)) return MATCH_ERROR; return MATCH_YES; } /* Match a BLOCK statement. */ match gfc_match_block (void) { match m; if (gfc_match_label () == MATCH_ERROR) return MATCH_ERROR; if (gfc_match (" block") != MATCH_YES) return MATCH_NO; /* For this to be a correct BLOCK statement, the line must end now. */ m = gfc_match_eos (); if (m == MATCH_ERROR) return MATCH_ERROR; if (m == MATCH_NO) return MATCH_NO; return MATCH_YES; } /* Match an ASSOCIATE statement. */ match gfc_match_associate (void) { if (gfc_match_label () == MATCH_ERROR) return MATCH_ERROR; if (gfc_match (" associate") != MATCH_YES) return MATCH_NO; /* Match the association list. */ if (gfc_match_char ('(') != MATCH_YES) { gfc_error ("Expected association list at %C"); return MATCH_ERROR; } new_st.ext.block.assoc = NULL; while (true) { gfc_association_list* newAssoc = gfc_get_association_list (); gfc_association_list* a; /* Match the next association. */ if (gfc_match (" %n => %e", newAssoc->name, &newAssoc->target) != MATCH_YES) { /* Have another go, allowing for procedure pointer selectors. */ gfc_matching_procptr_assignment = 1; if (gfc_match (" %n => %e", newAssoc->name, &newAssoc->target) != MATCH_YES) { gfc_error ("Expected association at %C"); goto assocListError; } gfc_matching_procptr_assignment = 0; } newAssoc->where = gfc_current_locus; /* Check that the current name is not yet in the list. */ for (a = new_st.ext.block.assoc; a; a = a->next) if (!strcmp (a->name, newAssoc->name)) { gfc_error ("Duplicate name %qs in association at %C", newAssoc->name); goto assocListError; } /* The target expression must not be coindexed. */ if (gfc_is_coindexed (newAssoc->target)) { gfc_error ("Association target at %C must not be coindexed"); goto assocListError; } /* The `variable' field is left blank for now; because the target is not yet resolved, we can't use gfc_has_vector_subscript to determine it for now. This is set during resolution. */ /* Put it into the list. */ newAssoc->next = new_st.ext.block.assoc; new_st.ext.block.assoc = newAssoc; /* Try next one or end if closing parenthesis is found. */ gfc_gobble_whitespace (); if (gfc_peek_char () == ')') break; if (gfc_match_char (',') != MATCH_YES) { gfc_error ("Expected %<)%> or %<,%> at %C"); return MATCH_ERROR; } continue; assocListError: free (newAssoc); goto error; } if (gfc_match_char (')') != MATCH_YES) { /* This should never happen as we peek above. */ gcc_unreachable (); } if (gfc_match_eos () != MATCH_YES) { gfc_error ("Junk after ASSOCIATE statement at %C"); goto error; } return MATCH_YES; error: gfc_free_association_list (new_st.ext.block.assoc); return MATCH_ERROR; } /* Match a Fortran 2003 derived-type-spec (F03:R455), which is just the name of an accessible derived type. */ static match match_derived_type_spec (gfc_typespec *ts) { char name[GFC_MAX_SYMBOL_LEN + 1]; locus old_locus; gfc_symbol *derived; old_locus = gfc_current_locus; if (gfc_match ("%n", name) != MATCH_YES) { gfc_current_locus = old_locus; return MATCH_NO; } gfc_find_symbol (name, NULL, 1, &derived); if (derived && derived->attr.flavor == FL_PROCEDURE && derived->attr.generic) derived = gfc_find_dt_in_generic (derived); if (derived && derived->attr.flavor == FL_DERIVED) { ts->type = BT_DERIVED; ts->u.derived = derived; return MATCH_YES; } gfc_current_locus = old_locus; return MATCH_NO; } /* Match a Fortran 2003 type-spec (F03:R401). This is similar to gfc_match_decl_type_spec() from decl.c, with the following exceptions: It only includes the intrinsic types from the Fortran 2003 standard (thus, neither BYTE nor forms like REAL*4 are allowed). Additionally, the implicit_flag is not needed, so it was removed. Derived types are identified by their name alone. */ match gfc_match_type_spec (gfc_typespec *ts) { match m; locus old_locus; char c, name[GFC_MAX_SYMBOL_LEN + 1]; gfc_clear_ts (ts); gfc_gobble_whitespace (); old_locus = gfc_current_locus; /* If c isn't [a-z], then return immediately. */ c = gfc_peek_ascii_char (); if (!ISALPHA(c)) return MATCH_NO; if (match_derived_type_spec (ts) == MATCH_YES) { /* Enforce F03:C401. */ if (ts->u.derived->attr.abstract) { gfc_error ("Derived type %qs at %L may not be ABSTRACT", ts->u.derived->name, &old_locus); return MATCH_ERROR; } return MATCH_YES; } if (gfc_match ("integer") == MATCH_YES) { ts->type = BT_INTEGER; ts->kind = gfc_default_integer_kind; goto kind_selector; } if (gfc_match ("double precision") == MATCH_YES) { ts->type = BT_REAL; ts->kind = gfc_default_double_kind; return MATCH_YES; } if (gfc_match ("complex") == MATCH_YES) { ts->type = BT_COMPLEX; ts->kind = gfc_default_complex_kind; goto kind_selector; } if (gfc_match ("character") == MATCH_YES) { ts->type = BT_CHARACTER; m = gfc_match_char_spec (ts); if (ts->u.cl && ts->u.cl->length) gfc_resolve_expr (ts->u.cl->length); if (m == MATCH_NO) m = MATCH_YES; return m; } /* REAL is a real pain because it can be a type, intrinsic subprogram, or list item in a type-list of an OpenMP reduction clause. Need to differentiate REAL([KIND]=scalar-int-initialization-expr) from REAL(A,[KIND]) and REAL(KIND,A). Logically, when this code was written the use of LOGICAL as a type-spec or intrinsic subprogram was overlooked. */ m = gfc_match (" %n", name); if (m == MATCH_YES && (strcmp (name, "real") == 0 || strcmp (name, "logical") == 0)) { char c; gfc_expr *e; locus where; if (*name == 'r') { ts->type = BT_REAL; ts->kind = gfc_default_real_kind; } else { ts->type = BT_LOGICAL; ts->kind = gfc_default_logical_kind; } gfc_gobble_whitespace (); /* Prevent REAL*4, etc. */ c = gfc_peek_ascii_char (); if (c == '*') { gfc_error ("Invalid type-spec at %C"); return MATCH_ERROR; } /* Found leading colon in REAL::, a trailing ')' in for example TYPE IS (REAL), or REAL, for an OpenMP list-item. */ if (c == ':' || c == ')' || (flag_openmp && c == ',')) return MATCH_YES; /* Found something other than the opening '(' in REAL(... */ if (c != '(') return MATCH_NO; else gfc_next_char (); /* Burn the '('. */ /* Look for the optional KIND=. */ where = gfc_current_locus; m = gfc_match ("%n", name); if (m == MATCH_YES) { gfc_gobble_whitespace (); c = gfc_next_char (); if (c == '=') { if (strcmp(name, "a") == 0 || strcmp(name, "l") == 0) return MATCH_NO; else if (strcmp(name, "kind") == 0) goto found; else return MATCH_ERROR; } else gfc_current_locus = where; } else gfc_current_locus = where; found: m = gfc_match_init_expr (&e); if (m == MATCH_NO || m == MATCH_ERROR) return MATCH_NO; /* If a comma appears, it is an intrinsic subprogram. */ gfc_gobble_whitespace (); c = gfc_peek_ascii_char (); if (c == ',') { gfc_free_expr (e); return MATCH_NO; } /* If ')' appears, we have REAL(initialization-expr), here check for a scalar integer initialization-expr and valid kind parameter. */ if (c == ')') { if (e->ts.type != BT_INTEGER || e->rank > 0) { gfc_free_expr (e); return MATCH_NO; } gfc_next_char (); /* Burn the ')'. */ ts->kind = (int) mpz_get_si (e->value.integer); if (gfc_validate_kind (ts->type, ts->kind , true) == -1) { gfc_error ("Invalid type-spec at %C"); return MATCH_ERROR; } gfc_free_expr (e); return MATCH_YES; } } /* If a type is not matched, simply return MATCH_NO. */ gfc_current_locus = old_locus; return MATCH_NO; kind_selector: gfc_gobble_whitespace (); /* This prevents INTEGER*4, etc. */ if (gfc_peek_ascii_char () == '*') { gfc_error ("Invalid type-spec at %C"); return MATCH_ERROR; } m = gfc_match_kind_spec (ts, false); /* No kind specifier found. */ if (m == MATCH_NO) m = MATCH_YES; return m; } /******************** FORALL subroutines ********************/ /* Free a list of FORALL iterators. */ void gfc_free_forall_iterator (gfc_forall_iterator *iter) { gfc_forall_iterator *next; while (iter) { next = iter->next; gfc_free_expr (iter->var); gfc_free_expr (iter->start); gfc_free_expr (iter->end); gfc_free_expr (iter->stride); free (iter); iter = next; } } /* Match an iterator as part of a FORALL statement. The format is: <var> = <start>:<end>[:<stride>] On MATCH_NO, the caller tests for the possibility that there is a scalar mask expression. */ static match match_forall_iterator (gfc_forall_iterator **result) { gfc_forall_iterator *iter; locus where; match m; where = gfc_current_locus; iter = XCNEW (gfc_forall_iterator); m = gfc_match_expr (&iter->var); if (m != MATCH_YES) goto cleanup; if (gfc_match_char ('=') != MATCH_YES || iter->var->expr_type != EXPR_VARIABLE) { m = MATCH_NO; goto cleanup; } m = gfc_match_expr (&iter->start); if (m != MATCH_YES) goto cleanup; if (gfc_match_char (':') != MATCH_YES) goto syntax; m = gfc_match_expr (&iter->end); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_char (':') == MATCH_NO) iter->stride = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1); else { m = gfc_match_expr (&iter->stride); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; } /* Mark the iteration variable's symbol as used as a FORALL index. */ iter->var->symtree->n.sym->forall_index = true; *result = iter; return MATCH_YES; syntax: gfc_error ("Syntax error in FORALL iterator at %C"); m = MATCH_ERROR; cleanup: gfc_current_locus = where; gfc_free_forall_iterator (iter); return m; } /* Match the header of a FORALL statement. */ static match match_forall_header (gfc_forall_iterator **phead, gfc_expr **mask) { gfc_forall_iterator *head, *tail, *new_iter; gfc_expr *msk; match m; gfc_gobble_whitespace (); head = tail = NULL; msk = NULL; if (gfc_match_char ('(') != MATCH_YES) return MATCH_NO; m = match_forall_iterator (&new_iter); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; head = tail = new_iter; for (;;) { if (gfc_match_char (',') != MATCH_YES) break; m = match_forall_iterator (&new_iter); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { tail->next = new_iter; tail = new_iter; continue; } /* Have to have a mask expression. */ m = gfc_match_expr (&msk); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; break; } if (gfc_match_char (')') == MATCH_NO) goto syntax; *phead = head; *mask = msk; return MATCH_YES; syntax: gfc_syntax_error (ST_FORALL); cleanup: gfc_free_expr (msk); gfc_free_forall_iterator (head); return MATCH_ERROR; } /* Match the rest of a simple FORALL statement that follows an IF statement. */ static match match_simple_forall (void) { gfc_forall_iterator *head; gfc_expr *mask; gfc_code *c; match m; mask = NULL; head = NULL; c = NULL; m = match_forall_header (&head, &mask); if (m == MATCH_NO) goto syntax; if (m != MATCH_YES) goto cleanup; m = gfc_match_assignment (); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) { m = gfc_match_pointer_assignment (); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; } c = XCNEW (gfc_code); *c = new_st; c->loc = gfc_current_locus; if (gfc_match_eos () != MATCH_YES) goto syntax; gfc_clear_new_st (); new_st.op = EXEC_FORALL; new_st.expr1 = mask; new_st.ext.forall_iterator = head; new_st.block = gfc_get_code (EXEC_FORALL); new_st.block->next = c; return MATCH_YES; syntax: gfc_syntax_error (ST_FORALL); cleanup: gfc_free_forall_iterator (head); gfc_free_expr (mask); return MATCH_ERROR; } /* Match a FORALL statement. */ match gfc_match_forall (gfc_statement *st) { gfc_forall_iterator *head; gfc_expr *mask; gfc_code *c; match m0, m; head = NULL; mask = NULL; c = NULL; m0 = gfc_match_label (); if (m0 == MATCH_ERROR) return MATCH_ERROR; m = gfc_match (" forall"); if (m != MATCH_YES) return m; m = match_forall_header (&head, &mask); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; if (gfc_match_eos () == MATCH_YES) { *st = ST_FORALL_BLOCK; new_st.op = EXEC_FORALL; new_st.expr1 = mask; new_st.ext.forall_iterator = head; return MATCH_YES; } m = gfc_match_assignment (); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) { m = gfc_match_pointer_assignment (); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; } c = XCNEW (gfc_code); *c = new_st; c->loc = gfc_current_locus; gfc_clear_new_st (); new_st.op = EXEC_FORALL; new_st.expr1 = mask; new_st.ext.forall_iterator = head; new_st.block = gfc_get_code (EXEC_FORALL); new_st.block->next = c; *st = ST_FORALL; return MATCH_YES; syntax: gfc_syntax_error (ST_FORALL); cleanup: gfc_free_forall_iterator (head); gfc_free_expr (mask); gfc_free_statements (c); return MATCH_NO; } /* Match a DO statement. */ match gfc_match_do (void) { gfc_iterator iter, *ip; locus old_loc; gfc_st_label *label; match m; old_loc = gfc_current_locus; label = NULL; iter.var = iter.start = iter.end = iter.step = NULL; m = gfc_match_label (); if (m == MATCH_ERROR) return m; if (gfc_match (" do") != MATCH_YES) return MATCH_NO; m = gfc_match_st_label (&label); if (m == MATCH_ERROR) goto cleanup; /* Match an infinite DO, make it like a DO WHILE(.TRUE.). */ if (gfc_match_eos () == MATCH_YES) { iter.end = gfc_get_logical_expr (gfc_default_logical_kind, NULL, true); new_st.op = EXEC_DO_WHILE; goto done; } /* Match an optional comma, if no comma is found, a space is obligatory. */ if (gfc_match_char (',') != MATCH_YES && gfc_match ("% ") != MATCH_YES) return MATCH_NO; /* Check for balanced parens. */ if (gfc_match_parens () == MATCH_ERROR) return MATCH_ERROR; if (gfc_match (" concurrent") == MATCH_YES) { gfc_forall_iterator *head; gfc_expr *mask; if (!gfc_notify_std (GFC_STD_F2008, "DO CONCURRENT construct at %C")) return MATCH_ERROR; mask = NULL; head = NULL; m = match_forall_header (&head, &mask); if (m == MATCH_NO) return m; if (m == MATCH_ERROR) goto concurr_cleanup; if (gfc_match_eos () != MATCH_YES) goto concurr_cleanup; if (label != NULL && !gfc_reference_st_label (label, ST_LABEL_DO_TARGET)) goto concurr_cleanup; new_st.label1 = label; new_st.op = EXEC_DO_CONCURRENT; new_st.expr1 = mask; new_st.ext.forall_iterator = head; return MATCH_YES; concurr_cleanup: gfc_syntax_error (ST_DO); gfc_free_expr (mask); gfc_free_forall_iterator (head); return MATCH_ERROR; } /* See if we have a DO WHILE. */ if (gfc_match (" while ( %e )%t", &iter.end) == MATCH_YES) { new_st.op = EXEC_DO_WHILE; goto done; } /* The abortive DO WHILE may have done something to the symbol table, so we start over. */ gfc_undo_symbols (); gfc_current_locus = old_loc; gfc_match_label (); /* This won't error. */ gfc_match (" do "); /* This will work. */ gfc_match_st_label (&label); /* Can't error out. */ gfc_match_char (','); /* Optional comma. */ m = gfc_match_iterator (&iter, 0); if (m == MATCH_NO) return MATCH_NO; if (m == MATCH_ERROR) goto cleanup; iter.var->symtree->n.sym->attr.implied_index = 0; gfc_check_do_variable (iter.var->symtree); if (gfc_match_eos () != MATCH_YES) { gfc_syntax_error (ST_DO); goto cleanup; } new_st.op = EXEC_DO; done: if (label != NULL && !gfc_reference_st_label (label, ST_LABEL_DO_TARGET)) goto cleanup; new_st.label1 = label; if (new_st.op == EXEC_DO_WHILE) new_st.expr1 = iter.end; else { new_st.ext.iterator = ip = gfc_get_iterator (); *ip = iter; } return MATCH_YES; cleanup: gfc_free_iterator (&iter, 0); return MATCH_ERROR; } /* Match an EXIT or CYCLE statement. */ static match match_exit_cycle (gfc_statement st, gfc_exec_op op) { gfc_state_data *p, *o; gfc_symbol *sym; match m; int cnt; if (gfc_match_eos () == MATCH_YES) sym = NULL; else { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_symtree* stree; m = gfc_match ("% %n%t", name); if (m == MATCH_ERROR) return MATCH_ERROR; if (m == MATCH_NO) { gfc_syntax_error (st); return MATCH_ERROR; } /* Find the corresponding symbol. If there's a BLOCK statement between here and the label, it is not in gfc_current_ns but a parent namespace! */ stree = gfc_find_symtree_in_proc (name, gfc_current_ns); if (!stree) { gfc_error ("Name %qs in %s statement at %C is unknown", name, gfc_ascii_statement (st)); return MATCH_ERROR; } sym = stree->n.sym; if (sym->attr.flavor != FL_LABEL) { gfc_error ("Name %qs in %s statement at %C is not a construct name", name, gfc_ascii_statement (st)); return MATCH_ERROR; } } /* Find the loop specified by the label (or lack of a label). */ for (o = NULL, p = gfc_state_stack; p; p = p->previous) if (o == NULL && p->state == COMP_OMP_STRUCTURED_BLOCK) o = p; else if (p->state == COMP_CRITICAL) { gfc_error("%s statement at %C leaves CRITICAL construct", gfc_ascii_statement (st)); return MATCH_ERROR; } else if (p->state == COMP_DO_CONCURRENT && (op == EXEC_EXIT || (sym && sym != p->sym))) { /* F2008, C821 & C845. */ gfc_error("%s statement at %C leaves DO CONCURRENT construct", gfc_ascii_statement (st)); return MATCH_ERROR; } else if ((sym && sym == p->sym) || (!sym && (p->state == COMP_DO || p->state == COMP_DO_CONCURRENT))) break; if (p == NULL) { if (sym == NULL) gfc_error ("%s statement at %C is not within a construct", gfc_ascii_statement (st)); else gfc_error ("%s statement at %C is not within construct %qs", gfc_ascii_statement (st), sym->name); return MATCH_ERROR; } /* Special checks for EXIT from non-loop constructs. */ switch (p->state) { case COMP_DO: case COMP_DO_CONCURRENT: break; case COMP_CRITICAL: /* This is already handled above. */ gcc_unreachable (); case COMP_ASSOCIATE: case COMP_BLOCK: case COMP_IF: case COMP_SELECT: case COMP_SELECT_TYPE: gcc_assert (sym); if (op == EXEC_CYCLE) { gfc_error ("CYCLE statement at %C is not applicable to non-loop" " construct %qs", sym->name); return MATCH_ERROR; } gcc_assert (op == EXEC_EXIT); if (!gfc_notify_std (GFC_STD_F2008, "EXIT statement with no" " do-construct-name at %C")) return MATCH_ERROR; break; default: gfc_error ("%s statement at %C is not applicable to construct %qs", gfc_ascii_statement (st), sym->name); return MATCH_ERROR; } if (o != NULL) { gfc_error (is_oacc (p) ? G_("%s statement at %C leaving OpenACC structured block") : G_("%s statement at %C leaving OpenMP structured block"), gfc_ascii_statement (st)); return MATCH_ERROR; } for (o = p, cnt = 0; o->state == COMP_DO && o->previous != NULL; cnt++) o = o->previous; if (cnt > 0 && o != NULL && o->state == COMP_OMP_STRUCTURED_BLOCK && (o->head->op == EXEC_OACC_LOOP || o->head->op == EXEC_OACC_PARALLEL_LOOP)) { int collapse = 1; gcc_assert (o->head->next != NULL && (o->head->next->op == EXEC_DO || o->head->next->op == EXEC_DO_WHILE) && o->previous != NULL && o->previous->tail->op == o->head->op); if (o->previous->tail->ext.omp_clauses != NULL && o->previous->tail->ext.omp_clauses->collapse > 1) collapse = o->previous->tail->ext.omp_clauses->collapse; if (st == ST_EXIT && cnt <= collapse) { gfc_error ("EXIT statement at %C terminating !$ACC LOOP loop"); return MATCH_ERROR; } if (st == ST_CYCLE && cnt < collapse) { gfc_error ("CYCLE statement at %C to non-innermost collapsed" " !$ACC LOOP loop"); return MATCH_ERROR; } } if (cnt > 0 && o != NULL && (o->state == COMP_OMP_STRUCTURED_BLOCK) && (o->head->op == EXEC_OMP_DO || o->head->op == EXEC_OMP_PARALLEL_DO || o->head->op == EXEC_OMP_SIMD || o->head->op == EXEC_OMP_DO_SIMD || o->head->op == EXEC_OMP_PARALLEL_DO_SIMD)) { int count = 1; gcc_assert (o->head->next != NULL && (o->head->next->op == EXEC_DO || o->head->next->op == EXEC_DO_WHILE) && o->previous != NULL && o->previous->tail->op == o->head->op); if (o->previous->tail->ext.omp_clauses != NULL) { if (o->previous->tail->ext.omp_clauses->collapse > 1) count = o->previous->tail->ext.omp_clauses->collapse; if (o->previous->tail->ext.omp_clauses->orderedc) count = o->previous->tail->ext.omp_clauses->orderedc; } if (st == ST_EXIT && cnt <= count) { gfc_error ("EXIT statement at %C terminating !$OMP DO loop"); return MATCH_ERROR; } if (st == ST_CYCLE && cnt < count) { gfc_error ("CYCLE statement at %C to non-innermost collapsed" " !$OMP DO loop"); return MATCH_ERROR; } } /* Save the first statement in the construct - needed by the backend. */ new_st.ext.which_construct = p->construct; new_st.op = op; return MATCH_YES; } /* Match the EXIT statement. */ match gfc_match_exit (void) { return match_exit_cycle (ST_EXIT, EXEC_EXIT); } /* Match the CYCLE statement. */ match gfc_match_cycle (void) { return match_exit_cycle (ST_CYCLE, EXEC_CYCLE); } /* Match a stop-code after an (ERROR) STOP or PAUSE statement. The requirements for a stop-code differ in the standards. Fortran 95 has R840 stop-stmt is STOP [ stop-code ] R841 stop-code is scalar-char-constant or digit [ digit [ digit [ digit [ digit ] ] ] ] Fortran 2003 matches Fortran 95 except R840 and R841 are now R849 and R850. Fortran 2008 has R855 stop-stmt is STOP [ stop-code ] R856 allstop-stmt is ALL STOP [ stop-code ] R857 stop-code is scalar-default-char-constant-expr or scalar-int-constant-expr For free-form source code, all standards contain a statement of the form: A blank shall be used to separate names, constants, or labels from adjacent keywords, names, constants, or labels. A stop-code is not a name, constant, or label. So, under Fortran 95 and 2003, STOP123 is valid, but it is invalid Fortran 2008. */ static match gfc_match_stopcode (gfc_statement st) { gfc_expr *e = NULL; match m; bool f95, f03; /* Set f95 for -std=f95. */ f95 = gfc_option.allow_std == (GFC_STD_F95_OBS | GFC_STD_F95 | GFC_STD_F77 | GFC_STD_F2008_OBS); /* Set f03 for -std=f2003. */ f03 = gfc_option.allow_std == (GFC_STD_F95_OBS | GFC_STD_F95 | GFC_STD_F77 | GFC_STD_F2008_OBS | GFC_STD_F2003); /* Look for a blank between STOP and the stop-code for F2008 or later. */ if (gfc_current_form != FORM_FIXED && !(f95 || f03)) { char c = gfc_peek_ascii_char (); /* Look for end-of-statement. There is no stop-code. */ if (c == '\n' || c == '!' || c == ';') goto done; if (c != ' ') { gfc_error ("Blank required in %s statement near %C", gfc_ascii_statement (st)); return MATCH_ERROR; } } if (gfc_match_eos () != MATCH_YES) { int stopcode; locus old_locus; /* First look for the F95 or F2003 digit [...] construct. */ old_locus = gfc_current_locus; m = gfc_match_small_int (&stopcode); if (m == MATCH_YES && (f95 || f03)) { if (stopcode < 0) { gfc_error ("STOP code at %C cannot be negative"); return MATCH_ERROR; } if (stopcode > 99999) { gfc_error ("STOP code at %C contains too many digits"); return MATCH_ERROR; } } /* Reset the locus and now load gfc_expr. */ gfc_current_locus = old_locus; m = gfc_match_expr (&e); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; if (gfc_match_eos () != MATCH_YES) goto syntax; } if (gfc_pure (NULL)) { if (st == ST_ERROR_STOP) { if (!gfc_notify_std (GFC_STD_F2015, "%s statement at %C in PURE " "procedure", gfc_ascii_statement (st))) goto cleanup; } else { gfc_error ("%s statement not allowed in PURE procedure at %C", gfc_ascii_statement (st)); goto cleanup; } } gfc_unset_implicit_pure (NULL); if (st == ST_STOP && gfc_find_state (COMP_CRITICAL)) { gfc_error ("Image control statement STOP at %C in CRITICAL block"); goto cleanup; } if (st == ST_STOP && gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement STOP at %C in DO CONCURRENT block"); goto cleanup; } if (e != NULL) { gfc_simplify_expr (e, 0); /* Test for F95 and F2003 style STOP stop-code. */ if (e->expr_type != EXPR_CONSTANT && (f95 || f03)) { gfc_error ("STOP code at %L must be a scalar CHARACTER constant or " "digit[digit[digit[digit[digit]]]]", &e->where); goto cleanup; } /* Use the machinery for an initialization expression to reduce the stop-code to a constant. */ gfc_init_expr_flag = true; gfc_reduce_init_expr (e); gfc_init_expr_flag = false; if (!(e->ts.type == BT_CHARACTER || e->ts.type == BT_INTEGER)) { gfc_error ("STOP code at %L must be either INTEGER or CHARACTER type", &e->where); goto cleanup; } if (e->rank != 0) { gfc_error ("STOP code at %L must be scalar", &e->where); goto cleanup; } if (e->ts.type == BT_CHARACTER && e->ts.kind != gfc_default_character_kind) { gfc_error ("STOP code at %L must be default character KIND=%d", &e->where, (int) gfc_default_character_kind); goto cleanup; } if (e->ts.type == BT_INTEGER && e->ts.kind != gfc_default_integer_kind) { gfc_error ("STOP code at %L must be default integer KIND=%d", &e->where, (int) gfc_default_integer_kind); goto cleanup; } } done: switch (st) { case ST_STOP: new_st.op = EXEC_STOP; break; case ST_ERROR_STOP: new_st.op = EXEC_ERROR_STOP; break; case ST_PAUSE: new_st.op = EXEC_PAUSE; break; default: gcc_unreachable (); } new_st.expr1 = e; new_st.ext.stop_code = -1; return MATCH_YES; syntax: gfc_syntax_error (st); cleanup: gfc_free_expr (e); return MATCH_ERROR; } /* Match the (deprecated) PAUSE statement. */ match gfc_match_pause (void) { match m; m = gfc_match_stopcode (ST_PAUSE); if (m == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F95_DEL, "PAUSE statement at %C")) m = MATCH_ERROR; } return m; } /* Match the STOP statement. */ match gfc_match_stop (void) { return gfc_match_stopcode (ST_STOP); } /* Match the ERROR STOP statement. */ match gfc_match_error_stop (void) { if (!gfc_notify_std (GFC_STD_F2008, "ERROR STOP statement at %C")) return MATCH_ERROR; return gfc_match_stopcode (ST_ERROR_STOP); } /* Match EVENT POST/WAIT statement. Syntax: EVENT POST ( event-variable [, sync-stat-list] ) EVENT WAIT ( event-variable [, wait-spec-list] ) with wait-spec-list is sync-stat-list or until-spec until-spec is UNTIL_COUNT = scalar-int-expr sync-stat is STAT= or ERRMSG=. */ static match event_statement (gfc_statement st) { match m; gfc_expr *tmp, *eventvar, *until_count, *stat, *errmsg; bool saw_until_count, saw_stat, saw_errmsg; tmp = eventvar = until_count = stat = errmsg = NULL; saw_until_count = saw_stat = saw_errmsg = false; if (gfc_pure (NULL)) { gfc_error ("Image control statement EVENT %s at %C in PURE procedure", st == ST_EVENT_POST ? "POST" : "WAIT"); return MATCH_ERROR; } gfc_unset_implicit_pure (NULL); if (flag_coarray == GFC_FCOARRAY_NONE) { gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to enable"); return MATCH_ERROR; } if (gfc_find_state (COMP_CRITICAL)) { gfc_error ("Image control statement EVENT %s at %C in CRITICAL block", st == ST_EVENT_POST ? "POST" : "WAIT"); return MATCH_ERROR; } if (gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement EVENT %s at %C in DO CONCURRENT " "block", st == ST_EVENT_POST ? "POST" : "WAIT"); return MATCH_ERROR; } if (gfc_match_char ('(') != MATCH_YES) goto syntax; if (gfc_match ("%e", &eventvar) != MATCH_YES) goto syntax; m = gfc_match_char (','); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_NO) { m = gfc_match_char (')'); if (m == MATCH_YES) goto done; goto syntax; } for (;;) { m = gfc_match (" stat = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_stat) { gfc_error ("Redundant STAT tag found at %L", &tmp->where); goto cleanup; } stat = tmp; saw_stat = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } m = gfc_match (" errmsg = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_errmsg) { gfc_error ("Redundant ERRMSG tag found at %L", &tmp->where); goto cleanup; } errmsg = tmp; saw_errmsg = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } m = gfc_match (" until_count = %e", &tmp); if (m == MATCH_ERROR || st == ST_EVENT_POST) goto syntax; if (m == MATCH_YES) { if (saw_until_count) { gfc_error ("Redundant UNTIL_COUNT tag found at %L", &tmp->where); goto cleanup; } until_count = tmp; saw_until_count = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } break; } if (m == MATCH_ERROR) goto syntax; if (gfc_match (" )%t") != MATCH_YES) goto syntax; done: switch (st) { case ST_EVENT_POST: new_st.op = EXEC_EVENT_POST; break; case ST_EVENT_WAIT: new_st.op = EXEC_EVENT_WAIT; break; default: gcc_unreachable (); } new_st.expr1 = eventvar; new_st.expr2 = stat; new_st.expr3 = errmsg; new_st.expr4 = until_count; return MATCH_YES; syntax: gfc_syntax_error (st); cleanup: if (until_count != tmp) gfc_free_expr (until_count); if (errmsg != tmp) gfc_free_expr (errmsg); if (stat != tmp) gfc_free_expr (stat); gfc_free_expr (tmp); gfc_free_expr (eventvar); return MATCH_ERROR; } match gfc_match_event_post (void) { if (!gfc_notify_std (GFC_STD_F2008_TS, "EVENT POST statement at %C")) return MATCH_ERROR; return event_statement (ST_EVENT_POST); } match gfc_match_event_wait (void) { if (!gfc_notify_std (GFC_STD_F2008_TS, "EVENT WAIT statement at %C")) return MATCH_ERROR; return event_statement (ST_EVENT_WAIT); } /* Match a FAIL IMAGE statement. */ match gfc_match_fail_image (void) { if (!gfc_notify_std (GFC_STD_F2008_TS, "FAIL IMAGE statement at %C")) return MATCH_ERROR; if (gfc_match_char ('(') == MATCH_YES) goto syntax; new_st.op = EXEC_FAIL_IMAGE; return MATCH_YES; syntax: gfc_syntax_error (ST_FAIL_IMAGE); return MATCH_ERROR; } /* Match LOCK/UNLOCK statement. Syntax: LOCK ( lock-variable [ , lock-stat-list ] ) UNLOCK ( lock-variable [ , sync-stat-list ] ) where lock-stat is ACQUIRED_LOCK or sync-stat and sync-stat is STAT= or ERRMSG=. */ static match lock_unlock_statement (gfc_statement st) { match m; gfc_expr *tmp, *lockvar, *acq_lock, *stat, *errmsg; bool saw_acq_lock, saw_stat, saw_errmsg; tmp = lockvar = acq_lock = stat = errmsg = NULL; saw_acq_lock = saw_stat = saw_errmsg = false; if (gfc_pure (NULL)) { gfc_error ("Image control statement %s at %C in PURE procedure", st == ST_LOCK ? "LOCK" : "UNLOCK"); return MATCH_ERROR; } gfc_unset_implicit_pure (NULL); if (flag_coarray == GFC_FCOARRAY_NONE) { gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to enable"); return MATCH_ERROR; } if (gfc_find_state (COMP_CRITICAL)) { gfc_error ("Image control statement %s at %C in CRITICAL block", st == ST_LOCK ? "LOCK" : "UNLOCK"); return MATCH_ERROR; } if (gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement %s at %C in DO CONCURRENT block", st == ST_LOCK ? "LOCK" : "UNLOCK"); return MATCH_ERROR; } if (gfc_match_char ('(') != MATCH_YES) goto syntax; if (gfc_match ("%e", &lockvar) != MATCH_YES) goto syntax; m = gfc_match_char (','); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_NO) { m = gfc_match_char (')'); if (m == MATCH_YES) goto done; goto syntax; } for (;;) { m = gfc_match (" stat = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_stat) { gfc_error ("Redundant STAT tag found at %L", &tmp->where); goto cleanup; } stat = tmp; saw_stat = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } m = gfc_match (" errmsg = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_errmsg) { gfc_error ("Redundant ERRMSG tag found at %L", &tmp->where); goto cleanup; } errmsg = tmp; saw_errmsg = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } m = gfc_match (" acquired_lock = %v", &tmp); if (m == MATCH_ERROR || st == ST_UNLOCK) goto syntax; if (m == MATCH_YES) { if (saw_acq_lock) { gfc_error ("Redundant ACQUIRED_LOCK tag found at %L", &tmp->where); goto cleanup; } acq_lock = tmp; saw_acq_lock = true; m = gfc_match_char (','); if (m == MATCH_YES) continue; tmp = NULL; break; } break; } if (m == MATCH_ERROR) goto syntax; if (gfc_match (" )%t") != MATCH_YES) goto syntax; done: switch (st) { case ST_LOCK: new_st.op = EXEC_LOCK; break; case ST_UNLOCK: new_st.op = EXEC_UNLOCK; break; default: gcc_unreachable (); } new_st.expr1 = lockvar; new_st.expr2 = stat; new_st.expr3 = errmsg; new_st.expr4 = acq_lock; return MATCH_YES; syntax: gfc_syntax_error (st); cleanup: if (acq_lock != tmp) gfc_free_expr (acq_lock); if (errmsg != tmp) gfc_free_expr (errmsg); if (stat != tmp) gfc_free_expr (stat); gfc_free_expr (tmp); gfc_free_expr (lockvar); return MATCH_ERROR; } match gfc_match_lock (void) { if (!gfc_notify_std (GFC_STD_F2008, "LOCK statement at %C")) return MATCH_ERROR; return lock_unlock_statement (ST_LOCK); } match gfc_match_unlock (void) { if (!gfc_notify_std (GFC_STD_F2008, "UNLOCK statement at %C")) return MATCH_ERROR; return lock_unlock_statement (ST_UNLOCK); } /* Match SYNC ALL/IMAGES/MEMORY statement. Syntax: SYNC ALL [(sync-stat-list)] SYNC MEMORY [(sync-stat-list)] SYNC IMAGES (image-set [, sync-stat-list] ) with sync-stat is int-expr or *. */ static match sync_statement (gfc_statement st) { match m; gfc_expr *tmp, *imageset, *stat, *errmsg; bool saw_stat, saw_errmsg; tmp = imageset = stat = errmsg = NULL; saw_stat = saw_errmsg = false; if (gfc_pure (NULL)) { gfc_error ("Image control statement SYNC at %C in PURE procedure"); return MATCH_ERROR; } gfc_unset_implicit_pure (NULL); if (!gfc_notify_std (GFC_STD_F2008, "SYNC statement at %C")) return MATCH_ERROR; if (flag_coarray == GFC_FCOARRAY_NONE) { gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to " "enable"); return MATCH_ERROR; } if (gfc_find_state (COMP_CRITICAL)) { gfc_error ("Image control statement SYNC at %C in CRITICAL block"); return MATCH_ERROR; } if (gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement SYNC at %C in DO CONCURRENT block"); return MATCH_ERROR; } if (gfc_match_eos () == MATCH_YES) { if (st == ST_SYNC_IMAGES) goto syntax; goto done; } if (gfc_match_char ('(') != MATCH_YES) goto syntax; if (st == ST_SYNC_IMAGES) { /* Denote '*' as imageset == NULL. */ m = gfc_match_char ('*'); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_NO) { if (gfc_match ("%e", &imageset) != MATCH_YES) goto syntax; } m = gfc_match_char (','); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_NO) { m = gfc_match_char (')'); if (m == MATCH_YES) goto done; goto syntax; } } for (;;) { m = gfc_match (" stat = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_stat) { gfc_error ("Redundant STAT tag found at %L", &tmp->where); goto cleanup; } stat = tmp; saw_stat = true; if (gfc_match_char (',') == MATCH_YES) continue; tmp = NULL; break; } m = gfc_match (" errmsg = %v", &tmp); if (m == MATCH_ERROR) goto syntax; if (m == MATCH_YES) { if (saw_errmsg) { gfc_error ("Redundant ERRMSG tag found at %L", &tmp->where); goto cleanup; } errmsg = tmp; saw_errmsg = true; if (gfc_match_char (',') == MATCH_YES) continue; tmp = NULL; break; } break; } if (gfc_match (" )%t") != MATCH_YES) goto syntax; done: switch (st) { case ST_SYNC_ALL: new_st.op = EXEC_SYNC_ALL; break; case ST_SYNC_IMAGES: new_st.op = EXEC_SYNC_IMAGES; break; case ST_SYNC_MEMORY: new_st.op = EXEC_SYNC_MEMORY; break; default: gcc_unreachable (); } new_st.expr1 = imageset; new_st.expr2 = stat; new_st.expr3 = errmsg; return MATCH_YES; syntax: gfc_syntax_error (st); cleanup: if (stat != tmp) gfc_free_expr (stat); if (errmsg != tmp) gfc_free_expr (errmsg); gfc_free_expr (tmp); gfc_free_expr (imageset); return MATCH_ERROR; } /* Match SYNC ALL statement. */ match gfc_match_sync_all (void) { return sync_statement (ST_SYNC_ALL); } /* Match SYNC IMAGES statement. */ match gfc_match_sync_images (void) { return sync_statement (ST_SYNC_IMAGES); } /* Match SYNC MEMORY statement. */ match gfc_match_sync_memory (void) { return sync_statement (ST_SYNC_MEMORY); } /* Match a CONTINUE statement. */ match gfc_match_continue (void) { if (gfc_match_eos () != MATCH_YES) { gfc_syntax_error (ST_CONTINUE); return MATCH_ERROR; } new_st.op = EXEC_CONTINUE; return MATCH_YES; } /* Match the (deprecated) ASSIGN statement. */ match gfc_match_assign (void) { gfc_expr *expr; gfc_st_label *label; if (gfc_match (" %l", &label) == MATCH_YES) { if (!gfc_reference_st_label (label, ST_LABEL_UNKNOWN)) return MATCH_ERROR; if (gfc_match (" to %v%t", &expr) == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F95_DEL, "ASSIGN statement at %C")) return MATCH_ERROR; expr->symtree->n.sym->attr.assign = 1; new_st.op = EXEC_LABEL_ASSIGN; new_st.label1 = label; new_st.expr1 = expr; return MATCH_YES; } } return MATCH_NO; } /* Match the GO TO statement. As a computed GOTO statement is matched, it is transformed into an equivalent SELECT block. No tree is necessary, and the resulting jumps-to-jumps are specifically optimized away by the back end. */ match gfc_match_goto (void) { gfc_code *head, *tail; gfc_expr *expr; gfc_case *cp; gfc_st_label *label; int i; match m; if (gfc_match (" %l%t", &label) == MATCH_YES) { if (!gfc_reference_st_label (label, ST_LABEL_TARGET)) return MATCH_ERROR; new_st.op = EXEC_GOTO; new_st.label1 = label; return MATCH_YES; } /* The assigned GO TO statement. */ if (gfc_match_variable (&expr, 0) == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F95_DEL, "Assigned GOTO statement at %C")) return MATCH_ERROR; new_st.op = EXEC_GOTO; new_st.expr1 = expr; if (gfc_match_eos () == MATCH_YES) return MATCH_YES; /* Match label list. */ gfc_match_char (','); if (gfc_match_char ('(') != MATCH_YES) { gfc_syntax_error (ST_GOTO); return MATCH_ERROR; } head = tail = NULL; do { m = gfc_match_st_label (&label); if (m != MATCH_YES) goto syntax; if (!gfc_reference_st_label (label, ST_LABEL_TARGET)) goto cleanup; if (head == NULL) head = tail = gfc_get_code (EXEC_GOTO); else { tail->block = gfc_get_code (EXEC_GOTO); tail = tail->block; } tail->label1 = label; } while (gfc_match_char (',') == MATCH_YES); if (gfc_match (")%t") != MATCH_YES) goto syntax; if (head == NULL) { gfc_error ("Statement label list in GOTO at %C cannot be empty"); goto syntax; } new_st.block = head; return MATCH_YES; } /* Last chance is a computed GO TO statement. */ if (gfc_match_char ('(') != MATCH_YES) { gfc_syntax_error (ST_GOTO); return MATCH_ERROR; } head = tail = NULL; i = 1; do { m = gfc_match_st_label (&label); if (m != MATCH_YES) goto syntax; if (!gfc_reference_st_label (label, ST_LABEL_TARGET)) goto cleanup; if (head == NULL) head = tail = gfc_get_code (EXEC_SELECT); else { tail->block = gfc_get_code (EXEC_SELECT); tail = tail->block; } cp = gfc_get_case (); cp->low = cp->high = gfc_get_int_expr (gfc_default_integer_kind, NULL, i++); tail->ext.block.case_list = cp; tail->next = gfc_get_code (EXEC_GOTO); tail->next->label1 = label; } while (gfc_match_char (',') == MATCH_YES); if (gfc_match_char (')') != MATCH_YES) goto syntax; if (head == NULL) { gfc_error ("Statement label list in GOTO at %C cannot be empty"); goto syntax; } /* Get the rest of the statement. */ gfc_match_char (','); if (gfc_match (" %e%t", &expr) != MATCH_YES) goto syntax; if (!gfc_notify_std (GFC_STD_F95_OBS, "Computed GOTO at %C")) return MATCH_ERROR; /* At this point, a computed GOTO has been fully matched and an equivalent SELECT statement constructed. */ new_st.op = EXEC_SELECT; new_st.expr1 = NULL; /* Hack: For a "real" SELECT, the expression is in expr. We put it in expr2 so we can distinguish then and produce the correct diagnostics. */ new_st.expr2 = expr; new_st.block = head; return MATCH_YES; syntax: gfc_syntax_error (ST_GOTO); cleanup: gfc_free_statements (head); return MATCH_ERROR; } /* Frees a list of gfc_alloc structures. */ void gfc_free_alloc_list (gfc_alloc *p) { gfc_alloc *q; for (; p; p = q) { q = p->next; gfc_free_expr (p->expr); free (p); } } /* Match an ALLOCATE statement. */ match gfc_match_allocate (void) { gfc_alloc *head, *tail; gfc_expr *stat, *errmsg, *tmp, *source, *mold; gfc_typespec ts; gfc_symbol *sym; match m; locus old_locus, deferred_locus; bool saw_stat, saw_errmsg, saw_source, saw_mold, saw_deferred, b1, b2, b3; bool saw_unlimited = false; head = tail = NULL; stat = errmsg = source = mold = tmp = NULL; saw_stat = saw_errmsg = saw_source = saw_mold = saw_deferred = false; if (gfc_match_char ('(') != MATCH_YES) goto syntax; /* Match an optional type-spec. */ old_locus = gfc_current_locus; m = gfc_match_type_spec (&ts); if (m == MATCH_ERROR) goto cleanup; else if (m == MATCH_NO) { char name[GFC_MAX_SYMBOL_LEN + 3]; if (gfc_match ("%n :: ", name) == MATCH_YES) { gfc_error ("Error in type-spec at %L", &old_locus); goto cleanup; } ts.type = BT_UNKNOWN; } else { if (gfc_match (" :: ") == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F2003, "typespec in ALLOCATE at %L", &old_locus)) goto cleanup; if (ts.deferred) { gfc_error ("Type-spec at %L cannot contain a deferred " "type parameter", &old_locus); goto cleanup; } if (ts.type == BT_CHARACTER) ts.u.cl->length_from_typespec = true; } else { ts.type = BT_UNKNOWN; gfc_current_locus = old_locus; } } for (;;) { if (head == NULL) head = tail = gfc_get_alloc (); else { tail->next = gfc_get_alloc (); tail = tail->next; } m = gfc_match_variable (&tail->expr, 0); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_check_do_variable (tail->expr->symtree)) goto cleanup; bool impure = gfc_impure_variable (tail->expr->symtree->n.sym); if (impure && gfc_pure (NULL)) { gfc_error ("Bad allocate-object at %C for a PURE procedure"); goto cleanup; } if (impure) gfc_unset_implicit_pure (NULL); if (tail->expr->ts.deferred) { saw_deferred = true; deferred_locus = tail->expr->where; } if (gfc_find_state (COMP_DO_CONCURRENT) || gfc_find_state (COMP_CRITICAL)) { gfc_ref *ref; bool coarray = tail->expr->symtree->n.sym->attr.codimension; for (ref = tail->expr->ref; ref; ref = ref->next) if (ref->type == REF_COMPONENT) coarray = ref->u.c.component->attr.codimension; if (coarray && gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("ALLOCATE of coarray at %C in DO CONCURRENT block"); goto cleanup; } if (coarray && gfc_find_state (COMP_CRITICAL)) { gfc_error ("ALLOCATE of coarray at %C in CRITICAL block"); goto cleanup; } } /* Check for F08:C628. */ sym = tail->expr->symtree->n.sym; b1 = !(tail->expr->ref && (tail->expr->ref->type == REF_COMPONENT || tail->expr->ref->type == REF_ARRAY)); if (sym && sym->ts.type == BT_CLASS && sym->attr.class_ok) b2 = !(CLASS_DATA (sym)->attr.allocatable || CLASS_DATA (sym)->attr.class_pointer); else b2 = sym && !(sym->attr.allocatable || sym->attr.pointer || sym->attr.proc_pointer); b3 = sym && sym->ns && sym->ns->proc_name && (sym->ns->proc_name->attr.allocatable || sym->ns->proc_name->attr.pointer || sym->ns->proc_name->attr.proc_pointer); if (b1 && b2 && !b3) { gfc_error ("Allocate-object at %L is neither a data pointer " "nor an allocatable variable", &tail->expr->where); goto cleanup; } /* The ALLOCATE statement had an optional typespec. Check the constraints. */ if (ts.type != BT_UNKNOWN) { /* Enforce F03:C624. */ if (!gfc_type_compatible (&tail->expr->ts, &ts)) { gfc_error ("Type of entity at %L is type incompatible with " "typespec", &tail->expr->where); goto cleanup; } /* Enforce F03:C627. */ if (ts.kind != tail->expr->ts.kind && !UNLIMITED_POLY (tail->expr)) { gfc_error ("Kind type parameter for entity at %L differs from " "the kind type parameter of the typespec", &tail->expr->where); goto cleanup; } } if (tail->expr->ts.type == BT_DERIVED) tail->expr->ts.u.derived = gfc_use_derived (tail->expr->ts.u.derived); saw_unlimited = saw_unlimited | UNLIMITED_POLY (tail->expr); if (gfc_peek_ascii_char () == '(' && !sym->attr.dimension) { gfc_error ("Shape specification for allocatable scalar at %C"); goto cleanup; } if (gfc_match_char (',') != MATCH_YES) break; alloc_opt_list: m = gfc_match (" stat = %v", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { /* Enforce C630. */ if (saw_stat) { gfc_error ("Redundant STAT tag found at %L", &tmp->where); goto cleanup; } stat = tmp; tmp = NULL; saw_stat = true; if (gfc_check_do_variable (stat->symtree)) goto cleanup; if (gfc_match_char (',') == MATCH_YES) goto alloc_opt_list; } m = gfc_match (" errmsg = %v", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F2003, "ERRMSG tag at %L", &tmp->where)) goto cleanup; /* Enforce C630. */ if (saw_errmsg) { gfc_error ("Redundant ERRMSG tag found at %L", &tmp->where); goto cleanup; } errmsg = tmp; tmp = NULL; saw_errmsg = true; if (gfc_match_char (',') == MATCH_YES) goto alloc_opt_list; } m = gfc_match (" source = %e", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F2003, "SOURCE tag at %L", &tmp->where)) goto cleanup; /* Enforce C630. */ if (saw_source) { gfc_error ("Redundant SOURCE tag found at %L", &tmp->where); goto cleanup; } /* The next 2 conditionals check C631. */ if (ts.type != BT_UNKNOWN) { gfc_error ("SOURCE tag at %L conflicts with the typespec at %L", &tmp->where, &old_locus); goto cleanup; } if (head->next && !gfc_notify_std (GFC_STD_F2008, "SOURCE tag at %L" " with more than a single allocate object", &tmp->where)) goto cleanup; source = tmp; tmp = NULL; saw_source = true; if (gfc_match_char (',') == MATCH_YES) goto alloc_opt_list; } m = gfc_match (" mold = %e", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F2008, "MOLD tag at %L", &tmp->where)) goto cleanup; /* Check F08:C636. */ if (saw_mold) { gfc_error ("Redundant MOLD tag found at %L", &tmp->where); goto cleanup; } /* Check F08:C637. */ if (ts.type != BT_UNKNOWN) { gfc_error ("MOLD tag at %L conflicts with the typespec at %L", &tmp->where, &old_locus); goto cleanup; } mold = tmp; tmp = NULL; saw_mold = true; mold->mold = 1; if (gfc_match_char (',') == MATCH_YES) goto alloc_opt_list; } gfc_gobble_whitespace (); if (gfc_peek_char () == ')') break; } if (gfc_match (" )%t") != MATCH_YES) goto syntax; /* Check F08:C637. */ if (source && mold) { gfc_error ("MOLD tag at %L conflicts with SOURCE tag at %L", &mold->where, &source->where); goto cleanup; } /* Check F03:C623, */ if (saw_deferred && ts.type == BT_UNKNOWN && !source && !mold) { gfc_error ("Allocate-object at %L with a deferred type parameter " "requires either a type-spec or SOURCE tag or a MOLD tag", &deferred_locus); goto cleanup; } /* Check F03:C625, */ if (saw_unlimited && ts.type == BT_UNKNOWN && !source && !mold) { for (tail = head; tail; tail = tail->next) { if (UNLIMITED_POLY (tail->expr)) gfc_error ("Unlimited polymorphic allocate-object at %L " "requires either a type-spec or SOURCE tag " "or a MOLD tag", &tail->expr->where); } goto cleanup; } new_st.op = EXEC_ALLOCATE; new_st.expr1 = stat; new_st.expr2 = errmsg; if (source) new_st.expr3 = source; else new_st.expr3 = mold; new_st.ext.alloc.list = head; new_st.ext.alloc.ts = ts; return MATCH_YES; syntax: gfc_syntax_error (ST_ALLOCATE); cleanup: gfc_free_expr (errmsg); gfc_free_expr (source); gfc_free_expr (stat); gfc_free_expr (mold); if (tmp && tmp->expr_type) gfc_free_expr (tmp); gfc_free_alloc_list (head); return MATCH_ERROR; } /* Match a NULLIFY statement. A NULLIFY statement is transformed into a set of pointer assignments to intrinsic NULL(). */ match gfc_match_nullify (void) { gfc_code *tail; gfc_expr *e, *p; match m; tail = NULL; if (gfc_match_char ('(') != MATCH_YES) goto syntax; for (;;) { m = gfc_match_variable (&p, 0); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; if (gfc_check_do_variable (p->symtree)) goto cleanup; /* F2008, C1242. */ if (gfc_is_coindexed (p)) { gfc_error ("Pointer object at %C shall not be coindexed"); goto cleanup; } /* build ' => NULL() '. */ e = gfc_get_null_expr (&gfc_current_locus); /* Chain to list. */ if (tail == NULL) { tail = &new_st; tail->op = EXEC_POINTER_ASSIGN; } else { tail->next = gfc_get_code (EXEC_POINTER_ASSIGN); tail = tail->next; } tail->expr1 = p; tail->expr2 = e; if (gfc_match (" )%t") == MATCH_YES) break; if (gfc_match_char (',') != MATCH_YES) goto syntax; } return MATCH_YES; syntax: gfc_syntax_error (ST_NULLIFY); cleanup: gfc_free_statements (new_st.next); new_st.next = NULL; gfc_free_expr (new_st.expr1); new_st.expr1 = NULL; gfc_free_expr (new_st.expr2); new_st.expr2 = NULL; return MATCH_ERROR; } /* Match a DEALLOCATE statement. */ match gfc_match_deallocate (void) { gfc_alloc *head, *tail; gfc_expr *stat, *errmsg, *tmp; gfc_symbol *sym; match m; bool saw_stat, saw_errmsg, b1, b2; head = tail = NULL; stat = errmsg = tmp = NULL; saw_stat = saw_errmsg = false; if (gfc_match_char ('(') != MATCH_YES) goto syntax; for (;;) { if (head == NULL) head = tail = gfc_get_alloc (); else { tail->next = gfc_get_alloc (); tail = tail->next; } m = gfc_match_variable (&tail->expr, 0); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; if (gfc_check_do_variable (tail->expr->symtree)) goto cleanup; sym = tail->expr->symtree->n.sym; bool impure = gfc_impure_variable (sym); if (impure && gfc_pure (NULL)) { gfc_error ("Illegal allocate-object at %C for a PURE procedure"); goto cleanup; } if (impure) gfc_unset_implicit_pure (NULL); if (gfc_is_coarray (tail->expr) && gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("DEALLOCATE of coarray at %C in DO CONCURRENT block"); goto cleanup; } if (gfc_is_coarray (tail->expr) && gfc_find_state (COMP_CRITICAL)) { gfc_error ("DEALLOCATE of coarray at %C in CRITICAL block"); goto cleanup; } /* FIXME: disable the checking on derived types. */ b1 = !(tail->expr->ref && (tail->expr->ref->type == REF_COMPONENT || tail->expr->ref->type == REF_ARRAY)); if (sym && sym->ts.type == BT_CLASS) b2 = !(CLASS_DATA (sym) && (CLASS_DATA (sym)->attr.allocatable || CLASS_DATA (sym)->attr.class_pointer)); else b2 = sym && !(sym->attr.allocatable || sym->attr.pointer || sym->attr.proc_pointer); if (b1 && b2) { gfc_error ("Allocate-object at %C is not a nonprocedure pointer " "nor an allocatable variable"); goto cleanup; } if (gfc_match_char (',') != MATCH_YES) break; dealloc_opt_list: m = gfc_match (" stat = %v", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (saw_stat) { gfc_error ("Redundant STAT tag found at %L", &tmp->where); gfc_free_expr (tmp); goto cleanup; } stat = tmp; saw_stat = true; if (gfc_check_do_variable (stat->symtree)) goto cleanup; if (gfc_match_char (',') == MATCH_YES) goto dealloc_opt_list; } m = gfc_match (" errmsg = %v", &tmp); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (!gfc_notify_std (GFC_STD_F2003, "ERRMSG at %L", &tmp->where)) goto cleanup; if (saw_errmsg) { gfc_error ("Redundant ERRMSG tag found at %L", &tmp->where); gfc_free_expr (tmp); goto cleanup; } errmsg = tmp; saw_errmsg = true; if (gfc_match_char (',') == MATCH_YES) goto dealloc_opt_list; } gfc_gobble_whitespace (); if (gfc_peek_char () == ')') break; } if (gfc_match (" )%t") != MATCH_YES) goto syntax; new_st.op = EXEC_DEALLOCATE; new_st.expr1 = stat; new_st.expr2 = errmsg; new_st.ext.alloc.list = head; return MATCH_YES; syntax: gfc_syntax_error (ST_DEALLOCATE); cleanup: gfc_free_expr (errmsg); gfc_free_expr (stat); gfc_free_alloc_list (head); return MATCH_ERROR; } /* Match a RETURN statement. */ match gfc_match_return (void) { gfc_expr *e; match m; gfc_compile_state s; e = NULL; if (gfc_find_state (COMP_CRITICAL)) { gfc_error ("Image control statement RETURN at %C in CRITICAL block"); return MATCH_ERROR; } if (gfc_find_state (COMP_DO_CONCURRENT)) { gfc_error ("Image control statement RETURN at %C in DO CONCURRENT block"); return MATCH_ERROR; } if (gfc_match_eos () == MATCH_YES) goto done; if (!gfc_find_state (COMP_SUBROUTINE)) { gfc_error ("Alternate RETURN statement at %C is only allowed within " "a SUBROUTINE"); goto cleanup; } if (gfc_current_form == FORM_FREE) { /* The following are valid, so we can't require a blank after the RETURN keyword: return+1 return(1) */ char c = gfc_peek_ascii_char (); if (ISALPHA (c) || ISDIGIT (c)) return MATCH_NO; } m = gfc_match (" %e%t", &e); if (m == MATCH_YES) goto done; if (m == MATCH_ERROR) goto cleanup; gfc_syntax_error (ST_RETURN); cleanup: gfc_free_expr (e); return MATCH_ERROR; done: gfc_enclosing_unit (&s); if (s == COMP_PROGRAM && !gfc_notify_std (GFC_STD_GNU, "RETURN statement in " "main program at %C")) return MATCH_ERROR; new_st.op = EXEC_RETURN; new_st.expr1 = e; return MATCH_YES; } /* Match the call of a type-bound procedure, if CALL%var has already been matched and var found to be a derived-type variable. */ static match match_typebound_call (gfc_symtree* varst) { gfc_expr* base; match m; base = gfc_get_expr (); base->expr_type = EXPR_VARIABLE; base->symtree = varst; base->where = gfc_current_locus; gfc_set_sym_referenced (varst->n.sym); m = gfc_match_varspec (base, 0, true, true); if (m == MATCH_NO) gfc_error ("Expected component reference at %C"); if (m != MATCH_YES) { gfc_free_expr (base); return MATCH_ERROR; } if (gfc_match_eos () != MATCH_YES) { gfc_error ("Junk after CALL at %C"); gfc_free_expr (base); return MATCH_ERROR; } if (base->expr_type == EXPR_COMPCALL) new_st.op = EXEC_COMPCALL; else if (base->expr_type == EXPR_PPC) new_st.op = EXEC_CALL_PPC; else { gfc_error ("Expected type-bound procedure or procedure pointer component " "at %C"); gfc_free_expr (base); return MATCH_ERROR; } new_st.expr1 = base; return MATCH_YES; } /* Match a CALL statement. The tricky part here are possible alternate return specifiers. We handle these by having all "subroutines" actually return an integer via a register that gives the return number. If the call specifies alternate returns, we generate code for a SELECT statement whose case clauses contain GOTOs to the various labels. */ match gfc_match_call (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_actual_arglist *a, *arglist; gfc_case *new_case; gfc_symbol *sym; gfc_symtree *st; gfc_code *c; match m; int i; arglist = NULL; m = gfc_match ("% %n", name); if (m == MATCH_NO) goto syntax; if (m != MATCH_YES) return m; if (gfc_get_ha_sym_tree (name, &st)) return MATCH_ERROR; sym = st->n.sym; /* If this is a variable of derived-type, it probably starts a type-bound procedure call. */ if ((sym->attr.flavor != FL_PROCEDURE || gfc_is_function_return_value (sym, gfc_current_ns)) && (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)) return match_typebound_call (st); /* If it does not seem to be callable (include functions so that the right association is made. They are thrown out in resolution.) ... */ if (!sym->attr.generic && !sym->attr.subroutine && !sym->attr.function) { if (!(sym->attr.external && !sym->attr.referenced)) { /* ...create a symbol in this scope... */ if (sym->ns != gfc_current_ns && gfc_get_sym_tree (name, NULL, &st, false) == 1) return MATCH_ERROR; if (sym != st->n.sym) sym = st->n.sym; } /* ...and then to try to make the symbol into a subroutine. */ if (!gfc_add_subroutine (&sym->attr, sym->name, NULL)) return MATCH_ERROR; } gfc_set_sym_referenced (sym); if (gfc_match_eos () != MATCH_YES) { m = gfc_match_actual_arglist (1, &arglist); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_eos () != MATCH_YES) goto syntax; } /* If any alternate return labels were found, construct a SELECT statement that will jump to the right place. */ i = 0; for (a = arglist; a; a = a->next) if (a->expr == NULL) { i = 1; break; } if (i) { gfc_symtree *select_st; gfc_symbol *select_sym; char name[GFC_MAX_SYMBOL_LEN + 1]; new_st.next = c = gfc_get_code (EXEC_SELECT); sprintf (name, "_result_%s", sym->name); gfc_get_ha_sym_tree (name, &select_st); /* Can't fail. */ select_sym = select_st->n.sym; select_sym->ts.type = BT_INTEGER; select_sym->ts.kind = gfc_default_integer_kind; gfc_set_sym_referenced (select_sym); c->expr1 = gfc_get_expr (); c->expr1->expr_type = EXPR_VARIABLE; c->expr1->symtree = select_st; c->expr1->ts = select_sym->ts; c->expr1->where = gfc_current_locus; i = 0; for (a = arglist; a; a = a->next) { if (a->expr != NULL) continue; if (!gfc_reference_st_label (a->label, ST_LABEL_TARGET)) continue; i++; c->block = gfc_get_code (EXEC_SELECT); c = c->block; new_case = gfc_get_case (); new_case->high = gfc_get_int_expr (gfc_default_integer_kind, NULL, i); new_case->low = new_case->high; c->ext.block.case_list = new_case; c->next = gfc_get_code (EXEC_GOTO); c->next->label1 = a->label; } } new_st.op = EXEC_CALL; new_st.symtree = st; new_st.ext.actual = arglist; return MATCH_YES; syntax: gfc_syntax_error (ST_CALL); cleanup: gfc_free_actual_arglist (arglist); return MATCH_ERROR; } /* Given a name, return a pointer to the common head structure, creating it if it does not exist. If FROM_MODULE is nonzero, we mangle the name so that it doesn't interfere with commons defined in the using namespace. TODO: Add to global symbol tree. */ gfc_common_head * gfc_get_common (const char *name, int from_module) { gfc_symtree *st; static int serial = 0; char mangled_name[GFC_MAX_SYMBOL_LEN + 1]; if (from_module) { /* A use associated common block is only needed to correctly layout the variables it contains. */ snprintf (mangled_name, GFC_MAX_SYMBOL_LEN, "_%d_%s", serial++, name); st = gfc_new_symtree (&gfc_current_ns->common_root, mangled_name); } else { st = gfc_find_symtree (gfc_current_ns->common_root, name); if (st == NULL) st = gfc_new_symtree (&gfc_current_ns->common_root, name); } if (st->n.common == NULL) { st->n.common = gfc_get_common_head (); st->n.common->where = gfc_current_locus; strcpy (st->n.common->name, name); } return st->n.common; } /* Match a common block name. */ match match_common_name (char *name) { match m; if (gfc_match_char ('/') == MATCH_NO) { name[0] = '\0'; return MATCH_YES; } if (gfc_match_char ('/') == MATCH_YES) { name[0] = '\0'; return MATCH_YES; } m = gfc_match_name (name); if (m == MATCH_ERROR) return MATCH_ERROR; if (m == MATCH_YES && gfc_match_char ('/') == MATCH_YES) return MATCH_YES; gfc_error ("Syntax error in common block name at %C"); return MATCH_ERROR; } /* Match a COMMON statement. */ match gfc_match_common (void) { gfc_symbol *sym, **head, *tail, *other; char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_common_head *t; gfc_array_spec *as; gfc_equiv *e1, *e2; match m; as = NULL; for (;;) { m = match_common_name (name); if (m == MATCH_ERROR) goto cleanup; if (name[0] == '\0') { t = &gfc_current_ns->blank_common; if (t->head == NULL) t->where = gfc_current_locus; } else { t = gfc_get_common (name, 0); } head = &t->head; if (*head == NULL) tail = NULL; else { tail = *head; while (tail->common_next) tail = tail->common_next; } /* Grab the list of symbols. */ for (;;) { m = gfc_match_symbol (&sym, 0); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; /* See if we know the current common block is bind(c), and if so, then see if we can check if the symbol is (which it'll need to be). This can happen if the bind(c) attr stmt was applied to the common block, and the variable(s) already defined, before declaring the common block. */ if (t->is_bind_c == 1) { if (sym->ts.type != BT_UNKNOWN && sym->ts.is_c_interop != 1) { /* If we find an error, just print it and continue, cause it's just semantic, and we can see if there are more errors. */ gfc_error_now ("Variable %qs at %L in common block %qs " "at %C must be declared with a C " "interoperable kind since common block " "%qs is bind(c)", sym->name, &(sym->declared_at), t->name, t->name); } if (sym->attr.is_bind_c == 1) gfc_error_now ("Variable %qs in common block %qs at %C can not " "be bind(c) since it is not global", sym->name, t->name); } if (sym->attr.in_common) { gfc_error ("Symbol %qs at %C is already in a COMMON block", sym->name); goto cleanup; } if (((sym->value != NULL && sym->value->expr_type != EXPR_NULL) || sym->attr.data) && gfc_current_state () != COMP_BLOCK_DATA) { if (!gfc_notify_std (GFC_STD_GNU, "Initialized symbol %qs at " "%C can only be COMMON in BLOCK DATA", sym->name)) goto cleanup; } /* Deal with an optional array specification after the symbol name. */ m = gfc_match_array_spec (&as, true, true); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_YES) { if (as->type != AS_EXPLICIT) { gfc_error ("Array specification for symbol %qs in COMMON " "at %C must be explicit", sym->name); goto cleanup; } if (!gfc_add_dimension (&sym->attr, sym->name, NULL)) goto cleanup; if (sym->attr.pointer) { gfc_error ("Symbol %qs in COMMON at %C cannot be a " "POINTER array", sym->name); goto cleanup; } sym->as = as; as = NULL; } /* Add the in_common attribute, but ignore the reported errors if any, and continue matching. */ gfc_add_in_common (&sym->attr, sym->name, NULL); sym->common_block = t; sym->common_block->refs++; if (tail != NULL) tail->common_next = sym; else *head = sym; tail = sym; sym->common_head = t; /* Check to see if the symbol is already in an equivalence group. If it is, set the other members as being in common. */ if (sym->attr.in_equivalence) { for (e1 = gfc_current_ns->equiv; e1; e1 = e1->next) { for (e2 = e1; e2; e2 = e2->eq) if (e2->expr->symtree->n.sym == sym) goto equiv_found; continue; equiv_found: for (e2 = e1; e2; e2 = e2->eq) { other = e2->expr->symtree->n.sym; if (other->common_head && other->common_head != sym->common_head) { gfc_error ("Symbol %qs, in COMMON block %qs at " "%C is being indirectly equivalenced to " "another COMMON block %qs", sym->name, sym->common_head->name, other->common_head->name); goto cleanup; } other->attr.in_common = 1; other->common_head = t; } } } gfc_gobble_whitespace (); if (gfc_match_eos () == MATCH_YES) goto done; if (gfc_peek_ascii_char () == '/') break; if (gfc_match_char (',') != MATCH_YES) goto syntax; gfc_gobble_whitespace (); if (gfc_peek_ascii_char () == '/') break; } } done: return MATCH_YES; syntax: gfc_syntax_error (ST_COMMON); cleanup: gfc_free_array_spec (as); return MATCH_ERROR; } /* Match a BLOCK DATA program unit. */ match gfc_match_block_data (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_symbol *sym; match m; if (gfc_match_eos () == MATCH_YES) { gfc_new_block = NULL; return MATCH_YES; } m = gfc_match ("% %n%t", name); if (m != MATCH_YES) return MATCH_ERROR; if (gfc_get_symbol (name, NULL, &sym)) return MATCH_ERROR; if (!gfc_add_flavor (&sym->attr, FL_BLOCK_DATA, sym->name, NULL)) return MATCH_ERROR; gfc_new_block = sym; return MATCH_YES; } /* Free a namelist structure. */ void gfc_free_namelist (gfc_namelist *name) { gfc_namelist *n; for (; name; name = n) { n = name->next; free (name); } } /* Free an OpenMP namelist structure. */ void gfc_free_omp_namelist (gfc_omp_namelist *name) { gfc_omp_namelist *n; for (; name; name = n) { gfc_free_expr (name->expr); if (name->udr) { if (name->udr->combiner) gfc_free_statement (name->udr->combiner); if (name->udr->initializer) gfc_free_statement (name->udr->initializer); free (name->udr); } n = name->next; free (name); } } /* Match a NAMELIST statement. */ match gfc_match_namelist (void) { gfc_symbol *group_name, *sym; gfc_namelist *nl; match m, m2; m = gfc_match (" / %s /", &group_name); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto error; for (;;) { if (group_name->ts.type != BT_UNKNOWN) { gfc_error ("Namelist group name %qs at %C already has a basic " "type of %s", group_name->name, gfc_typename (&group_name->ts)); return MATCH_ERROR; } if (group_name->attr.flavor == FL_NAMELIST && group_name->attr.use_assoc && !gfc_notify_std (GFC_STD_GNU, "Namelist group name %qs " "at %C already is USE associated and can" "not be respecified.", group_name->name)) return MATCH_ERROR; if (group_name->attr.flavor != FL_NAMELIST && !gfc_add_flavor (&group_name->attr, FL_NAMELIST, group_name->name, NULL)) return MATCH_ERROR; for (;;) { m = gfc_match_symbol (&sym, 1); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto error; if (sym->attr.in_namelist == 0 && !gfc_add_in_namelist (&sym->attr, sym->name, NULL)) goto error; /* Use gfc_error_check here, rather than goto error, so that these are the only errors for the next two lines. */ if (sym->as && sym->as->type == AS_ASSUMED_SIZE) { gfc_error ("Assumed size array %qs in namelist %qs at " "%C is not allowed", sym->name, group_name->name); gfc_error_check (); } nl = gfc_get_namelist (); nl->sym = sym; sym->refs++; if (group_name->namelist == NULL) group_name->namelist = group_name->namelist_tail = nl; else { group_name->namelist_tail->next = nl; group_name->namelist_tail = nl; } if (gfc_match_eos () == MATCH_YES) goto done; m = gfc_match_char (','); if (gfc_match_char ('/') == MATCH_YES) { m2 = gfc_match (" %s /", &group_name); if (m2 == MATCH_YES) break; if (m2 == MATCH_ERROR) goto error; goto syntax; } if (m != MATCH_YES) goto syntax; } } done: return MATCH_YES; syntax: gfc_syntax_error (ST_NAMELIST); error: return MATCH_ERROR; } /* Match a MODULE statement. */ match gfc_match_module (void) { match m; m = gfc_match (" %s%t", &gfc_new_block); if (m != MATCH_YES) return m; if (!gfc_add_flavor (&gfc_new_block->attr, FL_MODULE, gfc_new_block->name, NULL)) return MATCH_ERROR; return MATCH_YES; } /* Free equivalence sets and lists. Recursively is the easiest way to do this. */ void gfc_free_equiv_until (gfc_equiv *eq, gfc_equiv *stop) { if (eq == stop) return; gfc_free_equiv (eq->eq); gfc_free_equiv_until (eq->next, stop); gfc_free_expr (eq->expr); free (eq); } void gfc_free_equiv (gfc_equiv *eq) { gfc_free_equiv_until (eq, NULL); } /* Match an EQUIVALENCE statement. */ match gfc_match_equivalence (void) { gfc_equiv *eq, *set, *tail; gfc_ref *ref; gfc_symbol *sym; match m; gfc_common_head *common_head = NULL; bool common_flag; int cnt; tail = NULL; for (;;) { eq = gfc_get_equiv (); if (tail == NULL) tail = eq; eq->next = gfc_current_ns->equiv; gfc_current_ns->equiv = eq; if (gfc_match_char ('(') != MATCH_YES) goto syntax; set = eq; common_flag = FALSE; cnt = 0; for (;;) { m = gfc_match_equiv_variable (&set->expr); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; /* count the number of objects. */ cnt++; if (gfc_match_char ('%') == MATCH_YES) { gfc_error ("Derived type component %C is not a " "permitted EQUIVALENCE member"); goto cleanup; } for (ref = set->expr->ref; ref; ref = ref->next) if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION) { gfc_error ("Array reference in EQUIVALENCE at %C cannot " "be an array section"); goto cleanup; } sym = set->expr->symtree->n.sym; if (!gfc_add_in_equivalence (&sym->attr, sym->name, NULL)) goto cleanup; if (sym->attr.in_common) { common_flag = TRUE; common_head = sym->common_head; } if (gfc_match_char (')') == MATCH_YES) break; if (gfc_match_char (',') != MATCH_YES) goto syntax; set->eq = gfc_get_equiv (); set = set->eq; } if (cnt < 2) { gfc_error ("EQUIVALENCE at %C requires two or more objects"); goto cleanup; } /* If one of the members of an equivalence is in common, then mark them all as being in common. Before doing this, check that members of the equivalence group are not in different common blocks. */ if (common_flag) for (set = eq; set; set = set->eq) { sym = set->expr->symtree->n.sym; if (sym->common_head && sym->common_head != common_head) { gfc_error ("Attempt to indirectly overlap COMMON " "blocks %s and %s by EQUIVALENCE at %C", sym->common_head->name, common_head->name); goto cleanup; } sym->attr.in_common = 1; sym->common_head = common_head; } if (gfc_match_eos () == MATCH_YES) break; if (gfc_match_char (',') != MATCH_YES) { gfc_error ("Expecting a comma in EQUIVALENCE at %C"); goto cleanup; } } return MATCH_YES; syntax: gfc_syntax_error (ST_EQUIVALENCE); cleanup: eq = tail->next; tail->next = NULL; gfc_free_equiv (gfc_current_ns->equiv); gfc_current_ns->equiv = eq; return MATCH_ERROR; } /* Check that a statement function is not recursive. This is done by looking for the statement function symbol(sym) by looking recursively through its expression(e). If a reference to sym is found, true is returned. 12.5.4 requires that any variable of function that is implicitly typed shall have that type confirmed by any subsequent type declaration. The implicit typing is conveniently done here. */ static bool recursive_stmt_fcn (gfc_expr *, gfc_symbol *); static bool check_stmt_fcn (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED) { if (e == NULL) return false; switch (e->expr_type) { case EXPR_FUNCTION: if (e->symtree == NULL) return false; /* Check the name before testing for nested recursion! */ if (sym->name == e->symtree->n.sym->name) return true; /* Catch recursion via other statement functions. */ if (e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION && e->symtree->n.sym->value && recursive_stmt_fcn (e->symtree->n.sym->value, sym)) return true; if (e->symtree->n.sym->ts.type == BT_UNKNOWN) gfc_set_default_type (e->symtree->n.sym, 0, NULL); break; case EXPR_VARIABLE: if (e->symtree && sym->name == e->symtree->n.sym->name) return true; if (e->symtree->n.sym->ts.type == BT_UNKNOWN) gfc_set_default_type (e->symtree->n.sym, 0, NULL); break; default: break; } return false; } static bool recursive_stmt_fcn (gfc_expr *e, gfc_symbol *sym) { return gfc_traverse_expr (e, sym, check_stmt_fcn, 0); } /* Match a statement function declaration. It is so easy to match non-statement function statements with a MATCH_ERROR as opposed to MATCH_NO that we suppress error message in most cases. */ match gfc_match_st_function (void) { gfc_error_buffer old_error; gfc_symbol *sym; gfc_expr *expr; match m; m = gfc_match_symbol (&sym, 0); if (m != MATCH_YES) return m; gfc_push_error (&old_error); if (!gfc_add_procedure (&sym->attr, PROC_ST_FUNCTION, sym->name, NULL)) goto undo_error; if (gfc_match_formal_arglist (sym, 1, 0) != MATCH_YES) goto undo_error; m = gfc_match (" = %e%t", &expr); if (m == MATCH_NO) goto undo_error; gfc_free_error (&old_error); if (m == MATCH_ERROR) return m; if (recursive_stmt_fcn (expr, sym)) { gfc_error ("Statement function at %L is recursive", &expr->where); return MATCH_ERROR; } sym->value = expr; if ((gfc_current_state () == COMP_FUNCTION || gfc_current_state () == COMP_SUBROUTINE) && gfc_state_stack->previous->state == COMP_INTERFACE) { gfc_error ("Statement function at %L cannot appear within an INTERFACE", &expr->where); return MATCH_ERROR; } if (!gfc_notify_std (GFC_STD_F95_OBS, "Statement function at %C")) return MATCH_ERROR; return MATCH_YES; undo_error: gfc_pop_error (&old_error); return MATCH_NO; } /* Match an assignment to a pointer function (F2008). This could, in general be ambiguous with a statement function. In this implementation it remains so if it is the first statement after the specification block. */ match gfc_match_ptr_fcn_assign (void) { gfc_error_buffer old_error; locus old_loc; gfc_symbol *sym; gfc_expr *expr; match m; char name[GFC_MAX_SYMBOL_LEN + 1]; old_loc = gfc_current_locus; m = gfc_match_name (name); if (m != MATCH_YES) return m; gfc_find_symbol (name, NULL, 1, &sym); if (sym && sym->attr.flavor != FL_PROCEDURE) return MATCH_NO; gfc_push_error (&old_error); if (sym && sym->attr.function) goto match_actual_arglist; gfc_current_locus = old_loc; m = gfc_match_symbol (&sym, 0); if (m != MATCH_YES) return m; if (!gfc_add_procedure (&sym->attr, PROC_UNKNOWN, sym->name, NULL)) goto undo_error; match_actual_arglist: gfc_current_locus = old_loc; m = gfc_match (" %e", &expr); if (m != MATCH_YES) goto undo_error; new_st.op = EXEC_ASSIGN; new_st.expr1 = expr; expr = NULL; m = gfc_match (" = %e%t", &expr); if (m != MATCH_YES) goto undo_error; new_st.expr2 = expr; return MATCH_YES; undo_error: gfc_pop_error (&old_error); return MATCH_NO; } /***************** SELECT CASE subroutines ******************/ /* Free a single case structure. */ static void free_case (gfc_case *p) { if (p->low == p->high) p->high = NULL; gfc_free_expr (p->low); gfc_free_expr (p->high); free (p); } /* Free a list of case structures. */ void gfc_free_case_list (gfc_case *p) { gfc_case *q; for (; p; p = q) { q = p->next; free_case (p); } } /* Match a single case selector. Combining the requirements of F08:C830 and F08:C832 (R838) means that the case-value must have either CHARACTER, INTEGER, or LOGICAL type. */ static match match_case_selector (gfc_case **cp) { gfc_case *c; match m; c = gfc_get_case (); c->where = gfc_current_locus; if (gfc_match_char (':') == MATCH_YES) { m = gfc_match_init_expr (&c->high); if (m == MATCH_NO) goto need_expr; if (m == MATCH_ERROR) goto cleanup; if (c->high->ts.type != BT_LOGICAL && c->high->ts.type != BT_INTEGER && c->high->ts.type != BT_CHARACTER) { gfc_error ("Expression in CASE selector at %L cannot be %s", &c->high->where, gfc_typename (&c->high->ts)); goto cleanup; } } else { m = gfc_match_init_expr (&c->low); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto need_expr; if (c->low->ts.type != BT_LOGICAL && c->low->ts.type != BT_INTEGER && c->low->ts.type != BT_CHARACTER) { gfc_error ("Expression in CASE selector at %L cannot be %s", &c->low->where, gfc_typename (&c->low->ts)); goto cleanup; } /* If we're not looking at a ':' now, make a range out of a single target. Else get the upper bound for the case range. */ if (gfc_match_char (':') != MATCH_YES) c->high = c->low; else { m = gfc_match_init_expr (&c->high); if (m == MATCH_ERROR) goto cleanup; /* MATCH_NO is fine. It's OK if nothing is there! */ } } *cp = c; return MATCH_YES; need_expr: gfc_error ("Expected initialization expression in CASE at %C"); cleanup: free_case (c); return MATCH_ERROR; } /* Match the end of a case statement. */ static match match_case_eos (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; match m; if (gfc_match_eos () == MATCH_YES) return MATCH_YES; /* If the case construct doesn't have a case-construct-name, we should have matched the EOS. */ if (!gfc_current_block ()) return MATCH_NO; gfc_gobble_whitespace (); m = gfc_match_name (name); if (m != MATCH_YES) return m; if (strcmp (name, gfc_current_block ()->name) != 0) { gfc_error ("Expected block name %qs of SELECT construct at %C", gfc_current_block ()->name); return MATCH_ERROR; } return gfc_match_eos (); } /* Match a SELECT statement. */ match gfc_match_select (void) { gfc_expr *expr; match m; m = gfc_match_label (); if (m == MATCH_ERROR) return m; m = gfc_match (" select case ( %e )%t", &expr); if (m != MATCH_YES) return m; new_st.op = EXEC_SELECT; new_st.expr1 = expr; return MATCH_YES; } /* Transfer the selector typespec to the associate name. */ static void copy_ts_from_selector_to_associate (gfc_expr *associate, gfc_expr *selector) { gfc_ref *ref; gfc_symbol *assoc_sym; assoc_sym = associate->symtree->n.sym; /* At this stage the expression rank and arrayspec dimensions have not been completely sorted out. We must get the expr2->rank right here, so that the correct class container is obtained. */ ref = selector->ref; while (ref && ref->next) ref = ref->next; if (selector->ts.type == BT_CLASS && CLASS_DATA (selector)->as && ref && ref->type == REF_ARRAY) { /* Ensure that the array reference type is set. We cannot use gfc_resolve_expr at this point, so the usable parts of resolve.c(resolve_array_ref) are employed to do it. */ if (ref->u.ar.type == AR_UNKNOWN) { ref->u.ar.type = AR_ELEMENT; for (int i = 0; i < ref->u.ar.dimen + ref->u.ar.codimen; i++) if (ref->u.ar.dimen_type[i] == DIMEN_RANGE || ref->u.ar.dimen_type[i] == DIMEN_VECTOR || (ref->u.ar.dimen_type[i] == DIMEN_UNKNOWN && ref->u.ar.start[i] && ref->u.ar.start[i]->rank)) { ref->u.ar.type = AR_SECTION; break; } } if (ref->u.ar.type == AR_FULL) selector->rank = CLASS_DATA (selector)->as->rank; else if (ref->u.ar.type == AR_SECTION) selector->rank = ref->u.ar.dimen; else selector->rank = 0; } if (selector->rank) { assoc_sym->attr.dimension = 1; assoc_sym->as = gfc_get_array_spec (); assoc_sym->as->rank = selector->rank; assoc_sym->as->type = AS_DEFERRED; } else assoc_sym->as = NULL; if (selector->ts.type == BT_CLASS) { /* The correct class container has to be available. */ assoc_sym->ts.type = BT_CLASS; assoc_sym->ts.u.derived = CLASS_DATA (selector)->ts.u.derived; assoc_sym->attr.pointer = 1; gfc_build_class_symbol (&assoc_sym->ts, &assoc_sym->attr, &assoc_sym->as); } } /* Push the current selector onto the SELECT TYPE stack. */ static void select_type_push (gfc_symbol *sel) { gfc_select_type_stack *top = gfc_get_select_type_stack (); top->selector = sel; top->tmp = NULL; top->prev = select_type_stack; select_type_stack = top; } /* Set the temporary for the current intrinsic SELECT TYPE selector. */ static gfc_symtree * select_intrinsic_set_tmp (gfc_typespec *ts) { char name[GFC_MAX_SYMBOL_LEN]; gfc_symtree *tmp; int charlen = 0; if (ts->type == BT_CLASS || ts->type == BT_DERIVED) return NULL; if (select_type_stack->selector->ts.type == BT_CLASS && !select_type_stack->selector->attr.class_ok) return NULL; if (ts->type == BT_CHARACTER && ts->u.cl && ts->u.cl->length && ts->u.cl->length->expr_type == EXPR_CONSTANT) charlen = mpz_get_si (ts->u.cl->length->value.integer); if (ts->type != BT_CHARACTER) sprintf (name, "__tmp_%s_%d", gfc_basic_typename (ts->type), ts->kind); else sprintf (name, "__tmp_%s_%d_%d", gfc_basic_typename (ts->type), charlen, ts->kind); gfc_get_sym_tree (name, gfc_current_ns, &tmp, false); gfc_add_type (tmp->n.sym, ts, NULL); /* Copy across the array spec to the selector. */ if (select_type_stack->selector->ts.type == BT_CLASS && (CLASS_DATA (select_type_stack->selector)->attr.dimension || CLASS_DATA (select_type_stack->selector)->attr.codimension)) { tmp->n.sym->attr.pointer = 1; tmp->n.sym->attr.dimension = CLASS_DATA (select_type_stack->selector)->attr.dimension; tmp->n.sym->attr.codimension = CLASS_DATA (select_type_stack->selector)->attr.codimension; tmp->n.sym->as = gfc_copy_array_spec (CLASS_DATA (select_type_stack->selector)->as); } gfc_set_sym_referenced (tmp->n.sym); gfc_add_flavor (&tmp->n.sym->attr, FL_VARIABLE, name, NULL); tmp->n.sym->attr.select_type_temporary = 1; return tmp; } /* Set up a temporary for the current TYPE IS / CLASS IS branch . */ static void select_type_set_tmp (gfc_typespec *ts) { char name[GFC_MAX_SYMBOL_LEN]; gfc_symtree *tmp = NULL; if (!ts) { select_type_stack->tmp = NULL; return; } tmp = select_intrinsic_set_tmp (ts); if (tmp == NULL) { if (!ts->u.derived) return; if (ts->type == BT_CLASS) sprintf (name, "__tmp_class_%s", ts->u.derived->name); else sprintf (name, "__tmp_type_%s", ts->u.derived->name); gfc_get_sym_tree (name, gfc_current_ns, &tmp, false); gfc_add_type (tmp->n.sym, ts, NULL); if (select_type_stack->selector->ts.type == BT_CLASS && select_type_stack->selector->attr.class_ok) { tmp->n.sym->attr.pointer = CLASS_DATA (select_type_stack->selector)->attr.class_pointer; /* Copy across the array spec to the selector. */ if (CLASS_DATA (select_type_stack->selector)->attr.dimension || CLASS_DATA (select_type_stack->selector)->attr.codimension) { tmp->n.sym->attr.dimension = CLASS_DATA (select_type_stack->selector)->attr.dimension; tmp->n.sym->attr.codimension = CLASS_DATA (select_type_stack->selector)->attr.codimension; tmp->n.sym->as = gfc_copy_array_spec (CLASS_DATA (select_type_stack->selector)->as); } } gfc_set_sym_referenced (tmp->n.sym); gfc_add_flavor (&tmp->n.sym->attr, FL_VARIABLE, name, NULL); tmp->n.sym->attr.select_type_temporary = 1; if (ts->type == BT_CLASS) gfc_build_class_symbol (&tmp->n.sym->ts, &tmp->n.sym->attr, &tmp->n.sym->as); } /* Add an association for it, so the rest of the parser knows it is an associate-name. The target will be set during resolution. */ tmp->n.sym->assoc = gfc_get_association_list (); tmp->n.sym->assoc->dangling = 1; tmp->n.sym->assoc->st = tmp; select_type_stack->tmp = tmp; } /* Match a SELECT TYPE statement. */ match gfc_match_select_type (void) { gfc_expr *expr1, *expr2 = NULL; match m; char name[GFC_MAX_SYMBOL_LEN]; bool class_array; gfc_symbol *sym; gfc_namespace *ns = gfc_current_ns; m = gfc_match_label (); if (m == MATCH_ERROR) return m; m = gfc_match (" select type ( "); if (m != MATCH_YES) return m; gfc_current_ns = gfc_build_block_ns (ns); m = gfc_match (" %n => %e", name, &expr2); if (m == MATCH_YES) { expr1 = gfc_get_expr (); expr1->expr_type = EXPR_VARIABLE; expr1->where = expr2->where; if (gfc_get_sym_tree (name, NULL, &expr1->symtree, false)) { m = MATCH_ERROR; goto cleanup; } sym = expr1->symtree->n.sym; if (expr2->ts.type == BT_UNKNOWN) sym->attr.untyped = 1; else copy_ts_from_selector_to_associate (expr1, expr2); sym->attr.flavor = FL_VARIABLE; sym->attr.referenced = 1; sym->attr.class_ok = 1; } else { m = gfc_match (" %e ", &expr1); if (m != MATCH_YES) { std::swap (ns, gfc_current_ns); gfc_free_namespace (ns); return m; } } m = gfc_match (" )%t"); if (m != MATCH_YES) { gfc_error ("parse error in SELECT TYPE statement at %C"); goto cleanup; } /* This ghastly expression seems to be needed to distinguish a CLASS array, which can have a reference, from other expressions that have references, such as derived type components, and are not allowed by the standard. TODO: see if it is sufficient to exclude component and substring references. */ class_array = (expr1->expr_type == EXPR_VARIABLE && expr1->ts.type == BT_CLASS && CLASS_DATA (expr1) && (strcmp (CLASS_DATA (expr1)->name, "_data") == 0) && (CLASS_DATA (expr1)->attr.dimension || CLASS_DATA (expr1)->attr.codimension) && expr1->ref && expr1->ref->type == REF_ARRAY && expr1->ref->next == NULL); /* Check for F03:C811. */ if (!expr2 && (expr1->expr_type != EXPR_VARIABLE || (!class_array && expr1->ref != NULL))) { gfc_error ("Selector in SELECT TYPE at %C is not a named variable; " "use associate-name=>"); m = MATCH_ERROR; goto cleanup; } new_st.op = EXEC_SELECT_TYPE; new_st.expr1 = expr1; new_st.expr2 = expr2; new_st.ext.block.ns = gfc_current_ns; select_type_push (expr1->symtree->n.sym); gfc_current_ns = ns; return MATCH_YES; cleanup: gfc_free_expr (expr1); gfc_free_expr (expr2); gfc_undo_symbols (); std::swap (ns, gfc_current_ns); gfc_free_namespace (ns); return m; } /* Match a CASE statement. */ match gfc_match_case (void) { gfc_case *c, *head, *tail; match m; head = tail = NULL; if (gfc_current_state () != COMP_SELECT) { gfc_error ("Unexpected CASE statement at %C"); return MATCH_ERROR; } if (gfc_match ("% default") == MATCH_YES) { m = match_case_eos (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; new_st.op = EXEC_SELECT; c = gfc_get_case (); c->where = gfc_current_locus; new_st.ext.block.case_list = c; return MATCH_YES; } if (gfc_match_char ('(') != MATCH_YES) goto syntax; for (;;) { if (match_case_selector (&c) == MATCH_ERROR) goto cleanup; if (head == NULL) head = c; else tail->next = c; tail = c; if (gfc_match_char (')') == MATCH_YES) break; if (gfc_match_char (',') != MATCH_YES) goto syntax; } m = match_case_eos (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; new_st.op = EXEC_SELECT; new_st.ext.block.case_list = head; return MATCH_YES; syntax: gfc_error ("Syntax error in CASE specification at %C"); cleanup: gfc_free_case_list (head); /* new_st is cleaned up in parse.c. */ return MATCH_ERROR; } /* Match a TYPE IS statement. */ match gfc_match_type_is (void) { gfc_case *c = NULL; match m; if (gfc_current_state () != COMP_SELECT_TYPE) { gfc_error ("Unexpected TYPE IS statement at %C"); return MATCH_ERROR; } if (gfc_match_char ('(') != MATCH_YES) goto syntax; c = gfc_get_case (); c->where = gfc_current_locus; m = gfc_match_type_spec (&c->ts); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_char (')') != MATCH_YES) goto syntax; m = match_case_eos (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; new_st.op = EXEC_SELECT_TYPE; new_st.ext.block.case_list = c; if (c->ts.type == BT_DERIVED && c->ts.u.derived && (c->ts.u.derived->attr.sequence || c->ts.u.derived->attr.is_bind_c)) { gfc_error ("The type-spec shall not specify a sequence derived " "type or a type with the BIND attribute in SELECT " "TYPE at %C [F2003:C815]"); return MATCH_ERROR; } /* Create temporary variable. */ select_type_set_tmp (&c->ts); return MATCH_YES; syntax: gfc_error ("Syntax error in TYPE IS specification at %C"); cleanup: if (c != NULL) gfc_free_case_list (c); /* new_st is cleaned up in parse.c. */ return MATCH_ERROR; } /* Match a CLASS IS or CLASS DEFAULT statement. */ match gfc_match_class_is (void) { gfc_case *c = NULL; match m; if (gfc_current_state () != COMP_SELECT_TYPE) return MATCH_NO; if (gfc_match ("% default") == MATCH_YES) { m = match_case_eos (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; new_st.op = EXEC_SELECT_TYPE; c = gfc_get_case (); c->where = gfc_current_locus; c->ts.type = BT_UNKNOWN; new_st.ext.block.case_list = c; select_type_set_tmp (NULL); return MATCH_YES; } m = gfc_match ("% is"); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_char ('(') != MATCH_YES) goto syntax; c = gfc_get_case (); c->where = gfc_current_locus; m = match_derived_type_spec (&c->ts); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (c->ts.type == BT_DERIVED) c->ts.type = BT_CLASS; if (gfc_match_char (')') != MATCH_YES) goto syntax; m = match_case_eos (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; new_st.op = EXEC_SELECT_TYPE; new_st.ext.block.case_list = c; /* Create temporary variable. */ select_type_set_tmp (&c->ts); return MATCH_YES; syntax: gfc_error ("Syntax error in CLASS IS specification at %C"); cleanup: if (c != NULL) gfc_free_case_list (c); /* new_st is cleaned up in parse.c. */ return MATCH_ERROR; } /********************* WHERE subroutines ********************/ /* Match the rest of a simple WHERE statement that follows an IF statement. */ static match match_simple_where (void) { gfc_expr *expr; gfc_code *c; match m; m = gfc_match (" ( %e )", &expr); if (m != MATCH_YES) return m; m = gfc_match_assignment (); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_eos () != MATCH_YES) goto syntax; c = gfc_get_code (EXEC_WHERE); c->expr1 = expr; c->next = XCNEW (gfc_code); *c->next = new_st; c->next->loc = gfc_current_locus; gfc_clear_new_st (); new_st.op = EXEC_WHERE; new_st.block = c; return MATCH_YES; syntax: gfc_syntax_error (ST_WHERE); cleanup: gfc_free_expr (expr); return MATCH_ERROR; } /* Match a WHERE statement. */ match gfc_match_where (gfc_statement *st) { gfc_expr *expr; match m0, m; gfc_code *c; m0 = gfc_match_label (); if (m0 == MATCH_ERROR) return m0; m = gfc_match (" where ( %e )", &expr); if (m != MATCH_YES) return m; if (gfc_match_eos () == MATCH_YES) { *st = ST_WHERE_BLOCK; new_st.op = EXEC_WHERE; new_st.expr1 = expr; return MATCH_YES; } m = gfc_match_assignment (); if (m == MATCH_NO) gfc_syntax_error (ST_WHERE); if (m != MATCH_YES) { gfc_free_expr (expr); return MATCH_ERROR; } /* We've got a simple WHERE statement. */ *st = ST_WHERE; c = gfc_get_code (EXEC_WHERE); c->expr1 = expr; /* Put in the assignment. It will not be processed by add_statement, so we need to copy the location here. */ c->next = XCNEW (gfc_code); *c->next = new_st; c->next->loc = gfc_current_locus; gfc_clear_new_st (); new_st.op = EXEC_WHERE; new_st.block = c; return MATCH_YES; } /* Match an ELSEWHERE statement. We leave behind a WHERE node in new_st if successful. */ match gfc_match_elsewhere (void) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_expr *expr; match m; if (gfc_current_state () != COMP_WHERE) { gfc_error ("ELSEWHERE statement at %C not enclosed in WHERE block"); return MATCH_ERROR; } expr = NULL; if (gfc_match_char ('(') == MATCH_YES) { m = gfc_match_expr (&expr); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) return MATCH_ERROR; if (gfc_match_char (')') != MATCH_YES) goto syntax; } if (gfc_match_eos () != MATCH_YES) { /* Only makes sense if we have a where-construct-name. */ if (!gfc_current_block ()) { m = MATCH_ERROR; goto cleanup; } /* Better be a name at this point. */ m = gfc_match_name (name); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; if (gfc_match_eos () != MATCH_YES) goto syntax; if (strcmp (name, gfc_current_block ()->name) != 0) { gfc_error ("Label %qs at %C doesn't match WHERE label %qs", name, gfc_current_block ()->name); goto cleanup; } } new_st.op = EXEC_WHERE; new_st.expr1 = expr; return MATCH_YES; syntax: gfc_syntax_error (ST_ELSEWHERE); cleanup: gfc_free_expr (expr); return MATCH_ERROR; }
tak1827/wavelet
cmd/benchmark/flood.go
// Copyright (c) 2019 Perlin // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package main import ( "github.com/perlin-network/wavelet" "github.com/perlin-network/wavelet/sys" "github.com/perlin-network/wavelet/wctl" "github.com/pkg/errors" ) func floodTransactions(numWorkers int) func(client *wctl.Client) ([]*wctl.TxResponse, error) { return func(client *wctl.Client) ([]*wctl.TxResponse, error) { chRes := make(chan *wctl.TxResponse, numWorkers) chErr := make(chan error, numWorkers) for i := 0; i < numWorkers; i++ { go sendTransaction(i+1, client, chRes, chErr) } var responses []*wctl.TxResponse var err error for i := 0; i < numWorkers; i++ { if e := <-chErr; e != nil { if err == nil { err = e } else { err = errors.Wrap(err, e.Error()) } } responses = append(responses, <-chRes) } return responses, err } } func sendTransaction( i int, client *wctl.Client, chRes chan<- *wctl.TxResponse, chErr chan<- error, ) { n := 1 payload := wavelet.Batch{ Tags: make([]uint8, 0, n), Payloads: make([][]byte, 0, n), } //transfer := wavelet.Transfer{Recipient: client.PublicKey, Amount: uint64(1)} stake := wavelet.Stake{Opcode: sys.PlaceStake, Amount: uint64(i)} for i := 0; i < n; i++ { if err := payload.AddStake(stake); err != nil { panic(err) } } marshaled, err := payload.Marshal() if err != nil { panic(err) } res, err := client.SendTransaction(byte(sys.TagBatch), marshaled) if err != nil { chRes <- res chErr <- err return } chRes <- res chErr <- err }
IntellectEU/catalyst-bootstrap
catalyst-generator/src/main/resources/templates/usecase/mqtt/test/DemoApplicationTests.java
<reponame>IntellectEU/catalyst-bootstrap {{=<% %>=}} <%license%> package <%fullPackageName%>; import static <%packageName%>.Router.HOST; import static <%packageName%>.Router.TOPIC_NAME; import <%packageName%>.model.CarData; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.CamelSpringBootRunner; import org.apache.camel.test.spring.UseAdviceWith; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.testcontainers.containers.GenericContainer; @RunWith(CamelSpringBootRunner.class) @SpringBootTest @UseAdviceWith public class DemoApplicationTests { @ClassRule public static GenericContainer mosquitto = new GenericContainer("eclipse-mosquitto") .withExposedPorts(1883); String mosquittoUrl; private ObjectMapper objectMapper = new ObjectMapper(); @EndpointInject(uri = "mock:result") MockEndpoint mockResult; @Autowired CamelContext camelContext; @Autowired ProducerTemplate producerTemplate; @Before public void init() throws Exception { mosquitto.start(); mosquittoUrl = "tcp://" + mosquitto.getContainerIpAddress() + ":" + mosquitto.getMappedPort(1883); camelContext.getRouteDefinition("toMqttRoute").adviceWith(camelContext, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("direct:in"); weaveByToUri("mqtt:mosquitoTo?host=tcp://" + HOST + "&publishTopicName=" + TOPIC_NAME) .replace().to("mqtt:testTo?host=" + mosquittoUrl + "&publishTopicName=carData"); weaveById("fillMqttProcessor").remove(); } }); camelContext.getRouteDefinition("fromMqttRoute").adviceWith(camelContext, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("mqtt:testFrom?host=" + mosquittoUrl + "&subscribeTopicNames=carData"); } }); camelContext.start(); } @Test public void runTest() throws Exception { List<CarData> list = new ArrayList<>(); list.add(new CarData(1, 228)); String listInJson = objectMapper.writeValueAsString(list); producerTemplate.sendBody("direct:in", listInJson); mockResult.expectedMessageCount(1); mockResult.message(0).body().isEqualTo(listInJson); mockResult.assertIsSatisfied(); } @After public void destroy() throws Exception { camelContext.stop(); } }
fernandocamargo/future
src/hooks/services/expertlead/city/constants.js
export const URL = '/city';
MikeMajara/fastboard.io.front
src/components/BoardLeave/index.js
export { default } from './BoardLeave';
EyeOfDarkness/Arc
arc-core/src/arc/audio/AudioFilter.java
<filename>arc-core/src/arc/audio/AudioFilter.java package arc.audio; public abstract class AudioFilter{ protected long handle; protected AudioFilter(long handle){ this.handle = handle; } }
FreCap/sql
legacy/src/test/java/com/amazon/opendistroforelasticsearch/sql/legacy/util/SqlExplainUtils.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.legacy.util; import com.alibaba.druid.sql.parser.ParserException; import com.amazon.opendistroforelasticsearch.sql.legacy.exception.SqlParseException; import com.amazon.opendistroforelasticsearch.sql.legacy.query.ESActionFactory; import com.amazon.opendistroforelasticsearch.sql.legacy.query.QueryAction; import org.elasticsearch.client.Client; import org.mockito.Mockito; import java.sql.SQLFeatureNotSupportedException; /** * Test utils class that explains a query */ public class SqlExplainUtils { public static String explain(String query) { try { Client mockClient = Mockito.mock(Client.class); CheckScriptContents.stubMockClient(mockClient); QueryAction queryAction = ESActionFactory.create(mockClient, query); return queryAction.explain().explain(); } catch (SqlParseException | SQLFeatureNotSupportedException e) { throw new ParserException("Illegal sql expr in: " + query); } } private SqlExplainUtils() {} }
ethanwood17/code-gov-front-end
src/components/menu/subcomponents/search-box-dropdown/search-box-dropdown.container.test.js
<filename>src/components/menu/subcomponents/search-box-dropdown/search-box-dropdown.container.test.js import { push } from 'connected-react-router' import hideSearchDropdown from 'actions/hide-search-dropdown' import updateSearchParams from 'actions/update-search-params' import { getSection } from 'utils/url-parsing' import { mapStateToProps, mapDispatchToProps } from 'components/menu/subcomponents/search-box-dropdown/search-box-dropdown.container' jest.mock('connected-react-router') jest.mock('actions/hide-search-dropdown') jest.mock('actions/update-search-params') jest.mock('utils/url-parsing') const props = { searchDropdown: 'test-search-dropdown', } const dispatch = jest.fn() // helper function to test `onSubmit` function dispatches correct action based off section const testOnSubmit = ({ section, query, action, expected }) => { getSection.mockImplementation(() => section) mapDispatchToProps(dispatch).onSubmit(query) expect(dispatch).toBeCalled() expect(action).toBeCalledWith(expected) } describe('containers - Menu - SearchBoxDropdown', () => { describe('mapStateToProps', () => { it('should return the correct properties', () => { expect(mapStateToProps(props)).toMatchSnapshot() }) }) describe('mapDispatchToProps', () => { describe('hideSearchDropdown', () => { it('should dispatch the `hideSearchDropdown` action', () => { mapDispatchToProps(dispatch).hideSearchDropdown() expect(dispatch).toBeCalled() expect(hideSearchDropdown).toBeCalled() }) }) describe('onSubmit', () => { it('should dispatch the `hideSearchDropdown` action', () => { mapDispatchToProps(dispatch).onSubmit('test-query') expect(dispatch).toBeCalled() expect(hideSearchDropdown).toBeCalled() }) describe('section is `search`', () => { it('should dispatch the `updateSearchParams` action with the correct params', () => { const expected = { page: 1, query: 'test-query', filters: [] } testOnSubmit({ section: 'search', query: 'test-query', action: updateSearchParams, expected }) }) }) describe('section is not `search`', () => { it('should dispatch the `updateSearchParams` action with the correct params', () => { const expected = { page: 1, query: 'test-query', size: 10, sort: 'best_match', filters: [] } testOnSubmit({ section: 'not-search', query: 'test-query', action: updateSearchParams, expected }) }) it('should dispatch the action to `push` to the correct page', () => { const expected = `/search?page=1&query=test-query&size=10&sort=best_match` testOnSubmit({ section: 'not-search', query: 'test-query', action: push, expected }) }) }) }) }) })
Sukora-Stas/JavaRushTasks
2.JavaCore/src/com/javarush/task/task19/task1909/Solution.java
<filename>2.JavaCore/src/com/javarush/task/task19/task1909/Solution.java<gh_stars>1-10 package com.javarush.task.task19.task1909; /* Замена знаков */ import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader conReader = new BufferedReader(new InputStreamReader(System.in)); String fileName1 = conReader.readLine(); String fileName2 = conReader.readLine(); conReader.close(); BufferedReader fileReader = new BufferedReader(new FileReader(fileName1)); BufferedWriter fileWriter = new BufferedWriter(new FileWriter(fileName2)); while (fileReader.ready()) { String s = fileReader.readLine(); fileWriter.write(s.replace('.','!')); } fileWriter.close(); fileReader.close(); } }
fumiphys/programming_contest
tree/src/heavy_light_decomposition.cpp
<gh_stars>1-10 /* * Heavy Light Decomposition */ #include <cassert> #include <iostream> #include "../heavy_light_decomposition.hpp" using namespace std; int main(int argc, char *argv[]) { cout << "-- test for heavy light decomposition start --" << endl; HeavyLightDecomposition<int> hld(8); hld.adde(0, 1, 1); hld.adde(0, 5, 1); hld.adde(1, 2, 1); hld.adde(1, 3, 1); hld.adde(3, 4, 1); hld.adde(5, 6, 1); hld.adde(6, 7, 1); hld.build(); assert(hld.lca(1, 5) == 0); assert(hld.lca(2, 4) == 1); assert(hld.lca(1, 7) == 0); assert(hld.lca(5, 7) == 5); cout << "-- test for heavy light decomposition end: Success --" << endl; return 0; }
rio-31/android_frameworks_base-1
core/tests/coretests/src/android/content/ContentProviderTest.java
/* * Copyright (C) 2018 The Android Open Source Project * * 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 android.content; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; import android.content.pm.ApplicationInfo; import android.content.pm.ProviderInfo; import android.net.Uri; import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; @RunWith(AndroidJUnit4.class) public class ContentProviderTest { private Context mContext; private ContentProvider mCp; private ApplicationInfo mProviderApp; private ProviderInfo mProvider; @Before public void setUp() { mProviderApp = new ApplicationInfo(); mProviderApp.uid = 10001; mProvider = new ProviderInfo(); mProvider.authority = "com.example"; mProvider.applicationInfo = mProviderApp; mContext = mock(Context.class); mCp = mock(ContentProvider.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); mCp.attachInfo(mContext, mProvider); } @Test public void testValidateIncomingUri_Normal() throws Exception { assertEquals(Uri.parse("content://com.example/"), mCp.validateIncomingUri(Uri.parse("content://com.example/"))); assertEquals(Uri.parse("content://com.example/foo/bar"), mCp.validateIncomingUri(Uri.parse("content://com.example/foo/bar"))); assertEquals(Uri.parse("content://com.example/foo%2Fbar"), mCp.validateIncomingUri(Uri.parse("content://com.example/foo%2Fbar"))); assertEquals(Uri.parse("content://com.example/foo%2F%2Fbar"), mCp.validateIncomingUri(Uri.parse("content://com.example/foo%2F%2Fbar"))); } @Test public void testValidateIncomingUri_Shady() throws Exception { assertEquals(Uri.parse("content://com.example/"), mCp.validateIncomingUri(Uri.parse("content://com.example//"))); assertEquals(Uri.parse("content://com.example/foo/bar/"), mCp.validateIncomingUri(Uri.parse("content://com.example//foo//bar//"))); assertEquals(Uri.parse("content://com.example/foo/bar/"), mCp.validateIncomingUri(Uri.parse("content://com.example/foo///bar/"))); assertEquals(Uri.parse("content://com.example/foo%2F%2Fbar/baz"), mCp.validateIncomingUri(Uri.parse("content://com.example/foo%2F%2Fbar//baz"))); } @Test public void testValidateIncomingUri_NonPath() throws Exception { // We only touch paths; queries and fragments are left intact assertEquals(Uri.parse("content://com.example/foo/bar?foo=b//ar#foo=b//ar"), mCp.validateIncomingUri( Uri.parse("content://com.example/foo/bar?foo=b//ar#foo=b//ar"))); } }
AsahiOS/gate
usr/src/uts/common/sys/user.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Copyright (c) 2018, Joyent, Inc. */ #ifndef _SYS_USER_H #define _SYS_USER_H #include <sys/types.h> #include <sys/signal.h> #ifdef __cplusplus extern "C" { #endif /* * struct exdata is visible in and out of the kernel. This is because it * is referenced in <sys/core.h> which doesn't have this kind of magic. */ struct exdata { struct vnode *vp; size_t ux_tsize; /* text size */ size_t ux_dsize; /* data size */ size_t ux_bsize; /* bss size */ size_t ux_lsize; /* lib size */ long ux_nshlibs; /* number of shared libs needed */ short ux_mach; /* machine type */ short ux_mag; /* magic number MUST be here */ off_t ux_toffset; /* file offset to raw text */ off_t ux_doffset; /* file offset to raw data */ off_t ux_loffset; /* file offset to lib sctn */ caddr_t ux_txtorg; /* start addr of text in mem */ caddr_t ux_datorg; /* start addr of data in mem */ caddr_t ux_entloc; /* entry location */ }; #ifdef __cplusplus } #endif #if defined(_KERNEL) || defined(_KMEMUSER) #include <sys/param.h> #include <sys/pcb.h> #include <sys/siginfo.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/auxv.h> #include <sys/errno.h> #include <sys/t_lock.h> #include <sys/refstr.h> #ifdef __cplusplus extern "C" { #endif /* * File Descriptor assignment generation. * * Certain file descriptor consumers (namely epoll) need to be able to detect * when the resource underlying an fd change due to (re)assignment. Checks * comparing old and new file_t pointers work OK, but could easily be fooled by * an entry freed-to and reused-from the cache. To better detect such * assingments, a generation number is kept in the uf_entry. Whenever a * non-NULL file_t is assigned to the entry, the generation is incremented, * indicating the change. There is a minute possibility that a rollover of the * value could cause assigments to evade detection by consumers, but it is * considered acceptably small. */ typedef uint_t uf_entry_gen_t; /* * Entry in the per-process list of open files. * Note: only certain fields are copied in flist_grow() and flist_fork(). * This is indicated in brackets in the structure member comments. */ typedef struct uf_entry { kmutex_t uf_lock; /* per-fd lock [never copied] */ struct file *uf_file; /* file pointer [grow, fork] */ struct fpollinfo *uf_fpollinfo; /* poll state [grow] */ int uf_refcnt; /* LWPs accessing this file [grow] */ int uf_alloc; /* right subtree allocs [grow, fork] */ short uf_flag; /* fcntl F_GETFD flags [grow, fork] */ short uf_busy; /* file is allocated [grow, fork] */ kcondvar_t uf_wanted_cv; /* waiting for setf() [never copied] */ kcondvar_t uf_closing_cv; /* waiting for close() [never copied] */ struct portfd *uf_portfd; /* associated with port [grow] */ uf_entry_gen_t uf_gen; /* assigned fd generation [grow,fork] */ /* Avoid false sharing - pad to coherency granularity (64 bytes) */ char uf_pad[64 - sizeof (kmutex_t) - 2 * sizeof (void*) - 2 * sizeof (int) - 2 * sizeof (short) - 2 * sizeof (kcondvar_t) - sizeof (struct portfd *) - sizeof (uf_entry_gen_t)]; } uf_entry_t; /* * Retired file lists -- see flist_grow() for details. */ typedef struct uf_rlist { struct uf_rlist *ur_next; uf_entry_t *ur_list; int ur_nfiles; } uf_rlist_t; /* * Per-process file information. */ typedef struct uf_info { kmutex_t fi_lock; /* see below */ int fi_badfd; /* bad file descriptor # */ int fi_action; /* action to take on bad fd use */ int fi_nfiles; /* number of entries in fi_list[] */ uf_entry_t *volatile fi_list; /* current file list */ uf_rlist_t *fi_rlist; /* retired file lists */ } uf_info_t; /* * File list locking. * * Each process has a list of open files, fi_list, indexed by fd. * fi_list is an array of uf_entry_t structures, each with its own lock. * One might think that the correct way to lock a file descriptor would be: * * ufp = fip->fi_list[fd]; * mutex_enter(&ufp->uf_lock); * * However, that construct is only safe if fi_lock is already held. If not, * fi_list can change in the window between loading ufp and entering uf_lock. * The UF_ENTER() macro deals with this possibility. UF_ENTER(ufp, fip, fd) * locks fd and sets ufp to fd's uf_entry. The locking rules are as follows: * * (1) fi_lock protects fi_list and fi_nfiles. It also protects the * uf_alloc and uf_busy fields of every fd's ufp; see fd_find() for * details on file descriptor allocation. * * (2) UF_ENTER(ufp, fip, fd) locks descriptor fd and sets ufp to point * to the uf_entry_t for fd. UF_ENTER() protects all fields in ufp * except uf_alloc and uf_busy. UF_ENTER(ufp, fip, fd) also prevents * ufp->uf_alloc, ufp->uf_busy, fip->fi_list and fip->fi_nfiles from * changing. * * (3) The lock ordering is (1), (2). * * (4) Note that fip->fi_list and fip->fi_nfiles cannot change while *any* * file list lock is held. Thus flist_grow() must acquire all such * locks -- fi_lock and every fd's uf_lock -- to install a new file list. */ #define UF_ENTER(ufp, fip, fd) \ for (;;) { \ uf_entry_t *_flist = (fip)->fi_list; \ ufp = &_flist[fd]; \ ASSERT((fd) < (fip)->fi_nfiles); \ mutex_enter(&ufp->uf_lock); \ if (_flist == (fip)->fi_list) \ break; \ mutex_exit(&ufp->uf_lock); \ } #define UF_EXIT(ufp) mutex_exit(&ufp->uf_lock) #define PSARGSZ 80 /* Space for exec arguments (used by ps(1)) */ #define MAXCOMLEN 16 /* <= MAXNAMLEN, >= sizeof (ac_comm) */ typedef struct { /* kernel syscall set type */ uint_t word[9]; /* space for syscall numbers [1..288] */ } k_sysset_t; /* * __KERN_NAUXV_IMPL is defined as a convenience sizing mechanism * for the portions of the kernel that care about aux vectors. * * Applications that need to know how many aux vectors the kernel * supplies should use the proc(4) interface to read /proc/PID/auxv. * * This value should not be changed in a patch. */ #if defined(__sparc) #define __KERN_NAUXV_IMPL 20 #elif defined(__i386) || defined(__amd64) #define __KERN_NAUXV_IMPL 25 #endif struct execsw; /* * The user structure; one allocated per process. Contains all the * per-process data that doesn't need to be referenced while the * process is swapped. */ typedef struct user { /* * These fields are initialized at process creation time and never * modified. They can be accessed without acquiring locks. */ struct execsw *u_execsw; /* pointer to exec switch entry */ auxv_t u_auxv[__KERN_NAUXV_IMPL]; /* aux vector from exec */ timestruc_t u_start; /* hrestime at process start */ clock_t u_ticks; /* lbolt at process start */ char u_comm[MAXCOMLEN + 1]; /* executable file name from exec */ char u_psargs[PSARGSZ]; /* arguments from exec */ int u_argc; /* value of argc passed to main() */ uintptr_t u_argv; /* value of argv passed to main() */ uintptr_t u_envp; /* value of envp passed to main() */ uintptr_t u_commpagep; /* address of mapped comm page */ /* * These fields are protected by p_lock: */ struct vnode *u_cdir; /* current directory */ struct vnode *u_rdir; /* root directory */ uint64_t u_mem; /* accumulated memory usage */ size_t u_mem_max; /* peak RSS (K) */ mode_t u_cmask; /* mask for file creation */ char u_acflag; /* accounting flag */ char u_systrap; /* /proc: any syscall mask bits set? */ refstr_t *u_cwd; /* cached string for cwd */ k_sysset_t u_entrymask; /* /proc syscall stop-on-entry mask */ k_sysset_t u_exitmask; /* /proc syscall stop-on-exit mask */ k_sigset_t u_signodefer; /* signals defered when caught */ k_sigset_t u_sigonstack; /* signals taken on alternate stack */ k_sigset_t u_sigresethand; /* signals reset when caught */ k_sigset_t u_sigrestart; /* signals that restart system calls */ k_sigset_t u_sigmask[MAXSIG]; /* signals held while in catcher */ void (*u_signal[MAXSIG])(); /* Disposition of signals */ /* * Resource controls provide the backend for process resource limits, * the interfaces for which are maintained for compatibility. To * preserve the behaviour associated with the RLIM_SAVED_CUR and * RLIM_SAVED_MAX tokens, we retain the "saved" rlimits. */ struct rlimit64 u_saved_rlimit[RLIM_NSAVED]; uf_info_t u_finfo; /* open file information */ } user_t; #include <sys/proc.h> /* cannot include before user defined */ #ifdef _KERNEL #define P_FINFO(p) (&(p)->p_user.u_finfo) #endif /* _KERNEL */ #ifdef __cplusplus } #endif #else /* defined(_KERNEL) || defined(_KMEMUSER) */ /* * Here, we define a fake version of struct user for programs * (debuggers) that use ptrace() to read and modify the saved * registers directly in the u-area. ptrace() has been removed * from the operating system and now exists as a library function * in libc, built on the /proc process filesystem. The ptrace() * library function provides access only to the members of the * fake struct user defined here. * * User-level programs that must know the real contents of struct * user will have to define _KMEMUSER before including <sys/user.h>. * Such programs also become machine specific. Carefully consider * the consequences of your actions. */ #include <sys/regset.h> #ifdef __cplusplus extern "C" { #endif #define PSARGSZ 80 /* Space for exec arguments (used by ps(1)) */ typedef struct user { gregset_t u_reg; /* user's saved registers */ greg_t *u_ar0; /* address of user's saved R0 */ char u_psargs[PSARGSZ]; /* arguments from exec */ void (*u_signal[MAXSIG])(); /* Disposition of signals */ int u_code; /* fault code on trap */ caddr_t u_addr; /* fault PC on trap */ } user_t; #ifdef __cplusplus } #endif #endif /* defined(_KERNEL) || defined(_KMEMUSER) */ #endif /* _SYS_USER_H */
isabella232/feedbunch
FeedBunch-app/db/migrate/20140519123128_add_user_id_unread_entries_index_to_feed_subscriptions.rb
<gh_stars>10-100 class AddUserIdUnreadEntriesIndexToFeedSubscriptions < ActiveRecord::Migration[5.2] def change add_index :feed_subscriptions, [:user_id, :unread_entries], name: 'index_feed_subscriptions_on_user_id_unread_entries' end end
PacktPublishing/Modernizing-Enterprise-CMS-using-Pimcore
4. Creating documentes in Pimcore/tmp/vendor/pimcore/pimcore/bundles/AdminBundle/Resources/public/js/pimcore/object/tags/image.js
/** * Pimcore * * This source file is available under two different licenses: * - GNU General Public License version 3 (GPLv3) * - Pimcore Enterprise License (PEL) * Full copyright and license information is available in * LICENSE.md which is distributed with this source code. * * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org) * @license http://www.pimcore.org/license GPLv3 and PEL */ pimcore.registerNS("pimcore.object.tags.image"); pimcore.object.tags.image = Class.create(pimcore.object.tags.abstract, { type: "image", dirty: false, initialize: function (data, fieldConfig) { if (data) { this.data = data; } else { this.data = {}; } this.fieldConfig = fieldConfig; }, getGridColumnConfig: function (field, forGridConfigPreview) { return { text: t(field.label), width: 100, sortable: false, dataIndex: field.key, getEditor: this.getWindowCellEditor.bind(this, field), renderer: function (key, value, metaData, record, rowIndex, colIndex, store, view) { this.applyPermissionStyle(key, value, metaData, record); if (record.data.inheritedFields && record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) { metaData.tdCls += " grid_value_inherited"; } if (value && value.id) { if (forGridConfigPreview) { var params = { id: value.id, width: 88, height: 20, frame: true }; var path = Routing.generate('pimcore_admin_asset_getimagethumbnail', params); return '<img src="'+path+'" />'; } var params = { id: value.id, width: 88, height: 88, frame: true }; var path = Routing.generate('pimcore_admin_asset_getimagethumbnail', params); return '<img src="'+path+'" style="width:88px; height:88px;" />'; } }.bind(this, field.key) }; }, getLayoutEdit: function () { if (intval(this.fieldConfig.width) < 1) { this.fieldConfig.width = 300; } if (intval(this.fieldConfig.height) < 1) { this.fieldConfig.height = 300; } var conf = { width: this.fieldConfig.width, height: this.fieldConfig.height, border: true, style: "padding-bottom: 10px", tbar: { overflowHandler: 'menu', items: [{ xtype: "tbspacer", width: 48, height: 24, cls: "pimcore_icon_droptarget_upload" }, { xtype: "tbtext", text: "<b>" + this.fieldConfig.title + "</b>" }, "->", { xtype: "button", iconCls: "pimcore_icon_upload", overflowText: t("upload"), cls: "pimcore_inline_upload", handler: this.uploadDialog.bind(this) }, { xtype: "button", iconCls: "pimcore_icon_open", overflowText: t("open"), handler: this.openImage.bind(this) }, { xtype: "button", iconCls: "pimcore_icon_delete", overflowText: t("delete"), handler: this.empty.bind(this) }, { xtype: "button", iconCls: "pimcore_icon_search", overflowText: t("search"), handler: this.openSearchEditor.bind(this) }] }, componentCls: "object_field object_field_type_" + this.type, bodyCls: "pimcore_droptarget_image pimcore_image_container" }; this.component = new Ext.Panel(conf); this.component.on("afterrender", function (el) { // add drop zone new Ext.dd.DropZone(el.getEl(), { reference: this, ddGroup: "element", getTargetFromEvent: function (e) { return this.reference.component.getEl(); }, onNodeOver: function (target, dd, e, data) { if (data.records.length === 1 && data.records[0].data.type === "image") { return Ext.dd.DropZone.prototype.dropAllowed; } }, onNodeDrop: this.onNodeDrop.bind(this) }); el.getEl().on("contextmenu", this.onContextMenu.bind(this)); pimcore.helpers.registerAssetDnDSingleUpload(el.getEl().dom, this.fieldConfig.uploadPath, 'path', function (e) { if (e['asset']['type'] === "image") { this.empty(true); this.dirty = true; this.data.id = e['asset']['id']; this.updateImage(); return true; } else { pimcore.helpers.showNotification(t("error"), t('unsupported_filetype'), "error"); } }.bind(this), null, this.context); this.updateImage(); }.bind(this)); return this.component; }, getLayoutShow: function () { if (intval(this.fieldConfig.width) < 1) { this.fieldConfig.width = 300; } if (intval(this.fieldConfig.height) < 1) { this.fieldConfig.height = 300; } var conf = { width: this.fieldConfig.width, height: this.fieldConfig.height, border: true, style: "padding-bottom: 10px", tbar: { overflowHandler: 'menu', items: [{ xtype: "tbtext", text: "<b>" + this.fieldConfig.title + "</b>" }, "->",{ xtype: "button", iconCls: "pimcore_icon_open", overflowText: t("open"), handler: this.openImage.bind(this) }] }, cls: "object_field", bodyCls: "pimcore_droptarget_image pimcore_image_container" }; this.component = new Ext.Panel(conf); this.component.on("afterrender", function (el) { el.getEl().on("contextmenu", this.onContextMenu.bind(this)); this.updateImage(); }.bind(this)); return this.component; }, onNodeDrop: function (target, dd, e, data) { if(!pimcore.helpers.dragAndDropValidateSingleItem(data)) { return false; } data = data.records[0].data; if (data.type === "image") { this.empty(true); if (this.data.id !== data.id) { this.dirty = true; } this.data.id = data.id; this.updateImage(); return true; } return false; }, openSearchEditor: function () { pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), { type: ["asset"], subtype: { asset: ["image"] } }, { context: Ext.apply({scope: "objectEditor"}, this.getContext()) }); }, uploadDialog: function () { pimcore.helpers.assetSingleUploadDialog(this.fieldConfig.uploadPath, "path", function (res) { try { this.empty(true); var data = Ext.decode(res.response.responseText); if (data["id"] && data["type"] == "image") { this.data.id = data["id"]; this.dirty = true; } this.updateImage(); } catch (e) { console.log(e); } }.bind(this), null, this.context); }, addDataFromSelector: function (item) { this.empty(true); if (item) { if (!this.data || this.data.id != item.id) { this.dirty = true; } this.data = this.data || {}; this.data.id = item.id; this.updateImage(); return true; } }, openImage: function () { if (this.data) { pimcore.helpers.openAsset(this.data.id, "image"); } }, updateImage: function () { if(this.data && this.data["id"]) { // 5px padding (-10) var body = this.getBody(); var width = body.getWidth() - 10; var height = this.fieldConfig.height - 60; // strage body.getHeight() returns 2? so we use the config instead var path = Routing.generate('pimcore_admin_asset_getimagethumbnail', { id: this.data.id, width: width, height: height, contain: true }); body.removeCls("pimcore_droptarget_image"); var innerBody = body.down('.x-autocontainer-innerCt'); innerBody.setStyle({ backgroundImage: "url(" + path + ")", backgroundPosition: "center center", backgroundRepeat: "no-repeat" }); body.repaint(); } }, getBody: function () { // get the id from the body element of the panel because there is no method to set body's html // (only in configure) var elements = Ext.get(this.component.getEl().dom).query(".pimcore_image_container"); var bodyId = elements[0].getAttribute("id"); var body = Ext.get(bodyId); return body; }, onContextMenu: function (e) { var menu = new Ext.menu.Menu(); if (this.data) { if(!this.fieldConfig.noteditable) { menu.add(new Ext.menu.Item({ text: t('empty'), iconCls: "pimcore_icon_delete", handler: function (item) { item.parentMenu.destroy(); this.empty(); }.bind(this) })); } menu.add(new Ext.menu.Item({ text: t('open'), iconCls: "pimcore_icon_open", handler: function (item) { item.parentMenu.destroy(); this.openImage(); }.bind(this) })); if (!this.fieldConfig.noteditable && this instanceof pimcore.object.tags.hotspotimage) { menu.add(new Ext.menu.Item({ text: t('select_specific_area_of_image'), iconCls: "pimcore_icon_image_region", handler: function (item) { item.parentMenu.destroy(); this.openCropWindow(); }.bind(this) })); menu.add(new Ext.menu.Item({ text: t('add_marker_or_hotspots'), iconCls: "pimcore_icon_image pimcore_icon_overlay_edit", handler: function (item) { item.parentMenu.destroy(); this.openHotspotWindow(); }.bind(this) })); } } if(!this.fieldConfig.noteditable) { menu.add(new Ext.menu.Item({ text: t('search'), iconCls: "pimcore_icon_search", handler: function (item) { item.parentMenu.destroy(); this.openSearchEditor(); }.bind(this) })); menu.add(new Ext.menu.Item({ text: t('upload'), cls: "pimcore_inline_upload", iconCls: "pimcore_icon_upload", handler: function (item) { item.parentMenu.destroy(); this.uploadDialog(); }.bind(this) })); } menu.showAt(e.getXY()); e.stopEvent(); }, empty: function () { if (this.data) { this.data = {}; } var body = this.getBody(); body.down('.x-autocontainer-innerCt').setStyle({ backgroundImage: "" }); body.addCls("pimcore_droptarget_image"); this.dirty = true; body.repaint(); }, getValue: function () { return this.data; }, getName: function () { return this.fieldConfig.name; }, isDirty: function () { if (!this.isRendered()) { return false; } return this.dirty; }, getCellEditValue: function () { return this.getValue(); } });
jcorbin/anansi
bitmap.go
<gh_stars>1-10 package anansi import ( "errors" "image" "unicode/utf8" ) // Bitmap is a 2-color bitmap targeting unicode braille runes. type Bitmap struct { Bit []bool Stride int Rect image.Rectangle } // Load the given bit data into the bitmap. func (bi *Bitmap) Load(stride int, data []bool) { h := len(data) / stride for i, n := 0, len(data)%h; i < n; i++ { data = append(data, false) } bi.Bit = data bi.Stride = stride bi.Rect = image.Rectangle{image.ZP, image.Pt(stride, h)} } // Resize the bitmap, re-allocating its bit storage. func (bi *Bitmap) Resize(sz image.Point) { bi.Bit = make([]bool, sz.X*sz.Y) bi.Stride = sz.X bi.Rect = image.Rectangle{image.ZP, sz} } // ParseBitmap parses a convenience representation for creating bitmaps. // The set string argument indicates how a 1 (or true) bit will be recognized; // it may be any 1 or 2 rune string. Any other single or double runes in the // strings will be mapped to zero (allowing the caller to put anything there // for other, self-documenting, purposes). func ParseBitmap(set string, lines ...string) (stride int, data []bool, err error) { var setRunes [2]rune var pat []rune switch utf8.RuneCountInString(set) { case 1: setRunes[0], _ = utf8.DecodeRuneInString(set) pat = setRunes[:1] case 2: var n int setRunes[0], n = utf8.DecodeRuneInString(set) setRunes[1], _ = utf8.DecodeRuneInString(set[n:]) pat = setRunes[:2] default: return 0, nil, errors.New("must use a 1 or 2-rune string") } var n int for _, line := range lines { m := utf8.RuneCountInString(line) if len(pat) == 2 { if m%2 == 1 { return 0, nil, errors.New("odd-length line in double rune bitmap parse") } m /= 2 } if stride == 0 { stride = m } else if m != stride { return 0, nil, errors.New("inconsistent line length") } n += stride } data = make([]bool, 0, n) for _, line := range lines { for len(line) > 0 { all := true for _, patRune := range pat { r, n := utf8.DecodeRuneInString(line) line = line[n:] all = all && r == patRune } if all { data = append(data, true) } else { data = append(data, false) } } } return stride, data, nil } // MustParseBitmap is an infaliable version of ParseBitmapString: it // panics if any non-nil error is returned by it. func MustParseBitmap(set string, lines ...string) (stride int, data []bool) { stride, data, err := ParseBitmap(set, lines...) if err != nil { panic(err) } return stride, data } // RuneSize returns the size of the bitmap in runes. func (bi *Bitmap) RuneSize() (sz image.Point) { sz.X = (bi.Rect.Dx() + 1) / 2 sz.Y = (bi.Rect.Dy() + 3) / 4 return sz } // Get a single bitmap cell value. func (bi *Bitmap) Get(p image.Point) bool { i, within := bi.index(p) return within && bi.Bit[i] } // Set a single bitmap cell value. func (bi *Bitmap) Set(p image.Point, b bool) { if i, within := bi.index(p); within { bi.Bit[i] = b } } func (bi *Bitmap) index(p image.Point) (int, bool) { if p.In(bi.Rect) { return p.Y*bi.Stride + p.X, true } return -1, false } // Rune builds a unicode braille rune representing a single 2x4 rectangle of // bits, anchored at the give top-left point. func (bi *Bitmap) Rune(p image.Point) (c rune) { // Each braille rune is a 2x4 grid of points, represented by a codepoint in // the U+2800 thru U+28FF range; in other words, an 8-bit space. // // Each point in that 2x4 grid is coded by one of those 8 bits: // 0x0001 0x0008 // 0x0002 0x0010 // 0x0004 0x0020 // 0x0040 0x0080 // // For example, the braille rune '⢕', whose grid explodes to: // |·| | // | |·| // |·| | // | |·| // Has code point U+2895 = 0x2800 | 0x0001 | 0x0004 | 0x0010 | 0x0080 // first row if i, within := bi.index(p); within { col2Within := p.X+1 < bi.Rect.Max.X if bi.Bit[i] { c |= 0x0001 } if col2Within && bi.Bit[i+1] { c |= 0x0008 } // second row p.Y++ if within = p.Y < bi.Rect.Max.Y; within { i += bi.Stride if bi.Bit[i] { c |= 0x0002 } if col2Within && bi.Bit[i+1] { c |= 0x0010 } // third row p.Y++ if within = p.Y < bi.Rect.Max.Y; within { i += bi.Stride if bi.Bit[i] { c |= 0x0004 } if col2Within && bi.Bit[i+1] { c |= 0x0020 } // fourth row p.Y++ if within = p.Y < bi.Rect.Max.Y; within { i += bi.Stride if bi.Bit[i] { c |= 0x0040 } if col2Within && bi.Bit[i+1] { c |= 0x0080 } } } } } return 0x2800 | c } // SubAt is a convenience for calling SubRect with at as the new Min point, and // the receiver's Rect.Max point. func (bi Bitmap) SubAt(at image.Point) Bitmap { return bi.SubRect(image.Rectangle{Min: at, Max: bi.Rect.Max}) } // SubSize is a convenience for calling SubRect with a Max point determined by // adding the given size to the receiver's Rect.Min point. func (bi Bitmap) SubSize(sz image.Point) Bitmap { return bi.SubRect(image.Rectangle{Min: bi.Rect.Min, Max: bi.Rect.Min.Add(sz)}) } // SubRect returns a subgrid, sharing the receiver's Rune/Attr/Stride data, but // with a new bounding Rect. // Clamps r.Max to bi.Rect.Max, and returns the zero Bitmap if r.Min is not in // bi.Rect. func (bi Bitmap) SubRect(r image.Rectangle) Bitmap { if !r.Min.In(bi.Rect) { return Bitmap{} } if r.Max.X > bi.Rect.Max.X { r.Max.X = bi.Rect.Max.X } if r.Max.Y > bi.Rect.Max.Y { r.Max.Y = bi.Rect.Max.Y } return Bitmap{ Bit: bi.Bit, Stride: bi.Stride, Rect: r, } }
manoj-savantly/sprout-platform
backend/modules/forms/src/main/java/net/savantly/sprout/module/forms/domain/definition/FormDefinitionDto.java
<filename>backend/modules/forms/src/main/java/net/savantly/sprout/module/forms/domain/definition/FormDefinitionDto.java package net.savantly.sprout.module.forms.domain.definition; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @Getter @Setter @Accessors(chain = true) public class FormDefinitionDto { @JsonProperty("_id") private String id; @JsonProperty("type") private String formType; private String title; private String name; private String path; private String display; private ZonedDateTime created; private ZonedDateTime modified; private List<Map<String, Object>> components = new ArrayList<Map<String,Object>>(); private List<String> tags = new ArrayList<>(); private Map<String, Object> settings = new HashMap<String,Object>(); }
AlessandroBorges/Bor_Vulkan
Vulkan/jni/bor.vulkan.structs.VkClearRect.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class bor_vulkan_structs_VkClearRect */ #ifndef _Included_bor_vulkan_structs_VkClearRect #define _Included_bor_vulkan_structs_VkClearRect #ifdef __cplusplus extern "C" { #endif #undef bor_vulkan_structs_VkClearRect_VKAPPLICATIONINFO_ID #define bor_vulkan_structs_VkClearRect_VKAPPLICATIONINFO_ID 1L #undef bor_vulkan_structs_VkClearRect_VKINSTANCECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKINSTANCECREATEINFO_ID 2L #undef bor_vulkan_structs_VkClearRect_VKALLOCATIONCALLBACKS_ID #define bor_vulkan_structs_VkClearRect_VKALLOCATIONCALLBACKS_ID 3L #undef bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEFEATURES_ID #define bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEFEATURES_ID 4L #undef bor_vulkan_structs_VkClearRect_VKFORMATPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKFORMATPROPERTIES_ID 5L #undef bor_vulkan_structs_VkClearRect_VKEXTENT3D_ID #define bor_vulkan_structs_VkClearRect_VKEXTENT3D_ID 6L #undef bor_vulkan_structs_VkClearRect_VKIMAGEFORMATPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKIMAGEFORMATPROPERTIES_ID 7L #undef bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICELIMITS_ID #define bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICELIMITS_ID 8L #undef bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICESPARSEPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICESPARSEPROPERTIES_ID 9L #undef bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEPROPERTIES_ID 10L #undef bor_vulkan_structs_VkClearRect_VKQUEUEFAMILYPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKQUEUEFAMILYPROPERTIES_ID 11L #undef bor_vulkan_structs_VkClearRect_VKMEMORYTYPE_ID #define bor_vulkan_structs_VkClearRect_VKMEMORYTYPE_ID 12L #undef bor_vulkan_structs_VkClearRect_VKMEMORYHEAP_ID #define bor_vulkan_structs_VkClearRect_VKMEMORYHEAP_ID 13L #undef bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEMEMORYPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKPHYSICALDEVICEMEMORYPROPERTIES_ID 14L #undef bor_vulkan_structs_VkClearRect_VKDEVICEQUEUECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDEVICEQUEUECREATEINFO_ID 15L #undef bor_vulkan_structs_VkClearRect_VKDEVICECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDEVICECREATEINFO_ID 16L #undef bor_vulkan_structs_VkClearRect_VKEXTENSIONPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKEXTENSIONPROPERTIES_ID 17L #undef bor_vulkan_structs_VkClearRect_VKLAYERPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKLAYERPROPERTIES_ID 18L #undef bor_vulkan_structs_VkClearRect_VKSUBMITINFO_ID #define bor_vulkan_structs_VkClearRect_VKSUBMITINFO_ID 19L #undef bor_vulkan_structs_VkClearRect_VKMEMORYALLOCATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKMEMORYALLOCATEINFO_ID 20L #undef bor_vulkan_structs_VkClearRect_VKMAPPEDMEMORYRANGE_ID #define bor_vulkan_structs_VkClearRect_VKMAPPEDMEMORYRANGE_ID 21L #undef bor_vulkan_structs_VkClearRect_VKMEMORYREQUIREMENTS_ID #define bor_vulkan_structs_VkClearRect_VKMEMORYREQUIREMENTS_ID 22L #undef bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEFORMATPROPERTIES_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEFORMATPROPERTIES_ID 23L #undef bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYREQUIREMENTS_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYREQUIREMENTS_ID 24L #undef bor_vulkan_structs_VkClearRect_VKSPARSEMEMORYBIND_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEMEMORYBIND_ID 25L #undef bor_vulkan_structs_VkClearRect_VKSPARSEBUFFERMEMORYBINDINFO_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEBUFFERMEMORYBINDINFO_ID 26L #undef bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEOPAQUEMEMORYBINDINFO_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEOPAQUEMEMORYBINDINFO_ID 27L #undef bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCE_ID #define bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCE_ID 28L #undef bor_vulkan_structs_VkClearRect_VKOFFSET3D_ID #define bor_vulkan_structs_VkClearRect_VKOFFSET3D_ID 29L #undef bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYBIND_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYBIND_ID 30L #undef bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYBINDINFO_ID #define bor_vulkan_structs_VkClearRect_VKSPARSEIMAGEMEMORYBINDINFO_ID 31L #undef bor_vulkan_structs_VkClearRect_VKBINDSPARSEINFO_ID #define bor_vulkan_structs_VkClearRect_VKBINDSPARSEINFO_ID 32L #undef bor_vulkan_structs_VkClearRect_VKFENCECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKFENCECREATEINFO_ID 33L #undef bor_vulkan_structs_VkClearRect_VKSEMAPHORECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKSEMAPHORECREATEINFO_ID 34L #undef bor_vulkan_structs_VkClearRect_VKEVENTCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKEVENTCREATEINFO_ID 35L #undef bor_vulkan_structs_VkClearRect_VKQUERYPOOLCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKQUERYPOOLCREATEINFO_ID 36L #undef bor_vulkan_structs_VkClearRect_VKBUFFERCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKBUFFERCREATEINFO_ID 37L #undef bor_vulkan_structs_VkClearRect_VKBUFFERVIEWCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKBUFFERVIEWCREATEINFO_ID 38L #undef bor_vulkan_structs_VkClearRect_VKIMAGECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKIMAGECREATEINFO_ID 39L #undef bor_vulkan_structs_VkClearRect_VKSUBRESOURCELAYOUT_ID #define bor_vulkan_structs_VkClearRect_VKSUBRESOURCELAYOUT_ID 40L #undef bor_vulkan_structs_VkClearRect_VKCOMPONENTMAPPING_ID #define bor_vulkan_structs_VkClearRect_VKCOMPONENTMAPPING_ID 41L #undef bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCERANGE_ID #define bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCERANGE_ID 42L #undef bor_vulkan_structs_VkClearRect_VKIMAGEVIEWCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKIMAGEVIEWCREATEINFO_ID 43L #undef bor_vulkan_structs_VkClearRect_VKSHADERMODULECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKSHADERMODULECREATEINFO_ID 44L #undef bor_vulkan_structs_VkClearRect_VKPIPELINECACHECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINECACHECREATEINFO_ID 45L #undef bor_vulkan_structs_VkClearRect_VKSPECIALIZATIONMAPENTRY_ID #define bor_vulkan_structs_VkClearRect_VKSPECIALIZATIONMAPENTRY_ID 46L #undef bor_vulkan_structs_VkClearRect_VKSPECIALIZATIONINFO_ID #define bor_vulkan_structs_VkClearRect_VKSPECIALIZATIONINFO_ID 47L #undef bor_vulkan_structs_VkClearRect_VKPIPELINESHADERSTAGECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINESHADERSTAGECREATEINFO_ID 48L #undef bor_vulkan_structs_VkClearRect_VKVERTEXINPUTBINDINGDESCRIPTION_ID #define bor_vulkan_structs_VkClearRect_VKVERTEXINPUTBINDINGDESCRIPTION_ID 49L #undef bor_vulkan_structs_VkClearRect_VKVERTEXINPUTATTRIBUTEDESCRIPTION_ID #define bor_vulkan_structs_VkClearRect_VKVERTEXINPUTATTRIBUTEDESCRIPTION_ID 50L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEVERTEXINPUTSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEVERTEXINPUTSTATECREATEINFO_ID 51L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEINPUTASSEMBLYSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEINPUTASSEMBLYSTATECREATEINFO_ID 52L #undef bor_vulkan_structs_VkClearRect_VKPIPELINETESSELLATIONSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINETESSELLATIONSTATECREATEINFO_ID 53L #undef bor_vulkan_structs_VkClearRect_VKVIEWPORT_ID #define bor_vulkan_structs_VkClearRect_VKVIEWPORT_ID 54L #undef bor_vulkan_structs_VkClearRect_VKOFFSET2D_ID #define bor_vulkan_structs_VkClearRect_VKOFFSET2D_ID 55L #undef bor_vulkan_structs_VkClearRect_VKEXTENT2D_ID #define bor_vulkan_structs_VkClearRect_VKEXTENT2D_ID 56L #undef bor_vulkan_structs_VkClearRect_VKRECT2D_ID #define bor_vulkan_structs_VkClearRect_VKRECT2D_ID 57L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEVIEWPORTSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEVIEWPORTSTATECREATEINFO_ID 58L #undef bor_vulkan_structs_VkClearRect_VKPIPELINERASTERIZATIONSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINERASTERIZATIONSTATECREATEINFO_ID 59L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEMULTISAMPLESTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEMULTISAMPLESTATECREATEINFO_ID 60L #undef bor_vulkan_structs_VkClearRect_VKSTENCILOPSTATE_ID #define bor_vulkan_structs_VkClearRect_VKSTENCILOPSTATE_ID 61L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEDEPTHSTENCILSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEDEPTHSTENCILSTATECREATEINFO_ID 62L #undef bor_vulkan_structs_VkClearRect_VKPIPELINECOLORBLENDATTACHMENTSTATE_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINECOLORBLENDATTACHMENTSTATE_ID 63L #undef bor_vulkan_structs_VkClearRect_VKPIPELINECOLORBLENDSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINECOLORBLENDSTATECREATEINFO_ID 64L #undef bor_vulkan_structs_VkClearRect_VKPIPELINEDYNAMICSTATECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINEDYNAMICSTATECREATEINFO_ID 65L #undef bor_vulkan_structs_VkClearRect_VKGRAPHICSPIPELINECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKGRAPHICSPIPELINECREATEINFO_ID 66L #undef bor_vulkan_structs_VkClearRect_VKCOMPUTEPIPELINECREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKCOMPUTEPIPELINECREATEINFO_ID 67L #undef bor_vulkan_structs_VkClearRect_VKPUSHCONSTANTRANGE_ID #define bor_vulkan_structs_VkClearRect_VKPUSHCONSTANTRANGE_ID 68L #undef bor_vulkan_structs_VkClearRect_VKPIPELINELAYOUTCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINELAYOUTCREATEINFO_ID 69L #undef bor_vulkan_structs_VkClearRect_VKSAMPLERCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKSAMPLERCREATEINFO_ID 70L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETLAYOUTBINDING_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETLAYOUTBINDING_ID 71L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETLAYOUTCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETLAYOUTCREATEINFO_ID 72L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORPOOLSIZE_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORPOOLSIZE_ID 73L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORPOOLCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORPOOLCREATEINFO_ID 74L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETALLOCATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORSETALLOCATEINFO_ID 75L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORIMAGEINFO_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORIMAGEINFO_ID 76L #undef bor_vulkan_structs_VkClearRect_VKDESCRIPTORBUFFERINFO_ID #define bor_vulkan_structs_VkClearRect_VKDESCRIPTORBUFFERINFO_ID 77L #undef bor_vulkan_structs_VkClearRect_VKWRITEDESCRIPTORSET_ID #define bor_vulkan_structs_VkClearRect_VKWRITEDESCRIPTORSET_ID 78L #undef bor_vulkan_structs_VkClearRect_VKCOPYDESCRIPTORSET_ID #define bor_vulkan_structs_VkClearRect_VKCOPYDESCRIPTORSET_ID 79L #undef bor_vulkan_structs_VkClearRect_VKFRAMEBUFFERCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKFRAMEBUFFERCREATEINFO_ID 80L #undef bor_vulkan_structs_VkClearRect_VKATTACHMENTDESCRIPTION_ID #define bor_vulkan_structs_VkClearRect_VKATTACHMENTDESCRIPTION_ID 81L #undef bor_vulkan_structs_VkClearRect_VKATTACHMENTREFERENCE_ID #define bor_vulkan_structs_VkClearRect_VKATTACHMENTREFERENCE_ID 82L #undef bor_vulkan_structs_VkClearRect_VKSUBPASSDESCRIPTION_ID #define bor_vulkan_structs_VkClearRect_VKSUBPASSDESCRIPTION_ID 83L #undef bor_vulkan_structs_VkClearRect_VKSUBPASSDEPENDENCY_ID #define bor_vulkan_structs_VkClearRect_VKSUBPASSDEPENDENCY_ID 84L #undef bor_vulkan_structs_VkClearRect_VKRENDERPASSCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKRENDERPASSCREATEINFO_ID 85L #undef bor_vulkan_structs_VkClearRect_VKCOMMANDPOOLCREATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKCOMMANDPOOLCREATEINFO_ID 86L #undef bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERALLOCATEINFO_ID #define bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERALLOCATEINFO_ID 87L #undef bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERINHERITANCEINFO_ID #define bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERINHERITANCEINFO_ID 88L #undef bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERBEGININFO_ID #define bor_vulkan_structs_VkClearRect_VKCOMMANDBUFFERBEGININFO_ID 89L #undef bor_vulkan_structs_VkClearRect_VKBUFFERCOPY_ID #define bor_vulkan_structs_VkClearRect_VKBUFFERCOPY_ID 90L #undef bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCELAYERS_ID #define bor_vulkan_structs_VkClearRect_VKIMAGESUBRESOURCELAYERS_ID 91L #undef bor_vulkan_structs_VkClearRect_VKIMAGECOPY_ID #define bor_vulkan_structs_VkClearRect_VKIMAGECOPY_ID 92L #undef bor_vulkan_structs_VkClearRect_VKIMAGEBLIT_ID #define bor_vulkan_structs_VkClearRect_VKIMAGEBLIT_ID 93L #undef bor_vulkan_structs_VkClearRect_VKBUFFERIMAGECOPY_ID #define bor_vulkan_structs_VkClearRect_VKBUFFERIMAGECOPY_ID 94L #undef bor_vulkan_structs_VkClearRect_VKCLEARDEPTHSTENCILVALUE_ID #define bor_vulkan_structs_VkClearRect_VKCLEARDEPTHSTENCILVALUE_ID 95L #undef bor_vulkan_structs_VkClearRect_VKCLEARATTACHMENT_ID #define bor_vulkan_structs_VkClearRect_VKCLEARATTACHMENT_ID 96L #undef bor_vulkan_structs_VkClearRect_VKCLEARRECT_ID #define bor_vulkan_structs_VkClearRect_VKCLEARRECT_ID 97L #undef bor_vulkan_structs_VkClearRect_VKIMAGERESOLVE_ID #define bor_vulkan_structs_VkClearRect_VKIMAGERESOLVE_ID 98L #undef bor_vulkan_structs_VkClearRect_VKMEMORYBARRIER_ID #define bor_vulkan_structs_VkClearRect_VKMEMORYBARRIER_ID 99L #undef bor_vulkan_structs_VkClearRect_VKBUFFERMEMORYBARRIER_ID #define bor_vulkan_structs_VkClearRect_VKBUFFERMEMORYBARRIER_ID 100L #undef bor_vulkan_structs_VkClearRect_VKIMAGEMEMORYBARRIER_ID #define bor_vulkan_structs_VkClearRect_VKIMAGEMEMORYBARRIER_ID 101L #undef bor_vulkan_structs_VkClearRect_VKRENDERPASSBEGININFO_ID #define bor_vulkan_structs_VkClearRect_VKRENDERPASSBEGININFO_ID 102L #undef bor_vulkan_structs_VkClearRect_VKDISPATCHINDIRECTCOMMAND_ID #define bor_vulkan_structs_VkClearRect_VKDISPATCHINDIRECTCOMMAND_ID 103L #undef bor_vulkan_structs_VkClearRect_VKDRAWINDEXEDINDIRECTCOMMAND_ID #define bor_vulkan_structs_VkClearRect_VKDRAWINDEXEDINDIRECTCOMMAND_ID 104L #undef bor_vulkan_structs_VkClearRect_VKDRAWINDIRECTCOMMAND_ID #define bor_vulkan_structs_VkClearRect_VKDRAWINDIRECTCOMMAND_ID 105L #undef bor_vulkan_structs_VkClearRect_VKSURFACECAPABILITIESKHR_ID #define bor_vulkan_structs_VkClearRect_VKSURFACECAPABILITIESKHR_ID 106L #undef bor_vulkan_structs_VkClearRect_VKSURFACEFORMATKHR_ID #define bor_vulkan_structs_VkClearRect_VKSURFACEFORMATKHR_ID 107L #undef bor_vulkan_structs_VkClearRect_VKSWAPCHAINCREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKSWAPCHAINCREATEINFOKHR_ID 108L #undef bor_vulkan_structs_VkClearRect_VKPRESENTINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKPRESENTINFOKHR_ID 109L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYPROPERTIESKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYPROPERTIESKHR_ID 110L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYMODEPARAMETERSKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYMODEPARAMETERSKHR_ID 111L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYMODEPROPERTIESKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYMODEPROPERTIESKHR_ID 112L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYMODECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYMODECREATEINFOKHR_ID 113L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYPLANECAPABILITIESKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYPLANECAPABILITIESKHR_ID 114L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYPLANEPROPERTIESKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYPLANEPROPERTIESKHR_ID 115L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYSURFACECREATEINFOKHR_ID 116L #undef bor_vulkan_structs_VkClearRect_VKDISPLAYPRESENTINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKDISPLAYPRESENTINFOKHR_ID 117L #undef bor_vulkan_structs_VkClearRect_VKXLIBSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKXLIBSURFACECREATEINFOKHR_ID 118L #undef bor_vulkan_structs_VkClearRect_VKXCBSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKXCBSURFACECREATEINFOKHR_ID 119L #undef bor_vulkan_structs_VkClearRect_VKWAYLANDSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKWAYLANDSURFACECREATEINFOKHR_ID 120L #undef bor_vulkan_structs_VkClearRect_VKMIRSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKMIRSURFACECREATEINFOKHR_ID 121L #undef bor_vulkan_structs_VkClearRect_VKANDROIDSURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKANDROIDSURFACECREATEINFOKHR_ID 122L #undef bor_vulkan_structs_VkClearRect_VKWIN32SURFACECREATEINFOKHR_ID #define bor_vulkan_structs_VkClearRect_VKWIN32SURFACECREATEINFOKHR_ID 123L #undef bor_vulkan_structs_VkClearRect_VKDEBUGREPORTCALLBACKCREATEINFOEXT_ID #define bor_vulkan_structs_VkClearRect_VKDEBUGREPORTCALLBACKCREATEINFOEXT_ID 124L #undef bor_vulkan_structs_VkClearRect_VKPIPELINERASTERIZATIONSTATERASTERIZATIONORDERAMD_ID #define bor_vulkan_structs_VkClearRect_VKPIPELINERASTERIZATIONSTATERASTERIZATIONORDERAMD_ID 125L #undef bor_vulkan_structs_VkClearRect_VKDEBUGMARKEROBJECTNAMEINFOEXT_ID #define bor_vulkan_structs_VkClearRect_VKDEBUGMARKEROBJECTNAMEINFOEXT_ID 126L #undef bor_vulkan_structs_VkClearRect_VKDEBUGMARKEROBJECTTAGINFOEXT_ID #define bor_vulkan_structs_VkClearRect_VKDEBUGMARKEROBJECTTAGINFOEXT_ID 127L #undef bor_vulkan_structs_VkClearRect_VKDEBUGMARKERMARKERINFOEXT_ID #define bor_vulkan_structs_VkClearRect_VKDEBUGMARKERMARKERINFOEXT_ID 128L #undef bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONIMAGECREATEINFONV_ID #define bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONIMAGECREATEINFONV_ID 129L #undef bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONBUFFERCREATEINFONV_ID #define bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONBUFFERCREATEINFONV_ID 130L #undef bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONMEMORYALLOCATEINFONV_ID #define bor_vulkan_structs_VkClearRect_VKDEDICATEDALLOCATIONMEMORYALLOCATEINFONV_ID 131L #undef bor_vulkan_structs_VkClearRect_VKCLEARVALUE_ID #define bor_vulkan_structs_VkClearRect_VKCLEARVALUE_ID 200L #undef bor_vulkan_structs_VkClearRect_VKCLEARCOLORVALUE_ID #define bor_vulkan_structs_VkClearRect_VKCLEARCOLORVALUE_ID 201L #undef bor_vulkan_structs_VkClearRect_TAG_ID #define bor_vulkan_structs_VkClearRect_TAG_ID 97L /* * Class: bor_vulkan_structs_VkClearRect * Method: setRect0 * Signature: (Ljava/nio/Buffer;Ljava/nio/ByteBuffer;)V */ JNIEXPORT void JNICALL Java_bor_vulkan_structs_VkClearRect_setRect0 (JNIEnv *, jclass, jobject, jobject); /* * Class: bor_vulkan_structs_VkClearRect * Method: getRect0 * Signature: (Ljava/nio/Buffer;)J */ JNIEXPORT jlong JNICALL Java_bor_vulkan_structs_VkClearRect_getRect0 (JNIEnv *, jclass, jobject); /* * Class: bor_vulkan_structs_VkClearRect * Method: setBaseArrayLayer0 * Signature: (Ljava/nio/Buffer;I)V */ JNIEXPORT void JNICALL Java_bor_vulkan_structs_VkClearRect_setBaseArrayLayer0 (JNIEnv *, jclass, jobject, jint); /* * Class: bor_vulkan_structs_VkClearRect * Method: getBaseArrayLayer0 * Signature: (Ljava/nio/Buffer;)I */ JNIEXPORT jint JNICALL Java_bor_vulkan_structs_VkClearRect_getBaseArrayLayer0 (JNIEnv *, jclass, jobject); /* * Class: bor_vulkan_structs_VkClearRect * Method: setLayerCount0 * Signature: (Ljava/nio/Buffer;I)V */ JNIEXPORT void JNICALL Java_bor_vulkan_structs_VkClearRect_setLayerCount0 (JNIEnv *, jclass, jobject, jint); /* * Class: bor_vulkan_structs_VkClearRect * Method: getLayerCount0 * Signature: (Ljava/nio/Buffer;)I */ JNIEXPORT jint JNICALL Java_bor_vulkan_structs_VkClearRect_getLayerCount0 (JNIEnv *, jclass, jobject); #ifdef __cplusplus } #endif #endif
y10naoki/nestalib
src/response.c
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * The MIT License * * Copyright (c) 2008-2011 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define API_INTERNAL #include "nestalib.h" /* * レスポンスの初期処理を行ないます。 * レスポンス構造体のメモリを確保します。 * * socket: ソケット * * 戻り値 * レスポンス構造体のポインタ */ APIEXPORT struct response_t* resp_initialize(SOCKET socket) { struct response_t *resp; resp = (struct response_t*)malloc(sizeof(struct response_t)); if (resp == NULL) { err_write("rsponse: No memory."); return NULL; } resp->socket = socket; resp->content_size = 0; return resp; } /* * レスポンスを終了します。 * 確保された領域は解放されます。 * * resp: レスポンス構造体のポインタ * * 戻り値 * なし */ APIEXPORT void resp_finalize(struct response_t* resp) { free(resp); } /* * HTTPヘッダーをレスポンスします。 * * resp: レスポンス構造体のポインタ * hdr: 送信するヘッダー構造体のポインタ * * 戻り値 * 送信したバイト数を返します。 * エラーの場合は -1 を返します。 */ APIEXPORT int resp_send_header(struct response_t* resp, struct http_header_t* hdr) { return send_header(resp->socket, hdr); } /* * HTTPボディをレスポンスします。 * レスポンス構造体のコンテントサイズが設定されます。 * * resp: レスポンス構造体のポインタ * body: 送信するデータのポインタ * body_size: 送信するデータサイズ * * 戻り値 * 送信したバイト数を返します。 * エラーの場合は -1 を返します。 */ APIEXPORT int resp_send_body(struct response_t* resp, const void* body, int body_size) { int result; result = send_data(resp->socket, body, body_size); if (result < 0) return -1; resp->content_size = body_size; return result; } /* * HTTPデータをレスポンスします。 * * resp: レスポンス構造体のポインタ * body: 送信するデータのポインタ * body_size: 送信するデータサイズ * * 戻り値 * 送信したバイト数を返します。 * エラーの場合は -1 を返します。 */ APIEXPORT int resp_send_data(struct response_t* resp, const void* data, int data_size) { int result; result = send_data(resp->socket, data, data_size); if (result < 0) return -1; return result; } /* * コンテントサイズを設定します。 * * resp: レスポンス構造体のポインタ * content_size: コンテントサイズ * * 戻り値 * なし */ APIEXPORT void resp_set_content_size(struct response_t* resp, int content_size) { resp->content_size = content_size; }
ArtSCactus/JWD-Web-project
Web project/src/main/java/com/epam/Main.java
<gh_stars>0 package com.epam; import java.io.IOException; //Only for temporal use, just to test some small features public class Main { public static void main(String[] args) throws IllegalAccessException, IOException { } }
JennerChen/zq-react-ui-pack
src/util/randomStr.js
export const randomStr = () => Math.random() .toString(36) .slice(4, 10);
BobbyWhiskey/sg-orbit
packages/react-components/src/shared/src/keys.js
<filename>packages/react-components/src/shared/src/keys.js export const Keys = { backspace: 8, tab: 9, enter: 13, esc: 27, space: 32, end: 35, home: 36, left: 37, up: 38, right: 39, down: 40, delete: 46 };
RivenZoo/FullSource
Jx3Full/Source/Source/KG3DEngine/KG3DEngine/KG3DEffectFileTable.cpp
<reponame>RivenZoo/FullSource #include "StdAfx.h" #include "KG3DEffectFileTable.h" #include "KG3DGraphicsTool.h" #ifdef _DEBUG #define new DEBUG_NEW_3DENGINE #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif KG3DEffectFileTable g_cEffectFileTable; KG3DEffectFileTable::KG3DEffectFileTable(void) { } KG3DEffectFileTable::~KG3DEffectFileTable(void) { for (std::map<LPD3DXEFFECT, EffectInfo>::iterator i = m_ReleaseMapTable.begin(); i != m_ReleaseMapTable.end(); ++i) { ASSERT(QueryRef(i->first) == 0); } } HRESULT KG3DEffectFileTable::OnLostDevice() { //m_Lock.Lock(); for (std::map<LPD3DXEFFECT, EffectInfo>::iterator i = m_ReleaseMapTable.begin(); i != m_ReleaseMapTable.end(); ++i) { i->first->OnLostDevice(); } //m_Lock.Unlock(); return S_OK; } HRESULT KG3DEffectFileTable::OnResetDevice() { //m_Lock.Lock(); for (std::map<LPD3DXEFFECT, EffectInfo>::iterator i = m_ReleaseMapTable.begin(); i != m_ReleaseMapTable.end(); ++i) { i->first->OnResetDevice(); } //m_Lock.Unlock(); return S_OK; } HRESULT KG3DEffectFileTable::LoadFromFile(LPCSTR strFileName, LPD3DXEFFECT& pEffect) { //m_Lock.Lock(); HRESULT hr = E_FAIL; stdext::hash_map<std::string, LPD3DXEFFECT>::iterator i; KG_PROCESS_ERROR(strFileName); i = m_EffectFiles.find(strFileName); if (i != m_EffectFiles.end()) { pEffect = i->second; m_ReleaseMapTable[pEffect].dwRef++; hr = S_OK; } else { LPD3DXEFFECT pNewEffect = NULL; DWORD dwShaderFlags = 0; #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif hr = KG3DD3DXCreateEffectFromFile(g_pd3dDevice, strFileName, NULL, NULL, dwShaderFlags, NULL, &pNewEffect, NULL); KGLOG_COM_PROCESS_ERROR(hr); m_EffectFiles[strFileName] = pNewEffect; m_ReleaseMapTable[pNewEffect].strFileName = strFileName; m_ReleaseMapTable[pNewEffect].dwRef = 1; pEffect = pNewEffect; } if (pEffect) { pEffect->AddRef(); } Exit0: //m_Lock.Unlock(); return hr; } void KG3DEffectFileTable::Release(LPD3DXEFFECT pEffect) { std::map<LPD3DXEFFECT, EffectInfo>::iterator j; //m_Lock.Lock(); KGLOG_PROCESS_ERROR(pEffect); j = m_ReleaseMapTable.find(pEffect); if (j != m_ReleaseMapTable.end()) { pEffect->Release(); m_ReleaseMapTable[pEffect].dwRef--; if (m_ReleaseMapTable[pEffect].dwRef == 0) { ASSERT(QueryRef(pEffect) == 1); pEffect->Release(); stdext::hash_map<std::string, LPD3DXEFFECT>::iterator i = m_EffectFiles.find(m_ReleaseMapTable[pEffect].strFileName); if (i != m_EffectFiles.end()) { m_EffectFiles.erase(i); } m_ReleaseMapTable.erase(j); } } Exit0: ; //m_Lock.Unlock(); }
sadupally/Dev
unisa-tools/unisa-tpustudentplacement/src/java/za/ac/unisa/lms/tools/tpustudentplacement/forms/Country.java
<filename>unisa-tools/unisa-tpustudentplacement/src/java/za/ac/unisa/lms/tools/tpustudentplacement/forms/Country.java<gh_stars>0 package za.ac.unisa.lms.tools.tpustudentplacement.forms; import za.ac.unisa.lms.tools.tpustudentplacement.dao.CountryDAO; import java.util.List; public class Country { private String code; private String description; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List listAllCountries()throws Exception{ CountryDAO dao=new CountryDAO(); return dao.getCountryList(); } public String getSchoolCountry(int schoolCode)throws Exception { CountryDAO dao=new CountryDAO(); return dao.getSchoolCountry(schoolCode); } public String getSchoolCountryCode(int schoolCode)throws Exception { CountryDAO dao=new CountryDAO(); return dao.getSchoolCountryCode(schoolCode); } public List getCountryList() throws Exception { CountryDAO dao=new CountryDAO(); return dao.getCountryList(); } }
PleXone2019/-esp32-snippets
cpp_utils/SSLUtils.h
/* * SSLUtils.h * * Created on: Sep 16, 2017 * Author: kolban */ #ifndef COMPONENTS_CPP_UTILS_SSLUTILS_H_ #define COMPONENTS_CPP_UTILS_SSLUTILS_H_ #include <string> class SSLUtils { private: static char* m_certificate; static char* m_key; public: SSLUtils(); virtual ~SSLUtils(); static void setCertificate(std::string certificate); static char* getCertificate(); static void setKey(std::string key); static char* getKey(); }; #endif /* COMPONENTS_CPP_UTILS_SSLUTILS_H_ */
hugorebelo/gitlabhq
spec/migrations/rename_security_dashboard_feature_flag_to_instance_security_dashboard_spec.rb
<filename>spec/migrations/rename_security_dashboard_feature_flag_to_instance_security_dashboard_spec.rb # frozen_string_literal: true require 'spec_helper' require Rails.root.join('db', 'migrate', '20200212014653_rename_security_dashboard_feature_flag_to_instance_security_dashboard.rb') describe RenameSecurityDashboardFeatureFlagToInstanceSecurityDashboard do let(:feature_gates) { table(:feature_gates) } subject(:migration) { described_class.new } describe '#up' do it 'copies the security_dashboard feature gate to a new instance_security_dashboard gate' do feature_gates.create!(feature_key: :security_dashboard, key: :actors, value: 'Project:1') feature_gates.create!(feature_key: :security_dashboard, key: :boolean, value: 'false') migration.up instance_security_dashboard_feature = feature_gates.find_by(feature_key: :instance_security_dashboard, key: :boolean) expect(instance_security_dashboard_feature.value).to eq('false') end context 'when there is no security_dashboard gate' do it 'does nothing' do migration.up instance_security_dashboard_feature = feature_gates.find_by(feature_key: :instance_security_dashboard, key: :boolean) expect(instance_security_dashboard_feature).to be_nil end end context 'when there is already an instance_security_dashboard gate' do it 'does nothing' do feature_gates.create!(feature_key: :security_dashboard, key: 'boolean', value: 'false') feature_gates.create!(feature_key: :instance_security_dashboard, key: 'boolean', value: 'false') expect { migration.up }.not_to raise_error end end end describe '#down' do it 'removes the instance_security_dashboard gate' do actors_instance_security_dashboard_feature = feature_gates.create!(feature_key: :instance_security_dashboard, key: :actors, value: 'Project:1') instance_security_dashboard_feature = feature_gates.create!(feature_key: :instance_security_dashboard, key: :boolean, value: 'false') migration.down expect { instance_security_dashboard_feature.reload }.to raise_error(ActiveRecord::RecordNotFound) expect(actors_instance_security_dashboard_feature.reload).to be_present end end end
mczal/Profile-Matching
src/main/java/com/spk/model/utils/Religion.java
package com.spk.model.utils; /** * Created by Gl552 on 4/24/2017. */ public enum Religion { IGNORE, MOESLIM, CATHOLIC, CHRISTIAN, BUDDHA, HINDU, OTHER }
mol42/hbb-survey-web-admin
app/i18n.js
/** * i18n.js * * This will setup the i18n language files and locale data for your app. * */ import { addLocaleData } from 'react-intl'; import trLocaleData from 'react-intl/locale-data/tr'; import { DEFAULT_LOCALE } from '../app/redux/constants'; import trTranslationMessages from './translations/tr.json'; addLocaleData(trLocaleData); export const appLocales = [ 'tr' ]; export const formatTranslationMessages = (locale, messages) => { const defaultFormattedMessages = locale !== DEFAULT_LOCALE ? formatTranslationMessages(DEFAULT_LOCALE, trTranslationMessages) : {}; return Object.keys(messages).reduce((formattedMessages, key) => { const formattedMessage = !messages[key] && locale !== DEFAULT_LOCALE ? defaultFormattedMessages[key] : messages[key]; return Object.assign(formattedMessages, { [key]: formattedMessage }); }, {}); }; export const translationMessages = { tr: formatTranslationMessages('tr', trTranslationMessages) };
py-az-cli/py-az-cli
pyaz/group/deployment/operation/__init__.py
<filename>pyaz/group/deployment/operation/__init__.py ''' Manage deployment operations. ''' from .... pyaz_utils import _call_az def list(name, resource_group, top=None): ''' Required Parameters: - name -- The deployment name. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - top -- The number of results to return. ''' return _call_az("az group deployment operation list", locals()) def show(name, operation_ids, resource_group): ''' Required Parameters: - name -- The deployment name. - operation_ids -- A list of operation ids to show - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` ''' return _call_az("az group deployment operation show", locals())
VladimirMetodiev/JavaDevelopment
src/functionalProgrammingExercises/CustomMinFunction.java
<filename>src/functionalProgrammingExercises/CustomMinFunction.java package functionalProgrammingExercises; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class CustomMinFunction { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] numbers = Arrays.stream(input.nextLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); Function<int[], Integer> getMin = (arr) -> { int min = arr[0]; for (int a = 1; a < arr.length; a++) { if(min > arr[a]) min = arr[a]; } return min; }; System.out.println(getMin.apply(numbers)); } } //Condition //Write a simple program that reads a set of numbers from the console and finds the smallest of the numbers using //a simple Function<Integer[], Integer> . //Test //16 28 3 17 -4 19 8 23 0 7 //-4 //6 37 -9 16 -3 27 14 -9 -2 19 //-9 //Solution // public static void main(String[] args) { // Scanner input = new Scanner(System.in); // // List<Integer> num = Arrays.stream(input.nextLine().split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()); // int minimum = Collections.min(num); // // System.out.println(minimum); // }
Lazyuki/DiscordStatsBot
commands/unignore.js
module.exports.name = 'unignore'; module.exports.alias = [ 'unignore' ]; module.exports.isAllowed = (message) => { return message.member.hasPermission('ADMINISTRATOR'); }; module.exports.help = '`,unignore <#channel | ID>`Unignore a channel from the list of ignored channels.'; module.exports.command = (message, content, bot, server) => { let arr = server.ignoredChannels; let chan = server.guild.channels.get(content); if (chan) { let index = arr.indexOf(content); if (index == -1) return; arr.splice(index, 1); message.channel.send(`<#${content}> is no longer ignored`); } else if (message.mentions.channels.size != 0) { for (let [id,] of message.mentions.channels) { let index = arr.indexOf(id); if (index == -1) return; arr.splice(index, 1); message.channel.send(`<#${id}> is no longer ignored`); } } };
arsmn/ontest-server
module/hash/hasher.go
<filename>module/hash/hasher.go package hash import "context" type Hasher interface { Compare(ctx context.Context, password []byte, hash []byte) error Generate(ctx context.Context, password []byte) ([]byte, error) } type Provider interface { Hasher() Hasher }
deebugger/redirector
service/webService/src/main/webapp/uxData/scripts/directives/BtnSwitch.js
/** * Copyright 2017 Comcast Cable Communications Management, 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. * * @author <NAME> (<EMAIL>) */ angular.module('uxData').directive('btnSwitch', function () { return { restrict: 'A', require: 'ngModel', templateUrl: '../uxData/views/switcher.html', replace: true, link: function (scope, element, attrs, ngModel) { // Specify how UI should be updated ngModel.$render = function () { render(); }; var render = function () { var val = ngModel.$viewValue; var open = angular.element(element.children()[0]); open.removeClass(val ? 'hide' : 'show'); open.addClass(val ? 'show' : 'hide'); var closed = angular.element(element.children()[1]); closed.removeClass(val ? 'show' : 'hide'); closed.addClass(val ? 'hide' : 'show'); }; // Listen for the button click event to enable binding element.bind('click', function (event) { event.preventDefault(); event.stopPropagation(); scope.$apply(toggle); }); // Toggle the model value function toggle() { var val = ngModel.$viewValue; ngModel.$setViewValue(!val); render(); } if (!ngModel) { //TODO: Indicate that something is missing! return; } // do nothing if no ng-model // Initial render render(); } }; });
fintx/fintx-framework
src/main/java/org/fintx/business/service/impl/RequestFailSvcImpl.java
package org.fintx.business.service.impl; import org.fintx.business.dao.RequestFailDao; import org.fintx.business.entity.RequestFail; import org.fintx.business.service.RequestFailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RequestFailSvcImpl implements RequestFailService { @Autowired private RequestFailDao requestFailDao; @Override public int add(RequestFail request) { return requestFailDao.add(request); } }
maestre3d/lifetrack-sandbox
pkg/infrastructure/persistence/dbpool/dynamo.go
<reponame>maestre3d/lifetrack-sandbox<filename>pkg/infrastructure/persistence/dbpool/dynamo.go package dbpool import ( "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/maestre3d/lifetrack-sanbox/pkg/infrastructure/configuration" "github.com/maestre3d/lifetrack-sanbox/pkg/infrastructure/remote" ) // NewDynamoDBPool creates a new AWS DynamoDB connection pool func NewDynamoDBPool(cfg configuration.Configuration) *dynamodb.DynamoDB { return dynamodb.New(remote.NewAWSSession(cfg.DynamoTable.Region)) }
anahubert/special-disco
routes/userRoutes.js
const express = require('express'); const userController = require('./../controllers/userController'); const authController = require('./../controllers/authController'); const ratingController = require('./../controllers/ratingController'); const router = express.Router(); router.post('/signup', authController.signup); router.post('/login', authController.login); router.get('/user/:id', ratingController.getUserLikes); router.get('/most-liked', ratingController.getMostLiked); // authenticated calls router.use(authController.protect); router.post('/logout', authController.logout); router.get('/me', userController.getMe, userController.getUser); router.patch( '/me/update-password', userController.getMe, authController.updatePassword ); router.post('/user/:id/like', ratingController.likeUser); router.delete('/user/:id/unlike', ratingController.unlikeUser); module.exports = router;
xny838754132/designPatterns
src/com/nai/simplefactory/Client.java
<filename>src/com/nai/simplefactory/Client.java package com.nai.simplefactory; /** * 简单工厂模式~ */ public class Client { public static void main(String[] args) { Operation operate = OperationFactory.createOperate("+"); operate.setNumberA(10); operate.setNumberB(20); double result = 0; try { result = operate.getResult(); } catch (Exception e) { e.printStackTrace(); } System.out.println(result); } }
WillZhuang/ethereum-lite-explorer
node_modules/@alethio/cms/dist/component/ICmsRendererConfig.js
//# sourceMappingURL=ICmsRendererConfig.js.map
marvk/vatsim-api
src/main/java/net/marvk/fs/vatsim/api/data/VatsimCountry.java
<reponame>marvk/vatsim-api package net.marvk.fs.vatsim.api.data; import lombok.Data; @Data public class VatsimCountry { private final String name; private final String shorthand; private final String discriminator; }
kkcookies99/UAST
Dataset/Leetcode/valid/67/273.c
<reponame>kkcookies99/UAST char * XXX(char * a, char * b){ int a_size = strlen(a); int b_size = strlen(b); char *c; int f = 0; //最终进位标志 if(b_size < a_size){ c = (char *)malloc(a_size*sizeof(char)); memset(c, 0, a_size); memcpy(&c[a_size - b_size], b, b_size); } else if(b_size >= a_size){ c = (char *)malloc(b_size*sizeof(char)); memset(c, 0, b_size); memcpy(&c[b_size - a_size], a, a_size); } int tem = 0; if(b_size < a_size){ //a + c for(int i = a_size-1; i > 0; i--){ tem = (a[i] - '0') + (c[i] - '0'); switch(tem){ case 0: c[i] = '0'; break; case 1: c[i] = '1'; break; case 2: c[i] = '0'; c[i-1]+= 1; break; case 3: c[i] = '1'; c[i-1]+= 1; break; }; } } else if(b_size >= a_size){ //b + c for(int i = b_size-1; i > 0; i--){ tem = (b[i] - '0') + (c[i] - '0'); switch(tem){ case 0: c[i] = '0'; break; case 1: c[i] = '1'; break; case 2: c[i] = '0'; c[i-1]+= 1; break; case 3: c[i] = '1'; c[i-1]+= 1; break; }; } } if(b_size < a_size){ tem = (a[0] - '0') + (c[0] - '0'); switch(tem){ case 0: c[0] = '0'; break; case 1: c[0] = '1'; break; case 2: c[0] = '0'; f = 1; break; case 3: c[0] = '1'; f = 1; break; }; } else if(b_size >= a_size){ tem = (b[0] - '0') + (c[0] - '0'); switch(tem){ case 0: c[0] = '0'; break; case 1: c[0] = '1'; break; case 2: c[0] = '0'; f = 1; break; case 3: c[0] = '1'; f = 1; break; }; } if(f){ char *d = (char *)malloc(sizeof(char) * strlen(c)); d[0] = '1'; memcpy(&d[1], c, strlen(c)); return d; } else return c; return c; } undefined for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
mjuenema/python-terrascript
tests/test_provider_gavinbunney_kubectl.py
# tests/test_provider_gavinbunney_kubectl.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:20:27 UTC) def test_provider_import(): import terrascript.provider.gavinbunney.kubectl def test_resource_import(): from terrascript.resource.gavinbunney.kubectl import kubectl_manifest from terrascript.resource.gavinbunney.kubectl import kubectl_server_version def test_datasource_import(): from terrascript.data.gavinbunney.kubectl import kubectl_file_documents from terrascript.data.gavinbunney.kubectl import kubectl_filename_list from terrascript.data.gavinbunney.kubectl import kubectl_path_documents from terrascript.data.gavinbunney.kubectl import kubectl_server_version # TODO: Shortcut imports without namespace for official and supported providers. # TODO: This has to be moved into a required_providers block. # def test_version_source(): # # import terrascript.provider.gavinbunney.kubectl # # t = terrascript.provider.gavinbunney.kubectl.kubectl() # s = str(t) # # assert 'https://github.com/gavinbunney/terraform-provider-kubectl' in s # assert '1.11.3' in s
yuiwashita/Strata
modules/pricer/src/main/java/com/opengamma/strata/pricer/credit/IsdaCdsHelper.java
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.credit; import java.time.LocalDate; import java.time.Period; import java.util.Optional; import java.util.OptionalDouble; import java.util.stream.Stream; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.CurrencyAmount; import com.opengamma.strata.basics.date.BusinessDayConvention; import com.opengamma.strata.basics.date.DayCount; import com.opengamma.strata.basics.date.DayCounts; import com.opengamma.strata.basics.date.HolidayCalendarId; import com.opengamma.strata.market.curve.NodalCurve; import com.opengamma.strata.pricer.PricingException; import com.opengamma.strata.pricer.impl.credit.isda.AccrualOnDefaultFormulae; import com.opengamma.strata.pricer.impl.credit.isda.AnalyticCdsPricer; import com.opengamma.strata.pricer.impl.credit.isda.CdsAnalytic; import com.opengamma.strata.pricer.impl.credit.isda.CdsPriceType; import com.opengamma.strata.pricer.impl.credit.isda.FastCreditCurveBuilder; import com.opengamma.strata.pricer.impl.credit.isda.IsdaCompliantCreditCurve; import com.opengamma.strata.pricer.impl.credit.isda.IsdaCompliantCreditCurveBuilder; import com.opengamma.strata.pricer.impl.credit.isda.IsdaCompliantYieldCurve; import com.opengamma.strata.pricer.impl.credit.isda.IsdaCompliantYieldCurveBuild; import com.opengamma.strata.pricer.impl.credit.isda.IsdaInstrumentTypes; import com.opengamma.strata.product.credit.ResolvedCds; import com.opengamma.strata.product.credit.type.CdsConvention; import com.opengamma.strata.product.credit.type.IsdaYieldCurveConvention; /** * Helper for interacting with the underlying Analytics layer for CDS pricing. * <p> * Translation from Strata business objects such as DayCount and StubMethod is done here. * The translation of underlying types for the yield curve is performed here. * Par rate representations of the curves are calibrated and converted to ISDA calibrated curves. * Present value of the expanded CDS product (single name or index) is calculated here. */ class IsdaCdsHelper { // hard-coded reference data public static final ReferenceData REF_DATA = ReferenceData.standard(); /** * DayCount used with calculating time during curve calibration. * <p> * The model expects ACT_365F, but this value is not on the trade or the convention. */ private final static DayCount CURVE_DAY_COUNT = DayCounts.ACT_365F; /** * When protection starts, at the start or end of the day. * <p> * If true, then protections starts at the beginning of the day, otherwise it is at the end. * The model expects this, but it is not a property of the trade or convention. * If true the protection is from the start of day and the effective accrual start and end dates are one day less. * The exception is the final accrual end date which should have one day added * (if protectionFromStartOfDay = true) in the final CDSCouponDes to compensate for this, so the * accrual end date is just the CDS maturity. The effect of having protectionFromStartOfDay = true * is to add an extra day of protection. */ private final static boolean PROTECT_START = true; /** * ISDA Standard model implementation in analytics. */ private final static AnalyticCdsPricer CALCULATOR = new AnalyticCdsPricer(); //------------------------------------------------------------------------- /** * Calculate present value on the specified valuation date. * * @param valuationDate date that present value is calculated on, also date that curves will be calibrated to * @param product the expanded CDS product * @param yieldCurve the par rates representation of the ISDA yield curve * @param creditCurve the par rates representation of the ISDA credit curve * @param recoveryRate the recovery rate for the reference entity/issue * @param scalingFactor the scaling factor * @return the present value of the expanded CDS product */ public static CurrencyAmount price( LocalDate valuationDate, ResolvedCds product, NodalCurve yieldCurve, NodalCurve creditCurve, double recoveryRate, double scalingFactor) { // setup CdsAnalytic cdsAnalytic = toAnalytic(valuationDate, product, recoveryRate); IsdaCompliantYieldCurve yieldCurveAnalytics = IsdaCompliantYieldCurve.makeFromRT(yieldCurve.getXValues(), yieldCurve.getYValues()); IsdaCompliantCreditCurve creditCurveAnalytics = IsdaCompliantCreditCurve.makeFromRT(creditCurve.getXValues(), creditCurve.getYValues()); // calculate double coupon = product.getCoupon(); double pv = CALCULATOR.pv(cdsAnalytic, yieldCurveAnalytics, creditCurveAnalytics, coupon, CdsPriceType.DIRTY, 0d); // create result int sign = product.getBuySellProtection().isBuy() ? 1 : -1; double notional = product.getNotional(); double factor = scalingFactor; double adjusted = pv * notional * sign * factor; double upfrontFeeAmount = priceUpfrontFee( valuationDate, product.getUpfrontFeeAmount(), product.getUpfrontFeePaymentDate(), yieldCurveAnalytics) * sign; double adjustedPlusFee = adjusted + upfrontFeeAmount; return CurrencyAmount.of(product.getCurrency(), adjustedPlusFee); } //------------------------------------------------------------------------- // The fee is always calculated as being payable by the protection buyer. // If the seller should pay the fee, then a negative amount is used. private static double priceUpfrontFee( LocalDate valuationDate, OptionalDouble amount, Optional<LocalDate> paymentDate, IsdaCompliantYieldCurve yieldCurve) { if (!amount.isPresent()) { return 0d; // no fee } if (!paymentDate.get().isAfter(valuationDate)) { return 0d; // fee already paid } double feeSettleYearFraction = CURVE_DAY_COUNT.yearFraction(valuationDate, paymentDate.get()); double discountFactor = yieldCurve.getDiscountFactor(feeSettleYearFraction); return discountFactor * amount.getAsDouble(); } /** * Calculate par spread on the specified valuation date. * * @param valuationDate date that par spread is calculated on, also date that curves will be calibrated to * @param product the expanded CDS product * @param yieldCurve the par rates representation of the ISDA yield curve * @param creditCurve the par rates representation of the ISDA credit curve * @param recoveryRate the recovery rate for the reference entity/issue * @return the par spread of the expanded CDS product */ public static double parSpread(LocalDate valuationDate, ResolvedCds product, NodalCurve yieldCurve, NodalCurve creditCurve, double recoveryRate) { // setup CdsAnalytic cdsAnalytic = toAnalytic(valuationDate, product, recoveryRate); IsdaCompliantYieldCurve yieldCurveAnalytics = IsdaCompliantYieldCurve.makeFromRT(yieldCurve.getXValues(), yieldCurve.getYValues()); IsdaCompliantCreditCurve creditCurveAnalytics = IsdaCompliantCreditCurve.makeFromRT(creditCurve.getXValues(), creditCurve.getYValues()); return CALCULATOR.parSpread(cdsAnalytic, yieldCurveAnalytics, creditCurveAnalytics); } // Converts the interest rate curve par rates to the corresponding analytics form. // Calibration is performed here. public static IsdaCompliantYieldCurve createIsdaDiscountCurve( LocalDate valuationDate, IsdaYieldCurveInputs yieldCurve) { try { // model does not use floating leg of underlying IRS IsdaYieldCurveConvention curveConvention = yieldCurve.getCurveConvention(); Period swapInterval = curveConvention.getFixedPaymentFrequency().getPeriod(); DayCount mmDayCount = curveConvention.getMoneyMarketDayCount(); DayCount swapDayCount = curveConvention.getFixedDayCount(); BusinessDayConvention convention = curveConvention.getBusinessDayConvention(); HolidayCalendarId holidayCalendar = curveConvention.getHolidayCalendar(); LocalDate spotDate = curveConvention.calculateSpotDateFromTradeDate(valuationDate, REF_DATA); IsdaInstrumentTypes[] types = Stream.of(yieldCurve.getYieldCurveInstruments()) .map(IsdaCdsHelper::mapInstrumentType) .toArray(IsdaInstrumentTypes[]::new); IsdaCompliantYieldCurveBuild builder = new IsdaCompliantYieldCurveBuild( valuationDate, spotDate, types, yieldCurve.getYieldCurvePoints(), mmDayCount, swapDayCount, swapInterval, CURVE_DAY_COUNT, convention, holidayCalendar.resolve(REF_DATA)); return builder.build(yieldCurve.getParRates()); } catch (Exception ex) { throw new PricingException("Error converting the ISDA Discount Curve: " + ex.getMessage(), ex); } } // Converts the credit curve par rates to the corresponding analytics form. // Calibration is performed here. public static IsdaCompliantCreditCurve createIsdaCreditCurve( LocalDate valuationDate, IsdaCreditCurveInputs curveCurve, IsdaCompliantYieldCurve yieldCurve, double recoveryRate) { try { CdsConvention cdsConvention = curveCurve.getCdsConvention(); FastCreditCurveBuilder builder = new FastCreditCurveBuilder( AccrualOnDefaultFormulae.ORIGINAL_ISDA, IsdaCompliantCreditCurveBuilder.ArbitrageHandling.Fail); return builder.calibrateCreditCurve( valuationDate, cdsConvention.calculateUnadjustedStepInDate(valuationDate), cdsConvention.calculateAdjustedSettleDate(valuationDate, REF_DATA), cdsConvention.calculateAdjustedStartDate(valuationDate, REF_DATA), curveCurve.getEndDatePoints(), curveCurve.getParRates(), cdsConvention.isPayAccruedOnDefault(), cdsConvention.getPaymentFrequency().getPeriod(), cdsConvention.getStubConvention(), PROTECT_START, yieldCurve, recoveryRate); } catch (Exception ex) { throw new PricingException("Error converting the ISDA Credit Curve: " + ex.getMessage(), ex); } } // Converts the credit curve par rates to the corresponding analytics form. // Calibration is performed here. public static IsdaCompliantCreditCurve createIsdaCreditCurve( LocalDate valuationDate, IsdaCreditCurveInputs curveCurve, NodalCurve yieldCurve, double recoveryRate) { try { IsdaCompliantYieldCurve yieldCurveAnalytics = IsdaCompliantYieldCurve.makeFromRT(yieldCurve.getXValues(), yieldCurve.getYValues()); CdsConvention cdsConvention = curveCurve.getCdsConvention(); FastCreditCurveBuilder builder = new FastCreditCurveBuilder( AccrualOnDefaultFormulae.ORIGINAL_ISDA, IsdaCompliantCreditCurveBuilder.ArbitrageHandling.Fail); return builder.calibrateCreditCurve( valuationDate, cdsConvention.calculateUnadjustedStepInDate(valuationDate), cdsConvention.calculateAdjustedSettleDate(valuationDate, REF_DATA), cdsConvention.calculateAdjustedStartDate(valuationDate, REF_DATA), curveCurve.getEndDatePoints(), curveCurve.getParRates(), cdsConvention.isPayAccruedOnDefault(), cdsConvention.getPaymentFrequency().getPeriod(), cdsConvention.getStubConvention(), PROTECT_START, yieldCurveAnalytics, recoveryRate); } catch (Exception ex) { throw new PricingException("Error converting the ISDA Credit Curve: " + ex.getMessage(), ex); } } // Converts the expanded CDS product to the corresponding analytics form. private static CdsAnalytic toAnalytic(LocalDate valuationDate, ResolvedCds product, double recoveryRate) { try { return new CdsAnalytic( valuationDate, valuationDate.plusDays(1), valuationDate, product.getStartDate(), product.getEndDate(), product.isPayAccruedOnDefault(), product.getPaymentInterval(), product.getStubConvention(), PROTECT_START, recoveryRate, product.getBusinessDayAdjustment().getConvention(), product.getBusinessDayAdjustment().getCalendar().resolve(REF_DATA), product.getAccrualDayCount(), CURVE_DAY_COUNT); } catch (Exception ex) { throw new PricingException("Error converting the trade to an analytic: " + ex.getMessage(), ex); } } //------------------------------------------------------------------------- // Converts type of interest curve underlying to the corresponding analytics value. private static IsdaInstrumentTypes mapInstrumentType(IsdaYieldCurveUnderlyingType input) { switch (input) { case ISDA_MONEY_MARKET: return IsdaInstrumentTypes.MONEY_MARKET; case ISDA_SWAP: return IsdaInstrumentTypes.SWAP; default: throw new IllegalStateException("Unexpected underlying type: " + input); } } }
4everalone/nano
sample/webservice/eBayDemoApp/src/com/ebay/trading/api/ReviseMyMessagesFoldersRequestType.java
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.trading.api; import java.io.Serializable; import com.leansoft.nano.annotation.*; import java.util.List; /** * * Renames, removes, or restores the specified My Messages folders for * a given user. * */ @RootElement(name = "ReviseMyMessagesFoldersRequest", namespace = "urn:ebay:apis:eBLBaseComponents") public class ReviseMyMessagesFoldersRequestType extends AbstractRequestType implements Serializable { private static final long serialVersionUID = -1L; @Element(name = "Operation") @Order(value=0) public MyMessagesFolderOperationCodeType operation; @Element(name = "FolderID") @Order(value=1) public List<Long> folderID; @Element(name = "FolderName") @Order(value=2) public List<String> folderName; }
olevitt/sugoi-api
sugoi-api-core/src/main/java/fr/insee/sugoi/sugoiapicore/utils/broker/JmsFactory.java
<gh_stars>0 package fr.insee.sugoi.sugoiapicore.utils.broker; import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.support.converter.MappingJackson2MessageConverter; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.jms.support.converter.MessageType; public class JmsFactory { public static ActiveMQConnectionFactory connectionFactory(String broker_url) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL(broker_url); return connectionFactory; } public static JmsTemplate getJmsTemplate(String broker_url) { JmsTemplate template = new JmsTemplate(); template.setConnectionFactory(connectionFactory(broker_url)); template.setMessageConverter(messageConverter()); return template; } public static DefaultJmsListenerContainerFactory jmsListenerContainerFactory(String broker_url) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory(broker_url)); factory.setConcurrency("1-1"); return factory; } public static MessageConverter messageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setTargetType(MessageType.TEXT); converter.setTypeIdPropertyName("_type"); return converter; } }
KAIXIE/ChatDemoUI3.0
app/src/main/java/com/hyphenate/chatuidemo/mvp/view/fragment/BlackFragment.java
<reponame>KAIXIE/ChatDemoUI3.0<gh_stars>0 package com.hyphenate.chatuidemo.mvp.view.fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import com.hyphenate.chatuidemo.R; import com.hyphenate.chatuidemo.base.BaseLazyFragment; import com.hyphenate.chatuidemo.mvp.model.BlackModel; import com.hyphenate.chatuidemo.mvp.presenter.BlackFragmentPresenter; import com.hyphenate.chatuidemo.mvp.presenter.impl.BlackFragmentPresenterImpl; import com.hyphenate.chatuidemo.mvp.view.BlackFragmentView; import com.hyphenate.chatuidemo.ui.my.MyAdapter; import com.hyphenate.chatuidemo.utils.LogUtil; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.Unbinder; /** * Created by Administrator on 2017/11/23. */ public class BlackFragment extends BaseLazyFragment implements BlackFragmentView { // private List<String> mlist = new ArrayList<>(); // private List<BlackModel.ArticlePagerBean.RowsBean> mList = new ArrayList<>(); private BlackModel mBlackModel; @BindView(R.id.recycler_black) RecyclerView mRecyclerBlack; @BindView(R.id.refreshLayout) SmartRefreshLayout mRefreshLayout; Unbinder unbinder; private MyAdapter myAdapter; private BlackFragmentPresenter mBlackFragmentPresenter; private List<BlackModel.ArticlePagerBean.RowsBean> mRowsBeanList; @Override protected int getLayoutID() { return R.layout.fragment_black; } @Override protected void initFragment() { mBlackFragmentPresenter = new BlackFragmentPresenterImpl(); mBlackFragmentPresenter.attachView(this); mBlackFragmentPresenter.getData("1","10","1"); //假数据 initData(); mRecyclerBlack.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false)); // blackRecyclerAdapter = new BlackDetailPhotoAdapter(getContext(),mlist); // recyclerBlack.setAdapter(blackRecyclerAdapter); // blackRecyclerAdapter.notifyDataSetChanged(); myAdapter = new MyAdapter(mRowsBeanList, getContext()); mRecyclerBlack.setAdapter(myAdapter); myAdapter.addHeaderView(LayoutInflater.from(getContext()).inflate(R.layout.item_black_head, null)); mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { refreshlayout.finishRefresh(2000); //假数据 initData(); } }); mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() { @Override public void onLoadmore(RefreshLayout refreshlayout) { refreshlayout.finishLoadmore(2000); } }); } private void initData() { for (int i = 0; i < 10; i++) { // mlist.add("" + i); } } @Override public void showProgress() { } @Override public void hideProgress() { } @Override public void showMsg(String message) { } @Override public void showError(String message) { } @Override public void setData(BlackModel blackModel) { mBlackModel = blackModel; mRowsBeanList = mBlackModel.getArticlePager().getRows(); LogUtil.e("---"+ mRowsBeanList.size()); LogUtil.e("---"+ mRowsBeanList.get(0)); } }
robertb-r/fiji
src-plugins/Script_Editor/src/main/java/fiji/scripting/TextEditor.java
package fiji.scripting; import common.RefreshScripts; import fiji.scripting.java.Refresh_Javas; import ij.IJ; import ij.WindowManager; import ij.gui.GenericDialog; import ij.io.SaveDialog; import ij.plugin.BrowserLauncher; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.ZipException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.Position; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; public class TextEditor extends JFrame implements ActionListener, ChangeListener { protected JTabbedPane tabbed; protected JMenuItem newFile, open, save, saveas, compileAndRun, compile, debug, close, undo, redo, cut, copy, paste, find, replace, selectAll, autocomplete, resume, terminate, kill, gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports, removeTrailingWhitespace, findNext, findPrevious, openHelp, addImport, clearScreen, nextError, previousError, openHelpWithoutFrames, nextTab, previousTab, runSelection, extractSourceJar, toggleBookmark, listBookmarks, openSourceForClass, newPlugin, installMacro, openSourceForMenuItem, showDiff, commit, ijToFront, openMacroFunctions, decreaseFontSize, increaseFontSize, chooseFontSize, chooseTabSize, gitGrep, loadToolsJar, openInGitweb, replaceTabsWithSpaces, replaceSpacesWithTabs, toggleWhiteSpaceLabeling, zapGremlins; protected RecentFilesMenuItem openRecent; protected JMenu gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, toolsMenu, runMenu, whiteSpaceMenu; protected int tabsMenuTabsStart; protected Set<JMenuItem> tabsMenuItems; protected FindAndReplaceDialog findDialog; protected JCheckBoxMenuItem autoSave, showDeprecation, wrapLines; protected JTextArea errorScreen = new JTextArea(); protected final String templateFolder = "templates/"; protected Languages.Language[] availableLanguages = Languages.getInstance().languages; protected int compileStartOffset; protected Position compileStartPosition; protected ErrorHandler errorHandler; public TextEditor(String path) { super("Script Editor"); WindowManager.addWindow(this); // Initialize menu int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); int shift = ActionEvent.SHIFT_MASK; JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); newFile = addToMenu(file, "New", KeyEvent.VK_N, ctrl); newFile.setMnemonic(KeyEvent.VK_N); open = addToMenu(file, "Open...", KeyEvent.VK_O, ctrl); open.setMnemonic(KeyEvent.VK_O); openRecent = new RecentFilesMenuItem(this); openRecent.setMnemonic(KeyEvent.VK_R); file.add(openRecent); save = addToMenu(file, "Save", KeyEvent.VK_S, ctrl); save.setMnemonic(KeyEvent.VK_S); saveas = addToMenu(file, "Save as...", 0, 0); saveas.setMnemonic(KeyEvent.VK_A); file.addSeparator(); makeJar = addToMenu(file, "Export as .jar", 0, 0); makeJar.setMnemonic(KeyEvent.VK_E); makeJarWithSource = addToMenu(file, "Export as .jar (with source)", 0, 0); makeJarWithSource.setMnemonic(KeyEvent.VK_X); file.addSeparator(); close = addToMenu(file, "Close", KeyEvent.VK_W, ctrl); mbar.add(file); JMenu edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); undo = addToMenu(edit, "Undo", KeyEvent.VK_Z, ctrl); redo = addToMenu(edit, "Redo", KeyEvent.VK_Y, ctrl); edit.addSeparator(); selectAll = addToMenu(edit, "Select All", KeyEvent.VK_A, ctrl); cut = addToMenu(edit, "Cut", KeyEvent.VK_X, ctrl); copy = addToMenu(edit, "Copy", KeyEvent.VK_C, ctrl); paste = addToMenu(edit, "Paste", KeyEvent.VK_V, ctrl); edit.addSeparator(); find = addToMenu(edit, "Find...", KeyEvent.VK_F, ctrl); find.setMnemonic(KeyEvent.VK_F); findNext = addToMenu(edit, "Find Next", KeyEvent.VK_F3, 0); findNext.setMnemonic(KeyEvent.VK_N); findPrevious = addToMenu(edit, "Find Previous", KeyEvent.VK_F3, shift); findPrevious.setMnemonic(KeyEvent.VK_P); replace = addToMenu(edit, "Find and Replace...", KeyEvent.VK_H, ctrl); gotoLine = addToMenu(edit, "Goto line...", KeyEvent.VK_G, ctrl); gotoLine.setMnemonic(KeyEvent.VK_G); toggleBookmark = addToMenu(edit, "Toggle Bookmark", KeyEvent.VK_B, ctrl); toggleBookmark.setMnemonic(KeyEvent.VK_B); listBookmarks = addToMenu(edit, "List Bookmarks", 0, 0); listBookmarks.setMnemonic(KeyEvent.VK_O); edit.addSeparator(); // Font adjustments decreaseFontSize = addToMenu(edit, "Decrease font size", KeyEvent.VK_MINUS, ctrl); decreaseFontSize.setMnemonic(KeyEvent.VK_D); increaseFontSize = addToMenu(edit, "Increase font size", KeyEvent.VK_PLUS, ctrl); increaseFontSize.setMnemonic(KeyEvent.VK_C); fontSizeMenu = new JMenu("Font sizes"); fontSizeMenu.setMnemonic(KeyEvent.VK_Z); boolean[] fontSizeShortcutUsed = new boolean[10]; ButtonGroup buttonGroup = new ButtonGroup(); for (final int size : new int[] { 8, 10, 12, 16, 20, 28, 42 } ) { JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size + " pt"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { getEditorPane().setFontSize(size); updateTabAndFontSize(false); } }); for (char c : ("" + size).toCharArray()) { int digit = c - '0'; if (!fontSizeShortcutUsed[digit]) { item.setMnemonic(KeyEvent.VK_0 + digit); fontSizeShortcutUsed[digit] = true; break; } } buttonGroup.add(item); fontSizeMenu.add(item); } chooseFontSize = new JRadioButtonMenuItem("Other...", false); chooseFontSize.setMnemonic(KeyEvent.VK_O); chooseFontSize.addActionListener(this); buttonGroup.add(chooseFontSize); fontSizeMenu.add(chooseFontSize); edit.add(fontSizeMenu); // Add tab size adjusting menu tabSizeMenu = new JMenu("Tab sizes"); tabSizeMenu.setMnemonic(KeyEvent.VK_T); ButtonGroup bg = new ButtonGroup(); for (final int size : new int[] { 2, 4, 8 }) { JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size, size == 8); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { getEditorPane().setTabSize(size); updateTabAndFontSize(false); } }); item.setMnemonic(KeyEvent.VK_0 + (size % 10)); bg.add(item); tabSizeMenu.add(item); } chooseTabSize = new JRadioButtonMenuItem("Other...", false); chooseTabSize.setMnemonic(KeyEvent.VK_O); chooseTabSize.addActionListener(this); bg.add(chooseTabSize); tabSizeMenu.add(chooseTabSize); edit.add(tabSizeMenu); wrapLines = new JCheckBoxMenuItem("Wrap lines"); wrapLines.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { getEditorPane().setLineWrap(wrapLines.getState()); } }); edit.add(wrapLines); edit.addSeparator(); clearScreen = addToMenu(edit, "Clear output panel", 0, 0); clearScreen.setMnemonic(KeyEvent.VK_L); //edit.addSeparator(); //autocomplete = addToMenu(edit, "Autocomplete", KeyEvent.VK_SPACE, ctrl); zapGremlins = addToMenu(edit, "Zap Gremlins", 0, 0); //autocomplete.setMnemonic(KeyEvent.VK_A); edit.addSeparator(); addImport = addToMenu(edit, "Add import...", 0, 0); addImport.setMnemonic(KeyEvent.VK_I); removeUnusedImports = addToMenu(edit, "Remove unused imports", 0, 0); removeUnusedImports.setMnemonic(KeyEvent.VK_U); sortImports = addToMenu(edit, "Sort imports", 0, 0); sortImports.setMnemonic(KeyEvent.VK_S); mbar.add(edit); whiteSpaceMenu = new JMenu("Whitespace"); whiteSpaceMenu.setMnemonic(KeyEvent.VK_W); removeTrailingWhitespace = addToMenu(whiteSpaceMenu, "Remove trailing whitespace", 0, 0); removeTrailingWhitespace.setMnemonic(KeyEvent.VK_W); replaceTabsWithSpaces = addToMenu(whiteSpaceMenu, "Replace tabs with spaces", 0, 0); replaceTabsWithSpaces.setMnemonic(KeyEvent.VK_S); replaceSpacesWithTabs = addToMenu(whiteSpaceMenu, "Replace spaces with tabs", 0, 0); replaceSpacesWithTabs.setMnemonic(KeyEvent.VK_T); toggleWhiteSpaceLabeling = new JRadioButtonMenuItem("Label whitespace"); toggleWhiteSpaceLabeling.setMnemonic(KeyEvent.VK_L); toggleWhiteSpaceLabeling.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getTextArea().setWhitespaceVisible(toggleWhiteSpaceLabeling.isSelected()); } }); whiteSpaceMenu.add(toggleWhiteSpaceLabeling); edit.add(whiteSpaceMenu); JMenu languages = new JMenu("Language"); languages.setMnemonic(KeyEvent.VK_L); ButtonGroup group = new ButtonGroup(); for (final Languages.Language language : Languages.getInstance().languages) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(language.menuLabel); if (language.shortCut != 0) item.setMnemonic(language.shortCut); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setLanguage(language); } }); group.add(item); languages.add(item); language.setMenuItem(item); } mbar.add(languages); JMenu templates = new JMenu("Templates"); templates.setMnemonic(KeyEvent.VK_T); addTemplates(templates); mbar.add(templates); runMenu = new JMenu("Run"); runMenu.setMnemonic(KeyEvent.VK_R); compileAndRun = addToMenu(runMenu, "Compile and Run", KeyEvent.VK_R, ctrl); compileAndRun.setMnemonic(KeyEvent.VK_R); runSelection = addToMenu(runMenu, "Run selected code", KeyEvent.VK_R, ctrl | shift); runSelection.setMnemonic(KeyEvent.VK_S); compile = addToMenu(runMenu, "Compile", KeyEvent.VK_C, ctrl | shift); compile.setMnemonic(KeyEvent.VK_C); autoSave = new JCheckBoxMenuItem("Auto-save before compiling"); runMenu.add(autoSave); showDeprecation = new JCheckBoxMenuItem("Show deprecations"); runMenu.add(showDeprecation); installMacro = addToMenu(runMenu, "Install Macro", KeyEvent.VK_I, ctrl); installMacro.setMnemonic(KeyEvent.VK_I); runMenu.addSeparator(); nextError = addToMenu(runMenu, "Next Error", KeyEvent.VK_F4, 0); nextError.setMnemonic(KeyEvent.VK_N); previousError = addToMenu(runMenu, "Previous Error", KeyEvent.VK_F4, shift); previousError.setMnemonic(KeyEvent.VK_P); runMenu.addSeparator(); kill = addToMenu(runMenu, "Kill running script...", 0, 0); kill.setMnemonic(KeyEvent.VK_K); kill.setEnabled(false); runMenu.addSeparator(); debug = addToMenu(runMenu, "Start Debugging", KeyEvent.VK_D, ctrl); debug.setMnemonic(KeyEvent.VK_D); resume = addToMenu(runMenu, "Resume", 0, 0); resume.setMnemonic(KeyEvent.VK_R); terminate = addToMenu(runMenu, "Terminate", 0, 0); terminate.setMnemonic(KeyEvent.VK_T); mbar.add(runMenu); toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic(KeyEvent.VK_O); openHelpWithoutFrames = addToMenu(toolsMenu, "Open Help for Class...", 0, 0); openHelpWithoutFrames.setMnemonic(KeyEvent.VK_O); openHelp = addToMenu(toolsMenu, "Open Help for Class (with frames)...", 0, 0); openHelp.setMnemonic(KeyEvent.VK_P); openMacroFunctions = addToMenu(toolsMenu, "Open Help on Macro Functions...", 0, 0); openMacroFunctions.setMnemonic(KeyEvent.VK_H); extractSourceJar = addToMenu(toolsMenu, "Extract source .jar...", 0, 0); extractSourceJar.setMnemonic(KeyEvent.VK_E); newPlugin = addToMenu(toolsMenu, "Create new plugin...", 0, 0); newPlugin.setMnemonic(KeyEvent.VK_C); ijToFront = addToMenu(toolsMenu, "Focus on the main Fiji window", 0, 0); ijToFront.setMnemonic(KeyEvent.VK_F); openSourceForClass = addToMenu(toolsMenu, "Open .java file for class...", 0, 0); openSourceForClass.setMnemonic(KeyEvent.VK_J); openSourceForMenuItem = addToMenu(toolsMenu, "Open .java file for menu item...", 0, 0); openSourceForMenuItem.setMnemonic(KeyEvent.VK_M); mbar.add(toolsMenu); gitMenu = new JMenu("Git"); gitMenu.setMnemonic(KeyEvent.VK_G); showDiff = addToMenu(gitMenu, "Show diff...", 0, 0); showDiff.setMnemonic(KeyEvent.VK_D); commit = addToMenu(gitMenu, "Commit...", 0, 0); commit.setMnemonic(KeyEvent.VK_C); gitGrep = addToMenu(gitMenu, "Grep...", 0, 0); gitGrep.setMnemonic(KeyEvent.VK_G); openInGitweb = addToMenu(gitMenu, "Open in gitweb", 0, 0); openInGitweb.setMnemonic(KeyEvent.VK_W); mbar.add(gitMenu); tabsMenu = new JMenu("Tabs"); tabsMenu.setMnemonic(KeyEvent.VK_A); nextTab = addToMenu(tabsMenu, "Next Tab", KeyEvent.VK_PAGE_DOWN, ctrl); nextTab.setMnemonic(KeyEvent.VK_N); previousTab = addToMenu(tabsMenu, "Previous Tab", KeyEvent.VK_PAGE_UP, ctrl); previousTab.setMnemonic(KeyEvent.VK_P); tabsMenu.addSeparator(); tabsMenuTabsStart = tabsMenu.getItemCount(); tabsMenuItems = new HashSet<JMenuItem>(); mbar.add(tabsMenu); // Add the editor and output area tabbed = new JTabbedPane(); tabbed.addChangeListener(this); open(null); // make sure the editor pane is added tabbed.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); getContentPane().add(tabbed); // for Eclipse and MS Visual Studio lovers addAccelerator(compileAndRun, KeyEvent.VK_F11, 0, true); addAccelerator(compileAndRun, KeyEvent.VK_F5, 0, true); addAccelerator(debug, KeyEvent.VK_F11, ctrl, true); addAccelerator(debug, KeyEvent.VK_F5, shift, true); addAccelerator(nextTab, KeyEvent.VK_PAGE_DOWN, ctrl, true); addAccelerator(previousTab, KeyEvent.VK_PAGE_UP, ctrl, true); addAccelerator(increaseFontSize, KeyEvent.VK_EQUALS, ctrl | shift, true); // make sure that the window is not closed by accident addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { while (tabbed.getTabCount() > 0) { if (!handleUnsavedChanges()) return; int index = tabbed.getSelectedIndex(); removeTab(index); } dispose(); } public void windowClosed(WindowEvent e) { WindowManager.removeWindow(TextEditor.this); } }); addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { final EditorPane editorPane = getEditorPane(); if (editorPane != null) editorPane.checkForOutsideChanges(); } }); Font font = new Font("Courier", Font.PLAIN, 12); errorScreen.setFont(font); errorScreen.setEditable(false); errorScreen.setLineWrap(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); try { if (SwingUtilities.isEventDispatchThread()) pack(); else SwingUtilities.invokeAndWait(new Runnable() { public void run() { pack(); }}); } catch (Exception ie) {} getToolkit().setDynamicLayout(true); //added to accomodate the autocomplete part findDialog = new FindAndReplaceDialog(this); setLocationRelativeTo(null); // center on screen open(path); final EditorPane editorPane = getEditorPane(); if (editorPane != null) editorPane.requestFocus(); } public TextEditor(String title, String text) { this(null); final EditorPane editorPane = getEditorPane(); editorPane.setText(text); editorPane.setLanguageByFileName(title); setFileName(title); setTitle(); } /** * Open a new editor to edit the given file, with a templateFile if the file does not exist yet */ public TextEditor(File file, File templateFile) { this(file.exists() ? file.getPath() : templateFile.getPath()); if (!file.exists()) { final EditorPane editorPane = getEditorPane(); try { editorPane.setFile(file.getAbsolutePath()); } catch (IOException e) { IJ.handleException(e); } editorPane.setLanguageByFileName(file.getName()); setTitle(); } } final public RSyntaxTextArea getTextArea() { return getEditorPane(); } public EditorPane getEditorPane() { Tab tab = getTab(); return tab == null ? null : tab.editorPane; } public Languages.Language getCurrentLanguage() { return getEditorPane().currentLanguage; } public JMenuItem addToMenu(JMenu menu, String menuEntry, int key, int modifiers) { JMenuItem item = new JMenuItem(menuEntry); menu.add(item); if (key != 0) item.setAccelerator(KeyStroke.getKeyStroke(key, modifiers)); item.addActionListener(this); return item; } protected static class AcceleratorTriplet { JMenuItem component; int key, modifiers; } protected List<AcceleratorTriplet> defaultAccelerators = new ArrayList<AcceleratorTriplet>(); public void addAccelerator(final JMenuItem component, int key, int modifiers) { addAccelerator(component, key, modifiers, false); } public void addAccelerator(final JMenuItem component, int key, int modifiers, boolean record) { if (record) { AcceleratorTriplet triplet = new AcceleratorTriplet(); triplet.component = component; triplet.key = key; triplet.modifiers = modifiers; defaultAccelerators.add(triplet); } RSyntaxTextArea textArea = getTextArea(); if (textArea != null) addAccelerator(textArea, component, key, modifiers); } public void addAccelerator(RSyntaxTextArea textArea, final JMenuItem component, int key, int modifiers) { textArea.getInputMap().put(KeyStroke.getKeyStroke(key, modifiers), component); textArea.getActionMap().put(component, new AbstractAction() { public void actionPerformed(ActionEvent e) { if (!component.isEnabled()) return; ActionEvent event = new ActionEvent(component, 0, "Accelerator"); TextEditor.this.actionPerformed(event); } }); } public void addDefaultAccelerators(RSyntaxTextArea textArea) { for (AcceleratorTriplet triplet : defaultAccelerators) addAccelerator(textArea, triplet.component, triplet.key, triplet.modifiers); } protected JMenu getMenu(JMenu root, String menuItemPath, boolean createIfNecessary) { int gt = menuItemPath.indexOf('>'); if (gt < 0) return root; String menuLabel = menuItemPath.substring(0, gt); String rest = menuItemPath.substring(gt + 1); for (int i = 0; i < root.getItemCount(); i++) { JMenuItem item = root.getItem(i); if ((item instanceof JMenu) && menuLabel.equals(item.getLabel())) return getMenu((JMenu)item, rest, createIfNecessary); } if (!createIfNecessary) return null; JMenu subMenu = new JMenu(menuLabel); root.add(subMenu); return getMenu(subMenu, rest, createIfNecessary); } /** * Initializes the template menu. */ protected void addTemplates(JMenu templatesMenu) { String url = TextEditor.class.getResource("TextEditor.class").toString(); String classFilePath = "/" + getClass().getName().replace('.', '/') + ".class"; if (!url.endsWith(classFilePath)) return; url = url.substring(0, url.length() - classFilePath.length() + 1) + templateFolder; List<String> templates = new FileFunctions(this).getResourceList(url); Collections.sort(templates); for (String template : templates) { String path = template.replace('/', '>'); JMenu menu = getMenu(templatesMenu, path, true); String label = path.substring(path.lastIndexOf('>') + 1).replace('_', ' '); int dot = label.lastIndexOf('.'); if (dot > 0) label = label.substring(0, dot); final String templateURL = url + template; JMenuItem item = new JMenuItem(label); menu.add(item); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadTemplate(templateURL); } }); } } /** * Loads a template file from the given resource * * @param url The resource to load. */ public void loadTemplate(String url) { createNewDocument(); try { // Load the template InputStream in = new URL(url).openStream(); getTextArea().read(new BufferedReader(new InputStreamReader(in)), null); int dot = url.lastIndexOf('.'); if (dot > 0) { Languages.Language language = Languages.get(url.substring(dot)); if (language != null) setLanguage(language); } } catch (Exception e) { e.printStackTrace(); error("The template '" + url + "' was not found."); } } public void createNewDocument() { open(null); } public boolean fileChanged() { return getEditorPane().fileChanged(); } public boolean handleUnsavedChanges() { return handleUnsavedChanges(false); } public boolean handleUnsavedChanges(boolean beforeCompiling) { if (!fileChanged()) return true; if (beforeCompiling && autoSave.getState()) { save(); return true; } switch (JOptionPane.showConfirmDialog(this, "Do you want to save changes?")) { case JOptionPane.NO_OPTION: return true; case JOptionPane.YES_OPTION: if (save()) return true; } return false; } protected void grabFocus() { toFront(); } protected void grabFocus(final int laterCount) { if (laterCount == 0) { grabFocus(); return; } SwingUtilities.invokeLater(new Thread() { public void run() { grabFocus(laterCount - 1); } }); } public void actionPerformed(ActionEvent ae) { final Object source = ae.getSource(); if (source == newFile) createNewDocument(); else if (source == open) { final EditorPane editorPane = getEditorPane(); String defaultDir = editorPane != null && editorPane.file != null ? editorPane.file.getParent() : System.getProperty("ij.dir"); final String path = openWithDialog("Open...", defaultDir, new String[] { ".class", ".jar" }, false); if (path != null) new Thread() { public void run() { open(path); } }.start(); return; } else if (source == save) save(); else if (source == saveas) saveAs(); else if (source == makeJar) makeJar(false); else if (source == makeJarWithSource) makeJar(true); else if (source == compileAndRun) runText(); else if (source == compile) compile(); else if (source == runSelection) runText(true); else if (source == installMacro) installMacro(); else if (source == nextError) new Thread() { public void run() { nextError(true); } }.start(); else if (source == previousError) new Thread() { public void run() { nextError(false); } }.start(); else if (source == debug) { try { new Script_Editor().addToolsJarToClassPath(); getEditorPane().startDebugging(); } catch (Exception e) { error("No debug support for this language"); } } else if (source == kill) chooseTaskToKill(); else if (source == close) if (tabbed.getTabCount() < 2) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); else { if (!handleUnsavedChanges()) return; int index = tabbed.getSelectedIndex(); removeTab(index); if (index > 0) index--; switchTo(index); } else if (source == cut) getTextArea().cut(); else if (source == copy) getTextArea().copy(); else if (source == paste) getTextArea().paste(); else if (source == undo) getTextArea().undoLastAction(); else if (source == redo) getTextArea().redoLastAction(); else if (source == find) findOrReplace(false); else if (source == findNext) findDialog.searchOrReplace(false); else if (source == findPrevious) findDialog.searchOrReplace(false, false); else if (source == replace) findOrReplace(true); else if (source == gotoLine) gotoLine(); else if (source == toggleBookmark) toggleBookmark(); else if (source == listBookmarks) listBookmarks(); else if (source == selectAll) { getTextArea().setCaretPosition(0); getTextArea().moveCaretPosition(getTextArea().getDocument().getLength()); } else if (source == chooseFontSize) { int fontSize = (int)IJ.getNumber("Font size", getEditorPane().getFontSize()); if (fontSize != IJ.CANCELED) { getEditorPane().setFontSize(fontSize); updateTabAndFontSize(false); } } else if (source == chooseTabSize) { int tabSize = (int)IJ.getNumber("Tab size", getEditorPane().getTabSize()); if (tabSize != IJ.CANCELED) { getEditorPane().setTabSize(tabSize); updateTabAndFontSize(false); } } else if (source == addImport) addImport(null); else if (source == removeUnusedImports) new TokenFunctions(getTextArea()).removeUnusedImports(); else if (source == sortImports) new TokenFunctions(getTextArea()).sortImports(); else if (source == removeTrailingWhitespace) new TokenFunctions(getTextArea()).removeTrailingWhitespace(); else if (source == replaceTabsWithSpaces) getTextArea().convertTabsToSpaces(); else if (source == replaceSpacesWithTabs) getTextArea().convertSpacesToTabs(); else if (source == clearScreen) getTab().getScreen().setText(""); else if (source == zapGremlins) zapGremlins(); else if (source == autocomplete) { try { getEditorPane().autocomp.doCompletion(); } catch (Exception e) {} } else if (source == resume) getEditorPane().resume(); else if (source == terminate) { getEditorPane().terminate(); } else if (source == openHelp) openHelp(null); else if (source == openHelpWithoutFrames) openHelp(null, false); else if (source == openMacroFunctions) new MacroFunctions().openHelp(getTextArea().getSelectedText()); else if (source == extractSourceJar) extractSourceJar(); else if (source == openSourceForClass) { String className = getSelectedClassNameOrAsk(); if (className != null) try { String path = new FileFunctions(this).getSourcePath(className); if (path != null) open(path); else { String url = new FileFunctions(this).getSourceURL(className); new BrowserLauncher().run(url); } } catch (ClassNotFoundException e) { error("Could not open source for class " + className); } } else if (source == openSourceForMenuItem) new OpenSourceForMenuItem().run(null); else if (source == showDiff) { new Thread() { public void run() { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).showDiff(pane.file, pane.getGitDirectory()); } }.start(); } else if (source == commit) { new Thread() { public void run() { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).commit(pane.file, pane.getGitDirectory()); } }.start(); } else if (source == gitGrep) { String searchTerm = getTextArea().getSelectedText(); File searchRoot = getEditorPane().file; if (searchRoot == null) error("File was not yet saved; no location known!"); searchRoot = searchRoot.getParentFile(); GenericDialog gd = new GenericDialog("Grep options"); gd.addStringField("Search_term", searchTerm == null ? "" : searchTerm, 20); gd.addMessage("This search will be performed in\n\n\t" + searchRoot); gd.showDialog(); grabFocus(2); if (!gd.wasCanceled()) new FileFunctions(this).gitGrep(gd.getNextString(), searchRoot); } else if (source == openInGitweb) { EditorPane editorPane = getEditorPane(); new FileFunctions(this).openInGitweb(editorPane.file, editorPane.gitDirectory, editorPane.getCaretLineNumber() + 1); } else if (source == newPlugin) new FileFunctions(this).newPlugin(); else if (source == ijToFront) IJ.getInstance().toFront(); else if (source == increaseFontSize || source == decreaseFontSize) { getEditorPane().increaseFontSize((float)(source == increaseFontSize ? 1.2 : 1 / 1.2)); updateTabAndFontSize(false); } else if (source == nextTab) switchTabRelative(1); else if (source == previousTab) switchTabRelative(-1); else if (source == loadToolsJar) new Script_Editor().addToolsJarToClassPath(); else if (handleTabsMenu(source)) return; } public void installDebugSupportMenuItem() { loadToolsJar = addToMenu(toolsMenu, "Load debugging support via internet", 0, 0); loadToolsJar.setVisible(false); } protected boolean handleTabsMenu(Object source) { if (!(source instanceof JMenuItem)) return false; JMenuItem item = (JMenuItem)source; if (!tabsMenuItems.contains(item)) return false; for (int i = tabsMenuTabsStart; i < tabsMenu.getItemCount(); i++) if (tabsMenu.getItem(i) == item) { switchTo(i - tabsMenuTabsStart); return true; } return false; } public void stateChanged(ChangeEvent e) { int index = tabbed.getSelectedIndex(); if (index < 0) { setTitle(""); return; } final EditorPane editorPane = getEditorPane(index); editorPane.requestFocus(); setTitle(); editorPane.checkForOutsideChanges(); SwingUtilities.invokeLater(new Runnable() { public void run() { editorPane.setLanguageByFileName(editorPane.getFileName()); toggleWhiteSpaceLabeling.setSelected(((RSyntaxTextArea)editorPane).isWhitespaceVisible()); } }); } public EditorPane getEditorPane(int index) { return getTab(index).editorPane; } public void findOrReplace(boolean replace) { findDialog.setLocationRelativeTo(this); // override search pattern only if // there is sth. selected String selection = getTextArea().getSelectedText(); if (selection != null) findDialog.setSearchPattern(selection); findDialog.show(replace); } public void gotoLine() { String line = JOptionPane.showInputDialog(this, "Line:", "Goto line...", JOptionPane.QUESTION_MESSAGE); if (line == null) return; try { gotoLine(Integer.parseInt(line)); } catch (BadLocationException e) { error("Line number out of range: " + line); } catch (NumberFormatException e) { error("Invalid line number: " + line); } } public void gotoLine(int line) throws BadLocationException { getTextArea().setCaretPosition(getTextArea().getLineStartOffset(line-1)); } public void toggleBookmark() { getEditorPane().toggleBookmark(); } public void listBookmarks() { Vector<EditorPane.Bookmark> bookmarks = new Vector<EditorPane.Bookmark>(); for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).getBookmarks(i, bookmarks); BookmarkDialog dialog = new BookmarkDialog(this, bookmarks); dialog.show(); } public boolean reload() { return reload("Reload the file?"); } public boolean reload(String message) { File file = getEditorPane().file; if (file == null || !file.exists()) return true; boolean modified = getEditorPane().fileChanged(); String[] options = { "Reload", "Do not reload" }; if (modified) options[0] = "Reload (discarding changes)"; switch (JOptionPane.showOptionDialog(this, message, "Reload", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0])) { case 0: try { getEditorPane().setFile(file.getPath()); return true; } catch (IOException e) { error("Could not reload " + file.getPath()); } break; } return false; } public Tab getTab() { int index = tabbed.getSelectedIndex(); if (index < 0) return null; return (Tab)tabbed.getComponentAt(index); } public Tab getTab(int index) { return (Tab)tabbed.getComponentAt(index); } public class Tab extends JSplitPane { protected final EditorPane editorPane = new EditorPane(TextEditor.this); protected final JTextArea screen = new JTextArea(); protected final JScrollPane scroll; protected boolean showingErrors; private Executer executer; private final JButton runit, killit, toggleErrors; public Tab() { super(JSplitPane.VERTICAL_SPLIT); super.setResizeWeight(350.0 / 430.0); screen.setEditable(false); screen.setLineWrap(true); screen.setFont(new Font("Courier", Font.PLAIN, 12)); JPanel bottom = new JPanel(); bottom.setLayout(new GridBagLayout()); GridBagConstraints bc = new GridBagConstraints(); bc.gridx = 0; bc.gridy = 0; bc.weightx = 0; bc.weighty = 0; bc.anchor = GridBagConstraints.NORTHWEST; bc.fill = GridBagConstraints.NONE; runit = new JButton("Run"); runit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { runText(); } }); bottom.add(runit, bc); bc.gridx = 1; killit = new JButton("Kill"); killit.setEnabled(false); killit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { kill(); } }); bottom.add(killit, bc); bc.gridx = 2; bc.fill = GridBagConstraints.HORIZONTAL; bc.weightx = 1; bottom.add(new JPanel(), bc); bc.gridx = 3; bc.fill = GridBagConstraints.NONE; bc.weightx = 0; bc.anchor = GridBagConstraints.NORTHEAST; toggleErrors = new JButton("Show Errors"); toggleErrors.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { toggleErrors(); } }); bottom.add(toggleErrors, bc); bc.gridx = 4; bc.fill = GridBagConstraints.NONE; bc.weightx = 0; bc.anchor = GridBagConstraints.NORTHEAST; JButton clear = new JButton("Clear"); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (showingErrors) errorScreen.setText(""); else screen.setText(""); } }); bottom.add(clear, bc); bc.gridx = 0; bc.gridy = 1; bc.anchor = GridBagConstraints.NORTHWEST; bc.fill = GridBagConstraints.BOTH; bc.weightx = 1; bc.weighty = 1; bc.gridwidth = 5; screen.setEditable(false); screen.setLineWrap(true); Font font = new Font("Courier", Font.PLAIN, 12); screen.setFont(font); scroll = new JScrollPane(screen); scroll.setPreferredSize(new Dimension(600, 80)); bottom.add(scroll, bc); super.setTopComponent(editorPane.embedWithScrollbars()); super.setBottomComponent(bottom); } /** Invoke in the context of the event dispatch thread. */ private void prepare() { editorPane.setEditable(false); runit.setEnabled(false); killit.setEnabled(true); } private void restore() { SwingUtilities.invokeLater(new Runnable() { public void run() { editorPane.setEditable(true); runit.setEnabled(true); killit.setEnabled(false); executer = null; } }); } public void toggleErrors() { showingErrors = !showingErrors; if (showingErrors) { toggleErrors.setLabel("Show Output"); scroll.setViewportView(errorScreen); } else { toggleErrors.setLabel("Show Errors"); scroll.setViewportView(screen); } } public void showErrors() { if (!showingErrors) toggleErrors(); else if (scroll.getViewport().getView() == null) scroll.setViewportView(errorScreen); } public void showOutput() { if (showingErrors) toggleErrors(); } public JTextArea getScreen() { return showingErrors ? errorScreen: screen; } boolean isExecuting() { return null != executer; } String getTitle() { return (editorPane.fileChanged() ? "*" : "") + editorPane.getFileName() + (isExecuting() ? " (Running)" : ""); } /** Invoke in the context of the event dispatch thread. */ private void execute(final Languages.Language language, final boolean selectionOnly) throws IOException { prepare(); final JTextAreaOutputStream output = new JTextAreaOutputStream(this.screen); final JTextAreaOutputStream errors = new JTextAreaOutputStream(errorScreen); final RefreshScripts interpreter = language.newInterpreter(); interpreter.setOutputStreams(output, errors); // Pipe current text into the runScript: final PipedInputStream pi = new PipedInputStream(); final PipedOutputStream po = new PipedOutputStream(pi); // The Executer creates a Thread that // does the reading from PipedInputStream this.executer = new TextEditor.Executer(output, errors) { public void execute() { try { interpreter.runScript(pi, editorPane.getFileName()); output.flush(); errors.flush(); markCompileEnd(); } finally { restore(); } } }; // Write into PipedOutputStream // from another Thread try { final String text; if (selectionOnly) { String selected = editorPane.getSelectedText(); if (selected == null) { error("Selection required!"); text = null; } else text = selected + "\n"; // Ensure code blocks are terminated } else { text = editorPane.getText(); } new Thread() { { setPriority(Thread.NORM_PRIORITY); } public void run() { PrintWriter pw = new PrintWriter(po); pw.write(text); pw.flush(); // will lock and wait in some cases try { po.close(); } catch (Throwable tt) { tt.printStackTrace(); } } }.start(); } catch (Throwable t) { t.printStackTrace(); } finally { // Re-enable when all text to send has been sent editorPane.setEditable(true); } } protected void kill() { if (null == executer) return; // Graceful attempt: executer.interrupt(); // Give it 3 seconds. Then, stop it. final long now = System.currentTimeMillis(); new Thread() { { setPriority(Thread.NORM_PRIORITY); } public void run() { while (System.currentTimeMillis() - now < 3000) try { Thread.sleep(100); } catch (InterruptedException e) {} if (null != executer) executer.obliterate(); restore(); } }.start(); } } public static boolean isBinary(String path) { if (path == null) return false; // heuristic: read the first up to 8000 bytes, and say that it is binary if it contains a NUL try { FileInputStream in = new FileInputStream(path); int left = 8000; byte[] buffer = new byte[left]; while (left > 0) { int count = in.read(buffer, 0, left); if (count < 0) break; for (int i = 0; i < count; i++) if (buffer[i] == 0) { in.close(); return true; } left -= count; } in.close(); return false; } catch (IOException e) { return false; } } /** Open a new tab with some content; the languageExtension is like ".java", ".py", etc. */ public Tab newTab(String content, String language) { Tab tab = open(""); if (null != language && language.length() > 0) { language = language.trim().toLowerCase(); if ('.' != language.charAt(0)) language = "." + language; tab.editorPane.setLanguage(Languages.getInstance().map.get(language)); } if (null != content) tab.editorPane.setText(content); return tab; } public Tab open(String path) { if (path != null && path.startsWith("class:")) try { path = new FileFunctions(this).getSourcePath(path.substring(6)); if (path == null) return null; } catch (ClassNotFoundException e) { error("Could not find " + path); } if (isBinary(path)) { IJ.open(path); return null; } /* * We need to remove RSyntaxTextArea's cached key, input and * action map if there is even the slightest chance that a new * TextArea is instantiated from a different class loader than * the map's actions. * * Otherwise the instanceof check will pretend that the new text * area is not an instance of RTextArea, and as a consequence, * no keyboard input will be possible. */ JTextComponent.removeKeymap("RTextAreaKeymap"); UIManager.put("RSyntaxTextAreaUI.actionMap", null); UIManager.put("RSyntaxTextAreaUI.inputMap", null); try { Tab tab = getTab(); boolean wasNew = tab != null && tab.editorPane.isNew(); if (!wasNew) { tab = new Tab(); addDefaultAccelerators(tab.editorPane); } synchronized(tab.editorPane) { tab.editorPane.setFile("".equals(path) ? null : path); if (wasNew) { int index = tabbed.getSelectedIndex() + tabsMenuTabsStart; tabsMenu.getItem(index) .setText(tab.editorPane.getFileName()); } else { tabbed.addTab("", tab); switchTo(tabbed.getTabCount() - 1); tabsMenuItems.add(addToMenu(tabsMenu, tab.editorPane.getFileName(), 0, 0)); } setFileName(tab.editorPane.file); try { updateTabAndFontSize(true); } catch (NullPointerException e) { /* ignore */ } } if (path != null && !"".equals(path)) openRecent.add(path); return tab; } catch (FileNotFoundException e) { e.printStackTrace(); error("The file '" + path + "' was not found."); } catch (Exception e) { e.printStackTrace(); error("There was an error while opening '" + path + "': " + e); } return null; } public boolean saveAs() { EditorPane editorPane = getEditorPane(); SaveDialog sd = new SaveDialog("Save as ", editorPane.file == null ? System.getProperty("ij.dir") : editorPane.file.getParentFile().getAbsolutePath(), editorPane.getFileName() , ""); grabFocus(2); String name = sd.getFileName(); if (name == null) return false; String path = sd.getDirectory() + name; return saveAs(path, true); } public void saveAs(String path) { saveAs(path, true); } public boolean saveAs(String path, boolean askBeforeReplacing) { File file = new File(path); if (file.exists() && askBeforeReplacing && JOptionPane.showConfirmDialog(this, "Do you want to replace " + path + "?", "Replace " + path + "?", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; if (!write(file)) return false; setFileName(file); openRecent.add(path); return true; } public boolean save() { File file = getEditorPane().file; if (file == null) return saveAs(); if (!write(file)) return false; setTitle(); return true; } public boolean write(File file) { try { getEditorPane().write(file); return true; } catch (IOException e) { error("Could not save " + file.getName()); e.printStackTrace(); return false; } } public boolean makeJar(boolean includeSources) { File file = getEditorPane().file; Languages.Language currentLanguage = getCurrentLanguage(); if ((file == null || currentLanguage.isCompileable()) && !handleUnsavedChanges(true)) return false; String name = getEditorPane().getFileName(); if (name.endsWith(currentLanguage.extension)) name = name.substring(0, name.length() - currentLanguage.extension.length()); if (name.indexOf('_') < 0) name += "_"; name += ".jar"; SaveDialog sd = new SaveDialog("Export ", name, ".jar"); grabFocus(2); name = sd.getFileName(); if (name == null) return false; String path = sd.getDirectory() + name; if (new File(path).exists() && JOptionPane.showConfirmDialog(this, "Do you want to replace " + path + "?", "Replace " + path + "?", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; try { makeJar(path, includeSources); return true; } catch (IOException e) { e.printStackTrace(); error("Could not write " + path + ": " + e.getMessage()); return false; } } public void makeJar(String path, boolean includeSources) throws IOException { List<String> paths = new ArrayList<String>(); List<String> names = new ArrayList<String>(); File tmpDir = null, file = getEditorPane().file; String sourceName = null; Languages.Language currentLanguage = getCurrentLanguage(); if (!(currentLanguage.interpreterClass == Refresh_Javas.class)) sourceName = file.getName(); if (!currentLanguage.menuLabel.equals("None")) try { tmpDir = File.createTempFile("tmp", ""); tmpDir.delete(); tmpDir.mkdir(); String sourcePath; Refresh_Javas java; if (sourceName == null) { sourcePath = file.getAbsolutePath(); java = (Refresh_Javas)currentLanguage.newInterpreter(); } else { // this is a script, we need to generate a Java wrapper RefreshScripts interpreter = currentLanguage.newInterpreter(); sourcePath = generateScriptWrapper(tmpDir, sourceName, interpreter); java = (Refresh_Javas)Languages.get(".java").newInterpreter(); } java.showDeprecation(showDeprecation.getState()); java.compile(sourcePath, tmpDir.getAbsolutePath()); getClasses(tmpDir, paths, names); if (includeSources) { String name = java.getPackageName(sourcePath); name = (name == null ? "" : name.replace('.', '/') + "/") + file.getName(); sourceName = name; } } catch (Exception e) { e.printStackTrace(); if (e instanceof IOException) throw (IOException)e; throw new IOException(e.getMessage()); } OutputStream out = new FileOutputStream(path); JarOutputStream jar = new JarOutputStream(out); if (sourceName != null) writeJarEntry(jar, sourceName, getTextArea().getText().getBytes()); for (int i = 0; i < paths.size(); i++) writeJarEntry(jar, names.get(i), readFile(paths.get(i))); jar.close(); if (tmpDir != null) deleteRecursively(tmpDir); } protected final static String scriptWrapper = "import ij.IJ;\n" + "\n" + "import ij.plugin.PlugIn;\n" + "\n" + "public class CLASS_NAME implements PlugIn {\n" + "\tpublic void run(String arg) {\n" + "\t\ttry {\n" + "\t\t\tnew INTERPRETER().runScript(getClass()\n" + "\t\t\t\t.getResource(\"SCRIPT_NAME\").openStream());\n" + "\t\t} catch (Exception e) {\n" + "\t\t\tIJ.handleException(e);\n" + "\t\t}\n" + "\t}\n" + "}\n"; protected String generateScriptWrapper(File outputDirectory, String scriptName, RefreshScripts interpreter) throws FileNotFoundException, IOException { String className = scriptName; int dot = className.indexOf('.'); if (dot >= 0) className = className.substring(0, dot); if (className.indexOf('_') < 0) className += "_"; String code = scriptWrapper.replace("CLASS_NAME", className) .replace("SCRIPT_NAME", scriptName) .replace("INTERPRETER", interpreter.getClass().getName()); File output = new File(outputDirectory, className + ".java"); OutputStream out = new FileOutputStream(output); out.write(code.getBytes()); out.close(); return output.getAbsolutePath(); } static void getClasses(File directory, List<String> paths, List<String> names) { getClasses(directory, paths, names, ""); } static void getClasses(File directory, List<String> paths, List<String> names, String prefix) { if (!prefix.equals("")) prefix += "/"; for (File file : directory.listFiles()) if (file.isDirectory()) getClasses(file, paths, names, prefix + file.getName()); else { paths.add(file.getAbsolutePath()); names.add(prefix + file.getName()); } } static void writeJarEntry(JarOutputStream out, String name, byte[] buf) throws IOException { try { JarEntry entry = new JarEntry(name); out.putNextEntry(entry); out.write(buf, 0, buf.length); out.closeEntry(); } catch (ZipException e) { e.printStackTrace(); throw new IOException(e.getMessage()); } } static byte[] readFile(String fileName) throws IOException { File file = new File(fileName); InputStream in = new FileInputStream(file); byte[] buffer = new byte[(int)file.length()]; in.read(buffer); in.close(); return buffer; } static void deleteRecursively(File directory) { for (File file : directory.listFiles()) if (file.isDirectory()) deleteRecursively(file); else file.delete(); directory.delete(); } void setLanguage(Languages.Language language) { getEditorPane().setLanguage(language); updateTabAndFontSize(true); } void updateLanguageMenu(Languages.Language language) { if (!language.getMenuItem().isSelected()) language.getMenuItem().setSelected(true); runMenu.setVisible(language.isRunnable()); compileAndRun.setLabel(language.isCompileable() ? "Compile and Run" : "Run"); compileAndRun.setEnabled(language.isRunnable()); runSelection.setVisible(language.isRunnable() && !language.isCompileable()); compile.setVisible(language.isCompileable()); autoSave.setVisible(language.isCompileable()); showDeprecation.setVisible(language.isCompileable()); makeJarWithSource.setVisible(language.isCompileable()); debug.setVisible(language.isDebuggable()); if (loadToolsJar != null) loadToolsJar.setVisible(language.isDebuggable()); debug.setVisible(language.isDebuggable()); resume.setVisible(language.isDebuggable()); terminate.setVisible(language.isDebuggable()); boolean isJava = language.menuLabel.equals("Java"); addImport.setVisible(isJava); removeUnusedImports.setVisible(isJava); sortImports.setVisible(isJava); openSourceForMenuItem.setVisible(isJava); boolean isMacro = language.menuLabel.equals("ImageJ Macro"); installMacro.setVisible(isMacro); openMacroFunctions.setVisible(isMacro); openSourceForClass.setVisible(!isMacro); openHelp.setVisible(!isMacro && language.isRunnable()); openHelpWithoutFrames.setVisible(!isMacro && language.isRunnable()); nextError.setVisible(!isMacro && language.isRunnable()); previousError.setVisible(!isMacro && language.isRunnable()); if (getEditorPane() == null) return; boolean isInGit = getEditorPane().getGitDirectory() != null; gitMenu.setVisible(isInGit); updateTabAndFontSize(false); } protected void updateTabAndFontSize(boolean setByLanguage) { EditorPane pane = getEditorPane(); if (setByLanguage) pane.setTabSize(pane.currentLanguage.menuLabel.equals("Python") ? 4 : 8); int tabSize = pane.getTabSize(); boolean defaultSize = false; for (int i = 0; i < tabSizeMenu.getItemCount(); i++) { JMenuItem item = tabSizeMenu.getItem(i); if (item == chooseTabSize) { item.setSelected(!defaultSize); item.setLabel("Other" + (defaultSize ? "" : " (" + tabSize + ")") + "..."); } else if (tabSize == Integer.parseInt(item.getLabel())) { item.setSelected(true); defaultSize = true; } } int fontSize = (int)pane.getFontSize(); defaultSize = false; for (int i = 0; i < fontSizeMenu.getItemCount(); i++) { JMenuItem item = fontSizeMenu.getItem(i); if (item == chooseFontSize) { item.setSelected(!defaultSize); item.setLabel("Other" + (defaultSize ? "" : " (" + fontSize + ")") + "..."); continue; } String label = item.getLabel(); if (label.endsWith(" pt")) label = label.substring(0, label.length() - 3); if (fontSize == Integer.parseInt(label)) { item.setSelected(true); defaultSize = true; } } wrapLines.setState(pane.getLineWrap()); } public void setFileName(String baseName) { getEditorPane().setFileName(baseName); } public void setFileName(File file) { getEditorPane().setFileName(file); } synchronized void setTitle() { final Tab tab = getTab(); if (null == tab || null == tab.editorPane) return; final boolean fileChanged = tab.editorPane.fileChanged(); final String fileName = tab.editorPane.getFileName(); final String title = (fileChanged ? "*" : "") + fileName + (executingTasks.isEmpty() ? "" : " (Running)"); SwingUtilities.invokeLater(new Runnable() { public void run() { setTitle(title); // to the main window int index = tabbed.getSelectedIndex(); // Update all tabs: could have changed for (int i=0; i<tabbed.getTabCount(); i++) tabbed.setTitleAt(i, ((Tab)tabbed.getComponentAt(i)).getTitle()); } }); } public synchronized void setTitle(String title) { super.setTitle(title); int index = tabsMenuTabsStart + tabbed.getSelectedIndex(); if (index < tabsMenu.getItemCount()) { JMenuItem item = tabsMenu.getItem(index); if (item != null) item.setLabel(title); } } /** Using a Vector to benefit from all its methods being synchronzed. */ private ArrayList<Executer> executingTasks = new ArrayList<Executer>(); /** Generic Thread that keeps a starting time stamp, * sets the priority to normal and starts itself. */ private abstract class Executer extends ThreadGroup { JTextAreaOutputStream output, errors; Executer(final JTextAreaOutputStream output, final JTextAreaOutputStream errors) { super("Script Editor Run :: " + new Date().toString()); this.output = output; this.errors = errors; // Store itself for later executingTasks.add(this); setTitle(); // Enable kill menu kill.setEnabled(true); // Fork a task, as a part of this ThreadGroup new Thread(this, getName()) { { setPriority(Thread.NORM_PRIORITY); start(); } public void run() { try { execute(); // Wait until any children threads die: int activeCount = getThreadGroup().activeCount(); while (activeCount > 1) { if (isInterrupted()) break; try { Thread.sleep(500); List<Thread> ts = getAllThreads(); activeCount = ts.size(); if (activeCount <= 1) break; if (IJ.debugMode) System.err.println("Waiting for " + ts.size() + " threads to die"); int count_zSelector = 0; for (Thread t : ts) { if (t.getName().equals("zSelector")) { count_zSelector++; } if (IJ.debugMode) System.err.println("THREAD: " + t.getName()); } if (activeCount == count_zSelector + 1) { // Do not wait on the stack slice selector thread. break; } } catch (InterruptedException ie) {} } } catch (Throwable t) { IJ.handleException(t); } finally { executingTasks.remove(Executer.this); try { if (null != output) output.shutdown(); if (null != errors) errors.shutdown(); } catch (Exception e) { IJ.handleException(e); } // Leave kill menu item enabled if other tasks are running kill.setEnabled(executingTasks.size() > 0); setTitle(); } } }; } /** The method to extend, that will do the actual work. */ abstract void execute(); /** Fetch a list of all threads from all thread subgroups, recursively. */ List<Thread> getAllThreads() { ArrayList<Thread> threads = new ArrayList<Thread>(); // From all subgroups: ThreadGroup[] tgs = new ThreadGroup[activeGroupCount() * 2 + 100]; this.enumerate(tgs, true); for (ThreadGroup tg : tgs) { if (null == tg) continue; Thread[] ts = new Thread[tg.activeCount() * 2 + 100]; tg.enumerate(ts); for (Thread t : ts) { if (null == t) continue; threads.add(t); } } // And from this group: Thread[] ts = new Thread[activeCount() * 2 + 100]; this.enumerate(ts); for (Thread t : ts) { if (null == t) continue; threads.add(t); } return threads; } /** Totally destroy/stop all threads in this and all recursive thread subgroups. Will remove itself from the executingTasks list. */ void obliterate() { try { // Stop printing to the screen if (null != output) output.shutdownNow(); if (null != errors) errors.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } for (Thread thread : getAllThreads()) { try { thread.interrupt(); Thread.yield(); // give it a chance thread.stop(); } catch (Throwable t) { t.printStackTrace(); } } executingTasks.remove(this); setTitle(); } } /** Query the list of running scripts and provide a dialog to choose one and kill it. */ public void chooseTaskToKill() { Executer[] executers = executingTasks.toArray(new Executer[0]); if (0 == executers.length) { error("\nNo tasks running!\n"); return; } String[] names = new String[executers.length]; for (int i = 0; i < names.length; i++) names[i] = executers[i].getName(); GenericDialog gd = new GenericDialog("Kill"); gd.addChoice("Running scripts: ", names, names[names.length - 1]); gd.addCheckbox("Kill all", false); gd.showDialog(); if (gd.wasCanceled()) return; if (gd.getNextBoolean()) { // Kill all for (int i=0; i<tabbed.getTabCount(); i++) ((Tab)tabbed.getComponentAt(i)).kill(); } else { // Kill selected only Executer ex = executers[gd.getNextChoiceIndex()]; for (int i=0; i<tabbed.getTabCount(); i++) { Tab tab = (Tab)tabbed.getComponentAt(i); if (ex == tab.executer) { tab.kill(); break; } } } } /** Run the text in the textArea without compiling it, only if it's not java. */ public void runText() { runText(false); } public void runText(final boolean selectionOnly) { final Languages.Language currentLanguage = getCurrentLanguage(); if (currentLanguage.isCompileable()) { if (selectionOnly) { error("Cannot run selection of compiled language!"); return; } if (handleUnsavedChanges(true)) runScript(); return; } if (!currentLanguage.isRunnable()) { error("Select a language first!"); // TODO guess the language, if possible. return; } markCompileStart(); try { Tab tab = getTab(); tab.showOutput(); tab.execute(currentLanguage, selectionOnly); } catch (Throwable t) { t.printStackTrace(); } } public void runScript() { final RefreshScripts interpreter = getCurrentLanguage().newInterpreter(); if (interpreter == null) { error("There is no interpreter for this language"); return; } if (getCurrentLanguage().isCompileable()) getTab().showErrors(); else getTab().showOutput(); markCompileStart(); final JTextAreaOutputStream output = new JTextAreaOutputStream(getTab().screen); final JTextAreaOutputStream errors = new JTextAreaOutputStream(errorScreen); interpreter.setOutputStreams(output, errors); final File file = getEditorPane().file; new TextEditor.Executer(output, errors) { public void execute() { interpreter.runScript(file.getPath()); output.flush(); errors.flush(); markCompileEnd(); } }; } public void compile() { if (!handleUnsavedChanges(true)) return; final RefreshScripts interpreter = getCurrentLanguage().newInterpreter(); final JTextAreaOutputStream output = new JTextAreaOutputStream(getTab().screen); final JTextAreaOutputStream errors = new JTextAreaOutputStream(errorScreen); interpreter.setOutputStreams(output, errors); getTab().showErrors(); if (interpreter instanceof Refresh_Javas) { final Refresh_Javas java = (Refresh_Javas)interpreter; final File file = getEditorPane().file; final String sourcePath = file.getAbsolutePath(); java.showDeprecation(showDeprecation.getState()); markCompileStart(); new Thread() { public void run() { java.compileAndRun(sourcePath, true); errorScreen.insert("Compilation finished.\n", errorScreen.getDocument().getLength()); markCompileEnd(); } }.start(); } } public String getSelectedTextOrAsk(String label) { String selection = getTextArea().getSelectedText(); if (selection == null || selection.indexOf('\n') >= 0) { selection = JOptionPane.showInputDialog(this, label + ":", label + "...", JOptionPane.QUESTION_MESSAGE); if (selection == null) return null; } return selection; } public String getSelectedClassNameOrAsk() { String className = getSelectedTextOrAsk("Class name"); if (className != null) className = className.trim(); if (className != null && className.indexOf('.') < 0) className = getEditorPane().getClassNameFunctions().getFullName(className); return className; } protected static void append(JTextArea textArea, String text) { int length = textArea.getDocument().getLength(); textArea.insert(text, length); textArea.setCaretPosition(length); } public void markCompileStart() { errorHandler = null; String started = "Started " + getEditorPane().getFileName() + " at " + new Date() + "\n"; int offset = errorScreen.getDocument().getLength(); append(errorScreen, started); append(getTab().screen, started); compileStartOffset = errorScreen.getDocument().getLength(); try { compileStartPosition = errorScreen.getDocument().createPosition(offset); } catch (BadLocationException e) { handleException(e); } ExceptionHandler.addThread(Thread.currentThread(), this); } public void markCompileEnd() { if (errorHandler == null) { errorHandler = new ErrorHandler(getCurrentLanguage(), errorScreen, compileStartPosition.getOffset()); if (errorHandler.getErrorCount() > 0) getTab().showErrors(); } if (compileStartOffset != errorScreen.getDocument().getLength()) getTab().showErrors(); if (getTab().showingErrors) try { errorHandler.scrollToVisible(compileStartOffset); } catch (BadLocationException e) { // ignore } } public void installMacro() { new MacroFunctions().installMacro(getTitle(), getEditorPane().getText()); } public boolean nextError(boolean forward) { if (errorHandler != null && errorHandler.nextError(forward)) try { File file = new File(errorHandler.getPath()); if (!file.isAbsolute()) file = getFileForBasename(file.getName()); errorHandler.markLine(); switchTo(file, errorHandler.getLine()); getTab().showErrors(); errorScreen.invalidate(); return true; } catch (Exception e) { IJ.handleException(e); } return false; } public void switchTo(String path, int lineNumber) throws IOException { switchTo(new File(path).getCanonicalFile(), lineNumber); } public void switchTo(File file, final int lineNumber) { if (!editorPaneContainsFile(getEditorPane(), file)) switchTo(file); SwingUtilities.invokeLater(new Runnable() { public void run() { try { gotoLine(lineNumber); } catch (BadLocationException e) { // ignore } } }); } public void switchTo(File file) { for (int i = 0; i < tabbed.getTabCount(); i++) if (editorPaneContainsFile(getEditorPane(i), file)) { switchTo(i); return; } open(file.getPath()); } public void switchTo(int index) { if (index == tabbed.getSelectedIndex()) return; tabbed.setSelectedIndex(index); } protected void switchTabRelative(int delta) { int index = tabbed.getSelectedIndex(); int count = tabbed.getTabCount(); index = ((index + delta) % count); if (index < 0) index += count; switchTo(index); } protected void removeTab(int index) { tabbed.remove(index); index += tabsMenuTabsStart; tabsMenuItems.remove(tabsMenu.getItem(index)); tabsMenu.remove(index); } boolean editorPaneContainsFile(EditorPane editorPane, File file) { try { return file != null && editorPane != null && editorPane.file != null && file.getCanonicalFile() .equals(editorPane.file.getCanonicalFile()); } catch (IOException e) { return false; } } public File getFile() { return getEditorPane().file; } public File getFileForBasename(String baseName) { File file = getFile(); if (file != null && file.getName().equals(baseName)) return file; for (int i = 0; i < tabbed.getTabCount(); i++) { file = getEditorPane(i).file; if (file != null && file.getName().equals(baseName)) return file; } return null; } public void addImport(String className) { if (className == null) className = getSelectedClassNameOrAsk(); if (className != null) new TokenFunctions(getTextArea()).addImport(className.trim()); } public void openHelp(String className) { openHelp(className, true); } public void openHelp(String className, boolean withFrames) { if (className == null) className = getSelectedClassNameOrAsk(); if (className != null) getEditorPane().getClassNameFunctions().openHelpForClass(className, withFrames); } public void extractSourceJar() { String path = openWithDialog("Open...", null, new String[] { ".jar" }, true); if (path != null) extractSourceJar(path); } public void extractSourceJar(String path) { try { FileFunctions functions = new FileFunctions(this); List<String> paths = functions.extractSourceJar(path); for (String file : paths) if (!functions.isBinaryFile(file)) { open(file); EditorPane pane = getEditorPane(); new TokenFunctions(pane).removeTrailingWhitespace(); if (pane.fileChanged()) save(); } } catch (IOException e) { error("There was a problem opening " + path + ": " + e.getMessage()); } } /* extensionMustMatch == false means extension must not match */ protected String openWithDialog(final String title, final String directory, final String[] extensions, final boolean extensionMustMatch) { FileDialog dialog = new FileDialog(this, title); if (directory != null) dialog.setDirectory(directory); if (extensions != null) dialog.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { for (String extension : extensions) if (name.endsWith(extension)) return extensionMustMatch; return !extensionMustMatch; } }); dialog.setVisible(true); String dir = dialog.getDirectory(); String name = dialog.getFile(); if (dir == null || name == null) return null; return new File(dir, name).getAbsolutePath(); } /** * Write a message to the output screen * * @param message The text to write */ public void write(String message) { Tab tab = getTab(); if (!message.endsWith("\n")) message += "\n"; tab.screen.insert(message, tab.screen.getDocument().getLength()); } public void writeError(String message) { Tab tab = getTab(); tab.showErrors(); if (!message.endsWith("\n")) message += "\n"; errorScreen.insert(message, errorScreen.getDocument().getLength()); } protected void error(String message) { JOptionPane.showMessageDialog(this, message); } void handleException(Throwable e) { ij.IJ.handleException(e); } /** Removes invalid characters, shows a dialog. * @return The amount of invalid characters found. */ public int zapGremlins() { int count = getEditorPane().zapGremlins(); String msg = count > 0 ? "Zap Gremlins converted " + count + " invalid characters to spaces" : "No invalid characters found!"; JOptionPane.showMessageDialog(this, msg); return count; } }
joshnuss/spree-contact-form
app/controllers/spree/contact_controller.rb
module Spree class ContactController < BaseController before_filter :load_topics def show @message = Message.new end def create @message = Message.new(params[:message] || {}) if @message.save ContactMailer.message_email(@message).deliver flash[:notice] = t('contact_thank_you') redirect_to root_path else render :action => 'show' end end private def load_topics @topics = ContactTopic.all end end end
mbtaylor/cds-healpix-java
src/test/java/cds/healpix/NestedSmallCellApproxedMethodTest.java
<reponame>mbtaylor/cds-healpix-java // Copyright 2017-2018 - Universite de Strasbourg/CNRS // The CDS HEALPix library is developped by the Centre de Donnees // astronomiques de Strasbourgs (CDS) from the following external papers: // - [Gorsky2005] - "HEALPix: A Framework for High-Resolution Discretization and // Fast Analysis of Data Distributed on the Sphere" // http://adsabs.harvard.edu/abs/2005ApJ...622..759G // - [Calabretta2004] - "Mapping on the HEALPix grid" // http://adsabs.harvard.edu/abs/2004astro.ph.12607C // - [Calabretta2007] - "Mapping on the HEALPix grid" // http://adsabs.harvard.edu/abs/2007MNRAS.381..865C // - [Reinecke2015] - "Efficient data structures for masks on 2D grids" // http://adsabs.harvard.edu/abs/2015A&A...580A.132R // It is distributed under the terms of the BSD License 2.0 // // This file is part of the CDS HEALPix library. // package cds.healpix; import static org.junit.Assert.assertEquals; import org.junit.Test; import cds.healpix.Healpix; import cds.healpix.HealpixNestedBMOC; import cds.healpix.HealpixNestedFixedRadiusConeComputer; public class NestedSmallCellApproxedMethodTest { public void coneTest(double coneCenterLonRad, double coneCenterLatRad, double radiusRad, int depth, final long[] expectedRes) { // final int startingDepth = Constants.getBestStartingDepthForConeSearch(radiusRad); // final NestedLargeCellApproxedMethod nlc = new NestedLargeCellApproxedMethod(startingDepth, depth, radiusRad); // final NestedSmallCellApproxedMethod nlc = new NestedSmallCellApproxedMethod(startingDepth, depth, radiusRad); final HealpixNestedFixedRadiusConeComputer nlc = Healpix.getNested(depth).newConeComputerApprox(radiusRad); System.out.println(nlc.getClass().getName()); final HealpixNestedBMOC moc = nlc.overlappingCells(coneCenterLonRad, coneCenterLatRad); System.out.println("Moc size: " + moc.size()); System.out.println("Moc deep size: " + moc.computeDeepSize()); int i = 0; for (final HealpixNestedBMOC.CurrentValueAccessor cell : moc) { // System.out.println(cell); // assertEquals(expectedRes[i++], cell.getHash()); } // assertEquals(expectedRes.length, i); } @Test public void testCone() { System.out.println("lon: " + Math.toRadians(085.51340) + "; lat: " + Math.toRadians(-01.89284)); //085.51340 -01.89284 //coneTest(0.0, 0.0, 2.0, 3, null); // Cone. depth: 6; lonRad: 1.4887397926478119; latRad: -0.03928177631283567; rRad: 0.01994913445007241 // coneTest(1.4887397926478119, -0.03928177631283567, 0.01994913445007241, 6, null); System.out.println("---------"); coneTest(1.4923946835544672, -0.03320059031799468, 0.016729491874516444, 7, null); // Cone. depth: 7; lonRad: 1.4923946835544672; latRad: -0.03320059031799468; rRad: 0.016729491874516444 // Cone. depth: 3; lonRad: 1.4985159126238619; latRad: 1.4771883195119886; rRad: 0.642057147736403 coneTest(1.4985159126238619, 1.4771883195119886, 0.642057147736403, 3, null); } }
mfaithfull/QOR
Source/ArchQOR/Z/HLAssembler/Emittables/Z_EInstruction.cpp
<reponame>mfaithfull/QOR //Z_EInstruction.cpp // Copyright (c) 2008-2010, <NAME> <<EMAIL>> // Copyright (c) Querysoft Limited 2012, 2015 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Implement an Z instruction emittable #include "ArchQOR.h" #if ( QOR_ARCH == QOR_ARCH_Z ) #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_EInstruction.h" #include "ArchQOR/Zarch/HLAssembler/ZHLAContext.h" #include <assert.h> //------------------------------------------------------------------------------ namespace nsArch { //------------------------------------------------------------------------------ namespace nsZ { //------------------------------------------------------------------------------ CEInstruction::CEInstruction( CZHLAIntrinsics* c, Cmp_unsigned__int32 code, COperand** operandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW : CEmittable( (nsArch::CHighLevelAssemblerBase*)c, EMITTABLE_INSTRUCTION ) { } //------------------------------------------------------------------------------ CEInstruction::~CEInstruction() __QCMP_THROW { } //------------------------------------------------------------------------------ void CEInstruction::getVariable( VarData* _candidate, VarAllocRecord*& cur, VarAllocRecord*& var ) { } //------------------------------------------------------------------------------ void CEInstruction::prepare( CHLAssemblerContextBase& hlac ) __QCMP_THROW { } //------------------------------------------------------------------------------ nsArch::CEmittable* CEInstruction::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW { return translated(); } //------------------------------------------------------------------------------ void CEInstruction::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW { } //------------------------------------------------------------------------------ int CEInstruction::getMaxSize() const __QCMP_THROW { // TODO: Do something more exact. return 15; } //------------------------------------------------------------------------------ bool CEInstruction::tryUnuseVar( nsArch::CommonVarData* vdata ) __QCMP_THROW { return false; } //------------------------------------------------------------------------------ CETarget* CEInstruction::getJumpTarget() const __QCMP_THROW { return 0; } }//nsZ }//nsArch #endif//( QOR_ARCH == QOR_ARCH_Z )
mooshak-dcc/mooshak-2
src/main/java/pt/up/fc/dcc/mooshak/shared/events/LogoutEvent.java
package pt.up.fc.dcc.mooshak.shared.events; import java.util.ArrayList; import java.util.List; /** * Event to force logout on client side, typically due to an error. * * @author <NAME> <zp.dcc.fc.up.pt> */ public class LogoutEvent extends MooshakEvent { String reason = ""; public LogoutEvent() { super(); } public LogoutEvent(String reason) { super(); this.reason = reason; } /** * Convenience method for crating a list of messages with a single * logout event, typically on error * * @param message * @return */ public static List<MooshakEvent> getLogoutEventAsList(String message) { List<MooshakEvent> events = new ArrayList<MooshakEvent>(); events.add(new LogoutEvent(message)); return events; } /** * Get reason for logout * @return the reason */ public String getReason() { return reason; } /** * Set reason for logout * @param reason the reason to set */ public void setReason(String reason) { this.reason = reason; } }
singhaniatanay/Competitive-Programming
MakeMyTrip/sort012.java
<gh_stars>1-10 // { Driver Code Starts //Initial template for Java import java.io.*; import java.util.*; class GFG { // } Driver Code Ends //User function template for Java public static void sort012(int a[], int n){ // code here int i=-1; int j= 0; int k = n-1; while(j<=k){ if(a[j]==0){ swap(a,i+1,j); i++; j++; }else if(a[j]==1){ j++; }else{ swap(a,j,k); k--; } } } public static void swap(int[] arr,int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // { Driver Code Starts. public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){ int n = Integer.parseInt(br.readLine().trim()); int arr[] = new int[n]; String inputLine[] = br.readLine().trim().split(" "); for(int i=0; i<n; i++){ arr[i] = Integer.parseInt(inputLine[i]); } sort012(arr, n); StringBuffer str = new StringBuffer(); for(int i=0; i<n; i++){ str.append(arr[i]+" "); } System.out.println(str); } } } // } Driver Code Ends
HackintoshwithUbuntu/BigRepo
Python/Grok Learning - for school, boring/Intro to python 2/Chapter 6.py
<gh_stars>0 words = {} engList = [] final = [] for line in open('dictionary.txt'): english, Aboriginal = line.rstrip().split(',') words[english] = Aboriginal engLine = input("English: ") while engLine: engList = engLine.split() for word in engList: final.append(words[word]) for counter in range(len(final)-1): print(final[counter], end = ' ') try: print(final[counter+1]) except: print(final[0]) final = [] engLine = input("English: ") Dict = {} score = 0 file = open('scrabble_letters.txt').read().rstrip().split("\n") for line in file: temp = line.split() Dict[temp[1]] = int(temp[0]) letters = list(input("Word: ").upper()) for letter in letters: score = score + Dict[letter] print(score, "points") import csv with open('nominees.csv', newline='') as f: winner = input('Winning title: ') for line in csv.DictReader(f): if line['title'] == winner: print('Congratulations:', line['director(s)']) classlist = open('classlist.txt').read().lower().split('\n') used = [] counter = 0 for name in classlist: try: first, *middle, last = name.split() if first + ''.join(middle) not in used: used.append(first + ''.join(middle)) else: name = first + ''.join(middle) + last[0] if name not in used: used.append(name) else: while True: counter = counter + 1 if first + ''.join(middle) + last[0] + str(counter) not in used: used.append(first + ''.join(middle) + last[0] + str(counter)) break except: pass for username in used: print(username)
Adilla/Blasmatch
external/pet/array.c
/* * Copyright 2011 Leiden University. All rights reserved. * Copyright 2012-2014 <NAME>. 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 LEIDEN UNIVERSITY ''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 LEIDEN UNIVERSITY 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. * * The views and conclusions contained in the software and documentation * are those of the authors and should not be interpreted as * representing official policies, either expressed or implied, of * Leiden University. */ #include <string.h> #include "array.h" /* Given a partial index expression "base" and an extra index "index", * append the extra index to "base" and return the result. * Additionally, add the constraints that the extra index is non-negative. * If "index" represent a member access, i.e., if its range is a wrapped * relation, then we recursively extend the range of this nested relation. * * The inputs "base" and "index", as well as the result, all have * an anonymous zero-dimensional domain. */ __isl_give isl_multi_pw_aff *pet_array_subscript( __isl_take isl_multi_pw_aff *base, __isl_take isl_pw_aff *index) { isl_id *id; isl_set *domain; isl_multi_pw_aff *access; int member_access; member_access = isl_multi_pw_aff_range_is_wrapping(base); if (member_access < 0) goto error; if (member_access) { isl_multi_pw_aff *domain, *range; isl_id *id; id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out); domain = isl_multi_pw_aff_copy(base); domain = isl_multi_pw_aff_range_factor_domain(domain); range = isl_multi_pw_aff_range_factor_range(base); range = pet_array_subscript(range, index); access = isl_multi_pw_aff_range_product(domain, range); access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id); return access; } id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set); domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index)); index = isl_pw_aff_intersect_domain(index, domain); access = isl_multi_pw_aff_from_pw_aff(index); access = isl_multi_pw_aff_flat_range_product(base, access); access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id); return access; error: isl_multi_pw_aff_free(base); isl_pw_aff_free(index); return NULL; } /* Construct a name for a member access by concatenating the name * of the array of structures and the member, separated by an underscore. * * The caller is responsible for freeing the result. */ char *pet_array_member_access_name(isl_ctx *ctx, const char *base, const char *field) { int len; char *name; len = strlen(base) + 1 + strlen(field); name = isl_alloc_array(ctx, char, len + 1); if (!name) return NULL; snprintf(name, len + 1, "%s_%s", base, field); return name; } /* Given an index expression "base" for an element of an array of structures * and an expression "field" for the field member being accessed, construct * an index expression for an access to that member of the given structure. * In particular, take the range product of "base" and "field" and * attach a name to the result. */ __isl_give isl_multi_pw_aff *pet_array_member( __isl_take isl_multi_pw_aff *base, __isl_take isl_multi_pw_aff *field) { isl_ctx *ctx; isl_multi_pw_aff *access; const char *base_name, *field_name; char *name; ctx = isl_multi_pw_aff_get_ctx(base); base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out); field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out); name = pet_array_member_access_name(ctx, base_name, field_name); access = isl_multi_pw_aff_range_product(base, field); access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name); free(name); return access; }
zjutjh/boomerang-vue
src/main.js
<reponame>zjutjh/boomerang-vue<gh_stars>1-10 // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import VueCarousel from 'vue-carousel' import App from './App' import router from './router' import store from './store' import API from './api/index' import fetch from './middlewares/fetch' import './common/style/index.scss' import getValue from './common/mixin/getValue' Vue.use(VueCarousel) Vue.config.productionTip = false Vue.prototype.API = API Vue.prototype.fetch = fetch Vue.prototype.getValue = getValue /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
couchbaselabs/couchbase-cloud-go-client
model_status_ok.go
<filename>model_status_ok.go /* Couchbase Public API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) API version: 2.0.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package couchbasecapella import ( "encoding/json" ) // StatusOK struct for StatusOK type StatusOK struct { Status string `json:"status"` } // NewStatusOK instantiates a new StatusOK object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewStatusOK(status string) *StatusOK { this := StatusOK{} this.Status = status return &this } // NewStatusOKWithDefaults instantiates a new StatusOK object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewStatusOKWithDefaults() *StatusOK { this := StatusOK{} return &this } // GetStatus returns the Status field value func (o *StatusOK) GetStatus() string { if o == nil { var ret string return ret } return o.Status } // GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. func (o *StatusOK) GetStatusOk() (*string, bool) { if o == nil { return nil, false } return &o.Status, true } // SetStatus sets field value func (o *StatusOK) SetStatus(v string) { o.Status = v } func (o StatusOK) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["status"] = o.Status } return json.Marshal(toSerialize) } type NullableStatusOK struct { value *StatusOK isSet bool } func (v NullableStatusOK) Get() *StatusOK { return v.value } func (v *NullableStatusOK) Set(val *StatusOK) { v.value = val v.isSet = true } func (v NullableStatusOK) IsSet() bool { return v.isSet } func (v *NullableStatusOK) Unset() { v.value = nil v.isSet = false } func NewNullableStatusOK(val *StatusOK) *NullableStatusOK { return &NullableStatusOK{value: val, isSet: true} } func (v NullableStatusOK) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableStatusOK) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }