text
stringlengths
27
775k
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace SmtpRedirector.Server.Data { public class MailMessage { public Guid Id { get; set; } public DateTime RecievedDateTime { get; set; } public string SourceHostname { get; set; } public IPAddress SourceIpAddress { get; set; } public ISet<Recipient> Recipients { get; set; } public EmailAddress FromAddress { get; set; } public EmailBody Body { get; set; } public ISet<Header> Headers { get; set; } public MailMessage(EmailAddress fromAddress) { FromAddress = fromAddress; } } public class Header { public string Name { get; set; } public string Value { get; set; } } public class EmailBody { } }
## Check If N and Its Double Exist Difficulty: Easy Problem link: https://leetcode.com/problems/check-if-n-and-its-double-exist/
package mongostore import ( "testing" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func TestModels(t *testing.T) { var ( modelNocacher = &nocacherModel{ Idx: bson.NewObjectId(), Regexp: "askdjalks", EEnabled: true, } modelPathRuler = &pathRulerModel{ Idx: bson.NewObjectId(), PPath: "/path", MMethod: "GET", SServerName: "srv1", RRewritePath: "/path_2", NNeedCombine: true, CCombineReqCfgs: []*combinerModel{ &combinerModel{ Idx: bson.NewObjectId(), SServerName: "srv1", PPath: "/pp/1", FField: "field1", MMethod: "GET", }, &combinerModel{ Idx: bson.NewObjectId(), SServerName: "srv1", PPath: "/pp/2", FField: "field1", MMethod: "GET", }, }, } modelServerRuler = &serverRulerModel{ Idx: bson.NewObjectId(), PPrefix: "/prefix", SServerName: "srv1", NNeedStripPrefix: true, } modelReverseServer = &reverseServerModel{ Idx: bson.NewObjectId(), NName: "srv1", AAddr: "http://localhost:8089", WW: 5, } ) session, err := mgo.Dial("mongodb://localhost:27017") defer session.Close() if err != nil { t.Error(err) } db := session.DB("gateway") if err := db.C("plugin_cache").Insert(modelNocacher); err != nil { t.Error(err) } if err := db.C("plugin_proxy_path").Insert(modelPathRuler); err != nil { t.Error(err) } if err := db.C("plugin_proxy_server").Insert(modelServerRuler); err != nil { t.Error(err) } if err := db.C("plugin_proxy_reverse").Insert(modelReverseServer); err != nil { t.Error(err) } }
import * as utils from 'helpers/utils'; export class MiscAssistHelper { constructor(game, assister, target, assistPos) { this.game = game; this.assister = assister; this.target = target; this.assistPos = assistPos; } miscAssist() { switch(this.assister.assist) { case 'Dance': case 'Sing': this.dance(); break; case 'Harsh Command': this.harshCommand(); break; case 'Rally Attack': this.rally('atk'); break; case 'Rally Defense': this.rally('def'); break; case 'Rally Resistance': this.rally('res'); break; case 'Rally Speed': this.rally('spd'); break; } } dance() { // Allows a unit to move again if (!['Dance', 'Sing'].includes(this.target.assist)) { this.target.setTurnStart(); } } harshCommand() { // Harsh command turns penalties into hone buffs _.forEach(['Atk', 'Spd', 'Def', 'Res'], (stat) => { let penalty = this.target.stats['threaten' + stat]; this.target.stats['threaten' + stat] = 0; this.target.stats['hone' + stat] = Math.max(this.target.stats['hone' + stat], penalty); }); } rally(stat) { // Rallys are a "hone" buff - only highest takes effect // Rally is always for a flat amount of 4 let honestat = _.camelCase('hone-' + stat); this.target.stats[honestat] = Math.max(this.target.stats[honestat], 4); } }
package logging class ConsoleAppenderOptions( val level: LogLevel = LogLevel.DEBUG, val verbose: Boolean = true )
<?php session_start(); require_once 'session.class.php'; session::destroy(); header('Location: index.php?msg=You have been logged out'); exit; ?>
# frozen_string_literal: true class ManageAction DOUBLE_OPT_IN_COUNTRIES = %w[DE AT].freeze def self.create(params, extra_params: {}, skip_queue: false, skip_counter: false) new(params, extra_params: extra_params, skip_queue: skip_queue, skip_counter: skip_counter).create end def initialize(params, extra_params: {}, skip_queue: false, skip_counter: false) @params = params.clone @skip_queue = skip_queue @skip_counter = skip_counter @extra_attrs = extra_params.clone sanitize_params end def create if should_create_new_action? create_action else # TODO: Update existing member previous_action end end def create_action action_params = { page: page }.merge(@extra_attrs) return PendingActionService.create(@params) if requires_double_opt_in if existing_member.present? action_params[:member] = existing_member action_params[:form_data] = form_data action_params[:subscribed_member] = false update_existing_member @action = Action.create!(action_params) publish_event elsif !requires_consent? || @params[:consented] action_params[:member] = create_member action_params[:form_data] = form_data action_params[:subscribed_member] = true @action = Action.create!(action_params) publish_event else action_params[:form_data] = @params.slice( :name, :first_name, :last_name, :country, :email_service, :clicked_copy_body_button, :action_target, :action_target_email, :source, :consented ) action_params[:subscribed_member] = false @action = Action.create!(action_params) end Analytics::Page.increment(page.id, new_member: action_params[:subscribed_member]) unless @skip_counter @action end def previous_action return nil unless existing_member.present? @previous_action ||= Action.not_donation.where(member: existing_member, page_id: page).first if page.campaign.present? && @previous_action.blank? page.campaign.pages.each do |connected_page| next if connected_page.id == page.id @previous_action ||= Action.not_donation.where(member: existing_member, page_id: connected_page.id).first end end @previous_action end private def create_member member = Member.new(email: @params[:email]) MemberUpdater.run(member, @params) member end def update_existing_member MemberUpdater.run(existing_member, @params) end def existing_member @existing_member ||= Member.find_by_email(@params[:email]) end def publish_event @mailing_id = AkidParser.parse(@params[:akid], Settings.action_kit.akid_secret)[:mailing_id] ActionQueue::Pusher.push(:new_action, @action, @mailing_id) unless @skip_queue end def form_data @params.tap do |params| email = MemberEmailGuesser.run(params) params[:action_referrer_email] = email if email.present? end end def should_create_new_action? @extra_attrs[:donation] || previous_action.nil? || page.allow_duplicate_actions? end def page @page ||= Page.find(@params[:page_id]) end def sanitize_params if @extra_attrs[:donation] @params[:donor_status] = @params[:is_subscription] ? 'recurring_donor' : 'donor' end @params[:consented] = ActiveRecord::Type::Boolean.new.deserialize(@params[:consented]) end def requires_consent? Country[@params[:country]]&.in_eea? && !@extra_attrs[:donation] && (existing_member.nil? || !existing_member.consented?) end def requires_double_opt_in return false if @params[:consented] == false return false unless page.plugins.map(&:class).include? Plugins::Petition requires_consent? && DOUBLE_OPT_IN_COUNTRIES.include?(@params[:country]) && !@params[:consented] end end
# Run an example component This guide shows you how to build Fuchsia to include an example package from Fuchsia's source [`//examples`](/examples/) directory and run that component on your Fuchsia device. Note: This guide is specific to [components v1](/docs/glossary.md#components-v1) and uses [component manifests](/docs/concepts/components/v1/component_manifests.md). ## Exploring the example Fuchsia package {#exploring-the-example-fuchsia-package} Open the [`examples/hello_world/BUILD.gn`](/examples/hello_world/BUILD.gn) file. This example, written in both C++ and Rust, prints `Hello, world!`. Each language-dependent directory has the following: * A [`BUILD.gn`](#build-gn) file that defines its [Fuchsia package](#fuchsia-package). * A `meta` subdirectory with [component manifests](#component-manifest) (`.cmx`) files. ### BUILD.gn {#build-gn} Generate Ninja (GN) is a meta build system. Output files from GN serve as inputs to [Ninja](https://ninja-build.org/){:.external}, the actual build system. If you aren't familiar with GN, see [Introduction to GN](/docs/concepts/build_system/intro.md). In the [`examples/hello_world/BUILD.gn`](/examples/hello_world/BUILD.gn) file, the `hello_world` target is a group containing other dependencies, notably `cpp` and `rust`. Therefore, this target builds both of them: ```none group("hello_world") { testonly = true deps = [ ":tests", "cpp", "rust", ] } ``` To learn more about how GN defines Fuchsia packages, see the [`build/package.gni`](/build/package.gni) file. ### Component manifest {#component-manifest} A `.cmx` file, known as a [component manifest](/docs/glossary.md#component-manifest), describes how to run an application on Fuchsia as a [component](/docs/glossary.md#component). In other words, a component manifest creates a [Fuchsia package](/docs/glossary.md#fuchsia-package). ### Fuchsia package {#fuchsia-package} To include a package in your Fuchsia image, you have the following options: * Base: Packages that are produced by build and included in paving images. These packages are included in over-the-air updates and are always updated as a single unit. * Cache: Packages that are included in paving images, but are not included in over-the-air system updates. These packages can be updated at any time when updates are available. * Universe: Packages that are not included in paving image. These optional packages are fetched and run on-demand. ## Include the example package in your Fuchsia image {#include-the-example-package-in-your-fuchsia-image} Note: If you already built Fuchsia and you're not changing your product or board, these commands take less than a few minutes to run. If you are changing your product or board, these changes can take up to 90 minutes to run. To include the example package in Universe so that it can be fetched on-demand, use the `--with` flag when setting your product and board environment and building Fuchsia: <pre class="prettyprint"> <code class="devsite-terminal">fx set <var>product</var>.<var>board</var> --with //examples/hello_world</code> </pre> For a Fuchsia emulator with the minimum build configuration, the command is: ```posix-terminal fx set core.qemu-x64 --with //examples/hello_world ``` In this example, `core` is a product with a minimal feature set, which includes common network capabilities, and `x64` refers to the x64 architecture. For a Fuchsia device with the minimum build configuration, the command is: ```posix-terminal fx set core.x64 --with //examples/hello_world ``` See [Configure a build](/docs/development/build/fx.md#configure-a-build) for more options. Once you have set your build configuration, build Fuchsia with the following command: ```posix-terminal fx build ``` You now have a build that includes the example package in Universe. ## Run the example component {#run-the-example-component} To run a Fuchsia component, use its [Fuchsia package URL](/docs/glossary.md#fuchsia-pkg-url) as an argument to the `fx shell run` command: 1. Open a terminal and run `fx serve`: ```posix-terminal fx serve ``` 1. Open another terminal and run the example component: ```posix-terminal fx shell run fuchsia-pkg://fuchsia.com/hello_world_cpp#meta/hello_world_cpp.cmx ``` This command prints the following output: ```none Hello, World! ``` If `fx serve` is not running, the command prints an error message from the device or emulator. If `fx serve` is running, but the package is not found, then [try going through these steps again](#include-the-example-package-in-your-fuchsia-image), rebuilding your Fuchsia image to include this package and repaving it to the device. ### Run the example component using a simple string {#run-the-example-component-using-a-simple-string} The `fx shell run` command can match a string to a package URL if the string is only mapped to one component in your product configuration. For example: ```posix-terminal $ fx shell run hello_world_cpp.cmx ``` If multiple matches exist, the command prints the list of matches: ```none $ fx shell run hello_world fuchsia-pkg://fuchsia.com/hello_world_cpp_tests#meta/hello_world_cpp_unittests.cmx fuchsia-pkg://fuchsia.com/hello_world_cpp#meta/hello_world_cpp.cmx Error: "hello_world" matched multiple components. ``` ### Explore the components in your product configuration {#explore-components-in-product-configuration} You can explore what components are in your product configuration using the `locate` command. * Find your favorite component: ```posix-terminal fx shell locate hello_world_cpp.cmx ``` * Find all runnable components: ```posix-terminal fx shell locate --list cmx ``` * Find multiple test components: ```posix-terminal fx shell locate --list test ```
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Tbl_stockist_package_inventory extends Model { protected $table = 'tbl_stockist_package_inventory'; public $timestamps = false; protected $fillable = [ 'product_package_id', 'stockist_id', 'package_quantity', 'archived' ]; }
<?php declare(strict_types = 1); namespace Lwf\Debug; /** * ErrorHandler converts a PHP error into a \ErrorException */ class ErrorHandler { /** * Handle a PHP error and throw a \ErrorException * * @param int $severity The severity of the error * @param string $message The message of the error * @param string $file The filename where the error has been triggered * @param int $line The line number in the file at wich the error has been triggered * * @throws \ErrorException * * @see http://php.net/manual/en/function.set-error-handler.php */ public function handle(int $severity, string $message, string $file, int $line) { if (!(error_reporting() & $severity)) { // This error code is not included in error_reporting return; } throw new \ErrorException($message, 0, $severity, $file, $line); } }
import { forwardRef, InputHTMLAttributes } from "react"; import { UseFormRegister } from "react-hook-form"; import { InputsSignIn } from "../Modals/SignIn"; import { InputsSignUp } from "../Modals/SignUp"; import { Container } from "./styles"; type InputFieldProps = InputHTMLAttributes<HTMLInputElement> & { labelId: "username" | "password" | "passwordConfirmation" | "remember"; label: string; error: boolean; }; const InputFieldComponent = ( { labelId, label, error, ...rest }: InputFieldProps, ref: React.Ref<HTMLInputElement> ) => { return ( <Container htmlFor={labelId} error={error}> {rest.type === "checkbox" ? <span>{label}: </span> : <p>{label}:</p>} <input id={labelId} {...rest} ref={ref} /> </Container> ); }; export const InputField = forwardRef< HTMLInputElement, InputFieldProps & ReturnType<UseFormRegister<InputsSignIn | InputsSignUp>> >(InputFieldComponent);
boilerplate: angularjs ====================== A project boilerplate for prototyping web apps using Jekyll and Bootstrap 3. This boilerplate uses: - jQuery 2.1.1 - Bootstrap 3.2.0 - Font-Awesome 4.1.0 ### Table of Contents 1. [Usage](#usage): how to use this boilerplate 2. [Directory Structure](#directory-structure) 3. [Grunt Tasks](#grunt-tasks) Usage ----- 1. Install Node packages: `$ npm install` 2. Install Bower packages: `$ bower install` Directory Structure ------------------- ``` shell boilerplate: angularjs # root directory ├── app | ├── _data | ├── _includes | ├── _layouts | └── _posts │ ├── assets │ │ ├── css │ │ ├── fonts | │ ├── img | | └── js | | ├── app | | └── lib | ├── .htaccess | └── index.html ├── src | ├── less | └── scss ├── _config.yml ├── bower.json ├── Gruntfile.js ├── package.json └── README.md ``` source ------ `source/` source directory is where we place precompiled assets e.g., less, scss, image files or in other words the 'raw-sources' we then specify and use Gruntfile to everything that is in here for to their respective destinations in build the application directory for staging or production use. **Bootstrap Less:** Bootstrap less css are placed in `source/less/bootstrap` and an bootstrap main less file is created in `source/less/bootstrap.less` that imports all bootstrap components from the bootstrap directory, if you don't intend to migrate to newer versions or pull massive updates from github then you may edit the less files in there but if you'd like to stay up to date, just create a new directory with all your overrides and then import them to your main less file. **Font-Awesome Less:** Don't forget to edit `source/less/font-awesome/variables.less` font path and point it to `/assets/fonts/font-awesome` otherwise fonts will not show up. Grunt Tasks ----------- These are the default tasks that Gruntfile executes, you may add necessary tasks to build your application. You may run `$ grunt` to perform default tasks. **copy** it copies all packages downloaded inside `bower_components` which are also listed in `bower.json` you may add additional package anytime just make sure ```shell $ grunt updatepkg ``` **less** compiles the default Less stylesheet and outputs it to `application/assets/css` with a full and minified version. watch: you may run this while working on your less stylesheets, it watches `source/less/` directory for file changes and automatically executes the less task that compiles less stylesheets to css, outputs go to `application/assets/css`. ```shell $ grunt watchless # or $ grunt buildless ``` **imagemin** optimises image files `*.{gif,jpg,png}` and compresses these up to 20% less of the the original file size. ```shell $ grunt buildimg ``` **jshint** watch folders changes and automatically jshint to lint the `.js` filez you're currently working on just run ```shell $ grunt watchjs #or $ grunt lint ```
while True: try: a = int(input('請輸入第一位數字:')) b = int(input('請輸入第二位數字:')) c = int(input('請選擇何種運算符號?\n1.加, 2.減, 3.乘, 4.除')) if c == 1: print('{} 和 {} 相加後的答案為:{}'.format(a, b, a+b)) d = input('要繼續嗎?按Q離開') if d == 'q' or d == 'Q': break elif c == 2: print('{} 和 {} 相減後的答案為:{}'.format(a, b, a-b)) d = input('要繼續嗎?按Q離開') if d == 'q' or d == 'Q': break elif c == 3: print('{} 和 {} 相乘後的答案為:{}'.format(a, b, a*b)) d = input('要繼續嗎?按Q離開') if d == 'q' or d == 'Q': break elif c == 4: print('{} 和 {} 相除後的答案為:{}'.format(a, b, a/b)) d = input('要繼續嗎?按Q離開') if d == 'q' or d == 'Q': break else: print('輸入錯誤') except ValueError: print("輸入格式有誤") except: print("程式出現其它異常")
/** * Copyright (c) 2016 广东天波信息技术股份有限公司 * @author linhx */ package com.common.sdk.printer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.Context; import android.graphics.Bitmap; import com.common.sdk.InternalErrorException; import com.common.sdk.TelpoException; import com.common.sdk.DeviceNotFoundException; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.EnumMap; import java.util.Map; import android.util.Log; import android.graphics.Paint; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Typeface; /** * 天波热敏打印机控制类 * * @author linhx * @version 1.0 * @since 1.0 */ public class ThermalPrinter { private Context mContext = null; public static String version; public static String sdkversion; public static final String TAG = "Tps900"; public ThermalPrinter(Context context) { mContext = context; } /** * 左对齐 */ public final static int ALGIN_LEFT = 0; /** * 居中对齐 */ public final static int ALGIN_MIDDLE = 1; /** * 右对齐 */ public final static int ALGIN_RIGHT = 2; /** * 走纸方向,向前 */ public final static int DIRECTION_FORWORD = 0; /** * 走纸方向,向后 */ public final static int DIRECTION_BACK = 1; /** * 点行走纸 */ public final static int WALK_DOTLINE = 0; /** * 字符行走纸 */ public final static int WALK_LINE = 1; /** * 打印机就绪 */ public final static int STATUS_OK = 0; /** * 打印机缺纸 */ public final static int STATUS_NO_PAPER = 1; /** * 打印机机芯过热 */ public final static int STATUS_OVER_HEAT = 2; /** * 打印机缓存已满 */ public final static int STATUS_OVER_FLOW = 3; /** * 打印机状态未知 */ public final static int STATUS_UNKNOWN = 4; /** * 打印机资源申请,必须先申请才能使用打印机相关操作,使用完需调用{@link ThermalPrinter#stop()}方法进行释放 * * @throws DeviceAlreadyOpenException * 当资源已经申请时再申请产生 * @throws DeviceNotFoundException * 当找不到设备时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void start()throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("start"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 打印机重置,所有设置恢复默认设置,打印缓冲清空 * * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void reset() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("reset"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 打印走纸 * * @param line * 点行数,>0 * @throws IllegalArgumentException * 当点行小于等于0时 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws DeviceOverFlowException * 打印过程中打印机缓存满产生 * @throws NoPaperException * 打印过程中打印机缺纸时产生 * @author linhx * @version 1.0 * @throw OverHeatException 打印过程中打印机芯过热产生 * @since 1.0 */ public synchronized void walkPaper(int line) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("walkPaper", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, line); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } public void printQrcode(String str, int w, int h) throws TelpoException { Bitmap bitmap = null; try { bitmap = CreateCode(str, BarcodeFormat.QR_CODE, w, h); } catch (WriterException e) { e.printStackTrace(); } // BarcodeFormat.QR_CODE if (bitmap != null) { Log.v(TAG, "Find the Bmp"); this.printLogo(bitmap); } } public Bitmap CreateCode(String str, com.google.zxing.BarcodeFormat type, int bmpWidth, int bmpHeight) throws WriterException { String utf8Str = null; // 生成二维矩阵,编码时要指定大小,不要生成了图片以后再进行缩放,以防模糊导致识别失败 Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix matrix = new MultiFormatWriter().encode(str, type, bmpWidth, bmpHeight, hints); int width = matrix.getWidth(); int height = matrix.getHeight(); // 二维矩阵转为一维像素数组(一直横着排) int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * width + x] = 0xffffffff; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // 通过像素数组生成bitmap,具体参考api bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * 释放打印机,不使用打印机时必须释放 * * @author linhx * @version 1.0 * @throws TelpoException * @since 1.0 */ public synchronized void stop() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("stop"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 检测打印机状态 * * @return 返回值见<BR> * {@link ThermalPrinter#STATUS_OK}<BR> * {@link ThermalPrinter#STATUS_NO_PAPER}<BR> * {@link ThermalPrinter#STATUS_OVER_HEAT}<BR> * {@link ThermalPrinter#STATUS_OVER_FLOW}<BR> * {@link ThermalPrinter#STATUS_UNKNOWN} * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @since 1.0 */ public synchronized int checkStatus() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; int iResult = 0; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("checkStatus"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { iResult = (Integer) method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } return iResult; } /** * 打印字体宽高放大 * * @param widthMultiple * 1-2倍,打印机初始状态为1 * @param heightMultiple * 1-2倍,打印机初始状态为1 * @throws IllegalArgumentException * 当倍数小于1或者大于2时产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void enlargeFontSize(int widthMultiple, int heightMultiple) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("enlargeFontSize", new Class[]{int.class, int.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, widthMultiple, heightMultiple); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置字体 * * @param type * 字号设置,1-2,默认为2号字体 <BR> * 对于单字节字符 1号字体大小为 8*16 2号字体大小为12*24 <BR> * 对于双字节字符 1号字体大小为 16*16 2号字体大小为24*24 <BR> * * @throws IllegalArgumentException * 当倍数小于1或者大于2时产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setFontSize(int type) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setFontSize", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, type); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置是否反白 * * @param mode * true,允许反白打印 <BR> * false,禁止反白,默认状态 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setHighlight(boolean mode) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setHighlight", boolean.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, mode); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置打印灰度值 * * @param level * 0-12,默认为4 * @throws IllegalArgumentException * 当灰度值小于0或者大于15时产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setGray(int level) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setGray", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, level); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } public void textAsBitmap( String text, boolean fontGrande, boolean negrito, boolean invertido ) { try { this.reset(); this.setGray(7); } catch (Exception e) { e.printStackTrace(); } Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.WHITE); if(invertido) paint.setColor(Color.BLACK); paint.setFakeBoldText(negrito); paint.setTextAlign(Paint.Align.LEFT); paint.setTypeface(Typeface.MONOSPACE); paint.setTextSize(20); float baseline = - paint.ascent(); // ascent() is negative int width = (int) (paint.measureText(text) + 0.5f); // round int height = (int) (baseline + paint.descent() + 0.5f); // Log.v(TAG, "width: " + width); // Log.v(TAG, "height: " + height); // Log.v(TAG, "baseline: " + baseline); // Log.v(TAG, "paint.measureText(text): " + paint.measureText(text)); // Log.v(TAG, "paint.descent(): " + paint.descent()); Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(image); canvas.drawPaint(paint); paint.setColor(Color.BLACK); if(invertido) paint.setColor(Color.WHITE); canvas.drawText(text, 0, baseline, paint); try { if(fontGrande) this.printLogo( Bitmap.createScaledBitmap(image, width, height * 2, false) ); else this.printLogo(image); ; // this.printLogo(createBlackAndWhite(image)); } catch (Exception e) { e.printStackTrace(); } } public static Bitmap createBlackAndWhite(Bitmap src) { int width = src.getWidth(); int height = src.getHeight(); // create output bitmap Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig()); // color information int A, R, G, B; int pixel; // scan through all pixels for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { // get pixel color pixel = src.getPixel(x, y); A = Color.alpha(pixel); R = Color.red(pixel); G = Color.green(pixel); B = Color.blue(pixel); int gray = (int) (0.2989 * R + 0.5870 * G + 0.1140 * B); // use 128 as threshold, above -> white, below -> black if (gray > 128) gray = 255; else gray = 0; // set new pixel color to output bitmap bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray)); } } return bmOut; } /** * 设置打印对齐方式 * * @param mode * 对齐方式 <BR> * {@link ThermalPrinter#ALGIN_LEFT} 左对齐 <BR> * {@link ThermalPrinter#ALGIN_MIDDLE} 居中对齐 <BR> * {@link ThermalPrinter#ALGIN_RIGHT} 右对齐 * @throws IllegalArgumentException * 当对齐方式参数 <tt>mode</tt>非法时产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setAlgin(int mode) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setAlgin", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, mode); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 添加打印内容 * * @param content * 要打印的内容 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws NullPointerException * 当参数<tt>content</tt>为空时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void addString(String content) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("addString", String.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, content); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 清除已添加的打印内容 * * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @version 1.0 * @author linhx * @since 1.0 */ public synchronized void clearString() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("clearString"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 启动打印,打印完不走纸 * * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws DeviceOverFlowException * 打印过程中打印机缓存满产生 * @throws NoPaperException * 打印过程中打印机缺纸时产生 * @author linhx * @version 1.0 * @throw OverHeatException 打印过程中打印机芯过热产生 * @since 1.0 */ public synchronized void printString() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("printString"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 启动打印并走纸 * * @param direction * 打印完后走纸方向 <BR> * {@link ThermalPrinter#DIRECTION_FORWORD},向前走纸<BR> * {@link ThermalPrinter#DIRECTION_BACK},向后走纸 * @param mode * 走纸模式 <BR> * {@link ThermalPrinter#WALK_DOTLINE},点行<BR> * {@link ThermalPrinter#WALK_LINE},字符行 * @param lines * 走纸行数,1-255 * @throws IllegalArgumentException * 参数不正确导致 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws DeviceOverFlowException * 打印过程中打印机缓存满产生 * @throws NoPaperException * 打印过程中打印机缺纸时产生 * @author linhx * @version 1.0 * @throw OverHeatException 打印过程中打印机芯过热产生 * @since 1.0 */ public synchronized void printStringAndWalk(int direction, int mode, int lines) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("printStringAndWalk", new Class[]{int.class, int.class, int.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, direction, mode, lines); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置行间距 * * @param lineSpace * 行间距,单位点行,0-255 * @throws IllegalArgumentException * 当行间距<tt>lineSpace</tt>小于1或者大于255时候产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setLineSpace(int lineSpace) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setLineSpace", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, lineSpace); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置字符间距 * * @param charSpace * 字符间距,单位点行,0-255 * @throws IllegalArgumentException * 当字符间距间距<tt>lineSpace</tt>小于1或者大于255时候产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 2.0 * @date 2016-01-20 * @since 2.0 */ public synchronized void setCharSpace(int charSpace) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setCharSpace", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, charSpace); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置左边距 * * @param space * 左边距,单位0.125mm,0-255 * @throws IllegalArgumentException * 当行间距<tt>space</tt>小于1或者大于255时候产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @author linhx * @version 1.0 * @since 1.0 */ public synchronized void setLeftIndent(int space) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setLeftIndent", int.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, space); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 打印图片,不加入缓冲队列直接打印 * * @param image * Bitmap对象,宽必须小于或等于384个像素点,如果设置了左间距,则左间距加上宽需要小于384 * @throws NullPointerException * 当参数<tt>image</tt>为空时 * @throws IllegalArgumentException * 当图片的宽高不符合要求的时候产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws DeviceOverFlowException * 打印过程中打印机缓存满产生 * @throws NoPaperException * 打印过程中打印机缺纸时产生 * @throws OverHeatException * 打印过程中打印机芯过热产生 * @author linhx * @version 1.0 * * @since 1.0 */ public synchronized void printLogo(Bitmap image) throws TelpoException { printLogo(image, false); } /** * 打印图片 * * @param image * Bitmap对象,宽必须小于或等于384个像素点,如果设置了左间距,则左间距加上宽需要小于384 * @param isBuffer * 是否将图片数据加入缓冲队列,true加入缓冲队列(文字图片混排时保持流畅),false不加入缓冲队列直接打印 * @throws NullPointerException * 当参数<tt>image</tt>为空时 * @throws IllegalArgumentException * 当图片的宽高不符合要求的时候产生 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws DeviceOverFlowException * 打印过程中打印机缓存满产生 * @throws NoPaperException * 打印过程中打印机缺纸时产生 * @throws OverHeatException * 打印过程中打印机芯过热产生 * @author linhx * @version 2.0 * @since 2.0 */ public synchronized void printLogo(Bitmap image, boolean isBuffer) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("printLogo", new Class[] {Bitmap.class, boolean.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, image, isBuffer); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } public synchronized String getVersion() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; String version = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("getVersion"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { version = (String)method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } return version; } /* * 获取SDK打印模块版本号 */ public String getSDKVersion() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; String sdkVersion = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("getSDKVersion"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { sdkVersion = (String)method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } return sdkVersion; } /** * 搜索黑标 * * @param direction * 搜索方向<BR> * {@link DIRECTION_FORWORD} 向前搜索<BR> * {@link DIRECTION_BACK} 向后搜索<BR> * @param search_disdance * 最大搜索距离,0~255,单位mm,1mm = 8点行 * @param walk_disdance * 搜索到黑标后的走纸距离,0~255,单位mm,1mm = 8点行 * * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 * @throws InternalErrorException * 内部库运行错误 */ public void searchMark(int direction, int search_disdance, int walk_disdance) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("searchMark", new Class[] {int.class, int.class, int.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, direction, search_disdance, walk_disdance); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } public void paperCut() throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("paperCut"); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } /** * 设置加粗 * * @param isBold * true 加粗;false 不加粗 * @throws DeviceNotOpenException * 当资源或设备未申请或打开时产生 */ public void setBold(boolean isBold) throws TelpoException { Class<?> thermalPrinter = null; Method method = null; Object obj = null; try { thermalPrinter = Class.forName("com.common.sdk.thermalprinter.ThermalPrinterServiceManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new InternalErrorException(); } obj = mContext.getSystemService("ThermalPrinter"); try { method = thermalPrinter.getMethod("setBold", boolean.class); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new InternalErrorException(); } try { method.invoke(obj, isBold); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (IllegalAccessException e) { e.printStackTrace(); throw new InternalErrorException(); } catch (InvocationTargetException e) { e.printStackTrace(); Exception targetExp = (Exception) e.getTargetException(); if (targetExp instanceof TelpoException) { throw (TelpoException)targetExp; } } } }
package com.jsongo.core.network import com.google.gson.* import com.jsongo.core.BaseCore import com.jsongo.core.R import com.jsongo.core.constant.ConstConf import com.safframework.log.LogLevel import com.safframework.log.okhttp.LoggingInterceptor import okhttp3.Cache import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.lang.reflect.Type import java.sql.Timestamp import java.util.* import java.util.concurrent.TimeUnit import kotlin.collections.HashMap /** * @author jsongo * @date 2019/3/26 15:54 */ object ApiManager { private val TIMEOUT = BaseCore.context.resources.getInteger(R.integer.network_time_out).toLong() private var gson: Gson? = null /** * OkHttpCLient集合 * key : isAddAuth(true/false) */ private val okHttpClientPool = HashMap<String, OkHttpClient>() /** * Retrofit集合 * key : BaseUrl_OkHttpClientKey */ private val retrofitPool = HashMap<String, Retrofit>() /** * apiService集合 * key : apiServiceName_RetrofitKey */ private val apiServicePool = HashMap<String, Any>() /** * 获取ApiService */ fun <T : Any> createApiService(clazz: Class<T>, isAddAuth: Boolean = true): T { val okHttpClientPair = createOkHttpClient(isAddAuth) val retrofitPair = createRetrofit(okHttpClientPair) val key = "${clazz.name}_${retrofitPair.first}" val cachedApiService = apiServicePool[key] val apiService: T if (cachedApiService == null) { apiService = retrofitPair.second.create(clazz) apiServicePool[key] = apiService } else { apiService = cachedApiService as T } return apiService } /** * 获取APIService,不带身份认证 */ fun <T : Any> createApiServiceWithoutAuth(clazz: Class<T>): T { return createApiService(clazz, false) } @Synchronized fun createOkHttpClient(isAddAuth: Boolean): Pair<String, OkHttpClient> { //key val key = isAddAuth.toString() //从缓存中获取 var okHttpClient = okHttpClientPool[key] //为空则创建 if (okHttpClient == null) { okHttpClient = OkHttpClient.Builder() .connectTimeout(TIMEOUT, TimeUnit.SECONDS) //连接超时设置 .readTimeout(TIMEOUT, TimeUnit.SECONDS) //写入缓存超时10s .writeTimeout(TIMEOUT, TimeUnit.SECONDS) //读取缓存超时10s .retryOnConnectionFailure(true) //失败重连 .addInterceptor(HeaderInterceptor(isAddAuth)) //添加header .addInterceptor(NetCacheInterceptor()) //添加网络缓存 .addLogIntercepter() //日志拦截器 .setCacheFile() //网络缓存 .build() okHttpClientPool[key] = okHttpClient } //返回key 和 OkHttpClient对象 return Pair(key, okHttpClient) } @Synchronized private fun createRetrofit( okHttpClientPair: Pair<String, OkHttpClient>, baseUrl: String = ServerAddr.SERVER_ADDRESS ): Pair<String, Retrofit> { //key val key = "${baseUrl}_${okHttpClientPair.first}" //从缓存中获取 var retrofit = retrofitPool[key] //为空则创建 if (retrofit == null) { retrofit = Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(getGson())) .client(okHttpClientPair.second) .build() //放入缓存 retrofitPool[key] = retrofit } //返回key 和 Retrofit对象 return Pair(key, retrofit!!) } /** * 设置缓存文件路径 */ private fun OkHttpClient.Builder.setCacheFile(): OkHttpClient.Builder { //设置缓存文件 val cacheFile = File(ConstConf.HTTP_CACHE_DIR) //缓存大小为10M val cacheSize = 10 * 1024 * 1024L val cache = Cache(cacheFile, cacheSize) cache(cache) return this } /** * 调试模式下加入日志拦截器 * @param builder */ private fun OkHttpClient.Builder.addLogIntercepter(): OkHttpClient.Builder { if (BaseCore.isDebug) { addInterceptor(LoggingInterceptor.Builder().apply { this.isDebug = BaseCore.isDebug this.logLevel = LogLevel.DEBUG }.build()) } return this } fun getGson(): Gson { if (gson == null) { gson = GsonBuilder() //.setDateFormat("yyyy-MM-dd HH:mm:ss SSS") .registerTypeAdapter(java.util.Date::class.java, DateSerializer()) .registerTypeAdapter(java.util.Date::class.java, DateDeserializer()) .create() } return gson!! } internal class DateSerializer : JsonSerializer<Date> { override fun serialize( src: Date, typeOfSrc: Type, context: JsonSerializationContext ): JsonElement { return JsonPrimitive(src.getTime()) } } internal class DateDeserializer : JsonDeserializer<Date> { @Throws(JsonParseException::class) override fun deserialize( json: JsonElement, typeOfT: Type, context: JsonDeserializationContext ): Date { val asLong = json.asLong return Timestamp(asLong) } } }
import {RequiredEncryptedConnectionOptions, Node, SyntaxKind} from "../../../parser-node"; import {TokenKind} from "../../../scanner"; import {CustomSyntaxKind, makeCustomRule} from "../../factory"; import {optional, zeroOrMore} from "../../../nearley-wrapper"; import {getTextRange, toValueNode} from "../../parse-util"; import {RequiredEncryptedConnectionOption} from "../../custom-data"; import {Diagnostic} from "../../../diagnostic"; /** * https://github.com/mysql/mysql-server/blob/5c8c085ba96d30d697d0baa54d67b102c232116b/sql/sql_yacc.yy#L14367 * * @todo Duplication `Option` items should produce parse errors */ makeCustomRule(SyntaxKind.RequiredEncryptedConnectionOptions) .addSubstitution( [ CustomSyntaxKind.RequiredEncryptedConnectionOption, zeroOrMore([ optional(TokenKind.AND), CustomSyntaxKind.RequiredEncryptedConnectionOption, ] as const), ] as const, (data) : RequiredEncryptedConnectionOptions => { const arr = data .flat(2) .filter((item) : item is RequiredEncryptedConnectionOption => { if (item == undefined) { return false; } if ("tokenKind" in item) { return false; } return true; }); const result : Omit<RequiredEncryptedConnectionOptions, keyof Node|"optionLocations"> = { x509Subject : undefined, x509Issuer : undefined, sslCipher : undefined, }; const syntacticErrors : Diagnostic[] = []; const optionLocations : RequiredEncryptedConnectionOptions["optionLocations"] = []; for (const item of arr) { if (item.syntacticErrors != undefined && item.syntacticErrors.length > 0) { syntacticErrors.push(...item.syntacticErrors); } for (const k of Object.keys(item)) { if (k in result) { (result as any)[k] = (item as any)[k]; optionLocations.push(toValueNode( k as any, item )) break; } } } return { ...getTextRange(data), syntaxKind : SyntaxKind.RequiredEncryptedConnectionOptions, ...result, syntacticErrors : ( syntacticErrors.length > 0 ? syntacticErrors : undefined ), optionLocations, }; } )
#ifndef FILEREADER_H #define FILEREADER_H #include <vector> #include <iterator> #include <string> #include <algorithm> #include <map> // #include <boost/algorithm/string.hpp> using namespace std; # include "../entities/Point.h" # include "../entities/Mbr.h" class FileReader { string filename; string delimeter; public: FileReader(); FileReader(string, string); vector<vector<string>> get_data(); vector<vector<string>> get_data(string); vector<Point> get_points(); vector<Mbr> get_mbrs(); vector<Point> get_points(string filename, string delimeter); vector<Mbr> get_mbrs(string filename, string delimeter); map<long long int, long long int> get_precomputed_hilbert(string hilbert_filename); }; #endif
class UpdateVestalVersions < ActiveRecord::Migration def self.up add_column :versions, :reverted_from, :integer rename_column :versions, :changes, :modifications end def self.down remove_column :versions, :reverted_from rename_column :versions, :modifications, :changes end end
#!/bin/bash langage="Java+PHP+Javascript+Python" old=IFS IFS=+ set $langage IFS=$old echo $1 echo $2 echo $3 echo $4 IFS=$old set $langage
package main import ( "fmt" "os" "text/template" "github.com/urfave/cli" ) var ( GenerateK8sSpecCommand = cli.Command{ Name: "generate-k8s-spec", Usage: "Generate k8s ReplicationController specs", Category: "Kubernetes spec file generation", Action: generateK8sSpec, } GenerateK8sNetPolicyCommand = cli.Command{ Name: "generate-k8s-net-policy", Usage: "Generate k8s NetworkPolicy specs", Category: "Kubernetes spec file generation", Action: generateK8sNetPolicy, } ) type PolicyTemplate struct { Name FuncHost Policy string } func writeSpec(template *template.Template, templateConfig interface{}, path string, typ string) { log.Infof("Generating k8s %s %s...", typ, path) spec, err := os.Create(path) if err != nil { log.Fatal("Unable to open spec file \"%s\" for writing: %s", path, err) } defer spec.Close() if err := template.Execute(spec, templateConfig); err != nil { log.Fatal("Unable to write spec file: %s", err) } } func generateK8sNetPolicy(cli *cli.Context) { tree := GetExternalFuncTree() policyTmpl, err := template.ParseFiles("templates/k8s_net_policy.json") if err != nil { log.Fatalf("Unable to read template file: %s", err) } format := "{\n \"podSelector\": {\n \"matchLabels\": {\n" format += " \"apisim\": \"%s\"\n }\n }\n}" for host, funcNode := range tree { // status can reach all functions policyText := fmt.Sprintf(format, "status") for port := range funcNode { callers := FindCallers(host, port) l4callers := callers.L4Callers() for k := range l4callers { policyText += "," + fmt.Sprintf(format, k) } } c := PolicyTemplate{host, policyText} writeSpec(policyTmpl, c, string(host)+"_netpolicy.spec", "NetPolicy") } } type TemplateConfig struct { Name FuncHost Ports string Command string } func generateK8sSpec(cli *cli.Context) { tree := GetExternalFuncTree() rcTmpl, err := template.ParseFiles("templates/k8s_rc.json") if err != nil { log.Fatalf("Unable to read template file: %s", err) } svcTmpl, err := template.ParseFiles("templates/k8s_svc.json") if err != nil { log.Fatalf("Unable to read template file: %s", err) } for host, nodeFunc := range tree { ports := "" nports := 0 for port := range nodeFunc { if nports > 0 { ports += "," } f := "{\"containerPort\": %s, \"name\": \"apisim-%s\"}" ports += fmt.Sprintf(f, string(port), string(port)) nports++ } c := TemplateConfig{host, ports, "\"/go/bin/app\", \"node-server\""} writeSpec(rcTmpl, c, string(host)+"_rc.spec", "ReplicationController") ports = "" nports = 0 for port := range nodeFunc { if nports > 0 { ports += "," } f := "{\"port\": %s, \"targetPort\": \"apisim-%s\"}" ports += fmt.Sprintf(f, string(port), string(port)) nports++ } c = TemplateConfig{host, ports, ""} writeSpec(svcTmpl, c, string(host)+"_svc.spec", "Service") } }
# Elm project ### Prerequisites Follow official install instructions for your setup: - [Elm](http://elm-lang.org/) 0.19 - node - yarn ### Development build - `yarn start` for a hot-reload dev server ### Tests - `yarn test` ### Production build - `yarn build` ### Deployment #### Needs to be configured in settings - When a pull request is created against `main`, netlify builds a preview site - When code is merged into `main` it is deployed to [current release](https://SITENAME.netlify.app)
require 'argo/property' module Argo class NumberProperty < Property end end
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "generator.h" #import <algorithm> #import <iterator> using std::ofstream; using std::string; using std::vector; static const string in = " "; static const string inin = in + in; static void write_syscall_signature_line(ofstream& os, const Syscall& sc, string name_prefix) { auto syscall_name = name_prefix + sc.name; os << "syscall_result " << syscall_name << "("; // Writes all arguments. sc.for_each_kernel_arg([&](const TypeSpec& arg) { os << arg.as_cpp_declaration(false) << ", "; }); os << "uint64_t pc) {\n"; } bool KernelWrapperGenerator::header(ofstream& os) { if (!Generator::header(os)) return false; os << "extern \"C\" {\n"; return os.good(); } bool KernelWrapperGenerator::syscall(ofstream& os, const Syscall& sc) { if (sc.is_vdso()) return true; auto syscall_name = syscall_prefix_ + sc.name; write_syscall_signature_line(os, sc, wrapper_prefix_); os << in << "return do_syscall(" << define_prefix_ << sc.name << ", " << "pc, " << "&VDso::ValidSyscallPC::" << sc.name << ", " << "[&](ProcessDispatcher* current_process) -> uint64_t {\n"; string args; for (const TypeSpec& arg : sc.arg_spec) { if (!args.empty()) args += ", "; if (arg.arr_spec) { args += "make_user_"; args += arg.arr_spec->kind_lowercase_str(); args += "_ptr("; args += arg.name; args += ")"; } else { args += arg.name; } } vector<string> out_handles; sc.for_each_return([&](const TypeSpec& arg) { if (!args.empty()) args += ", "; if (arg.arr_spec) { assert(arg.arr_spec->kind == ArraySpec::OUT); assert(arg.arr_spec->count == 1); if (arg.type == "zx_handle_t") { out_handles.push_back(arg.name); os << inin << "user_out_handle out_handle_" << arg.name << ";\n"; args += "&out_handle_"; args += arg.name; } else { args += "make_user_out_ptr("; args += arg.name; args += ")"; } } else { args += arg.name; } }); os << inin << (sc.is_noreturn() ? "/*noreturn*/ " : "auto result = ") << syscall_name << "(" << args << ");\n"; if (sc.is_noreturn()) { os << inin << "/* NOTREACHED */\n"; os << inin << "return ZX_ERR_BAD_STATE;\n"; } else { for (const auto& arg : out_handles) { os << inin << "if (out_handle_" << arg << ".begin_copyout(current_process, make_user_out_ptr(" << arg << ")))\n" << inin << in << "return ZX_ERR_INVALID_ARGS;\n"; } for (const auto& arg : out_handles) { os << inin << "out_handle_" << arg << ".finish_copyout(current_process);\n"; } os << inin << "return result;\n"; } os << in << "});\n" << "}\n"; return os.good(); } bool KernelWrapperGenerator::footer(ofstream& os) { os << "}\n"; return os.good(); }
package io.continuum.bokeh package tests import org.specs2.mutable._ class PlottingSpec extends Specification { "bokeh.plotting API" should { "support markers" in { val fig = new Figure() object source extends ColumnDataSource { val x = column(List(1.0, 2.0, 3.0)) val y = column(List(2.0, 3.0, 4.0)) } fig.circle(List(2.0, 3.0, 4.0)).size(5.0) fig.circle(1.0, 2.0).size(5.0) fig.circle(List(1.0, 2.0, 3.0), 2.0).size(5.0) fig.circle(1.0, List(2.0, 3.0, 4.0)).size(5.0) fig.circle(List(1.0, 2.0, 3.0), List(2.0, 3.0, 4.0)).size(5.0) fig.circle(List((1.0, 2.0), (2.0, 3.0), (3.0, 4.0))).size(5.0) fig.circle(source.x, source.y) fig.circle(source)(_.x, _.y) 1 === 1 // TODO: write actuall tests } } }
#!/usr/bin/ruby $:.unshift '../lib' require 'tempfile' require 'test/unit' require 'socket' require 'xmpp4r/stream' require 'xmpp4r/semaphore' include Jabber class StreamTest < Test::Unit::TestCase def setup @tmpfile = Tempfile::new("StreamSendTest") @tmpfilepath = @tmpfile.path() @tmpfile.unlink @servlisten = UNIXServer::new(@tmpfilepath) thServer = Thread.new { @server = @servlisten.accept } @iostream = UNIXSocket::new(@tmpfilepath) n = 0 while not defined? @server and n < 10 sleep 0.1 n += 1 end @stream = Stream::new @stream.start(@iostream) end def teardown @stream.close @server.close end ## # tests that connection really waits the call to process() to dispatch # stanzas to filters def test_process called = false @stream.add_xml_callback { called = true } assert(!called) @server.puts('<stream:stream>') @server.flush assert(called) end def test_process100 @server.puts('<stream:stream>') @server.flush done = Semaphore.new n = 0 @stream.add_message_callback { n += 1 done.run if n % 100 == 0 } 100.times { @server.puts('<message/>') @server.flush } done.wait assert_equal(100, n) @server.puts('<message/>' * 100) @server.flush done.wait assert_equal(200, n) end def test_send @server.puts('<stream:stream>') @server.flush Thread.new { assert_equal(Iq.new(:get).delete_namespace.to_s, @server.gets('>')) @stream.receive(Iq.new(:result)) } called = 0 @stream.send(Iq.new(:get)) { |reply| called += 1 if reply.kind_of? Iq and reply.type == :result true else false end } assert_equal(1, called) end def test_send_nested @server.puts('<stream:stream>') @server.flush finished = Semaphore.new Thread.new { assert_equal(Iq.new(:get).delete_namespace.to_s, @server.gets('>')) @server.puts(Iq.new(:result).set_id('1').delete_namespace.to_s) @server.flush assert_equal(Iq.new(:set).delete_namespace.to_s, @server.gets('>')) @server.puts(Iq.new(:result).set_id('2').delete_namespace.to_s) @server.flush assert_equal(Iq.new(:get).delete_namespace.to_s, @server.gets('>')) @server.puts(Iq.new(:result).set_id('3').delete_namespace.to_s) @server.flush finished.run } called_outer = 0 called_inner = 0 @stream.send(Iq.new(:get)) do |reply| called_outer += 1 assert_kind_of(Iq, reply) assert_equal(:result, reply.type) if reply.id == '1' @stream.send(Iq.new(:set)) do |reply2| called_inner += 1 assert_kind_of(Iq, reply2) assert_equal(:result, reply2.type) assert_equal('2', reply2.id) @stream.send(Iq.new(:get)) true end false elsif reply.id == '3' true else false end end assert_equal(2, called_outer) assert_equal(1, called_inner) finished.wait end def test_send_in_callback @server.puts('<stream:stream>') @server.flush finished = Semaphore.new @stream.add_message_callback { @stream.send_with_id(Iq.new(:get)) { |reply| assert_equal(:result, reply.type) } } Thread.new { @server.gets('>') @server.puts(Iq.new(:result)) finished.run } @server.puts(Message.new) finished.wait end def test_bidi @server.puts('<stream:stream>') @server.flush finished = Semaphore.new ok = true n = 100 Thread.new { n.times { |i| ok &&= (Iq.new(:get).set_id(i).delete_namespace.to_s == @server.gets('>')) @server.puts(Iq.new(:result).set_id(i).to_s) @server.flush } finished.run } n.times { |i| @stream.send(Iq.new(:get).set_id(i)) { |reply| ok &&= reply.kind_of? Iq ok &&= (:result == reply.type) ok &&= (i.to_s == reply.id) true } } finished.wait assert(ok) end def test_similar_children delay = 0.1 n = 0 @stream.add_message_callback { n += 1 } assert_equal(0, n) @server.puts('<stream:stream><message/>') @server.flush sleep delay assert_equal(1, n) @server.puts('<message>') @server.flush sleep delay assert_equal(1, n) @server.puts('<message/>') @server.flush sleep delay assert_equal(1, n) @server.puts('</message>') @server.flush sleep delay assert_equal(2, n) @server.puts('<message><stream:stream><message/></stream:stream>') @server.flush sleep delay assert_equal(2, n) @server.puts('</message>') @server.flush sleep delay assert_equal(3, n) end end
## December 15th 2017 Ugh, Boost didn't work either. Going to try just a straight port to wiringpy or something. Still waiting on some supplies before full construction can begin. But plans are being laid. LED spots tested, etc. Going to look into a shade of gold to match the existing paint, for the scuffs from dissassembly.
''' Created on April 23, 2019 @author: gsnyder Assign a user to a user group ''' import argparse import json import logging from pprint import pprint import sys from blackduck.HubRestApi import HubInstance parser = argparse.ArgumentParser("Create a new user") parser.add_argument("user") parser.add_argument("user_group") args = parser.parse_args() logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) hub = HubInstance() parameters={"q":"userName:{}".format(args.user)} users = hub.get_users(parameters=parameters).get('items', []) if users and len(users) == 1: user_obj = users[0] user_group_obj = hub.get_user_group_by_name(args.user_group) if user_group_obj: add_user_url = hub.get_link(user_group_obj, "users") post_data = [{"user": user_obj['_meta']['href']}] response = hub.execute_post(add_user_url, data=post_data) if response.status_code == 204: logging.info("Added user {} to user group {}".format(args.user, args.user_group)) else: logging.error("Failed to add user {} to user group {}, status code was {}".format( args.user, args.user_group, response.status_code)) else: logging.debug("did not find user group object for user group = {}".format(args.user_group)) else: logging.debug("Could not find user object with username = {}".format(args.user))
# encoding: utf-8 module Moip class Model include ActiveModel::Validations include ActiveModel::Serialization def to_json hash = self.serializable_hash.delete_if {|key, value| value.nil? } hash.to_json end def set_parameters params params.each do |key, value| self.send("#{key}=".to_sym, value) end end def validate_response response if response.key? "errors" and response["errors"].size > 0 error = response["errors"][0] self.errors.add :moip_error, "#{error["description"]}" false else true end end class << self # metodo que cria um objeto e seta os seus parametros se responder pela chave # recebe um Hash como parametro def build params if params.is_a? Hash object = new params.each do |key, value| object.send("#{key}=".to_sym, value) if object.respond_to? key.to_sym end object else raise Exception.new "unexpected parameter, expected Hash, received #{params.class}" end end end end end
#!/usr/bin/env python3 ################ mylis: Tiny Scheme Environment in Python 3.10 ## Additional runtime support by Luciano Ramalho for lis.py by ## Peter Norvig (c) 2010-18; See http://norvig.com/lispy.html import operator as op import readline # "unused" import to enable readline in input() import sys from collections.abc import Sequence, Iterator from typing import Any, Protocol, Callable, NoReturn import parser from evaluator import Environment, standard_env, evaluate from mytypes import Expression, UndefinedSymbol, UnexpectedCloseParen, EvaluatorException ################ non-interactive execution def run_lines(source: str, env: Environment | None = None) -> Iterator[Any]: global_env = Environment({}, standard_env()) if env is not None: global_env.update(env) tokens = parser.tokenize(source) while tokens: exp = parser.read_from_tokens(tokens) yield evaluate(exp, global_env) def run(source: str, **env: Expression) -> Any: for result in run_lines(source, env): pass return result ############### multi-line REPL class QuitRequest(Exception): """Signal to quit multi-line input.""" ELLIPSIS = '\N{HORIZONTAL ELLIPSIS}' def raise_unexpected_paren(line: str) -> NoReturn: max_msg_len = 16 if len(line) < max_msg_len: msg = line else: msg = ELLIPSIS + line[-(max_msg_len-1):] raise UnexpectedCloseParen(msg) QUIT_COMMAND = '.q' InputFn = Callable[[str], str] def multiline_input(prompt1: str, prompt2: str, *, quit_cmd: str = QUIT_COMMAND, input_fn: InputFn = input) -> str: paren_cnt = 0 lines = [] prompt = prompt1 while True: line = input_fn(prompt).rstrip() if line == quit_cmd: raise QuitRequest() for char in line: if char == '(': paren_cnt += 1 elif char == ')': paren_cnt -= 1 if paren_cnt < 0: raise_unexpected_paren(line) lines.append(line) prompt = prompt2 if paren_cnt == 0: break return '\n'.join(lines) def multiline_repl(prompt1: str = '> ', prompt2: str = '... ', error_mark: str = '***', *, quit_cmd: str = QUIT_COMMAND, input_fn: InputFn = input) -> None: """Read-Eval-Print-Loop""" global_env = Environment({}, standard_env()) print(f'To exit type {QUIT_COMMAND}', file=sys.stderr) while True: # ___________________________________________ Read try: source = multiline_input(prompt1, prompt2, quit_cmd=quit_cmd, input_fn=input_fn) except (EOFError, QuitRequest): break except UnexpectedCloseParen as exc: print(error_mark, exc) continue if not source: continue # ___________________________________________ Eval current_exp = parser.parse(source) try: result = evaluate(current_exp, global_env) except EvaluatorException as exc: print(error_mark, exc) continue # ___________________________________________ Print if result is not None: print(parser.s_expr(result)) ############### command-line integration class TextReader(Protocol): def read(self) -> str: ... def run_file(source_file: TextReader, env: Environment | None = None) -> Any: source = source_file.read() return run(source, **env) def env_from_args(args: Sequence[str]) -> Environment: env = {} for arg in (a for a in args if '=' in a): parts = arg.split('=') if len(parts) != 2 or not all(parts): continue name, val = parts try: atom = parser.parse_atom(val) except ValueError: continue env[name] = atom return env ############### main PROMPT1 = '\N{WHITE RIGHT-POINTING TRIANGLE} ' PROMPT2 = '\N{MIDLINE HORIZONTAL ELLIPSIS} ' ERROR_MARK = '\N{POLICE CARS REVOLVING LIGHT} ' def repl(): multiline_repl(PROMPT1, PROMPT2, ERROR_MARK) def main(args: list[str]) -> None: if len(args) == 1: repl() else: arg_env = env_from_args(args[1:]) with open(args[1]) as source_file: try: run_file(source_file, arg_env) except UndefinedSymbol as exc: key = exc.args[0] print(f'{ERROR_MARK} {key!r} was not defined.') cmd = ' '.join(args) print(' You can define it as an option:') print(f' $ {cmd} {key}=<value>') if __name__ == '__main__': main(sys.argv)
import { Box, Text, Link as HTMLLink } from '@theme-ui/components'; import Layout from './layout'; import SEO from './seo'; import Link from './link'; import PageListHeading from './page-list-heading'; import DraftBadge from './draft-badge'; const NotesPage = (props) => ( <Layout pageContext={props.pageContext}> <SEO title="Notes by Nicola Molinari" description="A collections of notes, mostly about technical topics." pathname={props.path} /> <PageListHeading title="Notes" sideElement={<Link to="/notes/tags">View all tags</Link>} /> <Box as="p" sx={{ mb: [5] }}> <Text as="span">{'You can find other of my articles on '}</Text> <HTMLLink href="https://medium.com/@emmenko">Medium</HTMLLink> </Box> <section sx={{ mb: [5, 6, 7] }}> {props.data.allNotePage.nodes.map((notePage) => ( <Box mb={5} key={notePage.slug}> {notePage.isDraft && <DraftBadge />} <Box> <Link to={notePage.slug} variant="links.navigation"> <Text as="h2" sx={{ fontSize: 5, fontWeight: 'semibold', lineHeight: 'heading', mb: [1, 2], }} > {notePage.title} </Text> </Link> </Box> <Box sx={{ color: 'secondary', fontStyle: 1 }}> <time>{notePage.date}</time> </Box> <Box as="p" sx={{ mt: 3 }}> {notePage.description} </Box> </Box> ))} </section> </Layout> ); export default NotesPage;
package com.endava.cats.fuzzer.headers.base; import com.endava.cats.io.ServiceCaller; import com.endava.cats.model.FuzzingStrategy; import com.endava.cats.report.TestCaseListener; import java.util.List; import java.util.stream.Collectors; /** * Base class for fuzzers sending Control Chars or Unicode Separators in headers. */ public abstract class InvisibleCharsBaseFuzzer extends ExpectOnly4XXBaseHeadersFuzzer { protected InvisibleCharsBaseFuzzer(ServiceCaller sc, TestCaseListener lr) { super(sc, lr); } @Override public List<FuzzingStrategy> fuzzStrategy() { return this.getInvisibleChars() .stream().map(value -> concreteFuzzStrategy().withData(value)) .collect(Collectors.toList()); } @Override public String description() { return "iterate through each header and " + typeOfDataSentToTheService(); } public abstract List<String> getInvisibleChars(); public abstract FuzzingStrategy concreteFuzzStrategy(); }
package app;/* BEGIN_HEADER TreeView 3 * * Please refer to our LICENSE file if you wish to make changes to this software * * END_HEADER */ import gui.labels.url.UrlPresets; import gui.window.TVController; import gui.window.TreeViewFrame; import model.data.matrix.DataModel; import model.data.matrix.TVModel; import model.fileImport.LoadException; import model.fileType.FileSet; import util.LogBuffer; import util.StringRes; import javax.swing.*; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; /** * This class defines the treeview application. In practice, it holds the common * functionality of the app.LinkedViewApp and the AppletApp. * * The main responsibilities of this class are to - hold static global * configuration variables, such as version and URLs - hold link to global * XmlConfig object - hold gene and array url preset objects - keep track of all * open windows - at one point, it kept track of plugins, but now the * PluginManager does that. * * The actual Gui handling of a given window is done by TreeViewFrame, which * represents a single document. Because multiple documents can be open at a * given time, there can be multiple TVFrame objects. However, there can be only * one TreeView object. What this really means is that TreeView itself just * manages two resources, the window list and the global config. Anything that * effects these resources should bottleneck through TreeView. * * 1/16/2003 by popular demand (with the exception of my advisor) I have decided * to try and make an applet version. As a first cut, I'm just going to make * this class extend applet and pop open a JFrame. * * 9/24/2003 this has now been superceded by the applet.ButtonApplet class. * * @author Alok Saldanha <alok@genome.stanford.edu> * @version $Revision: 1.16 $ $Date: 2010-05-11 13:31:51 $ */ public abstract class TreeViewApp {// implements WindowListener { /** holds all open windows */ // protected java.util.Vector<Window> windows; private final UrlPresets rowUrlPresets; private final UrlPresets columnUrlPresets; // private boolean exitOnWindowsClosed = true; /* holds global configuration settings */ private final Preferences globalConfig; /** * Constructor for the app.TreeViewApp object. Opens up a globalConfig from the * default location. */ public TreeViewApp() { this(null, false); } /** * Constructor for the app.TreeViewApp object takes configuration from the * passed in XmlConfig. * */ public TreeViewApp(final Preferences preferences, final boolean isApplet) { // windows = new java.util.Vector<Window>(); if (preferences != null) { globalConfig = preferences; } else { globalConfig = getMainPreferencesNode(); } handlePreferencesVersion(); rowUrlPresets = new UrlPresets("GeneUrlPresets"); rowUrlPresets.setConfigNode(getGlobalConfig()); columnUrlPresets = new UrlPresets("ArrayUrlPresets"); columnUrlPresets.setConfigNode(getGlobalConfig()); if (columnUrlPresets.getPresetLabelTypes().length == 0) { columnUrlPresets.addPreset("Google", "http://www.google.com/search?hl=en&ie=ISO-8859-1" + "&q=HEADER"); columnUrlPresets.setDefaultPreset(-1); } // Generate an XML file of the Preferences at this point, so it // can be viewed and analyzed. try { FileOutputStream fos = new FileOutputStream("prefs.xml"); globalConfig.exportSubtree(fos); fos.close(); final ToolTipManager ttm = ToolTipManager.sharedInstance(); ttm.setEnabled(true); } catch (final IOException | BackingStoreException e1) { LogBuffer.logException(e1); LogBuffer.println("Could not model.export preferences XML " + "file for viewing."); } } /** URL of codebase */ public abstract URL getCodeBase(); /** Starts up the application's setup process */ public abstract void start(); /** * The returned object contains presets for the URLs used when searching for * row labels in online databases. * * @return URLPresets for row labels. */ public UrlPresets getRowLabelUrlPresets() { return rowUrlPresets; } /** * The returned object contains presets for the URLs used when searching for * column labels in online databases. * * @return URLPresets for column labels. */ public UrlPresets getColumnLabelUrlPresets() { return columnUrlPresets; } /** * Loads the Preferences file stored on the users machine. If none is * present with the root node 'app.TreeViewApp', it creates a new one. * * @return Preferences */ public Preferences getMainPreferencesNode() { return Preferences.userRoot().node(StringRes.pnode_globalMain); } /** * Versioning following MAJOR.MINOR.PATCH * See http://semver.org/ * This routine now has the purpose of handling the preferences version. * If needed, it will make a decision how old versions are adapted and if * major restructuring of old preferences setups are needed. */ private void handlePreferencesVersion() { // Default 'none' to detect if Preferences are stored for the first time String currVersion = getNotedPreferencesVersion(); // An earlier version exists if(!"none".equals(currVersion)) { // Existing version does not match current version if(!StringRes.preferencesVersionTag.equals(currVersion)) { // TODO make sure old preferences are migrated well (BB Issue #407) } } // finally store the new version globalConfig.put("version", StringRes.preferencesVersionTag); } /** * * @return The version String denoting the Preferences version stored in * the node which was initially assigned to the configNode of this class * upon application startup. */ public String getNotedPreferencesVersion() { String version; if(globalConfig == null) { return "none"; } version = globalConfig.get("version", "none"); return version; } /** * returns an XmlConfig representing global configuration variables * * @return The globalConfig value */ public Preferences getGlobalConfig() { return globalConfig; } /** * creates a ViewFrame window * * @throws LoadException */ public TreeViewFrame openNew() { try { return openNew(null); } catch (final LoadException e) { // ignore, since not loading anything shouldn't throw. return null; } } /** * creates a new ViewFrame window displaying the specified * <code>FileSet</code> * * @param fileSet * FileSet to be displayed * @exception LoadException * If the fileset cannot be loaded, the window is closed and * the exception rethrown. * @throws LoadException */ public TreeViewFrame openNew(final FileSet fileSet) throws LoadException { // setup toplevel final TreeViewFrame tvFrame = new TreeViewFrame(this); final DataModel model = new TVModel(); final TVController tvController = new TVController(tvFrame, model); if (fileSet != null) { tvController.openFile(fileSet,false,false); } // tvFrame.addWindowListener(this); return tvFrame; } // /** // * A WindowListener, which allows other windows to react to another window // * being opened. // * // * @param e // * A window opening event. Used to add the window to the windows // * list. // */ // @Override // public void windowOpened(final WindowEvent e) { // // windows.addElement(e.getWindow()); // rebuildWindowMenus(); // } // /** // * rebuilds all the window menus. Should be called whenever a // * <code>ViewFrame</code> is created, destroyed, or changes its name. The // * first two cases are handled by <code>app.TreeViewApp</code>, the // * <code>ViewFrame</code> itself should call this method when it changes // its // * name. // */ // public void rebuildWindowMenus() { // // final int max = windows.size(); // for (int i = 0; i < max; i++) { // final ViewFrame source = (ViewFrame) windows.elementAt(i); // // rebuildWindowMenu( source.getWindowMenu()); // source.rebuildWindowMenu(windows); // } // } // /** // * A WindowListener, which allows other windows to react to another window // * being closed. // * // * @param e // * A window closing event. Used to remove the window from the // * windows list. // */ // @Override // public void windowClosed(final WindowEvent e) { // // windows.removeElement(e.getWindow()); // // if (windows.isEmpty() && exitOnWindowsClosed) { // endProgram(); // } // rebuildWindowMenus(); // } // /** // * loops over the list of windows the <code>app.TreeViewApp</code> has // collected // * through the WindowListener interface. just closes the window; other // * bookkeeping stuff is done by the <code>windowClosed</code> method. // */ // public void closeAllWindows() { // // final Enumeration<Window> e = windows.elements(); // while (e.hasMoreElements()) { // final ViewFrame f = (ViewFrame) e.nextElement(); // f.closeWindow(); // } // } // // public ViewFrame[] getWindows() { // // final ViewFrame[] frames = new ViewFrame[windows.size()]; // int i = 0; // // final Enumeration<Window> e = windows.elements(); // while (e.hasMoreElements()) { // frames[i++] = (ViewFrame) e.nextElement(); // } // // return frames; // } /** Stores the globalconfig, closes all windows, and then exits. */ protected abstract void endProgram(); // @Override // public void windowActivated(final WindowEvent e) { // // nothing // } // // @Override // public void windowClosing(final WindowEvent e) { // // nothing // } // // @Override // public void windowDeactivated(final WindowEvent e) { // // nothing // } // // @Override // public void windowDeiconified(final WindowEvent e) { // // nothing // } // // @Override // public void windowIconified(final WindowEvent e) { // // nothing // } // /** // * @param exitOnWindowsClosed // * the exitOnWindowsClosed to set // */ // public void setExitOnWindowsClosed(final boolean exitOnWindowsClosed) { // // this.exitOnWindowsClosed = exitOnWindowsClosed; // } }
package uk.co.barbuzz.appwidget.widget.click import android.annotation.SuppressLint import android.app.Notification import android.content.Intent import android.content.pm.PackageManager import uk.co.barbuzz.appwidget.R import uk.co.barbuzz.appwidget.base.navigation.ComponentCommand import uk.co.barbuzz.appwidget.widget.WidgetResources import uk.co.barbuzz.appwidget.widget.chooser.componentName import uk.co.barbuzz.appwidget.widget.click.commands.AppDetailsCommand import uk.co.barbuzz.appwidget.widget.click.commands.PlayStoreCommand import uk.co.barbuzz.appwidget.widget.click.commands.UninstallCommand import javax.inject.Inject internal class ActionListGenerator @Inject constructor( private val packageManager: PackageManager, private val widgetResources: WidgetResources, private val input: ClickHandlingActivity.Input ) { fun actionList(): List<Action> { return listOfNotNull( Action(R.string.widget_action_uninstall, widgetResources.deleteIcon, ::UninstallCommand), Action(R.string.widget_action_app_details, widgetResources.settingsIcon, ::AppDetailsCommand), Action(R.string.widget_action_play_store, widgetResources.playStoreIcon, ::PlayStoreCommand), appNotificationsAction(), appSettingsAction() ) } private fun appNotificationsAction(): Action? { val intent = Intent(Intent.ACTION_MAIN) .addCategory(Notification.INTENT_CATEGORY_NOTIFICATION_PREFERENCES) .setPackage(input.packageName) val resolveInfo = packageManager.queryIntentActivities(intent, 0).firstOrNull() ?: return null return Action( R.string.widget_action_app_notification_settings, command = ComponentCommand(resolveInfo.activityInfo.componentName()) ) } @SuppressLint("InlinedApi") private fun appSettingsAction(): Action? { val intent = Intent(Intent.ACTION_APPLICATION_PREFERENCES) .addCategory(Intent.CATEGORY_DEFAULT) .setPackage(input.packageName) val resolveInfo = packageManager.queryIntentActivities(intent, 0).firstOrNull() ?: return null return Action( R.string.widget_action_app_settings, command = ComponentCommand(resolveInfo.activityInfo.componentName()) ) } }
require './daemon' require './kafka_client' class ConsumerDaemon WAIT_MAX = 1 include Services def initialize @kafka = kafka_client @daemon = Daemon.new(0.5, true, self) end def exec message = @kafka.read_message movie = JSON.parse(message, symbolize_names: true) log_info('Serving ticket for movie', movie: movie) end def run @daemon.run end end ConsumerDaemon.new.run
--- name: "\U0001F41B Bug Report" about: "If something isn't working as expected \U0001F914." title: '' labels: bug assignees: '' --- <!-- Thanks for reporting an issue 😄 to `react-building-blocks`! Before you submit, please search open / closed issues before submitting, since someone else might have asked the same thing before. --> # 🐛 Bug Report ### 🏗 Relevant Components <!--- Please mention which components are related to your issue. --> ... ### 😯 Current Behavior <!--- Tell us what happens instead of the expected behavior. Please include the relevant error if there is one. --> ... ### 🤔 Expected Behavior <!--- Tell us what should happen. You can also provide a suggested solution if you'd like. --> ... ### 👣 Steps to Reproduce <!--- Please add an easy way to reproduce it. --> 1. [First Step] 2. [Second Step] 3. [and so on...] ### 👀 Severity <!--- Try to reflect how sever the issue is in general. Pick the most relevant one. --> - Critical / Major / Low
use std::collections::VecDeque; use std::ffi::{CString, OsStr, OsString}; use std::io; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use crate::{constants, open_beneath, util, AsPath, LookupFlags}; mod file_meta; mod iter; mod open_opts; pub use file_meta::{FileType, Metadata}; pub use iter::{Entry, ReadDirIter, SeekPos}; pub use open_opts::OpenOptions; #[cfg(target_os = "linux")] bitflags::bitflags! { /// Linux-specific: Flags for [`rename2()`]. /// /// If any of these flags are not supported by the filesystem, [`rename2()`] will fail with /// `EINVAL`. /// /// [`rename2()`]: ./fn.rename2.html pub struct Rename2Flags: libc::c_int { /// Rename the file without replacing the "new" file if it exists (fail with `EEXIST` in /// that case). /// /// This requires support from the underlying filesystem; older kernels do not support this /// for a number of filesystems. See renameat2(2) for more details. const NOREPLACE = libc::RENAME_NOREPLACE as libc::c_int; /// Atomically exchange the "old" and "new" files. const EXCHANGE = libc::RENAME_EXCHANGE as libc::c_int; /// Create a "whiteout" object at the source of the rename while performing the rename. /// Useful for overlay/union filesystems. /// /// Added in Linux 3.18. Requires CAP_MKNOD. const WHITEOUT = libc::RENAME_WHITEOUT as libc::c_int; } } #[inline] fn cstr(s: &OsStr) -> io::Result<CString> { Ok(CString::new(s.as_bytes())?) } /// A wrapper around a directory file descriptor that allows opening files within that directory. #[derive(Debug)] pub struct Dir { fd: RawFd, } impl Dir { /// Open the specified directory. pub fn open<P: AsPath>(path: P) -> io::Result<Self> { path.with_cstr(|s| { Ok(Self { fd: util::openat_raw(libc::AT_FDCWD, s, constants::DIR_OPEN_FLAGS, 0)?, }) }) } #[inline] fn reopen_raw(&self, flags: libc::c_int) -> io::Result<RawFd> { util::open_dot(self.fd, flags, 0).map(|f| f.into_raw_fd()) } /// Open the parent directory of this directory, without checking if it's open to the root /// directory. /// /// If this directory is open to the root directory, this method will return a new directory /// open to the same directory (similarly to [`try_clone()`]). /// /// [`try_clone()`]: #method.try_clone #[inline] pub fn parent_unchecked(&self) -> io::Result<Self> { Ok(Self { fd: util::open_dotdot(self.fd, constants::DIR_OPEN_FLAGS, 0) .map(|f| f.into_raw_fd())?, }) } /// Open the parent directory of this directory. /// /// This returns `Ok(None)` if this directory is open to the root directory. pub fn parent(&self) -> io::Result<Option<Self>> { let parent = self.parent_unchecked()?; if util::samestat(&util::fstat(self.fd)?, &util::fstat(parent.fd)?) { Ok(None) } else { Ok(Some(parent)) } } /// Open a subdirectory of this directory. /// /// `path` or one of its components can refer to a symlink (unless `LookupFlags::NO_SYMLINKS` /// is passed), but the specified subdirectory must be contained within this directory. #[inline] pub fn sub_dir<P: AsPath>(&self, path: P, lookup_flags: LookupFlags) -> io::Result<Self> { Ok(Self { fd: open_beneath(self.fd, path, constants::DIR_OPEN_FLAGS, 0, lookup_flags)? .into_raw_fd(), }) } /// Create a directory within this directory. pub fn create_dir<P: AsPath>( &self, path: P, mode: libc::mode_t, lookup_flags: LookupFlags, ) -> io::Result<()> { let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; if let Some(fname) = fname { let fd = subdir.as_ref().unwrap_or(self).as_raw_fd(); util::mkdirat(fd, &cstr(fname)?, mode) } else { Err(io::Error::from_raw_os_error(libc::EEXIST)) } } /// Remove a subdirectory of this directory. pub fn remove_dir<P: AsPath>(&self, path: P, lookup_flags: LookupFlags) -> io::Result<()> { let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; if let Some(fname) = fname { let fd = subdir.as_ref().unwrap_or(self).as_raw_fd(); match util::unlinkat(fd, &cstr(fname)?, true) { Err(e) => { #[cfg(not(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd", target_os = "macos", target_os = "ios" )))] if e.raw_os_error() == Some(libc::EEXIST) { return Err(io::Error::from_raw_os_error(libc::ENOTEMPTY)); } Err(e) } Ok(()) => Ok(()), } } else { Err(std::io::Error::from_raw_os_error(libc::EBUSY)) } } /// Remove a file within this directory. pub fn remove_file<P: AsPath>(&self, path: P, lookup_flags: LookupFlags) -> io::Result<()> { let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; if let Some(fname) = fname { let fd = subdir.as_ref().unwrap_or(self).as_raw_fd(); util::unlinkat(fd, &cstr(fname)?, false) } else { Err(io::Error::from_raw_os_error(libc::EISDIR)) } } /// Create a symlink within this directory. /// /// `path` specifies the path where the symlink is created, and `target` specifies the file /// that the symlink will point to. Note that the order is swapped compared to the C `symlink()` /// function (and Rust's `std::os::unix::fs::symlink()`). pub fn symlink<P: AsPath, T: AsPath>( &self, path: P, target: T, lookup_flags: LookupFlags, ) -> io::Result<()> { let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; if let Some(fname) = fname { let fd = subdir.as_ref().unwrap_or(self).as_raw_fd(); target.with_cstr(|target| util::symlinkat(target, fd, &cstr(fname)?)) } else { Err(io::Error::from_raw_os_error(libc::EEXIST)) } } /// Read the contents of the specified symlink. pub fn read_link<P: AsPath>(&self, path: P, lookup_flags: LookupFlags) -> io::Result<PathBuf> { cfg_if::cfg_if! { if #[cfg(all(target_os = "linux", feature = "openat2"))] { // On Linux, we can actually get a file descriptor to the *symlink*, then // readlink() that. However, if we don't have openat2() then this costs an extra // syscall, so let's only do it if the `openat2` feature is enabled. use std::ffi::CStr; let file = open_beneath( self.fd, path, libc::O_PATH | libc::O_NOFOLLOW, 0, lookup_flags, )?; match util::readlinkat(file.as_raw_fd(), unsafe { CStr::from_bytes_with_nul_unchecked(b"\0".as_ref()) }) { Ok(target) => Ok(target), // This error means we got a file descriptor that doesn't point to a symlink Err(e) if e.raw_os_error() == Some(libc::ENOENT) => { Err(io::Error::from_raw_os_error(libc::EINVAL)) } Err(e) => Err(e), } } else { // On other OSes (or without openat2()), we have to split the path and perform a // few more allocations. let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; if let Some(fname) = fname { let fd = subdir.as_ref().unwrap_or(self).as_raw_fd(); util::readlinkat(fd, &cstr(fname)?) } else { Err(io::Error::from_raw_os_error(libc::EINVAL)) } } } } /// Rename a file in this directory. /// /// This is exactly equivalent to `rename(self, old, self, new, lookup_flags)`. #[inline] pub fn local_rename<P: AsPath, R: AsPath>( &self, old: P, new: R, lookup_flags: LookupFlags, ) -> io::Result<()> { rename(self, old, self, new, lookup_flags) } /// List the contents of this directory. pub fn list_self(&self) -> io::Result<ReadDirIter> { ReadDirIter::new_consume(self.reopen_raw(libc::O_DIRECTORY | libc::O_RDONLY)?) } /// List the contents of the specified subdirectory. /// /// This is equivalent to `self.sub_dir(path, lookup_flags)?.list_self()`, but more efficient. pub fn list_dir<P: AsPath>( &self, path: P, lookup_flags: LookupFlags, ) -> io::Result<ReadDirIter> { ReadDirIter::new_consume( open_beneath( self.fd, path, libc::O_DIRECTORY | libc::O_RDONLY, 0, lookup_flags, )? .into_raw_fd(), ) } /// Try to "clone" this `Dir`. /// /// This is equivalent to `self.sub_dir(".")`, but more efficient. #[inline] pub fn try_clone(&self) -> io::Result<Self> { Ok(Self { fd: util::dup(self.fd)?, }) } /// Retrieve metadata of this directory. /// /// This is equivalent to `self.metadata(".", LookupFlags::empty())`, but it's significantly /// more efficient. #[inline] pub fn self_metadata(&self) -> io::Result<Metadata> { util::fstat(self.fd).map(Metadata::new) } /// Retrieve information on the file with the given path. /// /// The specified file must be located within this directory. Symlinks in the final component /// of the path are not followed. pub fn metadata<P: AsPath>(&self, path: P, lookup_flags: LookupFlags) -> io::Result<Metadata> { let (subdir, fname) = prepare_inner_operation(self, path.as_path(), lookup_flags)?; let subdir = subdir.as_ref().unwrap_or(self); if let Some(fname) = fname { fname.with_cstr(|s| { util::fstatat(subdir.as_raw_fd(), s, libc::AT_SYMLINK_NOFOLLOW).map(Metadata::new) }) } else { subdir.self_metadata() } } /// Recover the path to the directory that this `Dir` is currently open to. /// /// **WARNINGS (make sure to read)**: /// - **Do NOT** use this path to open any files within the directory (i.e. /// `File::open(path.join("file.txt"))`! That would defeat the entire purpose of this crate /// by opening vectors for symlink attacks. /// - If a potentially malicious user controls a parent directory of the directory that this /// `Dir` is currently open to, the path returned by this function is NOT safe to use. /// /// OS-specific optimizations: /// - On Linux, this will try `readlink("/proc/self/fd/$fd")`. /// - On macOS, this will try `fcntl(fd, F_GETPATH)`. /// /// If either of these techniques fails (or on other platforms), it will fall back on a more /// reliable (but slower) strategy. /// /// Some notes: /// - If the directory has been deleted, this function will fail with `ENOENT` (this is /// guaranteed, though beware of race conditions). /// - This function may or may not fail with `EACCES` if the currrent process does not have /// access to one or more of this directory's parent directories. pub fn recover_path(&self) -> io::Result<PathBuf> { #[cfg(any(target_os = "linux", target_os = "android"))] if let Ok(path) = std::fs::read_link(format!("/proc/self/fd/{}", self.fd)) { let path_bytes = path.as_os_str().as_bytes(); if path_bytes.starts_with(b"/") && !path_bytes.ends_with(b" (deleted)") { return Ok(path); } } let self_meta = self.self_metadata()?; #[cfg(target_os = "macos")] { use std::ffi::CStr; let mut buf = [0u8; libc::PATH_MAX as usize]; if unsafe { libc::fcntl(self.fd, libc::F_GETPATH, buf.as_mut_ptr()) } == 0 { let index = buf.iter().position(|&c| c == 0).unwrap(); let c_path = unsafe { CStr::from_bytes_with_nul_unchecked(&buf[..index + 1]) }; // F_GETPATH will return the old path if the directory is deleted, so let's make // sure it exists (and while we're at it, let's check that it's the same file using // samestat()). if let Ok(path_stat) = util::fstatat(libc::AT_FDCWD, c_path, 0) { if util::samestat(&self_meta.stat(), &path_stat) { return Ok(PathBuf::from(OsStr::from_bytes(&buf[..index]))); } } } } #[inline] fn recover_entry(parent: &Dir, sub_meta: &Metadata) -> io::Result<Entry> { for entry in parent.list_self()? { let entry = entry?; // Only check directories (or files with unknown types) match entry.file_type() { Some(FileType::Directory) | None => { // stat() the entry and see if it matches. // // We can't check entry.ino() to avoid stat() because that doesn't work // when you cross filesystem boundaries. if let Ok(entry_meta) = entry.metadata() { if same_meta(sub_meta, &entry_meta) { return Ok(entry); } } } _ => (), } } Err(io::Error::from_raw_os_error(libc::ENOENT)) } let mut res = VecDeque::new(); let mut sub_meta = self_meta; let mut parent = self.parent_unchecked()?; loop { let parent_meta = parent.self_metadata()?; if same_meta(&sub_meta, &parent_meta) { // Rewinding with ".." didn't move us; we must have hit the root if res.is_empty() { res.push_front(b'/'); } return Ok(PathBuf::from(OsString::from_vec(res.into()))); } let entry = recover_entry(&parent, &sub_meta)?; let entry_name = entry.name(); res.reserve(entry_name.len() + 1); for ch in entry_name.as_bytes().iter().rev().copied() { res.push_front(ch); } res.push_front(b'/'); parent = parent.parent_unchecked()?; sub_meta = parent_meta; } } /// Set this process's current working directory to this directory. /// /// This is roughly equivalent to `std::env::set_current_dir(self.recover_path()?)`, but 1) it /// is **much** more efficient, and 2) it is more secure (notably, it avoids race conditions). #[inline] pub fn change_cwd_to(&self) -> io::Result<()> { if unsafe { libc::fchdir(self.fd) } < 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } /// Return an `OpenOptions` struct that can be use to open files within this directory. /// /// See the documentation of [`OpenOptions`] for more details. /// /// [`OpenOptions`]: ./struct.OpenOptions.html #[inline] pub fn open_file(&self) -> OpenOptions { OpenOptions::beneath(self) } } impl Drop for Dir { #[inline] fn drop(&mut self) { unsafe { libc::close(self.fd); } } } impl AsRawFd for Dir { #[inline] fn as_raw_fd(&self) -> RawFd { self.fd } } impl IntoRawFd for Dir { #[inline] fn into_raw_fd(self) -> RawFd { let fd = self.fd; std::mem::forget(self); fd } } impl FromRawFd for Dir { #[inline] unsafe fn from_raw_fd(fd: RawFd) -> Self { Self { fd } } } /// Create a hardlink to a file in (possibly) a different directory. pub fn hardlink<P, R>( old_dir: &Dir, old_path: P, new_dir: &Dir, new_path: R, lookup_flags: LookupFlags, ) -> io::Result<()> where P: AsPath, R: AsPath, { let (old_subdir, old_fname) = prepare_inner_operation(old_dir, old_path.as_path(), lookup_flags)?; let old_fname = if let Some(old_fname) = old_fname { old_fname } else { // Assume we can't create hardlinks to directories (it seems that macOS *can*, but it's // hacky) return Err(std::io::Error::from_raw_os_error(libc::EPERM)); }; let (new_subdir, new_fname) = prepare_inner_operation(new_dir, new_path.as_path(), lookup_flags)?; let old_subdir = old_subdir.as_ref().unwrap_or(old_dir); let new_subdir = new_subdir.as_ref().unwrap_or(new_dir); if let Some(new_fname) = new_fname { old_fname.with_cstr(|old_fname| { new_fname.with_cstr(|new_fname| { util::linkat( old_subdir.as_raw_fd(), old_fname, new_subdir.as_raw_fd(), new_fname, 0, ) }) }) } else { // The "new" path cannot exist already Err(std::io::Error::from_raw_os_error(libc::EEXIST)) } } /// Rename a file across directories. pub fn rename<P, R>( old_dir: &Dir, old_path: P, new_dir: &Dir, new_path: R, lookup_flags: LookupFlags, ) -> io::Result<()> where P: AsPath, R: AsPath, { let (old_subdir, old_fname) = prepare_inner_operation(old_dir, old_path.as_path(), lookup_flags)?; let old_subdir = old_subdir.as_ref().unwrap_or(old_dir); let old_fname = if let Some(old_fname) = old_fname { old_fname } else { return Err(std::io::Error::from_raw_os_error(libc::EBUSY)); }; let (new_subdir, new_fname) = prepare_inner_operation(new_dir, new_path.as_path(), lookup_flags)?; let new_subdir = new_subdir.as_ref().unwrap_or(new_dir); if let Some(new_fname) = new_fname { old_fname.with_cstr(|old_fname| { new_fname.with_cstr(|new_fname| { util::renameat( old_subdir.as_raw_fd(), old_fname, new_subdir.as_raw_fd(), new_fname, ) }) }) } else { Err(std::io::Error::from_raw_os_error(libc::EBUSY)) } } /// Linux-specific: Rename a file across directories, specifying extra flags to modify behavior. /// /// This calls the `renameat2()` syscall, which was added in Linux 3.15. It will fail with `ENOSYS` /// on older kernels, and it will fail with `EINVAL` if any of the given `flags` are not supported /// by the filesystem. See renameat2(2) for more details. /// /// Otherwise, the semantics of this are identical to [`rename()`]. /// /// [`rename()`]: ./fn.rename.html #[cfg(target_os = "linux")] pub fn rename2<P, R>( old_dir: &Dir, old_path: P, new_dir: &Dir, new_path: R, flags: Rename2Flags, lookup_flags: LookupFlags, ) -> io::Result<()> where P: AsPath, R: AsPath, { let (old_subdir, old_fname) = prepare_inner_operation(old_dir, old_path.as_path(), lookup_flags)?; let old_subdir = old_subdir.as_ref().unwrap_or(old_dir); let old_fname = if let Some(old_fname) = old_fname { old_fname } else { return Err(std::io::Error::from_raw_os_error(libc::EBUSY)); }; let (new_subdir, new_fname) = prepare_inner_operation(new_dir, new_path.as_path(), lookup_flags)?; let new_subdir = new_subdir.as_ref().unwrap_or(new_dir); if let Some(new_fname) = new_fname { old_fname.with_cstr(|old_fname| { new_fname.with_cstr(|new_fname| { util::renameat2( old_subdir.as_raw_fd(), old_fname, new_subdir.as_raw_fd(), new_fname, flags.bits, ) }) }) } else { Err(std::io::Error::from_raw_os_error(libc::EBUSY)) } } #[inline] fn same_meta(a: &Metadata, b: &Metadata) -> bool { util::samestat(a.stat(), b.stat()) } fn prepare_inner_operation<'a>( dir: &Dir, mut path: &'a Path, lookup_flags: LookupFlags, ) -> io::Result<(Option<Dir>, Option<&'a OsStr>)> { match path.strip_prefix("/") { Ok(p) => { // If we didn't get the IN_ROOT flag, then a path starting with "/" is disallowed. if !lookup_flags.contains(LookupFlags::IN_ROOT) { return Err(io::Error::from_raw_os_error(libc::EXDEV)); } // Trim the "/" prefix path = p; // Make sure there are no leading slashes debug_assert_ne!(path.as_os_str().as_bytes().first(), Some(&b'/')); if path.as_os_str().is_empty() { // Just "/" return Ok((None, None)); } } // Not an absolute path Err(_) => { if path.as_os_str().is_empty() { // Empty path -> ENOENT return Err(io::Error::from_raw_os_error(libc::ENOENT)); } } } debug_assert!(!path.as_os_str().as_bytes().is_empty()); debug_assert!(!path.as_os_str().as_bytes().starts_with(b"/")); if let Some((parent, fname)) = util::path_split(path) { debug_assert!(!path.ends_with("..")); debug_assert!(!fname.as_bytes().contains(&b'/')); Ok(( if let Some(parent) = parent { Some(dir.sub_dir(parent, lookup_flags)?) } else { None }, if fname.as_bytes() == b"." { None } else { Some(fname) }, )) } else { debug_assert!(path.ends_with("..")); // So this is a path like "a/b/..". We can't really get a (containing directory, filename) // pair out of this. Ok((Some(dir.sub_dir(path, lookup_flags)?), None)) } } #[cfg(test)] mod tests { use super::*; fn same_dir(a: &Dir, b: &Dir) -> io::Result<bool> { Ok(same_meta(&a.self_metadata()?, &b.self_metadata()?)) } #[test] fn test_prepare_inner_operation() { let tmpdir = tempfile::tempdir().unwrap(); let tmpdir_path = tmpdir.as_ref(); let tmpdir = Dir::open(tmpdir_path).unwrap(); tmpdir.create_dir("a", 0o777, LookupFlags::empty()).unwrap(); tmpdir .create_dir("a/b", 0o777, LookupFlags::empty()) .unwrap(); for (path, lookup_flags, expect_dname, expect_fname) in [ ("/", LookupFlags::IN_ROOT, None, None), (".", LookupFlags::empty(), None, None), ("a", LookupFlags::empty(), None, Some("a")), ("a/", LookupFlags::empty(), None, Some("a")), ("a/.", LookupFlags::empty(), Some("a"), None), ("a/b", LookupFlags::empty(), Some("a"), Some("b")), ("a/b/.", LookupFlags::empty(), Some("a/b"), None), ("a/b/c", LookupFlags::empty(), Some("a/b"), Some("c")), ("a/b/c/", LookupFlags::empty(), Some("a/b"), Some("c")), ("a/..", LookupFlags::empty(), Some("."), None), ("/..", LookupFlags::IN_ROOT, Some("."), None), ] .iter() { let (subdir, fname) = prepare_inner_operation(&tmpdir, Path::new(path), *lookup_flags).unwrap(); if let Some(expect_dname) = expect_dname { assert!(same_dir( &tmpdir.sub_dir(*expect_dname, LookupFlags::empty()).unwrap(), subdir.as_ref().unwrap() ) .unwrap()); } else { assert!(subdir.is_none()); } assert_eq!(expect_fname.map(OsStr::new), fname); } for (path, lookup_flags, eno) in [ ("/", LookupFlags::empty(), libc::EXDEV), ("..", LookupFlags::empty(), libc::EXDEV), ("a/../..", LookupFlags::empty(), libc::EXDEV), ("", LookupFlags::empty(), libc::ENOENT), ] .iter() { assert_eq!( prepare_inner_operation(&tmpdir, Path::new(path), *lookup_flags) .unwrap_err() .raw_os_error(), Some(*eno) ); } } #[test] fn test_metadata() { for path in [PathBuf::from("."), PathBuf::from("/"), std::env::temp_dir()].iter() { let dir = Dir::open(path).unwrap(); let meta1 = dir.self_metadata().unwrap(); let meta2 = dir.metadata(".", LookupFlags::empty()).unwrap(); assert!(util::samestat(meta1.stat(), meta2.stat())); let meta3 = dir.metadata("/", LookupFlags::IN_ROOT).unwrap(); assert!(util::samestat(meta1.stat(), meta3.stat())); let meta4 = dir.metadata("..", LookupFlags::IN_ROOT).unwrap(); assert!(util::samestat(meta1.stat(), meta4.stat())); } } #[test] fn test_try_clone() { for path in [".", "/"].iter() { let dir = Dir::open(*path).unwrap(); assert!(same_dir(&dir, &dir.try_clone().unwrap()).unwrap()); } } }
package Catmandu::Bag::IdGenerator::Incremental; use Catmandu::Sane; use Moo; with 'Catmandu::Bag::IdGenerator'; sub generate { my ($self, $bag) = @_; my $id; $bag->store->transaction( sub { my $info_bag = $bag->store->bag('info'); my $info_key = $bag->name . '_id'; my $rec = $info_bag->get_or_add($info_key, {latest => '0'}); $id = ++$rec->{latest}; $rec->{latest} = "$rec->{latest}"; $info_bag->add($rec); $info_bag->commit; } ); "$id"; } 1;
class Flight < ApplicationRecord belongs_to :user belongs_to :airline validates_presence_of :departure, :return, :cost, :origin_city, :destination_city validates :number, length: { minimum: 6 } end
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wall -fno-warn-tabs #-} import Control.Monad import Data.Maybe import Data.List import Data.Bits import Data.Word import Data.Char import Data.ByteString (ByteString) import System.IO import System.Environment import System.Exit import System.Posix.User import System.Posix.Files import Crypto.Hash import qualified Data.ByteArray as BA import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC main :: IO () main = do hPutStrLn stderr "HELOO HELLO BOOOOOOOOOOOOOOOOO" getEnv "auth_sqlite_db" >>= hPutStrLn stderr fp : _as <- getArgs fs <- getFileStatus fp hPutStrLn stderr fp hPutStrLn stderr . show $ fileMode fs hPutStrLn stderr . show =<< getUserEntryForID (fileOwner fs) h <- openFile fp ReadMode un <- BSC.hGetLine h p <- BSC.hGetLine h when (un /= "yosh") exitFailure -- u <- (<> "\n") . BSC.pack <$> getEffectiveUserName h0 <- hello let h1 = BA.convert $ sha512 p when (h1 /= h0) $ do writeFile "/home/tatsuya/openvpn_auth.log" $ show h0 <> "\n" <> show h1 <> "\n" exitFailure BS.writeFile "/home/tatsuya/openvpn_auth.log" $ un <> "\n" <> p <> "\n" sha512 :: ByteString -> Digest SHA512 sha512 = hash hexDigits :: [Char] hexDigits = "0123456789abcdef" hexToNum1 :: Char -> Word8 hexToNum1 = fromIntegral . fromJust . (`elemIndex` hexDigits) readHex :: Char -> Char -> Word8 readHex a b = (hexToNum1 a `shift` 4) .|. hexToNum1 b readHash :: String -> ByteString readHash = BS.pack . rh where rh (a : b : cs) = readHex a b : rh cs rh "" = [] rh _ = error "bad" hello :: IO ByteString hello = (readHash . takeWhile (not . isSpace) <$>) $ do h <- openFile "/etc/openvpn/password-file.txt" ReadMode fp <- hGetLine h readFile fp
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import RSVP from 'rsvp'; import sinon from 'sinon'; import { waitUntil } from '@ember/test-helpers'; import { A } from '@ember/array'; import onTransitionEnd from 'ember-transition-end/utils/on-transition-end'; import { run } from '@ember/runloop'; import { click, render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import ModalModel from 'ember-modal-service/models/modal'; import SchedulerService from 'ember-task-scheduler/services/scheduler'; import ModalComponent from 'ember-modal-service/components/modal'; const { spy } = sinon; const ANIMATION_DELAY = 300; let component, service, content, didOpenSpy, model; function waitForTransitionEnd(element) { return new RSVP.Promise((resolve) => { onTransitionEnd(element, resolve); }); } function waitForTimeout(timeout) { return new RSVP.Promise((resolve) => { setTimeout(resolve, timeout); }); } function waitForScheduler() { return waitUntil(() => !service.hasPendingTasks() && !run.hasScheduledTimers(), { timeout: 2000 }); } function isVisible(element) { return element.getAttribute('data-modal-show') === 'true'; } function getComponent(owner, element) { const instances = owner.__container__.lookup('-view-registry:main'); return instances[element.id]; } module('Integration | Component | modal', (hooks) => { setupRenderingTest(hooks); hooks.beforeEach(async function() { this.owner.register('service:scheduler', SchedulerService); this.owner.register('model:modal', ModalModel); content = A(); didOpenSpy = spy(); model = ModalModel.create({ name: 'foo' }); const layout = hbs` <button data-id="resolve" {{on 'click' (action 'resolve' 'foo')}}>Resolve</button> <button data-id="reject" {{on 'click' (action 'reject' 'foo')}}>Reject</button> `; class MyComponent extends ModalComponent { layout = layout; target = null; model = model; didOpen = didOpenSpy; } this.owner.register('component:my-modal', MyComponent); service = this.owner.lookup('service:scheduler'); }); test('it defines the appropriate `data-id` on the component wrapper', async(assert) => { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); assert.ok(component); }); test('it binds visible class from component', async function(assert) { await render(hbs `<MyModal @visible={{this.visible}}/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); this.set('visible', false); assert.notOk(isVisible(component)); this.set('visible', true); assert.ok(isVisible(component)); }); test('it hides and removes modal when promise is resolved', async(assert) => { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); assert.ok(isVisible(component)); run(() => { model.resolve(); }); assert.notOk(isVisible(component)); assert.equal(content.length, 0); }); test('it hides and removes modal when promise is rejected', async(assert) => { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); assert.ok(isVisible(component)); run(() => { model.reject(); }); assert.notOk(isVisible(component)); assert.equal(content.length, 0); }); test('it sends didOpen when it is rendered', async(assert) => { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); assert.ok(didOpenSpy.calledOnce); }); test('it sends didOpen when it is rendered and has transitions', async(assert) => { await render(hbs `<MyModal class="animated"/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); assert.ok(didOpenSpy.notCalled); await waitForTimeout(ANIMATION_DELAY); assert.ok(didOpenSpy.calledOnce); }); test('it does not sends didOpen when it is destroyed', async function(assert) { await render(hbs ` {{#unless destroy}} <MyModal class="animated"/> {{/unless}} `); component = document.querySelector('[data-id="modalFoo"]'); await waitForTransitionEnd(component); this.set('destroy', true); await waitForScheduler(); assert.ok(didOpenSpy.notCalled); }); test('it waits for transitions before being removed', async(assert) => { await render(hbs `<MyModal class="animated"/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); run(() => { model.resolve(); }); assert.notOk(isVisible(component)); await waitForTimeout(ANIMATION_DELAY); assert.equal(content.length, 0); }); test('it resolves promise with arguments', async function(assert) { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); const instance = getComponent(this.owner, component); await waitForScheduler(); instance.resolve('foo'); assert.equal(await model.promise, 'foo'); }); test('it rejects promise with arguments', async function(assert) { assert.expect(1); await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); const instance = getComponent(this.owner, component); await waitForScheduler(); model.promise.catch((foo) => { assert.equal(foo, 'foo'); }); instance.reject('foo'); }); test('it resolves promise with action', async(assert) => { await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); await click('[data-id="resolve"]'); assert.equal(await model.promise, 'foo'); }); test('it rejects promise with action', async(assert) => { assert.expect(1); await render(hbs `<MyModal/>`); component = document.querySelector('[data-id="modalFoo"]'); await waitForScheduler(); model.promise.catch((foo) => { assert.equal(foo, 'foo'); }); await click('[data-id="reject"]'); }); });
import axios from 'axios'; import api from '../apiHost'; import token from '../auth/token'; const url = `${api}/admin/store`; const getStoreCandidate = async () => { const response = await axios.get(`${url}/candidate`, token); return response.data; } const acceptStore = async (id) => { const response = await axios.post(`${url}/${id}/accept`, null, token); return response.data; } const denyStore = async (id) => { const response = await axios.post(`${url}/${id}/deny`, null, token); return response.data; } export default { getStoreCandidate, acceptStore, denyStore };
package JSON::Schema::Validator::Context; use strict; use warnings; use utf8; use JSON::Schema::Validator::ValidationError; use Class::Accessor::Lite ( ro => [qw(root_validator root_schema errors positions)], ); sub new { my ($class, $validator, $schema) = @_; return bless { root_validator => $validator, root_schema => $schema, errors => [], positions => [], }, $class; } sub rv { $_[0]->root_validator } sub rs { $_[0]->root_schema } sub prims { $_[0]->root_validator->prims } # TODO refactor sub push_error { my ($self, $error) = @_; push @{$self->errors}, $error; } sub push_pos { my ($self, $pos) = @_; push @{$self->positions}, $pos; } sub pop_pos { my ($self) = @_; pop @{$self->positions}; } sub is_root { my ($self) = @_; return scalar @{$self->positions} == 0 ? 1 : 0; } sub position { my ($self) = @_; return '/' . join '/', @{$self->positions}; } sub generate_error { my ($self, $attr) = @_; return JSON::Schema::Validator::ValidationError->new($attr, $self->position); } sub in_attr ($&) { my ($self, $attr, $code) = @_; $self->push_pos($attr->attr_name); my $is_valid = $code->(); my @res = $is_valid ? (1, undef) : (0, $self->generate_error($attr)); $self->pop_pos(); return @res; } sub in ($&) { my ($self, $pos, $code) = @_; $self->push_pos($pos); my $res = $code->(); $self->pop_pos(); return $res; } sub sub_validator { my ($self, $sub_schema) = @_; require JSON::Schema::Validator; return JSON::Schema::Validator->new( $sub_schema, $self->rv->options, # inherit options ); } 1;
using System.Collections; using System.Collections.Generic; using UnityEngine; //This script creates a continious background effect by replacing two identical background images interchangeably. public class RepeatingBackground : MonoBehaviour { private float groundLength; void Awake() { groundLength = 26; } void Update() { if(transform.position.x < -groundLength) { RepositionBackground(); } } private void RepositionBackground() { Vector2 groundOffset = new Vector2(groundLength * 2f, 0); transform.position = (Vector2) transform.position + groundOffset; } }
#include <QApplication> #include <QQmlApplicationEngine> #include <qqml.h> #include "ffmpegplayer.h" FFMPEGLogger* FFMPEGLogger::_instance = nullptr; int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<FFMPEGPlayer>("qmlffmpeg", 1, 0, "FFMPEGPlayer"); qmlRegisterSingletonType<FFMPEGLogger>("qmlffmpeg", 1, 0, "FFMPEGLogger", FFMPEGLogger::provider); qRegisterMetaType<FFMPEGLogger::Level>("Level"); qRegisterMetaType<FFMPEGParams>("FFMPEGParams"); engine.load(QUrl(QStringLiteral("qrc:/qmlffmpeg.qml"))); return app.exec(); }
#-- encoding: UTF-8 ActiveRecord::Base.send :include, ActiveRecord::Acts::Tree
import React from 'react' import { shallow } from 'enzyme' import toJson from 'enzyme-to-json' import AppContainer from '../AppContainer' describe('(Containers) AppContainer', () => { it('Should render component properly', () => { const props = { checkToken: jest.fn(), store: { getState: jest.fn(), }, history: { getState: jest.fn(), }, routes: { onChange: jest.fn(), }, checkToken: jest.fn(), } const wrapper = shallow( <AppContainer {...props} />) wrapper.instance().shouldComponentUpdate() }) })
/* canvas test ** 20160119 ** yiru */ var draw={ cancelIndex:0, cancelList:[], sel:'size', getCanvas:function(){ return document.getElementById('canvas'); }, init:function(img){ var toolbar=document.getElementsByClassName('c-toolbar')[0]; toolbar.addEventListener('click',draw.tools,false); var canvas:any=draw.getCanvas(); var cw=canvas.parentNode.offsetWidth; var ch=canvas.parentNode.offsetHeight; canvas.width=cw; canvas.height=ch; // load image draw.loadImg(img,cw,ch); //鼠标 canvas.addEventListener('mousedown',draw.onMouseDown,false); // canvas.addEventListener('mousemove',onMouseMove,false); // canvas.addEventListener('mouseup',onMouseUp,false); //触摸 canvas.addEventListener('touchstart',draw.onMouseDown,false); // canvas.addEventListener('touchmove',onMouseMove,false); // canvas.addEventListener('touchend',onMouseUp,false); }, tools:function(e){ var e=e||window.event; var ele=e.target||e.srcElement; var txt=ele.innerHTML; console.log(txt); draw.sel=txt; var canvas:any=draw.getCanvas(); var cw=canvas.parentNode.offsetWidth; var ch=canvas.parentNode.offsetHeight; var ctx=canvas.getContext('2d'); switch(txt){ case 'color': draw.sel='size'; break; case 'size': console.log(txt); break; case 'erase': console.log(txt); break; case 'note': console.log(txt); break; case 'text': console.log(txt); break; case 'clean': draw.sel='size'; ctx.clearRect(0,0,cw,ch); break; case '撤销': draw.sel='size'; if(draw.cancelList.length-1<draw.cancelIndex) return false; draw.pre(); break; case '重做': draw.sel='size'; if(draw.cancelIndex<=0) return false; draw.next(); break; case '保存': draw.sel='size'; draw.downloadImg(); break; default:; } }, onMouseDown:function(e){ var canvas:any=draw.getCanvas(); var ctx=canvas.getContext('2d'); ctx.beginPath(); var p=draw.pos(e); ctx.moveTo(p.x,p.y); canvas.addEventListener('mousemove',draw.onMouseMove,false); canvas.addEventListener('touchmove',draw.onMouseMove,false); document.addEventListener('mouseup',draw.onMouseUp,false); document.addEventListener('touchend',draw.onMouseUp,false); }, onMouseMove:function(e){ var e=e||window.event; // var ele=e.target||e.srcElement; e.preventDefault(); var canvas:any=draw.getCanvas(); var ctx=canvas.getContext('2d'); var size=1,color='red'; if(draw.sel=='size'){ ctx.lineWidth=size; ctx.strokeStyle=color; var p=draw.pos(e); ctx.lineTo(p.x,p.y); // ctx.shadowColor=color; // ctx.shadowBlur=1; ctx.stroke(); } else if(draw.sel=='eraser'){ //ctx.beginPath(); ctx.lineWidth=1; ctx.strokeStyle='#fff'; var p=draw.pos(e); ctx.clearRect(p.x-size*10,p.y-size*10,size*20,size*20); } }, onMouseUp:function(e){ var e=e||window.event; // var ele=e.target||e.srcElement; var canvas:any=draw.getCanvas(); var ctx=canvas.getContext('2d'); if(draw.sel=='text'){ /*$('#note').show(); var tArea=$('#txtArea'); tArea.val(''); tArea.focus(); tArea.off('blur').on('blur',function(){ var txt=$(this).val(); ctx.font='12px 微软雅黑'; ctx.fillStyle='red'; var p=getP; ctx.fillText(txt,p.x,p.y); $('#note').hide(); draw.sel='size'; })*/ }; canvas.removeEventListener('mousemove',draw.onMouseMove,false); canvas.removeEventListener('touchmove',draw.onMouseMove,false); document.removeEventListener('mouseup',draw.onMouseUp,false); document.removeEventListener('touchend',draw.onMouseUp,false); draw.saveData(); }, pos:function(e){ var canvas:any=draw.getCanvas().parentNode; var x,y; if(draw.isTouch(e)){ x=e.touches[0].pageX-canvas.offsetLeft; y=e.touches[0].pageY-canvas.offsetTop; } else{ // console.log(canvas.offsetLeft); // console.log(canvas.offsetParent); // console.log(canvas.getBoundingClientRect().left); x=e.pageX-canvas.getBoundingClientRect().left; y=e.pageY-canvas.getBoundingClientRect().top; } return {x:x,y:y}; }, isTouch:function(e){ var type=e.type; if(type.indexOf('touch')>=0) return true; else return false; }, getWidth:function(){ var xWidth=null; if(window.innerWidth!==null){ xWidth=window.innerWidth; } else{ xWidth=document.body.clientWidth; } return xWidth; }, saveData:function(){ var canvas:any=draw.getCanvas(); draw.cancelIndex=0; var dataUrl=canvas.toDataURL(); draw.cancelList.push(dataUrl); // return draw.temp().cancelList; }, /*startDraw:function(){ var canvas=draw.getCanvas(); var ctx=canvas.getContext('2d'); var size=1,color='red'; ctx.lineWidth=size; ctx.strokeStyle=color; var p=draw.pos(e); ctx.lineTo(p.x,p.y); // ctx.shadowColor=color; // ctx.shadowBlur=1; }, eraser:function(){ var canvas=draw.getCanvas(); var ctx=canvas.getContext('2d'); var size=1,color='red'; //ctx.beginPath(); ctx.lineWidth=1; ctx.strokeStyle='#fff'; var p=draw.pos(e); ctx.clearRect(p.x-size*10,p.y-size*10,size*20,size*20); },*/ pre:function(){ var canvas:any=draw.getCanvas(); var ctx=canvas.getContext('2d'); var cw=canvas.parentNode.offsetWidth; var ch=canvas.parentNode.offsetHeight; draw.cancelIndex++; ctx.clearRect(0,0,cw,ch); var cImage=new Image(); var index=draw.cancelList.length-1-draw.cancelIndex; if(index>=0){ cImage.src=draw.cancelList[index]; cImage.onload=function(){ ctx.drawImage(cImage,0,0,cImage.width,cImage.height,0,0,cw,ch); } } }, next:function(){ var canvas:any=draw.getCanvas(); var ctx=canvas.getContext('2d'); var cw=canvas.parentNode.offsetWidth; var ch=canvas.parentNode.offsetHeight; draw.cancelIndex--; ctx.clearRect(0,0,cw,ch); var cImage=new Image(); var index=draw.cancelList.length-1-draw.cancelIndex; cImage.src=draw.cancelList[index]; cImage.onload=function(){ ctx.drawImage(cImage,0,0,cImage.width,cImage.height,0,0,cw,ch); } }, loadImg:function(url,cw,ch){ var canvasImg:any=document.getElementById('imgCanvas'); var ctxImg=canvasImg.getContext('2d'); canvasImg.width=cw; canvasImg.height=ch; var img=new Image(); img.src=url; img.onload=function(){ ctxImg.drawImage(img,0,0,cw,ch); } }, downloadImg:function(){ console.log(draw.cancelList); document.location.href=draw.cancelList[draw.cancelList.length-1]; }, // distroy event distroy:()=>{ var toolbar=document.getElementsByClassName('c-toolbar')[0]; var canvas=draw.getCanvas(); toolbar.removeEventListener('click',draw.tools,false); canvas.removeEventListener('mousedown',draw.onMouseDown,false); canvas.removeEventListener('touchstart',draw.onMouseDown,false); canvas.removeEventListener('mousemove',draw.onMouseMove,false); canvas.removeEventListener('touchmove',draw.onMouseMove,false); document.removeEventListener('mouseup',draw.onMouseUp,false); document.removeEventListener('touchend',draw.onMouseUp,false); } } ; export default draw;
package cieslak.matty.worklog.activity import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.DatePicker import android.widget.TextView import android.widget.TimePicker import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import cieslak.matty.worklog.R import cieslak.matty.worklog.helper.DatabaseHandler import cieslak.matty.worklog.model.StartEndEnum import cieslak.matty.worklog.model.WorkdayEntry import java.time.Duration import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* class LogWorkActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { var minute: Int = 0 var hour: Int = 0 var day: Int = 0 var month: Int = 0 var year: Int = 0 var canBeSaved = false private var currentBtn = StartEndEnum.START private var startDateTime = LocalDateTime.MIN private var endDateTime = LocalDateTime.MIN private val readableFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_log_work) //disable save button val saveButton: Button = findViewById(R.id.save_work_entry_btn) saveButton.isClickable = false } fun selectDateTime(v: View) { when (v.id) { R.id.start_date_btn -> { currentBtn = StartEndEnum.START showDatePicker() } R.id.end_date_btn -> { currentBtn = StartEndEnum.END showDatePicker() } } } private fun showDatePicker() { val calendar: Calendar = Calendar.getInstance() val timePickerDialog = TimePickerDialog( this@LogWorkActivity, this@LogWorkActivity, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), true ) timePickerDialog.show() } override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) { this.minute = minute this.hour = hourOfDay val calendar: Calendar = Calendar.getInstance() val datePickerDialog = DatePickerDialog( this@LogWorkActivity, this@LogWorkActivity, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) datePickerDialog.show() } override fun onDateSet(view: DatePicker?, year: Int, month: Int, day: Int) { this.day = day this.month = month this.year = year when (currentBtn) { StartEndEnum.START -> { startDateTime = LocalDateTime.of(year, month, day, hour, minute) val textView: TextView = findViewById(R.id.start_date_lbl) textView.text = startDateTime.format(readableFormatter).toString() } StartEndEnum.END -> { endDateTime = LocalDateTime.of(year, month, day, hour, minute) val textView: TextView = findViewById(R.id.end_date_lbl) textView.text = endDateTime.format(readableFormatter).toString() } } if (startDateTime != LocalDateTime.MIN && endDateTime != LocalDateTime.MIN) { val textView: TextView = findViewById(R.id.time_worked_lbl) if (endDateTime.isAfter(startDateTime)) { val difference = Duration.between(startDateTime, endDateTime) // get minutes and hours val mins = difference.toMinutes() - (difference.toHours() * 60) val hrs = difference.toHours() val diffHours = if (hrs < 10) "0$hrs" else hrs val diffMinutes = if (mins < 10) "0$mins" else mins textView.text = String.format("Worked for %s:%s", diffHours, diffMinutes) //enable save button val saveButton: Button = findViewById(R.id.save_work_entry_btn) saveButton.isClickable = true saveButton.setBackgroundColor(resources.getColor(R.color.green_500, null)) } else { textView.text = getString(R.string.start_before_end_txt) //disable save button val saveButton: Button = findViewById(R.id.save_work_entry_btn) saveButton.setBackgroundColor(resources.getColor(R.color.grey_700, null)) saveButton.isClickable = false } } } fun clickedCancel(view: View) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } fun saveNewLogEntry(view: View) { val databaseHandler = DatabaseHandler(this) databaseHandler.addEntry(WorkdayEntry(startDateTime, endDateTime)) Toast.makeText(this, "Saved new entry", Toast.LENGTH_SHORT).show() val intent = Intent(this, MainActivity::class.java) startActivity(intent) } }
# Copyright (C) 2016-2018 Virgil Security Inc. # # Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> # # 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. # # (3) Neither the name of the copyright holder 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 AUTHOR ''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 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. from virgil_crypto.keys import VirgilPrivateKey, VirgilPublicKey from virgil_crypto import VirgilCrypto class AccessTokenSigner(object): """Access Token cryptographic signature operations Class provides a cryptographic signature operations for Access Token. """ def __init__(self, crypto=VirgilCrypto()): self.__algorithm = "VEDS512" self.__crypto = crypto def generate_token_signature(self, token, private_key): # type: (Union[bytes, bytearray], VirgilPrivateKey) -> bytearray """Generate signature for Access token Args: token: Access Token bytes. private_key: Signer Private Key. Returns: Signature bytes. Raises: ValueError: if token or private key missing or malformed """ if not private_key: raise ValueError("Missing private key") if not token: raise ValueError("Missing token for sign") if not isinstance(private_key, VirgilPrivateKey): raise ValueError("private_key must be a VirgilPrivateKey type") return self.__crypto.generate_signature(token, private_key) def verify_token_signature(self, signature, token, public_key): # type: (Union[bytes, bytearray], Union[bytes, bytearray], VirgilPublicKey) -> bool """Verify Access Token signature Args: signature: Token signature bytes token: Access Token public_key: Signer Public Key Returns: True if signature is valid, False otherwise. Raises: ValueError: if public key or token missed or malformed. """ if not isinstance(public_key, VirgilPublicKey): raise ValueError("public_key must be a VirgilPublicKey type") if not token: raise ValueError("Missing token to verify") return self.__crypto.verify_signature( token, signature, public_key ) @property def algorithm(self): """Get Algorithm""" return self.__algorithm @property def crypto(self): """Get Crypto""" return self.__crypto
package com.github.littlelightmc.essential.base import com.github.littlelightmc.essential.defaultLocale import pro.darc.cake.core.inject.LifeCycle import pro.darc.cake.core.inject.LifeInject import pro.darc.cake.module.command.command import pro.darc.cake.module.extensions.cake object Essential { @LifeInject([LifeCycle.CakeEnable, LifeCycle.CakeReload]) @JvmStatic fun init() { command("essential", plugin = cake) { command("version") { executor { defaultLocale.sendTo(sender, "info addon version") } } } } }
import React, { Component, Fragment } from "react"; import PropTypes from "prop-types"; import Grid from "@material-ui/core/Grid"; import { withStyles } from "@material-ui/core/styles"; import CatalogGrid from "@reactioncommerce/components/CatalogGrid/v1"; import PageLoading from "components/PageLoading"; import PageStepper from "components/PageStepper"; import PageSizeSelector from "components/PageSizeSelector"; import SortBySelector from "components/SortBySelector"; import ProductGridEmptyMessage from "./ProductGridEmptyMessage"; const styles = (theme) => ({ filters: { justifyContent: "flex-end", marginBottom: theme.spacing(2) } }); class ProductGrid extends Component { static propTypes = { catalogItems: PropTypes.arrayOf(PropTypes.object), classes: PropTypes.object, currencyCode: PropTypes.string.isRequired, isLoadingCatalogItems: PropTypes.bool, pageInfo: PropTypes.shape({ startCursor: PropTypes.string, endCursor: PropTypes.string, hasNextPage: PropTypes.bool, hasPreviousPage: PropTypes.bool, loadNextPage: PropTypes.func, loadPreviousPage: PropTypes.func }), pageSize: PropTypes.number.isRequired, setPageSize: PropTypes.func.isRequired, setSortBy: PropTypes.func.isRequired, sortBy: PropTypes.string.isRequired }; // renderFilters() { // const { classes, pageSize, setPageSize, setSortBy, sortBy } = this.props; // return ( // <Grid container spacing={1} className={classes.filters}> // <Grid item> // <PageSizeSelector pageSize={pageSize} onChange={setPageSize} /> // </Grid> // <Grid item> // <SortBySelector sortBy={sortBy} onChange={setSortBy} /> // </Grid> // </Grid> // ); // } renderMainArea() { const { catalogItems, isLoadingCatalogItems, pageInfo } = this.props; if (isLoadingCatalogItems) return <PageLoading />; const products = (catalogItems || []).map((item) => item.node.product); if (products.length === 0) return <ProductGridEmptyMessage />; return ( <Fragment> <Grid container spacing={3}> <CatalogGrid products={products} placeholderImageURL="/images/placeholder.gif" {...this.props} /> </Grid> {pageInfo && <PageStepper pageInfo={pageInfo} />} </Fragment> ); } render() { return ( <Fragment> {this.renderFilters()} {this.renderMainArea()} </Fragment> ); } } export default withStyles(styles)(ProductGrid);
import { Failure } from '../definitions/Failure' export interface Entity { /** * Validate the entity so that it has correct values * @return all errors, or empty list if the entity is valid */ validate(): Failure.Info[] }
package models.user import scala.concurrent.ExecutionContext.Implicits.global import slick.driver.H2Driver.api._ import scala.concurrent.{Future, ExecutionContext} import play.api.Play import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfig} import slick.driver.JdbcProfile class Emails(tag: Tag) extends Table[Email](tag, "EMAILS") { def id = column[Int]("ID", O.PrimaryKey) def email = column[String]("EMAIL") def subscribed = column[Char]("SUBSCRIBED") def * = (id, email, subscribed) <> (Email.tupled, Email.unapply) } case class Email(id:Int, email:String, subscribed:Char) object Emails { protected val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current) val emails: TableQuery[Emails] = TableQuery[Emails] def listAll = { println(emails.result.statements.head) dbConfig.db.run(emails.result) } }
#!/bin/bash a=24 # a的二進位值為 11000 a=$((a<<1)) # 位移後a的二進位值為 110000,換算為10進位為48 echo $a b=31 # b的二進位值為 11111 b=$((b>>1)) # 位移後a的二進位值為 1111,換算為10進位為15 echo $b
/*Updating idoc_drawing */ UPDATE imw_dev_scan.idoc_drawing I INNER JOIN chart_drawings D ON I.drawing_for_master_id = IFNULL(D.import_id,0) AND I.drawing_for = CASE D.exam_name WHEN 'LA' THEN 'LA' WHEN 'FundusExam' THEN 'Fundus_Exam' WHEN 'SLE' THEN 'SLE' END SET I.drawing_for_master_id = D.id; /* Drop column from drawig table*/ ALTER TABLE chart_drawings DROP COLUMN import_id;
#!./perl -w # t/dumpperl.t - test all branches of, and modes of triggering, Dumpperl() BEGIN { if ($ENV{PERL_CORE}){ require Config; import Config; no warnings 'once'; if ($Config{'extensions'} !~ /\bData\/Dumper\b/) { print "1..0 # Skip: Data::Dumper was not built\n"; exit 0; } } } use strict; use Carp; use Data::Dumper; use Test::More tests => 31; use lib qw( ./t/lib ); use Testing qw( _dumptostr ); $Data::Dumper::Indent=1; { local $Data::Dumper::Useperl=1; local $Data::Dumper::Useqq=0; local $Data::Dumper::Deparse=0; note('$Data::Dumper::Useperl => 1'); run_tests_for_pure_perl_implementations(); } { local $Data::Dumper::Useperl=0; local $Data::Dumper::Useqq=1; local $Data::Dumper::Deparse=0; note('$Data::Dumper::Useqq => 1'); run_tests_for_pure_perl_implementations(); } { local $Data::Dumper::Useperl=0; local $Data::Dumper::Useqq=0; local $Data::Dumper::Deparse=1; note('$Data::Dumper::Deparse => 1'); run_tests_for_pure_perl_implementations(); } sub run_tests_for_pure_perl_implementations { my ($a, $b, $obj); my (@names); my (@newnames, $objagain, %newnames); my $dumpstr; $a = 'alpha'; $b = 'beta'; my @c = ( qw| eta theta | ); my %d = ( iota => 'kappa' ); note('names not provided'); $obj = Data::Dumper->new([$a, $b]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$VAR1.+alpha.+\$VAR2.+beta/s, "Dump: two strings" ); $obj = Data::Dumper->new([$a, \@c]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$VAR1.+alpha.+\$VAR2.+\[.+eta.+theta.+\]/s, "Dump: one string, one array ref" ); $obj = Data::Dumper->new([$a, \%d]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$VAR1.+alpha.+\$VAR2.+\{.+iota.+kappa.+\}/s, "Dump: one string, one hash ref" ); $obj = Data::Dumper->new([$a, undef]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$VAR1.+alpha.+\$VAR2.+undef/s, "Dump: one string, one undef" ); note('names provided'); $obj = Data::Dumper->new([$a, $b], [ qw( a b ) ]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$a.+alpha.+\$b.+beta/s, "Dump: names: two strings" ); $obj = Data::Dumper->new([$a, \@c], [ qw( a *c ) ]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$a.+alpha.+\@c.+eta.+theta/s, "Dump: names: one string, one array ref" ); $obj = Data::Dumper->new([$a, \%d], [ qw( a *d ) ]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$a.+alpha.+\%d.+iota.+kappa/s, "Dump: names: one string, one hash ref" ); $obj = Data::Dumper->new([$a,undef], [qw(a *c)]); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$a.+alpha.+\$c.+undef/s, "Dump: names: one string, one undef" ); $obj = Data::Dumper->new([$a, $b], [ 'a', '']); $dumpstr = _dumptostr($obj); like($dumpstr, qr/\$a.+alpha.+\$.+beta/s, "Dump: names: two strings: one name empty" ); $obj = Data::Dumper->new([$a, $b], [ 'a', '$foo']); $dumpstr = _dumptostr($obj); no warnings 'uninitialized'; like($dumpstr, qr/\$a.+alpha.+\$foo.+beta/s, "Dump: names: two strings: one name start with '\$'" ); use warnings; } { my ($obj, $dumpstr, $realtype); $obj = Data::Dumper->new([ {IO => *{$::{STDERR}}{IO}} ]); $obj->Useperl(1); eval { $dumpstr = _dumptostr($obj); }; $realtype = 'IO'; like($@, qr/Can't handle '$realtype' type/, "Got expected error: pure-perl: Data-Dumper does not handle $realtype"); }
use crate::models::{ Position, TString, }; use scroll::{ ctx::{ SizeWith, TryFromCtx, TryIntoCtx, }, Endian, Error as ScrollError, Pread, Pwrite, LE, }; #[derive(Clone, Debug, PartialEq, Eq, Pread, Pwrite)] #[repr(C)] pub struct Sign { pub text: TString, pub position: Position, } impl SizeWith<Sign> for Sign { fn size_with(ctx: &Self) -> usize { TString::size_with(&ctx.text) + Position::size_with(&LE) } } #[derive(Clone, Debug, Default, PartialEq, Eq)] #[repr(C)] pub struct Signs { pub count: u16, pub signs: Vec<Sign>, } impl Signs { #[must_use] pub fn find_sign_at_position(&self, position: Position) -> Option<&Sign> { let s = &self.signs; s.iter().find(|sign| sign.position == position) } } impl<'a> TryFromCtx<'a, Endian> for Signs { type Error = ScrollError; fn try_from_ctx( buf: &'a [u8], _: Endian, ) -> Result<(Self, usize), Self::Error> { let offset = &mut 0; let count = buf.gread_with::<u16>(offset, LE)?; let signs = (0..count) .map(|_| buf.gread::<Sign>(offset)) .collect::<Result<Vec<_>, Self::Error>>()?; Ok((Self { count, signs }, *offset)) } } impl SizeWith<Signs> for Signs { fn size_with(ctx: &Self) -> usize { u16::size_with(&LE) + ctx .signs .iter() .map(|sign| Sign::size_with(sign)) .sum::<usize>() } } impl TryIntoCtx<Endian> for &Signs { type Error = ScrollError; fn try_into_ctx( self, buf: &mut [u8], _: Endian, ) -> Result<usize, Self::Error> { let offset = &mut 0; let Signs { count, signs } = self; buf.gwrite_with(count, offset, LE)?; signs .iter() .map(|sign| buf.gwrite(sign, offset)) .collect::<Result<Vec<_>, Self::Error>>()?; let expected_size = Signs::size_with(self); assert!( expected_size == *offset, "Signs offset mismatch on write; expected {:?}, got {:?}", expected_size, offset ); Ok(*offset) } }
-module(shackle_test_utils). -export([ preload_modules/0 ]). %% public preload_modules() -> Filenames = filelib:wildcard("_build/default/lib/*/ebin/*.beam"), Rootnames = [filename:rootname(Filename, ".beam") || Filename <- Filenames], lists:foreach(fun code:load_abs/1, Rootnames).
// Vendors. import axios from "axios"; // Custom. import GraphClient from "../VoApi/GraphClient"; import VoBase from "../VoBase"; // import VoAuth from '../VoAuth'; import VoConfig from "../VoConfig"; class VoDocs extends VoBase { graphqlClient: any; init() { this.graphqlClient = GraphClient.createGraphClient( this.getGraphqlUrl, true ); } get getGraphqlUrl() { return VoConfig.get.DOCS_BASE_URL + "" + VoConfig.get.DOCS_GRAPHQL; } async getTemporaryFileUrl(id: string) { try { const url = `${this.getUrl}/docs/download/${id}`; return axios.get(url); } catch (error) { throw error; } } } export default new VoDocs("docs");
package com.junerver.cloudnote.bean import com.junerver.cloudnote.db.entity.Note /** * @Description 对应全部日志数据的模型 * @Author Junerver * Created at 2021/10/14 10:10 */ data class GetAllNoteResp(var results: List<Note>)
import React from 'react'; import InputGroup from './InputGroup' export default InputGroup;
/* * Copyright (c) 2021 Kyungyoon Kim(pemassi). * All rights reserved. */ package io.pemassi.pata.exceptions data class DataModelUnsupportedTypeException( override val message: String ): Exception(message)
import { Pipe, PipeTransform, OnDestroy } from '@angular/core'; import { CustomerService } from "../api/customer.service"; import { Country } from "../api/api.model"; import { Subscription } from "rxjs"; @Pipe({ name: 'country' }) export class CountryPipe implements PipeTransform, OnDestroy { private countries: Country[] private sub: Subscription constructor(service: CustomerService) { this.sub = service.getCountries().subscribe(countries=>{ this.countries = countries }) } ngOnDestroy() { this.sub.unsubscribe() } transform(value: any, args?: any): any { if(this.countries) { let country = this.countries.find(country=>{ return country.id == value }) if(country) return country.name } return null; } }
<?php return [ 'view_manager' => [ 'display_not_found_reason' => false, 'display_exceptions' => false, ], ];
# A shaded view of the CSC projection. You need OpenGL for this. require 'quad_sphere/csc' require 'opengl' class CSCShadedApp WINDOW_SIZE = 480 # How many subdivisions of each cube face. Can be raised for # smoother shading, at the cost of model complexity. FACE_SUBDIV = 10 def run @ang1 = 0 @ang2 = 0 @ang3 = 0 glutInit glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(WINDOW_SIZE, WINDOW_SIZE) glutCreateWindow('CSC') glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) glFrontFace(GL_CW) glClearColor(0.5, 0.5, 0.5, 0.0) setup_model glutDisplayFunc(method :display) glutReshapeFunc(method :reshape) glutKeyboardFunc(method :keyboard) # And run. glutMainLoop() end private def setup_model glGenLists(1) glNewList(1, GL_COMPILE) # The cube faces, and the colour we want each: faces = [ [ QuadSphere::TOP_FACE, [ 0.9, 0.25, 0.25, 1.0 ] ], # red [ QuadSphere::FRONT_FACE, [ 0.25, 0.25, 0.9, 1.0 ] ], # blue [ QuadSphere::EAST_FACE, [ 0.25, 0.9, 0.25, 1.0 ] ], # green [ QuadSphere::BACK_FACE, [ 0.9, 0.9, 0.25, 1.0 ] ], # yellow [ QuadSphere::WEST_FACE, [ 0.25, 0.9, 0.9, 1.0 ] ], #cyan [ QuadSphere::BOTTOM_FACE, [ 0.9, 0.25, 0.9, 1.0 ] ] ] #magenta faces.each do |face, colour| glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, colour); # Calculate all the vertices we'll use for this face... vertices = grid(face, FACE_SUBDIV) # ... and arrange them in triangle strips: mesh2strips(FACE_SUBDIV, vertices) end glEndList end def reshape(w, h) glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, w.to_f / h.to_f, 1.0, 20.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(3.2,0,0, 0,0,0, 0,0,1) # Add a light. glPushMatrix() glTranslate(2.5,-0.8,0.8); glLightfv(GL_LIGHT0, GL_POSITION, [0, 0, 0, 1]) glPopMatrix() end def display # XXX - maybe it'd be more efficient to only clear the depth # buffer if we moved the model or camera? glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Rotate and draw the model. glPushMatrix() glRotate(@ang1, 0, 0, 1) glRotate(@ang2, 1, 0, 0) glRotate(@ang3, 0, 1, 0) glCallList(1) glPopMatrix() # Done. glutSwapBuffers() end def keyboard(key, x, y) case (key) when ?s @ang1 = (@ang1 + 5) % 360 glutPostRedisplay() when ?a @ang1 = (@ang1 - 5) % 360 glutPostRedisplay() when ?w @ang2 = (@ang2 + 5) % 360 glutPostRedisplay() when ?q @ang2 = (@ang2 - 5) % 360 glutPostRedisplay() when ?x @ang3 = (@ang3 + 5) % 360 glutPostRedisplay() when ?z @ang3 = (@ang3 - 5) % 360 glutPostRedisplay() when ?r @ang1 = @ang2 = @ang3 = 0 glutPostRedisplay() when ?\e, ?Q exit(0) end end # Create a NxN grid of points on a face of the cube. Note that this # will generate (N+1)*(N+1) points. # # Each point is projected on the sphere and stored in an array. Note # that all these are points on the unit sphere, and so their distance # to the origin is 1, and so each point can be used as its own normal. def grid(face, n) dx = 2.0/n dy = 2.0/n a = Array.new n += 1 n.times do |j| y = -1.0 + j*dy n.times do |i| x = -1.0 + i*dx lon, lat = QuadSphere::CSC.inverse(face, x, y) sx = Math::cos(lat) * Math::cos(lon) sy = Math::cos(lat) * Math::sin(lon) sz = Math::sin(lat) a << [sx,sy,sz] end end a end # p grid(0, 3) # # Create triangle strips to represent a NxN mesh. The given array # should then contain (N+1)**2 points, arranged as N+1 rows of N+1 # points. def mesh2strips(n,a) dx = 2.0/n dy = 2.0/n row = n+1 n.times do |j| glBegin(GL_TRIANGLE_STRIP) rowi = j*row row.times do |x| add_vertex(a[rowi+x]) add_vertex(a[rowi+row+x]) end glEnd end end def add_vertex(v) glNormal3fv(v) glVertex3fv(v) end end CSCShadedApp.new.run
package api import ( "encoding/json" "github.com/MadhavJivrajani/go-corona-go/utils" ) type arrayJson []json.RawMessage func PlotGeneral(key string) ([]float64, error) { body, err := ApiIndiaTimeline() if err != nil { var empty []float64 return empty, err } var data arrayJson json.Unmarshal(body, &data) dataPoints, err := utils.ExtractDataPoints(data, key) if err != nil { var empty []float64 return empty, err } return dataPoints, nil } // PlotConfirmed provides plotting functionality for confirmed cases per day. func PlotConfirmed() error { dataPoints, err := PlotGeneral("dailyconfirmed") if err != nil { return err } plotDesc := utils.PlotData{ XAxis: "Dates starting from 30th January 2020.", YAxis: "Number of confirmed Covid-19 cases in India.", Caption: "A plot showing the trend of the number of confirmed Covid-19 cases per day.", } utils.PrintPlot(dataPoints, plotDesc) return nil } // PlotDeaths provides plotting functionality for number of deaths per day. func PlotDeaths() error { dataPoints, err := PlotGeneral("dailydeceased") if err != nil { return err } plotDesc := utils.PlotData{ XAxis: "Dates starting from 30th January 2020.", YAxis: "Number of deaths due to Covid-19 cases in India.", Caption: "A plot showing the trend of the number of deaths due to Covid-19 per day.", } utils.PrintPlot(dataPoints, plotDesc) return nil } // PlotRecovered provides plotting functionality for number of recoveries from Covid-19 per day. func PlotRecovered() error { dataPoints, err := PlotGeneral("dailyrecovered") if err != nil { return err } plotDesc := utils.PlotData{ XAxis: "Dates starting from 30th January 2020.", YAxis: "Number of recoveries from Covid-19 in India.", Caption: "A plot showing the trend of the number of deaths due to Covid-19 per day.", } utils.PrintPlot(dataPoints, plotDesc) return nil }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Shipping extends Model { public $timetamps= false; protected $fillabe=[ 'shipping_name' ,'shipping_address','shipping_phone','shipping_email','shipping_notes','shipping_method']; protected $primaryKey ='shipping_id'; protected $table ='tbl_shipping'; }
/// Forward hatch pattern bar chart example. /// /// The second series of bars is rendered with a pattern by defining a /// fillPatternFn mapping function. import 'package:flutter/material.dart'; import 'package:charts_flutter/flutter.dart' as charts; class PatternForwardHatchBarChart extends StatelessWidget { final List<IncomingAndSpending> listNoNCC; final List<IncomingAndSpending> listKHNo; final List<IncomingAndSpending> listIncoming; final List<IncomingAndSpending> listSpending; const PatternForwardHatchBarChart( {Key? key, required this.listNoNCC, required this.listKHNo, required this.listIncoming, required this.listSpending}) : super(key: key); @override Widget build(BuildContext context) { return new charts.BarChart( _createData(), animate: true, barGroupingType: charts.BarGroupingType.grouped, vertical: false, ); } /// Create series list with multiple series List<charts.Series<IncomingAndSpending, String>> _createData() { return [ new charts.Series<IncomingAndSpending, String>( id: 'Incoming', domainFn: (IncomingAndSpending report, _) => report.date, measureFn: (IncomingAndSpending report, _) => report.value, data: listIncoming, colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault), new charts.Series<IncomingAndSpending, String>( id: 'Spending', domainFn: (IncomingAndSpending report, _) => report.date, measureFn: (IncomingAndSpending report, _) => report.value, data: listSpending, colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault, ), new charts.Series<IncomingAndSpending, String>( id: 'NoNhaCungCap', domainFn: (IncomingAndSpending report, _) => report.date, measureFn: (IncomingAndSpending report, _) => report.value, data: listNoNCC, colorFn: (_, __) => charts.MaterialPalette.yellow.shadeDefault), new charts.Series<IncomingAndSpending, String>( id: 'KHNo', domainFn: (IncomingAndSpending report, _) => report.date, measureFn: (IncomingAndSpending report, _) => report.value, data: listKHNo, colorFn: (_, __) => charts.MaterialPalette.green.shadeDefault, ), ]; } } /// Sample ordinal data type. class IncomingAndSpending { final String date; final double value; IncomingAndSpending(this.date, this.value); }
using Domain.Core.ValueObjects; using System; using System.Collections.Generic; using System.Text; namespace Archai.CharacterCreator.Domain.ValueObject { public class SpriteData { public uint Width { get; } public uint Height { get; } public Color[,] Data { get; } public SpriteData(uint width, uint height, Color[,] data) { Width = width; Height = height; if(data.Length != width * height) { } Data = new Color[width, height]; Array.Copy(data, Data, width * height); } } }
package com.zendesk.scalaflow.sugar import com.google.cloud.dataflow.sdk.options.PipelineOptions.CheckEnabled._ import com.google.cloud.dataflow.sdk.testing.{DataflowAssert, TestPipeline} import com.google.cloud.dataflow.sdk.transforms.Create import org.scalatest.{FlatSpec, Matchers} import com.zendesk.scalaflow._ object CaseClassOpsSpec { case class Foo() case class Bar(name: String) case class Qux(name: String, age: Int) case class Wibble(foo: Foo, bar: Bar, qux: Qux) } class CaseClassOpsSpec extends FlatSpec with Matchers { import CaseClassOpsSpec._ behavior of "CaseClassCoders" it should "handle zero member case class" in { implicit val fooCoder = caseClassCoder(Foo) val pipeline = testPipeline() val output = pipeline.begin .transform(Create.of(Foo())) .map(identity) DataflowAssert.that(output).containsInAnyOrder(Foo()) pipeline.run() } it should "handle single member case class" in { implicit val barCoder = caseClassCoder(Bar) val pipeline = testPipeline() val output = pipeline.begin .transform(Create.of(Bar("Fred"))) .map(_.copy(name = "John")) DataflowAssert.that(output).containsInAnyOrder(Bar("John")) pipeline.run() } it should "handle double member case classes" in { implicit val quxCoder = caseClassCoder(Qux) val pipeline = testPipeline() val output = pipeline.begin .transform(Create.of(Qux("Fred", 27))) .map(_.copy(age = 35)) DataflowAssert.that(output).containsInAnyOrder(Qux("Fred", 35)) pipeline.run() } it should "handle nested case classes" in { implicit val fooCoder = caseClassCoder(Foo) implicit val barCoder = caseClassCoder(Bar) implicit val quxCoder = caseClassCoder(Qux) implicit val wibbleCoder = caseClassCoder(Wibble) val pipeline = testPipeline() val output = pipeline.begin .transform(Create.of(Wibble(Foo(), Bar("John"), Qux("Fred", 27)))) .map(_.copy(qux = Qux("Fred", 35))) DataflowAssert.that(output).containsInAnyOrder(Wibble(Foo(), Bar("John"), Qux("Fred", 35))) pipeline.run() } private def testPipeline() = { val pipelineOptions = TestPipeline.testingPipelineOptions pipelineOptions.setStableUniqueNames(OFF) TestPipeline.fromOptions(pipelineOptions) } }
# Browserify Babel sample A sample app on using Browserify + Babel [Video In Spanish](https://www.youtube.com/watch?v=ITM6egxpHIg)
# QRReader A Java program to read QR codes from PDF files and dump the decoded QR codes into a csv file.
const Joi = require('joi'); const envVarsSchema = Joi.object() .keys({ NODE_ENV: Joi.string().valid('production', 'development', 'test').required(), PORT: Joi.number().default(3000), }) .unknown(); module.exports = envVarsSchema;
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.OpcUa.Vault.Models { using Microsoft.Azure.IIoT.OpcUa.Vault.Storage.Models; using System; /// <summary> /// Trust relationship extensions /// </summary> public static class TrustDocumentEx { /// <summary> /// Create model /// </summary> /// <param name="document"></param> public static TrustRelationshipModel ToServiceModel( this TrustDocument document) { return new TrustRelationshipModel { TrustedId = document.TrustedId, TrustingId = document.TrustingId, TrustingType = document.TrustingType, TrustedType = document.TrustedType, }; } /// <summary> /// Convert to service model /// </summary> /// <param name="model"></param> /// <param name="id"></param> /// <param name="etag"></param> /// <returns></returns> public static TrustDocument ToDocumentModel( this TrustRelationshipModel model, string id = null, string etag = null) { if (string.IsNullOrEmpty(id)) { // Assign unique id id = "utr" + (model.TrustedId + model.TrustingId).ToSha1Hash(); } var document = new TrustDocument { ETag = etag, Id = id, TrustedId = model.TrustedId, TrustingId = model.TrustingId, TrustingType = model.TrustingType, TrustedType = model.TrustedType, ClassType = TrustDocument.ClassTypeName }; return document; } /// <summary> /// Convert to service model /// </summary> /// <param name="model"></param> /// <returns></returns> public static TrustDocument Clone(this TrustDocument model) { return new TrustDocument { Id = model.Id, TrustedId = model.TrustedId, TrustingId = model.TrustingId, TrustingType = model.TrustingType, TrustedType = model.TrustedType, ETag = model.ETag, ClassType = model.ClassType }; } } }
using UnityEngine; using System.Collections; public class camera : MonoBehaviour { public Transform camTrans; public GameObject boatObj; // Use this for initialization void Start () { GameObject mainCamObj = GameObject.Find("Main Camera"); boatObj = GameObject.Find("BoatContainer"); camTrans = mainCamObj.GetComponent<Transform>(); } // Update is called once per frame void Update () { Transform boatTrans = boatObj.GetComponent<Transform>(); } }
import 'package:counter/main.dart'; import 'package:redux_saga/redux_saga.dart'; import 'package:test/test.dart'; void main() { group('Middleware Tests', () { test('incrementAsync Test', () { Iterable gen = incrementAsync(); Iterator iterator = gen.iterator; iterator.moveNext(); expect(iterator.current, TypeMatcher<Delay>(), reason: 'incrementAsync should return a Delay effect'); expect(iterator.current.duration, Duration(seconds: 1), reason: 'Delay effect must resolve after 1 second'); iterator.moveNext(); expect(iterator.current, TypeMatcher<Put>(), reason: 'incrementAsync should return a Put effect'); expect(iterator.current.action, TypeMatcher<IncrementAction>(), reason: 'incrementAsync Saga must dispatch an IncrementAction action'); expect(iterator.moveNext(), false, reason: 'incrementAsync Saga must be done'); }); }); }
import { FinMath as math } from '../src/math' describe('FinMath', () => { describe('constructor', () => { it('should create an instance of Math without exception when all arguments passed', () => { expect(() => new math(1)).not.toThrow() }) it('should create an instance of Math without exception when no argument provided', () => { expect(() => new math()).not.toThrow() }) }) describe('fromNumber', () => { it('should throw exception when a passed number is greater than MAX_SAFE_INTEGER', () => { expect(() => math.fromNumber(Number.MAX_SAFE_INTEGER + 1)).toThrowError( 'Given argument is greater than a MAX_SAFE_INTEGER: 9007199254740992 > 9007199254740991' ) }) it('should throw exception when a passed number is less than MIN_SAFE_INTEGER', () => { expect(() => math.fromNumber(Number.MIN_SAFE_INTEGER - 1)).toThrowError('') }) it('should not throw exception when a number equals MAX_SAFE_INTEGER', () => { expect(() => math.fromNumber(Number.MAX_SAFE_INTEGER)).not.toThrow() }) it('should not throw exception when a number equals MIN_SAFE_INTEGER', () => { expect(() => math.fromNumber(Number.MIN_SAFE_INTEGER)).not.toThrow() }) it('should not throw exception when a number between MIN_SAFE_INTEGER and MAX_SAFE_INTEGER', () => { expect(() => math.fromNumber(Number.MAX_SAFE_INTEGER - 1)).not.toThrow() expect(() => math.fromNumber(Number.MIN_SAFE_INTEGER + 1)).not.toThrow() }) it('should return an instance of Math when a number equals zero', () => { expect(math.fromNumber(0)).toBeInstanceOf(math) }) it('should return an instance of Math when a number is positive', () => { expect(math.fromNumber(1)).toBeInstanceOf(math) }) it('should return an instance of Math when a number is negative', () => { expect(math.fromNumber(-1)).toBeInstanceOf(math) }) }) /* describe('fromString', () => { test.todo('should throw exception when given string is not valid number') test.todo('should pass validation when given string is a valid integer') test.todo('should pass validation when given string is a valid float') test.todo('should pass validation when given string is a postestitodo number') test.todo('should pass validation when given string is a negative number') }) */ describe('add', () => { it.each([ [0, 0, 0], [0.0, 0, 0.0], [0, 0.0, 0.0], [0.0, 0.0, 0.0], [-1, 1, 0], [1, -1, 0], [-1, -1, -2], [-0.00007, 0.00006, -0.00001], [0.00007, -0.00006, 0.00001], [-0.00007, -0.00006, -0.00013], [89_9999_9999_9999, 1, 90_0000_0000_0000], [90_0000_0000_0000, -1, 89_9999_9999_9999], [1, 0.1, 1.1], [1, 0.01, 1.01], [1, 0.001, 1.001], [1, 0.0001, 1.0001], [1, 0.00001, 1.00001], [1, 0.000001, 1.000001], [1, 0.0000001, 1.0000001], [1, 0.00000001, 1.00000001] ])('add(%d, %d) === %d', (firstInput, secondInput, expected) => { expect( math .fromNumber(firstInput) .add(secondInput) .result() ).toBe(expected) }) }) describe('sub', () => { it.each([ [0, 0, 0], [0.0, 0.0, 0.0], [-1, -1, 0.0], [-1.0, -1.0, 0.0], [-2.0, -1.0, -1.0], [10.00010001, 0.0001, 10.00000001], [89999999999999, 1, 89999999999998], [Number.MAX_SAFE_INTEGER, 1, 9007199254740990], [Number.MIN_SAFE_INTEGER, -1, -9007199254740990] ])('sub(%d, %d) === %d', (firstOperand, secondOperand, expected) => { expect( math .fromNumber(firstOperand) .sub(secondOperand) .result() ).toBe(expected) }) }) describe('mul', () => { it.each([ [0.375, 0.0000125, 0.0000046875], [0.0007, 0.0006, 0.00000042], [0.00093, 0.003, 0.00000279], [100.502, 10.1, 1015.0702] ])('mul(%d, %d) === %d', (firstOperand, secondOperand, expected) => { expect( math .fromNumber(firstOperand) .mul(secondOperand) .result() ).toBe(expected) }) }) describe('result', () => { it('should return result after a single operation', () => { expect( math .fromNumber(0) .add(100.0) .result() ).toBe(100.0) }) it('should return result after a double operation', () => { expect( math .fromNumber(0) .add(100.25) .add(100.25) .result() ).toBe(200.5) }) it('should return result after a triple operation', () => { expect( math .fromNumber(0) .add(100.25) .add(100.25) .add(100.25) .result() ).toBe(300.75) }) it('should return default value when operations never called', () => { expect(new math().result()).toBe(0) }) it('should return left operand when result requested after initialization', () => { expect(math.fromNumber(100).result()).toBe(100) expect(math.fromNumber(100.25).result()).toBe(100.25) }) }) describe('resultAsString', () => { it('should return result after a single operation', () => { expect( math .fromNumber(0) .add(100.25) .resultAsString() ).toBe('100.25') }) it('should return result after a double operation', () => { expect( math .fromNumber(0) .add(100.25) .add(100.25) .resultAsString() ).toBe('200.5') }) it('should return result after a triple operation', () => { expect( math .fromNumber(0) .add(100.25) .add(100.25) .add(100.25) .resultAsString() ).toBe('300.75') }) it('should return default value when operations never called', () => { expect(new math().resultAsString()).toBe('0') }) it('should return left operand when result requested after initialization', () => { expect(math.fromNumber(100).resultAsString()).toBe('100') expect(math.fromNumber(100.25).resultAsString()).toBe('100.25') }) }) })
/* ----------------------------------------------------------------------------* * * M I N I M A L I S T I C U L P E N T I T Y * * Copyright (C) 2010 Amit Chawre. * * ----------------------------------------------------------------------------*/ /** @file NwMiniUlpEntity.h @brief This file contains example of a minimalistic ULP entity. */ #include <stdio.h> #include <assert.h> #include "NwEvt.h" #include "NwLog.h" #ifndef __NW_MINI_ULP_H__ #define __NW_MINI_ULP_H__ typedef struct { int hSocket; uint16_t seqNum; uint8_t restartCounter; uint8_t localIpStr[16]; uint8_t peerIpStr[16]; uint32_t localPort[1025]; NwEventT ev[1025]; NwGtpv1uStackHandleT hGtpv1uStack; NwGtpv1uStackSessionHandleT hGtpv1uConn; } NwMiniUlpEntityT; #ifdef __cplusplus extern "C" { #endif NwGtpv1uRcT nwMiniUlpInit(NwMiniUlpEntityT *thiz, NwGtpv1uStackHandleT hGtpv1uStack); NwGtpv1uRcT nwMiniUlpDestroy(NwMiniUlpEntityT *thiz); NwGtpv1uRcT nwMiniUlpCreateConn(NwMiniUlpEntityT *thiz, char *localIpStr, uint16_t localPort, char *peerIpStr); NwGtpv1uRcT nwMiniUlpDestroyConn(NwMiniUlpEntityT *thiz); NwGtpv1uRcT nwMiniUlpSendMsg(NwMiniUlpEntityT *thiz); NwGtpv1uRcT nwMiniUlpTpduSend(NwMiniUlpEntityT *thiz, uint8_t *tpduBuf, uint32_t tpduLen, uint16_t fromPort); NwGtpv1uRcT nwMiniUlpProcessStackReqCallback(NwGtpv1uUlpHandleT hUlp, NwGtpv1uUlpApiT *pUlpApi); #ifdef __cplusplus } #endif #endif
require "nokogiri" require "kaminari" require "simple_form" require "semantic-ui-sass" require "ckeditor" require "active_decorator" require "jquery-rails" require "jquery-ui-rails" require "cocoon" require "pry" require "pry-rails" require "pry-nav" require "better_errors" require "binding_of_caller" module Fanta class Engine < ::Rails::Engine isolate_namespace Fanta #自分のローカル時間を記録 config.time_zone = 'Tokyo' #Active Record Timezone config.active_record.default_timezone = :local config.i18n.default_locale = :ja config.assets.compress = false config.assets.debug = true initializer "sprite.assets.precompile" do |app| app.config.assets.precompile << %w( cocoon ) end end end
<?php namespace App\Services; use App\Exceptions\UserNotAllowedException; use App\Models\Task; use App\Models\User; class TaskService { /** * Handle task list * @param App\Models\User * @param string $q * @return array */ public function list( User $user, string $q = '' ) { if(!empty($q)){ $tasks = $user->tasks()->where('label', 'LIKE', "%$q%")->get(); } else { $tasks = $user->tasks; } return $tasks; } /** * Handle task creation * @param string $label * @param int $is_complete * @param int $user_id * @return App\Models\Task */ public function create( string $label, int $is_complete, int $user_id ) { $data = [ 'label' => $label, 'is_complete' => $is_complete, 'user_id' => $user_id, ]; $task = Task::create($data); return $task; } /** * Handle task edition * @param App\Models\Task $task * @param string $label * @param int $is_complete * @param int $user_id * @return App\Models\Task */ public function update( Task $task, string $label, int $is_complete, int $user_id ) { $this->checkPermission($task, $user_id); $data = [ 'label' => $label, 'is_complete' => $is_complete, ]; $task->fill($data); $task->save(); return $task->fresh(); } /** * Handle task delete * @param App\Models\Task $task * @param int $user_id * @return bool */ public function destroy( Task $task, int $user_id ) { $this->checkPermission($task, $user_id); return $task->delete(); } /** * Handle user permission * @param App\Models\Task $task * @param int $user_id * @return void * @throws App\Exceptions\UserNotAllowedException */ public function checkPermission(Task $task, int $user_id) { if($task->user_id != $user_id) { throw new UserNotAllowedException; } } }
if [ "$TP_HOME" = "" ] ; then echo "ERROR: TP_HOME not found in your environment." echo echo "Please, set the TP_HOME variable in your environment to match the" echo "location of the Tableau Prover version you want to use." exit 1 fi $TP_HOME/bin/analysers/clean.sh $TP_HOME/bin/analysers/cwSAT.sh $TP_HOME/bin/analysers/satcnf2.sh $TP_HOME/bin/analysers/satcnf.sh $TP_HOME/bin/analysers/SATS.sh $TP_HOME/bin/analysers/SATs2.sh $TP_HOME/bin/analysers/SATs3.sh $TP_HOME/bin/analysers/SATs4.sh $TP_HOME/bin/analysers/SATs5.sh $TP_HOME/bin/analysers/SATH.sh $TP_HOME/bin/analysers/SATH2.sh
module Preprocess.Type where import qualified Interpreter.AST as I import qualified Parse.AST as P preprocessType :: P.Type -> I.Type preprocessType (P.NamedT name) = I.NamedType name preprocessType (P.ListT t) = I.ListType (preprocessType t) preprocessType (P.PureFunT a b) = I.PureFunctionType (preprocessType a) (preprocessType b)
--- title: netlify demo date: 2021-01-14T08:57:59.838Z description: just testing --- ![hehe](tech-team.png "tech team") ![]() just testing you
#!/bin/bash -x set -o errexit set -o nounset set -o pipefail # Install the latest kernel-ml (mainline kernel) from elrepo's elrepo-kernel yum # repository yum -y install http://www.elrepo.org/elrepo-release-6-8.el6.elrepo.noarch.rpm # Install kernel-ml-devel as its needed for when guest additions are compiled yum -y --enablerepo=elrepo-kernel install kernel-ml kernel-ml-devel /sbin/grubby --set-default=$(ls -1 /boot/vmlinuz-4* | sort | tail -n1) # cleanup.sh should remove unused kernels but we need to boot into the new # kernel first reboot sleep 30
module.exports = function (grunt, pkg) { grunt.config.merge({ webfont: { rh_icon: { src: 'src/iconfont/vectors/rh_icon/*.svg', dest: 'dist/fonts/rh_icon', destCss: 'dist/files/', options: { fontFilename: 'rh-iconfont-{hash}', relativeFontPath: '../fonts/rh_icon', font: 'rh-iconfont', stylesheet: 'scss', template: 'src/iconfont/templates/sass-template.css', htmlDemo: true, htmlDemoTemplate: 'src/iconfont/templates/html-template.html', destHtml: 'dist/files', templateOptions: { "fontFamilyName": "rh-iconfont", "baseClass": "rh-icon", "pathFromDist": "fonts/rh_icon/rh-iconfont" } } }, rh_web_icon: { src: 'src/iconfont/vectors/web_icon/*.svg', dest: 'dist/fonts/web_icon', destCss: 'dist/files/', options: { fontFilename: 'rh-web-iconfont-{hash}', relativeFontPath: '../fonts/web_icon', font: 'web-iconfont', stylesheet: 'scss', template: 'src/iconfont/templates/sass-template.css', htmlDemo: true, htmlDemoTemplate: 'src/iconfont/templates/html-template.html', destHtml: 'dist/files', templateOptions: { "fontFamilyName": "rh-web-iconfont", "baseClass": "web-icon", "pathFromDist": "fonts/web_icon/rh-web-iconfont" } } } }, }); }
# Œ 1224 ‰ --- ] nwnk dwsu drsu pRB jwcY mn qn ko AwDwr ]2]78]101] swrg mhlw 5 ] mYlw hir ky nwm ibnu jIau ] iqin pRiB swcY Awip BulwieAw ibKY TgaurI pIau ]1] rhwau ] koit jnm BRmqO bhu BWqI iQiq nhI kqhU pweI ] pUrw siqguru shij n ByitAw swkqu AwvY jweI ]1] rwiK lyhu pRB sMimRQ dwqy qum pRB Agm Apwr ] nwnk dws qyrI srxweI Bvjlu auqirE pwr ]2]79]102] swrg mhlw 5 ] rmx kau rwm ky gux bwd ] swDsMig iDAweIAY prmysru AMimRq jw ky suAwd ]1] rhwau ] ismrq eyku Acuq AibnwsI ibnsy mwieAw mwd ] shj And Anhd Duin bwxI bhuir n pey ibKwd ]1] snkwidk bRhmwidk gwvq gwvq suk pRihlwd ] pIvq Aimau mnohr hir rsu jip nwnk hir ibsmwd ]2]80]103] swrg mhlw 5 ] kIn@y pwp ky bhu kot ] idnsu rYnI Qkq nwhI kqih nwhI Cot ]1] rhwau ] mhw bjr ibK ibAwDI isir auTweI pot ] auGir geIAW iKnih BIqir jmih gRwsy Jot ]1] psu pryq aust grDB Aink jonI lyt ] Bju swDsMig goibMd nwnk kCu n lwgY Pyt ]2]81]104] swrg mhlw 5 ] AMDy Kwvih ibsU ky gtwk ] nYn sRvn srIru sBu huitE swsu gieE qq Gwt ]1] rhwau ] AnwQ r\wix audr ly poKih mwieAw geIAw hwit ] iklibK krq krq pCuqwvih kbhu n swkih CWit ]1] inMdku jmdUqI Awie sMGwirE dyvih mUMf aupir mtwk ] nwnk Awpn ktwrI Awps kau lweI mnu Apnw kIno Pwt ]2]82]105] swrg mhlw 5 ] tUtI inMdk kI AD bIc ] jn kw rwKw Awip suAwmI bymuK kau Awie phUcI mIc ]1] rhwau ] aus kw kihAw koie n suxeI khI n bYsxu pwvY ] eIhW duKu AwgY nrku BuMcY bhu jonI BrmwvY ]1] pRgtu BieAw KMfI bRhmMfI kIqw Apxw pwieAw ] nwnk srix inrBau krqy kI And mMgl gux gwieAw ]2]83]106] swrg mhlw 5 ] iqRsnw clq ####
import React from 'react' import style from './button.css' const Button = props => ( <button className={style.button} onClick={() => props.onClick()} disabled={props.disabled} ><p>{props.children}</p> </button> ) Button.propTypes = { onClick: React.PropTypes.func, children: React.PropTypes.string, disabled: React.PropTypes.bool, } export default Button
# frozen_string_literal: true require_relative 'boot' require 'rails/all' if (google_domain = ENV["GOOGLE_DOMAIN"]) && !ENV['EMAIL_DOMAIN'] warn "Stop using deprecated GOOGLE_DOMAIN" ENV["EMAIL_DOMAIN"] = google_domain.sub('@', '') end Bundler.require(:preload) Bundler.require(:assets) if Rails.env.development? || ENV["PRECOMPILE"] ### # Railties need to be loaded before the application is defined if ['development', 'staging'].include?(Rails.env) require 'better_errors' require 'rack-mini-profiler' # side effect: removes expires headers end if ['staging', 'production'].include?(Rails.env) require 'airbrake' require 'airbrake/user_informer' require 'newrelic_rpm' else # avoids circular dependencies warning # https://discuss.newrelic.com/t/circular-require-in-ruby-agent-lib-new-relic-agent-method-tracer-rb/42737 require 'new_relic/control' # needed even in dev/test mode require 'new_relic/agent/method_tracer' end # END Railties ### require_relative "../lib/samson/env_check" module Samson class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. deprecated_url = ->(var) do url = ENV[var].presence return url if !url || url.start_with?('http') warn "Using deprecated url without protocol for #{var}" "https://#{url}" end config.eager_load_paths << "#{config.root}/lib" if Rails.env.test? config.cache_store = :memory_store else servers = [] options = { value_max_bytes: 3000000, compress: true, expires_in: 7.days, namespace: "samson-#{Rails.version}-#{RUBY_VERSION}", pool_size: [Integer(ENV.fetch('RAILS_MAX_THREADS', '250')) / 10, 2].max # 1/10 th of threads, see puma.rb } # support memcachier env used by heroku # https://devcenter.heroku.com/articles/memcachier#rails-3-and-4 if ENV["MEMCACHIER_SERVERS"] servers = (ENV["MEMCACHIER_SERVERS"]).split(",") options.merge!( username: ENV["MEMCACHIER_USERNAME"], password: ENV["MEMCACHIER_PASSWORD"], failover: true, socket_timeout: 1.5, socket_failure_delay: 0.2 ) end config.cache_store = :dalli_store, servers, options end # Allow streaming config.preload_frameworks = true config.allow_concurrency = true # Used for all Samson specific configuration. config.samson = ActiveSupport::OrderedOptions.new # Email prefix e.g. [PREFIX] Someone deployed PROJECT to STAGE (REF) config.samson.email = ActiveSupport::OrderedOptions.new config.samson.email.prefix = ENV["EMAIL_PREFIX"].presence || "DEPLOY" config.samson.email.sender_domain = ENV["EMAIL_SENDER_DOMAIN"].presence || "samson-deployment.com" # Email notifications config.samson.project_created_email = ENV["PROJECT_CREATED_NOTIFY_ADDRESS"] config.samson.project_deleted_email = ENV["PROJECT_DELETED_NOTIFY_ADDRESS"].presence || ENV["PROJECT_CREATED_NOTIFY_ADDRESS"] # Tired of the i18n deprecation warning config.i18n.enforce_available_locales = true # The directory in which repositories should be cached. config.samson.cached_repos_dir = Rails.root.join("cached_repos") # The Github teams and organizations used for permissions config.samson.github = ActiveSupport::OrderedOptions.new config.samson.github.organization = ENV["GITHUB_ORGANIZATION"].presence config.samson.github.admin_team = ENV["GITHUB_ADMIN_TEAM"].presence config.samson.github.deploy_team = ENV["GITHUB_DEPLOY_TEAM"].presence config.samson.github.web_url = deprecated_url.call("GITHUB_WEB_URL") || 'https://github.com' config.samson.github.api_url = deprecated_url.call("GITHUB_API_URL") || 'https://api.github.com' config.samson.github.status_url = deprecated_url.call("GITHUB_STATUS_URL") || 'https://status.github.com' config.samson.references_cache_ttl = ENV['REFERENCES_CACHE_TTL'].presence || 10.minutes # Configuration for LDAP config.samson.ldap = ActiveSupport::OrderedOptions.new config.samson.ldap.title = ENV["LDAP_TITLE"].presence config.samson.ldap.host = ENV["LDAP_HOST"].presence config.samson.ldap.port = ENV["LDAP_PORT"].presence config.samson.ldap.base = ENV["LDAP_BASE"].presence config.samson.ldap.uid = ENV["LDAP_UID"].presence config.samson.ldap.bind_dn = ENV["LDAP_BINDDN"].presence config.samson.ldap.password = ENV["LDAP_PASSWORD"].presence config.samson.gitlab = ActiveSupport::OrderedOptions.new config.samson.gitlab.web_url = deprecated_url.call("GITLAB_URL") || 'https://gitlab.com' config.samson.auth = ActiveSupport::OrderedOptions.new config.samson.auth.github = Samson::EnvCheck.set?("AUTH_GITHUB") config.samson.auth.google = Samson::EnvCheck.set?("AUTH_GOOGLE") config.samson.auth.ldap = Samson::EnvCheck.set?("AUTH_LDAP") config.samson.auth.gitlab = Samson::EnvCheck.set?("AUTH_GITLAB") config.samson.uri = URI(ENV["DEFAULT_URL"] || 'http://localhost:3000') config.sse_rails_engine.access_control_allow_origin = config.samson.uri.to_s config.samson.stream_origin = ENV['STREAM_ORIGIN'].presence || config.samson.uri.to_s config.samson.deploy_origin = ENV['DEPLOY_ORIGIN'].presence || config.samson.uri.to_s self.default_url_options = { host: config.samson.uri.host, protocol: config.samson.uri.scheme } config.action_controller.action_on_unpermitted_parameters = :raise config.action_view.default_form_builder = 'Samson::FormBuilder' # string so we can auto-reload it config.active_job.queue_adapter = :sucker_punch config.samson.export_job = ActiveSupport::OrderedOptions.new config.samson.export_job.downloaded_age = Integer(ENV['EXPORT_JOB_DOWNLOADED_AGE'] || 12.hours) config.samson.export_job.max_age = Integer(ENV['EXPORT_JOB_MAX_AGE'] || 1.day) # flowdock uses routes: run after the routes are loaded # config.ru sets SERVER_MODE after application.rb is loaded when using `rails s` initializer :execute_job, after: :set_routes_reloader_hook do if !Rails.env.test? && ENV['SERVER_MODE'] && !ENV['PRECOMPILE'] JobExecution.enabled = true Job.running.each { |j| j.stop!(nil) } Job.non_deploy.pending.each do |job| JobExecution.start_job(JobExecution.new(job.commit, job)) end Deploy.start_deploys_waiting_for_restart! RestartSignalHandler.listen end end unless ENV['PRECOMPILE'] config.after_initialize do # Token used to request badges config.samson.badge_token = \ Digest::MD5.hexdigest('badge_token'.dup + Samson::Application.config.secret_key_base) end end # we want 'project' as root for project collections in controller responses ActiveModelSerializers.config.adapter = :json end end require 'samson/hooks' require "#{Rails.root}/lib/samson/logging"
import { ACTIONS } from '../actions/game'; import { unlockThresholds, unlocks } from '../data/level-up-definitions' export default function(state = {}, action) { switch (action.type) { case ACTIONS.TICK: { const [unlockPopType, popRequired] = unlockThresholds[state.island.level - 1]; const currentPop = state.population[unlockPopType].owned; if (currentPop >= popRequired) { const newState = Object.assign({}, state); const island = Object.assign({}, newState.island); newState.island = island; island.level++; const unlocked = unlocks[island.level - 1]; if (unlocked.title) { island.title = unlocked.title; } if (unlocked.buildings) { const constructions = Object.assign({}, newState.construction); newState.construction = constructions; unlocked.buildings.forEach(conId => { const construction = Object.assign({}, constructions[conId]); construction.unlocked = true; constructions[conId] = construction; }); } if (unlocked.resources) { const warehouse = Object.assign({}, newState.warehouse); const resources = Object.assign({}, warehouse.resources); newState.warehouse = warehouse; warehouse.resources = resources; unlocked.resources.forEach(resId => { const resource = Object.assign({}, resources[resId]); resources[resId] = resource; resource.unlocked = true; }); } if (unlocked.population) { const population = Object.assign({}, newState.population); newState.population = population; const popUnlocked = Object.assign({}, population[unlocked.population]); popUnlocked.unlocked = true; population[unlocked.population] = popUnlocked; } if (unlocked.housing) { const types = {...newState.housing.types} const housing = {...newState.housing, types: types}; newState.housing = housing; unlocked.housing.forEach(houseId => { const unlockedHouse = {...types[houseId], unlocked: true}; types[houseId] = unlockedHouse; }); } return newState; } return state; } default: return state; } }
ActiveSupport::Inflector.inflections(:_gem_active_reporter) do |inflect| sys_inflect = ActiveSupport::Inflector.inflections %i(acronyms humans uncountables singulars plurals acronyms_camelize_regex acronyms_underscore_regex).each do |var| inflect.instance_variable_set("@#{var}", sys_inflect.send(var).dup) end inflect.uncountable "delta" end
const iterHillClimbing = (state, problem, candidate) => { const value = problem.func(candidate) state.evaluations++ if (value <= state.value) { return false } state.value = value state.solution = candidate return true } module.exports = { iterHillClimbing }
package com.lujiahao.java8inaction.chapter5; import lombok.Data; /** * @author lujiahao * @date 2019-03-11 17:17 */ @Data public class Trader { public final String name; public final String city; }
module Lib.Server.Handler.PostLogin where import Lib.Data.Permission import Lib.Api.Types import Lib.Server.Types import Blaze.ByteString.Builder ( toByteString ) import Servant hiding ( BadPassword , NoSuchUser , throwError , ServerError ) import Lib.Server.Error import Servant.Auth.Server as Auth import Web.Cookie import Control.Lens ( (^.) ) import Lib.Server.Handler.GetPhotographers import Lib.Data.Photographer import Control.Comonad import Data.Generics.Labels () servePostLogin :: LoginForm -> ServerApp (Headers '[Header "Set-Cookie" Text] NoContent) servePostLogin LoginForm = do (Photographers photographers) <- readPhotographers let perms = (extract photographers) ^. #perms setLoggedIn perms where setLoggedIn perms = do let cookie = AuthCookie { permissions = perms } ServerEnv {..} <- ask mCookie <- liftIO $ makeSessionCookie cookieSettings jwtSettings cookie case mCookie of Nothing -> throwError $ ServerError "servantErr" Just setCookie -> do return $ addHeader (decodeUtf8 ((toByteString . renderSetCookie) (setCookie { setCookieSecure = False , setCookieHttpOnly = False } ) ) ) NoContent
import { html } from 'lit-html' export default { // This is the folder where this component shows in Storybook. title: 'Atomic Elements/VisuallyHidden', } export const Examples = () => html` <gds-visually-hidden> <a href="#">Visually hidden link</a> </gds-visually-hidden> <gds-visually-hidden focusable> <a href="#">Visually hidden but focusable link</a> </gds-visually-hidden> `
package de.deutschebahn.bahnhoflive.view import android.view.View import com.google.android.material.snackbar.Snackbar import de.deutschebahn.bahnhoflive.R class ConfirmationDialog(targetView: View, message: String, confirmedAction: View.OnClickListener) { init { val snackbar = Snackbar.make(targetView, message, Snackbar.LENGTH_SHORT) snackbar.setAction("Ja", confirmedAction) snackbar.view.setBackgroundColor(snackbar.context.resources.getColor(R.color.white)) snackbar.show() } }
; ModuleID = 'generated/1/binary/args_v1.o.0.5.precodegen.bc' source_filename = "ld-temp.o" target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-pc-linux-gnu" @global_time = internal global i64 0, align 8 ; Function Attrs: noinline norecurse nounwind uwtable define internal void @_Z10path_startv() #0 { %1 = tail call i64 @time(i64* nonnull @global_time) #4 ret void } ; Function Attrs: nounwind declare i64 @time(i64*) local_unnamed_addr #1 ; Function Attrs: noinline norecurse nounwind uwtable define internal void @_Z9path_goalv() #0 { %1 = tail call i64 @time(i64* nonnull @global_time) #4 ret void } ; Function Attrs: noinline norecurse nounwind uwtable define internal void @_Z12path_nongoalv() #0 { %1 = tail call i64 @time(i64* nonnull @global_time) #4 ret void } ; Function Attrs: norecurse nounwind uwtable define dso_local i32 @main(i32 %0, i8** nocapture readonly %1) #2 { %3 = alloca i32, align 4 tail call void @_Z10path_startv() %4 = bitcast i32* %3 to i8* call void @llvm.lifetime.start.p0i8(i64 4, i8* nonnull %4) store volatile i32 %0, i32* %3, align 4 %5 = tail call i32 @rand() #4 %6 = icmp eq i32 %0, 2 br i1 %6, label %7, label %16 7: ; preds = %2 %8 = getelementptr inbounds i8*, i8** %1, i64 1 %9 = load i8*, i8** %8, align 8, !tbaa !2 %10 = load i8, i8* %9, align 1, !tbaa !6 %11 = sext i8 %10 to i32 %12 = shl i32 %5, 24 %13 = ashr exact i32 %12, 24 %14 = icmp eq i32 %13, %11 br i1 %14, label %15, label %16 15: ; preds = %7 tail call void @_Z9path_goalv() br label %28 16: ; preds = %7, %2 %17 = load volatile i32, i32* %3, align 4 %18 = icmp eq i32 %17, 2 br i1 %18, label %19, label %28 19: ; preds = %16 %20 = getelementptr inbounds i8*, i8** %1, i64 1 %21 = load i8*, i8** %20, align 8, !tbaa !2 %22 = load i8, i8* %21, align 1, !tbaa !6 %23 = sext i8 %22 to i32 %24 = shl i32 %5, 24 %25 = ashr exact i32 %24, 24 %26 = icmp eq i32 %25, %23 br i1 %26, label %27, label %28 27: ; preds = %19 tail call void @_Z12path_nongoalv() br label %28 28: ; preds = %27, %19, %16, %15 call void @llvm.lifetime.end.p0i8(i64 4, i8* nonnull %4) ret i32 0 } ; Function Attrs: argmemonly nounwind willreturn declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture) #3 ; Function Attrs: nounwind declare i32 @rand() local_unnamed_addr #1 ; Function Attrs: argmemonly nounwind willreturn declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture) #3 attributes #0 = { noinline norecurse nounwind uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="none" "less-precise-fpmad"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #1 = { nounwind "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="none" "less-precise-fpmad"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #2 = { norecurse nounwind uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="none" "less-precise-fpmad"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #3 = { argmemonly nounwind willreturn } attributes #4 = { nounwind } !llvm.ident = !{!0} !llvm.module.flags = !{!1} !0 = !{!"clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)"} !1 = !{i32 1, !"wchar_size", i32 4} !2 = !{!3, !3, i64 0} !3 = !{!"any pointer", !4, i64 0} !4 = !{!"omnipotent char", !5, i64 0} !5 = !{!"Simple C++ TBAA"} !6 = !{!4, !4, i64 0}
package io.unlaunch; import io.unlaunch.exceptions.UnlaunchHttpException; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class UnlaunchGenericRestWrapper { private final Client client; private final WebTarget apiWebTarget; private static final Logger logger = LoggerFactory.getLogger(UnlaunchRestWrapper.class); UnlaunchGenericRestWrapper(String host, String path, long connectionTimeoutMs, long readTimeoutMs) { ClientConfig configuration = new ClientConfig(); configuration.property(ClientProperties.CONNECT_TIMEOUT, (int)connectionTimeoutMs); configuration.property(ClientProperties.READ_TIMEOUT, (int)readTimeoutMs); client = ClientBuilder.newClient(configuration); apiWebTarget = client.target(host).path(path); } public static UnlaunchGenericRestWrapper create( String host, String apiPath, long connectionTimeoutMs, long readTimeoutMs) { return new UnlaunchGenericRestWrapper(host, apiPath, connectionTimeoutMs, readTimeoutMs); } public Response get() { try { Invocation.Builder invocationBuilder = apiWebTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get(); return response; } catch ( ProcessingException | WebApplicationException ex) { logger.warn("unable to perform HTTP GET action on URL {}. Error was: {}", apiWebTarget.getUri(), ex.getMessage()); throw new UnlaunchHttpException("unable to perform get action on entity", ex); } } @Override public String toString() { return "UnlaunchRestWrapper for URI: " + apiWebTarget.getUri(); } }
package ru.pasha__kun.klisp import ru.pasha__kun.klisp.types.* import java.util.HashMap internal fun macroExpand(args: Map<String, LispValue>, body: LispValue): LispValue = when(body){ is LispName -> args.getOrDefault(body.value, body) is LispList -> LispList().apply { addAll(body.map { macroExpand(args, it) }) } else -> body } internal fun mapArgs(names: LispArray, args: LispList): Map<String, LispValue> { val v = names.size val a = args.size - 1 if (v > a) throw RuntimeException("Not enough arguments!") val r = HashMap<String, LispValue>() for (i in 0..v - 2) { r[names[i].run { when (this) { is LispString -> this.value is LispName -> this.value is LispKey -> this.value else -> throw RuntimeException("Bad argument name!") } }] = args[i + 1] } r[names[v - 1].run { when (this) { is LispString -> this.value is LispName -> this.value is LispKey -> this.value else -> throw RuntimeException("Bad argument name!") } }] = if (v < a) args.subList(v, a) as LispList else args[v] return r } inline fun<T> Iterable<T>.forEachFrom(index: Int, fn: (T)->Unit){ forEachIndexed { i, v -> if (i >= index) fn(v) } }
package xds import ( "fmt" "strings" "github.com/pkg/errors" mesh_proto "github.com/Kong/kuma/api/mesh/v1alpha1" mesh_core "github.com/Kong/kuma/pkg/core/resources/apis/mesh" core_model "github.com/Kong/kuma/pkg/core/resources/model" envoy_core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" ) type ProxyId struct { Mesh string Name string } func (id *ProxyId) String() string { return fmt.Sprintf("%s.%s", id.Mesh, id.Name) } // ServiceName is a convenience type alias to clarify the meaning of string value. type ServiceName = string // RouteMap holds the most specific TrafficRoute for each outbound interface of a Dataplane. type RouteMap map[ServiceName]*mesh_core.TrafficRouteResource // TagSelectorSet is a set of unique TagSelectors. type TagSelectorSet []mesh_proto.TagSelector // DestinationMap holds a set of selectors for all reachable Dataplanes grouped by service name. type DestinationMap map[ServiceName]TagSelectorSet // Endpoint holds routing-related information about a single endpoint. type Endpoint struct { Target string Port uint32 Tags map[string]string } // EndpointList is a list of Endpoints with convenience methods. type EndpointList []Endpoint // EndpointMap holds routing-related information about a set of endpoints grouped by service name. type EndpointMap map[ServiceName][]Endpoint // LogMap holds the most specific TrafficLog for each outbound interface of a Dataplane. type LogMap map[ServiceName]*mesh_proto.LoggingBackend // HealthCheckMap holds the most specific HealthCheck for each reachable service. type HealthCheckMap map[ServiceName]*mesh_core.HealthCheckResource // FaultInjectionMap holds the most specific FaultInjectionResource for each InboundInterface type FaultInjectionMap map[mesh_proto.InboundInterface]*mesh_proto.FaultInjection // TrafficPermissionMap holds the most specific TrafficPermissionResource for each InboundInterface type TrafficPermissionMap map[mesh_proto.InboundInterface]*mesh_core.TrafficPermissionResource type Proxy struct { Id ProxyId Dataplane *mesh_core.DataplaneResource TrafficPermissions TrafficPermissionMap Logs LogMap TrafficRoutes RouteMap OutboundSelectors DestinationMap OutboundTargets EndpointMap HealthChecks HealthCheckMap TrafficTrace *mesh_core.TrafficTraceResource TracingBackend *mesh_proto.TracingBackend Metadata *DataplaneMetadata FaultInjections FaultInjectionMap } func (s TagSelectorSet) Add(new mesh_proto.TagSelector) TagSelectorSet { for _, old := range s { if new.Equal(old) { return s } } return append(s, new) } func (l EndpointList) Filter(selector mesh_proto.TagSelector) EndpointList { var endpoints EndpointList for _, endpoint := range l { if selector.Matches(endpoint.Tags) { endpoints = append(endpoints, endpoint) } } return endpoints } func BuildProxyId(mesh, name string, more ...string) (*ProxyId, error) { id := strings.Join(append([]string{mesh, name}, more...), ".") return ParseProxyIdFromString(id) } func ParseProxyId(node *envoy_core.Node) (*ProxyId, error) { if node == nil { return nil, errors.Errorf("Envoy node must not be nil") } return ParseProxyIdFromString(node.Id) } func ParseProxyIdFromString(id string) (*ProxyId, error) { parts := strings.SplitN(id, ".", 2) mesh := parts[0] if mesh == "" { return nil, errors.New("mesh must not be empty") } if len(parts) < 2 { return nil, errors.New("the name should be provided after the dot") } name := parts[1] if name == "" { return nil, errors.New("name must not be empty") } return &ProxyId{ Mesh: mesh, Name: name, }, nil } func (id *ProxyId) ToResourceKey() core_model.ResourceKey { return core_model.ResourceKey{ Name: id.Name, Mesh: id.Mesh, } } func FromResourceKey(key core_model.ResourceKey) ProxyId { return ProxyId{ Mesh: key.Mesh, Name: key.Name, } }
/* * Copyright (c) 2016. See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mbrlabs.mundus.editor.ui.widgets import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.utils.Align import com.kotcrab.vis.ui.widget.VisTable /** * @author Marcus Brummer * @version 03-01-2016 */ open class Toolbar { val root = VisTable() private val left = VisTable() private val right = VisTable() init { root.setBackground("menu-bg") root.align(Align.left or Align.center) left.left().top() root.add(left).pad(2f).expandX().fillX() right.right().top() root.add(right).pad(2f).expandX().fillX().row() root.addSeparator().pad(0f).height(2f).colspan(2) } fun addItem(actor: Actor, addLeft: Boolean) { if (addLeft) { left.add(actor) } else { right.add(actor) } } fun addSeperator(addLeft: Boolean) { if (addLeft) { left.addSeparator(true) } else { right.addSeparator(true) } } }