repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
GWT-M3O-TEST/m3o
examples/go-function/example.go
package example import ( "encoding/json" "io/ioutil" "net/http" ) type request struct { Name string `json:"name"` } type response struct { Message string `json:"message"` } func Helloworld(w http.ResponseWriter, r *http.Request) { message := "Hello world!" ct := r.Header.Get("Content-Type") if ct == "application/json" { b, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(500) return } var req request if err := json.Unmarshal(b, &req); err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) return } if len(req.Name) > 0 { message = "Hello " + req.Name + "!" } if err := json.NewEncoder(w).Encode(response{Message: message}); err != nil { w.WriteHeader(500) return } return } r.ParseForm() name := r.Form.Get("name") if len(name) > 0 { message = "Hello " + name + "!" } w.Write([]byte(message)) }
boybeak/WowPaper
app/src/main/java/com/nulldreams/wowpaper/adapter/holder/FooterHolder.java
<reponame>boybeak/WowPaper package com.nulldreams.wowpaper.adapter.holder; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.text.TextUtils; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.nulldreams.adapter.AbsViewHolder; import com.nulldreams.adapter.DelegateAdapter; import com.nulldreams.wowpaper.R; import com.nulldreams.wowpaper.adapter.delegate.FooterDelegate; /** * Created by boybe on 2017/3/22. */ public class FooterHolder extends AbsViewHolder<FooterDelegate> { private TextView msgTv; private ProgressBar progressBar; public FooterHolder(View itemView) { super(itemView); msgTv = (TextView)findViewById(R.id.footer_message); progressBar = (ProgressBar)findViewById(R.id.footer_progress); } @Override public void onBindView(Context context, FooterDelegate footerDelegate, int position, DelegateAdapter adapter) { switch (footerDelegate.getState()) { case FooterDelegate.STATE_NONE: msgTv.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); msgTv.setText(null); break; case FooterDelegate.STATE_LOADING: msgTv.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); break; case FooterDelegate.STATE_SUCCESS: msgTv.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); msgTv.setText(R.string.text_success); break; case FooterDelegate.STATE_FAILED: msgTv.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); msgTv.setText(R.string.text_failed); break; } if (!TextUtils.isEmpty(footerDelegate.getStaticMsg())) { msgTv.setText(footerDelegate.getStaticMsg()); } } }
lauracristinaes/aula-java
hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToStdout.java
<reponame>lauracristinaes/aula-java /* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.tool.schema.internal.exec; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import org.hibernate.internal.build.AllowSysOut; import org.hibernate.tool.schema.spi.SchemaManagementException; /** * @author <NAME> */ public class ScriptTargetOutputToStdout extends AbstractScriptTargetOutput { private Writer writer; @Override protected Writer writer() { if ( writer == null ) { throw new SchemaManagementException( "Illegal state : writer null - not prepared" ); } return writer; } @Override @AllowSysOut public void prepare() { super.prepare(); this.writer = new OutputStreamWriter( System.out ); } @Override public void accept(String command) { super.accept( command ); } @Override public void release() { if ( writer != null ) { try { writer.close(); } catch (IOException e) { throw new SchemaManagementException( "Unable to close file writer : " + e.toString() ); } finally { writer = null; } } } }
alesmenzel/churchill
packages/stream/stream.js
const Transport = require("@churchill/transport"); const { ChurchillError } = require("@churchill/utils"); const toText = require("./format"); const E_BACKPRESSURE = "Backpressure: your logging destination buffer is full and messages will be lost, this usually means that your logging destination cannot keep up or is too slow"; /** * @typedef {import("stream").Writable} Writable * @typedef {import("@churchill/core")} Logger */ class Stream extends Transport { /** * Synchronous logging to a stream * @param {Object} opts Options * @param {Function} [opts.format] Formatting function * @param {String} [opts.maxLevel] Max logging level * @param {Writable} opts.stream Stream */ constructor(opts) { super({ ...opts, format: opts.format || toText }); const { stream } = opts; if (!stream) { throw new Error("You must provide a stream, did you forget to pass options.stream?"); } this.writable = true; this.stream = stream; this.stream.on("error", err => { this.emit("error", err); }); this.stream.on("drain", () => { this.writable = true; }); } /** * Log a Message * @param {Object} info Message * @param {*} output (Optional) Output of the global formatting function * @param {Logger} logger Logger */ async log(info, output, logger) { const out = this.format(info, output, logger); if (!this.writable) { this.emit("error", new ChurchillError(E_BACKPRESSURE, { info, out })); return null; } const canWrite = this.stream.write(out); if (!canWrite) { this.writable = false; } return null; } } /** * Create a stream transport * @param {Object} opts Options * @param {Function} [opts.format] Formatting function * @param {String} [opts.maxLevel] Max logging level * @param {Writable} opts.stream Stream */ Stream.create = opts => { return new Stream(opts); }; module.exports = Stream;
VINichkov/JobsGalore
db/tools/create_company.rb
require 'csv' require 'json' arr_company=[] CSV.open("company.csv") do |file| file.each do |str| arr_company<<str[0] if str[0]!=nil end end words = [] File.open("words.txt") do |file| words=file.readlines end puts words arr = [] arr_company.each do |elem| recrutmentagency = [false, false, false, true].sample description ='' Random.rand(50).times do description += words[Random.rand(words.size)].delete("\n")+' ' end arr << {"name":elem,"size":"nil","location":"nil","recrutmentagency": recrutmentagency,"description":description} end File.open("3Company.json",'w') do |output_file| output_file.puts JSON.generate Hash["Company",arr] end
alienfast/gulp-asset-pipeline
src/ruby/rails.js
<reponame>alienfast/gulp-asset-pipeline<filename>src/ruby/rails.js import Ruby from './ruby' import path from 'path' import glob from 'glob' import jsonfile from 'jsonfile' import console from 'console' import File from '../util/file' import Base from '../base' const Files = { CACHE: `.gulp-pipeline-rails.json`, GEM_LOCK: `Gemfile.lock` } const Rails = class extends Base { constructor(config = {debug: false}) { // We need a rails app to run our rails script runner. // Since this project could be a rails engine, find a rails app somewhere in or under the cwd. let entries = glob.sync('**/bin/rails', {realpath: true}) if (!entries || entries.length <= 0) { throw new Error(`Unable to find Rails application directory based on existence of 'bin/rails'`) } if (entries.length > 1) { throw new Error(`railsAppCwd() should only find one rails application but found ${entries}`) } let cwd = path.join(entries[0], '../..') super({cwd: cwd}, config) } enumerateEngines() { let results = this.exec(`${Ruby.localPath('railsRunner.sh')} ${Ruby.localPath('enumerateEngines.rb')}`) // run via spring with zero results: // status: 0, // stdout: '{}\n', // stderr: 'Running via Spring preloader in process 95498\n', return JSON.parse(results.stdout) } /** * Return the baseDirectories to search for assets such as images. In rails, this means * enumerating rails engines and collecting their root paths. This is a lengthy process * because you have to startup a rails environment to enumerate the engines, so we cache * the baseDirectories in a file and compare it to the Gemfile.lock's modified time. If * the Gemfile.lock changes, we throw out the cache, enumerate the engines again and write * a new cache file. * * @returns {{baseDirectories: string[]}} */ baseDirectories() { if (!File.modified(Files.GEM_LOCK, Files.CACHE)) { this.log(`Gemfile.lock is unchanged, using baseDirectories cache.`) return jsonfile.readFileSync(Files.CACHE) } else { this.log(`Generating baseDirectories and rails engines cache...`) File.delete(Files.CACHE, true) let engines = this.enumerateEngines() console.log(this.dump(engines)) // eslint-disable-line no-console let baseDirectories = ['./'] for (let key of Object.keys(engines)) { baseDirectories.push(engines[key]) } this.log(`Writing baseDirectories cache...`) let result = {baseDirectories: baseDirectories} jsonfile.writeFileSync(Files.CACHE, result, {spaces: 2}) return result } } } export default Rails
Bhuvanesh1208/ruby2.6.1
msys64/mingw64/x86_64-w64-mingw32/include/d2d1effects.h
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef _D2D1_EFFECTS_ #define _D2D1_EFFECTS_ #include <winapifamily.h> #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) DEFINE_GUID(CLSID_D2D12DAffineTransform, 0x6aa97485,0x6354,0x4cfc,0x90,0x8c,0xe4,0xa7,0x4f,0x62,0xc9,0x6c); DEFINE_GUID(CLSID_D2D13DPerspectiveTransform, 0xc2844d0b,0x3d86,0x46e7,0x85,0xba,0x52,0x6c,0x92,0x40,0xf3,0xfb); DEFINE_GUID(CLSID_D2D13DTransform, 0xe8467b04,0xec61,0x4b8a,0xb5,0xde,0xd4,0xd7,0x3d,0xeb,0xea,0x5a); DEFINE_GUID(CLSID_D2D1ArithmeticComposite, 0xfc151437,0x049a,0x4784,0xa2,0x4a,0xf1,0xc4,0xda,0xf2,0x09,0x87); DEFINE_GUID(CLSID_D2D1Atlas, 0x913e2be4,0xfdcf,0x4fe2,0xa5,0xf0,0x24,0x54,0xf1,0x4f,0xf4,0x8); DEFINE_GUID(CLSID_D2D1BitmapSource, 0x5fb6c24d,0xc6dd,0x4231,0x94,0x04,0x50,0xf4,0xd5,0xc3,0x25,0x2d); DEFINE_GUID(CLSID_D2D1Blend, 0x81c5b77b,0x13f8,0x4cdd,0xad,0x20,0xc8,0x90,0x54,0x7a,0xc6,0x5d); DEFINE_GUID(CLSID_D2D1Border, 0x2a2d49c0,0x4acf,0x43c7,0x8c,0x6a,0x7c,0x4a,0x27,0x87,0x4d,0x27); DEFINE_GUID(CLSID_D2D1Brightness, 0x8cea8d1e,0x77b0,0x4986,0xb3,0xb9,0x2f,0x0c,0x0e,0xae,0x78,0x87); DEFINE_GUID(CLSID_D2D1ColorManagement, 0x1a28524c,0xfdd6,0x4aa4,0xae,0x8f,0x83,0x7e,0xb8,0x26,0x7b,0x37); DEFINE_GUID(CLSID_D2D1ColorMatrix, 0x921f03d6,0x641c,0x47df,0x85,0x2d,0xb4,0xbb,0x61,0x53,0xae,0x11); DEFINE_GUID(CLSID_D2D1Composite, 0x48fc9f51,0xf6ac,0x48f1,0x8b,0x58,0x3b,0x28,0xac,0x46,0xf7,0x6d); DEFINE_GUID(CLSID_D2D1ConvolveMatrix, 0x407f8c08,0x5533,0x4331,0xa3,0x41,0x23,0xcc,0x38,0x77,0x84,0x3e); DEFINE_GUID(CLSID_D2D1Crop, 0xe23f7110,0x0e9a,0x4324,0xaf,0x47,0x6a,0x2c,0x0c,0x46,0xf3,0x5b); DEFINE_GUID(CLSID_D2D1DirectionalBlur, 0x174319a6,0x58e9,0x49b2,0xbb,0x63,0xca,0xf2,0xc8,0x11,0xa3,0xdb); DEFINE_GUID(CLSID_D2D1DiscreteTransfer, 0x90866fcd,0x488e,0x454b,0xaf,0x06,0xe5,0x04,0x1b,0x66,0xc3,0x6c); DEFINE_GUID(CLSID_D2D1DisplacementMap, 0xedc48364,0x0417,0x4111,0x94,0x50,0x43,0x84,0x5f,0xa9,0xf8,0x90); DEFINE_GUID(CLSID_D2D1DistantDiffuse, 0x3e7efd62,0xa32d,0x46d4,0xa8,0x3c,0x52,0x78,0x88,0x9a,0xc9,0x54); DEFINE_GUID(CLSID_D2D1DistantSpecular, 0x428c1ee5,0x77b8,0x4450,0x8a,0xb5,0x72,0x21,0x9c,0x21,0xab,0xda); DEFINE_GUID(CLSID_D2D1DpiCompensation, 0x6c26c5c7,0x34e0,0x46fc,0x9c,0xfd,0xe5,0x82,0x37,0x6, 0xe2,0x28); DEFINE_GUID(CLSID_D2D1Flood, 0x61c23c20,0xae69,0x4d8e,0x94,0xcf,0x50,0x07,0x8d,0xf6,0x38,0xf2); DEFINE_GUID(CLSID_D2D1GammaTransfer, 0x409444c4,0xc419,0x41a0,0xb0,0xc1,0x8c,0xd0,0xc0,0xa1,0x8e,0x42); DEFINE_GUID(CLSID_D2D1GaussianBlur, 0x1feb6d69,0x2fe6,0x4ac9,0x8c,0x58,0x1d,0x7f,0x93,0xe7,0xa6,0xa5); DEFINE_GUID(CLSID_D2D1Scale, 0x9daf9369,0x3846,0x4d0e,0xa4,0x4e,0xc, 0x60,0x79,0x34,0xa5,0xd7); DEFINE_GUID(CLSID_D2D1Histogram, 0x881db7d0,0xf7ee,0x4d4d,0xa6,0xd2,0x46,0x97,0xac,0xc6,0x6e,0xe8); DEFINE_GUID(CLSID_D2D1HueRotation, 0x0f4458ec,0x4b32,0x491b,0x9e,0x85,0xbd,0x73,0xf4,0x4d,0x3e,0xb6); DEFINE_GUID(CLSID_D2D1LinearTransfer, 0xad47c8fd,0x63ef,0x4acc,0x9b,0x51,0x67,0x97,0x9c,0x03,0x6c,0x06); DEFINE_GUID(CLSID_D2D1LuminanceToAlpha, 0x41251ab7,0x0beb,0x46f8,0x9d,0xa7,0x59,0xe9,0x3f,0xcc,0xe5,0xde); DEFINE_GUID(CLSID_D2D1Morphology, 0xeae6c40d,0x626a,0x4c2d,0xbf,0xcb,0x39,0x10,0x01,0xab,0xe2,0x02); DEFINE_GUID(CLSID_D2D1OpacityMetadata, 0x6c53006a,0x4450,0x4199,0xaa,0x5b,0xad,0x16,0x56,0xfe,0xce,0x5e); DEFINE_GUID(CLSID_D2D1PointDiffuse, 0xb9e303c3,0xc08c,0x4f91,0x8b,0x7b,0x38,0x65,0x6b,0xc4,0x8c,0x20); DEFINE_GUID(CLSID_D2D1PointSpecular, 0x09c3ca26,0x3ae2,0x4f09,0x9e,0xbc,0xed,0x38,0x65,0xd5,0x3f,0x22); DEFINE_GUID(CLSID_D2D1Premultiply, 0x06eab419,0xdeed,0x4018,0x80,0xd2,0x3e,0x1d,0x47,0x1a,0xde,0xb2); DEFINE_GUID(CLSID_D2D1Saturation, 0x5cb2d9cf,0x327d,0x459f,0xa0,0xce,0x40,0xc0,0xb2,0x08,0x6b,0xf7); DEFINE_GUID(CLSID_D2D1Shadow, 0xc67ea361,0x1863,0x4e69,0x89,0xdb,0x69,0x5d,0x3e,0x9a,0x5b,0x6b); DEFINE_GUID(CLSID_D2D1SpotDiffuse, 0x818a1105,0x7932,0x44f4,0xaa,0x86,0x08,0xae,0x7b,0x2f,0x2c,0x93); DEFINE_GUID(CLSID_D2D1SpotSpecular, 0xedae421e,0x7654,0x4a37,0x9d,0xb8,0x71,0xac,0xc1,0xbe,0xb3,0xc1); DEFINE_GUID(CLSID_D2D1TableTransfer, 0x5bf818c3,0x5e43,0x48cb,0xb6,0x31,0x86,0x83,0x96,0xd6,0xa1,0xd4); DEFINE_GUID(CLSID_D2D1Tile, 0xb0784138,0x3b76,0x4bc5,0xb1,0x3b,0x0f,0xa2,0xad,0x02,0x65,0x9f); DEFINE_GUID(CLSID_D2D1Turbulence, 0xcf2bb6ae,0x889a,0x4ad7,0xba,0x29,0xa2,0xfd,0x73,0x2c,0x9f,0xc9); DEFINE_GUID(CLSID_D2D1UnPremultiply, 0xfb9ac489,0xad8d,0x41ed,0x99,0x99,0xbb,0x63,0x47,0xd1,0x10,0xf7); typedef enum D2D1_SHADOW_PROP { D2D1_SHADOW_PROP_BLUR_STANDARD_DEVIATION = 0, D2D1_SHADOW_PROP_COLOR = 1, D2D1_SHADOW_PROP_OPTIMIZATION = 2, D2D1_SHADOW_PROP_FORCE_DWORD = 0xffffffff } D2D1_SHADOW_PROP; typedef enum D2D1_2DAFFINETRANSFORM_PROP { D2D1_2DAFFINETRANSFORM_PROP_INTERPOLATION_MODE = 0, D2D1_2DAFFINETRANSFORM_PROP_BORDER_MODE = 1, D2D1_2DAFFINETRANSFORM_PROP_TRANSFORM_MATRIX = 2, D2D1_2DAFFINETRANSFORM_PROP_SHARPNESS = 3, D2D1_2DAFFINETRANSFORM_PROP_FORCE_DWORD = 0xffffffff } D2D1_2DAFFINETRANSFORM_PROP; typedef enum D2D1_COMPOSITE_PROP { D2D1_COMPOSITE_PROP_MODE = 0, D2D1_COMPOSITE_PROP_FORCE_DWORD = 0xffffffff } D2D1_COMPOSITE_PROP; typedef enum D2D1_CHANNEL_SELECTOR { D2D1_CHANNEL_SELECTOR_R = 0, D2D1_CHANNEL_SELECTOR_G = 1, D2D1_CHANNEL_SELECTOR_B = 2, D2D1_CHANNEL_SELECTOR_A = 3, D2D1_CHANNEL_SELECTOR_FORCE_DWORD = 0xffffffff } D2D1_CHANNEL_SELECTOR; typedef enum D2D1_BORDER_MODE { D2D1_BORDER_MODE_SOFT = 0, D2D1_BORDER_MODE_HARD = 1, D2D1_BORDER_MODE_FORCE_DWORD = 0xffffffff } D2D1_BORDER_MODE; typedef enum D2D1_COLORMATRIX_PROP { D2D1_COLORMATRIX_PROP_COLOR_MATRIX = 0, D2D1_COLORMATRIX_PROP_ALPHA_MODE = 1, D2D1_COLORMATRIX_PROP_CLAMP_OUTPUT = 2, D2D1_COLORMATRIX_PROP_FORCE_DWORD = 0xffffffff } D2D1_COLORMATRIX_PROP; typedef enum D2D1_COLORMATRIX_ALPHA_MODE { D2D1_COLORMATRIX_ALPHA_MODE_PREMULTIPLIED = 1, D2D1_COLORMATRIX_ALPHA_MODE_STRAIGHT = 2, D2D1_COLORMATRIX_ALPHA_MODE_FORCE_DWORD = 0xffffffff } D2D1_COLORMATRIX_ALPHA_MODE; typedef enum D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE { D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_NEAREST_NEIGHBOR = 0, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_LINEAR = 1, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_CUBIC = 2, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_MULTI_SAMPLE_LINEAR = 3, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_ANISOTROPIC = 4, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC = 5, D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE_FORCE_DWORD = 0xffffffff } D2D1_2DAFFINETRANSFORM_INTERPOLATION_MODE; typedef enum D2D1_BLEND_PROP { D2D1_BLEND_PROP_MODE = 0, D2D1_BLEND_PROP_FORCE_DWORD = 0xffffffff } D2D1_BLEND_PROP; typedef enum D2D1_BLEND_MODE { D2D1_BLEND_MODE_MULTIPLY = 0, D2D1_BLEND_MODE_SCREEN = 1, D2D1_BLEND_MODE_DARKEN = 2, D2D1_BLEND_MODE_LIGHTEN = 3, D2D1_BLEND_MODE_DISSOLVE = 4, D2D1_BLEND_MODE_COLOR_BURN = 5, D2D1_BLEND_MODE_LINEAR_BURN = 6, D2D1_BLEND_MODE_DARKER_COLOR = 7, D2D1_BLEND_MODE_LIGHTER_COLOR = 8, D2D1_BLEND_MODE_COLOR_DODGE = 9, D2D1_BLEND_MODE_LINEAR_DODGE = 10, D2D1_BLEND_MODE_OVERLAY = 11, D2D1_BLEND_MODE_SOFT_LIGHT = 12, D2D1_BLEND_MODE_HARD_LIGHT = 13, D2D1_BLEND_MODE_VIVID_LIGHT = 14, D2D1_BLEND_MODE_LINEAR_LIGHT = 15, D2D1_BLEND_MODE_PIN_LIGHT = 16, D2D1_BLEND_MODE_HARD_MIX = 17, D2D1_BLEND_MODE_DIFFERENCE = 18, D2D1_BLEND_MODE_EXCLUSION = 19, D2D1_BLEND_MODE_HUE = 20, D2D1_BLEND_MODE_SATURATION = 21, D2D1_BLEND_MODE_COLOR = 22, D2D1_BLEND_MODE_LUMINOSITY = 23, D2D1_BLEND_MODE_SUBTRACT = 24, D2D1_BLEND_MODE_DIVISION = 25, D2D1_BLEND_MODE_FORCE_DWORD = 0xffffffff } D2D1_BLEND_MODE; typedef enum D2D1_MORPHOLOGY_PROP { D2D1_MORPHOLOGY_PROP_MODE = 0, D2D1_MORPHOLOGY_PROP_WIDTH = 1, D2D1_MORPHOLOGY_PROP_HEIGHT = 2, D2D1_MORPHOLOGY_PROP_FORCE_DWORD = 0xffffffff } D2D1_MORPHOLOGY_PROP; typedef enum D2D1_FLOOD_PROP { D2D1_FLOOD_PROP_COLOR = 0, D2D1_FLOOD_PROP_FORCE_DWORD = 0xffffffff } D2D1_FLOOD_PROP; typedef enum D2D1_MORPHOLOGY_MODE { D2D1_MORPHOLOGY_MODE_ERODE = 0, D2D1_MORPHOLOGY_MODE_DILATE = 1, D2D1_MORPHOLOGY_MODE_FORCE_DWORD = 0xffffffff } D2D1_MORPHOLOGY_MODE; typedef enum D2D1_TURBULENCE_NOISE { D2D1_TURBULENCE_NOISE_FRACTAL_SUM = 0, D2D1_TURBULENCE_NOISE_TURBULENCE = 1, D2D1_TURBULENCE_NOISE_FORCE_DWORD = 0xffffffff } D2D1_TURBULENCE_NOISE; typedef enum D2D1_DISPLACEMENTMAP_PROP { D2D1_DISPLACEMENTMAP_PROP_SCALE = 0, D2D1_DISPLACEMENTMAP_PROP_X_CHANNEL_SELECT = 1, D2D1_DISPLACEMENTMAP_PROP_Y_CHANNEL_SELECT = 2, D2D1_DISPLACEMENTMAP_PROP_FORCE_DWORD = 0xffffffff } D2D1_DISPLACEMENTMAP_PROP; typedef enum D2D1_TURBULENCE_PROP { D2D1_TURBULENCE_PROP_OFFSET = 0, D2D1_TURBULENCE_PROP_SIZE = 1, D2D1_TURBULENCE_PROP_BASE_FREQUENCY = 2, D2D1_TURBULENCE_PROP_NUM_OCTAVES = 3, D2D1_TURBULENCE_PROP_SEED = 4, D2D1_TURBULENCE_PROP_NOISE = 5, D2D1_TURBULENCE_PROP_STITCHABLE = 6, D2D1_TURBULENCE_PROP_FORCE_DWORD = 0xffffffff } D2D1_TURBULENCE_PROP; typedef enum D2D1_ARITHMETICCOMPOSITE_PROP { D2D1_ARITHMETICCOMPOSITE_PROP_COEFFICIENTS = 0, D2D1_ARITHMETICCOMPOSITE_PROP_CLAMP_OUTPUT = 1, D2D1_ARITHMETICCOMPOSITE_PROP_FORCE_DWORD = 0xffffffff } D2D1_ARITHMETICCOMPOSITE_PROP; typedef enum D2D1_CROP_PROP { D2D1_CROP_PROP_RECT = 0, D2D1_CROP_PROP_BORDER_MODE = 1, D2D1_CROP_PROP_FORCE_DWORD = 0xffffffff } D2D1_CROP_PROP; typedef enum D2D1_GAUSSIANBLUR_PROP { D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION = 0, D2D1_GAUSSIANBLUR_PROP_OPTIMIZATION = 1, D2D1_GAUSSIANBLUR_PROP_BORDER_MODE = 2, D2D1_GAUSSIANBLUR_PROP_FORCE_DWORD = 0xffffffff } D2D1_GAUSSIANBLUR_PROP; typedef enum D2D1_DIRECTIONALBLUR_PROP { D2D1_DIRECTIONALBLUR_PROP_STANDARD_DEVIATION = 0, D2D1_DIRECTIONALBLUR_PROP_ANGLE = 1, D2D1_DIRECTIONALBLUR_PROP_OPTIMIZATION = 2, D2D1_DIRECTIONALBLUR_PROP_BORDER_MODE = 3, D2D1_DIRECTIONALBLUR_PROP_FORCE_DWORD = 0xffffffff } D2D1_DIRECTIONALBLUR_PROP; typedef enum D2D1_SPOTDIFFUSE_PROP { D2D1_SPOTDIFFUSE_PROP_LIGHT_POSITION = 0, D2D1_SPOTDIFFUSE_PROP_POINTS_AT = 1, D2D1_SPOTDIFFUSE_PROP_FOCUS = 2, D2D1_SPOTDIFFUSE_PROP_LIMITING_CONE_ANGLE = 3, D2D1_SPOTDIFFUSE_PROP_DIFFUSE_CONSTANT = 4, D2D1_SPOTDIFFUSE_PROP_SURFACE_SCALE = 5, D2D1_SPOTDIFFUSE_PROP_COLOR = 6, D2D1_SPOTDIFFUSE_PROP_KERNEL_UNIT_LENGTH = 7, D2D1_SPOTDIFFUSE_PROP_SCALE_MODE = 8, D2D1_SPOTDIFFUSE_PROP_FORCE_DWORD = 0xffffffff } D2D1_SPOTDIFFUSE_PROP; typedef enum D2D1_BORDER_PROP { D2D1_BORDER_PROP_EDGE_MODE_X = 0, D2D1_BORDER_PROP_EDGE_MODE_Y = 1, D2D1_BORDER_PROP_FORCE_DWORD = 0xffffffff } D2D1_BORDER_PROP; typedef enum D2D1_POINTDIFFUSE_PROP { D2D1_POINTDIFFUSE_PROP_LIGHT_POSITION = 0, D2D1_POINTDIFFUSE_PROP_DIFFUSE_CONSTANT = 1, D2D1_POINTDIFFUSE_PROP_SURFACE_SCALE = 2, D2D1_POINTDIFFUSE_PROP_COLOR = 3, D2D1_POINTDIFFUSE_PROP_KERNEL_UNIT_LENGTH = 4, D2D1_POINTDIFFUSE_PROP_SCALE_MODE = 5, D2D1_POINTDIFFUSE_PROP_FORCE_DWORD = 0xffffffff } D2D1_POINTDIFFUSE_PROP; typedef enum D2D1_TABLETRANSFER_PROP { D2D1_TABLETRANSFER_PROP_RED_TABLE = 0, D2D1_TABLETRANSFER_PROP_RED_DISABLE = 1, D2D1_TABLETRANSFER_PROP_GREEN_TABLE = 2, D2D1_TABLETRANSFER_PROP_GREEN_DISABLE = 3, D2D1_TABLETRANSFER_PROP_BLUE_TABLE = 4, D2D1_TABLETRANSFER_PROP_BLUE_DISABLE = 5, D2D1_TABLETRANSFER_PROP_ALPHA_TABLE = 6, D2D1_TABLETRANSFER_PROP_ALPHA_DISABLE = 7, D2D1_TABLETRANSFER_PROP_CLAMP_OUTPUT = 8, D2D1_TABLETRANSFER_PROP_FORCE_DWORD = 0xffffffff } D2D1_TABLETRANSFER_PROP; typedef enum D2D1_DISCRETETRANSFER_PROP { D2D1_DISCRETETRANSFER_PROP_RED_TABLE = 0, D2D1_DISCRETETRANSFER_PROP_RED_DISABLE = 1, D2D1_DISCRETETRANSFER_PROP_GREEN_TABLE = 2, D2D1_DISCRETETRANSFER_PROP_GREEN_DISABLE = 3, D2D1_DISCRETETRANSFER_PROP_BLUE_TABLE = 4, D2D1_DISCRETETRANSFER_PROP_BLUE_DISABLE = 5, D2D1_DISCRETETRANSFER_PROP_ALPHA_TABLE = 6, D2D1_DISCRETETRANSFER_PROP_ALPHA_DISABLE = 7, D2D1_DISCRETETRANSFER_PROP_CLAMP_OUTPUT = 8, D2D1_DISCRETETRANSFER_PROP_FORCE_DWORD = 0xffffffff } D2D1_DISCRETETRANSFER_PROP; typedef enum D2D1_LINEARTRANSFER_PROP { D2D1_LINEARTRANSFER_PROP_RED_Y_INTERCEPT = 0, D2D1_LINEARTRANSFER_PROP_RED_SLOPE = 1, D2D1_LINEARTRANSFER_PROP_RED_DISABLE = 2, D2D1_LINEARTRANSFER_PROP_GREEN_Y_INTERCEPT = 3, D2D1_LINEARTRANSFER_PROP_GREEN_SLOPE = 4, D2D1_LINEARTRANSFER_PROP_GREEN_DISABLE = 5, D2D1_LINEARTRANSFER_PROP_BLUE_Y_INTERCEPT = 6, D2D1_LINEARTRANSFER_PROP_BLUE_SLOPE = 7, D2D1_LINEARTRANSFER_PROP_BLUE_DISABLE = 8, D2D1_LINEARTRANSFER_PROP_ALPHA_Y_INTERCEPT = 9, D2D1_LINEARTRANSFER_PROP_ALPHA_SLOPE = 10, D2D1_LINEARTRANSFER_PROP_ALPHA_DISABLE = 11, D2D1_LINEARTRANSFER_PROP_CLAMP_OUTPUT = 12, D2D1_LINEARTRANSFER_PROP_FORCE_DWORD = 0xffffffff } D2D1_LINEARTRANSFER_PROP; typedef enum D2D1_GAMMATRANSFER_PROP { D2D1_GAMMATRANSFER_PROP_RED_AMPLITUDE = 0, D2D1_GAMMATRANSFER_PROP_RED_EXPONENT = 1, D2D1_GAMMATRANSFER_PROP_RED_OFFSET = 2, D2D1_GAMMATRANSFER_PROP_RED_DISABLE = 3, D2D1_GAMMATRANSFER_PROP_GREEN_AMPLITUDE = 4, D2D1_GAMMATRANSFER_PROP_GREEN_EXPONENT = 5, D2D1_GAMMATRANSFER_PROP_GREEN_OFFSET = 6, D2D1_GAMMATRANSFER_PROP_GREEN_DISABLE = 7, D2D1_GAMMATRANSFER_PROP_BLUE_AMPLITUDE = 8, D2D1_GAMMATRANSFER_PROP_BLUE_EXPONENT = 9, D2D1_GAMMATRANSFER_PROP_BLUE_OFFSET = 10, D2D1_GAMMATRANSFER_PROP_BLUE_DISABLE = 11, D2D1_GAMMATRANSFER_PROP_ALPHA_AMPLITUDE = 12, D2D1_GAMMATRANSFER_PROP_ALPHA_EXPONENT = 13, D2D1_GAMMATRANSFER_PROP_ALPHA_OFFSET = 14, D2D1_GAMMATRANSFER_PROP_ALPHA_DISABLE = 15, D2D1_GAMMATRANSFER_PROP_CLAMP_OUTPUT = 16, D2D1_GAMMATRANSFER_PROP_FORCE_DWORD = 0xffffffff } D2D1_GAMMATRANSFER_PROP; typedef enum D2D1_CONVOLVEMATRIX_PROP { D2D1_CONVOLVEMATRIX_PROP_KERNEL_UNIT_LENGTH = 0, D2D1_CONVOLVEMATRIX_PROP_SCALE_MODE = 1, D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_X = 2, D2D1_CONVOLVEMATRIX_PROP_KERNEL_SIZE_Y = 3, D2D1_CONVOLVEMATRIX_PROP_KERNEL_MATRIX = 4, D2D1_CONVOLVEMATRIX_PROP_DIVISOR = 5, D2D1_CONVOLVEMATRIX_PROP_BIAS = 6, D2D1_CONVOLVEMATRIX_PROP_KERNEL_OFFSET = 7, D2D1_CONVOLVEMATRIX_PROP_PRESERVE_ALPHA = 8, D2D1_CONVOLVEMATRIX_PROP_BORDER_MODE = 9, D2D1_CONVOLVEMATRIX_PROP_CLAMP_OUTPUT = 10, D2D1_CONVOLVEMATRIX_PROP_FORCE_DWORD = 0xffffffff } D2D1_CONVOLVEMATRIX_PROP; typedef enum D2D1_BORDER_EDGE_MODE { D2D1_BORDER_EDGE_MODE_CLAMP = 0, D2D1_BORDER_EDGE_MODE_WRAP = 1, D2D1_BORDER_EDGE_MODE_MIRROR = 2, D2D1_BORDER_EDGE_MODE_FORCE_DWORD = 0xffffffff } D2D1_BORDER_EDGE_MODE; typedef enum D2D1_DISTANTDIFFUSE_PROP { D2D1_DISTANTDIFFUSE_PROP_AZIMUTH = 0, D2D1_DISTANTDIFFUSE_PROP_ELEVATION = 1, D2D1_DISTANTDIFFUSE_PROP_DIFFUSE_CONSTANT = 2, D2D1_DISTANTDIFFUSE_PROP_SURFACE_SCALE = 3, D2D1_DISTANTDIFFUSE_PROP_COLOR = 4, D2D1_DISTANTDIFFUSE_PROP_KERNEL_UNIT_LENGTH = 5, D2D1_DISTANTDIFFUSE_PROP_SCALE_MODE = 6, D2D1_DISTANTDIFFUSE_PROP_FORCE_DWORD = 0xffffffff } D2D1_DISTANTDIFFUSE_PROP; typedef enum D2D1_POINTSPECULAR_PROP { D2D1_POINTSPECULAR_PROP_LIGHT_POSITION = 0, D2D1_POINTSPECULAR_PROP_SPECULAR_EXPONENT = 1, D2D1_POINTSPECULAR_PROP_SPECULAR_CONSTANT = 2, D2D1_POINTSPECULAR_PROP_SURFACE_SCALE = 3, D2D1_POINTSPECULAR_PROP_COLOR = 4, D2D1_POINTSPECULAR_PROP_KERNEL_UNIT_LENGTH = 5, D2D1_POINTSPECULAR_PROP_SCALE_MODE = 6, D2D1_POINTSPECULAR_PROP_FORCE_DWORD = 0xffffffff } D2D1_POINTSPECULAR_PROP; typedef enum D2D1_SPOTSPECULAR_PROP { D2D1_SPOTSPECULAR_PROP_LIGHT_POSITION = 0, D2D1_SPOTSPECULAR_PROP_POINTS_AT = 1, D2D1_SPOTSPECULAR_PROP_FOCUS = 2, D2D1_SPOTSPECULAR_PROP_LIMITING_CONE_ANGLE = 3, D2D1_SPOTSPECULAR_PROP_SPECULAR_EXPONENT = 4, D2D1_SPOTSPECULAR_PROP_SPECULAR_CONSTANT = 5, D2D1_SPOTSPECULAR_PROP_SURFACE_SCALE = 6, D2D1_SPOTSPECULAR_PROP_COLOR = 7, D2D1_SPOTSPECULAR_PROP_KERNEL_UNIT_LENGTH = 8, D2D1_SPOTSPECULAR_PROP_SCALE_MODE = 9, D2D1_SPOTSPECULAR_PROP_FORCE_DWORD = 0xffffffff } D2D1_SPOTSPECULAR_PROP; typedef enum D2D1_DISTANTSPECULAR_PROP { D2D1_DISTANTSPECULAR_PROP_AZIMUTH = 0, D2D1_DISTANTSPECULAR_PROP_ELEVATION = 1, D2D1_DISTANTSPECULAR_PROP_SPECULAR_EXPONENT = 2, D2D1_DISTANTSPECULAR_PROP_SPECULAR_CONSTANT = 3, D2D1_DISTANTSPECULAR_PROP_SURFACE_SCALE = 4, D2D1_DISTANTSPECULAR_PROP_COLOR = 5, D2D1_DISTANTSPECULAR_PROP_KERNEL_UNIT_LENGTH = 6, D2D1_DISTANTSPECULAR_PROP_SCALE_MODE = 7, D2D1_DISTANTSPECULAR_PROP_FORCE_DWORD = 0xffffffff } D2D1_DISTANTSPECULAR_PROP; typedef enum D2D1_TILE_PROP { D2D1_TILE_PROP_RECT = 0, D2D1_TILE_PROP_FORCE_DWORD = 0xffffffff } D2D1_TILE_PROP; #endif #endif /* _D2D1_EFFECTS_ */
michaelwillis/sfizz
tests/InterpolatorsT.cpp
<reponame>michaelwillis/sfizz<gh_stars>100-1000 // SPDX-License-Identifier: BSD-2-Clause // This code is part of the sfizz library and is licensed under a BSD 2-clause // license. You should have receive a LICENSE.md file along with the code. // If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz #include "sfizz/Interpolators.h" #include "catch2/catch.hpp" #include <array> #include <numeric> using namespace Catch::literals; TEST_CASE("[Interpolators] Sample at points") { std::array<float, 32> values; std::iota(values.begin(), values.end(), 0.0f); for (unsigned i = 2; i < values.size() - 2; ++i) { REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorLinear>(&values[i], 0.0f) == Approx(values[i]).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorHermite3>(&values[i], 0.0f) == Approx(values[i]).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorBspline3>(&values[i], 0.0f) == Approx(values[i]).margin(1e-2)); } } TEST_CASE("[Interpolators] Sample next") { std::array<float, 32> values; std::iota(values.begin(), values.end(), 0.0f); for (unsigned i = 2; i < values.size() - 2; ++i) { REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorLinear>(&values[i], 1.0f) == Approx(values[i + 1]).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorHermite3>(&values[i], 1.0f) == Approx(values[i + 1]).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorBspline3>(&values[i], 1.0f) == Approx(values[i + 1]).margin(1e-2)); } } TEST_CASE("[Interpolators] Straight line") { std::array<float, 32> values; std::iota(values.begin(), values.end(), 0.0f); for (unsigned i = 2; i < values.size() - 2; ++i) { REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorLinear>(&values[i], 0.5f) == Approx(values[i] + 0.5f).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorHermite3>(&values[i], 0.5f) == Approx(values[i] + 0.5f).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorBspline3>(&values[i], 0.5f) == Approx(values[i] + 0.5f).margin(1e-2)); } } TEST_CASE("[Interpolators] Squares") { std::array<float, 32> x; std::array<float, 32> y; for (unsigned i = 0; i < x.size(); ++i) { x[i] = static_cast<float>(i) / static_cast<float>(x.size()); y[i] = x[i] * x[i]; } for (unsigned i = 2; i < x.size() - 2; ++i) { const auto half_x = x[i] + 0.5f / static_cast<float>(x.size()); const auto expected = (half_x) * (half_x); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorHermite3>(&y[i], 0.5f) == Approx(expected).margin(1e-2)); REQUIRE(sfz::interpolate<sfz::InterpolatorModel::kInterpolatorBspline3>(&y[i], 0.5f) == Approx(expected).margin(1e-2)); } } template <class WS> static std::pair<double, double> windowedSincError(WS& ws, double step = 0.1, bool verbose = false) { size_t points = ws.getNumPoints(); double x1 = points / -2.0; double x2 = points / +2.0; double maxAbsErr = 0.0; double meanAbsErr = 0.0; //double meanSquareErr = 0.0; double x; size_t n; for (n = 0; (x = x1 + n * step) < x2; ++n) { double val = ws.getUnchecked(x); double ref = ws.getExact(x); double absErr = std::fabs(val - ref); maxAbsErr = std::max(maxAbsErr, absErr); meanAbsErr += absErr; //meanSquareErr += absErr * absErr; } meanAbsErr /= n; //meanSquareErr /= n; if (verbose) { std::cerr << "MaxAbsErr=" << maxAbsErr << " MeanAbsErr=" << meanAbsErr //<< " MeanSquareErr=" << meanSquareErr << " with Points=" << points << " TableSize=" << ws.getTableSize() << "\n"; } return { maxAbsErr, meanAbsErr }; } TEST_CASE("[Interpolators] Windowed sinc precision") { sfz::initializeInterpolators(); double maxAbsTolerance = 5e-2; double meanAbsTolerance = 1e-3; auto Check = [=](std::pair<double, double> maxAndMeanErr) { REQUIRE(maxAndMeanErr.first < maxAbsTolerance); REQUIRE(maxAndMeanErr.second < meanAbsTolerance); }; Check(windowedSincError(*sfz::SincInterpolatorTraits<8>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<12>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<16>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<24>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<36>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<48>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<60>::windowedSinc)); Check(windowedSincError(*sfz::SincInterpolatorTraits<72>::windowedSinc)); }
strategicallynicole/oaky
src/components/StrategicModel/index.js
<gh_stars>0 import { makeStyles, Theme } from "@material-ui/core" import * as React from "react" import Model from './model' import "./index.scss" export default function StrategicModel() { return ( <section className="items-center h-auto my-20"><div clasName=" items-center relative flex flex-wrap overflow-visible"> <div className="relative items-center w-full h-full overflow-visible model "> <Model /></div></div></section>) }
yanshen43/MCAT
XXmotif/src/ProgressBar.h
#ifndef _PROGRESS_BAR_H #define _PROGRESS_BAR_H #include <string> /** * Returns a string à la "[====== ] 75.0%" * with total length width. */ std::string progressBar(double curr, double total, int width); #endif
andy-zhangtao/ntci
ci-deployer/systemd/init.go
<gh_stars>1-10 package main import ( "os" "strings" "github.com/BurntSushi/toml" "github.com/coreos/go-systemd/dbus" "github.com/sirupsen/logrus" "ntci/ci-deployer/model/config" ) var c config.Configure var conn *dbus.Conn func init() { var err error switch strings.ToLower(os.Getenv("NTCI_DEPLOY_LOG_LEVEL")) { case "info": logrus.SetLevel(logrus.InfoLevel) case "warn": logrus.SetLevel(logrus.WarnLevel) case "error": logrus.SetLevel(logrus.ErrorLevel) default: logrus.SetLevel(logrus.DebugLevel) } if os.Getenv("NTCI_DEPLOY_CONFIG") != "" { if _, err := toml.DecodeFile(os.Getenv("NTCI_DEPLOY_CONFIG"), &c); err != nil { logrus.Fatal("Configure Init Failed! ") } } conn, err = dbus.New() if err != nil { logrus.Fatalf("Connect Systemd Error: %s", err.Error()) } if c.Port == 0 { c.Port = 80 } logrus.Debug("-------Configure-------") logrus.Debugf("Listen On: %d", c.Port) for key, value := range c.Units { logrus.Debugf("Name: %s Unit: %s", key, value) } logrus.Debug("-----------------------") }
kakts/c-unix-programming
ch07/popen-sample.c
/** * @file popen--sample.c * * コード例7.4 popenとpcloseの例 */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; char buf[1024]; // ls -l *c | wcのコマンドの実行結果を読み取れるストリームを取得 if ((fp = popen("ls -l ch07/*.c | wc", "r")) == NULL) { perror("popen"); exit(1); } fgets(buf, sizeof(buf), fp); printf("%s", buf); pclose(fp); }
powerhome/common-ios
Foundation/Classes/BLLocalization.h
// // BLLocalization.h // BowerLabsFoundation // // Created by <NAME> on 2013-01-24. // Copyright (c) 2013 Bower Labs Inc. All rights reserved. // #import <Foundation/Foundation.h> NSString* BLLocalizedPluralizedString(NSInteger c, NSString* none, NSString* singular, NSString* plural, ...);
sigurasg/ghidra
Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/ExternalMergerAddTest.java
/* ### * IP: GHIDRA * * 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 ghidra.app.merge.listing; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import ghidra.app.merge.ProgramMultiUserMergeManager; import ghidra.program.database.MergeProgram; import ghidra.program.database.MergeProgramModifier; import ghidra.program.model.data.*; import ghidra.program.model.lang.Register; import ghidra.program.model.listing.*; import ghidra.program.model.symbol.*; /** * Test the merge of the versioned program's listing. */ public class ExternalMergerAddTest extends AbstractExternalMergerTest { // *** NotepadMergeListingTest *** // External Refs // 01001000: op0 to ADVAPI32.DLL IsTextUnicode 77dc4f85 // 01001004: op0 to ADVAPI32.DLL RegCreateKeyW <KEY> // 01001008: op0 to ADVAPI32.DLL RegQueryValueExW 77db8078 // 0100100c: op0 to ADVAPI32.DLL RegSetValueExW 77db9348 // 01001010: op0 to ADVAPI32.DLL RegOpenKeyExA 77db82ac // 01001014: op0 to ADVAPI32.DLL RegQueryValueExA 77db858e // 01001018: op0 to ADVAPI32.DLL RegCloseKey <KEY> // 010010c0: op0 to KERNEL32.DLL LocalFree 77e9499c // 010010c4: op0 to KERNEL32.DLL GetProcAddress 77e9564b // 010013cc: no ref (has string) // 010013d8: no ref (has string) // 010013f0: no ref (has string) // Mem Refs // 01001a92: op0 to 01001370 DAT_01001370 DATA primary user // 01001abb: op0 to 01001ac1 LAB_01001ac1 CONDITIONAL_JUMP primary // 01001aec: op1 to 01001398 AddrTable010080c0Element36 DATA primary // 01001b5f: op0 to 010061e3 FUN_010061e3 UNCONDITIONAL_CALL primary // Stack Refs // 01001a55: op1 no ref to stack offset 0x10 // 01001af5: op0 to stack offset -0x24a // 01001b03: op1 to stack offset -0x24c // 01002125: op0 to stack offset -0x10 // 010024ea: op1 no ref to stack offset 0x10 // 01002510: op0 no ref to stack offset 0x8 // 01002a05: op0 no ref to stack offset -0x18 protected static final Reference ExternalReference = null; public ExternalMergerAddTest() { super(); } @Override protected ProgramMultiUserMergeManager createMergeManager(ProgramChangeSet resultChangeSet, ProgramChangeSet myChangeSet) { // NOTE: this makes the tests faster. If you need visual debugging, then make this true boolean showListingPanels = false; ProgramMultiUserMergeManager mergeManger = new ProgramMultiUserMergeManager(resultProgram, myProgram, originalProgram, latestProgram, resultChangeSet, myChangeSet, showListingPanels); return mergeManger; } @Test public void testAddSameExtLibraryNoConflict() throws Exception { final String libname = "advapi32.dll"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram program) throws Exception { program.addExternalLibraryName(libname, SourceType.IMPORTED); } @Override public void modifyPrivate(MergeProgram program) throws Exception { program.addExternalLibraryName(libname, SourceType.IMPORTED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertEquals(true, externalManager.contains(libname)); } @Test public void testAddSameExtLibraryDiffSourceConflict() throws Exception { final String libname = "advapi32.dll"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram program) throws Exception { program.addExternalLibraryName(libname, SourceType.IMPORTED); } @Override public void modifyPrivate(MergeProgram program) throws Exception { program.addExternalLibraryName(libname, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); // No conflict since external function merger only merges source type when merging name change. waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertEquals(true, externalManager.contains(libname)); } @Test public void testAddSameExtLabelNoAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Test public void testAddSameExtLabelSameAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address = "77db1020"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Test public void testAddSameExtLabelWithDiffAddressConflictKeepLatest() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address1 = "0x100"; final String address2 = "0x110"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address1, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address2, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); ExternalLocation externalLocation2 = externalManager.getUniqueExternalLocation(libname, label + "_conflict1"); assertNull(externalLocation2); } @Test public void testAddSameExtLabelWithDiffAddressConflictKeepMy() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address1 = "0x100"; final String address2 = "0x110"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address1, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address2, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); ExternalLocation externalLocation2 = externalManager.getUniqueExternalLocation(libname, label + "_conflict1"); assertNull(externalLocation2); } @Test public void testAddSameExtLabelWithDiffAddressConflictKeepBoth() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address1 = "0x100"; final String address2 = "0x110"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address1, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address2, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", KEEP_BOTH_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); List<ExternalLocation> externals = externalManager.getExternalLocations(libname, label); assertEquals(2, externals.size()); ExternalLocationIterator loc1It = externalManager.getExternalLocations(addr(address1)); assertTrue(loc1It.hasNext()); assertEquals(label, loc1It.next().getLabel()); assertTrue(!loc1It.hasNext()); ExternalLocationIterator loc2It = externalManager.getExternalLocations(addr(address2)); assertTrue(loc2It.hasNext()); assertEquals(label, loc2It.next().getLabel()); assertTrue(!loc2It.hasNext()); } @Test public void testAddLabelVsNamespaceAutoMerge() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.createNamespace(library, label, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); Symbol namespaceSymbol = getUniqueSymbol(program, label, library); assertNotNull(namespaceSymbol); assertEquals(SymbolType.NAMESPACE, namespaceSymbol.getSymbolType()); assertTrue(namespaceSymbol.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); SymbolTable symtab = resultProgram.getSymbolTable(); assertNotNull(symtab.getNamespace(label, externalLibrary)); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(label, externalLocation.getLabel()); } @Test public void testAddNamespaceVsLabelAutoMerge() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.createNamespace(library, label, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); assertNotNull(program.getSymbolTable().getNamespace(label, library)); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNotNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); SymbolTable symtab = resultProgram.getSymbolTable(); Namespace blue = symtab.getNamespace(label, externalLibrary); assertTrue(blue.isExternal()); } @Test public void testAddFunctionVsLabelAutoMerge() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); // chooseRadioButton(MY_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.FUNCTION, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation1 = externalManager.getExternalLocation(blue); assertNotNull(externalLocation1); assertEquals(libname, externalLocation1.getLibraryName()); assertEquals(label, externalLocation1.getLabel()); } @Test public void testAddLabelVsFunctionAutoMerge() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.FUNCTION, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation1 = externalManager.getExternalLocation(blue); assertNotNull(externalLocation1); assertEquals(libname, externalLocation1.getLibraryName()); assertEquals(label, externalLocation1.getLabel()); } @Test public void testAddFunctionVsDataLabelConflictKeepLatest() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, new WordDataType(), SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Function Versus Data Type Conflict", LATEST_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.FUNCTION, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation1 = externalManager.getExternalLocation(blue); assertEquals(libname, externalLocation1.getLibraryName()); assertEquals(label, externalLocation1.getLabel()); } @Test public void testAddFunctionVsDataLabelConflictKeepMy() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, new WordDataType(), SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Function Versus Data Type Conflict", MY_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.LABEL, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation1 = externalManager.getExternalLocation(blue); assertEquals(libname, externalLocation1.getLibraryName()); assertEquals(label, externalLocation1.getLabel()); } @Test public void testAddDataLabelVsFunctionConflictKeepLatest() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, new WordDataType(), SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Function Versus Data Type Conflict", LATEST_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.LABEL, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation = externalManager.getExternalLocation(blue); assertNotNull(externalLocation); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(label, externalLocation.getLabel()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } @Test public void testAddDataLabelVsFunctionConflictKeepMy() throws Exception { final String libname = "user32.dll"; final String label = "blue"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, new WordDataType(), SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(library, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Function Versus Data Type Conflict", MY_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, label, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, label + "_conflict1", externalLibrary); assertNotNull(blue); assertNull(blueConflict); assertEquals(SymbolType.FUNCTION, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation = externalManager.getExternalLocation(blue); assertNotNull(externalLocation); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(label, externalLocation.getLabel()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddDiffExtLabelWithSameAddressKeepLatest() throws Exception { final String libname = "advapi32.dll"; final String label1 = "apples"; final String label2 = "oranges"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label1, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label1); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label1, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label2, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label2); assertNotNull(externalLocation); assertEquals(libname + "::" + label2, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label1); assertNotNull(externalLocation); assertEquals(libname + "::" + label1, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); externalLocation = externalManager.getUniqueExternalLocation(libname, label2); assertNull(externalLocation); } @Test public void testAddDiffExtLabelWithSameAddressKeepMy() throws Exception { final String libname = "advapi32.dll"; final String label1 = "apples"; final String label2 = "oranges"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label1, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label1); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label1, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label2, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label2); assertNotNull(externalLocation); assertEquals(libname + "::" + label2, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON);// Choose "oranges" labeled external. waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label1); assertNull(externalLocation); externalLocation = externalManager.getUniqueExternalLocation(libname, label2); assertNotNull(externalLocation); assertEquals(libname + "::" + label2, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } /** * The external function merger only detects and merges source differences when a name * difference is being merged. */ @Test public void testAddSameExtLabelWithDiffSourceNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address, SourceType.IMPORTED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.IMPORTED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.IMPORTED); assertEquals(false, externalLocation.isFunction()); } @Test public void testAddExtNoLabelSameAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalName(addr(program, address), null); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::EXT_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalName(addr(program, address), null); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(false, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalName(addr(resultProgram, address), null); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_00000100", externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(false, externalLocation.isFunction()); } @Test public void testAddExtFunctionNoLabelSameAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(program, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(program, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(resultProgram, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionNoLabelLatestOnlyNoConflict() throws Exception { final String libname = "advapi32.dll"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(program, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(program, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(resultProgram, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionNoLabelMyOnlyNoConflict() throws Exception { final String libname = "advapi32.dll"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, null, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(program, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); String defaultExternalName = SymbolUtilities.getDefaultExternalFunctionName(addr(resultProgram, address)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, defaultExternalName); assertNotNull(externalLocation); assertEquals(libname + "::EXT_FUN_00000100", externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.DEFAULT); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionSameLabelSameAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "apples"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtLabelVsExtFunctionNoAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionVsExtLabelNoAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionWithAddressVsNoAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddExtFunctionNoAddressVsWithAddressNoConflict() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, null, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertNull(externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalFunction(libname, label, address, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(true, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(true, externalLocation.isFunction()); } @Test public void testAddSameExternalLibraryNoConflict() throws Exception { final String libname = "user32.dll"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); Symbol externalLibrarySymbol = resultProgram.getSymbolTable().getLibrarySymbol(libname); assertNotNull(externalLibrarySymbol); assertEquals(SymbolType.LIBRARY, externalLibrarySymbol.getSymbolType()); Symbol conflictSymbol = resultProgram.getSymbolTable().getLibrarySymbol(libname + "_conflict1"); assertNull(conflictSymbol); } @Test public void testAddSameNamespaceNoConflict() throws Exception { final String libname = "user32.dll"; final String namespace = "MyNamespace"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.createNamespace(library, namespace, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.createNamespace(library, namespace, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol myNamespaceSymbol = getUniqueSymbol(resultProgram, namespace, externalLibrary); assertNotNull(myNamespaceSymbol); assertEquals(SymbolType.NAMESPACE, myNamespaceSymbol.getSymbolType()); Symbol conflictSymbol = getUniqueSymbol(resultProgram, "MyNamespace_conflict1", externalLibrary); assertNull(conflictSymbol); } @Test public void testSimpleAddSubClassAddSubNamespaceConflict1() throws Exception { final String libname = "user32.dll"; final String namespace1 = "blue"; final String namespace2 = "green"; final String class1 = "red"; final String class2 = "yellow"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace ns = mergeProgram.createNamespace(library, namespace1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(library, namespace2, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(library, class1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(library, class2, SourceType.USER_DEFINED); assertNotNull(ns); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace ns = mergeProgram.createClass(library, namespace1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(library, namespace2, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(library, class1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(library, class2, SourceType.USER_DEFINED); assertNotNull(ns); } }); executeMerge(ASK_USER); waitForReadTextDialog("Symbol Merge Information", "The following symbols were renamed", 4000); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Symbol blue = getUniqueSymbol(resultProgram, namespace1, externalLibrary); Symbol blueConflict = getUniqueSymbol(resultProgram, namespace1 + "_conflict1", externalLibrary); Symbol green = getUniqueSymbol(resultProgram, namespace2, externalLibrary); Symbol greenConflict = getUniqueSymbol(resultProgram, namespace2 + "_conflict1", externalLibrary); Symbol red = getUniqueSymbol(resultProgram, class1, externalLibrary); Symbol redConflict = getUniqueSymbol(resultProgram, class1 + "_conflict1", externalLibrary); Symbol yellow = getUniqueSymbol(resultProgram, class2, externalLibrary); Symbol yellowConflict = getUniqueSymbol(resultProgram, class2 + "_conflict1", externalLibrary); assertEquals(SymbolType.NAMESPACE, blue.getSymbolType()); assertEquals(SymbolType.CLASS, blueConflict.getSymbolType()); assertEquals(SymbolType.NAMESPACE, green.getSymbolType()); assertEquals(SymbolType.CLASS, greenConflict.getSymbolType()); assertEquals(SymbolType.CLASS, red.getSymbolType()); assertEquals(SymbolType.NAMESPACE, redConflict.getSymbolType()); assertEquals(SymbolType.CLASS, yellow.getSymbolType()); assertEquals(SymbolType.NAMESPACE, yellowConflict.getSymbolType()); } @Test public void testSimpleAddSubClassAddSubNamespaceConflict2() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String namespace1 = "blue"; final String namespace2 = "green"; final String class1 = "red"; final String class2 = "yellow"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace parentNS = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); Namespace ns = mergeProgram.createNamespace(parentNS, namespace1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(parentNS, namespace2, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(parentNS, class1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(parentNS, class2, SourceType.USER_DEFINED); assertNotNull(ns); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace parentNS = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); Namespace ns = mergeProgram.createClass(parentNS, namespace1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createClass(parentNS, namespace2, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(parentNS, class1, SourceType.USER_DEFINED); assertNotNull(ns); ns = mergeProgram.createNamespace(parentNS, class2, SourceType.USER_DEFINED); assertNotNull(ns); } }); executeMerge(ASK_USER); waitForReadTextDialog("Symbol Merge Information", "The following symbols were renamed", 4000); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); Symbol blue = getUniqueSymbol(resultProgram, namespace1, myNamespace); Symbol blueConflict = getUniqueSymbol(resultProgram, namespace1 + "_conflict1", myNamespace); Symbol green = getUniqueSymbol(resultProgram, namespace2, myNamespace); Symbol greenConflict = getUniqueSymbol(resultProgram, namespace2 + "_conflict1", myNamespace); Symbol red = getUniqueSymbol(resultProgram, class1, myNamespace); Symbol redConflict = getUniqueSymbol(resultProgram, class1 + "_conflict1", myNamespace); Symbol yellow = getUniqueSymbol(resultProgram, class2, myNamespace); Symbol yellowConflict = getUniqueSymbol(resultProgram, class2 + "_conflict1", myNamespace); assertEquals(SymbolType.NAMESPACE, blue.getSymbolType()); assertEquals(SymbolType.CLASS, blueConflict.getSymbolType()); assertEquals(SymbolType.NAMESPACE, green.getSymbolType()); assertEquals(SymbolType.CLASS, greenConflict.getSymbolType()); assertEquals(SymbolType.CLASS, red.getSymbolType()); assertEquals(SymbolType.NAMESPACE, redConflict.getSymbolType()); assertEquals(SymbolType.CLASS, yellow.getSymbolType()); assertEquals(SymbolType.NAMESPACE, yellowConflict.getSymbolType()); } @Test public void testAddSameExternalFunctionNoConflict() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "apple"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); assertNull(applesConflict); } @Test public void testAddNonConflictingExternalLabels() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label1 = "apples"; final String label2 = "oranges"; final String address1 = "0x100"; final String address2 = "0x120"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label1, address1, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label2, address2, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label1, myNamespace); Symbol oranges = getUniqueSymbol(resultProgram, label2, myNamespace); assertEquals(SymbolType.LABEL, apples.getSymbolType()); assertEquals(SymbolType.LABEL, oranges.getSymbolType()); ExternalLocation externalLocation = (ExternalLocation) apples.getObject(); assertEquals(label1, externalLocation.getLabel()); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(parentNamespace, externalLocation.getParentName()); assertEquals(libname + "::" + parentNamespace, externalLocation.getParentNameSpace().getName(true)); assertEquals(null, externalLocation.getFunction()); assertEquals(libname + "::" + parentNamespace + "::" + label1, externalLocation.getSymbol().getName(true)); assertEquals(SourceType.USER_DEFINED, externalLocation.getSource()); assertEquals(addr(resultProgram, address1), externalLocation.getAddress()); ExternalLocation orangesExternalLocation = (ExternalLocation) oranges.getObject(); assertEquals(label2, orangesExternalLocation.getLabel()); assertEquals(libname, orangesExternalLocation.getLibraryName()); assertEquals(parentNamespace, orangesExternalLocation.getParentName()); assertEquals(libname + "::" + parentNamespace, orangesExternalLocation.getParentNameSpace().getName(true)); assertEquals(null, orangesExternalLocation.getFunction()); assertEquals(libname + "::" + parentNamespace + "::" + label2, orangesExternalLocation.getSymbol().getName(true)); assertEquals(SourceType.USER_DEFINED, orangesExternalLocation.getSource()); assertEquals(addr(resultProgram, address2), orangesExternalLocation.getAddress()); } @Test public void testAddDiffExternalLabelChooseLatest() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "apples"; final String address1 = "0x100"; final String address2 = "0x120"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address1, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address2, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.LABEL, apples.getSymbolType()); assertNull(applesConflict); ExternalLocation externalLocation = (ExternalLocation) apples.getObject(); assertEquals(label, externalLocation.getLabel()); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(parentNamespace, externalLocation.getParentName()); assertEquals(libname + "::" + parentNamespace, externalLocation.getParentNameSpace().getName(true)); assertEquals(null, externalLocation.getFunction()); assertEquals(libname + "::" + parentNamespace + "::" + label, externalLocation.getSymbol().getName(true)); assertEquals(SourceType.USER_DEFINED, externalLocation.getSource()); assertEquals(addr(resultProgram, address1), externalLocation.getAddress()); } @Test public void testAddDiffExternalLabelChooseMy() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "apples"; final String address1 = "0x100"; final String address2 = "0x120"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address1, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address2, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.LABEL, apples.getSymbolType()); assertNull(applesConflict); ExternalLocation externalLocation = (ExternalLocation) apples.getObject(); assertEquals(label, externalLocation.getLabel()); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(parentNamespace, externalLocation.getParentName()); assertEquals(libname + "::" + parentNamespace, externalLocation.getParentNameSpace().getName(true)); assertEquals(null, externalLocation.getFunction()); assertEquals(libname + "::" + parentNamespace + "::" + label, externalLocation.getSymbol().getName(true)); assertEquals(SourceType.USER_DEFINED, externalLocation.getSource()); assertEquals(addr(resultProgram, address2), externalLocation.getAddress()); } @Test public void testAddDiffExternalLabelKeepBoth() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "apples"; final String address1 = "0x100"; final String address2 = "0x120"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address1, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(namespace, label, address2, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", KEEP_BOTH_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = resultProgram.getSymbolTable().getNamespace(parentNamespace, externalLibrary); assertNotNull(myNamespace); SymbolTable symtab = resultProgram.getSymbolTable(); List<Symbol> symbols = symtab.getSymbols(label, myNamespace); assertEquals(2, symbols.size()); assertTrue(!symbols.get(0).getAddress().equals(symbols.get(1).getAddress())); } @Test public void testAddDiffExternalFunctionKeepLatest() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "blue"; final String address = "0x100"; final String param1 = "P1"; final String comment1 = "Test Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r0"); Parameter parameter1 = new ParameterImpl("Length", new CharDataType(), register, program); parameter1.setComment("Latest Parameter Comment"); mergeProgram.updateFunction(function, false, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); assertNull(applesConflict); Function function = (Function) apples.getObject(); assertTrue(new ByteDataType().isEquivalent(function.getReturnType())); assertEquals(1, function.getParameterCount()); Parameter parameter = function.getParameter(0); assertEquals(param1, parameter.getName()); assertTrue(new DWordDataType().isEquivalent(parameter.getDataType())); assertTrue(parameter.isStackVariable()); assertEquals(4, parameter.getStackOffset()); assertEquals(comment1, parameter.getComment()); } @Test public void testAddDiffExternalFunctionKeepMy() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "blue"; final String address = "0x100"; final String param1 = "P1"; final String param2 = "Length"; final String comment1 = "Test Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r0"); Parameter parameter1 = new ParameterImpl(param2, new CharDataType(), register, program); parameter1.setComment("Latest Parameter Comment"); mergeProgram.updateFunction(function, true, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); assertNull(applesConflict); Function function = (Function) apples.getObject(); checkFunctionReturnType(function, new FloatDataType()); assertTrue(new FloatDataType().isEquivalent(function.getReturnType())); assertEquals(1, function.getParameterCount()); Parameter parameter = function.getParameter(0); assertEquals(param2, parameter.getName()); assertTrue(new CharDataType().isEquivalent(parameter.getDataType())); assertTrue(parameter.isRegisterVariable()); Register baseRegister = parameter.getRegister().getBaseRegister(); Register register = resultProgram.getRegister("r0"); assertTrue(baseRegister.contains(register)); assertEquals("Latest Parameter Comment", parameter.getComment()); } @Test public void testAddDiffExternalFunctionKeepBoth() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label1 = "oranges"; final String label2 = "apples"; final String address = null; final String param1 = "P1"; final String param2 = "Length"; final String comment1 = "Test Parameter Comment"; final String comment2 = "My Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); mergeProgram.addExternalFunction(namespace, label1, "0x120", SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label2, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label2, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r0l"); Parameter parameter1 = new ParameterImpl(param2, new CharDataType(), register, program); parameter1.setComment(comment2); mergeProgram.updateFunction(function, true, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", KEEP_BOTH_BUTTON); waitForMergeCompletion(); SymbolTable symbolTable = resultProgram.getSymbolTable(); Namespace externalLibrary = (Namespace) symbolTable.getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = symbolTable.getNamespace(parentNamespace, externalLibrary); assertNotNull(myNamespace); Symbol oranges = getUniqueSymbol(resultProgram, label1, myNamespace); assertNotNull(oranges); List<Symbol> symbols = symbolTable.getSymbols(label2, myNamespace); assertEquals(2, symbols.size()); Object obj1 = symbols.get(0).getObject(); Object obj2 = symbols.get(1).getObject(); assertTrue(obj1 instanceof Function); assertTrue(obj2 instanceof Function); Function fun1 = (Function) obj1; Function fun2 = (Function) obj2; if (!fun1.getReturnType().isEquivalent(new ByteDataType())) { Function tmp = fun1; fun1 = fun2; fun2 = tmp; } assertTrue(new ByteDataType().isEquivalent(fun1.getReturnType())); assertEquals(1, fun1.getParameterCount()); Parameter parameter = fun1.getParameter(0); assertEquals(param1, parameter.getName()); assertTrue(new DWordDataType().isEquivalent(parameter.getDataType())); assertTrue(parameter.isStackVariable()); assertEquals(4, parameter.getStackOffset()); assertEquals(comment1, parameter.getComment()); assertTrue(new FloatDataType().isEquivalent(fun2.getReturnType())); assertEquals(1, fun2.getParameterCount()); Parameter f2parameter = fun2.getParameter(0); assertEquals(param2, f2parameter.getName()); assertTrue(new CharDataType().isEquivalent(f2parameter.getDataType())); assertTrue(f2parameter.isRegisterVariable()); assertEquals(resultProgram.getRegister("r0l"), f2parameter.getRegister()); assertEquals(comment2, f2parameter.getComment()); } @Test public void testAddDiffExternalFunction2ChooseLatest() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "blue"; final String address = "0x100"; final String param1 = "P1"; final String param2 = "Length"; final String comment1 = "Test Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r0"); Parameter parameter1 = new ParameterImpl(param2, new CharDataType(), register, program); parameter1.setComment("Latest Parameter Comment"); mergeProgram.updateFunction(function, false, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); assertNull(applesConflict); Function function = (Function) apples.getObject(); checkFunctionReturnType(function, new ByteDataType()); assertEquals(1, function.getParameterCount()); Parameter parameter = function.getParameter(0); assertEquals(param1, parameter.getName()); assertEquals(comment1, parameter.getComment()); checkParameterDataType(parameter, new DWordDataType()); assertTrue(parameter.isStackVariable()); } @Test public void testAddDiffExternalFunction2ChooseMy() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "blue"; final String address = "0x100"; final String param1 = "P1"; final String param2 = "Length"; final String comment1 = "Test Parameter Comment"; final String comment2 = "Latest Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r12l"); Parameter parameter1 = new ParameterImpl(param2, new CharDataType(), register, program); parameter1.setComment(comment2); mergeProgram.updateFunction(function, false, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); assertNotNull(myNamespace); Symbol apples = getUniqueSymbol(resultProgram, label, myNamespace); Symbol applesConflict = getUniqueSymbol(resultProgram, label + "_conflict1", myNamespace); assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); assertNull(applesConflict); Function function = (Function) apples.getObject(); checkFunctionReturnType(function, new FloatDataType()); assertEquals(1, function.getParameterCount()); Parameter parameter = function.getParameter(0); assertEquals(param2, parameter.getName()); assertEquals(comment2, parameter.getComment()); checkParameterDataType(parameter, new CharDataType()); assertTrue(parameter.isRegisterVariable()); assertEquals("r12l", parameter.getRegister().getName()); } @Test public void testAddDiffExternalFunction2KeepBoth() throws Exception { final String libname = "user32.dll"; final String parentNamespace = "MyNamespace"; final String label = "blue"; final String address = null; final String param1 = "P1"; final String param2 = "Length"; final String comment1 = "Test Parameter Comment"; final String comment2 = "Latest Parameter Comment"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Parameter parameter1 = new ParameterImpl(param1, new DWordDataType(), 4, program); parameter1.setComment(comment1); mergeProgram.updateFunction(function, true, new ByteDataType(), parameter1); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, parentNamespace, SourceType.USER_DEFINED); ExternalLocation externalLocation = mergeProgram.addExternalFunction(namespace, label, address, SourceType.USER_DEFINED); Function function = externalLocation.getFunction(); assertNotNull(function); Program program = mergeProgram.getProgram(); Register register = program.getRegister("r12l"); Parameter parameter1 = new ParameterImpl(param2, new CharDataType(), register, program); parameter1.setComment(comment2); mergeProgram.updateFunction(function, false, new FloatDataType(), parameter1); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", KEEP_BOTH_BUTTON); waitForMergeCompletion(); SymbolTable symbolTable = resultProgram.getSymbolTable(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Namespace myNamespace = (Namespace) getUniqueSymbol(resultProgram, parentNamespace, externalLibrary).getObject(); List<Symbol> symbols = symbolTable.getSymbols(label, myNamespace); assertEquals(2, symbols.size()); Object obj1 = symbols.get(0).getObject(); Object obj2 = symbols.get(1).getObject(); assertTrue(obj1 instanceof Function); assertTrue(obj2 instanceof Function); Function fun1 = (Function) obj1; Function fun2 = (Function) obj2; if (!fun1.getReturnType().isEquivalent(new ByteDataType())) { Function tmp = fun1; fun1 = fun2; fun2 = tmp; } assertTrue(new ByteDataType().isEquivalent(fun1.getReturnType())); assertEquals(1, fun1.getParameterCount()); Parameter parameter = fun1.getParameter(0); assertEquals(param1, parameter.getName()); assertTrue(new DWordDataType().isEquivalent(parameter.getDataType())); assertTrue(parameter.isStackVariable()); assertEquals(4, parameter.getStackOffset()); assertEquals(comment1, parameter.getComment()); assertTrue(new FloatDataType().isEquivalent(fun2.getReturnType())); assertEquals(1, fun2.getParameterCount()); Parameter f2parameter = fun2.getParameter(0); assertEquals(param2, f2parameter.getName()); assertTrue(new CharDataType().isEquivalent(f2parameter.getDataType())); assertTrue(f2parameter.isRegisterVariable()); assertEquals("r12l", f2parameter.getRegister().getName()); assertEquals(comment2, f2parameter.getComment()); // // assertNotNull(myNamespace); // SymbolTable symtab = resultProgram.getSymbolTable(); // Symbol apples = getUniqueSymbol(resultProgram,label, myNamespace); // assertNotNull(apples); // assertEquals(SymbolType.FUNCTION, apples.getSymbolType()); // Function function = (Function) apples.getObject(); // checkFunctionReturnType(function, new ByteDataType()); // assertEquals(1, function.getParameterCount()); // Parameter parameter = function.getParameter(0); // assertEquals(param1, parameter.getName()); // assertEquals(comment1, parameter.getComment()); // checkParameterDataType(parameter, new DWordDataType()); // assertTrue(parameter.isStackVariable()); // // Symbol applesConflict = getUniqueSymbol(resultProgram,label + "_conflict1", myNamespace); // assertNotNull(applesConflict); // assertEquals(SymbolType.FUNCTION, applesConflict.getSymbolType()); // Function conflictFunction = (Function) applesConflict.getObject(); // checkFunctionReturnType(conflictFunction, new FloatDataType()); // assertEquals(1, conflictFunction.getParameterCount()); // Parameter conflictParameter = conflictFunction.getParameter(0); // assertEquals(param2, conflictParameter.getName()); // assertEquals(comment2, conflictParameter.getComment()); // checkParameterDataType(conflictParameter, new CharDataType()); // assertTrue(conflictParameter.isRegisterVariable()); // assertEquals("r12", conflictParameter.getRegister().getName()); // } @Test public void testAddExternalLocationVersusNamespaceNoConflict() throws Exception { final String libname = "user32.dll"; final String label = "Foo"; final String address = "0x100"; mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); mergeProgram.addExternalLocation(library, label, address, new DoubleDataType(), SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { Library library = mergeProgram.createExternalLibrary(libname, SourceType.USER_DEFINED); Namespace namespace = mergeProgram.createNamespace(library, label, SourceType.USER_DEFINED); assertNotNull(namespace); } }); executeMerge(ASK_USER); waitForMergeCompletion(); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); assertNotNull(externalLibrary); Symbol namespaceSymbol = resultProgram.getSymbolTable().getNamespaceSymbol(label, externalLibrary); assertNotNull(namespaceSymbol); List<Symbol> symbols = resultProgram.getSymbolTable().getSymbols(label, externalLibrary); assertEquals(2, symbols.size()); Symbol otherSymbol = symbols.get(0) == namespaceSymbol ? symbols.get(1) : symbols.get(0); Object object = otherSymbol.getObject(); assertTrue(object instanceof ExternalLocation); ExternalLocation locationFoo = (ExternalLocation) object; checkExternalDataType(locationFoo, new DoubleDataType()); } @Test public void testAddSameLabelDiffDataTypeKeepBoth() throws Exception { final String libname = "MyLibrary"; final String label = "blue"; final String address = null; final String[] BLUE_PATH = new String[] { libname, label }; final CategoryPath catPath = new CategoryPath("/cat1"); final Structure myStruct = new StructureDataType(catPath, "MyStruct", 0); myStruct.add(new WordDataType()); myStruct.add(new FloatDataType()); final TypedefDataType myTypedef = new TypedefDataType("MyTypedef", myStruct); mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myStruct, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myStruct, externalLocation.getDataType()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myTypedef, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myTypedef, externalLocation.getDataType()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", KEEP_BOTH_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); SymbolTable symtab = resultProgram.getSymbolTable(); List<Symbol> symbols = symtab.getSymbols(label, externalLibrary); assertEquals(2, symbols.size()); ExternalLocation loc1 = (ExternalLocation) symbols.get(0).getObject(); ExternalLocation loc2 = (ExternalLocation) symbols.get(1).getObject(); DataType type1 = loc1.getDataType(); DataType type2 = loc2.getDataType(); if (type1.isEquivalent(myStruct)) { checkDataType(myTypedef, type2); } else { checkDataType(myTypedef, type1); checkDataType(myStruct, type2); } } @Test public void testAddSameLabelDiffDataTypeKeepLatest() throws Exception { final String libname = "MyLibrary"; final String label = "blue"; final String address = "0x100"; final String[] BLUE_PATH = new String[] { libname, label }; final CategoryPath catPath = new CategoryPath("/cat1"); final Structure myStruct = new StructureDataType(catPath, "MyStruct", 0); myStruct.add(new WordDataType()); myStruct.add(new FloatDataType()); final TypedefDataType myTypedef = new TypedefDataType("MyTypeDef", myStruct); mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myStruct, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myStruct, externalLocation.getDataType()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myTypedef, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myTypedef, externalLocation.getDataType()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", LATEST_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); SymbolTable symtab = resultProgram.getSymbolTable(); List<Symbol> symbols = symtab.getSymbols(label, externalLibrary); assertEquals(1, symbols.size()); Symbol blue = symbols.get(0); assertEquals(SymbolType.LABEL, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation = externalManager.getExternalLocation(blue); assertNotNull(externalLocation); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); checkDataType(myStruct, externalLocation.getDataType()); } @Test public void testAddSameLabelDiffDataTypeKeepMy() throws Exception { final String libname = "MyLibrary"; final String label = "blue"; final String address = "0x100"; final String[] BLUE_PATH = new String[] { libname, label }; final CategoryPath catPath = new CategoryPath("/cat1"); final Structure myStruct = new StructureDataType(catPath, "MyStruct", 0); myStruct.add(new WordDataType()); myStruct.add(new FloatDataType()); final TypedefDataType myTypedef = new TypedefDataType("MyStruct", myStruct); mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myStruct, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myStruct, externalLocation.getDataType()); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { createExternalLabel(mergeProgram, BLUE_PATH, address, myTypedef, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = getExternalLocation(program, BLUE_PATH); assertNotNull(externalLocation); assertEquals(false, externalLocation.isFunction()); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); checkDataType(myTypedef, externalLocation.getDataType()); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", MY_BUTTON); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); Namespace externalLibrary = (Namespace) resultProgram.getSymbolTable().getLibrarySymbol(libname).getObject(); SymbolTable symtab = resultProgram.getSymbolTable(); List<Symbol> symbols = symtab.getSymbols(label, externalLibrary); assertEquals(1, symbols.size()); Symbol blue = symbols.get(0); assertEquals(SymbolType.LABEL, blue.getSymbolType()); assertTrue(blue.isExternal()); ExternalLocation externalLocation = externalManager.getExternalLocation(blue); assertNotNull(externalLocation); assertEquals(libname, externalLocation.getLibraryName()); assertEquals(addr(resultProgram, address), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); checkDataType(myTypedef, externalLocation.getDataType()); } void createExternalLabel(MergeProgram mergeProgram, String[] path, String memoryAddress, DataType dt, SourceType sourceType) { int nameIndex = path.length - 1; Library currentLibrary = null; for (int i = 0; i < nameIndex; i++) { currentLibrary = mergeProgram.createExternalLibrary(path[i], sourceType); } mergeProgram.addExternalLocation(currentLibrary, path[nameIndex], memoryAddress, dt, sourceType); } @Test public void testExternalAddDontUseForAll() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address1 = "0x100"; final String address2 = "0x110"; final String libnameA = "MyLibrary"; final String labelA = "blue"; final String[] BLUE_PATH = new String[] { libnameA, labelA }; final CategoryPath catPath = new CategoryPath("/cat1"); final Structure myStruct = new StructureDataType(catPath, "MyStruct", 0); myStruct.add(new WordDataType()); myStruct.add(new FloatDataType()); final TypedefDataType myTypedef = new TypedefDataType("MyStruct", myStruct); mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address1, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); createExternalLabel(mergeProgram, BLUE_PATH, null, myStruct, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address2, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); createExternalLabel(mergeProgram, BLUE_PATH, null, myTypedef, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", ExternalFunctionMerger.KEEP_BOTH_BUTTON_NAME, false); chooseButtonAndApply("Resolve External Add Conflict", ExternalFunctionMerger.KEEP_BOTH_BUTTON_NAME, false); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); List<ExternalLocation> externalLocations = externalManager.getExternalLocations(libname, label); assertEquals(2, externalLocations.size()); List<ExternalLocation> externalLocations2 = externalManager.getExternalLocations(BLUE_PATH[0], BLUE_PATH[1]); assertEquals(2, externalLocations2.size()); } @Test public void testExternalAddUseForAll() throws Exception { final String libname = "advapi32.dll"; final String label = "printf"; final String address1 = "0x100"; final String address2 = "0x110"; final String libnameA = "MyLibrary"; final String labelA = "blue"; final String[] BLUE_PATH = new String[] { libnameA, labelA }; final CategoryPath catPath = new CategoryPath("/cat1"); final Structure myStruct = new StructureDataType(catPath, "MyStruct", 0); myStruct.add(new WordDataType()); myStruct.add(new FloatDataType()); final TypedefDataType myTypedef = new TypedefDataType("MyStruct", myStruct); mtf.initialize("NotepadMergeListingTest", new MergeProgramModifier() { @Override public void initializeProgram(MergeProgram program) throws Exception { program.addMemory("memory", "0x0", 0x200); } @Override public void modifyLatest(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address1, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address1), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); createExternalLabel(mergeProgram, BLUE_PATH, null, myStruct, SourceType.USER_DEFINED); } @Override public void modifyPrivate(MergeProgram mergeProgram) throws Exception { mergeProgram.addExternalLocation(libname, label, address2, SourceType.USER_DEFINED); Program program = mergeProgram.getProgram(); ExternalManager externalManager = program.getExternalManager(); assertTrue(externalManager.contains(libname)); ExternalLocation externalLocation = externalManager.getUniqueExternalLocation(libname, label); assertNotNull(externalLocation); assertEquals(libname + "::" + label, externalLocation.toString()); assertEquals(addr(program, address2), externalLocation.getAddress()); assertTrue(externalLocation.getSource() == SourceType.USER_DEFINED); assertEquals(false, externalLocation.isFunction()); createExternalLabel(mergeProgram, BLUE_PATH, null, myTypedef, SourceType.USER_DEFINED); } }); executeMerge(ASK_USER); chooseButtonAndApply("Resolve External Add Conflict", ExternalFunctionMerger.KEEP_BOTH_BUTTON_NAME, true); waitForMergeCompletion(); ExternalManager externalManager = resultProgram.getExternalManager(); assertTrue(externalManager.contains(libname)); List<ExternalLocation> externalLocations = externalManager.getExternalLocations(libname, label); assertEquals(2, externalLocations.size()); List<ExternalLocation> externalLocations2 = externalManager.getExternalLocations(BLUE_PATH[0], BLUE_PATH[1]); assertEquals(2, externalLocations2.size()); } }
warrenseine/slack-types
python/slack_types/web_api/admin_apps_requests_list_response.py
<reponame>warrenseine/slack-types # To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = admin_apps_requests_list_response_from_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Optional, Any, List, TypeVar, Type, cast, Callable T = TypeVar("T") def from_str(x: Any) -> str: assert isinstance(x, str) return x def from_none(x: Any) -> Any: assert x is None return x def from_union(fs, x): for f in fs: try: return f(x) except: pass assert False def from_bool(x: Any) -> bool: assert isinstance(x, bool) return x def to_class(c: Type[T], x: Any) -> dict: assert isinstance(x, c) return cast(Any, x).to_dict() def from_list(f: Callable[[Any], T], x: Any) -> List[T]: assert isinstance(x, list) return [f(y) for y in x] def from_int(x: Any) -> int: assert isinstance(x, int) and not isinstance(x, bool) return x @dataclass class Icons: image_32: Optional[str] = None image_36: Optional[str] = None image_48: Optional[str] = None image_64: Optional[str] = None image_72: Optional[str] = None image_96: Optional[str] = None image_128: Optional[str] = None image_192: Optional[str] = None image_512: Optional[str] = None image_1024: Optional[str] = None image_original: Optional[str] = None @staticmethod def from_dict(obj: Any) -> 'Icons': assert isinstance(obj, dict) image_32 = from_union([from_str, from_none], obj.get("image_32")) image_36 = from_union([from_str, from_none], obj.get("image_36")) image_48 = from_union([from_str, from_none], obj.get("image_48")) image_64 = from_union([from_str, from_none], obj.get("image_64")) image_72 = from_union([from_str, from_none], obj.get("image_72")) image_96 = from_union([from_str, from_none], obj.get("image_96")) image_128 = from_union([from_str, from_none], obj.get("image_128")) image_192 = from_union([from_str, from_none], obj.get("image_192")) image_512 = from_union([from_str, from_none], obj.get("image_512")) image_1024 = from_union([from_str, from_none], obj.get("image_1024")) image_original = from_union([from_str, from_none], obj.get("image_original")) return Icons(image_32, image_36, image_48, image_64, image_72, image_96, image_128, image_192, image_512, image_1024, image_original) def to_dict(self) -> dict: result: dict = {} result["image_32"] = from_union([from_str, from_none], self.image_32) result["image_36"] = from_union([from_str, from_none], self.image_36) result["image_48"] = from_union([from_str, from_none], self.image_48) result["image_64"] = from_union([from_str, from_none], self.image_64) result["image_72"] = from_union([from_str, from_none], self.image_72) result["image_96"] = from_union([from_str, from_none], self.image_96) result["image_128"] = from_union([from_str, from_none], self.image_128) result["image_192"] = from_union([from_str, from_none], self.image_192) result["image_512"] = from_union([from_str, from_none], self.image_512) result["image_1024"] = from_union([from_str, from_none], self.image_1024) result["image_original"] = from_union([from_str, from_none], self.image_original) return result @dataclass class App: id: Optional[str] = None name: Optional[str] = None description: Optional[str] = None help_url: Optional[str] = None privacy_policy_url: Optional[str] = None app_homepage_url: Optional[str] = None app_directory_url: Optional[str] = None is_app_directory_approved: Optional[bool] = None is_internal: Optional[bool] = None additional_info: Optional[str] = None icons: Optional[Icons] = None @staticmethod def from_dict(obj: Any) -> 'App': assert isinstance(obj, dict) id = from_union([from_str, from_none], obj.get("id")) name = from_union([from_str, from_none], obj.get("name")) description = from_union([from_str, from_none], obj.get("description")) help_url = from_union([from_str, from_none], obj.get("help_url")) privacy_policy_url = from_union([from_str, from_none], obj.get("privacy_policy_url")) app_homepage_url = from_union([from_str, from_none], obj.get("app_homepage_url")) app_directory_url = from_union([from_str, from_none], obj.get("app_directory_url")) is_app_directory_approved = from_union([from_bool, from_none], obj.get("is_app_directory_approved")) is_internal = from_union([from_bool, from_none], obj.get("is_internal")) additional_info = from_union([from_str, from_none], obj.get("additional_info")) icons = from_union([Icons.from_dict, from_none], obj.get("icons")) return App(id, name, description, help_url, privacy_policy_url, app_homepage_url, app_directory_url, is_app_directory_approved, is_internal, additional_info, icons) def to_dict(self) -> dict: result: dict = {} result["id"] = from_union([from_str, from_none], self.id) result["name"] = from_union([from_str, from_none], self.name) result["description"] = from_union([from_str, from_none], self.description) result["help_url"] = from_union([from_str, from_none], self.help_url) result["privacy_policy_url"] = from_union([from_str, from_none], self.privacy_policy_url) result["app_homepage_url"] = from_union([from_str, from_none], self.app_homepage_url) result["app_directory_url"] = from_union([from_str, from_none], self.app_directory_url) result["is_app_directory_approved"] = from_union([from_bool, from_none], self.is_app_directory_approved) result["is_internal"] = from_union([from_bool, from_none], self.is_internal) result["additional_info"] = from_union([from_str, from_none], self.additional_info) result["icons"] = from_union([lambda x: to_class(Icons, x), from_none], self.icons) return result @dataclass class PreviousResolution: status: Optional[str] = None scopes: Optional[List[Any]] = None @staticmethod def from_dict(obj: Any) -> 'PreviousResolution': assert isinstance(obj, dict) status = from_union([from_str, from_none], obj.get("status")) scopes = from_union([lambda x: from_list(lambda x: x, x), from_none], obj.get("scopes")) return PreviousResolution(status, scopes) def to_dict(self) -> dict: result: dict = {} result["status"] = from_union([from_str, from_none], self.status) result["scopes"] = from_union([lambda x: from_list(lambda x: x, x), from_none], self.scopes) return result @dataclass class Team: id: Optional[str] = None name: Optional[str] = None domain: Optional[str] = None @staticmethod def from_dict(obj: Any) -> 'Team': assert isinstance(obj, dict) id = from_union([from_str, from_none], obj.get("id")) name = from_union([from_str, from_none], obj.get("name")) domain = from_union([from_str, from_none], obj.get("domain")) return Team(id, name, domain) def to_dict(self) -> dict: result: dict = {} result["id"] = from_union([from_str, from_none], self.id) result["name"] = from_union([from_str, from_none], self.name) result["domain"] = from_union([from_str, from_none], self.domain) return result @dataclass class User: id: Optional[str] = None name: Optional[str] = None email: Optional[str] = None @staticmethod def from_dict(obj: Any) -> 'User': assert isinstance(obj, dict) id = from_union([from_str, from_none], obj.get("id")) name = from_union([from_str, from_none], obj.get("name")) email = from_union([from_str, from_none], obj.get("email")) return User(id, name, email) def to_dict(self) -> dict: result: dict = {} result["id"] = from_union([from_str, from_none], self.id) result["name"] = from_union([from_str, from_none], self.name) result["email"] = from_union([from_str, from_none], self.email) return result @dataclass class AppRequest: id: Optional[str] = None app: Optional[App] = None user: Optional[User] = None team: Optional[Team] = None scopes: Optional[List[Any]] = None previous_resolution: Optional[PreviousResolution] = None is_user_app_collaborator: Optional[bool] = None message: Optional[str] = None date_created: Optional[int] = None @staticmethod def from_dict(obj: Any) -> 'AppRequest': assert isinstance(obj, dict) id = from_union([from_str, from_none], obj.get("id")) app = from_union([App.from_dict, from_none], obj.get("app")) user = from_union([User.from_dict, from_none], obj.get("user")) team = from_union([Team.from_dict, from_none], obj.get("team")) scopes = from_union([lambda x: from_list(lambda x: x, x), from_none], obj.get("scopes")) previous_resolution = from_union([PreviousResolution.from_dict, from_none], obj.get("previous_resolution")) is_user_app_collaborator = from_union([from_bool, from_none], obj.get("is_user_app_collaborator")) message = from_union([from_str, from_none], obj.get("message")) date_created = from_union([from_int, from_none], obj.get("date_created")) return AppRequest(id, app, user, team, scopes, previous_resolution, is_user_app_collaborator, message, date_created) def to_dict(self) -> dict: result: dict = {} result["id"] = from_union([from_str, from_none], self.id) result["app"] = from_union([lambda x: to_class(App, x), from_none], self.app) result["user"] = from_union([lambda x: to_class(User, x), from_none], self.user) result["team"] = from_union([lambda x: to_class(Team, x), from_none], self.team) result["scopes"] = from_union([lambda x: from_list(lambda x: x, x), from_none], self.scopes) result["previous_resolution"] = from_union([lambda x: to_class(PreviousResolution, x), from_none], self.previous_resolution) result["is_user_app_collaborator"] = from_union([from_bool, from_none], self.is_user_app_collaborator) result["message"] = from_union([from_str, from_none], self.message) result["date_created"] = from_union([from_int, from_none], self.date_created) return result @dataclass class ResponseMetadata: next_cursor: Optional[str] = None messages: Optional[List[str]] = None warnings: Optional[List[str]] = None @staticmethod def from_dict(obj: Any) -> 'ResponseMetadata': assert isinstance(obj, dict) next_cursor = from_union([from_str, from_none], obj.get("next_cursor")) messages = from_union([lambda x: from_list(from_str, x), from_none], obj.get("messages")) warnings = from_union([lambda x: from_list(from_str, x), from_none], obj.get("warnings")) return ResponseMetadata(next_cursor, messages, warnings) def to_dict(self) -> dict: result: dict = {} result["next_cursor"] = from_union([from_str, from_none], self.next_cursor) result["messages"] = from_union([lambda x: from_list(from_str, x), from_none], self.messages) result["warnings"] = from_union([lambda x: from_list(from_str, x), from_none], self.warnings) return result @dataclass class AdminAppsRequestsListResponse: ok: Optional[bool] = None warning: Optional[str] = None error: Optional[str] = None needed: Optional[str] = None provided: Optional[str] = None app_requests: Optional[List[AppRequest]] = None response_metadata: Optional[ResponseMetadata] = None @staticmethod def from_dict(obj: Any) -> 'AdminAppsRequestsListResponse': assert isinstance(obj, dict) ok = from_union([from_bool, from_none], obj.get("ok")) warning = from_union([from_str, from_none], obj.get("warning")) error = from_union([from_str, from_none], obj.get("error")) needed = from_union([from_str, from_none], obj.get("needed")) provided = from_union([from_str, from_none], obj.get("provided")) app_requests = from_union([lambda x: from_list(AppRequest.from_dict, x), from_none], obj.get("app_requests")) response_metadata = from_union([ResponseMetadata.from_dict, from_none], obj.get("response_metadata")) return AdminAppsRequestsListResponse(ok, warning, error, needed, provided, app_requests, response_metadata) def to_dict(self) -> dict: result: dict = {} result["ok"] = from_union([from_bool, from_none], self.ok) result["warning"] = from_union([from_str, from_none], self.warning) result["error"] = from_union([from_str, from_none], self.error) result["needed"] = from_union([from_str, from_none], self.needed) result["provided"] = from_union([from_str, from_none], self.provided) result["app_requests"] = from_union([lambda x: from_list(lambda x: to_class(AppRequest, x), x), from_none], self.app_requests) result["response_metadata"] = from_union([lambda x: to_class(ResponseMetadata, x), from_none], self.response_metadata) return result def admin_apps_requests_list_response_from_dict(s: Any) -> AdminAppsRequestsListResponse: return AdminAppsRequestsListResponse.from_dict(s) def admin_apps_requests_list_response_to_dict(x: AdminAppsRequestsListResponse) -> Any: return to_class(AdminAppsRequestsListResponse, x)
TRex22/OldCodeArchive
SchoolWork/2010/IT10_2010/Page 115 Activity 2/myAgeCheck/AgeCheck.java
package myAgeCheck; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; import java.text.*; public class AgeCheck { /** * @param args */ public static void main(String[] args) { try { //AgeCheck Copyright <NAME> int cost = 25; DecimalFormat dCost = new DecimalFormat("R#00.00"); //IPO //Input Age int age = Integer.parseInt(JOptionPane.showInputDialog( "Age" )); //Determine older than 16 //if not if (age <= 15) { JOptionPane.showMessageDialog(null, "Sorry You Lose" ); } else { JOptionPane.showMessageDialog(null, "You Can View The Movie") ; } //sorry you lose //else you can see movie if (age>= 16){ int much = Integer.parseInt(JOptionPane.showInputDialog( "How Many Tickets Do You Want?" )); String where = JOptionPane.showInputDialog("Where Do You Want To Sit, Back or Front of The Cinema?"); int total = cost*much; JFrame nameofframe = new JFrame(); //make visiable nameofframe.setVisible(true); nameofframe.setSize(350,500); nameofframe.setTitle( "Ticket Purchase" ); //import text area JTextArea txt = new JTextArea(); nameofframe.add(txt); //display in text area //fist set text then append after txt.setTabSize(9); txt.setText( "Age Restriction: 16"); txt.append("\nYou Want To Buy: "+much ); txt.append("\nYou Want To Sit At The "+where+" Of The Cinema"); txt.append("\nThe Tickets Cost "+dCost.format(cost)+" Each"); txt.append("\nYou Want To Buy "+much+" Tickets"); txt.append("\n--------------------------------------------"); txt.append("\nYou Will Pay: "+dCost.format(total) ); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error Known" ); } } }
0xicl33n/BudschieMorphMod
src/main/java/de/budschie/bmorph/main/ServerSetup.java
<filename>src/main/java/de/budschie/bmorph/main/ServerSetup.java<gh_stars>0 package de.budschie.bmorph.main; import de.budschie.bmorph.capabilities.blacklist.ConfigManager; import de.budschie.bmorph.commands.BlacklistCommand; import de.budschie.bmorph.commands.MorphCommand; import net.minecraft.server.MinecraftServer; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.fml.event.server.FMLServerStartingEvent; import net.minecraftforge.fml.event.server.FMLServerStoppingEvent; @EventBusSubscriber(bus = Bus.FORGE) public class ServerSetup { public static MinecraftServer server; @SubscribeEvent public static void onServerStarting(final FMLServerStartingEvent event) { MorphCommand.registerCommands(event.getServer().getCommandManager().getDispatcher()); BlacklistCommand.registerCommand(event.getServer().getCommandManager().getDispatcher()); System.out.println("Registered commands."); server = event.getServer(); ConfigManager.INSTANCE.loadAll(); } @SubscribeEvent public static void onServerStopping(final FMLServerStoppingEvent event) { ConfigManager.INSTANCE.serverShutdown(); } }
egranata/puppy
kernel/src/libc/string.cpp
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <kernel/libc/string.h> #include <kernel/libc/memory.h> extern "C" char* strdup(const char* str) { if (!str) return nullptr; auto l = 1 + strlen(str); auto n = malloc(l); memcopy((uint8_t*)str, (uint8_t*)n, l); return (char*)n; } extern "C" bool strprefix(const char* prefix, const char* full, const char** next) { switch (strncmp(prefix, full, strlen(prefix))) { case 0: { if (next) *next = full + strlen(prefix); return true; } default: return false; } } void memset_pattern4(void *b, uint32_t pattern, size_t len) { uint32_t *buffer = (uint32_t*)b; while (len >= 4) { *buffer = pattern; ++buffer; len -= 4; } uint8_t *remainder = (uint8_t*)buffer; switch (len) { case 0: break; case 1: *remainder = pattern & 0xFF; break; case 2: *remainder = pattern & 0xFF; *(remainder+1) = (pattern & 0xFF00) >> 8; break; case 3: *remainder = pattern & 0xFF; *(remainder+1) = (pattern & 0xFF00) >> 8; *(remainder+2) = (pattern & 0xFF0000) >> 16; break; } }
discopt/cmr
src/cmr/series_parallel.c
// #define CMR_DEBUG /* Uncomment to debug this file. */ // TODO: Try to not fill the hashtable in initialScan but just add all elements to the queue. #include <cmr/series_parallel.h> #include "env_internal.h" #include "hashtable.h" #include "sort.h" #include "listmatrix.h" #include <stdint.h> #include <time.h> typedef enum { REMOVED = 0, ZERO = 1, BLOCK = 2, OTHER = 3 } ElementType; typedef struct { long long hashValue; /**< \brief Hash value of this element. */ CMR_LISTHASHTABLE_ENTRY hashEntry; /**< \brief Entry in row or column hashtable. */ size_t distance; /**< \brief Distance in breadth-first search. */ size_t predecessor; /**< \brief Index of predecessor element in breadth-first search. */ bool inQueue; /**< \brief Whether this element is queued. */ char lastBFS; /**< \brief Last breadth-first search that found this node. **< Is 0 initially, positive for search runs, -1 if marked and -2 for SP-reduced **< element. */ bool specialBFS; /**< \brief Whether this is a special node in breadth-first search. */ } ElementData; CMR_ERROR CMRstatsSeriesParallelInit(CMR_SP_STATISTICS* stats) { assert(stats); stats->totalCount = 0; stats->totalTime = 0.0; stats->reduceCount = 0; stats->reduceTime = 0.0; stats->nonbinaryCount = 0; stats->nonbinaryTime = 0.0; stats->wheelCount = 0; stats->wheelTime = 0.0; return CMR_OKAY; } CMR_ERROR CMRstatsSeriesParallelPrint(FILE* stream, CMR_SP_STATISTICS* stats, const char* prefix) { assert(stream); assert(stats); if (!prefix) { fprintf(stream, "Series-parallel recognition:\n"); prefix = " "; } fprintf(stream, "%sreduction calls: %ld in %f seconds\n", prefix, stats->reduceCount, stats->reduceTime); fprintf(stream, "%swheel searches: %ld in %f seconds\n", prefix, stats->wheelCount, stats->wheelTime); fprintf(stream, "%sternary certificates: %ld in %f seconds\n", prefix, stats->nonbinaryCount, stats->nonbinaryTime); fprintf(stream, "%stotal: %ld in %f seconds\n", prefix, stats->totalCount, stats->totalTime); return CMR_OKAY; } static char seriesParallelStringBuffer[32]; /**< Static buffer for \ref CMRspString. */ char* CMRspReductionString(CMR_SP_REDUCTION reduction, char* buffer) { if (!buffer) buffer = seriesParallelStringBuffer; if (reduction.element > 0) { if (reduction.mate > 0) sprintf(buffer, "c%d copy of c%d", reduction.element, reduction.mate); else if (reduction.mate < 0) sprintf(buffer, "c%d unit at r%d", reduction.element, -reduction.mate); else sprintf(buffer, "c%d zero", reduction.element); return buffer; } else if (reduction.element < 0) { if (reduction.mate > 0) sprintf(buffer, "r%d unit at c%d", -reduction.element, reduction.mate); else if (reduction.mate < 0) sprintf(buffer, "r%d copy of r%d", -reduction.element, -reduction.mate); else sprintf(buffer, "r%d zero", -reduction.element); return buffer; } else return "<invalid series-parallel reduction>"; } /** * \brief Removes the given nonzero from the linked-list representation. */ static inline void unlinkNonzero( ListMatrixNonzero* nonzero /**< Nonzero to be removed from the linked lists. */ ) { assert(nonzero); CMRdbgMsg(4, "Removing r%d,c%d from linked list.\n", nonzero->row+1, nonzero->column+1); nonzero->above->below = nonzero->below; nonzero->below->above = nonzero->above; nonzero->left->right = nonzero->right; nonzero->right->left = nonzero->left; } /** * \brief Allocates and initializes element data (on the stack). */ static CMR_ERROR createElementData( CMR* cmr, /**< \ref CMR environment. */ ElementData** pelementData, /**< Pointer for storing the element data. */ size_t size /**< Number of elements. */ ) { assert(cmr); assert(pelementData); CMR_CALL( CMRallocStackArray(cmr, pelementData, size) ); ElementData* elementData = *pelementData; for (size_t e = 0; e < size; ++e) { elementData[e].hashValue = 0; elementData[e].hashEntry = SIZE_MAX; elementData[e].inQueue = false; elementData[e].lastBFS = 0; } return CMR_OKAY; } static CMR_ERROR createHashVector( CMR* cmr, /**< \ref CMR environment. */ long long** phashVector, /**< Pointer for storing the hash vector. */ size_t size /**< Size of hash vector. */ ) { assert(cmr); CMR_CALL( CMRallocStackArray(cmr, phashVector, size) ); long long* hashVector = *phashVector; size_t h = 1; for (size_t e = 0; e < size; ++e) { hashVector[e] = h; CMRdbgMsg(2, "Entry %d has hash %ld.\n", e, h); h = projectSignedHash(3 * h); } return CMR_OKAY; } /** * \brief Scan the matrix to compute the number of nonzeros and the hash of each row and each column. */ static CMR_ERROR calcNonzeroCountHashFromMatrix( CMR* cmr, /**< \ref CMR environment. */ CMR_CHRMAT* matrix, /**< Matrix. */ ListMatrix* listmatrix, /**< List matrix representation. */ ElementData* rowData, /**< Other row element data. */ ElementData* columnData, /**< Other column element data. */ long long* hashVector /**< Hash vector. */ ) { assert(cmr); assert(matrix); assert(rowData); assert(columnData); for (size_t row = 0; row < matrix->numRows; ++row) { size_t first = matrix->rowSlice[row]; size_t beyond = matrix->rowSlice[row + 1]; for (size_t e = first; e < beyond; ++e) { size_t column = matrix->entryColumns[e]; char value = matrix->entryValues[e]; assert(value == 1 || value == -1); /* Update row data. */ listmatrix->rowElements[row].numNonzeros++; long long newHash = projectSignedHash(rowData[row].hashValue + value * hashVector[column]); rowData[row].hashValue = newHash; /* Update column data. */ listmatrix->columnElements[column].numNonzeros++; newHash = projectSignedHash(columnData[column].hashValue + value * hashVector[row]); columnData[column].hashValue = newHash; } } return CMR_OKAY; } /** * \brief Scan the matrix to compute the number of nonzeros and the hash of each row and each column. */ static CMR_ERROR calcBinaryHashFromListMatrix( CMR* cmr, /**< \ref CMR environment. */ ListMatrix* listmatrix, /**< List matrix. */ ElementData* rowData, /**< Other row element data. */ ElementData* columnData, /**< Other column element data. */ long long* hashVector /**< Hash vector. */ ) { assert(cmr); assert(listmatrix); assert(rowData); assert(columnData); /* Reset hash values. */ for (ListMatrixNonzero* rowHead = listmatrix->anchor.below; rowHead->row != SIZE_MAX; rowHead = rowHead->below) rowData[rowHead->row].hashValue = 0; for (ListMatrixNonzero* columnHead = listmatrix->anchor.right; columnHead->column != SIZE_MAX; columnHead = columnHead->right) { columnData[columnHead->column].hashValue = 0; } for (ListMatrixNonzero* rowHead = listmatrix->anchor.below; rowHead->row != SIZE_MAX; rowHead = rowHead->below) { for (ListMatrixNonzero* nz = rowHead->right; nz != rowHead; nz = nz->right) { /* Update row data. */ long long newHash = projectSignedHash(rowData[nz->row].hashValue + hashVector[nz->column]); rowData[nz->row].hashValue = newHash; /* Update column data. */ newHash = projectSignedHash(columnData[nz->column].hashValue + hashVector[nz->row]); columnData[nz->column].hashValue = newHash; } } return CMR_OKAY; } /** * \brief Scans the matrix initially in order to add all rows or columns either to the queue or to the hashtable. */ static CMR_ERROR initializeQueueHashtableFromMatrix( CMR* cmr, /**< \ref CMR environment. */ CMR_LISTHASHTABLE* hashtable, /**< Row or column hashtable. */ ListMatrixElement* listmatrixElements, /**< Row or column list matrix elements. */ ElementData* data, /**< Other row/column data. */ size_t sizeData, /**< Length of \p ListMatrixElements and \p data. */ CMR_ELEMENT* queue, /**< Queue. */ size_t* pqueueEnd, /**< Pointer to end of queue. */ bool isRow /**< Whether we are deadling with rows. */ ) { assert(cmr); assert(hashtable || sizeData == 0); for (size_t i = 0; i < sizeData; ++i) { CMRdbgMsg(2, "%s %d has %d nonzeros.\n", isRow ? "Row" : "Column", i, listmatrixElements[i].numNonzeros); /* Check if it qualifies for addition to the hashtable. */ if (listmatrixElements[i].numNonzeros > 1) { CMR_LISTHASHTABLE_ENTRY entry = CMRlisthashtableFindFirst(hashtable, llabs(data[i].hashValue)); CMRdbgMsg(2, "Search for hash %ld of %s %d yields entry %d.\n", data[i].hashValue, isRow ? "row" : "column", i, entry); if (entry == SIZE_MAX) { CMR_CALL( CMRlisthashtableInsert(cmr, hashtable, llabs(data[i].hashValue), i, &data[i].hashEntry) ); continue; } } /* If it was not added to the hashtable, we add it to the queue. */ queue[*pqueueEnd] = isRow ? CMRrowToElement(i) : CMRcolumnToElement(i); data[i].hashEntry = SIZE_MAX; data[i].inQueue = true; (*pqueueEnd)++; } return CMR_OKAY; } /** * \brief Adds all rows or columns of the list representation of the matrix either to the queue or to the hashtable. */ static CMR_ERROR initializeQueueHashtableFromListMatrix( CMR* cmr, /**< \ref CMR environment. */ CMR_LISTHASHTABLE* hashtable, /**< Row or column hashtable. */ ListMatrix* listmatrix, /**< List matrix. */ ElementData* data, /**< Other row/column data array. */ CMR_ELEMENT* queue, /**< Queue. */ size_t* pqueueEnd, /**< Pointer to end of queue. */ bool isRow /**< Whether we are deadling with rows. */ ) { assert(cmr); CMRdbgMsg(2, "Initializing queue and hashtable from list representation. Inspecting %s.\n", isRow ? "rows" : "columns"); ListMatrixNonzero* anchor = &listmatrix->anchor; for (ListMatrixNonzero* head = isRow ? anchor->below : anchor->right; head != anchor; head = (isRow ? head->below : head->right)) { size_t i = isRow ? head->row : head->column; CMRdbgMsg(4, "%s %d has %d nonzeros.\n", isRow ? "Row" : "Column", i, isRow ? listmatrix->rowElements[i].numNonzeros : listmatrix->columnElements[i].numNonzeros); /* Check if it qualifies for addition to the hashtable. */ CMR_LISTHASHTABLE_ENTRY entry = CMRlisthashtableFindFirst(hashtable, llabs(data[i].hashValue)); CMRdbgMsg(6, "Search for hash %ld of %s %d yields entry %d.\n", data[i].hashValue, isRow ? "row" : "column", i, entry); if (entry == SIZE_MAX) CMR_CALL( CMRlisthashtableInsert(cmr, hashtable, llabs(data[i].hashValue), i, &data[i].hashEntry) ); else { /* If it was not added to the hashtable, we add it to the queue. */ queue[*pqueueEnd] = isRow ? CMRrowToElement(i) : CMRcolumnToElement(i); data[i].hashEntry = SIZE_MAX; data[i].inQueue = true; (*pqueueEnd)++; } } return CMR_OKAY; } /** * \brief Checks whether the row/column at \p index is a (negated) copy of a row/column stored in the hashtable. * * Compares the actual vectors by traversing the linked-list representation. */ static size_t findCopy( ListMatrixElement* listData, /**< Row/column list data. */ ElementData* data, /**< Other row/column data. */ CMR_LISTHASHTABLE* hashtable, /**< Row/column hashtable. */ size_t index, /**< Index in \p data. */ bool isRow, /**< Whether we are dealing with rows. */ bool support /**< Whether only the support of the vector matters. */ ) { CMR_LISTHASHTABLE_HASH hash = llabs(data[index].hashValue); CMRdbgMsg(4, "Processing %s %d with a collision (hash value %ld).\n", isRow ? "row" : "column", index, data[index].hashValue); for (CMR_LISTHASHTABLE_ENTRY entry = CMRlisthashtableFindFirst(hashtable, hash); entry != SIZE_MAX; entry = CMRlisthashtableFindNext(hashtable, hash, entry)) { size_t collisionIndex = CMRlisthashtableValue(hashtable, entry); CMRdbgMsg(8, "%s %d has the same hash value. Comparing...\n", isRow ? "Row" : "Column", collisionIndex); bool equal = true; bool negated = true; if (isRow) { ListMatrixNonzero* nz1 = listData[index].head.right; ListMatrixNonzero* nz2 = listData[collisionIndex].head.right; while (equal || negated || support) { if (nz1->column != nz2->column) { equal = false; negated = false; support = false; break; } if (nz1->column == SIZE_MAX) break; if (nz1->value == nz2->value) negated = false; else equal = false; nz1 = nz1->right; nz2 = nz2->right; } } else { ListMatrixNonzero* nz1 = listData[index].head.below; ListMatrixNonzero* nz2 = listData[collisionIndex].head.below; while (equal || negated || support) { if (nz1->row != nz2->row) { equal = false; negated = false; support = false; break; } if (nz1->row == SIZE_MAX) break; if (nz1->value == nz2->value) negated = false; else equal = false; nz1 = nz1->below; nz2 = nz2->below; } } if (equal || negated || support) return collisionIndex; } return SIZE_MAX; } /** * \brief Processes the deletion of a nonzero from the linked-list representation. */ static CMR_ERROR processNonzero( CMR* cmr, /**< \ref CMR environment. */ CMR_LISTHASHTABLE* hashtable, /**< Row/column hashtable. */ long long hashChange, /**< Modification of the hash value. */ size_t index, /**< Index of row/column. */ ListMatrixElement* indexListData, /**< Row/column list data. */ ElementData* indexData, /**< Other row/column data. */ CMR_ELEMENT* queue, /**< Queue. */ size_t* pqueueEnd, /**< Pointer to end of queue. */ size_t queueMemory, /**< Memory allocated for queue. */ bool isRow /**< Whether we are dealing with rows. */ ) { assert(cmr); assert(indexData); assert(hashtable); assert(queue); indexListData->numNonzeros--; long long newHash = projectSignedHash(indexData->hashValue + hashChange); CMRdbgMsg(4, "Processing nonzero. Old hash is %ld, change is %ld, new hash is %ld.\n", indexData->hashValue, hashChange, newHash); indexData->hashValue = newHash; /* Add to queue if necessary. */ if (!indexData->inQueue) { queue[*pqueueEnd % queueMemory] = isRow ? CMRrowToElement(index) : CMRcolumnToElement(index); indexData->inQueue = true; (*pqueueEnd)++; } /* Remove from hashtable if necessary. */ if (indexData->hashEntry != SIZE_MAX) { CMR_CALL( CMRlisthashtableRemove(cmr, hashtable, indexData->hashEntry) ); indexData->hashEntry = SIZE_MAX; } return CMR_OKAY; } /** * \brief Carry out the actual reduction algorithm after all data structures are initialized. */ static CMR_ERROR reduceListMatrix( CMR* cmr, /**< \ref CMR environment. */ ListMatrix* listmatrix, /**< List matrix. */ ElementData* rowData, /**< Row data. */ ElementData* columnData, /**< Column data. */ CMR_LISTHASHTABLE* rowHashtable, /**< Row hashtable. */ CMR_LISTHASHTABLE* columnHashtable, /**< Column hashtable. */ long long* entryToHash, /**< Pre-computed hash values of vector entries. */ CMR_ELEMENT* queue, /**< Queue. */ size_t* pqueueStart, /**< Pointer to start of queue. */ size_t* pqueueEnd, /**< Pointer to end of queue. */ size_t queueMemory, /**< Memory allocated for queue. */ CMR_SP_REDUCTION* reductions, /**< Array for storing the SP-reductions. Must be sufficiently large, e.g., number **< of rows + number of columns. */ size_t* pnumReductions, /**< Pointer for storing the number of SP-reductions. */ size_t* pnumRowReductions, /**< Pointer for storing the number of row reductions (may be \c NULL). */ size_t* pnumColumnReductions /**< Pointer for storing the number of column reductions (may be \c NULL). */ ) { assert(cmr); assert(listmatrix); while (*pqueueEnd > *pqueueStart) { #if defined(CMR_DEBUG) CMRdbgMsg(0, "\n Status:\n"); for (ListMatrixNonzero* nz = listmatrix->anchor.below; nz != &listmatrix->anchor; nz = nz->below) { size_t row = nz->row; CMRdbgMsg(6, "Row r%d: %d nonzeros, hashed = %s, hash = %ld", row+1, listmatrix->rowElements[row].numNonzeros, rowData[row].hashEntry == SIZE_MAX ? "NO" : "YES", rowData[row].hashValue); if (rowData[row].hashEntry != SIZE_MAX) { CMRdbgMsg(0, ", hashtable entry: %d with hash=%d, value=%d", rowData[row].hashEntry, CMRlisthashtableHash(rowHashtable, rowData[row].hashEntry), CMRlisthashtableValue(rowHashtable, rowData[row].hashEntry)); } CMRdbgMsg(0, "\n"); } for (ListMatrixNonzero* nz = listmatrix->anchor.right; nz != &listmatrix->anchor; nz = nz->right) { size_t column = nz->column; CMRdbgMsg(6, "Column c%d: %d nonzeros, hashed = %s, hash = %ld", column+1, listmatrix->columnElements[column].numNonzeros, columnData[column].hashEntry == SIZE_MAX ? "NO" : "YES", columnData[column].hashValue); if (columnData[column].hashEntry != SIZE_MAX) { CMRdbgMsg(0, ", hashtable entry: %d with hash=%d, value=%d", columnData[column].hashEntry, CMRlisthashtableHash(columnHashtable, columnData[column].hashEntry), CMRlisthashtableValue(columnHashtable, columnData[column].hashEntry)); } CMRdbgMsg(0, "\n"); } for (size_t q = *pqueueStart; q < *pqueueEnd; ++q) { CMR_ELEMENT e = queue[q % queueMemory]; CMRdbgMsg(6, "Queue #%d @ %d: %s %d\n", q, q % queueMemory, CMRelementIsRow(e) ? "row" : "column", CMRelementIsRow(e) ? CMRelementToRowIndex(e) : CMRelementToColumnIndex(e)); } CMRdbgMsg(0, "\n"); #endif /* CMR_DEBUG */ CMR_ELEMENT element = queue[(*pqueueStart) % queueMemory]; ++(*pqueueStart); CMRdbgMsg(2, "Top element is %s %d with %d nonzeros.\n", CMRelementIsRow(element) ? "row" : "column", CMRelementIsRow(element) ? CMRelementToRowIndex(element) : CMRelementToColumnIndex(element), CMRelementIsRow(element) ? listmatrix->rowElements[CMRelementToRowIndex(element)].numNonzeros : listmatrix->columnElements[CMRelementToColumnIndex(element)].numNonzeros); if (CMRelementIsRow(element)) { /* We consider a row. */ size_t row1 = CMRelementToRowIndex(element); if (listmatrix->rowElements[row1].numNonzeros > 1) { rowData[row1].inQueue = false; size_t row2 = findCopy(listmatrix->rowElements, rowData, rowHashtable, row1, true, false); if (row2 == SIZE_MAX) { CMRdbgMsg(6, "No parallel row found. Inserting row %d.\n", row1); CMR_CALL( CMRlisthashtableInsert(cmr, rowHashtable, llabs(rowData[row1].hashValue), row1, &rowData[row1].hashEntry) ); } else { CMRdbgMsg(6, "Row %d is parallel.\n", row2); /* We found a parallel row. */ reductions[*pnumReductions].element = CMRrowToElement(row1); reductions[*pnumReductions].mate = CMRrowToElement(row2); (*pnumReductions)++; (*pnumRowReductions)++; for (ListMatrixNonzero* entry = listmatrix->rowElements[row1].head.right; entry->column != SIZE_MAX; entry = entry->right) { CMRdbgMsg(8, "Processing nonzero at column %d.\n", entry->column); unlinkNonzero(entry); CMR_CALL( processNonzero(cmr, columnHashtable, -entryToHash[entry->row] * entry->value, entry->column, &listmatrix->columnElements[entry->column], &columnData[entry->column], queue, pqueueEnd, queueMemory, false) ); } listmatrix->rowElements[row1].numNonzeros = 0; rowData[row1].lastBFS = -2; listmatrix->rowElements[row1].head.above->below = listmatrix->rowElements[row1].head.below; listmatrix->rowElements[row1].head.below->above = listmatrix->rowElements[row1].head.above; assert(listmatrix->rowElements[row1].head.left == &listmatrix->rowElements[row1].head); assert(listmatrix->rowElements[row1].head.right == &listmatrix->rowElements[row1].head); } } else { /* Zero or unit row vector. */ CMRdbgMsg(4, "Processing %s row %d.\n", listmatrix->rowElements[row1].numNonzeros == 0 ? "zero" : "unit", row1); rowData[row1].inQueue = false; if (listmatrix->rowElements[row1].numNonzeros) { ListMatrixNonzero* entry = listmatrix->rowElements[row1].head.right; size_t column = entry->column; CMRdbgMsg(4, "Processing unit row %d with 1 in column %d.\n", row1, column); unlinkNonzero(entry); listmatrix->rowElements[row1].numNonzeros--; CMR_CALL( processNonzero(cmr, columnHashtable, -entryToHash[entry->row] * entry->value, column, &listmatrix->columnElements[column], &columnData[column], queue, pqueueEnd, queueMemory, false) ); reductions[*pnumReductions].mate = CMRcolumnToElement(column); } else reductions[*pnumReductions].mate = 0; reductions[*pnumReductions].element = element; (*pnumReductions)++; (*pnumRowReductions)++; rowData[row1].lastBFS = -2; listmatrix->rowElements[row1].head.above->below = listmatrix->rowElements[row1].head.below; listmatrix->rowElements[row1].head.below->above = listmatrix->rowElements[row1].head.above; } } else { /* We consider a column. */ size_t column1 = CMRelementToColumnIndex(element); if (listmatrix->columnElements[column1].numNonzeros > 1) { columnData[column1].inQueue = false; size_t column2 = findCopy(listmatrix->columnElements, columnData, columnHashtable, column1, false, false); if (column2 == SIZE_MAX) { CMRdbgMsg(6, "No parallel column found. Inserting column %d.\n", column1); CMR_CALL( CMRlisthashtableInsert(cmr, columnHashtable, llabs(columnData[column1].hashValue), column1, &columnData[column1].hashEntry) ); } else { CMRdbgMsg(6, "Column %d is parallel.\n", column2); /* We found a parallel column. */ reductions[*pnumReductions].element = CMRcolumnToElement(column1); reductions[*pnumReductions].mate = CMRcolumnToElement(column2); (*pnumReductions)++; (*pnumColumnReductions)++; columnData[column1].lastBFS = -2; for (ListMatrixNonzero* entry = listmatrix->columnElements[column1].head.below; entry->row != SIZE_MAX; entry = entry->below) { CMRdbgMsg(8, "Processing nonzero at row %d.\n", entry->row); unlinkNonzero(entry); CMR_CALL( processNonzero(cmr, rowHashtable, -entryToHash[entry->column] * entry->value, entry->row, &listmatrix->rowElements[entry->row], &rowData[entry->row], queue, pqueueEnd, queueMemory, true) ); } listmatrix->columnElements[column1].numNonzeros = 0; listmatrix->columnElements[column1].head.left->right = listmatrix->columnElements[column1].head.right; listmatrix->columnElements[column1].head.right->left = listmatrix->columnElements[column1].head.left; assert(listmatrix->columnElements[column1].head.above == &listmatrix->columnElements[column1].head); assert(listmatrix->columnElements[column1].head.below == &listmatrix->columnElements[column1].head); } } else { /* Zero or unit column vector. */ CMRdbgMsg(4, "Processing %s column %d.\n", listmatrix->columnElements[column1].numNonzeros == 0 ? "zero" : "unit", column1); columnData[column1].inQueue = false; if (listmatrix->columnElements[column1].numNonzeros) { ListMatrixNonzero* entry = listmatrix->columnElements[column1].head.below; size_t row = entry->row; CMRdbgMsg(4, "Processing unit column %d with 1 in row %d.\n", column1, row); unlinkNonzero(entry); listmatrix->columnElements[column1].numNonzeros--; CMR_CALL( processNonzero(cmr, rowHashtable, -entryToHash[entry->column] * entry->value, row, &listmatrix->rowElements[row], &rowData[row], queue, pqueueEnd, queueMemory, true) ); reductions[*pnumReductions].mate = CMRrowToElement(row); } else reductions[*pnumReductions].mate = 0; reductions[*pnumReductions].element = element; (*pnumReductions)++; (*pnumColumnReductions)++; columnData[column1].lastBFS = -2; listmatrix->columnElements[column1].head.left->right = listmatrix->columnElements[column1].head.right; listmatrix->columnElements[column1].head.right->left = listmatrix->columnElements[column1].head.left; } } } return CMR_OKAY; } /** * \brief Try to find an \f$ M_2 \f$-submatrix for a ternary SP-reduced matrix in list representation. */ static CMR_ERROR extractNonbinarySubmatrix( CMR* cmr, /**< \ref CMR environment. */ ListMatrix* listmatrix, /**< List matrix. */ ElementData* rowData, /**< Row data. */ ElementData* columnData, /**< Column data. */ CMR_LISTHASHTABLE* rowHashtable, /**< Row hashtable. */ CMR_LISTHASHTABLE* columnHashtable, /**< Column hashtable. */ long long* entryToHash, /**< Pre-computed hash values of vector entries. */ CMR_ELEMENT* queue, /**< Queue. */ size_t* pqueueStart, /**< Pointer to start of queue. */ size_t* pqueueEnd, /**< Pointer to end of queue. */ size_t queueMemory, /**< Memory allocated for queue. */ CMR_SUBMAT** pviolatorSubmatrix /**< Pointer for storing the submatrix if an \f$ M_2 \f$-submatrix is found. */ ) { assert(cmr); assert(listmatrix); assert(rowData); assert(columnData); assert(rowHashtable); assert(columnHashtable); assert(entryToHash); assert(queue); assert(pviolatorSubmatrix); CMRdbgMsg(2, "Searching for M_2-submatrix.\n"); *pviolatorSubmatrix = NULL; while (*pqueueEnd > *pqueueStart) { #if defined(CMR_DEBUG) CMRdbgMsg(0, "\n"); for (size_t q = *pqueueStart; q < *pqueueEnd; ++q) { CMR_ELEMENT e = queue[q % queueMemory]; CMRdbgMsg(6, "Queue #%d @ %d: %s\n", q, q % queueMemory, CMRelementString(e, NULL)); } CMRdbgMsg(0, "\n"); #endif /* CMR_DEBUG */ CMR_ELEMENT element = queue[(*pqueueStart) % queueMemory]; ++(*pqueueStart); if (CMRelementIsRow(element)) { /* We consider a row. */ size_t row1 = CMRelementToRowIndex(element); assert(listmatrix->rowElements[row1].numNonzeros > 1); rowData[row1].inQueue = false; size_t row2 = findCopy(listmatrix->rowElements, rowData, rowHashtable, row1, true, true); if (row2 == SIZE_MAX) { CMRdbgMsg(6, "No parallel row found. Inserting row %d.\n", row1); CMR_CALL( CMRlisthashtableInsert(cmr, rowHashtable, llabs(rowData[row1].hashValue), row1, &rowData[row1].hashEntry) ); } else { CMRdbgMsg(6, "Row %d is parallel.\n", row2); /* We found a row copy. */ size_t column1 = SIZE_MAX; size_t column2 = SIZE_MAX; ListMatrixNonzero* nz1 = listmatrix->rowElements[row1].head.right; ListMatrixNonzero* nz2 = listmatrix->rowElements[row2].head.right; while (column1 == SIZE_MAX || column2 == SIZE_MAX) { if (nz1->value == nz2->value) { if (column1 == SIZE_MAX) column1 = nz1->column; } else { if (column2 == SIZE_MAX) column2 = nz1->column; } nz1 = nz1->right; nz2 = nz2->right; } CMR_CALL( CMRsubmatCreate(cmr, 2, 2, pviolatorSubmatrix) ); CMR_SUBMAT* violatorSubmatrix = *pviolatorSubmatrix; violatorSubmatrix->rows[0] = row1; violatorSubmatrix->rows[1] = row2; violatorSubmatrix->columns[0] = column1; violatorSubmatrix->columns[1] = column2; break; } } else { /* We consider a column. */ size_t column1 = CMRelementToColumnIndex(element); assert(listmatrix->columnElements[column1].numNonzeros > 1); columnData[column1].inQueue = false; size_t column2 = findCopy(listmatrix->columnElements, columnData, columnHashtable, column1, false, true); if (column2 == SIZE_MAX) { CMRdbgMsg(6, "No parallel column found. Inserting column %d.\n", column1); CMR_CALL( CMRlisthashtableInsert(cmr, columnHashtable, llabs(columnData[column1].hashValue), column1, &columnData[column1].hashEntry) ); } else { CMRdbgMsg(6, "Column %d is parallel.\n", column2); /* We found a column copy. */ size_t row1 = SIZE_MAX; size_t row2 = SIZE_MAX; ListMatrixNonzero* nz1 = listmatrix->columnElements[column1].head.below; ListMatrixNonzero* nz2 = listmatrix->columnElements[column2].head.below; while (row1 == SIZE_MAX || row2 == SIZE_MAX) { if (nz1->value == nz2->value) { if (row1 == SIZE_MAX) row1 = nz1->row; } else { if (row2 == SIZE_MAX) row2 = nz1->row; } nz1 = nz1->below; nz2 = nz2->below; } CMR_CALL( CMRsubmatCreate(cmr, 2, 2, pviolatorSubmatrix) ); CMR_SUBMAT* violatorSubmatrix = *pviolatorSubmatrix; violatorSubmatrix->rows[0] = row1; violatorSubmatrix->rows[1] = row2; violatorSubmatrix->columns[0] = column1; violatorSubmatrix->columns[1] = column2; break; } } } return CMR_OKAY; } static CMR_ERROR breadthFirstSearch( CMR* cmr, /**< \ref CMR environment. */ size_t currentBFS, /**< Number of this execution of breadth-first search. */ ListMatrixElement* rowListData, /**< Row data. */ ListMatrixElement* columnListData, /**< Column data. */ ElementData* rowData, /**< Row data. */ ElementData* columnData, /**< Column data. */ CMR_ELEMENT* queue, /**< Queue. */ size_t queueMemory, /**< Memory for queue. */ CMR_ELEMENT* sources, /**< Array of source nodes. */ size_t numSources, /**< Number of source nodes. */ CMR_ELEMENT* targets, /**< Array of target nodes. */ size_t numTargets, /**< Number of target nodes. */ size_t* pfoundTarget, /**< Pointer for storing the index of the target node found. */ size_t* pnumEdges /**< Pointer for storing the number of traversed edges. */ ) { assert(cmr); assert(rowData); assert(columnData); assert(queue); assert(queueMemory > 0); CMRdbgMsg(6, "BFS #%d for %d sources and %d targets.\n", currentBFS, numSources, numTargets); size_t queueStart = 0; size_t queueEnd = numSources; for (size_t s = 0; s < numSources; ++s) { CMR_ELEMENT element = sources[s]; queue[s] = element; if (CMRelementIsRow(element)) { size_t row = CMRelementToRowIndex(element); rowData[row].distance = 0; rowData[row].lastBFS = currentBFS; } else { size_t column = CMRelementToColumnIndex(element); columnData[column].distance = 0; columnData[column].lastBFS = currentBFS; } } for (size_t t = 0; t < numTargets; ++t) { CMR_ELEMENT element = targets[t]; if (CMRelementIsRow(element)) rowData[CMRelementToRowIndex(element)].lastBFS = currentBFS+1; else columnData[CMRelementToColumnIndex(element)].lastBFS = currentBFS+1; } if (pnumEdges) *pnumEdges = 0; while (queueEnd > queueStart) { CMR_ELEMENT element = queue[queueStart % queueMemory]; queueStart++; CMRdbgMsg(8, "Queue: %s", CMRelementString(element, NULL)); for (size_t q = queueStart; q < queueEnd; ++q) CMRdbgMsg(0, ",%s", CMRelementString(queue[q % queueMemory], NULL)); CMRdbgMsg(0, "\n"); if (CMRelementIsRow(element)) { size_t row = CMRelementToRowIndex(element); for (ListMatrixNonzero* nz = rowListData[row].head.right; nz->column != SIZE_MAX; nz = nz->right) { /* Skip edge if disabled. */ if (nz->special) { CMRdbgMsg(10, "Edge r%d,c%d is disabled.\n", nz->row+1, nz->column+1); continue; } if (pnumEdges) (*pnumEdges)++; size_t column = nz->column; if (columnData[column].lastBFS != currentBFS) { /* We found a new column node. */ CMRdbgMsg(10, "Node c%d receives distance %d (last BFS #%d)\n", column+1, rowData[row].distance + 1, columnData[column].lastBFS); columnData[column].distance = rowData[row].distance + 1; columnData[column].predecessor = row; queue[queueEnd % queueMemory] = CMRcolumnToElement(column); queueEnd++; if (columnData[column].lastBFS == currentBFS+1) { queueStart = queueEnd; if (pfoundTarget) { for (size_t t = 0; t < numTargets; ++t) { if (targets[t] == CMRcolumnToElement(column)) { *pfoundTarget = t; break; } } } break; } else columnData[column].lastBFS = currentBFS; } else { CMRdbgMsg(10, "Node c%d already known.\n", column+1); } } } else { size_t column = CMRelementToColumnIndex(element); for (ListMatrixNonzero* nz = columnListData[column].head.below; nz->row != SIZE_MAX; nz = nz->below) { /* Skip edge if disabled. */ if (nz->special) { CMRdbgMsg(10, "Edge r%d,c%d is disabled.\n", nz->row+1, nz->column+1); continue; } if (pnumEdges) (*pnumEdges)++; size_t row = nz->row; if (rowData[row].lastBFS != currentBFS) { /* We found a new row node. */ CMRdbgMsg(10, "Node r%d receives distance %d (last BFS #%d)\n", row+1, columnData[column].distance + 1, rowData[row].lastBFS); rowData[row].distance = columnData[column].distance + 1; rowData[row].predecessor = column; queue[queueEnd % queueMemory] = CMRrowToElement(row); queueEnd++; if (rowData[row].lastBFS == currentBFS+1) { queueStart = queueEnd; if (pfoundTarget) { for (size_t t = 0; t < numTargets; ++t) { if (targets[t] == CMRrowToElement(row)) { *pfoundTarget = t; break; } } } break; } else rowData[row].lastBFS = currentBFS; } else { CMRdbgMsg(10, "Node r%d already known.\n", row+1); } } } } /* Reset lastBFS for targets. */ for (size_t t = 0; t < numTargets; ++t) { CMR_ELEMENT element = targets[t]; if (CMRelementIsRow(element)) rowData[CMRelementToRowIndex(element)].lastBFS = 0; else columnData[CMRelementToColumnIndex(element)].lastBFS = 0; } if (pnumEdges) (*pnumEdges) /= 2; return CMR_OKAY; } /** * \brief Extract remaining submatrix. */ static CMR_ERROR extractRemainingSubmatrix( CMR* cmr, /**< \ref CMR environment. */ CMR_CHRMAT* matrix, /**< Matrix. */ size_t numRowReductions, /**< Number of row SP reductions. */ size_t numColumnReductions, /**< Number of column SP reductions. */ ListMatrix* listmatrix, /**< List matrix. */ CMR_SUBMAT** preducedSubmatrix /**< Pointer for storing the reduced submatrix. */ ) { assert(cmr); assert(matrix); assert(listmatrix); assert(preducedSubmatrix); CMR_CALL( CMRsubmatCreate(cmr, matrix->numRows - numRowReductions, matrix->numColumns - numColumnReductions, preducedSubmatrix) ); CMR_SUBMAT* remainingSubmatrix = *preducedSubmatrix; size_t rowSubmatrix = 0; for (size_t row = 0; row < matrix->numRows; ++row) { if (listmatrix->rowElements[row].numNonzeros > 0) remainingSubmatrix->rows[rowSubmatrix++] = row; } assert(rowSubmatrix + numRowReductions == matrix->numRows); size_t columnSubmatrix = 0; for (size_t column = 0; column < matrix->numColumns; ++column) { if (listmatrix->columnElements[column].numNonzeros > 0) remainingSubmatrix->columns[columnSubmatrix++] = column; } assert(columnSubmatrix + numColumnReductions == matrix->numColumns); return CMR_OKAY; } /** * \brief Create full matrix as remaining submatrix. */ static CMR_ERROR createFullRemainingMatrix( CMR* cmr, /**< \ref CMR environment. */ CMR_CHRMAT* matrix, /**< Matrix. */ CMR_SUBMAT** preducedSubmatrix /**< Pointer for storing the reduced submatrix. */ ) { CMR_CALL( CMRsubmatCreate(cmr, matrix->numRows, matrix->numColumns, preducedSubmatrix) ); CMR_SUBMAT* remainingSubmatrix = *preducedSubmatrix; for (size_t row = 0; row < matrix->numRows; ++row) remainingSubmatrix->rows[row] = row; for (size_t column = 0; column < matrix->numColumns; ++column) remainingSubmatrix->columns[column] = column; return CMR_OKAY; } /** * \brief Searches for a wheel-submatrix. */ static CMR_ERROR extractWheelSubmatrix( CMR* cmr, /**< \ref CMR environment. */ ListMatrix* listmatrix, /**< List matrix. */ ElementData* rowData, /**< Row element data. */ ElementData* columnData, /**< Column element data. */ CMR_ELEMENT* queue, /**< Queue memory. */ size_t queueMemory, /**< Size of \p queue. */ size_t numReducedRows, /**< Number of rows in reduced matrix. */ size_t numReducedColumns, /**< Number of columns in reduced matrix. */ CMR_SUBMAT** pwheelSubmatrix, /**< Pointer for storing the wheel submatrix (may be \c NULL). */ CMR_SEPA** pseparation /**< Pointer for storing a 2-separation (may be \c NULL). */ ) { assert(cmr); assert(listmatrix); CMRdbgMsg(2, "Searching for wheel graph representation submatrix.\n"); size_t numRows = listmatrix->numRows; size_t numColumns = listmatrix->numColumns; size_t currentBFS = 0; for (size_t row = 0; row < numRows; ++row) rowData[row].specialBFS = false; for (size_t column = 0; column < numColumns; ++column) columnData[column].specialBFS = false; ListMatrixNonzero** nzBlock = NULL; /* Pointers for simultaneously traversing columns of block. */ CMR_CALL( CMRallocStackArray(cmr, &nzBlock, numColumns) ); CMR_ELEMENT* sources = NULL; CMR_CALL( CMRallocStackArray(cmr, &sources, numRows) ); CMR_ELEMENT* targets = NULL; CMR_CALL( CMRallocStackArray(cmr, &targets, numColumns) ); size_t numEdges = 0; for (size_t row = 0; row < numRows; ++row) numEdges += listmatrix->rowElements[row].numNonzeros; while (true) { size_t sourceRow = listmatrix->anchor.below->row; rowData[sourceRow].lastBFS = currentBFS; rowData[sourceRow].predecessor = SIZE_MAX; rowData[sourceRow].distance = 0; size_t targetColumn = listmatrix->rowElements[sourceRow].head.right->column; listmatrix->rowElements[sourceRow].head.right->special = 1; CMRdbgMsg(4, "Searching for a chordless cycle from r%d to c%d.\n", sourceRow+1, targetColumn+1); sources[0] = CMRrowToElement(sourceRow); targets[0] = CMRcolumnToElement(targetColumn); size_t foundTarget = SIZE_MAX; currentBFS++; CMR_CALL( breadthFirstSearch(cmr, currentBFS, listmatrix->rowElements, listmatrix->columnElements, rowData, columnData, queue, queueMemory, sources, 1, targets, 1, &foundTarget, 0) ); listmatrix->rowElements[sourceRow].head.right->special = 0; size_t length = (foundTarget == SIZE_MAX) ? SIZE_MAX : columnData[targetColumn].distance + 1; CMRdbgMsg(4, "Length of cycle is %d.\n", length); if (foundTarget < SIZE_MAX && length > 4) { /* We found a long chordless cycle. Traverse backwards along path and collect rows/columns. */ if (pwheelSubmatrix) { CMR_CALL( CMRsubmatCreate(cmr, length/2, length/2, pwheelSubmatrix) ); CMR_SUBMAT* wheelSubmatrix = *pwheelSubmatrix; size_t column = targetColumn; size_t row; for (size_t i = 0; i < length/2; ++i) { row = columnData[column].predecessor; wheelSubmatrix->columns[i] = column; wheelSubmatrix->rows[i] = row; column = rowData[row].predecessor; } } break; } size_t numSources = SIZE_MAX; size_t numTargets = SIZE_MAX; size_t numTraversedEdges = SIZE_MAX; if (foundTarget < SIZE_MAX) { assert(length == 4); /* We have found a 2-by-2 matrix with only 1's. */ size_t row1 = sourceRow; size_t row2 = columnData[targetColumn].predecessor; CMRdbgMsg(4, "Growing the 2x2 submatrix with 1's is at r%d, r%d, c%d, c%d.\n", row1+1, row2+1, targetColumn+1, rowData[row2].predecessor+1); /* Go trough the two nonzeros of the two rows simultaneously. */ ListMatrixNonzero* nz1 = listmatrix->rowElements[row1].head.right; ListMatrixNonzero* nz2 = listmatrix->rowElements[row2].head.right; numTargets = 0; while (nz1->column != SIZE_MAX) { CMRdbgMsg(6, "nonzeros at column indices %d and %d.\n", nz1->column, nz2->column); if (nz1->column < nz2->column) { nz1 = nz1->right; } else if (nz1->column > nz2->column) nz2 = nz2->right; else { columnData[nz1->column].specialBFS = true; nzBlock[numTargets] = listmatrix->columnElements[nz1->column].head.below; targets[numTargets++] = CMRcolumnToElement(nz1->column); nz1 = nz1->right; nz2 = nz2->right; } } CMRdbgMsg(4, "Identified %d target columns.\n", numTargets); assert(numTargets >= 2); /* Go through the nonzeros of all marked columns simultaneously. */ size_t maxIndex = 0; size_t maxRow = nzBlock[0]->row; size_t currentIndex = 1; numSources = 0; while (maxRow != SIZE_MAX) { if (currentIndex == maxIndex) { /* All nonzeros now have the same row. */ for (size_t j = 0; j < numTargets; ++j) nzBlock[j]->special = 1; rowData[maxRow].specialBFS = true; sources[numSources++] = CMRrowToElement(maxRow); ++maxRow; } while (nzBlock[currentIndex]->row < maxRow) nzBlock[currentIndex] = nzBlock[currentIndex]->below; if (nzBlock[currentIndex]->row > maxRow) { maxIndex = currentIndex; maxRow = nzBlock[currentIndex]->row; } currentIndex = (currentIndex + 1) % numTargets; } CMRdbgMsg(4, "Identified %d source rows.\n", numSources); assert(numSources >= 2); currentBFS++; foundTarget = SIZE_MAX; numTraversedEdges = 0; CMR_CALL( breadthFirstSearch(cmr, currentBFS, listmatrix->rowElements, listmatrix->columnElements, rowData, columnData, queue, queueMemory, sources, numSources, targets, numTargets, &foundTarget, &numTraversedEdges) ); } if (foundTarget < SIZE_MAX && pwheelSubmatrix) { size_t length = columnData[CMRelementToColumnIndex(targets[foundTarget])].distance + 1; targetColumn = CMRelementToColumnIndex(targets[foundTarget]); CMRdbgMsg(4, "Length of cycle is %d.\n", length); size_t wheelSize = length == 4 ? 3 : length/2; CMR_CALL( CMRsubmatCreate(cmr, wheelSize, wheelSize, pwheelSubmatrix) ); CMR_SUBMAT* wheelSubmatrix = *pwheelSubmatrix; if (length > 4) { /* The cycle is long and we simply traverse it and collect all rows and columns. */ size_t column = targetColumn; size_t row; for (size_t i = 0; i < length/2; ++i) { row = columnData[column].predecessor; wheelSubmatrix->columns[i] = column; wheelSubmatrix->rows[i] = row; column = rowData[row].predecessor; } } else { /* The cycle is short and we need to add one row and one column from the block of 1's. */ size_t column1 = targetColumn; /* Belongs to block. */ size_t row2 = columnData[column1].predecessor; /* Does not belong to block. */ size_t column2 = rowData[row2].predecessor; /* Does not belong to block. */ size_t row1 = columnData[column2].predecessor; /* Belongs to block. */ CMRdbgMsg(4, "Short cycle is induced by r%d,r%d,c%d,c%d.\n", row1+1, row2+1, column1+1, column2+1); /* Go through nonzeros of row2 and mark them. */ for (ListMatrixNonzero* nz = listmatrix->rowElements[row2].head.right; nz->column != SIZE_MAX; nz = nz->right) columnData[nz->column].lastBFS = -1; /* Find a non-marked source column. */ size_t column3 = SIZE_MAX; for (size_t t = 0; t < numTargets; ++t) { column3 = CMRelementToColumnIndex(targets[t]); if (columnData[column3].lastBFS >= 0) break; } assert(column3 != SIZE_MAX); CMRdbgMsg(4, "Adding c%d\n", column3+1); /* Go through nonzeros of column 2 and mark them. */ for (ListMatrixNonzero* nz = listmatrix->columnElements[column2].head.below; nz->row != SIZE_MAX; nz = nz->below) rowData[nz->row].lastBFS = -1; /* Find a non-marked source column. */ size_t row3 = SIZE_MAX; for (size_t s = 0; s < numSources; ++s) { row3 = CMRelementToRowIndex(sources[s]); if (rowData[row3].lastBFS >= 0) break; } assert(row3 != SIZE_MAX); CMRdbgMsg(4, "Adding r%d\n", row3+1); wheelSubmatrix->rows[0] = row3; wheelSubmatrix->rows[1] = row1; wheelSubmatrix->rows[2] = row2; wheelSubmatrix->columns[0] = column3; wheelSubmatrix->columns[1] = column1; wheelSubmatrix->columns[2] = column2; } break; } else if (foundTarget < SIZE_MAX) { /* Wheel found, but the user does not care. */ break; } assert(foundTarget == SIZE_MAX); if (pseparation) { CMRdbgMsg(4, "No path found. Extracting 2-separation.\n"); CMR_CALL( CMRsepaCreate(cmr, numReducedRows, numReducedColumns, pseparation) ); CMR_SEPA* sepa = *pseparation; /* Collect all reduced reachable rows/columns. */ size_t reducedRow = 0; size_t reducedSourceRow = 0; for (size_t row = 0; row < numRows; ++row) { if (rowData[row].lastBFS == -2) continue; sepa->rowsToPart[reducedRow] = (rowData[row].lastBFS == currentBFS) ? 0 : 1; CMRdbgMsg(6, "Assigning row r%ld = reduced row r%ld to part %d.\n", row+1, reducedRow+1, sepa->rowsToPart[reducedRow]); if (row == sourceRow) reducedSourceRow = reducedRow; ++reducedRow; } /* Collect all reduced columns that are not reachable. */ size_t reducedColumn = 0; size_t reducedTargetColumn = 0; for (size_t column = 0; column < numColumns; ++column) { if (columnData[column].lastBFS == -2) continue; sepa->columnsToPart[reducedColumn] = (columnData[column].lastBFS == currentBFS) ? 0 : 1; CMRdbgMsg(6, "Assigning column c%ld = reduced column c%ld to part %d.\n", column+1, reducedColumn+1, sepa->columnsToPart[column]); if (column == targetColumn) reducedTargetColumn = reducedColumn; ++reducedColumn; } CMRdbgMsg(6, "Extra row r%ld = reduced row r%ld for part 1 and extra column c%ld = reduced column c%ld for part 0.\n", sourceRow + 1, reducedSourceRow + 1, targetColumn + 1, reducedTargetColumn + 1); CMR_CALL( CMRsepaInitialize(cmr, sepa, SIZE_MAX, SIZE_MAX, reducedSourceRow, reducedTargetColumn, SIZE_MAX, SIZE_MAX, SIZE_MAX, SIZE_MAX) ); break; } CMRdbgMsg(4, "No path found. Determining smaller part of 2-separation.\n"); CMRdbgMsg(4, "%d edges were traversed, %d are in rank-1 submatrix, and %d of %d remain.\n", numTraversedEdges, numSources * numTargets, numEdges - numTraversedEdges - numSources * numTargets, numEdges); size_t numEdgesPartWithColumn = numTraversedEdges + numSources; size_t numEdgesPartWithRow = numEdges - numTraversedEdges - (numSources - 1) * numTargets; CMRdbgMsg(4, "Part with a column from block has %d nonzeros, part with a row from the block has %d nonzeros.\n", numEdgesPartWithColumn, numEdgesPartWithRow); /* We restrict our search on the smaller part. */ if (numEdgesPartWithColumn <= numEdgesPartWithRow) { numEdges = numEdgesPartWithColumn; /* Remove all but one column from the block. */ for (size_t t = 0; t < numTargets; ++t) { size_t column = CMRelementToColumnIndex(targets[t]); for (ListMatrixNonzero* nz = listmatrix->columnElements[column].head.below; nz->row != SIZE_MAX; nz = nz->below) { if (t > 0 || !rowData[nz->row].specialBFS) { listmatrix->rowElements[nz->row].numNonzeros--; unlinkNonzero(nz); } else nz->special = 0; } if (t == 0) listmatrix->columnElements[column].numNonzeros = numSources; else { listmatrix->columnElements[column].numNonzeros = 0; listmatrix->columnElements[column].head.left->right = listmatrix->columnElements[column].head.right; listmatrix->columnElements[column].head.right->left = listmatrix->columnElements[column].head.left; } } /* Mark all source rows and the single remaining target column as non-special again. */ for (size_t s = 0; s < numSources; ++s) rowData[CMRelementToRowIndex(sources[s])].specialBFS = false; columnData[CMRelementToColumnIndex(targets[0])].specialBFS = false; } else { numEdges = numEdgesPartWithRow; /* Remove all but one row from the block. */ for (size_t s = 0; s < numSources; ++s) { size_t row = CMRelementToRowIndex(sources[s]); for (ListMatrixNonzero* nz = listmatrix->rowElements[row].head.right; nz->column != SIZE_MAX; nz = nz->right) { if (s > 0 || !columnData[nz->column].specialBFS) { listmatrix->columnElements[nz->column].numNonzeros--; unlinkNonzero(nz); } else nz->special = 0; } if (s == 0) listmatrix->rowElements[row].numNonzeros = numTargets; else { listmatrix->rowElements[row].numNonzeros = 0; listmatrix->rowElements[row].head.left->right = listmatrix->rowElements[row].head.right; listmatrix->rowElements[row].head.right->left = listmatrix->rowElements[row].head.left; } } /* Mark all target columns and the single remaining source row as non-special again. */ for (size_t t = 0; t < numTargets; ++t) columnData[CMRelementToColumnIndex(targets[t])].specialBFS = false; rowData[CMRelementToRowIndex(sources[0])].specialBFS = false; } CMRdbgMsg(0, "!!! Recursing.\n"); } CMR_CALL( CMRfreeStackArray(cmr, &targets) ); CMR_CALL( CMRfreeStackArray(cmr, &sources) ); CMR_CALL( CMRfreeStackArray(cmr, &nzBlock) ); return CMR_OKAY; } static CMR_ERROR decomposeBinarySeriesParallel( CMR* cmr, /**< \ref CMR environment. */ CMR_CHRMAT* matrix, /**< Sparse char matrix. */ CMR_SP_REDUCTION* reductions, /**< Array for storing the SP-reductions. Must have capacity at least number of **< rows + number of columns. */ size_t* pnumReductions, /**< Pointer for storing the number of SP-reductions. */ CMR_SUBMAT** preducedSubmatrix, /**< Pointer for storing the SP-reduced submatrix (may be \c NULL). */ CMR_SUBMAT** pviolatorSubmatrix, /**< Pointer for storing a wheel-submatrix (may be \c NULL). */ CMR_SEPA** pseparation, /**< Pointer for storing a 2-separation (may be \c NULL). */ CMR_SP_STATISTICS* stats /**< Pointer to statistics (may be \c NULL). */ ) { assert(cmr); assert(matrix); assert(reductions && pnumReductions); CMRdbgMsg(0, "decomposeBinarySeriesParallel for a %dx%d matrix with %d nonzeros.\n", matrix->numRows, matrix->numColumns, matrix->numNonzeros); clock_t totalClock = 0; clock_t reduceClock = 0; if (stats) { reduceClock = clock(); totalClock = clock(); } size_t numRows = matrix->numRows; size_t numColumns = matrix->numColumns; /* Create list matrix to use numNonzeros. */ ListMatrix* listmatrix = NULL; CMR_CALL( CMRlistmatrixAlloc(cmr, numRows, numColumns, matrix->numNonzeros, &listmatrix) ); for (size_t row = 0; row < numRows; ++row) listmatrix->rowElements[row].numNonzeros = 0; for (size_t column = 0; column < numColumns; ++column) listmatrix->columnElements[column].numNonzeros = 0; /* Initialize element data and hash vector. */ ElementData* rowData = NULL; CMR_CALL( createElementData(cmr, &rowData, matrix->numRows) ); ElementData* columnData = NULL; CMR_CALL( createElementData(cmr, &columnData, matrix->numColumns) ); long long* hashVector = NULL; CMR_CALL( createHashVector(cmr, &hashVector, matrix->numRows > matrix->numColumns ? matrix->numRows : matrix->numColumns) ); /* Scan the matrix to initialize the element data. */ CMR_CALL( calcNonzeroCountHashFromMatrix(cmr, matrix, listmatrix, rowData, columnData, hashVector) ); /* Initialize the queue. */ CMR_ELEMENT* queue = NULL; size_t queueStart = 0; size_t queueEnd = 0; size_t queueMemory = numRows + numColumns; CMR_CALL( CMRallocStackArray(cmr, &queue, queueMemory) ); /* Initialize the hashtables. */ CMR_LISTHASHTABLE* rowHashtable = NULL; if (numRows > 0) { CMR_CALL( CMRlisthashtableCreate(cmr, &rowHashtable, nextPower2(numRows), numRows) ); CMR_CALL( initializeQueueHashtableFromMatrix(cmr, rowHashtable, listmatrix->rowElements, rowData, numRows, queue, &queueEnd, true) ); } CMR_LISTHASHTABLE* columnHashtable = NULL; if (numColumns > 0) { CMR_CALL( CMRlisthashtableCreate(cmr, &columnHashtable, nextPower2(numColumns), numColumns) ); CMR_CALL( initializeQueueHashtableFromMatrix(cmr, columnHashtable, listmatrix->columnElements, columnData, numColumns, queue, &queueEnd, false) ); } *pnumReductions = 0; if (queueEnd > queueStart || (pviolatorSubmatrix && (numRows + numColumns > 0))) { /* Initialize list matrix representation. */ CMR_CALL( CMRlistmatrixInitializeFromMatrix(cmr, listmatrix, matrix) ); /* We now start main loop. */ size_t numRowReductions = 0; size_t numColumnReductions = 0; CMR_CALL( reduceListMatrix(cmr, listmatrix, rowData, columnData, rowHashtable, columnHashtable, hashVector, queue, &queueStart, &queueEnd, queueMemory, reductions, pnumReductions, &numRowReductions, &numColumnReductions) ); if (stats) { stats->reduceCount++; stats->reduceTime += (clock() - reduceClock) * 1.0 / CLOCKS_PER_SEC; } /* Extract remaining submatrix. */ if (preducedSubmatrix) { CMR_CALL( extractRemainingSubmatrix(cmr, matrix, numRowReductions, numColumnReductions, listmatrix, preducedSubmatrix) ); } if ((pviolatorSubmatrix || pseparation) && (*pnumReductions != (matrix->numRows + matrix->numColumns))) { clock_t wheelClock = 0; if (stats) wheelClock = clock(); CMR_CALL( extractWheelSubmatrix(cmr, listmatrix, rowData, columnData, queue, queueMemory, numRows - numRowReductions, numColumns - numColumnReductions, pviolatorSubmatrix, pseparation) ); if (stats) { stats->wheelCount++; stats->wheelTime += (clock() - wheelClock) * 1.0 / CLOCKS_PER_SEC; } } } else { CMRdbgMsg(2, "No series/parallel element found.\n"); if (preducedSubmatrix) CMR_CALL( createFullRemainingMatrix(cmr, matrix, preducedSubmatrix) ); } CMR_CALL( CMRlisthashtableFree(cmr, &columnHashtable) ); CMR_CALL( CMRlisthashtableFree(cmr, &rowHashtable) ); CMR_CALL( CMRfreeStackArray(cmr, &queue) ); CMR_CALL( CMRfreeStackArray(cmr, &hashVector) ); CMR_CALL( CMRfreeStackArray(cmr, &columnData) ); CMR_CALL( CMRfreeStackArray(cmr, &rowData) ); CMR_CALL( CMRlistmatrixFree(cmr, &listmatrix) ); if (stats) { stats->totalCount++; stats->totalTime += (clock() - totalClock) * 1.0 / CLOCKS_PER_SEC; } return CMR_OKAY; } CMR_ERROR CMRtestBinarySeriesParallel(CMR* cmr, CMR_CHRMAT* matrix, bool* pisSeriesParallel, CMR_SP_REDUCTION* reductions, size_t* pnumReductions, CMR_SUBMAT** preducedSubmatrix, CMR_SUBMAT** pviolatorSubmatrix, CMR_SP_STATISTICS* stats) { assert(cmr); assert(matrix); assert(reductions || !pnumReductions); assert(!reductions || pnumReductions); CMR_SP_REDUCTION* localReductions = NULL; size_t localNumReductions = 0; if (!reductions) CMR_CALL( CMRallocStackArray(cmr, &localReductions, matrix->numRows + matrix->numColumns) ); CMR_CALL( decomposeBinarySeriesParallel(cmr, matrix, reductions ? reductions : localReductions, &localNumReductions, preducedSubmatrix, pviolatorSubmatrix, NULL, stats) ); if (pisSeriesParallel) *pisSeriesParallel = (*pnumReductions == matrix->numRows + matrix->numColumns); if (reductions) *pnumReductions = localNumReductions; else CMR_CALL( CMRfreeStackArray(cmr, &localReductions) ); return CMR_OKAY; } CMR_ERROR CMRdecomposeBinarySeriesParallel(CMR* cmr, CMR_CHRMAT* matrix, bool* pisSeriesParallel, CMR_SP_REDUCTION* reductions, size_t* pnumReductions, CMR_SUBMAT** preducedSubmatrix, CMR_SUBMAT** pviolatorSubmatrix, CMR_SEPA** pseparation, CMR_SP_STATISTICS* stats) { assert(cmr); assert(matrix); assert(reductions || !pnumReductions); assert(!reductions || pnumReductions); CMR_SP_REDUCTION* localReductions = NULL; size_t localNumReductions = 0; if (!reductions) CMR_CALL( CMRallocStackArray(cmr, &localReductions, matrix->numRows + matrix->numColumns) ); CMR_CALL( decomposeBinarySeriesParallel(cmr, matrix, reductions ? reductions : localReductions, &localNumReductions, preducedSubmatrix, pviolatorSubmatrix, pseparation, stats) ); if (pisSeriesParallel) *pisSeriesParallel = (localNumReductions == matrix->numRows + matrix->numColumns); if (reductions) *pnumReductions = localNumReductions; else CMR_CALL( CMRfreeStackArray(cmr, &localReductions) ); return CMR_OKAY; } static CMR_ERROR decomposeTernarySeriesParallel( CMR* cmr, /**< \ref CMR environment. */ CMR_CHRMAT* matrix, /**< Sparse char matrix. */ CMR_SP_REDUCTION* reductions, /**< Array for storing the SP-reductions. Must have capacity at least number of **< rows + number of columns. */ size_t* pnumReductions, /**< Pointer for storing the number of SP-reductions. */ CMR_SUBMAT** preducedSubmatrix, /**< Pointer for storing the SP-reduced submatrix (may be \c NULL). */ CMR_SUBMAT** pviolatorSubmatrix, /**< Pointer for storing a wheel-submatrix (may be \c NULL). */ CMR_SEPA** pseparation, /**< Pointer for storing a 2-separation (may be \c NULL). */ CMR_SP_STATISTICS* stats /**< Pointer to statistics (may be \c NULL). */ ) { assert(cmr); assert(matrix); assert(reductions && pnumReductions); CMRdbgMsg(0, "decomposeTernarySeriesParallel for a %dx%d matrix with %d nonzeros.\n", matrix->numRows, matrix->numColumns, matrix->numNonzeros); clock_t totalClock = 0; clock_t reduceClock = 0; if (stats) { reduceClock = clock(); totalClock = clock(); } size_t numRows = matrix->numRows; size_t numColumns = matrix->numColumns; /* Create list matrix to use numNonzeros. */ ListMatrix* listmatrix = NULL; CMR_CALL( CMRlistmatrixAlloc(cmr, numRows, numColumns, matrix->numNonzeros, &listmatrix) ); for (size_t row = 0; row < numRows; ++row) listmatrix->rowElements[row].numNonzeros = 0; for (size_t column = 0; column < numColumns; ++column) listmatrix->columnElements[column].numNonzeros = 0; /* Initialize element data and hash vector. */ ElementData* rowData = NULL; CMR_CALL( createElementData(cmr, &rowData, matrix->numRows) ); ElementData* columnData = NULL; CMR_CALL( createElementData(cmr, &columnData, matrix->numColumns) ); long long* hashVector = NULL; CMR_CALL( createHashVector(cmr, &hashVector, matrix->numRows > matrix->numColumns ? matrix->numRows : matrix->numColumns) ); /* Scan the matrix to initialize the element data. */ CMR_CALL( calcNonzeroCountHashFromMatrix(cmr, matrix, listmatrix, rowData, columnData, hashVector) ); /* Initialize the queue. */ CMR_ELEMENT* queue = NULL; size_t queueStart = 0; size_t queueEnd = 0; size_t queueMemory = numRows + numColumns; CMR_CALL( CMRallocStackArray(cmr, &queue, queueMemory) ); /* Initialize the hashtables. */ CMR_LISTHASHTABLE* rowHashtable = NULL; if (numRows > 0) { CMR_CALL( CMRlisthashtableCreate(cmr, &rowHashtable, nextPower2(numRows), numRows) ); CMR_CALL( initializeQueueHashtableFromMatrix(cmr, rowHashtable, listmatrix->rowElements, rowData, numRows, queue, &queueEnd, true) ); } CMR_LISTHASHTABLE* columnHashtable = NULL; if (numColumns > 0) { CMR_CALL( CMRlisthashtableCreate(cmr, &columnHashtable, nextPower2(numColumns), numColumns) ); CMR_CALL( initializeQueueHashtableFromMatrix(cmr, columnHashtable, listmatrix->columnElements, columnData, numColumns, queue, &queueEnd, false) ); } *pnumReductions = 0; if (queueEnd > queueStart || (pviolatorSubmatrix && (numRows + numColumns > 0))) { /* Create list matrix representation. */ CMR_CALL( CMRlistmatrixInitializeFromMatrix(cmr, listmatrix, matrix) ); /* We now start main loop. */ size_t numRowReductions = 0; size_t numColumnReductions = 0; CMR_CALL( reduceListMatrix(cmr, listmatrix, rowData, columnData, rowHashtable, columnHashtable, hashVector, queue, &queueStart, &queueEnd, queueMemory, reductions, pnumReductions, &numRowReductions, &numColumnReductions) ); if (stats) { stats->reduceCount++; stats->reduceTime += (clock() - reduceClock) * 1.0 / CLOCKS_PER_SEC; } /* Extract remaining submatrix. */ if (preducedSubmatrix) { CMR_CALL( extractRemainingSubmatrix(cmr, matrix, numRowReductions, numColumnReductions, listmatrix, preducedSubmatrix) ); } if ((pviolatorSubmatrix || pseparation) && (*pnumReductions != (matrix->numRows + matrix->numColumns))) { clock_t nonbinaryClock = 0; if (stats) nonbinaryClock = clock(); CMR_CALL( calcBinaryHashFromListMatrix(cmr, listmatrix, rowData, columnData, hashVector) ); queueStart = 0; queueEnd = 0; CMR_CALL( CMRlisthashtableFree(cmr, &rowHashtable) ); CMR_CALL( CMRlisthashtableCreate(cmr, &rowHashtable, nextPower2(numRows), numRows) ); CMR_CALL( initializeQueueHashtableFromListMatrix(cmr, rowHashtable, listmatrix, rowData, queue, &queueEnd, true) ); CMR_CALL( CMRlisthashtableFree(cmr, &columnHashtable) ); CMR_CALL( CMRlisthashtableCreate(cmr, &columnHashtable, nextPower2(numColumns), numColumns) ); CMR_CALL( initializeQueueHashtableFromListMatrix(cmr, columnHashtable, listmatrix, columnData, queue, &queueEnd, false) ); CMR_SUBMAT* violatorSubmatrix; CMR_CALL( extractNonbinarySubmatrix(cmr, listmatrix, rowData, columnData, rowHashtable, columnHashtable, hashVector, queue, &queueStart, &queueEnd, queueMemory, &violatorSubmatrix) ); if (violatorSubmatrix && pviolatorSubmatrix) *pviolatorSubmatrix = violatorSubmatrix; if (stats) { stats->nonbinaryCount++; stats->nonbinaryTime += (clock() - nonbinaryClock) * 1.0 / CLOCKS_PER_SEC; } if (pviolatorSubmatrix && *pviolatorSubmatrix) { CMRdbgMsg(2, "Extracted an M_2-submatrix.\n"); } else if (!violatorSubmatrix) { clock_t wheelClock = 0; if (stats) wheelClock = clock(); CMR_CALL( extractWheelSubmatrix(cmr, listmatrix, rowData, columnData, queue, queueMemory, numRows - numRowReductions, numColumns - numColumnReductions, pviolatorSubmatrix, pseparation) ); /* Check whether the rank-1 part also has ternary rank 1. */ if (pseparation) { CMRdbgMsg(2, "Checking block of -1/+1s for ternary rank 1.\n"); CMRdbgMsg(2, "Separation has part 0 (%ldx%ld) and part 1 (%ldx%ld) and ranks %d + %d.\n", (*pseparation)->numRows[0], (*pseparation)->numColumns[0], (*pseparation)->numRows[1], (*pseparation)->numColumns[1], CMRsepaRankTopRight(*pseparation), CMRsepaRank(*pseparation)); bool sepaIsTernary; CMR_SUBMAT* reducedMatrix = NULL; if (preducedSubmatrix) reducedMatrix = *preducedSubmatrix; else { CMR_CALL( extractRemainingSubmatrix(cmr, matrix, numRowReductions, numColumnReductions, listmatrix, &reducedMatrix) ); } CMR_CALL( CMRsepaCheckTernary(cmr, *pseparation, matrix, reducedMatrix, &sepaIsTernary, pviolatorSubmatrix) ); if (!preducedSubmatrix) CMR_CALL( CMRsubmatFree(cmr, &reducedMatrix) ); if (!sepaIsTernary) CMR_CALL( CMRsepaFree(cmr, pseparation) ); } if (stats) { stats->wheelCount++; stats->wheelTime += (clock() - wheelClock) * 1.0 / CLOCKS_PER_SEC; } } else { /* We found a violator but the user doesn't want it. */ assert(!violatorSubmatrix); CMR_CALL( CMRsubmatFree(cmr, &violatorSubmatrix) ); } } } else { CMRdbgMsg(2, "No series/parallel element found.\n"); if (preducedSubmatrix) CMR_CALL( createFullRemainingMatrix(cmr, matrix, preducedSubmatrix) ); } CMR_CALL( CMRlisthashtableFree(cmr, &columnHashtable) ); CMR_CALL( CMRlisthashtableFree(cmr, &rowHashtable) ); CMR_CALL( CMRfreeStackArray(cmr, &queue) ); CMR_CALL( CMRfreeStackArray(cmr, &hashVector) ); CMR_CALL( CMRfreeStackArray(cmr, &columnData) ); CMR_CALL( CMRfreeStackArray(cmr, &rowData) ); CMR_CALL( CMRlistmatrixFree(cmr, &listmatrix) ); if (stats) { stats->totalCount++; stats->totalTime += (clock() - totalClock) * 1.0 / CLOCKS_PER_SEC; } return CMR_OKAY; } CMR_ERROR CMRtestTernarySeriesParallel(CMR* cmr, CMR_CHRMAT* matrix, bool* pisSeriesParallel, CMR_SP_REDUCTION* reductions, size_t* pnumReductions, CMR_SUBMAT** preducedSubmatrix, CMR_SUBMAT** pviolatorSubmatrix, CMR_SP_STATISTICS* stats) { assert(cmr); assert(matrix); assert(reductions || !pnumReductions); assert(!reductions || pnumReductions); CMR_SP_REDUCTION* localReductions = NULL; size_t localNumReductions = 0; if (!reductions) CMR_CALL( CMRallocStackArray(cmr, &localReductions, matrix->numRows + matrix->numColumns) ); CMR_CALL( decomposeTernarySeriesParallel(cmr, matrix, reductions ? reductions : localReductions, &localNumReductions, preducedSubmatrix, pviolatorSubmatrix, NULL, stats) ); if (pisSeriesParallel) *pisSeriesParallel = (*pnumReductions == matrix->numRows + matrix->numColumns); if (reductions) *pnumReductions = localNumReductions; else CMR_CALL( CMRfreeStackArray(cmr, &localReductions) ); return CMR_OKAY; } CMR_ERROR CMRdecomposeTernarySeriesParallel(CMR* cmr, CMR_CHRMAT* matrix, bool* pisSeriesParallel, CMR_SP_REDUCTION* reductions, size_t* pnumReductions, CMR_SUBMAT** preducedSubmatrix, CMR_SUBMAT** pviolatorSubmatrix, CMR_SEPA** pseparation, CMR_SP_STATISTICS* stats) { assert(cmr); assert(matrix); assert(reductions || !pnumReductions); assert(!reductions || pnumReductions); CMR_SP_REDUCTION* localReductions = NULL; size_t localNumReductions = 0; if (!reductions) CMR_CALL( CMRallocStackArray(cmr, &localReductions, matrix->numRows + matrix->numColumns) ); CMR_CALL( decomposeTernarySeriesParallel(cmr, matrix, reductions ? reductions : localReductions, &localNumReductions, preducedSubmatrix, pviolatorSubmatrix, pseparation, stats) ); if (pisSeriesParallel) *pisSeriesParallel = (*pnumReductions == matrix->numRows + matrix->numColumns); if (reductions) *pnumReductions = localNumReductions; else CMR_CALL( CMRfreeStackArray(cmr, &localReductions) ); return CMR_OKAY; }
ElectronAsh/jag_sim
src/com/torlus/jnl/SignalType.java
package com.torlus.jnl; public enum SignalType { IN, OUT, /*IO,*/ BUS, /*TRI,*//*BI,*/ LOCAL; public static String rename(String name) { if ("IO".equals(name)) return "OUT"; if ("BI".equals(name) || "TRI".equals(name)) return "BUS"; return name; } public String vhdlPortType() { if (this.equals(IN)) { return "in"; } else if (this.equals(OUT) /*|| this.equals(IO)*/) { return "out"; } else { return "inout"; } } public String verilogPortType() { if (this.equals(IN)) { return "input"; } else if (this.equals(OUT) /*|| this.equals(IO)*/) { return "output"; } else if (this.equals(BUS)) { return "##DIR##"; } throw new RuntimeException("Incorrect port configuration"); } }
elenita1221/ComputeLibrary
documentation/_c_l_2_im2_col_8cpp.js
<filename>documentation/_c_l_2_im2_col_8cpp.js var _c_l_2_im2_col_8cpp = [ [ "CLIm2Col", "_c_l_2_im2_col_8cpp.xhtml#ad2289f0e5c61a8aa201bbc5f6d1eee22", null ], [ "CLIm2ColFixture", "_c_l_2_im2_col_8cpp.xhtml#a5337d141dd770ebf0b894c2ea328d475", null ], [ "DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a1df3843c8077aad2f1daacc093cbff1b", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a0a07e134c036b2a1d1c6b40b2feed6bb", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a7cffa0e3241e209bd45555ec6ab671b2", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a6ca0e7f050a0ca835ab43f159789ed02", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a510f1f6910ee702cb3238f8518e09667", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#ad213615f12a2cce2b5811f01b31973b5", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#af21d987bb26f92f874adfc8dff100fa8", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a58407d5257bafcaab6f94f1657bcb502", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a97c70188841b1214510b684aaea3c033", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#ae92888bc064d07459081a9c624d797db", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#afcf6e255d25bd3b6dc5cc3821f7dbc0e", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#a0ca21b2fe5a67cffca8cdd37ae7c1b9e", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_im2_col_8cpp.xhtml#ac217d5592ae8fbcfc904f1a2a7085893", null ] ];
zhangyin2088/Teamcat
teamcat_service/docker_build/target/one_step_build/teamcat/doraemon/static/project/js/project_statistics.js
$(document).ready(function(){ var theme = 'bootstrap'; var rootUri = window.location.href; init_web_app(); init_page(); function init_page() { load_issue_by_people(0); createOpenedIssueToday(0); createOpenedIssueTotal(0); createVersionTotalIssue(); createModuleIssueCount(0); createSeverityIssueCount(0); createCategoryIssueCount(0); createResolvedResultIssueCount(0); init_DropDownList("unresloved_chart_version",0,false); init_DropDownList("issuestatus_chart_version",0,false); init_DropDownList("opened_chart_version",0,false); init_DropDownList("total_chart_version",0,false); init_DropDownList("module_chart_version",0,false); init_DropDownList("severity_chart_version",0,false); init_DropDownList("category_chart_version",0,false); init_DropDownList("reslovedresult_chart_version",0,false); version_change_handler("opened_chart_version"); version_change_handler("issuestatus_chart_version"); version_change_handler("unresloved_chart_version"); version_change_handler("total_chart_version"); version_change_handler("module_chart_version"); version_change_handler("severity_chart_version"); version_change_handler("category_chart_version"); version_change_handler("reslovedresult_chart_version"); } function init_web_app() { var parent_height=$(".web-app-view-body-default").css("height"); $(".web-app-view-content-default").css("height",parent_height.replace("px","")+"px"); $(".webapp_header_leftbar_nav").hide(); } function createOpenedIssueToday(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_trend_new",function(result){ createTrendLineChart(result.result,'container2'); }); } function createOpenedIssueTotal(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_trend_total",function(result){ createTrendLineChart(result.result,'container9'); }); } function createVersionTotalIssue() { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/statistics/version_total_issue",function(result){ console.log(result); createColumnChart(result.result,'container4'); }); } function createModuleIssueCount(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_count_per_module",function(result){ createColumnChart(result.result,'container5'); }); } function createSeverityIssueCount(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_count_by_severity",function(result){ console.log(6); console.log(result); createPieChart(result.result,'container6'); }); } function createCategoryIssueCount(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_count_by_category",function(result){ createPieChart(result.result,'container8'); }); } function createResolvedResultIssueCount(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/issue_count_by_resolveresult",function(result){ createPieChart(result.result,'container7'); }); } //生成趋势线图 function createTrendLineChart(data,chart_container) { Highcharts.chart(chart_container, { chart: { type: data['chart_type'] }, title: { text: data['chart_title'] }, subtitle: { text: data['chart_sub_title'] }, xAxis: { categories: data['xaxis'] }, yAxis: { title: { } }, plotOptions: { line: { dataLabels: { enabled: true // 开启数据标签 }, enableMouseTracking: true // 关闭鼠标跟踪,对应的提示框、点击事件会失效 } }, series:data['series_data'] }); } //生成简单柱状图 function createColumnChart(data,chart_container) { Highcharts.chart(chart_container,{ chart: { type: data['chart_type'] }, title: { text:data['chart_title'] }, subtitle: { text:data['chart_sub_type'] }, xAxis: { categories:data['xaxis'], crosshair: true }, yAxis: { min: 0, title: { text: '问题数量 (个)' } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { column: { borderWidth: 0, colorByPoint:true, } }, series:data['series_data'] }); } function load_status_issue_count(version_id) { var project_id=$("#project_id").attr('projectid'); $("#status_chart_version").load("/project/"+project_id+"/version/"+version_id+"/statistics/issue_count_status"); } function load_issue_by_people(version_id) { var project_id=$("#project_id").attr('projectid'); $.getJSON("/api/project/"+project_id+"/"+version_id+"/statistics/unclosed_issue",function(result){ var data=result.result; $('#container').highcharts({ chart: { type: data["chart_type"] }, title: { text: data['chart_title'] }, xAxis: { categories: data['xaxis'] }, yAxis: { min: 0, title: { text: '' }, stackLabels: { enabled: true, style: { fontWeight: 'bold', color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray' } } }, legend: { align: 'right', x: -30, verticalAlign: 'top', y: 25, floating: true, backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white', borderColor: '#CCC', borderWidth: 1, shadow: false }, tooltip: { formatter: function () { return '<b>' + this.x + '</b><br/>' + this.series.name + ': ' + this.y + '<br/>' + '总数: ' + this.point.stackTotal; } }, plotOptions: { column: { stacking: 'normal', dataLabels: { enabled: true, color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white', style: { textShadow: '0 0 3px black' } } } }, series:data['series_data'] }); }); } //生成饼图 function createPieChart(data,chart_container) { Highcharts.chart(chart_container,{ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text:data['chart_title'] }, tooltip: { headerFormat: '{series.name}<br>', pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: true } }, series: [{ type: data['chart_type'], name: data['chart_title'], data: data['series_data'] }] }); } //version_change_handler function version_change_handler(controll_name) { $("#"+controll_name).on('change',function(event){ var args = event.args; if (args) { var item = args.item; var value = item.value; reload_chart(controll_name,value); } }); } function reload_chart(controll_name,value) { switch(controll_name) { case 'issuestatus_chart_version': load_status_issue_count(value); break; case 'unresloved_chart_version': load_issue_by_people(value); break; case 'opened_chart_version': createOpenedIssueToday(value); break; case 'total_chart_version': createOpenedIssueTotal(value); break; case 'module_chart_version': createModuleIssueCount(value); break; case 'severity_chart_version': createSeverityIssueCount(value); break; case 'category_chart_version': createCategoryIssueCount(value); break; case 'reslovedresult_chart_version': createResolvedResultIssueCount(value); break; default: break; } } /**********************************通用方法**************************************/ //初始化下来列表 function init_DropDownList(name,value,checkbox) { $("#"+name).jqxDropDownList({ theme : theme, width : "150px", height : 22, checkboxes:checkbox, filterable:true, }); if(value!=0){ var item = $("#"+name).jqxDropDownList('getItemByValue',value); $("#"+name).jqxDropDownList('selectItem', item); } } });
rifraf/IronRuby_Framework_4.7.2
Languages/Ruby/Tests/mspec/rubyspec/library/set/sortedset/add_spec.rb
<filename>Languages/Ruby/Tests/mspec/rubyspec/library/set/sortedset/add_spec.rb require File.dirname(__FILE__) + '/../../../spec_helper' require 'set' require File.dirname(__FILE__) + '/shared/add' describe "SortedSet#add" do it_behaves_like :sorted_set_add, :add ruby_bug "redmine #118", "1.9.1" do it "takes only values which responds <=>" do lambda { SortedSet[Object.new].add(Object.new) }.should raise_error(ArgumentError) obj = mock('x') lambda { SortedSet[obj].add(:aaa) }.should raise_error(ArgumentError) def obj.<=>(o) 1 end lambda { SortedSet[obj].add(:aaa) }.should_not raise_error(ArgumentError) end end end describe "SortedSet#add?" do before :each do @set = SortedSet.new end it "adds the passed Object to self" do @set.add?("cat") @set.should include("cat") end it "returns self when the Object has not yet been added to self" do @set.add?("cat").should equal(@set) end it "returns nil when the Object has already been added to self" do @set.add?("cat") @set.add?("cat").should be_nil end end
TimBarham/cordova-simulate-server
src/plugins/cordova-plugin-dialogs/sim-host-handlers.js
<gh_stars>0 /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * 'License'); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ // https://github.com/apache/cordova-plugin-dialogs/ module.exports = function (messages) { function alert (success, fail, args) { messages.call('alert', args).then(function () { success(); }, function (err) { fail(err); }); } function confirm (success, fail, args) { messages.call('confirm', args).then(function (result) { success(result); }, function (err) { fail(err); }); } function prompt (success, fail, args) { messages.call('prompt', args).then(function (result) { success(result); }, function (err) { fail(err); }); } function beep (success, fail, args) { var times = args[0]; messages.call('beep', times).then(function () { success(); }, function (err) { fail(err); }); } return { Notification: { alert: alert, confirm: confirm, prompt: prompt, beep: beep, } }; };
hangqiu/pixie
src/stirling/source_connectors/socket_tracer/protocols/cql/frame_body_decoder.cc
/* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #include "src/stirling/source_connectors/socket_tracer/protocols/cql/frame_body_decoder.h" #include <algorithm> #include <utility> #include "src/common/base/byte_utils.h" namespace px { namespace stirling { namespace protocols { namespace cass { // These Extract functions parse raw byte sequences into CQL types. // Note that the CQL protocol is big-endian, so all extract functions // also intrinsically convert from big-endian to host ordering. template <typename TIntType> StatusOr<TIntType> FrameBodyDecoder::ExtractIntCore() { return binary_decoder_.ExtractInt<TIntType>(); } template <typename TFloatType> StatusOr<TFloatType> ExtractFloatCore(std::string_view* buf) { if (buf->size() < sizeof(TFloatType)) { return error::ResourceUnavailable("Insufficient number of bytes."); } TFloatType val = utils::BEndianBytesToFloat<TFloatType>(*buf); buf->remove_prefix(sizeof(TFloatType)); return val; } template <typename TCharType> StatusOr<std::basic_string<TCharType>> FrameBodyDecoder::ExtractBytesCore(int64_t len) { PL_ASSIGN_OR_RETURN(std::basic_string_view<TCharType> tbuf, binary_decoder_.ExtractString<TCharType>(len)); return std::basic_string<TCharType>(tbuf); } template <typename TCharType, size_t N> Status FrameBodyDecoder::ExtractBytesCore(TCharType* out) { PL_ASSIGN_OR_RETURN(std::basic_string_view<TCharType> tbuf, binary_decoder_.ExtractString<TCharType>(N)); memcpy(out, tbuf.data(), N); return Status::OK(); } // [int] A 4 bytes signed integer StatusOr<int32_t> FrameBodyDecoder::ExtractInt() { return ExtractIntCore<int32_t>(); } // [long] A 8 bytes signed integer StatusOr<int64_t> FrameBodyDecoder::ExtractLong() { return ExtractIntCore<int64_t>(); } // [short] A 2 bytes unsigned integer StatusOr<uint16_t> FrameBodyDecoder::ExtractShort() { return ExtractIntCore<uint16_t>(); } // [byte] A 2 bytes unsigned integer StatusOr<uint8_t> FrameBodyDecoder::ExtractByte() { return ExtractIntCore<uint8_t>(); } // [float] StatusOr<float> ExtractFloat(std::string_view* buf) { return ExtractFloatCore<float>(buf); } // [double] StatusOr<double> ExtractDouble(std::string_view* buf) { return ExtractFloatCore<double>(buf); } // [string] A [short] n, followed by n bytes representing an UTF-8 string. StatusOr<std::string> FrameBodyDecoder::ExtractString() { PL_ASSIGN_OR_RETURN(uint16_t len, ExtractShort()); return ExtractBytesCore<char>(len); } // [long string] An [int] n, followed by n bytes representing an UTF-8 string. StatusOr<std::string> FrameBodyDecoder::ExtractLongString() { PL_ASSIGN_OR_RETURN(int32_t len, ExtractInt()); len = std::max(len, 0); return ExtractBytesCore<char>(len); } // [uuid] A 16 bytes long uuid. StatusOr<sole::uuid> FrameBodyDecoder::ExtractUUID() { sole::uuid uuid; // Logically, we want to get the different components of the UUID, and ensure correct byte-order. // For example, see datastax: // https://github.com/datastax/cpp-driver/blob/bbbbd7bc3eaba1b10ad8ac6f53c41fa93ee718db/src/serialization.hpp // They do it in components, because each component is big-endian ordered. // The ordering of bytes for the entire UUID is effectively: // input: {15 ........... 8 7 6 5 4 3 2 1 0} // output: {8 ............ 15}{6 7}{4 5}{0 1 2 3} // // Equivalent code would be: // PL_ASSIGN_OR_RETURN(uint64_t time_low, ExtractInt(buf)); // PL_ASSIGN_OR_RETURN(uint64_t time_mid, ExtractShort(buf)); // PL_ASSIGN_OR_RETURN(uint64_t time_hi_version, ExtractShort(buf)); // PL_ASSIGN_OR_RETURN(uint64_t clock_seq_and_node, ExtractLong(buf)); // // But then we constitute the components according to the following formula, // from uuid1() in sole.hpp: // // uuid.ab = (time_low << 32) | (time_mid << 16) | time_hi_version; // uuid.cd = clock_seq_and_node; // // But we notice that the outcome of all this is: // uuid.ab = {0 1 2 3}{4 5}{6 7} // uuid.cd = {8 ................. 15} // // And we realize that we can achieve this directly with the following shortcut: PL_ASSIGN_OR_RETURN(uuid.ab, ExtractLong()); PL_ASSIGN_OR_RETURN(uuid.cd, ExtractLong()); return uuid; } // [string list] A [short] n, followed by n [string]. StatusOr<StringList> FrameBodyDecoder::ExtractStringList() { PL_ASSIGN_OR_RETURN(uint16_t n, ExtractShort()); StringList string_list; for (int i = 0; i < n; ++i) { PL_ASSIGN_OR_RETURN(std::string s, ExtractString()); string_list.push_back(std::move(s)); } return string_list; } // [bytes] A [int] n, followed by n bytes if n >= 0. If n < 0, // no byte should follow and the value represented is `null`. StatusOr<std::basic_string<uint8_t>> FrameBodyDecoder::ExtractBytes() { PL_ASSIGN_OR_RETURN(int32_t len, ExtractInt()); len = std::max(len, 0); return ExtractBytesCore<uint8_t>(len); } // A [int] n, followed by n bytes if n >= 0. // If n == -1 no byte should follow and the value represented is `null`. // If n == -2 no byte should follow and the value represented is // `not set` not resulting in any change to the existing value. StatusOr<std::basic_string<uint8_t>> FrameBodyDecoder::ExtractValue() { PL_ASSIGN_OR_RETURN(int32_t len, ExtractInt()); if (len == -1) { return std::basic_string<uint8_t>(); } if (len == -2) { // TODO(oazizi): Need to send back 'not set' instead. return std::basic_string<uint8_t>(); } if (len < 0) { return error::Internal("Invalid length for value."); } return ExtractBytesCore<uint8_t>(len); } // [short bytes] A [short] n, followed by n bytes if n >= 0. StatusOr<std::basic_string<uint8_t>> FrameBodyDecoder::ExtractShortBytes() { PL_ASSIGN_OR_RETURN(uint16_t len, ExtractShort()); return ExtractBytesCore<uint8_t>(len); } // [inet] An address (ip and port) to a node. It consists of one // [byte] n, that represents the address size, followed by n // [byte] representing the IP address (in practice n can only be // either 4 (IPv4) or 16 (IPv6)), following by one [int] // representing the port. StatusOr<SockAddr> FrameBodyDecoder::ExtractInet() { PL_ASSIGN_OR_RETURN(uint8_t n, ExtractByte()); SockAddr addr; switch (n) { case 4: { addr.family = SockAddrFamily::kIPv4; auto& addr4 = addr.addr.emplace<SockAddrIPv4>(); PL_RETURN_IF_ERROR((ExtractBytesCore<uint8_t, 4>(reinterpret_cast<uint8_t*>(&addr4.addr)))); PL_ASSIGN_OR_RETURN(addr4.port, ExtractInt()); } break; case 16: { addr.family = SockAddrFamily::kIPv6; auto& addr6 = addr.addr.emplace<SockAddrIPv6>(); PL_RETURN_IF_ERROR((ExtractBytesCore<uint8_t, 16>(reinterpret_cast<uint8_t*>(&addr6.addr)))); PL_ASSIGN_OR_RETURN(addr6.port, ExtractInt()); } break; } return addr; } // [string map] A [short] n, followed by n pair <k><v> where <k> and <v> // are [string]. StatusOr<StringMap> FrameBodyDecoder::ExtractStringMap() { PL_ASSIGN_OR_RETURN(uint16_t n, ExtractShort()); StringMap string_map; for (int i = 0; i < n; ++i) { PL_ASSIGN_OR_RETURN(std::string key, ExtractString()); PL_ASSIGN_OR_RETURN(std::string val, ExtractString()); string_map.insert({std::move(key), std::move(val)}); } return string_map; } // [string multimap] A [short] n, followed by n pair <k><v> where <k> is a // [string] and <v> is a [string list]. StatusOr<StringMultiMap> FrameBodyDecoder::ExtractStringMultiMap() { PL_ASSIGN_OR_RETURN(uint16_t n, ExtractShort()); StringMultiMap string_multimap; for (int i = 0; i < n; ++i) { PL_ASSIGN_OR_RETURN(std::string key, ExtractString()); PL_ASSIGN_OR_RETURN(StringList val, ExtractStringList()); string_multimap.insert({std::move(key), std::move(val)}); } return string_multimap; } StatusOr<Option> FrameBodyDecoder::ExtractOption() { Option col_spec; PL_ASSIGN_OR_RETURN(uint16_t id, ExtractShort()); col_spec.type = static_cast<DataType>(id); if (col_spec.type == DataType::kCustom) { PL_ASSIGN_OR_RETURN(col_spec.value, ExtractString()); } if (col_spec.type == DataType::kList || col_spec.type == DataType::kSet) { PL_ASSIGN_OR_RETURN(Option type, ExtractOption()); // For now, we're throwing the result away. Could consider recording if desired. } if (col_spec.type == DataType::kMap) { PL_ASSIGN_OR_RETURN(Option key_type, ExtractOption()); PL_ASSIGN_OR_RETURN(Option val_type, ExtractOption()); // For now, we're throwing the result away. Could consider recording if desired. } // TODO(oazizi): Process kUDT and kTuple. DCHECK(col_spec.type != DataType::kUDT); DCHECK(col_spec.type != DataType::kTuple); return col_spec; } StatusOr<NameValuePair> FrameBodyDecoder::ExtractNameValuePair(bool with_names) { NameValuePair nv; if (with_names) { PL_ASSIGN_OR_RETURN(nv.name, ExtractString()); } PL_ASSIGN_OR_RETURN(nv.value, ExtractValue()); return nv; } StatusOr<std::vector<NameValuePair>> FrameBodyDecoder::ExtractNameValuePairList(bool with_names) { std::vector<NameValuePair> values; PL_ASSIGN_OR_RETURN(uint16_t n, ExtractShort()); for (int i = 0; i < n; ++i) { PL_ASSIGN_OR_RETURN(NameValuePair v, ExtractNameValuePair(with_names)); values.push_back(std::move(v)); } return values; } StatusOr<QueryParameters> FrameBodyDecoder::ExtractQueryParameters() { QueryParameters qp; PL_ASSIGN_OR_RETURN(qp.consistency, ExtractShort()); PL_ASSIGN_OR_RETURN(qp.flags, ExtractByte()); bool flag_values = qp.flags & 0x01; bool flag_skip_metadata = qp.flags & 0x02; bool flag_page_size = qp.flags & 0x04; bool flag_with_paging_state = qp.flags & 0x08; bool flag_with_serial_consistency = qp.flags & 0x10; bool flag_with_default_timestamp = qp.flags & 0x20; bool flag_with_names_for_values = qp.flags & 0x40; PL_UNUSED(flag_skip_metadata); if (flag_values) { PL_ASSIGN_OR_RETURN(qp.values, ExtractNameValuePairList(flag_with_names_for_values)); } if (flag_page_size) { PL_ASSIGN_OR_RETURN(qp.page_size, ExtractInt()); } if (flag_with_paging_state) { PL_ASSIGN_OR_RETURN(qp.paging_state, ExtractBytes()); } if (flag_with_serial_consistency) { PL_ASSIGN_OR_RETURN(qp.serial_consistency, ExtractShort()); } if (flag_with_default_timestamp) { PL_ASSIGN_OR_RETURN(qp.timestamp, ExtractLong()); } return qp; } StatusOr<ResultMetadata> FrameBodyDecoder::ExtractResultMetadata(bool prepared_result_metadata) { ResultMetadata r; PL_ASSIGN_OR_RETURN(r.flags, ExtractInt()); PL_ASSIGN_OR_RETURN(r.columns_count, ExtractInt()); // Version 4+ of the protocol has partition-key bind indexes // when the metadata is in response to a PREPARE request. bool has_pk = prepared_result_metadata && (version_ >= 4); if (has_pk) { PL_ASSIGN_OR_RETURN(int32_t pk_count, ExtractInt()); for (int i = 0; i < pk_count; ++i) { PL_ASSIGN_OR_RETURN(uint16_t pk_index_i, ExtractShort()); PL_UNUSED(pk_index_i); } } bool flag_global_tables_spec = r.flags & 0x0001; bool flag_has_more_pages = r.flags & 0x0002; bool flag_no_metadata = r.flags & 0x0004; if (flag_has_more_pages) { PL_ASSIGN_OR_RETURN(r.paging_state, ExtractBytes()); } if (!flag_no_metadata) { if (flag_global_tables_spec) { PL_ASSIGN_OR_RETURN(r.gts_keyspace_name, ExtractString()); PL_ASSIGN_OR_RETURN(r.gts_table_name, ExtractString()); } for (int i = 0; i < r.columns_count; ++i) { ColSpec col_spec; if (!flag_global_tables_spec) { PL_ASSIGN_OR_RETURN(col_spec.ks_name, ExtractString()); PL_ASSIGN_OR_RETURN(col_spec.table_name, ExtractString()); } PL_ASSIGN_OR_RETURN(col_spec.name, ExtractString()); PL_ASSIGN_OR_RETURN(col_spec.type, ExtractOption()); r.col_specs.push_back(std::move(col_spec)); } } return r; } StatusOr<SchemaChange> FrameBodyDecoder::ExtractSchemaChange() { SchemaChange sc; PL_ASSIGN_OR_RETURN(sc.change_type, ExtractString()); PL_ASSIGN_OR_RETURN(sc.target, ExtractString()); PL_ASSIGN_OR_RETURN(sc.keyspace, ExtractString()); if (sc.target != "KEYSPACE") { // Targets TABLE, TYPE, FUNCTION and AGGREGATE all have a name. PL_ASSIGN_OR_RETURN(sc.name, ExtractString()); } if (sc.target == "FUNCTION" || sc.target == "AGGREGATE") { // Targets FUNCTION and AGGREGATE also have argument types. PL_ASSIGN_OR_RETURN(sc.arg_types, ExtractStringList()); } return sc; } StatusOr<StartupReq> ParseStartupReq(Frame* frame) { StartupReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.options, decoder.ExtractStringMap()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<AuthResponseReq> ParseAuthResponseReq(Frame* frame) { AuthResponseReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.token, decoder.ExtractBytes()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<OptionsReq> ParseOptionsReq(Frame* frame) { OptionsReq r; FrameBodyDecoder decoder(*frame); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<RegisterReq> ParseRegisterReq(Frame* frame) { RegisterReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.event_types, decoder.ExtractStringList()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<QueryReq> ParseQueryReq(Frame* frame) { QueryReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.query, decoder.ExtractLongString()); PL_ASSIGN_OR_RETURN(r.qp, decoder.ExtractQueryParameters()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<PrepareReq> ParsePrepareReq(Frame* frame) { PrepareReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.query, decoder.ExtractLongString()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<ExecuteReq> ParseExecuteReq(Frame* frame) { ExecuteReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.id, decoder.ExtractShortBytes()); PL_ASSIGN_OR_RETURN(r.qp, decoder.ExtractQueryParameters()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<BatchReq> ParseBatchReq(Frame* frame) { BatchReq r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(uint8_t type_raw, decoder.ExtractByte()); PL_ASSIGN_OR_RETURN(r.type, EnumCast<BatchReqType>(type_raw)); PL_ASSIGN_OR_RETURN(uint16_t n, decoder.ExtractShort()); for (uint i = 0; i < n; ++i) { BatchQuery q; PL_ASSIGN_OR_RETURN(uint8_t kind_raw, decoder.ExtractByte()); PL_ASSIGN_OR_RETURN(q.kind, EnumCast<BatchQueryKind>(kind_raw)); switch (q.kind) { case BatchQueryKind::kString: { PL_ASSIGN_OR_RETURN(q.query_or_id, decoder.ExtractLongString()); break; } case BatchQueryKind::kID: { PL_ASSIGN_OR_RETURN(q.query_or_id, decoder.ExtractShortBytes()); break; } default: // EnumCast should ensure we never get here. LOG(DFATAL) << absl::Substitute("Unrecognized BatchQueryKind $0", static_cast<int>(q.kind)); } // See note below about flag_with_names_for_values. PL_ASSIGN_OR_RETURN(q.values, decoder.ExtractNameValuePairList(false)); r.queries.push_back(std::move(q)); } PL_ASSIGN_OR_RETURN(r.consistency, decoder.ExtractShort()); PL_ASSIGN_OR_RETURN(r.flags, decoder.ExtractByte()); bool flag_with_serial_consistency = r.flags & 0x10; bool flag_with_default_timestamp = r.flags & 0x20; bool flag_with_names_for_values = r.flags & 0x40; // Note that the flag `with_names_for_values` occurs after its use in the spec, // that's why we have hard-coded the value to false in the call to ExtractNameValuePairList() // above. This is actually what the spec defines, because of the spec bug: // // With names for values. If set, then all values for all <query_i> must be // preceded by a [string] <name_i> that have the same meaning as in QUERY // requests [IMPORTANT NOTE: this feature does not work and should not be // used. It is specified in a way that makes it impossible for the server // to implement. This will be fixed in a future version of the native // protocol. See https://issues.apache.org/jira/browse/CASSANDRA-10246 for // more details]. PL_UNUSED(flag_with_names_for_values); if (flag_with_serial_consistency) { PL_ASSIGN_OR_RETURN(r.serial_consistency, decoder.ExtractShort()); } if (flag_with_default_timestamp) { PL_ASSIGN_OR_RETURN(r.timestamp, decoder.ExtractLong()); } PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<ErrorResp> ParseErrorResp(Frame* frame) { ErrorResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.error_code, decoder.ExtractInt()); PL_ASSIGN_OR_RETURN(r.error_msg, decoder.ExtractString()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<ReadyResp> ParseReadyResp(Frame* frame) { ReadyResp r; FrameBodyDecoder decoder(*frame); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<SupportedResp> ParseSupportedResp(Frame* frame) { SupportedResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.options, decoder.ExtractStringMultiMap()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<AuthenticateResp> ParseAuthenticateResp(Frame* frame) { AuthenticateResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.authenticator_name, decoder.ExtractString()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<AuthSuccessResp> ParseAuthSuccessResp(Frame* frame) { AuthSuccessResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.token, decoder.ExtractBytes()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } StatusOr<AuthChallengeResp> ParseAuthChallengeResp(Frame* frame) { AuthChallengeResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.token, decoder.ExtractBytes()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } namespace { StatusOr<ResultVoidResp> ParseResultVoid(FrameBodyDecoder* decoder) { ResultVoidResp r; PL_RETURN_IF_ERROR(decoder->ExpectEOF()); return r; } // See section 4.2.5.2 of the spec. StatusOr<ResultRowsResp> ParseResultRows(FrameBodyDecoder* decoder) { ResultRowsResp r; PL_ASSIGN_OR_RETURN(r.metadata, decoder->ExtractResultMetadata()); PL_ASSIGN_OR_RETURN(r.rows_count, decoder->ExtractInt()); // Skip grabbing the row content for now. // PL_RETURN_IF_ERROR(decoder->ExpectEOF()); return r; } StatusOr<ResultSetKeyspaceResp> ParseResultSetKeyspace(FrameBodyDecoder* decoder) { ResultSetKeyspaceResp r; PL_ASSIGN_OR_RETURN(r.keyspace_name, decoder->ExtractString()); PL_RETURN_IF_ERROR(decoder->ExpectEOF()); return r; } StatusOr<ResultPreparedResp> ParseResultPrepared(FrameBodyDecoder* decoder) { ResultPreparedResp r; PL_ASSIGN_OR_RETURN(r.id, decoder->ExtractShortBytes()); // Note that two metadata are sent back. The first communicates the col specs for the Prepared // statement, while the second communicates the metadata for future EXECUTE statements. PL_ASSIGN_OR_RETURN(r.metadata, decoder->ExtractResultMetadata(/* has_pk */ true)); PL_ASSIGN_OR_RETURN(r.result_metadata, decoder->ExtractResultMetadata()); PL_RETURN_IF_ERROR(decoder->ExpectEOF()); return r; } StatusOr<ResultSchemaChangeResp> ParseResultSchemaChange(FrameBodyDecoder* decoder) { ResultSchemaChangeResp r; PL_ASSIGN_OR_RETURN(r.sc, decoder->ExtractSchemaChange()); PL_RETURN_IF_ERROR(decoder->ExpectEOF()); return r; } } // namespace StatusOr<ResultResp> ParseResultResp(Frame* frame) { ResultResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(int32_t kind_raw, decoder.ExtractInt()); PL_ASSIGN_OR_RETURN(r.kind, EnumCast<ResultRespKind>(kind_raw)); switch (r.kind) { case ResultRespKind::kVoid: { PL_ASSIGN_OR_RETURN(r.resp, ParseResultVoid(&decoder)); break; } case ResultRespKind::kRows: { PL_ASSIGN_OR_RETURN(r.resp, ParseResultRows(&decoder)); break; } case ResultRespKind::kSetKeyspace: { PL_ASSIGN_OR_RETURN(r.resp, ParseResultSetKeyspace(&decoder)); break; } case ResultRespKind::kPrepared: { PL_ASSIGN_OR_RETURN(r.resp, ParseResultPrepared(&decoder)); break; } case ResultRespKind::kSchemaChange: { PL_ASSIGN_OR_RETURN(r.resp, ParseResultSchemaChange(&decoder)); break; } default: // EnumCast should ensure we never get here. LOG(DFATAL) << absl::Substitute("Unrecognized ResultRespKind $0", static_cast<int>(r.kind)); } return r; } StatusOr<EventResp> ParseEventResp(Frame* frame) { EventResp r; FrameBodyDecoder decoder(*frame); PL_ASSIGN_OR_RETURN(r.event_type, decoder.ExtractString()); if (r.event_type == "TOPOLOGY_CHANGE" || r.event_type == "STATUS_CHANGE") { PL_ASSIGN_OR_RETURN(r.change_type, decoder.ExtractString()); PL_ASSIGN_OR_RETURN(r.addr, decoder.ExtractInet()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } else if (r.event_type == "SCHEMA_CHANGE") { PL_ASSIGN_OR_RETURN(r.sc, decoder.ExtractSchemaChange()); PL_RETURN_IF_ERROR(decoder.ExpectEOF()); return r; } return error::Internal("Unknown event_type $0", r.event_type); } } // namespace cass } // namespace protocols } // namespace stirling } // namespace px
adambirse/innovation-funding-service
ifs-rest-api-service/src/test/java/org/innovateuk/ifs/finance/service/FinanceRowMetaFieldRestServiceMocksTest.java
package org.innovateuk.ifs.finance.service; import org.innovateuk.ifs.BaseRestServiceUnitTest; import org.innovateuk.ifs.finance.resource.FinanceRowMetaFieldResource; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.innovateuk.ifs.commons.service.ParameterizedTypeReferences.financeRowMetaFieldResourceListType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * */ public class FinanceRowMetaFieldRestServiceMocksTest extends BaseRestServiceUnitTest<FinanceRowMetaFieldRestServiceImpl> { private static final String costFieldRestURL = "/costfield"; @Override protected FinanceRowMetaFieldRestServiceImpl registerRestServiceUnderTest() { FinanceRowMetaFieldRestServiceImpl costFieldService = new FinanceRowMetaFieldRestServiceImpl(); return costFieldService; } @Test public void test_getCostFields() { List<FinanceRowMetaFieldResource> returnedResponse = Stream.of(1, 2, 3).map(i -> new FinanceRowMetaFieldResource()).collect(Collectors.toList()); setupGetWithRestResultExpectations(costFieldRestURL + "/find-all/", financeRowMetaFieldResourceListType(), returnedResponse); List<FinanceRowMetaFieldResource> costFields = service.getFinanceRowMetaFields().getSuccess(); assertNotNull(costFields); assertEquals(returnedResponse, costFields); } }
jiangshide/sdk
eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/ZoomControlsRuleTest.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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.android.ide.common.layout; import com.android.ide.common.api.DropFeedback; import com.android.ide.common.api.IDragElement; import com.android.ide.common.api.INode; import com.android.ide.common.api.Rect; /** Test the {@link ZoomControlsRule} */ public class ZoomControlsRuleTest extends LayoutTestBase { public void testDoNothing() { String draggedButtonId = "@+id/DraggedButton"; IDragElement[] elements = TestDragElement.create(TestDragElement.create( "android.widget.Button").id(draggedButtonId)); INode layout = TestNode.create("android.widget.ZoomControls").id("@+id/ZoomControls01") .bounds(new Rect(0, 0, 240, 480)).add( TestNode.create("android.widget.Button").id("@+id/Button01").bounds( new Rect(0, 0, 100, 80)), TestNode.create("android.widget.Button").id("@+id/Button02").bounds( new Rect(0, 100, 100, 80)), TestNode.create("android.widget.Button").id("@+id/Button03").bounds( new Rect(0, 200, 100, 80)), TestNode.create("android.widget.Button").id("@+id/Button04").bounds( new Rect(0, 300, 100, 80))); ZoomControlsRule rule = new ZoomControlsRule(); // Enter target DropFeedback feedback = rule.onDropEnter(layout, null/*targetView*/, elements); // Zoom controls don't respond to drags assertNull(feedback); } }
amichard/tfrs
backend/api/migrations/0170_auto_20190819_0126.py
<filename>backend/api/migrations/0170_auto_20190819_0126.py # -*- coding: utf-8 -*- # Generated by Django 1.11.21 on 2019-08-19 01:26 from __future__ import unicode_literals import db_comments.model_mixins from django.conf import settings import django.contrib.postgres.fields.jsonb import django.core.serializers.json from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0169_add_view_compliance_report_permission'), ] operations = [ migrations.CreateModel( name='ComplianceReportSnapshot', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_timestamp', models.DateTimeField(auto_now_add=True, null=True)), ('update_timestamp', models.DateTimeField(auto_now=True, null=True)), ('snapshot', django.contrib.postgres.fields.jsonb.JSONField(encoder=django.core.serializers.json.DjangoJSONEncoder, null=True)), ], options={ 'db_table': 'compliance_report_snapshot', }, bases=(models.Model, db_comments.model_mixins.DBComments), ), migrations.AlterField( model_name='compliancereport', name='schedule_a', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='compliance_report', to='api.ScheduleA'), ), migrations.AlterField( model_name='compliancereport', name='schedule_b', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='compliance_report', to='api.ScheduleB'), ), migrations.AlterField( model_name='compliancereport', name='schedule_c', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='compliance_report', to='api.ScheduleC'), ), migrations.AlterField( model_name='compliancereport', name='schedule_d', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='compliance_report', to='api.ScheduleD'), ), migrations.AlterField( model_name='compliancereport', name='summary', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='compliance_report', to='api.ScheduleSummary'), ), migrations.AddField( model_name='compliancereportsnapshot', name='compliance_report', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='api.ComplianceReport'), ), migrations.AddField( model_name='compliancereportsnapshot', name='create_user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='api_compliancereportsnapshot_CREATE_USER', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='compliancereportsnapshot', name='update_user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='api_compliancereportsnapshot_UPDATE_USER', to=settings.AUTH_USER_MODEL), ), ]
augusto/jpa-workshop
src/main/java/com/ig/training/hibernate/domainmodel/manytomany_bidirectional/ManyToManyPerson.java
<gh_stars>1-10 package com.ig.training.hibernate.domainmodel.manytomany_bidirectional; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import java.util.ArrayList; import java.util.List; @Entity(name = "M2M_B_PERSON") public class ManyToManyPerson { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "FIRST_NAME") private String name; @ManyToMany(cascade = {CascadeType.ALL}) @JoinTable( name = "M2M_B_PERSON_ACCOUNT", joinColumns = {@JoinColumn(name = "PERSON_ID")}, inverseJoinColumns = {@JoinColumn(name = "ACCOUNT_ID")} ) private List<ManyToManyAccount> accounts = new ArrayList<>(); public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<ManyToManyAccount> getAccounts() { return accounts; } public void setAccounts(List<ManyToManyAccount> accounts) { this.accounts = accounts; } @Override public String toString() { return "OneToOnePerson{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
suzhenyu006/sonic-agent
src/main/java/org/cloud/sonic/agent/tests/android/minicap/MiniCapInputSocketThread.java
<filename>src/main/java/org/cloud/sonic/agent/tests/android/minicap/MiniCapInputSocketThread.java /* * Copyright (C) [SonicCloudOrg] Sonic Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.cloud.sonic.agent.tests.android.minicap; import com.android.ddmlib.IDevice; import org.cloud.sonic.agent.bridge.android.AndroidDeviceBridgeTool; import org.cloud.sonic.agent.common.maps.ScreenMap; import org.cloud.sonic.agent.tests.android.AndroidTestTaskBootThread; import org.cloud.sonic.agent.tools.PortTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.websocket.Session; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.concurrent.BlockingQueue; import static org.cloud.sonic.agent.tools.BytesTool.subByteArray; /** * minicap socket线程 * 通过端口转发,将设备视频流转发到此Socket * * @author Eason(main) JayWenStar(until e1a877b7) * @date 2021/12/02 00:52 下午 */ public class MiniCapInputSocketThread extends Thread { private final Logger log = LoggerFactory.getLogger(MiniCapInputSocketThread.class); /** * 占用符逻辑参考:{@link AndroidTestTaskBootThread#ANDROID_TEST_TASK_BOOT_PRE} */ public final static String ANDROID_INPUT_SOCKET_PRE = "android-minicap-input-socket-task-%s-%s-%s"; private IDevice iDevice; private BlockingQueue<byte[]> dataQueue; private MiniCapLocalThread miniCapPro; private AndroidTestTaskBootThread androidTestTaskBootThread; private Session session; public MiniCapInputSocketThread(IDevice iDevice, BlockingQueue<byte[]> dataQueue, MiniCapLocalThread miniCapPro, Session session) { this.iDevice = iDevice; this.dataQueue = dataQueue; this.miniCapPro = miniCapPro; this.session = session; this.androidTestTaskBootThread = miniCapPro.getAndroidTestTaskBootThread(); // 让资源合理关闭 this.setDaemon(false); this.setName(androidTestTaskBootThread.formatThreadName(ANDROID_INPUT_SOCKET_PRE)); } public IDevice getiDevice() { return iDevice; } public BlockingQueue<byte[]> getDataQueue() { return dataQueue; } public MiniCapLocalThread getMiniCapPro() { return miniCapPro; } public AndroidTestTaskBootThread getAndroidTestTaskBootThread() { return androidTestTaskBootThread; } public Session getSession() { return session; } @Override public void run() { int finalMiniCapPort = PortTool.getPort(); AndroidDeviceBridgeTool.forward(iDevice, finalMiniCapPort, "minicap"); Socket capSocket = null; InputStream inputStream = null; try { capSocket = new Socket("localhost", finalMiniCapPort); inputStream = capSocket.getInputStream(); int len = 1024; while (miniCapPro.isAlive()) { byte[] buffer = new byte[len]; int realLen; realLen = inputStream.read(buffer); if (buffer.length != realLen && realLen >= 0) { buffer = subByteArray(buffer, 0, realLen); } if (realLen >= 0) { dataQueue.offer(buffer); } } } catch (IOException e) { e.printStackTrace(); } finally { if (miniCapPro.isAlive()) { miniCapPro.interrupt(); log.info("miniCap thread closed."); } if (capSocket != null && capSocket.isConnected()) { try { capSocket.close(); log.info("miniCap socket closed."); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); log.info("miniCap input stream closed."); } catch (IOException e) { e.printStackTrace(); } } } AndroidDeviceBridgeTool.removeForward(iDevice, finalMiniCapPort, "minicap"); if (session != null) { ScreenMap.getMap().remove(session); } } }
ministryofjustice/scs_appraisals
app/services/multi_user_csv_renderer.rb
class MultiUserCSVRenderer def initialize(users) @users = users end def to_csv @users.map { |u| UserCSVRenderer.new(u).to_csv }.join("\n") end end
greenfish77/gaenari
include/gaenari/gaenari/method/stringfy/stringfy.util.hpp
<gh_stars>1-10 #ifndef HEADER_GAENARI_GAENARI_METHOD_STRINGFY_UTIL_HPP #define HEADER_GAENARI_GAENARI_METHOD_STRINGFY_UTIL_HPP namespace gaenari { namespace method { namespace stringfy { namespace util { inline stringfy::type get_mime_type(_in const std::string& mime_type) { if (mime_type == "text/plain") return stringfy::type::text_plain; if (mime_type == "text/colortag") return stringfy::type::text_colortag; return stringfy::type::unknown; } inline std::string get_op(_in const decision_tree::rule_t::rule_type& ruleype) { if (ruleype == decision_tree::rule_t::rule_type::cmp_equ) return "="; if (ruleype == decision_tree::rule_t::rule_type::cmp_lte) return "<="; if (ruleype == decision_tree::rule_t::rule_type::cmp_lt) return "<"; if (ruleype == decision_tree::rule_t::rule_type::cmp_gt) return ">"; if (ruleype == decision_tree::rule_t::rule_type::cmp_gte) return ">="; return "<err>"; } } // util } // stringfy } // method } // gaenari #endif // HEADER_GAENARI_GAENARI_METHOD_STRINGFY_UTIL_HPP
Colbys/smartactors-core
CoreFeatures/Database-plugins/PluginCollectionName/src/main/java/info/smart_tools/smartactors/database_plugins/collection_name_plugin/CollectionNamePlugin.java
<gh_stars>10-100 package info.smart_tools.smartactors.database_plugins.collection_name_plugin; import info.smart_tools.smartactors.feature_loading_system.bootstrap_item.BootstrapItem; import info.smart_tools.smartactors.database.database_storage.exceptions.StorageException; import info.smart_tools.smartactors.database.database_storage.utils.CollectionName; import info.smart_tools.smartactors.base.interfaces.iaction.exception.ActionExecuteException; import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap.IBootstrap; import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap_item.IBootstrapItem; import info.smart_tools.smartactors.ioc.iioccontainer.exception.RegistrationException; import info.smart_tools.smartactors.ioc.iioccontainer.exception.ResolutionException; import info.smart_tools.smartactors.ioc.ikey.IKey; import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException; import info.smart_tools.smartactors.ioc.ioc.IOC; import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.IPlugin; import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.exception.PluginException; import info.smart_tools.smartactors.ioc.named_keys_storage.Keys; import info.smart_tools.smartactors.ioc.resolve_by_name_ioc_with_lambda_strategy.ResolveByNameIocStrategy; /** * Plugin for load IOC strategy for collection name object */ public class CollectionNamePlugin implements IPlugin { private final IBootstrap<IBootstrapItem<String>> bootstrap; /** * Constructor * @param bootstrap bootstrap element */ public CollectionNamePlugin(final IBootstrap<IBootstrapItem<String>> bootstrap) { this.bootstrap = bootstrap; } @Override public void load() throws PluginException { try { IBootstrapItem<String> item = new BootstrapItem("CollectionNamePlugin"); item // .after("IOC") // .before("starter") .process(() -> { try { IKey collectionNameKey = Keys.getOrAdd(CollectionName.class.getCanonicalName()); IOC.register(collectionNameKey, new ResolveByNameIocStrategy( (args) -> { String name = String.valueOf(args[0]); try { return CollectionName.fromString(name); } catch (StorageException e) { throw new RuntimeException("Can't resolve collection name: ", e); } })); } catch (ResolutionException e) { throw new ActionExecuteException("CollectionName plugin can't load: can't get CollectionName key", e); } catch (InvalidArgumentException e) { throw new ActionExecuteException("CollectionName plugin can't load: can't create strategy", e); } catch (RegistrationException e) { throw new ActionExecuteException("CollectionName plugin can't load: can't register new strategy", e); } }); bootstrap.add(item); } catch (InvalidArgumentException e) { throw new PluginException("Can't load collection name plugin", e); } } }
jimkell/mostSandbox
src/edu/rutgers/MOST/presentation/GurobiParametersDialog.java
<reponame>jimkell/mostSandbox<gh_stars>1-10 package edu.rutgers.MOST.presentation; import java.io.File; public class GurobiParametersDialog extends AbstractParametersDialog { private static final long serialVersionUID = 1L; public GurobiParametersDialog( File saveFile ) { super( "Gurobi", saveFile ); GurobiParameters params = new GurobiParameters(); add( params.getDialogPanel(), params.getSavableParameters() ); finishSetup(); setModal( true ); } }
MarchenkoProjects/leech4j
src/main/java/org.leech4j/announce/udp/response/UdpResponse.java
<filename>src/main/java/org.leech4j/announce/udp/response/UdpResponse.java package org.leech4j.announce.udp.response; /** * @author <NAME> */ public interface UdpResponse { boolean isValid(int transactionId); }
Shtekata/14.Softuni-ReactJS
04.Components-Basic-Idea/react-components/src/App.js
<reponame>Shtekata/14.Softuni-ReactJS<filename>04.Components-Basic-Idea/react-components/src/App.js import logo from './logo.svg'; import './App.css'; import Heading from './components/Heading'; import Body from './components/Body'; const booksData = [ { title: 'Harry Potter', description: 'Wizzards and stuff', author: 'J.K.Rowling', isSelected: false }, { title: 'Programming with JS', description: 'Guide to programming', isSelected: false }, { title: 'The Bible', description: 'Most important book', isSelected: false }, { title: 'Chronicles of Narnia', description: 'Adventure', isSelected: false }, { title: null, description: 'Missing book', isSelected: false } ]; function App() { return ( <div className="site-wrapper"> <img src={logo} className="logo" alt="logo" /> <Heading> <h2>Our Custom Library Children</h2> <h3>Fovorite Books</h3> </Heading> <Body booksData={booksData}/> </div> ); } export default App;
stgrosshh/flummi
src/main/java/de/otto/flummi/request/IndicesExistsRequestBuilder.java
<reponame>stgrosshh/flummi<filename>src/main/java/de/otto/flummi/request/IndicesExistsRequestBuilder.java package de.otto.flummi.request; import de.otto.flummi.response.HttpServerErrorException; import de.otto.flummi.util.HttpClientWrapper; import org.asynchttpclient.Response; import org.slf4j.Logger; import java.util.concurrent.ExecutionException; import static org.slf4j.LoggerFactory.getLogger; public class IndicesExistsRequestBuilder implements RequestBuilder<Boolean> { private final String indexName; public static final Logger LOG = getLogger(IndicesExistsRequestBuilder.class); private HttpClientWrapper httpClient; public IndicesExistsRequestBuilder(HttpClientWrapper httpClient, String indexName) { this.indexName = indexName; this.httpClient = httpClient; } public Boolean execute() { try { Response response = httpClient.prepareHead("/" + indexName).execute().get(); int statusCode = response.getStatusCode(); if (statusCode >= 300 && response.getStatusCode() != 404) { throw new HttpServerErrorException(response.getStatusCode(), response.getStatusText(), response.getResponseBody()); } return statusCode < 300; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } }
dk00/old-stuff
tioj/1190.cpp
<reponame>dk00/old-stuff<filename>tioj/1190.cpp #include<cstdio> int s[501][501],to[250001]; main() { int i,j,k,n,m; while(scanf("%d %d",&n,&m)==2) { for(i=k=0;i<n;i++) for(j=0;j<n;j++) s[i][j]=k++; for(i=k=0;i<n*2-1;i++) for(j=0>?(i-n+1);j<=i && j<n;j++) to[s[j][i-j]]=k++; for(i=to[m-1],j=1;i!=m-1;i=to[i],j++); scanf("%d",&k); k%=j; for(i=m-1;k--;i=to[i]); printf("%d\n",i+1); } }
Discounty/Discounty.webapp
app/models/advertisement.rb
# == Schema Information # # Table name: advertisements # # id :integer not null, primary key # name :string # ad_data :json # ad_campaign_id :integer # created_at :datetime not null # updated_at :datetime not null # class Advertisement < ActiveRecord::Base belongs_to :ad_campaign sir_trevor_content :content end
QualiSystemsLab/kubernetes-shell
kubernetes/src/domain/operations/autoload.py
import data_model from domain.services.clients import ApiClientsProvider class AutolaodOperation(object): def __init__(self, api_clients_provider): """ :param ApiClientsProvider api_clients_provider: """ self.api_clients_provider = api_clients_provider def validate_config(self, cloud_provider_resource): """ :param data_model.Kubernetes cloud_provider_resource: :return: """ # create api clients by cluster name clients = self.api_clients_provider.get_api_clients(cloud_provider_resource) # list nodes and make sure we have 1 or more nodes just to check authentication works nodes = clients.core_api.list_node(watch=False) if not nodes or len(nodes.items) < 1: raise ValueError("Cluster '{}' has zero (0) nodes".format(cloud_provider_resource.cluster_name))
IBMStreams/OSStreams
src/cpp/UTILS/XML_utils.cpp
<reponame>IBMStreams/OSStreams /* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <UTILS/SPCTypes.h> #include <UTILS/XML_utils.h> #include <xercesc/framework/MemBufFormatTarget.hpp> #include <xercesc/util/IOException.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #include <xercesc/util/TransService.hpp> #include <xercesc/util/XMLUniDefs.hpp> using namespace std; using namespace xercesc; SPC_NAMESPACE_USE #define XML_UNICODE_FORM(str) XStr(str).unicodeForm() //---------------------------------------------------------------------- // get the value of a text node //---------------------------------------------------------------------- string XML_utils::getTextValue(DOMNode* pCurrent) { char* strValue = NULL; strValue = XMLString::transcode(pCurrent->getTextContent()); string s; if (strValue) { s.assign(strValue); XMLString::release(&strValue); } return s; } //---------------------------------------------------------------------- // get the XML value of a node //---------------------------------------------------------------------- string XML_utils::getRawTextValue(DOMNode* pCurrent) { string toret; try { // outputting the updated JDL static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull }; DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(gLS); // construct the DOMLSSerializer DOMLSSerializer* mySerializer = (static_cast<DOMImplementationLS*>(impl))->createLSSerializer(); assert(mySerializer); // getting the updated jdl char* str = XMLString::transcode(mySerializer->writeToString(pCurrent)); toret = str; // release the memory mySerializer->release(); XMLString::release(&str); } catch (const XERCES_CPP_NAMESPACE_QUALIFIER OutOfMemoryException& ex) { stringstream msg; msg << __FUNCTION__ << ": An error occurred during parsing/rewriting " << ": " << ex.getType() << " (" << ex.getMessage() << ")"; THROW(ParseError, msg.str()); } catch (const XERCES_CPP_NAMESPACE_QUALIFIER IOException& ex) { stringstream msg; msg << __FUNCTION__ << ": An error occurred during parsing/rewriting " << ": " << ex.getType() << " (" << ex.getMessage() << ")"; THROW(ParseError, msg.str()); } catch (const XMLException& ex) { stringstream msg; msg << __FUNCTION__ << ": An error occurred during parsing/rewriting " << ": " << ex.getType() << " (" << ex.getMessage() << ")"; THROW(ParseError, msg.str()); } catch (const DOMException& ex) { stringstream msg; msg << __FUNCTION__ << ": An error occurred during parsing/rewriting " << ": code=" << ex.code; unsigned maxLen = 1023; XMLCh errText[maxLen + 1]; if (DOMImplementation::loadDOMExceptionMsg(ex.code, errText, maxLen)) { msg << " DOMImplementation::loadDOMExceptionMsg failed"; } else { msg << " " << errText; } THROW(ParseError, msg.str()); } catch (...) { stringstream msg; msg << __FUNCTION__ << ": An error of unknown nature happened during parsing/rewriting "; THROW(ParseError, msg.str()); } return toret; } //---------------------------------------------------------------------- // get the value of an attribute name //---------------------------------------------------------------------- string XML_utils::getAttribValue(DOMNode* pCurrent, const char* attribName) { string str; // Get the attributes, if any, of the current element DOMNamedNodeMap* nodeMap = pCurrent->getAttributes(); // Check if the current node has any attributes if ((nodeMap != NULL) && (nodeMap->getLength() > 0)) { XMLCh* xmlString = NULL; xmlString = XMLString::transcode(attribName); if (xmlString) { DOMNode* attribNode = nodeMap->getNamedItem(xmlString); // Check if attribute node exists if (attribNode) { XMLCh* attribValue = NULL; attribValue = (XMLCh*)attribNode->getNodeValue(); if (attribValue) { // get the instance name char* strValue = NULL; strValue = XMLString::transcode(attribValue); if (strValue) { str.assign(strValue); XMLString::release(&strValue); } } } XMLString::release(&xmlString); } } return str; } void XML_utils::setAttribValue(DOMDocument* doc, DOMNode* pCurrent, const string& attribName, const string& attribValue) { string str; // Get the attributes, if any, of the current element DOMNamedNodeMap* nodeMap = pCurrent->getAttributes(); // Check if the current node has any attributes if ((nodeMap != NULL) && (nodeMap->getLength() > 0)) { XMLCh* xmlString = NULL; xmlString = XMLString::transcode(attribName.c_str()); if (xmlString) { DOMNode* attribNode = nodeMap->getNamedItem(xmlString); // Check if attribute node exists if (attribNode != NULL) { XMLCh* value = NULL; value = XMLString::transcode(attribValue.c_str()); if (value) { attribNode->setNodeValue(value); XMLString::release(&value); } } else { DOMElement* el = static_cast<DOMElement*>(pCurrent); XMLCh* name = NULL; name = XMLString::transcode(attribName.c_str()); XMLCh* value = NULL; value = XMLString::transcode(attribValue.c_str()); el->setAttribute(name, value); if (name) { XMLString::release(&name); } if (value) { XMLString::release(&value); } } XMLString::release(&xmlString); } } else { DOMElement* el = static_cast<DOMElement*>(pCurrent); XMLCh* name = NULL; name = XMLString::transcode(attribName.c_str()); XMLCh* value = NULL; value = XMLString::transcode(attribValue.c_str()); el->setAttribute(name, value); if (name) { XMLString::release(&name); } if (value) { XMLString::release(&value); } } } DOMNode* XML_utils::getMatchingNode(DOMDocument* pDoc, const char* tagName, const char* attribName, const char* attribValue) { DOMNodeList* nodeList = pDoc->getElementsByTagName(XML_UNICODE_FORM(tagName)); // go through the list and find the element with the matching value. int numElements = nodeList->getLength(); for (int i = 0; i < numElements; i++) { if (getAttribValue(nodeList->item(i), attribName) == attribValue) { return nodeList->item(i); } } return NULL; } int XML_utils::addChildTextTag(DOMDocument* pDoc, const char* tagName, const char* attribName, const char* attribValue, const char* childTag, const char* childValue) { DOMNode* dNode = getMatchingNode(pDoc, tagName, attribName, attribValue); if (!dNode) { return 1; // error } DOMElement* pElem = pDoc->createElement(XML_UNICODE_FORM(childTag)); dNode->appendChild(pElem); DOMText* pFragment = pDoc->createTextNode(XML_UNICODE_FORM(childValue)); pElem->appendChild(pFragment); return 0; } void XML_utils::trimWhiteSpace(string& str) { string::size_type fpos = str.find_first_not_of(" \r\t\n"); string::size_type lpos = str.find_last_not_of(" \r\t\n"); if (lpos == string::npos || fpos == string::npos) { str = string(); } else { str = str.substr(fpos, lpos - fpos + 1); } } string XML_utils::XMLCh2string(const XMLCh* chars) { const char* const outEncoding = "iso-8859-1"; XMLSize_t length = XMLString::stringLen(chars); auto_ptr<XMLByte> result(new XMLByte[length + 1]); XMLTransService::Codes failReason; XMLCh* fOutEncoding = XMLString::transcode(outEncoding); auto_ptr<XMLTranscoder> xml_iso_8859_1_transcoder( XMLPlatformUtils::fgTransService->makeNewTranscoderFor(fOutEncoding, failReason, 1024)); if (xml_iso_8859_1_transcoder.get() == NULL) { cerr << "ERROR: XMLCh2char: failed to switch encoding " << endl; return string(""); } XMLSize_t charsConsumed = 0; unsigned bytes_encoded = xml_iso_8859_1_transcoder->transcodeTo( static_cast<const XMLCh*>(chars), length, static_cast<XMLByte*>(result.get()), length, charsConsumed, XMLTranscoder::UnRep_Throw); XMLByte* ptr = result.get(); ptr[bytes_encoded] = '\0'; delete[] fOutEncoding; return string(reinterpret_cast<char*>(result.get())); } string XML_utils::escape(const char* str) { string res; if (str) { const char* ptr = str; while (*ptr) { switch (*ptr) { case '<': res += "&lt;"; break; case '>': res += "&gt;"; break; case '&': res += "&amp;"; break; default: res += *ptr; } ptr++; } } return res; }
zhcet19/NeoAlgo-1
C/graphs/Adjacency_List.c
<reponame>zhcet19/NeoAlgo-1<filename>C/graphs/Adjacency_List.c /* ADJACENCY LIST FOR REPRESENTING DIRECTED GRAPH It is a method of representing a digraph using 2 linked lists 1. Node list 2. Edge list corresponding to each node Edges arising from a node are stored in edge list of each node */ #include <stdio.h> #include <stdlib.h> /* Declare a structure for representing digraph with data and 2 links * link represents the edge between the parent node and next node (edge list) * pnext point to the next node from which new edges arise(node list) * g points to the graph */ typedef struct AdjacencyList { int data; struct AdjacencyList *link, *pnext; } AdjacencyList; AdjacencyList *g; //to insert into the graph void insert_to_graph(AdjacencyList *g, int parent, int value) { //ptr points to the first node in the graph AdjacencyList *ptr = g->link, *p; //Check if the graph is empty if (g->link == NULL) { //Allocate memory for ptr to store the value of parent node ptr = malloc(sizeof(AdjacencyList)); ptr->data = parent; ptr->pnext = NULL; ptr->link = NULL; // Set ptr as first node g->link = ptr; } else { //Search for parent in the node list while (ptr != NULL && ptr->data != parent) { p = ptr; ptr = ptr->pnext; } //If parent is not found in the node list insert as last node if (ptr == NULL) { ptr = malloc(sizeof(AdjacencyList)); ptr->data = parent; ptr->pnext = NULL; ptr->link = NULL; p->pnext = ptr; } } //Allocate memory for node to insert value in the edge list of parent node AdjacencyList *node; node = (AdjacencyList *)malloc(sizeof(AdjacencyList)); node->data = value; node->link = NULL; node->pnext = NULL; //Traverse till the end of the edge list while (ptr->link != NULL) ptr = ptr->link; //Insert value as the last node in the edge list ptr->link = node; } //To delete a node from the graph void delete_from_graph(AdjacencyList *g, int value) { //Set flag as 0 assuming value is not present in the graph int flag = 0; //If the graph is not empty if (g->link != NULL) { //ptr points to first node AdjacencyList *ptr = g->link, *p, *pre; //If the first node in the node list is value if (ptr->data == value) { //Delete the node and make the next node in node list as first node g->link = ptr->pnext; //value is present in the graph flag = 1; } //If value is not the first node else { //Traverse the node list till value is found while (ptr->pnext != NULL && ptr->data != value) { p = ptr; ptr = ptr->pnext; } //If value is found if (ptr->data == value) { //delete value node from the node list and rearrange pnext p->pnext = ptr->pnext; //value is present in the graph flag = 1; } } //ptr points to first node in the node list ptr = g->link; //Traverse till the end of the node list while (ptr != NULL) { //p is set as ptr p = ptr; //traverse the edge list of p till value is found while (p->link && p->data != value) { pre = p; p = p->link; } // If value is found in the edge list of p if (p->data == value) { //delete the edge between value and p pre->link = p->link; //value is present in the graph flag = 1; } //move to the next node in node list ptr = ptr->pnext; } } //If flag is 0 value in not present in the graph if (flag == 0) printf("Node %d does not exist !\n", value); } //to print the graph void print_graph(AdjacencyList *g) { //Check if graph is empty if (g->link == NULL) printf("Graph Empty !\n"); else { //ptr points to first node in the node list AdjacencyList *ptr = g->link, *p; //Traverse the node list while (ptr) { //print node p p = ptr; printf("%d ->", ptr->data); //traverse the edge list of p and print all the nodes while (p->link) { printf(" %d", p->link->data); p = p->link; } printf("\n"); ptr = ptr->pnext; } } } int main() { AdjacencyList *g = (AdjacencyList *)malloc(sizeof(AdjacencyList) * 10); g->link = NULL; //menu driven program to insert, delete and print graph according to choice while (1) { int choice; scanf("%d", &choice); switch (choice) { case 1: { int parent, value; scanf("%d %d", &parent, &value); insert_to_graph(g, parent, value); } break; case 2: { int value; scanf("%d", &value); delete_from_graph(g, value); } break; case 3: { print_graph(g); } break; case 4: { return 0; } } } return 0; } /* Sample input 1 2 3 1 3 4 1 1 5 1 2 4 3 4 Sample output 2 -> 3 4 3 -> 4 1 -> 5 */ /* TIME COMPLEXITY Insertion - O(n) Deletion - O(n^2) Print graph - O(n^2) Total time complexity of the program - O(n^2) SPACE COMPLEXITY- O(n) */
FabinoHq/wos
interface/guipxtext.js
//////////////////////////////////////////////////////////////////////////////// // _______ ________________________________ // // \\ . \ ________/ . . . . . . . . . . . . . . / // // \\ . \ ____ ___/ . . . . . __________________________/ // // \\ . \ // \ __/. . . _________/ / // . _________/ // // \\ . \_// \_// ___/. _____ / // . /_____ // // \\ . \/ _ \/ _/// . / \\ | \\ . \ // // \\ . /\\ / || . | || | \\______ \ // // \\ . / \\ / || . \____// | _________// / // // \\ . / \\ / // . / // . . . . / // // \\__/ \\_/ //______________/ //_____________/ // // // //////////////////////////////////////////////////////////////////////////////// // This is free and unencumbered software released into the public domain. // // // // Anyone is free to copy, modify, publish, use, compile, sell, or // // distribute this software, either in source code form or as a compiled // // binary, for any purpose, commercial or non-commercial, and by any // // means. // // // // In jurisdictions that recognize copyright laws, the author or authors // // of this software dedicate any and all copyright interest in the // // software to the public domain. We make this dedication for the benefit // // of the public at large and to the detriment of our heirs and // // successors. We intend this dedication to be an overt act of // // relinquishment in perpetuity of all present and future rights to this // // software under copyright law. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR // // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // // OTHER DEALINGS IN THE SOFTWARE. // // // // For more information, please refer to <http://unlicense.org> // //////////////////////////////////////////////////////////////////////////////// // WOS : Web Operating System // // interface/guipxtext.js : GUI Pixel Text (distance field) management // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Default pixel text hidden pass character // //////////////////////////////////////////////////////////////////////////////// const HiddenPxTextPassCharacter = '*'; //////////////////////////////////////////////////////////////////////////////// // Default pixel font settings // //////////////////////////////////////////////////////////////////////////////// const WOSDefaultMinPxTextWidth = 0.001; const WOSDefaultMaxPxTextWidth = 1.98; const WOSDefaultMinPxTextHeight = 0.025; const WOSDefaultMaxPxTextHeight = 0.2; const WOSDefaultPxTextUVWidth = 0.0625; const WOSDefaultPxTextUVHeight = 0.125; const WOSDefaultPxTextXOffset = 0.44; const WOSDefaultPxTextYOffset = 0.92; const WOSDefaultPxTextScaleXFactor = 1024.0; const WOSDefaultPxTextScaleYFactor = 1024.0; //////////////////////////////////////////////////////////////////////////////// // GuiPxText class definition // // param renderer : Renderer pointer // // param textShader : Text shader pointer // // param lineShader : Text line shader pointer // //////////////////////////////////////////////////////////////////////////////// function GuiPxText(renderer, textShader, lineShader) { // Renderer pointer this.renderer = renderer; // Text shader pointer this.textShader = textShader; // Line shader pointer this.lineShader = lineShader; // Text shader uniforms locations this.colorUniform = null; this.alphaUniform = null; this.smoothUniform = null; this.uvSizeUniform = null; this.uvOffsetUniform = null; // GuiPxText glyphs texture this.texture = null; // GuiPxText line texture this.lineTexture = null; // GuiPxText line need update this.needUpdate = false; // GuiPxText model matrix this.modelMatrix = new Matrix4x4(); // GuiPxText position this.position = new Vector2(0.0, 0.0); // GuiPxText size this.size = new Vector2(0.05, 0.05); // GuiPxText rotation angle this.angle = 0.0; // GuiPxText color this.color = new Vector3(1.0, 1.0, 1.0); // GuiPxText character alpha this.charAlpha = 1.0; // GuiPxText alpha this.alpha = 1.0; // GuiPxText smooth value this.smooth = 0.1; // GuiPxText UV size this.uvSize = new Vector2(1.0, 1.0); // GuiPxText UV offset this.uvOffset = new Vector2(0.0, 0.0); // GuiPxText internal string this.text = ""; this.textLength = 0; // Characters size this.charsize = new Vector2(1.0, 1.0); // Hidden text mode this.hidden = false; this.hidetext = ""; // Line optimize mode this.lineOptimize = true; // VecMat 4x4 model matrix this.vecmat = new VecMat4x4(); } GuiPxText.prototype = { //////////////////////////////////////////////////////////////////////////// // init : Init GUI PxText // // param lineOptimize : Text line texture optimization // // param texture : Texture pointer // // param text : Text to set // // param height : Text field height // // param hide : Text hide mode // // return : True if GUI PxText is successfully loaded // //////////////////////////////////////////////////////////////////////////// init: function(lineOptimize, texture, text, height, hide) { var i = 0; // Reset GuiText this.colorUniform = null; this.alphaUniform = null; this.smoothUniform = null; this.uvSizeUniform = null; this.uvOffsetUniform = null; this.texture = null; this.lineTexture = null; this.needUpdate = false; if (!this.modelMatrix) return false; this.modelMatrix.setIdentity(); if (!this.position) return false; this.position.reset(); this.angle = 0.0; if (!this.size) return false; this.size.setXY(1.0, 1.0); if (!this.color) return false; this.color.setXYZ(1.0, 1.0, 1.0); if (!this.uvSize) return false; this.uvSize.setXY(WOSDefaultPxTextUVWidth, WOSDefaultPxTextUVHeight); if (!this.uvOffset) return false; this.uvOffset.reset(); this.charAlpha = 1.0; this.alpha = 1.0; this.smooth = 0.1; this.text = ""; this.textLength = 0; if (!this.charsize) return false; this.charsize.setXY(1.0, 1.0); this.hidden = false; this.hidetext = ""; if (!this.vecmat) return false; this.vecmat.setIdentity(); // Set line optimize mode if (lineOptimize !== undefined) this.lineOptimize = lineOptimize; // Set hidden mode if (hide !== undefined) this.hidden = hide; // Set text if (text !== undefined) { this.textLength = text.length; if (this.hidden) { for (i = 0; i < this.textLength; ++i) { this.hidetext += this.convertASCII(text[i]); this.text += HiddenPxTextPassCharacter; } } else { for (i = 0; i < this.textLength; ++i) { this.text += this.convertASCII(text[i]); } } } // Set char size if (height !== undefined) this.charsize.vec[1] = height; if (this.charsize.vec[1] <= WOSDefaultMinPxTextHeight) this.charsize.vec[1] = WOSDefaultMinPxTextHeight; if (this.charsize.vec[1] >= WOSDefaultMaxPxTextHeight) this.charsize.vec[1] = WOSDefaultMaxPxTextHeight; this.charsize.vec[0] = this.charsize.vec[1]; // Set text size if (this.lineOptimize) { this.size.vec[0] = this.charsize.vec[0]*WOSDefaultPxTextXOffset*(this.textLength+1) +(1.0/WOSDefaultPxTextXOffset)*(this.textLength+1)*0.00007; } else { this.size.vec[0] = this.charsize.vec[0]* WOSDefaultPxTextXOffset*(this.textLength+1); } this.size.vec[1] = this.charsize.vec[1]; // Check renderer pointer if (!this.renderer) return false; // Check gl pointer if (!this.renderer.gl) return false; // Check text shader pointer if (!this.textShader) return false; // Line shader optimization if (this.lineOptimize) { // Check line shader pointer if (!this.lineShader) return false; } // Get text shader uniforms locations this.textShader.bind(); this.colorUniform = this.textShader.getUniform("color"); if (!this.colorUniform) return false; this.alphaUniform = this.textShader.getUniform("alpha"); if (!this.alphaUniform) return false; this.smoothUniform = this.textShader.getUniform("smooth"); if (!this.smoothUniform) return false; this.uvOffsetUniform = this.textShader.getUniform("uvOffset"); if (!this.uvOffsetUniform) return false; this.uvSizeUniform = this.textShader.getUniform("uvSize"); if (!this.uvSizeUniform) return false; this.textShader.unbind(); // Set texture this.texture = texture; if (!this.texture) return false; this.texture.setSmooth(true); // Clamp text width if (this.size.vec[0] <= WOSDefaultMinPxTextWidth) this.size.vec[0] = WOSDefaultMinPxTextWidth; if (this.size.vec[0] >= WOSDefaultMaxPxTextWidth) this.size.vec[0] = WOSDefaultMaxPxTextWidth; // Create line texture this.lineTexture = this.renderer.gl.createTexture(); if (!this.lineTexture) { // Could not create line texture return false; } this.renderer.gl.bindTexture( this.renderer.gl.TEXTURE_2D, this.lineTexture ); this.renderer.gl.texImage2D( this.renderer.gl.TEXTURE_2D, 0, this.renderer.gl.RGBA, 1, 1, 0, this.renderer.gl.RGBA, this.renderer.gl.UNSIGNED_BYTE, null ); // Set line texture wrap mode this.renderer.gl.texParameteri( this.renderer.gl.TEXTURE_2D, this.renderer.gl.TEXTURE_WRAP_S, this.renderer.gl.CLAMP_TO_EDGE ); this.renderer.gl.texParameteri( this.renderer.gl.TEXTURE_2D, this.renderer.gl.TEXTURE_WRAP_T, this.renderer.gl.CLAMP_TO_EDGE ); // Set line texture min and mag filters this.renderer.gl.texParameteri( this.renderer.gl.TEXTURE_2D, this.renderer.gl.TEXTURE_MIN_FILTER, this.renderer.gl.LINEAR ); this.renderer.gl.texParameteri( this.renderer.gl.TEXTURE_2D, this.renderer.gl.TEXTURE_MAG_FILTER, this.renderer.gl.LINEAR ); // PxText line need update this.needUpdate = true; // GUI PxText successfully loaded return true; }, //////////////////////////////////////////////////////////////////////////// // setPosition : Set text position // // param x : Text X position // // param y : Text Y position // //////////////////////////////////////////////////////////////////////////// setPosition: function(x, y) { this.position.vec[0] = x; this.position.vec[1] = y; }, //////////////////////////////////////////////////////////////////////////// // setPositionVec2 : Set text position from a 2 components vector // // param vector : 2 components vector to set text position from // //////////////////////////////////////////////////////////////////////////// setPositionVec2: function(vector) { this.position.vec[0] = vector.vec[0]; this.position.vec[1] = vector.vec[1]; }, //////////////////////////////////////////////////////////////////////////// // setX : Set text X position // // param x : Text X position // //////////////////////////////////////////////////////////////////////////// setX: function(x) { this.position.vec[0] = x; }, //////////////////////////////////////////////////////////////////////////// // setY : Set text Y position // // param y : Text Y position // //////////////////////////////////////////////////////////////////////////// setY: function(y) { this.position.vec[1] = y; }, //////////////////////////////////////////////////////////////////////////// // move : Translate text // // param x : X axis translate value // // param y : Y axis translate value // //////////////////////////////////////////////////////////////////////////// move: function(x, y) { this.position.vec[0] += x; this.position.vec[1] += y; }, //////////////////////////////////////////////////////////////////////////// // moveVec2 : Translate text by a 2 components vector // // param vector : 2 components vector to translate text by // //////////////////////////////////////////////////////////////////////////// moveVec2: function(vector) { this.position.vec[0] += vector.vec[0]; this.position.vec[1] += vector.vec[1]; }, //////////////////////////////////////////////////////////////////////////// // moveX : Translate text on X axis // // param x : X axis translate value // //////////////////////////////////////////////////////////////////////////// moveX: function(x) { this.position.vec[0] += x; }, //////////////////////////////////////////////////////////////////////////// // moveY : Translate text on Y axis // // param y : Y axis translate value // //////////////////////////////////////////////////////////////////////////// moveY: function(y) { this.position.vec[1] += y; }, //////////////////////////////////////////////////////////////////////////// // setHeight : Set text height // // param height : Text height to set // //////////////////////////////////////////////////////////////////////////// setHeight: function(height) { // Set char size if (height <= WOSDefaultMinPxTextHeight) height = WOSDefaultMinPxTextHeight; if (height >= WOSDefaultMaxPxTextHeight) height = WOSDefaultMaxPxTextHeight; this.charsize.vec[0] = height; this.charsize.vec[1] = height; // Set text size if (this.lineOptimize) { this.size.vec[0] = this.charsize.vec[0]*WOSDefaultPxTextXOffset*(this.textLength+1) +(1.0/WOSDefaultPxTextXOffset)*(this.textLength+1)*0.00007; } else { this.size.vec[0] = this.charsize.vec[0]* WOSDefaultPxTextXOffset*(this.textLength+1); } this.size.vec[1] = this.charsize.vec[1]; // Text line need update this.needUpdate = true; }, //////////////////////////////////////////////////////////////////////////// // setAngle : Set text rotation angle // // param angle : Text rotation angle to set in radians // //////////////////////////////////////////////////////////////////////////// setAngle: function(angle) { this.angle = angle; }, //////////////////////////////////////////////////////////////////////////// // rotate : Rotate text // // param angle : Angle to rotate text by in radians // //////////////////////////////////////////////////////////////////////////// rotate: function(angle) { this.angle += angle; }, //////////////////////////////////////////////////////////////////////////// // setColor : Set text color // // param r : Text red color channel to set // // param g : Text blue color channel to set // // param b : Text green color channel to set // //////////////////////////////////////////////////////////////////////////// setColor: function(r, g, b) { this.color.vec[0] = r; this.color.vec[1] = g; this.color.vec[2] = b; // Text line need update this.needUpdate = true; }, //////////////////////////////////////////////////////////////////////////// // setColorVec3 : Set text color from a 3 component vector // // param color : 3 component vector to set text color from // //////////////////////////////////////////////////////////////////////////// setColorVec3: function(color) { this.color.vec[0] = color.vec[0]; this.color.vec[1] = color.vec[1]; this.color.vec[2] = color.vec[2]; // Text line need update this.needUpdate = true; }, //////////////////////////////////////////////////////////////////////////// // setCharAlpha : Set character alpha // // param alpha : Text character alpha to set // //////////////////////////////////////////////////////////////////////////// setCharAlpha: function(alpha) { this.charAlpha = alpha; }, //////////////////////////////////////////////////////////////////////////// // setAlpha : Set text alpha // // param alpha : Text alpha to set // //////////////////////////////////////////////////////////////////////////// setAlpha: function(alpha) { this.alpha = alpha; }, //////////////////////////////////////////////////////////////////////////// // setSmooth : Set text smooth value // // param smooth : Text smooth value to set // //////////////////////////////////////////////////////////////////////////// setSmooth: function(smooth) { if (smooth <= 0.0) smooth = 0.0; if (smooth >= 1.0) smooth = 1.0; this.smooth = smooth*0.4; // Text line need update this.needUpdate = true; }, //////////////////////////////////////////////////////////////////////////// // setText : Set GuiText internal text string // // param text : Text to set // //////////////////////////////////////////////////////////////////////////// setText: function(text) { // Set text this.text = ""; this.hidetext = ""; this.textLength = 0; if (text) { this.textLength = text.length; if (this.hidden) { for (i = 0; i < this.textLength; ++i) { this.hidetext += this.convertASCII(text[i]); this.text += HiddenPxTextPassCharacter; } } else { for (i = 0; i < this.textLength; ++i) { this.text += this.convertASCII(text[i]); } } } // Set text width if (this.lineOptimize) { this.size.vec[0] = this.charsize.vec[0]*WOSDefaultPxTextXOffset*(this.textLength+1) +(1.0/WOSDefaultPxTextXOffset)*(this.textLength+1)*0.00007; } else { this.size.vec[0] = this.charsize.vec[0]* WOSDefaultPxTextXOffset*(this.textLength+1); } this.size.vec[1] = this.charsize.vec[1]; // Clamp text width if (this.size.vec[0] <= WOSDefaultMinPxTextWidth) this.size.vec[0] = WOSDefaultMinPxTextWidth; if (this.size.vec[0] >= WOSDefaultMaxPxTextWidth) this.size.vec[0] = WOSDefaultMaxPxTextWidth; // Text line need update this.needUpdate = true; }, //////////////////////////////////////////////////////////////////////////// // addCharacter : Add character to text at given index // // param index : Index to add character at // // param character : Character to add at specified index // //////////////////////////////////////////////////////////////////////////// addCharacter: function(index, character) { // Clamp index into text length range if (index <= 0) index = 0; if (index >= this.textLength) index = this.textLength; // Insert character this.setText( this.text.substring(0, index) + this.convertASCII(character) + this.text.substring(index, this.textLength) ); }, //////////////////////////////////////////////////////////////////////////// // eraseCharacter : Erase text character at given index // // param index : Index to erase character at // //////////////////////////////////////////////////////////////////////////// eraseCharacter: function(index) { if (this.textLength > 0) { // Clamp index into text length range if (index <= 1) index = 1; if (index >= this.textLength) index = this.textLength; // Erase character this.setText( this.text.substring(0, index-1) + this.text.substring(index, this.textLength) ); } }, //////////////////////////////////////////////////////////////////////////// // eraseSelection : Erase text characters between start and end indexes // // param start : Start index to erase characters from // // param end : Start index to erase characters to // //////////////////////////////////////////////////////////////////////////// eraseSelection: function(start, end) { var selStart = 0; var selEnd = 0; // Check indexes ordering if (start == end) { // Nothing to erase return; } else if (start < end) { // Normal indexes order selStart = start; selEnd = end; } else { // Inverted indexes order selStart = end; selEnd = start; } // Clamp indexes into text length range if (selStart <= 0) selStart = 0; if (selStart >= this.textLength) selStart = this.textLength; if (selEnd <= 0) selEnd = 0; if (selEnd >= this.textLength) selEnd = this.textLength; // Erase characters selection this.setText( this.text.substring(0, selStart) + this.text.substring(selEnd, this.textLength) ); }, //////////////////////////////////////////////////////////////////////////// // convertASCII : Convert character to ASCII // // param character : Character to convert to ASCII // // return : ASCII converted character // //////////////////////////////////////////////////////////////////////////// convertASCII: function(character) { if (character == '\u00A1') return '!'; if (character == '\u00B5') return 'u'; if (character == '\u00BF') return '?'; if (character == '\u00C0') return 'A'; if (character == '\u00C1') return 'A'; if (character == '\u00C2') return 'A'; if (character == '\u00C3') return 'A'; if (character == '\u00C4') return 'A'; if (character == '\u00C5') return 'A'; if (character == '\u00C7') return 'C'; if (character == '\u00C8') return 'E'; if (character == '\u00C9') return 'E'; if (character == '\u00CA') return 'E'; if (character == '\u00CB') return 'E'; if (character == '\u00CC') return 'I'; if (character == '\u00CD') return 'I'; if (character == '\u00CE') return 'I'; if (character == '\u00CF') return 'I'; if (character == '\u00D1') return 'N'; if (character == '\u00D2') return 'O'; if (character == '\u00D3') return 'O'; if (character == '\u00D4') return 'O'; if (character == '\u00D5') return 'O'; if (character == '\u00D6') return 'O'; if (character == '\u00D7') return 'x'; if (character == '\u00D8') return 'O'; if (character == '\u00D9') return 'U'; if (character == '\u00DA') return 'U'; if (character == '\u00DB') return 'U'; if (character == '\u00DC') return 'U'; if (character == '\u00DD') return 'Y'; if (character == '\u00E0') return 'a'; if (character == '\u00E1') return 'a'; if (character == '\u00E2') return 'a'; if (character == '\u00E3') return 'a'; if (character == '\u00E4') return 'a'; if (character == '\u00E5') return 'a'; if (character == '\u00E7') return 'c'; if (character == '\u00E8') return 'e'; if (character == '\u00E9') return 'e'; if (character == '\u00EA') return 'e'; if (character == '\u00EB') return 'e'; if (character == '\u00EC') return 'i'; if (character == '\u00ED') return 'i'; if (character == '\u00EE') return 'i'; if (character == '\u00EF') return 'i'; if (character == '\u00F1') return 'n'; if (character == '\u00F2') return 'o'; if (character == '\u00F3') return 'o'; if (character == '\u00F4') return 'o'; if (character == '\u00F5') return 'o'; if (character == '\u00F6') return 'o'; if (character == '\u00F7') return '/'; if (character == '\u00F8') return 'o'; if (character == '\u00F9') return 'u'; if (character == '\u00FA') return 'u'; if (character == '\u00FB') return 'u'; if (character == '\u00FC') return 'u'; if (character == '\u00FD') return 'y'; if (character == '\u00FF') return 'y'; if (character.charCodeAt(0) < 32) return ''; if (character.charCodeAt(0) > 126) return '?'; return character; }, //////////////////////////////////////////////////////////////////////////// // setHidden : Set text hidden mode // // param hidden : Text hidden mode to set // //////////////////////////////////////////////////////////////////////////// setHidden: function(hidden) { var text = this.getText(); this.hidden = hidden; this.setText(text); }, //////////////////////////////////////////////////////////////////////////// // getX : Get text X position // // return : Text X position // //////////////////////////////////////////////////////////////////////////// getX: function() { return this.position.vec[0]; }, //////////////////////////////////////////////////////////////////////////// // getY : Get text Y position // // return : Text Y position // //////////////////////////////////////////////////////////////////////////// getY: function() { return this.position.vec[1]; }, //////////////////////////////////////////////////////////////////////////// // getWidth : Get text width // // return : Text width // //////////////////////////////////////////////////////////////////////////// getWidth: function() { return this.size.vec[0]; }, //////////////////////////////////////////////////////////////////////////// // getHeight : Get text height // // return : Text height // //////////////////////////////////////////////////////////////////////////// getHeight: function() { return this.size.vec[1]; }, //////////////////////////////////////////////////////////////////////////// // getAngle : Get text rotation angle // // return : Text rotation angle in radians // //////////////////////////////////////////////////////////////////////////// getAngle: function() { return this.angle; }, //////////////////////////////////////////////////////////////////////////// // getCharAlpha : Get text character alpha // // return : Text character alpha // //////////////////////////////////////////////////////////////////////////// getCharAlpha: function() { return this.charAlpha; }, //////////////////////////////////////////////////////////////////////////// // getAlpha : Get text alpha // // return : Text alpha // //////////////////////////////////////////////////////////////////////////// getAlpha: function() { return this.alpha; }, //////////////////////////////////////////////////////////////////////////// // getSmooth : Get smooth value // // return : Text smooth value // //////////////////////////////////////////////////////////////////////////// getSmooth: function() { return this.smooth; }, //////////////////////////////////////////////////////////////////////////// // getText : Get text internal string // // return : Text internal string // //////////////////////////////////////////////////////////////////////////// getText: function() { if (this.hidden) return this.hidetext; return this.text; }, //////////////////////////////////////////////////////////////////////////// // getChar : Get text character at given index // // param index : Index to get text character at // // return : Text character at given index // //////////////////////////////////////////////////////////////////////////// getChar: function(index) { // Clamp index into text length range if (index <= 0) index = 0; if (index >= this.textLength) index = this.textLength; if (this.hidden) return this.hidetext[index]; return this.text[index]; }, //////////////////////////////////////////////////////////////////////////// // getCharPos : Get character position offset at given index // // param index : Index to get character position at // // return : character position offset // //////////////////////////////////////////////////////////////////////////// getCharPos: function(index) { var charPos = 0.0; // Clamp index into text length range if (index <= 0) index = 0; if (index >= this.textLength) index = this.textLength; // Compute chararacter position charPos = (WOSDefaultPxTextXOffset*this.charsize.vec[0]*index)+ (WOSDefaultPxTextXOffset*this.charsize.vec[0]*0.42); // Return character position at given index return charPos; }, //////////////////////////////////////////////////////////////////////////// // getNextWidth : Get text next width when a character is inserted // // return : Text width when new character is inserted // //////////////////////////////////////////////////////////////////////////// getNextWidth: function() { // Return next text width return (this.size.vec[0]+this.charsize.vec[0]*WOSDefaultPxTextXOffset); }, //////////////////////////////////////////////////////////////////////////// // getLength : Get text characters length // // return : Text length // //////////////////////////////////////////////////////////////////////////// getLength: function() { return this.textLength; }, //////////////////////////////////////////////////////////////////////////// // getFontsize : Get text font size // // return : Text font size // //////////////////////////////////////////////////////////////////////////// getFontsize: function() { return this.charsize.vec[1]; }, //////////////////////////////////////////////////////////////////////////// // getHidden : Get text hidden mode // // return : Text hidden mode // //////////////////////////////////////////////////////////////////////////// getHidden: function() { return this.hidden; }, //////////////////////////////////////////////////////////////////////////// // render : Render text // //////////////////////////////////////////////////////////////////////////// render: function() { var i = 0; var charCode = 0; var charX = 0; var charY = 0; var lineWidth = 0; var lineHeight = 0; if (this.lineOptimize) { if (this.needUpdate) { // Update line size lineWidth = Math.round( this.size.vec[0]*WOSDefaultPxTextScaleXFactor ); lineHeight = Math.round( this.size.vec[1]*WOSDefaultPxTextScaleYFactor ); this.size.vec[0] = lineWidth/WOSDefaultPxTextScaleXFactor; this.size.vec[1] = lineHeight/WOSDefaultPxTextScaleYFactor; // Set text line renderer size this.renderer.textLineRenderer.setShader(this.lineShader); this.renderer.textLineRenderer.setTexture(this.lineTexture); if (!this.renderer.textLineRenderer.setRenderSize( lineWidth, lineHeight)) { return; } // Render into text line renderer this.renderer.textLineRenderer.clear(); this.renderer.textLineRenderer.setActive(); // Bind text shader this.textShader.bind(); // Send shader uniforms this.textShader.sendUniformVec3(this.colorUniform, this.color); this.textShader.sendUniform(this.alphaUniform, this.charAlpha); this.textShader.sendUniform(this.smoothUniform, this.smooth); this.textShader.sendUniformVec2( this.uvSizeUniform, this.uvSize ); // Bind texture this.texture.bind(); // Bind VBO this.renderer.vertexBuffer.bind(); // Render text for (i = 0; i < this.textLength; ++i) { // Get current character charCode = this.text.charCodeAt(i)-32; if (charCode < 0) { charCode = 31; } if (charCode > 94) { charCode = 31; } charX = Math.floor(charCode%16); charY = Math.floor(charCode/16); if (charX <= 0) { charX = 0; } if (charX >= 15) { charX = 15; } if (charY <= 0) { charY = 0; } if (charY >= 5) { charY = 5; } // Set text model matrix this.modelMatrix.setIdentity(); if (this.size.vec[1] > 0.0) { this.modelMatrix.scale( 2.0/this.size.vec[1], 2.0/this.size.vec[1], 1.0 ); } this.modelMatrix.translate( -this.size.vec[0]*0.5, -this.size.vec[1]*0.5, 0.0 ); this.modelMatrix.translateX( (WOSDefaultPxTextXOffset*this.charsize.vec[0]*i)- (WOSDefaultPxTextXOffset*this.charsize.vec[0]*0.18) ); this.modelMatrix.scaleVec2(this.charsize); this.vecmat.setMatrix(this.modelMatrix); // Compute world matrix this.renderer.worldMatrix.setMatrix( this.renderer.projMatrix ); this.renderer.worldMatrix.multiply( this.renderer.view.viewMatrix ); this.uvOffset.vec[0] = charX*WOSDefaultPxTextUVWidth; this.uvOffset.vec[1] = charY*WOSDefaultPxTextUVHeight; // Update shader uniforms this.textShader.sendWorldMatrix(this.renderer.worldMatrix); this.textShader.sendModelVecmat(this.vecmat); this.textShader.sendUniformVec2( this.uvOffsetUniform, this.uvOffset ); // Render VBO this.renderer.vertexBuffer.render(this.textShader); } // Unbind VBO this.renderer.vertexBuffer.unbind(); // Unbind texture this.texture.unbind(); // Set renderer as active this.renderer.setActive(); // Recompute world matrix this.renderer.worldMatrix.setMatrix( this.renderer.projMatrix ); this.renderer.worldMatrix.multiply( this.renderer.view.viewMatrix ); this.textShader.sendWorldMatrix(this.renderer.worldMatrix); // Unbind text shader this.textShader.unbind(); // Text line updated this.needUpdate = false; } // Render text line this.renderer.textLineRenderer.setShader(this.lineShader); this.renderer.textLineRenderer.setTexture(this.lineTexture); this.renderer.textLineRenderer.setAlpha(this.alpha); this.renderer.textLineRenderer.setSizeVec2(this.size); this.renderer.textLineRenderer.setPositionVec2(this.position); this.renderer.textLineRenderer.setAngle(this.angle); this.renderer.textLineRenderer.render(); } else { // Bind text shader this.textShader.bind(); // Send shader uniforms this.textShader.sendUniformVec3(this.colorUniform, this.color); this.textShader.sendUniform(this.alphaUniform, this.alpha); this.textShader.sendUniform(this.smoothUniform, this.smooth); this.textShader.sendUniformVec2( this.uvSizeUniform, this.uvSize ); // Bind texture this.texture.bind(); // Bind VBO this.renderer.vertexBuffer.bind(); // Render text for (i = 0; i < this.textLength; ++i) { // Get current character charCode = this.text.charCodeAt(i)-32; if (charCode < 0) { charCode = 31; } if (charCode > 94) { charCode = 31; } charX = Math.floor(charCode%16); charY = Math.floor(charCode/16); if (charX <= 0) { charX = 0; } if (charX >= 15) { charX = 15; } if (charY <= 0) { charY = 0; } if (charY >= 5) { charY = 5; } // Set text model matrix this.modelMatrix.setIdentity(); this.modelMatrix.translateVec2(this.position); this.modelMatrix.translateX( (WOSDefaultPxTextXOffset*this.charsize.vec[0]*i)- (WOSDefaultPxTextXOffset*this.charsize.vec[0]*0.18) ); this.modelMatrix.scaleVec2(this.charsize); this.vecmat.setMatrix(this.modelMatrix); this.uvOffset.vec[0] = charX*WOSDefaultPxTextUVWidth; this.uvOffset.vec[1] = charY*WOSDefaultPxTextUVHeight; // Update shader uniforms this.textShader.sendModelVecmat(this.vecmat); this.textShader.sendUniformVec2( this.uvOffsetUniform, this.uvOffset ); // Render VBO this.renderer.vertexBuffer.render(this.textShader); } // Unbind VBO this.renderer.vertexBuffer.unbind(); // Unbind texture this.texture.unbind(); // Unbind text shader this.textShader.unbind(); } } };
OpenHacksGovid/Govid
my-app/src/components/Map/States/IL.js
import React from 'react'; class IL extends React.Component { render() { return ( <path onClick={() => this.props.onClick()} className={this.props.className} id="IL" data-name="Illinois" data-id="IL" d="m 661.43403,198.18521 -0.19413,0.48531 3.6884,2.32952 1.16476,2.32951 3.88252,3.6884 -0.0971,3.10602 -2.13539,6.11498 -4.85316,3.49427 -4.36784,0.87357 -0.87357,5.04728 1.45595,0.67944 -1.45595,9.90044 -3.59133,2.23245 0.67944,3.78546 -0.87357,0.38825 0,0 -0.7765,4.27078 3.10602,8.63862 11.06519,9.31806 0.97063,4.4649 2.13539,2.23245 6.98855,-0.38825 -1.26182,6.50323 -0.48532,6.98855 4.17372,3.3972 6.60029,2.9119 3.49427,2.71777 1.94126,5.53259 -1.06769,2.03833 6.89148,5.62966 0.29119,0.0971 -0.58238,-0.58238 1.94126,-4.56196 7.47386,2.03832 1.8442,-2.13539 -1.45594,-4.27077 6.11497,-3.59134 -1.65007,-2.32951 1.45595,-3.30015 0,-0.29119 -0.38826,-0.0971 0.0971,-8.63862 2.13539,-1.55301 3.68839,-8.63862 -0.7765,-3.78546 -2.42658,-4.56196 1.35888,-5.14435 -6.79441,-47.85212 -0.97064,-1.06769 -2.52364,-5.72673 -2.03832,-2.13539 -0.87357,-5.62966 0,-0.19412 -13.10352,1.8442 -7.86211,0.97063 -21.15976,2.42658 0,0 z" /> ); } } export default IL;
mauriziokovacic/ACME
ACME/utility/dense2sparse.py
<filename>ACME/utility/dense2sparse.py from .issparse import * from .SparseTensor import * def dense2sparse(A): """ Given a tensor, it returns is sparse representation Parameters ---------- A : Tensor a tensor Returns ------- SparseTensor a sparse tensor """ if issparse(A): return A s = list(A.shape) i = torch.nonzero(A) v = A[tuple(i.t())] return SparseTensor(size=s, indices=i, values=v)
s4/core
src/main/java/io/s4/util/MetricsName.java
/* * Copyright (c) 2010 Yahoo! Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. See accompanying LICENSE file. */ package io.s4.util; public enum MetricsName { // metrics event name S4_APP_METRICS("S4::S4AppMetrics"), S4_EVENT_METRICS("S4::S4EventMetrics"), S4_CORE_METRICS( "S4::S4CoreMetrics"), // metrics name low_level_listener_msg_in_ct("lll_in"), low_level_listener_msg_drop_ct( "lll_dr"), low_level_listener_qsz("lll_qsz"), low_level_listener_badmsg_ct( "lll_bad"), // exception can't be caught generic_listener_msg_in_ct("gl_in"), pecontainer_ev_dq_ct("pec_dq"), pecontainer_ev_nq_ct( "pec_nq"), pecontainer_msg_drop_ct("pec_dr"), pecontainer_qsz( "pec_qsz"), pecontainer_qsz_w("pec_qsz_w"), pecontainer_ev_process_ct( "pec_pr"), pecontainer_pe_ct("pec_pe"), pecontainer_ev_err_ct( "pec_err"), // exception can't be caught pecontainer_exec_elapse_time("pec_exec_t"), low_level_emitter_msg_out_ct( "lle_out"), low_level_emitter_out_err_ct("lle_err"), low_level_emitter_qsz( "lle_qsz"), s4_core_exit_ct("s4_ex_ct"), s4_core_free_mem("s4_fmem"), pe_join_ev_ct( "pe_j_ct"), pe_error_count("pe_err"); private final String eventShortName; private MetricsName(String eventShortName) { this.eventShortName = eventShortName; } public String toString() { return eventShortName; } public static void main(String[] args) { System.out.println(generic_listener_msg_in_ct.toString()); } }
oci-pronghorn/GreenLightning-API
HTTPClient/src/main/java/com/ociweb/oe/greenlightning/api/server/HTTPServer.java
package com.ociweb.oe.greenlightning.api.server; import com.ociweb.gl.api.Builder; import com.ociweb.gl.api.GreenApp; import com.ociweb.gl.api.GreenRuntime; import com.ociweb.pronghorn.network.HTTPServerConfig; import com.ociweb.pronghorn.util.AppendableProxy; import com.ociweb.pronghorn.util.Appendables; public class HTTPServer implements GreenApp { //private byte[] cookieHeader = HTTPHeaderDefaults.COOKIE.rootBytes(); //private int emptyResponseRouteId; private int smallResponseRouteId; //private int largeResponseRouteId; //private int splitResponseRouteId; private int shutdownRouteId; private AppendableProxy console; private final String host; private long keyFieldId; public HTTPServer(String host, Appendable console) { this.host = host; this.console = Appendables.proxy(console); } public HTTPServer(Appendable console) { this.host = null; this.console = Appendables.proxy(console); } @Override public void declareConfiguration(Builder c) { HTTPServerConfig conf = c.useHTTP1xServer(8088) .setHost(host) .useInsecureServer() .setConcurrentChannelsPerDecryptUnit(4) .setConcurrentChannelsPerEncryptUnit(4); //emptyResponseRouteId = c.registerRoute("/testpageA?arg=#{myarg}", cookieHeader); smallResponseRouteId = c.defineRoute().path("/testpageB").routeId(); //largeResponseRouteId = c.registerRoute("/testpageC", cookieHeader); //splitResponseRouteId = c.registerRoute("/testpageD"); //only do in test mode... //in production it is a bad idea to let clients turn off server. shutdownRouteId = c.defineRoute().path("/shutdown?key=${key}").routeId(); keyFieldId = c.lookupFieldByName(shutdownRouteId, "key"); } @Override public void declareBehavior(GreenRuntime runtime) { //runtime.addRestListener(new RestBehaviorEmptyResponse(runtime, "myarg", console)) // .includeRoutes(emptyResponseRouteId); runtime.addRestListener(new RestBehaviorSmallResponse(runtime, console)) .includeRoutes(smallResponseRouteId); // runtime.addRestListener(new RestBehaviorLargeResponse(runtime, console)) // .includeRoutes(largeResponseRouteId); // runtime.addRestListener(new RestBehaviorHandoff(runtime, "responder")) // .includeRoutes(splitResponseRouteId); //runtime.addPubSubListener(new RestBehaviorHandoffResponder(runtime, console)) // .addSubscription("responder"); //splitResponseRouteId runtime.addRestListener(new ShutdownRestListener(runtime, keyFieldId)) .includeRoutes(shutdownRouteId); //NOTE .includeAllRoutes() can be used to write a behavior taking all routes } }
ameshkov/homebrew-core
Formula/vcsh.rb
class Vcsh < Formula desc "Config manager based on git" homepage "https://github.com/RichiH/vcsh" url "https://github.com/RichiH/vcsh/archive/v1.20151229-1.tar.gz" version "1.20151229-1" sha256 "7682a517eaf88a86ea5e38ad81707800e965375eaff8b5cfd882e210fe2fef71" license "GPL-2.0" bottle :unneeded def install bin.install "vcsh" man1.install "vcsh.1" zsh_completion.install "_vcsh" end test do assert_match /Initialized empty/, shell_output("#{bin}/vcsh init test").strip end end
gowsp/yapi-restdocs
src/main/java/io/github/gowsp/util/TagUtil.java
package io.github.gowsp.util; import com.thoughtworks.qdox.model.JavaMethod; public abstract class TagUtil { public static String paramDesc(JavaMethod method, String paramName) { return method.getTagsByName("param").stream() .filter(d -> d.getValue().split("\\s")[0].equals(paramName)) .findFirst() .map(d -> d.getValue().replaceFirst(paramName, "").trim()) .orElse(paramName); } }
iplo/Chain
net/spdy/hpack_decoder.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/spdy/hpack_decoder.h" #include "base/basictypes.h" #include "net/spdy/hpack_constants.h" #include "net/spdy/hpack_output_stream.h" namespace net { using base::StringPiece; HpackDecoder::HpackDecoder(uint32 max_string_literal_size) : max_string_literal_size_(max_string_literal_size) {} HpackDecoder::~HpackDecoder() {} bool HpackDecoder::DecodeHeaderSet(StringPiece input, HpackHeaderPairVector* header_list) { HpackInputStream input_stream(max_string_literal_size_, input); while (input_stream.HasMoreData()) { // May add to |header_list|. if (!ProcessNextHeaderRepresentation(&input_stream, header_list)) return false; } // After processing opcodes, emit everything in the reference set // that hasn't already been emitted. for (size_t i = 1; i <= context_.GetMutableEntryCount(); ++i) { if (context_.IsReferencedAt(i) && (context_.GetTouchCountAt(i) == HpackEncodingContext::kUntouched)) { header_list->push_back( HpackHeaderPair(context_.GetNameAt(i).as_string(), context_.GetValueAt(i).as_string())); } context_.ClearTouchesAt(i); } return true; } bool HpackDecoder::ProcessNextHeaderRepresentation( HpackInputStream* input_stream, HpackHeaderPairVector* header_list) { // Touches are used below to track which headers have been emitted. // Implements 4.2. Indexed Header Field Representation. if (input_stream->MatchPrefixAndConsume(kIndexedOpcode)) { uint32 index_or_zero = 0; if (!input_stream->DecodeNextUint32(&index_or_zero)) return false; if (index_or_zero > context_.GetEntryCount()) return false; bool emitted = false; if (index_or_zero > 0) { uint32 index = index_or_zero; // The index will be put into the reference set. if (!context_.IsReferencedAt(index)) { header_list->push_back( HpackHeaderPair(context_.GetNameAt(index).as_string(), context_.GetValueAt(index).as_string())); emitted = true; } } uint32 new_index = 0; std::vector<uint32> removed_referenced_indices; context_.ProcessIndexedHeader( index_or_zero, &new_index, &removed_referenced_indices); if (emitted && new_index > 0) context_.AddTouchesAt(new_index, 0); return true; } // Implements 4.3.1. Literal Header Field without Indexing. if (input_stream->MatchPrefixAndConsume(kLiteralNoIndexOpcode)) { StringPiece name; if (!DecodeNextName(input_stream, &name)) return false; StringPiece value; if (!DecodeNextValue(input_stream, &value)) return false; header_list->push_back( HpackHeaderPair(name.as_string(), value.as_string())); return true; } // Implements 4.3.2. Literal Header Field with Incremental Indexing. if (input_stream->MatchPrefixAndConsume(kLiteralIncrementalIndexOpcode)) { StringPiece name; if (!DecodeNextName(input_stream, &name)) return false; StringPiece value; if (!DecodeNextValue(input_stream, &value)) return false; header_list->push_back( HpackHeaderPair(name.as_string(), value.as_string())); uint32 new_index = 0; std::vector<uint32> removed_referenced_indices; context_.ProcessLiteralHeaderWithIncrementalIndexing( name, value, &new_index, &removed_referenced_indices); if (new_index > 0) context_.AddTouchesAt(new_index, 0); return true; } return false; } bool HpackDecoder::DecodeNextName( HpackInputStream* input_stream, StringPiece* next_name) { uint32 index_or_zero = 0; if (!input_stream->DecodeNextUint32(&index_or_zero)) return false; if (index_or_zero == 0) return input_stream->DecodeNextStringLiteral(next_name); uint32 index = index_or_zero; if (index > context_.GetEntryCount()) return false; *next_name = context_.GetNameAt(index_or_zero); return true; } bool HpackDecoder::DecodeNextValue( HpackInputStream* input_stream, StringPiece* next_name) { return input_stream->DecodeNextStringLiteral(next_name); } } // namespace net
DallasC/Temporal
grpc-clients/orchestrator.go
package clients import ( "fmt" "github.com/RTradeLtd/config/v2" "github.com/RTradeLtd/grpc/dialer" nexus "github.com/RTradeLtd/grpc/nexus" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) // IPFSOrchestratorClient is a lighweight container for the orchestrator's // gRPC API client type IPFSOrchestratorClient struct { nexus.ServiceClient conn *grpc.ClientConn } // NewOcrhestratorClient instantiates a new orchestrator API client func NewOcrhestratorClient(opts config.Nexus) (*IPFSOrchestratorClient, error) { c := &IPFSOrchestratorClient{} // set up parameters for core conn dialOpts := make([]grpc.DialOption, 0) if opts.TLS.CertPath != "" { creds, err := credentials.NewClientTLSFromFile(opts.TLS.CertPath, "") if err != nil { return nil, fmt.Errorf("could not load tls cert: %s", err) } dialOpts = append(dialOpts, grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(dialer.NewCredentials(opts.Key, true))) } else { dialOpts = append(dialOpts, grpc.WithInsecure(), grpc.WithPerRPCCredentials(dialer.NewCredentials(opts.Key, false))) } // connect to orchestrator var err error c.conn, err = grpc.Dial(opts.Host+":"+opts.Port, dialOpts...) if err != nil { return nil, fmt.Errorf("failed to connect to core service: %s", err.Error()) } c.ServiceClient = nexus.NewServiceClient(c.conn) return c, nil } // Close shuts down the client's gRPC connection func (i *IPFSOrchestratorClient) Close() { i.conn.Close() }
Tovaniks/snazarov
chapter2_001/src/main/java/ru/job4j/generic/UserStore.java
package ru.job4j.generic; /** * Class UserStore. * * @author <NAME> * @version $Id$ * @since 2018.04.09 */ public class UserStore extends AbstractStore<User> implements Store<User> { }
LouisRenWeiWei/JXADF
Source/JxADF/JxPlatform/src/main/java/com/jxtech/tag/link/Link.java
package com.jxtech.tag.link; import com.jxtech.jbo.JboIFace; import com.jxtech.tag.comm.JxBaseUIBean; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.views.annotations.StrutsTag; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author <EMAIL> * @date 2014.11 * */ @StrutsTag(name = "Link", tldTagClass = "com.jxtech.tag.appbar.LinkTag", description = "Link") public class Link extends JxBaseUIBean { private String urlDataAttribute; private String txtDataAttribute; private Object urlDataValue; private Object txtDataValue; private String txt; private String url; private String title; private String titleDataAttribute; private String titleDataValue; private String mxevent; private JboIFace jbo; public Link(ValueStack stack, HttpServletRequest request, HttpServletResponse response) { super(stack, request, response); } @Override protected String getDefaultTemplate() { return "link/" + getRenderer() + "link-close"; } @Override public String getDefaultOpenTemplate() { return "link/" + getRenderer() + "link"; } @Override public void evaluateParams() { super.evaluateParams(); if (urlDataAttribute != null) { addParameter("urlDataAttribute", findString(urlDataAttribute).toUpperCase()); } if (txtDataAttribute != null) { addParameter("txtDataAttribute", findString(txtDataAttribute).toUpperCase()); } if (titleDataAttribute != null) { addParameter("titleDataAttribute", findString(titleDataAttribute).toUpperCase()); } if (jbo != null) { addParameter("jbo", jbo); } addParameter("urlDataValue", urlDataValue); addParameter("txtDataValue", txtDataValue); addParameter("titleDataValue", titleDataValue); if (url != null) { addParameter("url", findString(url)); } if (txt != null) { addParameter("txt", findString(txt)); } if (title != null) { addParameter("title", findString(title)); } if (mxevent != null) { addParameter("mxevent", findString(mxevent)); } } public void setJbo(JboIFace jbo) { this.jbo = jbo; } public void setUrlDataAttribute(String urlDataAttribute) { this.urlDataAttribute = urlDataAttribute; } public void setTxtDataAttribute(String txtDataAttribute) { this.txtDataAttribute = txtDataAttribute; } public void setUrlDataValue(Object urlDataValue) { this.urlDataValue = urlDataValue; } public void setTxtDataValue(Object txtDataValue) { this.txtDataValue = txtDataValue; } public void setMxevent(String mxevent) { this.mxevent = mxevent; } public void setTitle(String title) { this.title = title; } public void setTitleDataAttribute(String titleDataAttribute) { this.titleDataAttribute = titleDataAttribute; } public void setTxt(String txt) { this.txt = txt; } public void setUrl(String url) { this.url = url; } }
go-aah/aah
essentials/go_test.go
// Copyright (c) <NAME>. (https://github.com/jeevatkm) // Source code and usage is governed by a MIT style // license that can be found in the LICENSE file. package ess import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) func TestLookExecutable(t *testing.T) { assert.Equal(t, true, LookExecutable("go")) assert.Equal(t, false, LookExecutable("mygo")) } func TestIsImportPathExists(t *testing.T) { assert.Equal(t, false, IsImportPathExists("aahframe.work/unknown")) } func TestGoPath(t *testing.T) { gopath, err := GoPath() assert.Nil(t, err, "") t.Logf("gopath: %v", gopath) } func TestIsInGoRoot(t *testing.T) { goroot := os.Getenv("GOROOT") if IsStrEmpty(goroot) { goroot = "/usr/local/go" } // assert.Equal(t, true, IsInGoRoot(filepath.Join(goroot, "src/github.com/jeevatkm/myapp")) IsInGoRoot(filepath.Join(goroot, "src/github.com/jeevatkm/myapp")) assert.Equal(t, false, IsInGoRoot("/usr/local/")) }
Eduardo-Ortega102/specnaz
src/examples/specnaz-custom-dsl-example/src/main/java/org/specnaz/examples/custom_dsl/given_when_then/SpecnazGivenWhenThen.java
package org.specnaz.examples.custom_dsl.given_when_then; import org.specnaz.core.CoreDslBuilder; import org.specnaz.core.SpecnazCoreDsl; import java.util.function.Consumer; public interface SpecnazGivenWhenThen extends SpecnazCoreDsl { default void given(String description, Consumer<GivenBuilder> closure) { SpecnazCoreDsl.super.specification("Given " + description, coreDslBuilder -> { closure.accept(new GivenWhenThenBuilder(coreDslBuilder)); }); } /** * Do not call! Use {@link SpecnazGivenWhenThen#given} instead. */ @Override @Deprecated default void specification(String description, Consumer<CoreDslBuilder> specClosure) { throw new UnsupportedOperationException("Use given(description, closure) instead"); } }
demacedius/BurgWar
src/ClientLib/Systems/PostFrameCallbackSystem.cpp
// Copyright (C) 2020 <NAME> // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE #include <ClientLib/Systems/PostFrameCallbackSystem.hpp> #include <CoreLib/LogSystem/Logger.hpp> #include <CoreLib/Components/ScriptComponent.hpp> #include <ClientLib/LocalMatch.hpp> namespace bw { PostFrameCallbackSystem::PostFrameCallbackSystem() { Requires<ScriptComponent>(); SetMaximumUpdateRate(0); SetUpdateOrder(100); } void PostFrameCallbackSystem::OnEntityRemoved(Ndk::Entity* entity) { m_frameUpdateEntities.Remove(entity); } void PostFrameCallbackSystem::OnEntityValidation(Ndk::Entity* entity, bool /*justAdded*/) { auto& scriptComponent = entity->GetComponent<ScriptComponent>(); if (scriptComponent.HasCallbacks(ElementEvent::PostFrame)) m_frameUpdateEntities.Insert(entity); else m_frameUpdateEntities.Remove(entity); } void PostFrameCallbackSystem::OnUpdate(float /*elapsedTime*/) { for (const Ndk::EntityHandle& entity : m_frameUpdateEntities) { auto& scriptComponent = entity->GetComponent<ScriptComponent>(); scriptComponent.ExecuteCallback<ElementEvent::PostFrame>(); } } Ndk::SystemIndex PostFrameCallbackSystem::systemIndex; }
V1vek/chronos-timetracker
app/renderer/sagas/worklogTypes.js
import * as eff from 'redux-saga/effects'; import * as Api from 'api'; import { infoLog, } from './ui'; export function* getWorklogTypes() { try { const { payload } = yield eff.call(Api.fetchWorklogTypes); yield eff.call(infoLog, 'got worklog types', payload); } catch (err) { console.log(err); } }
dev-rbatista/Tutorial_Local_Smoke_Test_with_Docker_Containers-Gradle
src/test/java/switchtwentytwenty/project/datamodel/domainjpa/PersonJPATest.java
package switchtwentytwenty.project.datamodel.domainjpa; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; class PersonJPATest { String id = "<EMAIL>"; PersonIDJPA personIDJPA = new PersonIDJPA(id); PersonIDJPA personIDJPAOther = new PersonIDJPA("<EMAIL>"); String name = "TonyZe"; String birthdate = "23/12/1992"; Integer vat = 999999999; FamilyIDJPA familyIDJPA = new FamilyIDJPA(UUID.randomUUID().toString()); @Test @Tag("US010") void getNameTest() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String expected = "TonyZe"; String result = personJPA.getName(); assertEquals(expected,result); } @Test @Tag("US010") void getBirthdateTest() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String expected = "23/12/1992"; String result = personJPA.getBirthdate(); assertEquals(expected,result); } @Test @Tag("US010") void getVatTest() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); int expected = 999999999; int result = personJPA.getVat(); assertEquals(expected,result); } @Test @Tag("US010") void getFamilyidTest() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String expected = familyIDJPA.toString(); String result = personJPA.getFamilyid().toString(); assertEquals(expected,result); } @Test @Tag("US010") void getIdTest() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String expected = personIDJPA.toString(); String result = personJPA.getId().toString(); assertEquals(expected,result); } @Test @Tag("US010") void testEqualsSameObject() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); PersonJPA personJPATwo = personJPAOne; assertEquals(personJPAOne,personJPATwo); } @Test @Tag("US010") void testEqualsEqualPersonJPA() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); PersonJPA personJPATwo = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); assertEquals(personJPAOne,personJPATwo); assertNotSame(personJPAOne,personJPATwo); } @Test @Tag("US010") void testEqualsDifferentObjectTypes() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); assertNotEquals(personJPAOne,personIDJPA); } @Test @Tag("US010") void testEqualsDifferentFromNull() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String nullString = null; assertNotEquals(personJPAOne,nullString); } @Test @Tag("US010") void testEqualsDifferentPersonJPA() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); PersonJPA personJPATwo = new PersonJPA(personIDJPAOther, "otherPerson", birthdate, vat, familyIDJPA); assertNotEquals(personJPAOne,personJPATwo); } @Test @Tag("US010") void testHashCodeEqualPersonJPA() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); PersonJPA personJPATwo = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); assertEquals(personJPAOne.hashCode(),personJPATwo.hashCode()); assertNotSame(personJPAOne,personJPATwo); } @Test @Tag("US010") void testHashCodeDifferentPersonJPA() { PersonJPA personJPAOne = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); PersonJPA personJPATwo = new PersonJPA(personIDJPAOther, "otherPerson", birthdate, vat, familyIDJPA); assertNotEquals(personJPAOne.hashCode(),personJPATwo.hashCode()); } @Test @Tag("US010") void testToString() { PersonJPA personJPA = new PersonJPA(personIDJPA, name, birthdate, vat, familyIDJPA); String expected = "PersonJPA{" + "id=" + "<EMAIL>" + '}'; String result = personJPA.toString(); assertEquals(expected, result); assertNotSame(expected, result); } }
zhoutao0712/rtn11pb1
release/src-ra-4300/linux/linux-2.6.36.x/arch/arm/plat-mxc/include/mach/mxc_ehci.h
<filename>release/src-ra-4300/linux/linux-2.6.36.x/arch/arm/plat-mxc/include/mach/mxc_ehci.h #ifndef __INCLUDE_ASM_ARCH_MXC_EHCI_H #define __INCLUDE_ASM_ARCH_MXC_EHCI_H /* values for portsc field */ #define MXC_EHCI_PHY_LOW_POWER_SUSPEND (1 << 23) #define MXC_EHCI_FORCE_FS (1 << 24) #define MXC_EHCI_UTMI_8BIT (0 << 28) #define MXC_EHCI_UTMI_16BIT (1 << 28) #define MXC_EHCI_SERIAL (1 << 29) #define MXC_EHCI_MODE_UTMI (0 << 30) #define MXC_EHCI_MODE_PHILIPS (1 << 30) #define MXC_EHCI_MODE_ULPI (2 << 30) #define MXC_EHCI_MODE_SERIAL (3 << 30) /* values for flags field */ #define MXC_EHCI_INTERFACE_DIFF_UNI (0 << 0) #define MXC_EHCI_INTERFACE_DIFF_BI (1 << 0) #define MXC_EHCI_INTERFACE_SINGLE_UNI (2 << 0) #define MXC_EHCI_INTERFACE_SINGLE_BI (3 << 0) #define MXC_EHCI_INTERFACE_MASK (0xf) #define MXC_EHCI_POWER_PINS_ENABLED (1 << 5) #define MXC_EHCI_TTL_ENABLED (1 << 6) #define MXC_EHCI_INTERNAL_PHY (1 << 7) #define MXC_EHCI_IPPUE_DOWN (1 << 8) #define MXC_EHCI_IPPUE_UP (1 << 9) #define MXC_EHCI_WAKEUP_ENABLED (1 << 10) #define MXC_EHCI_ITC_NO_THRESHOLD (1 << 11) #define MXC_USBCTRL_OFFSET 0 #define MXC_USB_PHY_CTR_FUNC_OFFSET 0x8 #define MXC_USB_PHY_CTR_FUNC2_OFFSET 0xc #define MX5_USBOTHER_REGS_OFFSET 0x800 /* USB_PHY_CTRL_FUNC2*/ #define MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK 0x3 #define MX5_USB_UTMI_PHYCTRL1_PLLDIV_SHIFT 0 struct mxc_usbh_platform_data { int (*init)(struct platform_device *pdev); int (*exit)(struct platform_device *pdev); unsigned int portsc; unsigned int flags; struct otg_transceiver *otg; }; int mxc_initialize_usb_hw(int port, unsigned int flags); #endif /* __INCLUDE_ASM_ARCH_MXC_EHCI_H */
bernease/cli-demo-1
src/whylogs/tests/unit/core/statistics/test_schematracker.py
<reponame>bernease/cli-demo-1<filename>src/whylogs/tests/unit/core/statistics/test_schematracker.py from whylabs.logs.proto import InferredType from whylabs.logs.core.statistics import SchemaTracker Type = InferredType.Type def multiple_track(tracker, counts: dict): for item, count in counts.items(): for i in range(count): tracker.track(item) def test_track_nothing_should_return_unknown(): tracker = SchemaTracker() inferred_type = tracker.infer_type() assert inferred_type.type == Type.UNKNOWN assert inferred_type.ratio == 0.0 def test_track_datatype_counts(): type_counts = { Type.INTEGRAL: 2, Type.STRING: 2, Type.FRACTIONAL: 2, Type.BOOLEAN: 2, Type.UNKNOWN: 2 } tracker = SchemaTracker() multiple_track(tracker, type_counts) assert type_counts[Type.INTEGRAL] == tracker.get_count(Type.INTEGRAL) assert type_counts[Type.STRING] == tracker.get_count(Type.STRING) assert type_counts[Type.FRACTIONAL] == tracker.get_count(Type.FRACTIONAL) assert type_counts[Type.BOOLEAN] == tracker.get_count(Type.BOOLEAN) assert type_counts[Type.UNKNOWN] == tracker.get_count(Type.UNKNOWN) def test_70percent_string(): tracker = SchemaTracker() type_counts = { Type.INTEGRAL: 29, Type.STRING: 71 } multiple_track(tracker, type_counts) assert tracker.infer_type().type == Type.STRING def test_majority_float(): tracker = SchemaTracker() type_counts = { Type.FRACTIONAL: 50, Type.STRING: 30, Type.UNKNOWN: 20, } multiple_track(tracker, type_counts) assert tracker.infer_type().type == Type.FRACTIONAL def test_majority_int(): tracker = SchemaTracker() type_counts = { Type.INTEGRAL: 50, Type.STRING: 30, Type.UNKNOWN: 20, } multiple_track(tracker, type_counts) assert tracker.infer_type().type == Type.INTEGRAL def test_float_and_int(): tracker = SchemaTracker() multiple_track(tracker, counts={ Type.INTEGRAL: 50, Type.FRACTIONAL: 50, Type.STRING: 10, }) assert tracker.infer_type().type == Type.FRACTIONAL def test_all_types_equal_coerced_to_string(): tracker = SchemaTracker() multiple_track(tracker, counts={ Type.INTEGRAL: 20, Type.FRACTIONAL: 29, Type.STRING: 50, }) assert tracker.infer_type().type == Type.STRING def test_serialization_roundtrip(): tracker = SchemaTracker() type_count = { Type.INTEGRAL: 10, Type.STRING: 100, } multiple_track(tracker, type_count) roundtrip = SchemaTracker.from_protobuf(tracker.to_protobuf()) assert tracker.to_protobuf() == roundtrip.to_protobuf() assert roundtrip.get_count(Type.INTEGRAL) == 10 assert roundtrip.get_count(Type.STRING) == 100 def test_summary(): tracker = SchemaTracker() type_counts = { Type.INTEGRAL: 3, Type.STRING: 4, Type.FRACTIONAL: 5, Type.BOOLEAN: 6, Type.UNKNOWN: 1, } tracker = SchemaTracker() multiple_track(tracker, type_counts) summary = tracker.to_summary() c = summary.type_counts assert c['INTEGRAL'] == type_counts[Type.INTEGRAL] assert c['STRING'] == type_counts[Type.STRING] assert c['FRACTIONAL'] == type_counts[Type.FRACTIONAL] assert c['BOOLEAN'] == type_counts[Type.BOOLEAN] assert c['UNKNOWN'] == type_counts[Type.UNKNOWN] assert summary.inferred_type.type == tracker.infer_type().type def test_merge_total_counts_match(): x1 = SchemaTracker() multiple_track(x1, { Type.INTEGRAL: 10, Type.FRACTIONAL: 10, Type.BOOLEAN: 10, Type.UNKNOWN: 10 }) x2 = SchemaTracker() multiple_track(x2, { Type.INTEGRAL: 20, Type.FRACTIONAL: 20, Type.BOOLEAN: 20, Type.UNKNOWN: 20 }) merged = x1.merge(x2) assert merged.get_count(Type.INTEGRAL) == 30 assert merged.get_count(Type.FRACTIONAL) == 30 assert merged.get_count(Type.BOOLEAN) == 30 assert merged.get_count(Type.UNKNOWN) == 30 # Make sure we can serialize round trip SchemaTracker.from_protobuf(merged.to_protobuf())
MarioIvancic/mcu-libc
src/string/strcspn.c
#include <string.h> /* The strcspn() function shall compute the length (in bytes) of the maximum initial segment of the string pointed to by s1 which consists entirely of bytes not from the string pointed to by s2. The strcspn() function shall return the length of the computed segment of the string pointed to by s1; no return value is reserved to indicate an error. */ size_t strcspn(const char *s1, const char *s2) { const char *s = s1; const char *c; while (*s1) { for (c = s2; *c; c++) { if (*s1 == *c) break; } if (*c) break; s1++; } return s1 - s; }
dns/Cafu
Libs/Models/Loader_mdl_hl2_vvd.hpp
/* Cafu Engine, http://www.cafu.de/ Copyright (c) <NAME> and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_HL2_MDL_VVD_VERTEX_DATA_HPP_INCLUDED #define CAFU_HL2_MDL_VVD_VERTEX_DATA_HPP_INCLUDED #include "Math3D/Vector3.hpp" #include "Templates/Array.hpp" #if defined(_WIN32) && _MSC_VER<1600 #include "pstdint.h" // Paul Hsieh's portable implementation of the stdint.h header. #else #include <stdint.h> #endif #define HL2mdl_MAX_NUM_BONES_PER_VERT 3 #define HL2mdl_MAX_NUM_LODS 8 namespace HL2mdl { typedef float Vector2D[2]; struct Vector4D { float v[4]; }; struct StudioBoneWeightT { float Weight[HL2mdl_MAX_NUM_BONES_PER_VERT]; uint8_t Bone[HL2mdl_MAX_NUM_BONES_PER_VERT]; uint8_t NumBones; }; struct StudioVertexT { StudioBoneWeightT BoneWeights; Vector3fT Pos; Vector3fT Normal; Vector2D TexCoord; std::ostream& print(std::ostream& os, const char* indent) const; }; struct FixupT { uint32_t LOD; ///< Can use this to skip higher LODs. uint32_t StartVertex; ///< Begin of the "fixup strip". uint32_t NumVertices; ///< Length of the "fixup strip". std::ostream& print(std::ostream& os, const char* indent) const; }; /// This is the header of a VVD vertex data file. class VertexHeaderT { public: static const uint32_t FILE_ID_IDSV; ///< The ID of a VVD file with normal vertex data. static const uint32_t FILE_ID_IDCV; ///< The ID of a VVD file with compressed ("thin") vertex data. static const uint32_t FILE_VERSION; ///< The currently supported file format version. uint32_t ID; ///< Must be FILE_ID_IDSV or FILE_ID_IDCV. uint32_t Version; ///< Must be FILE_VERSION. uint32_t Checksum; ///< Must match the checksum in StudioHeaderT. uint32_t NumLODs; ///< The number of available detail levels. uint32_t NumLODVertices[HL2mdl_MAX_NUM_LODS]; ///< The cumulated number of vertices for the given and all lower detail levels. uint32_t NumFixups; ///< The number of FixupT instances. uint32_t FixupsOffset; ///< The byte offset to the first fixup, relative to "this". uint32_t VerticesOffset; ///< The byte offset to the first vertex, relative to "this". uint32_t TangentsOffset; ///< The byte offset to the first tangent, relative to "this". public: StudioVertexT* GetVertices() const { return ID == FILE_ID_IDSV && VerticesOffset != 0 ? (StudioVertexT*)((uint8_t*)this + VerticesOffset) : NULL; } Vector4D* GetTangents() const { return ID == FILE_ID_IDSV && TangentsOffset != 0 ? (Vector4D*)((uint8_t*)this + TangentsOffset) : NULL; } const FixupT* GetFixups() const { return (FixupT*)((uint8_t*)this + FixupsOffset); } void FixData() { // This is not efficient, but this is just model importer code anyway. ArrayT<StudioVertexT> NewVertices; ArrayT<Vector4D> NewTangents; for (uint32_t i = 0; i < NumFixups; i++) { const FixupT& Fixup = GetFixups()[i]; if (GetVertices()) { const StudioVertexT* Vertices = GetVertices() + Fixup.StartVertex; for (uint32_t VertNr = 0; VertNr < Fixup.NumVertices; VertNr++) NewVertices.PushBack(Vertices[VertNr]); } if (GetTangents()) { const Vector4D* Tangents = GetTangents() + Fixup.StartVertex; for (uint32_t VertNr = 0; VertNr < Fixup.NumVertices; VertNr++) NewTangents.PushBack(Tangents[VertNr]); } } for (uint32_t VertNr = 0; VertNr < NewVertices.Size(); VertNr++) GetVertices()[VertNr] = NewVertices[VertNr]; for (uint32_t VertNr = 0; VertNr < NewTangents.Size(); VertNr++) GetTangents()[VertNr] = NewTangents[VertNr]; NumFixups = 0; } std::ostream& print(std::ostream& os, const char* indent) const; }; } #endif
ssachtleben/herowar
app/dao/NewsDAO.java
package dao; import controllers.Application; import models.entity.News; import models.entity.User; import play.db.jpa.JPA; public class NewsDAO extends BaseDAO<Long, News> { public NewsDAO() { super(Long.class, News.class); } public void merge(News news, News news2) { news.setHeadline(news2.getHeadline()); news.setText(news2.getText()); } public News create(String headline, String text) { return create(headline, text, Application.getLocalUser()); } public News create(String headline, String text, User author) { final News news = new News(); news.setHeadline(headline); news.setText(text); news.setAuthor(author); JPA.em().persist(news); return news; } public long getNewsCount() { return this.getBaseCount(); } }
w3aponx/orientdb
object/src/main/java/com/orientechnologies/orient/object/serialization/OObjectSerializerManager.java
/* * * Copyright 2012 <NAME> (molino.luca--AT--gmail.com) * * 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.orientechnologies.orient.object.serialization; import com.orientechnologies.orient.core.db.OUserObject2RecordHandler; import com.orientechnologies.orient.core.db.object.ODatabaseObject; import com.orientechnologies.orient.core.entity.OEntityManager; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.serializer.object.OObjectSerializerHelperInterface; /** * @author luca.molino * */ public class OObjectSerializerManager implements OObjectSerializerHelperInterface { private static final OObjectSerializerManager instance = new OObjectSerializerManager(); public ODocument toStream(Object iPojo, ODocument iRecord, OEntityManager iEntityManager, OClass schemaClass, OUserObject2RecordHandler iObj2RecHandler, ODatabaseObject db, boolean iSaveOnlyDirty) { return OObjectSerializerHelper.toStream(iPojo, iRecord, iEntityManager, schemaClass, iObj2RecHandler, db, iSaveOnlyDirty); } public String getDocumentBoundField(Class<?> iClass) { return OObjectSerializerHelper.getDocumentBoundField(iClass); } public Object getFieldValue(Object iPojo, String iProperty) { return OObjectSerializerHelper.getFieldValue(iPojo, iProperty); } public void invokeCallback(Object iPojo, ODocument iDocument, Class<?> iAnnotation) { OObjectSerializerHelper.invokeCallback(iPojo, iDocument, iAnnotation); } public static OObjectSerializerManager getInstance() { return instance; } }
tonxxd/strapi
packages/strapi-plugin-upload/admin/src/containers/HomePage/index.js
/* * * HomePage * */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { injectIntl } from 'react-intl'; import { bindActionCreators, compose } from 'redux'; import { isEmpty } from 'lodash'; import { Header } from '@buffetjs/custom'; import { getQueryParameters, ContainerFluid, InputSearch, PageFooter, GlobalContext, } from 'strapi-helper-plugin'; import pluginId from '../../pluginId'; import { HomePageContextProvider } from '../../contexts/HomePage'; // Plugin's component import EntriesNumber from '../../components/EntriesNumber'; import List from '../../components/List'; import PluginInputFile from '../../components/PluginInputFile'; import { EntriesWrapper, Wrapper } from './components'; /* eslint-disable */ import { changeParams, deleteData, getData, onDrop, onSearch, setParams, } from './actions'; import selectHomePage from './selectors'; import reducer from './reducer'; import saga from './saga'; export class HomePage extends React.Component { static contextType = GlobalContext; UNSAFE_componentWillMount() { if (!isEmpty(this.props.location.search)) { const _page = parseInt(this.getURLParams('_page'), 10); const _limit = parseInt(this.getURLParams('_limit'), 10); const _sort = this.getURLParams('_sort'); this.props.setParams({ _limit, _page, _sort }); } } componentDidMount() { this.props.getData(); } UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.deleteSuccess !== this.props.deleteSuccess) { this.props.getData(); } if (nextProps.location.search !== this.props.location.search) { this.props.getData(); } } getURLParams = type => getQueryParameters(this.props.location.search, type); changeSort = name => { const { params: { _limit, _page }, } = this.props; const target = { name: 'params._sort', value: name, }; const search = `_page=${_page}&_limit=${_limit}&_sort=${name}`; this.props.changeParams({ target }); this.props.history.push({ pathname: this.props.history.pathname, search, }); }; handleChangeParams = e => { const { history, params } = this.props; const search = e.target.name === 'params._limit' ? `_page=${params._page}&_limit=${e.target.value}&_sort=${params._sort}` : `_page=${e.target.value}&_limit=${params._limit}&_sort=${params._sort}`; this.props.history.push({ pathname: history.pathname, search, }); this.props.changeParams(e); }; renderInputSearch = () => ( <InputSearch autoFocus name="search" onChange={this.props.onSearch} placeholder="upload.HomePage.InputSearch.placeholder" style={{ marginTop: '-11px' }} value={this.props.search} /> ); render() { const { formatMessage } = this.context; return ( <HomePageContextProvider deleteData={this.props.deleteData}> <ContainerFluid className="container-fluid"> <Wrapper> <Header actions={[ { Component: this.renderInputSearch, key: 'input-search', }, ]} title={{ label: formatMessage({ id: 'upload.HomePage.title', }), }} content={formatMessage({ id: 'upload.HomePage.description', })} /> </Wrapper> <PluginInputFile name="files" onDrop={this.props.onDrop} showLoader={this.props.uploadFilesLoading} /> <EntriesWrapper> <div> {/* NOTE: Prepare for bulk actions} <InputSelect name="bulkAction" onChange={() => console.log('change')} selectOptions={[{ value: 'select all'}]} style={{ minWidth: '200px', height: '32px', marginTop: '-8px' }} /> */} </div> <EntriesNumber number={this.props.entriesNumber} /> </EntriesWrapper> <List data={this.props.uploadedFiles} changeSort={this.changeSort} sort={this.props.params._sort} /> <div className="col-md-12"> <PageFooter count={this.props.entriesNumber} context={{ emitEvent: () => {} }} onChangeParams={this.handleChangeParams} params={this.props.params} /> </div> </ContainerFluid> </HomePageContextProvider> ); } } HomePage.defaultProps = { params: { _limit: 10, _page: 1, _sort: 'updatedAt', }, uploadedFiles: [], }; HomePage.propTypes = { changeParams: PropTypes.func.isRequired, deleteData: PropTypes.func.isRequired, deleteSuccess: PropTypes.bool.isRequired, entriesNumber: PropTypes.number.isRequired, getData: PropTypes.func.isRequired, history: PropTypes.object.isRequired, location: PropTypes.object.isRequired, onDrop: PropTypes.func.isRequired, onSearch: PropTypes.func.isRequired, params: PropTypes.object, search: PropTypes.string.isRequired, setParams: PropTypes.func.isRequired, uploadedFiles: PropTypes.arrayOf(PropTypes.object), uploadFilesLoading: PropTypes.bool.isRequired, }; function mapDispatchToProps(dispatch) { return bindActionCreators( { changeParams, deleteData, getData, onDrop, onSearch, setParams, }, dispatch ); } const mapStateToProps = selectHomePage(); const withConnect = connect(mapStateToProps, mapDispatchToProps); const withReducer = strapi.injectReducer({ key: 'homePage', reducer, pluginId, }); const withSaga = strapi.injectSaga({ key: 'homePage', saga, pluginId }); export default compose( withReducer, withSaga, withConnect )(injectIntl(HomePage));
potherca-contrib/origin-community-cartridges
openshift-origin-cartridge-jbossrhq-4/template/deployments/rhq.ear/coregui.war/WEB-INF/classes/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java
<reponame>potherca-contrib/origin-community-cartridges<filename>openshift-origin-cartridge-jbossrhq-4/template/deployments/rhq.ear/coregui.war/WEB-INF/classes/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java /* * RHQ Management Platform * Copyright (C) 2005-2010 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout; import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.content.InstalledPackageHistory; import org.rhq.core.domain.criteria.InstalledPackageHistoryCriteria; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.PortletConfigurationEditorComponent.Constant; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.groups.GroupPkgHistoryPortlet; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.summary.AbstractActivityView; import org.rhq.enterprise.gui.coregui.client.util.GwtRelativeDurationConverter; import org.rhq.enterprise.gui.coregui.client.util.Log; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; /**This portlet allows the end user to customize the Package History display * * @author <NAME> */ public class ResourcePkgHistoryPortlet extends GroupPkgHistoryPortlet { // A non-displayed, persisted identifier for the portlet public static final String KEY = "ResourcePackageHistory"; // A default displayed, persisted name for the portlet public static final String NAME = MSG.view_portlet_defaultName_resource_pkg_hisory(); private int resourceId = -1; public ResourcePkgHistoryPortlet(String locatorId, int resourceId) { super(locatorId, -1); this.resourceId = resourceId; } public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory(); public final Portlet getInstance(String locatorId, EntityContext context) { if (EntityContext.Type.Resource != context.getType()) { throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); } return new ResourcePkgHistoryPortlet(locatorId, context.getResourceId()); } } /** Fetches recent package history information and updates the DynamicForm instance with details. */ @Override protected void getRecentPkgHistory() { final DashboardPortlet storedPortlet = this.portletWindow.getStoredPortlet(); final Configuration portletConfig = storedPortlet.getConfiguration(); final int resourceId = this.resourceId; InstalledPackageHistoryCriteria criteria = new InstalledPackageHistoryCriteria(); PageControl pc = new PageControl(); //result count String currentSetting = portletConfig.getSimpleValue(Constant.RESULT_COUNT, Constant.RESULT_COUNT_DEFAULT); if (currentSetting.trim().isEmpty()) { pc.setPageSize(Integer.valueOf(Constant.RESULT_COUNT_DEFAULT)); } else { pc.setPageSize(Integer.valueOf(currentSetting)); } criteria.setPageControl(pc); criteria.addFilterResourceId(resourceId); criteria.addSortStatus(PageOrdering.DESC); GWTServiceLookup.getContentService().findInstalledPackageHistoryByCriteria(criteria, new AsyncCallback<PageList<InstalledPackageHistory>>() { @Override public void onFailure(Throwable caught) { Log.debug("Error retrieving installed package history for group [" + resourceId + "]:" + caught.getMessage()); currentlyLoading = false; } @Override public void onSuccess(PageList<InstalledPackageHistory> result) { VLayout column = new VLayout(); column.setHeight(10); if (!result.isEmpty()) { for (InstalledPackageHistory history : result) { LocatableDynamicForm row = new LocatableDynamicForm(recentPkgHistoryContent .extendLocatorId(history.getPackageVersion().getFileName() + history.getPackageVersion().getVersion())); row.setNumCols(3); StaticTextItem iconItem = AbstractActivityView.newTextItemIcon( "subsystems/content/Package_16.png", null); String title = history.getPackageVersion().getFileName() + ":"; String destination = "/rhq/resource/content/audit-trail-item.xhtml?id=" + resourceId + "&selectedHistoryId=" + history.getId(); //spinder 4/27/11: diabling links as they point into portal.war content pages // LinkItem link = AbstractActivityView.newLinkItem(title, destination); StaticTextItem link = AbstractActivityView.newTextItem(title); StaticTextItem time = AbstractActivityView.newTextItem(GwtRelativeDurationConverter .format(history.getTimestamp())); row.setItems(iconItem, link, time); column.addMember(row); } // //insert see more link // LocatableDynamicForm row = new LocatableDynamicForm(recentPkgHistoryContent // .extendLocatorId("PkgHistoryContentSeeMore")); // String destination = "/rhq/resource/content/audit-trail-item.xhtml?id=" + groupId; // addSeeMoreLink(row, destination, column); } else { LocatableDynamicForm row = AbstractActivityView.createEmptyDisplayRow(recentPkgHistoryContent .extendLocatorId("None"), MSG.view_portlet_results_empty()); column.addMember(row); } //cleanup for (Canvas child : recentPkgHistoryContent.getChildren()) { child.destroy(); } recentPkgHistoryContent.addChild(column); recentPkgHistoryContent.markForRedraw(); currentlyLoading = false; markForRedraw(); } }); } }
dhutchison/maven-archetype
maven-archetype-plugin/src/main/java/org/apache/maven/archetype/ui/creation/DefaultArchetypeCreationConfigurator.java
package org.apache.maven.archetype.ui.creation; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.apache.maven.archetype.common.ArchetypeFilesResolver; import org.apache.maven.archetype.common.Constants; import org.apache.maven.archetype.exception.ArchetypeNotConfigured; import org.apache.maven.archetype.exception.ArchetypeNotDefined; import org.apache.maven.archetype.exception.TemplateCreationException; import org.apache.maven.archetype.ui.ArchetypeConfiguration; import org.apache.maven.archetype.ui.ArchetypeDefinition; import org.apache.maven.archetype.ui.ArchetypeFactory; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.components.interactivity.PrompterException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.util.StringUtils; @Component( role = ArchetypeCreationConfigurator.class, hint = "default" ) public class DefaultArchetypeCreationConfigurator extends AbstractLogEnabled implements ArchetypeCreationConfigurator { @Requirement private ArchetypeCreationQueryer archetypeCreationQueryer; @Requirement private ArchetypeFactory archetypeFactory; @Requirement private ArchetypeFilesResolver archetypeFilesResolver; @Override public Properties configureArchetypeCreation( MavenProject project, Boolean interactiveMode, Properties commandLineProperties, File propertyFile, List<String> languages ) throws IOException, ArchetypeNotDefined, ArchetypeNotConfigured, PrompterException, TemplateCreationException { Properties properties = initialiseArchetypeProperties( commandLineProperties, propertyFile ); ArchetypeDefinition archetypeDefinition = archetypeFactory.createArchetypeDefinition( properties ); if ( !archetypeDefinition.isDefined() ) { archetypeDefinition = defineDefaultArchetype( project, properties ); } ArchetypeConfiguration archetypeConfiguration = archetypeFactory.createArchetypeConfiguration( project, archetypeDefinition, properties ); String resolvedPackage = archetypeFilesResolver.resolvePackage( project.getBasedir(), languages ); if ( !archetypeConfiguration.isConfigured() ) { archetypeConfiguration = defineDefaultConfiguration( project, archetypeDefinition, resolvedPackage, properties ); } if ( interactiveMode.booleanValue() ) { getLogger().debug( "Entering interactive mode" ); boolean confirmed = false; while ( !confirmed ) { if ( !archetypeDefinition.isDefined() )// <editor-fold text="..."> { getLogger().debug( "Archetype is yet not defined" ); if ( !archetypeDefinition.isGroupDefined() ) { getLogger().debug( "Asking for archetype's groupId" ); archetypeDefinition.setGroupId( archetypeCreationQueryer.getArchetypeGroupId( project.getGroupId() ) ); } if ( !archetypeDefinition.isArtifactDefined() ) { getLogger().debug( "Asking for archetype's artifactId" ); archetypeDefinition.setArtifactId( archetypeCreationQueryer.getArchetypeArtifactId( project.getArtifactId() + Constants.ARCHETYPE_SUFFIX ) ); } if ( !archetypeDefinition.isVersionDefined() ) { getLogger().debug( "Asking for archetype's version" ); archetypeDefinition.setVersion( archetypeCreationQueryer.getArchetypeVersion( project.getVersion() ) ); } archetypeFactory.updateArchetypeConfiguration( archetypeConfiguration, archetypeDefinition ); } // </editor-fold> if ( !archetypeConfiguration.isConfigured() )// <editor-fold text="..."> { getLogger().debug( "Archetype is not yet configured" ); if ( !archetypeConfiguration.isConfigured( Constants.GROUP_ID ) ) { getLogger().debug( "Asking for project's groupId" ); archetypeConfiguration.setProperty( Constants.GROUP_ID, archetypeCreationQueryer.getGroupId( archetypeConfiguration.getDefaultValue( Constants.GROUP_ID ) ) ); } if ( !archetypeConfiguration.isConfigured( Constants.ARTIFACT_ID ) ) { getLogger().debug( "Asking for project's artifactId" ); archetypeConfiguration.setProperty( Constants.ARTIFACT_ID, archetypeCreationQueryer.getArtifactId( archetypeConfiguration.getDefaultValue( Constants.ARTIFACT_ID ) ) ); } if ( !archetypeConfiguration.isConfigured( Constants.VERSION ) ) { getLogger().debug( "Asking for project's version" ); archetypeConfiguration.setProperty( Constants.VERSION, archetypeCreationQueryer.getVersion( archetypeConfiguration.getDefaultValue( Constants.VERSION ) ) ); } if ( !archetypeConfiguration.isConfigured( Constants.PACKAGE ) ) { getLogger().debug( "Asking for project's package" ); archetypeConfiguration.setProperty( Constants.PACKAGE, archetypeCreationQueryer.getPackage( StringUtils.isEmpty( resolvedPackage ) ? archetypeConfiguration.getDefaultValue( Constants.PACKAGE ) : resolvedPackage ) ); } } // </editor-fold> boolean stopAddingProperties = false; while ( !stopAddingProperties ) { getLogger().debug( "Asking for another required property" ); stopAddingProperties = !archetypeCreationQueryer.askAddAnotherProperty(); if ( !stopAddingProperties ) { getLogger().debug( "Asking for required property key" ); String propertyKey = archetypeCreationQueryer.askNewPropertyKey(); getLogger().debug( "Asking for required property value" ); String replacementValue = archetypeCreationQueryer.askReplacementValue( propertyKey, archetypeConfiguration.getDefaultValue( propertyKey ) ); archetypeConfiguration.setDefaultProperty( propertyKey, replacementValue ); archetypeConfiguration.setProperty( propertyKey, replacementValue ); } } getLogger().debug( "Asking for configuration confirmation" ); if ( archetypeCreationQueryer.confirmConfiguration( archetypeConfiguration ) ) { confirmed = true; } else { getLogger().debug( "Reseting archetype's definition and configuration" ); archetypeConfiguration.reset(); archetypeDefinition.reset(); } } // end while } else { getLogger().debug( "Entering batch mode" ); if ( !archetypeDefinition.isDefined() ) { throw new ArchetypeNotDefined( "The archetype is not defined" ); } else if ( !archetypeConfiguration.isConfigured() ) { throw new ArchetypeNotConfigured( "The archetype is not configured", null ); } } // end if return archetypeConfiguration.toProperties(); } private ArchetypeDefinition defineDefaultArchetype( MavenProject project, Properties properties ) { if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_GROUP_ID ) ) ) { properties.setProperty( Constants.ARCHETYPE_GROUP_ID, project.getGroupId() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_ARTIFACT_ID ) ) ) { properties.setProperty( Constants.ARCHETYPE_ARTIFACT_ID, project.getArtifactId() + Constants.ARCHETYPE_SUFFIX ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_VERSION ) ) ) { properties.setProperty( Constants.ARCHETYPE_VERSION, project.getVersion() ); } return archetypeFactory.createArchetypeDefinition( properties ); } private ArchetypeConfiguration defineDefaultConfiguration( MavenProject project, ArchetypeDefinition archetypeDefinition, String resolvedPackage, Properties properties ) { if ( StringUtils.isEmpty( properties.getProperty( Constants.GROUP_ID ) ) ) { getLogger().info( "Setting default groupId: " + project.getGroupId() ); properties.setProperty( Constants.GROUP_ID, project.getGroupId() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARTIFACT_ID ) ) ) { getLogger().info( "Setting default artifactId: " + project.getArtifactId() ); properties.setProperty( Constants.ARTIFACT_ID, project.getArtifactId() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.VERSION ) ) ) { getLogger().info( "Setting default version: " + project.getVersion() ); properties.setProperty( Constants.VERSION, project.getVersion() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_GROUP_ID ) ) ) { getLogger().info( "Setting default archetype's groupId: " + project.getGroupId() ); properties.setProperty( Constants.ARCHETYPE_GROUP_ID, project.getGroupId() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_ARTIFACT_ID ) ) ) { getLogger().info( "Setting default archetype's artifactId: " + project.getArtifactId() ); properties.setProperty( Constants.ARCHETYPE_ARTIFACT_ID, project.getArtifactId() + Constants.ARCHETYPE_SUFFIX ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.ARCHETYPE_VERSION ) ) ) { getLogger().info( "Setting default archetype's version: " + project.getVersion() ); properties.setProperty( Constants.ARCHETYPE_VERSION, project.getVersion() ); } if ( StringUtils.isEmpty( properties.getProperty( Constants.PACKAGE /*, properties.getProperty ( Constants.PACKAGE_NAME ) */ ) ) ) { if ( StringUtils.isEmpty( resolvedPackage ) ) { resolvedPackage = project.getGroupId(); } getLogger().info( "Setting default package: " + resolvedPackage ); /* properties.setProperty ( Constants.PACKAGE_NAME, resolvedPackage ); */ properties.setProperty( Constants.PACKAGE, resolvedPackage ); } return archetypeFactory.createArchetypeConfiguration( project, archetypeDefinition, properties ); } public void readProperties( Properties properties, File propertyFile ) throws IOException { getLogger().debug( "Reading property file " + propertyFile ); try ( InputStream is = new FileInputStream( propertyFile ) ) { properties.load( is ); getLogger().debug( "Read " + properties.size() + " properties" ); } } public void writeProperties( Properties properties, File propertyFile ) throws IOException { Properties storedProperties = new Properties(); try { readProperties( storedProperties, propertyFile ); } catch ( FileNotFoundException ex ) { getLogger().debug( "Property file not found. Creating a new one" ); } getLogger().debug( "Adding " + properties.size() + " properties" ); Iterator<?> propertiesIterator = properties.keySet().iterator(); while ( propertiesIterator.hasNext() ) { String propertyKey = (String) propertiesIterator.next(); storedProperties.setProperty( propertyKey, properties.getProperty( propertyKey ) ); } propertyFile.getParentFile().mkdirs(); if ( !propertyFile.exists() && !propertyFile.createNewFile() ) { getLogger().warn( "Could not create new file \"" + propertyFile.getPath() + "\" or the file already exists." ); } try ( OutputStream os = new FileOutputStream( propertyFile ) ) { storedProperties.store( os, "" ); getLogger().debug( "Stored " + storedProperties.size() + " properties" ); } } private Properties initialiseArchetypeProperties( Properties commandLineProperties, File propertyFile ) throws IOException { Properties properties = new Properties(); if ( propertyFile != null ) { try { readProperties( properties, propertyFile ); } catch ( FileNotFoundException ex ) { getLogger().debug( propertyFile.getName() + " does not exist" ); } } return properties; } }
welchbj/spotnet
frontend/app/serializers/playlist.js
import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ normalizePlaylistObject(playlist) { return { type: 'playlist', id: playlist.id, attributes: { description: ('description' in playlist) ? playlist.description : null, spotifyUrl: playlist.external_urls.spotify, numFollowers: ('followers' in playlist) ? playlist.followers.total : null, numTracks: ('tracks' in playlist) ? playlist.tracks.total : null, imageUrl: playlist.images.length > 0 ? playlist.images[0].url : null, name: playlist.name, ownerId: playlist.owner.id, spotifyUri: playlist.uri } }; }, normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) { // jshint ignore:line const numPlaylists = payload.total; let playlists = payload.items.map((item) => this.normalizePlaylistObject(item)); return { data: playlists, meta: { numPlaylists: numPlaylists } }; }, normalizeFindRecordResponse(store, primaryModelClass, payload, id, requestType) { // jshint ignore:line return { data: this.normalizePlaylistObject(payload) }; } });
hilmialyaz/Activiti
modules/org.milleni.dunning/src/main/java/org/milleni/dunning/ws/client/crmcontact/SmsSenderApplication.java
package org.milleni.dunning.ws.client.crmcontact; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SmsSenderApplication. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SmsSenderApplication"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="INVOICE_INFO"/> * &lt;enumeration value="INVOICE_NOTICE"/> * &lt;enumeration value="MANUEL"/> * &lt;enumeration value="OTOKK_INFO"/> * &lt;enumeration value="OTOKK_REMOVE_EXPIRED"/> * &lt;enumeration value="COMMITMENT_OFFER"/> * &lt;enumeration value="SUBSCRIBER_PROCESSES"/> * &lt;enumeration value="MILLENICRM"/> * &lt;enumeration value="ONLINE_SERVICES"/> * &lt;enumeration value="DOPINGWEB"/> * &lt;enumeration value="AUTOJOBS"/> * &lt;enumeration value="SFA"/> * &lt;enumeration value="REQUEST_MANAGEMENT"/> * &lt;enumeration value="INTERACTIVE_SMS"/> * &lt;enumeration value="DUNNING"/> * &lt;enumeration value="BILLING"/> * &lt;enumeration value="CRM-THK-CHURN"/> * &lt;enumeration value="REPORTING"/> * &lt;enumeration value="ACS"/> * &lt;enumeration value="NETWORK_DSL"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "SmsSenderApplication", namespace = "http://milleni.com/Common/Notification") @XmlEnum public enum SmsSenderApplication { INVOICE_INFO("INVOICE_INFO"), INVOICE_NOTICE("INVOICE_NOTICE"), MANUEL("MANUEL"), OTOKK_INFO("OTOKK_INFO"), OTOKK_REMOVE_EXPIRED("OTOKK_REMOVE_EXPIRED"), COMMITMENT_OFFER("COMMITMENT_OFFER"), SUBSCRIBER_PROCESSES("SUBSCRIBER_PROCESSES"), MILLENICRM("MILLENICRM"), ONLINE_SERVICES("ONLINE_SERVICES"), DOPINGWEB("DOPINGWEB"), AUTOJOBS("AUTOJOBS"), SFA("SFA"), REQUEST_MANAGEMENT("REQUEST_MANAGEMENT"), INTERACTIVE_SMS("INTERACTIVE_SMS"), DUNNING("DUNNING"), BILLING("BILLING"), @XmlEnumValue("CRM-THK-CHURN") CRM_THK_CHURN("CRM-THK-CHURN"), REPORTING("REPORTING"), ACS("ACS"), NETWORK_DSL("NETWORK_DSL"); private final String value; SmsSenderApplication(String v) { value = v; } public String value() { return value; } public static SmsSenderApplication fromValue(String v) { for (SmsSenderApplication c: SmsSenderApplication.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
spatialcurrent/go-dfl
pkg/dfl/Like.go
<filename>pkg/dfl/Like.go // ================================================================= // // Copyright (C) 2019 Spatial Current, Inc. - All Rights Reserved // Released as open source under the MIT License. See LICENSE file. // // ================================================================= package dfl import ( "fmt" "github.com/pkg/errors" ) // Like is a BinaryOperator that evaluates the SQL standard like expression. // It is similar to the ILike BinaryOperator but is case sensitive. // The parameters must be of type string. // The right parameter may have "%" characters that are interpreted as (.*) in a regular expression test. type Like struct { *BinaryOperator } func (l Like) Dfl(quotes []string, pretty bool, tabs int) string { return l.BinaryOperator.Dfl("like", quotes, pretty, tabs) } // Sql returns the SQL representation of this node as a string func (l Like) Sql(pretty bool, tabs int) string { return l.BinaryOperator.Sql("LIKE", pretty, tabs) } func (l Like) Map() map[string]interface{} { return l.BinaryOperator.Map("like", l.Left, l.Right) } func (l Like) Compile() Node { left := l.Left.Compile() right := l.Right.Compile() return Like{&BinaryOperator{Left: left, Right: right}} } func (l Like) Evaluate(vars map[string]interface{}, ctx interface{}, funcs FunctionMap, quotes []string) (map[string]interface{}, interface{}, error) { vars, lv, err := l.Left.Evaluate(vars, ctx, funcs, quotes) if err != nil { return vars, false, err } vars, rv, err := l.Right.Evaluate(vars, ctx, funcs, quotes) if err != nil { return vars, false, err } match, err := CompareStrings(fmt.Sprint(lv), fmt.Sprint(rv)) if err != nil { return vars, false, errors.Wrap(err, ErrorEvaluate{Node: l, Quotes: quotes}.Error()) } return vars, match, nil }
willianfonseca/presto
presto-tests/src/test/java/com/facebook/presto/server/TestAsyncPageTransportServlet.java
<reponame>willianfonseca/presto /* * 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.facebook.presto.server; import com.facebook.presto.execution.TaskId; import com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId; import org.testng.annotations.Test; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestAsyncPageTransportServlet { class TestServlet extends AsyncPageTransportServlet { TaskId taskId; OutputBufferId bufferId; String requestURI; long token; void parse(String uri) throws IOException { parseURI(uri, null, null); } @Override protected void processRequest( String requestURI, TaskId taskId, OutputBufferId bufferId, long token, HttpServletRequest request, HttpServletResponse response) { this.requestURI = requestURI; this.taskId = taskId; this.bufferId = bufferId; this.token = token; } @Override protected void reportFailure(HttpServletResponse response, String message) { throw new IllegalArgumentException(message); } } private TestServlet parse(String str) { TestServlet servlet = new TestServlet(); try { servlet.parse(str); } catch (IOException e) { fail(e.getMessage()); } return servlet; } @Test public void testParsing() { TestServlet servlet = parse("/v1/task/async/1.2.3.4/results/456/789"); assertEquals("1.2.3.4", servlet.taskId.toString()); assertEquals("456", servlet.bufferId.toString()); assertEquals(789, servlet.token); } @Test (expectedExceptions = { IllegalArgumentException.class }) public void testParseTooFewElements() { parse("/v1/task/async/1.2.3.4/results/456"); } @Test (expectedExceptions = { IllegalArgumentException.class }) public void testParseTooManyElements() { parse("/v1/task/async/1.2.3.4/results/456/789/foo"); } }
eclarizio/catalog-ui
src/smart-components/order/order-detail/order-lifecycle.js
import React from 'react'; import { Redirect, useRouteMatch } from 'react-router-dom'; import { useSelector } from 'react-redux'; import ExternalLinkAlt from '@patternfly/react-icons/dist/js/icons/external-link-alt-icon'; import useQuery from '../../../utilities/use-query'; import { ORDER_ROUTE } from '../../../constants/routes'; import ordersMessages from '../../../messages/orders.messages'; import { Card, CardBody } from '@patternfly/react-core'; import useFormatMessage from '../../../utilities/use-format-message'; const OrderLifecycle = () => { const formatMessage = useFormatMessage(); const [, search] = useQuery([]); const { url } = useRouteMatch(ORDER_ROUTE); const orderDetailData = useSelector( ({ orderReducer: { orderDetail } }) => orderDetail || {} ); const { order, orderItem } = orderDetailData; if (order.state !== 'Completed' && order.state !== 'Ordered') { return ( <Redirect to={{ pathname: url, search }} /> ); } return ( <Card> <CardBody> <a href={orderItem.external_url} target="_blank" rel="noopener noreferrer" > {formatMessage(ordersMessages.lifecycleLink)} &nbsp; <ExternalLinkAlt /> </a> </CardBody> </Card> ); }; export default OrderLifecycle;
afeng11/tomato-arm
release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/staging/ti-st/bt_drv.h
/* * Texas Instrument's Bluetooth Driver For Shared Transport. * * Bluetooth Driver acts as interface between HCI CORE and * TI Shared Transport Layer. * * Copyright (C) 2009 Texas Instruments * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef _BT_DRV_H #define _BT_DRV_H /* Bluetooth Driver Version */ #define VERSION "1.0" /* Defines number of seconds to wait for reg completion * callback getting called from ST (in case,registration * with ST returns PENDING status) */ #define BT_REGISTER_TIMEOUT msecs_to_jiffies(6000) /* 6 sec */ /* BT driver's local status */ #define BT_DRV_RUNNING 0 #define BT_ST_REGISTERED 1 /* BT driver operation structure */ struct hci_st { /* hci device pointer which binds to bt driver */ struct hci_dev *hdev; /* used locally,to maintain various BT driver status */ unsigned long flags; /* to hold ST registration callback status */ char streg_cbdata; /* write function pointer of ST driver */ long (*st_write) (struct sk_buff *); /* Wait on comepletion handler needed to synchronize * hci_st_open() and hci_st_registration_completion_cb() * functions.*/ struct completion wait_for_btdrv_reg_completion; }; #endif
zhiqwang/mmdeploy
configs/mmdet/detection/detection_tensorrt-int8_dynamic-300x300-512x512.py
<reponame>zhiqwang/mmdeploy _base_ = ['../_base_/base_tensorrt-int8_dynamic-300x300-512x512.py']
gregwhitaker/gradle-localstack
gradle-localstack-plugin/src/main/java/com/nike/pdm/localstack/aws/dynamodb/DeleteDynamoDbTableTask.java
/** * Copyright 2020-present, Nike, Inc. * All rights reserved. * * This source code is licensed under the Apache-2.0 license found in * the LICENSE file in the root directory of this source tree. */ package com.nike.pdm.localstack.aws.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.model.DeleteTableResult; import com.nike.pdm.localstack.aws.AwsClientFactory; import com.nike.pdm.localstack.compose.LocalStackModule; import com.nike.pdm.localstack.core.ConsoleLogger; import com.nike.pdm.localstack.core.Retry; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.options.Option; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Task that deletes a DynamoDB table. */ public class DeleteDynamoDbTableTask extends DefaultTask { @Input private String tableName; public DeleteDynamoDbTableTask() { setMustRunAfter(Arrays.asList(LocalStackModule.START_LOCALSTACK_TASK_NAME)); } @TaskAction public void run() { final Set<Class<? extends Throwable>> expectedErrors = new HashSet<>(Arrays.asList(IllegalArgumentException.class)); Retry.execute(() -> { final AmazonDynamoDB amazonDynamoDB = AwsClientFactory.getInstance().dynamoDb(getProject()); final DynamoDBTaskUtil dynamoDBTaskUtil = new DynamoDBTaskUtil(getProject()); ConsoleLogger.log("Deleting DynamoDB table: %s", tableName); if (!dynamoDBTaskUtil.tableExists(tableName)) { throw new IllegalArgumentException("Table does not exist: " + tableName); } DeleteTableResult deleteTableResult = amazonDynamoDB.deleteTable(tableName); ConsoleLogger.log("Deleted DynamoDB table: %s", tableName); return null; }, expectedErrors); } @Internal @Override public String getGroup() { return DynamoDbModule.GROUP_NAME; } @Internal @Override public String getDescription() { return "Drop a DynamoDB table."; } /** * Gets the name of the table to delete. * * @return table name */ public String getTableName() { return tableName; } /** * Sets the name of the table to delete. * * @param tableName table name */ @Option(option = "tableName", description = "Name of the table to delete") public void setTableName(String tableName) { this.tableName = tableName; } }
smartgreeting/store-rpc
seckill/internal/logic/getseckilllistlogic.go
package logic import ( "context" "github.com/smartgreeting/store-rpc/seckill/internal/svc" "github.com/smartgreeting/store-rpc/seckill/seckill" "github.com/tal-tech/go-zero/core/logx" ) type GetSeckillListLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewGetSeckillListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSeckillListLogic { return &GetSeckillListLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } // 获取秒杀列表 func (l *GetSeckillListLogic) GetSeckillList(in *seckill.GetSeckillReq) (*seckill.GetSeckillListReply, error) { // todo: add your logic here and delete this line return &seckill.GetSeckillListReply{}, nil }
AJAkimana/yottaget-ui
src/components/addHouseSteps/CoverImage.js
<gh_stars>0 import React, { useState } from 'react'; import { DropzoneDialog } from 'material-ui-dropzone'; import { Button, GridList, GridListTile, makeStyles } from '@material-ui/core'; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', overflow: 'hidden', backgroundColor: theme.palette.background.paper, }, gridList: { width: '100%', }, })); export const CoverImage = ({ handleBack, handleNext, coverImage, setCoverImage, }) => { const [isOpen, setIsOpen] = useState(false); const classes = useStyles(); const saveImage = (images) => { setIsOpen(false); setCoverImage(images[0]); }; const coverSrc = coverImage ? URL.createObjectURL(coverImage) : ''; return ( <> <Button onClick={() => setIsOpen(true)}>Add cover image</Button> <DropzoneDialog open={isOpen} onSave={saveImage} acceptedFiles={['image/jpeg', 'image/png', 'image/bmp']} showPreviews={true} filesLimit={1} maxFileSize={5000000} onClose={() => setIsOpen(false)} /> <div className={classes.root}> <GridList cellHeight={160} className={classes.gridList} cols={4}> <GridListTile cols={1}> <img src={coverSrc} alt={`No house cover selected`} /> </GridListTile> </GridList> </div> <div style={{ display: 'flex', marginTop: 50, justifyContent: 'flex-end' }} > <Button variant='contained' color='default' onClick={handleBack} style={{ marginRight: 20 }} > Back </Button> <Button variant='contained' color='primary' onClick={handleNext} disabled={!coverImage} > Next </Button> </div> </> ); };
jinzhan/santd
src/input/index.js
<reponame>jinzhan/santd /** * @file input 入口文件 */ import Input from './input'; import Search from './input-search'; import TextArea from './textarea'; import Group from './group'; import Password from './input-password'; Input.Search = Search; Input.TextArea = TextArea; Input.Group = Group; Input.Password = Password; export default Input;
zadjii/nebula
messages/ClientGetCloudHostRequestMessage.py
<reponame>zadjii/nebula<filename>messages/ClientGetCloudHostRequestMessage.py # last generated 2016-12-30 20:11:44.027000 from messages import BaseMessage from msg_codes import CLIENT_GET_CLOUD_HOST_REQUEST as CLIENT_GET_CLOUD_HOST_REQUEST __author__ = 'Mike' class ClientGetCloudHostRequestMessage(BaseMessage): def __init__(self, sid=None, cloud_uname=None, cname=None): super(ClientGetCloudHostRequestMessage, self).__init__() self.type = CLIENT_GET_CLOUD_HOST_REQUEST self.sid = sid self.cloud_uname = cloud_uname self.cname = cname @staticmethod def deserialize(json_dict): msg = ClientGetCloudHostRequestMessage() msg.sid = json_dict['sid'] msg.cloud_uname = json_dict['cloud_uname'] msg.cname = json_dict['cname'] return msg
LarsP8/service-proxy
core/src/main/java/com/predic8/membrane/core/kubernetes/GenericJsonParser.java
/* Copyright 2009, 2021 predic8 GmbH, www.predic8.com 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.predic8.membrane.core.kubernetes; import com.predic8.membrane.annot.MCAttribute; import com.predic8.membrane.annot.MCChildElement; import com.predic8.membrane.core.config.spring.K8sHelperGeneratorAutoGenerated; import org.jose4j.json.internal.json_simple.JSONArray; import org.jose4j.json.internal.json_simple.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Creates and configures a router rule with json as described in {@link K8sHelperGeneratorAutoGenerated} */ public class GenericJsonParser { @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T parse(Class<T> clazz, JSONObject json) { T obj = null; try { obj = clazz.newInstance(); for (Object property : json.entrySet()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) property; Method setter = getSetter(clazz, entry.getKey()); Object toSetValue = entry.getValue(); if (isStructured(setter)) { if (isCollection(setter)) { JSONArray collection = new JSONArray((Collection) toSetValue); List<Object> coll = new ArrayList<>(); for (Object o : collection) { JSONObject jo = new JSONObject((Map) o); String key = (String) jo.keySet().stream() .findFirst() .orElseThrow(() -> new RuntimeException("Can't get key from " + jo)); JSONObject unwrapped = new JSONObject((Map<String, Object>) jo.get(key)); Class<?> child = K8sHelperGeneratorAutoGenerated.elementMapping.get(key); coll.add(parse(child, unwrapped)); } toSetValue = coll; } else { Class<?> childClass = K8sHelperGeneratorAutoGenerated.elementMapping.get(entry.getKey()); toSetValue = parse(childClass, new JSONObject((Map) json.get(entry.getKey()))); } } setSetter(obj, setter, toSetValue); } } catch (Throwable e) { e.printStackTrace(); } return obj; } private static <T> Method getSetter(Class<T> clazz, String key) { return Arrays.stream(clazz.getMethods()) .filter(GenericJsonParser::isSetter) .filter(method -> matchesJsonKey(method, key)) .findFirst() .orElseThrow(() -> new RuntimeException("Can't find method for key: " + key + " in " + clazz.getName())); } private static <T> void setSetter(T instance, Method method, Object value) throws InvocationTargetException, IllegalAccessException { method.invoke(instance, value); } private static boolean matchesJsonKey(Method method, String key) { return method.getName().substring(3).equalsIgnoreCase(key) || equalsAttributeName(method, key); } private static boolean isCollection(Method method) { return Arrays.asList(method.getParameterTypes()).contains(List.class); } private static boolean equalsAttributeName(Method method, String key) { if (!method.isAnnotationPresent(MCAttribute.class)) return false; return method.getAnnotation(MCAttribute.class).attributeName().equals(key); } private static boolean isStructured(Method method) { return method.isAnnotationPresent(MCChildElement.class); } private static boolean isSetter(Method method) { return method.getName().startsWith("set"); } }
petitg1987/urchinEngine
test/src/3d/scene/renderer3d/Renderer3dTest.h
#pragma once #include <cppunit/TestFixture.h> #include <cppunit/Test.h> #include <Urchin3dEngine.h> class Renderer3dTest : public CppUnit::TestFixture { public: static CppUnit::Test* suite(); void modelPreWarm(); private: std::unique_ptr<urchin::Model> buildModel(std::string, const std::string&, const urchin::Point3<float>&) const; };
jcoreio/chai-webdriverio-async
src/assertions/text.js
/** * NOTICE * This file has been modified from the source in * https://github.com/marcodejongh/chai-webdriverio */ import getElements from '../util/getElements' const text = (client, chai, utils, options) => { async function assertText(expected) { const negate = utils.flag(this, 'negate') const { getValueAndSelector } = utils.flag(this, 'chai-webdriverio-async') const [texts, selector] = await getValueAndSelector() const expectedStr = typeof expected === 'string' ? JSON.stringify(expected) : expected if (!texts.length) { throw new chai.AssertionError( negate ? `Expected element <${selector}> to not have text ${expectedStr}, but no matching elements were found` : `Expected element <${selector}> to have text ${expectedStr}, but no matching elements were found` ) } const filteredList = texts.filter(text => expected instanceof RegExp ? text.match(expected) : text === expected ) this.assert( filteredList.length > 0, `Expected element <${selector}> to have text ${expectedStr}, but only found: ${texts .map(t => JSON.stringify(t)) .join(', ')}`, `Expected element <${selector}> to not have text ${expectedStr}, but found: ${texts .map(t => JSON.stringify(t)) .join(', ')}` ) } assertText.chain = function chainText() { const obj = utils.flag(this, 'object') utils.flag(this, 'chai-webdriverio-async', { type: 'text', message: `elements' text for #{selector}`, getValueAndSelector: async () => { const [elements, selector] = await getElements(obj, client) return [await Promise.all(elements.map(e => e.getText())), selector] }, }) } return assertText } export default text
nobo728x/logbook
logbook-common/src/main/java/org/zalando/logbook/common/MediaTypeQuery.java
<reponame>nobo728x/logbook package org.zalando.logbook.common; import java.util.Arrays; import java.util.function.Predicate; import java.util.regex.Pattern; public final class MediaTypeQuery { private static final Pattern WILDCARD = Pattern.compile("\\*"); private MediaTypeQuery() { } public static Predicate<String> compile(final String query, final String... queries) { return Arrays.stream(queries) .map(MediaTypeQuery::compile) .reduce(compile(query), Predicate::or); } private static Predicate<String> compile(final String query) { final int slash = query.indexOf('/'); final int semicolon = query.indexOf(';'); final int end = semicolon == -1 ? query.length() : semicolon; final String type = query.substring(0, slash).trim(); final String subType = query.substring(slash + 1, end).trim(); final String first = PatternLike.toPattern(WILDCARD, type, ".*?"); final String second = PatternLike.toPattern(WILDCARD, subType, ".*?"); // TODO support real matching on parameters final Pattern pattern = Pattern.compile(first + '/' + second + "(;.*)?"); return input -> input != null && pattern.matcher(input).matches(); } }
wzp1985/sms
app/models/message.rb
class Message < ActiveRecord::Base include AASM extend ActiveSupport::Memoizable aasm_state :pending aasm_state :delivered aasm_initial_state :pending aasm_event :deliver do transitions :to => :delivered, :from => :pending, :guard => lambda { |m| m.send(:ensure_delivered) } end belongs_to :user belongs_to :gateway has_and_belongs_to_many :telephone_numbers validates_presence_of :content, :user, :recipients, :gateway validates_length_of :content, :maximum => 640 validate :acceptance_of_telephone_numbers before_validation :associate_telephone_numbers @@per_page = 8 cattr_reader :per_page attr_accessible :recipients, :content, :deliver_at default_scope :order => "created_at DESC" named_scope :awaiting, lambda { { :conditions => ["aasm_state = ? AND deliver_at < ?", "pending", Time.now.utc] } } def recipients=(recipients) @recipients = recipients.squeeze(" ").split(",").map(&:strip).delete_if(&:empty?).uniq.join(", ") end def recipients telephone_numbers.map(&:to_s) end protected def ensure_delivered return false unless valid? result = gateway.deliver(telephone_numbers, content) self.delivered_at = Time.now result end def acceptance_of_telephone_numbers if gateway telephone_numbers.each do |t| errors.add :recipient, "number #{t.number} is not allowed in chosen gateway" unless gateway.allow_number?(t.number) end end end def associate_telephone_numbers return if @recipients.nil? telephone_numbers.clear @recipients.split(", ").each { |r| telephone_numbers << user.telephone_numbers.find_or_initialize_by_recipient(r) } telephone_numbers.uniq! @recipients = nil end end
mohnstrudel/kosher
app/controllers/front/manufacturers_controller.rb
<filename>app/controllers/front/manufacturers_controller.rb class Front::ManufacturersController < FrontController def index objects = Manufacturer.top_level.order(created_at: :desc) item_amount = objects.count page_size = Rails.application.config.page_size @page = (params[:page] || 1).to_i @pages_total = item_amount / page_size if item_amount%page_size != 0 @pages_total += 1 end @manufacturers = objects.paginate(page: params[:page], per_page: page_size) end def show @manufacturer = Manufacturer.friendly.find(params[:id]) end end
jeleedict/pathpedia
src/main/java/kr/ac/knu/ml/pathinfo/repository/PathInfoAbbreviationRepository.java
<reponame>jeleedict/pathpedia<gh_stars>1-10 /******************************************************************************* * Copyright (c) 2011, 2014 Kyungpook National University and Contributors * * Contributor(s): - <NAME> *******************************************************************************/ package kr.ac.knu.ml.pathinfo.repository; import java.util.ArrayList; import kr.ac.knu.ml.pathinfo.unit.PathInfoAbbreviation; public class PathInfoAbbreviationRepository { private ArrayList<PathInfoAbbreviation> abbreviations; public <E> void constructRepository( ArrayList<E> abbreviations ) { this.abbreviations = new ArrayList<PathInfoAbbreviation>(); for ( E e : abbreviations ) { if ( e instanceof String[] ) { PathInfoAbbreviation pia = new PathInfoAbbreviation ( (String[]) e ); this.abbreviations.add( pia ); } else if ( e instanceof PathInfoAbbreviation ) { this.abbreviations.add( (PathInfoAbbreviation) e ); } } } public ArrayList<String> getNormalTerm( String abbr ) { ArrayList<String> normalTerms = new ArrayList<String>(); for ( PathInfoAbbreviation pia : abbreviations ) { if ( pia.getAbbr().equals( abbr ) ) { normalTerms.add( pia.getNormalTerm() ); } } return normalTerms; } public String getAbbr( String id ) { for ( PathInfoAbbreviation pia : abbreviations ) { if ( pia.getId().equals( id ) ) return pia.getAbbr(); } return null; } }
cquiroz/ocs
bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/seqcomp/SeqRepeatFlatObs.java
// Copyright 1997-2000 // Association for Universities for Research in Astronomy, Inc., // Observatory Control System, Gemini Telescopes Project. // See the file LICENSE for complete details. // // $Id: SeqRepeatFlatObs.java 18053 2009-02-20 20:16:23Z swalker $ // package edu.gemini.spModel.seqcomp; import edu.gemini.pot.sp.SPComponentType; import edu.gemini.spModel.obscomp.InstConstants; import edu.gemini.spModel.obsclass.ObsClass; /** * A simple "Flat" iterator that does a flat observe for X times * with coadds and exposure time. */ public class SeqRepeatFlatObs extends SeqRepeatCoaddExp implements ICoaddExpSeqComponent { /** * This iter component's SP type. */ public static final SPComponentType SP_TYPE = SPComponentType.OBSERVER_FLAT; public static final String OBSERVE_TYPE = InstConstants.DARK_OBSERVE_TYPE; // for serialization private static final long serialVersionUID = 1L; /** * Default constructor. */ public SeqRepeatFlatObs() { super(SP_TYPE, ObsClass.PARTNER_CAL); } /** * Return the observe type property for this seq comp. */ public String getObserveType() { return InstConstants.FLAT_OBSERVE_TYPE; } }
ajscholz/material-kit-pro
src/pages/ecommerce-page.js
<reponame>ajscholz/material-kit-pro<gh_stars>0 import React from "react" import EcommercePage from "views/EcommercePage/EcommercePage" export default () => <EcommercePage />
radekkozak/RxNetwork
rxnetwork/src/test/java/greyfox/rxnetwork/internal/strategy/internet/impl/WalledGardenInternetObservingStrategyTest.java
package greyfox.rxnetwork.internal.strategy.internet.impl; import greyfox.rxnetwork.internal.strategy.internet.InternetObservingStrategy; import greyfox.rxnetwork.internal.strategy.internet.error.InternetObservingStrategyException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import org.junit.Test; import static greyfox.rxnetwork.internal.strategy.internet.impl.WalledGardenInternetObservingStrategy.builder; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class WalledGardenInternetObservingStrategyTest extends EndpointInternetObservingStrategyTest { private static final WalledGardenInternetObservingStrategy.Builder NULL_BUILDER = null; // WalledGardenInternetStrategy uses HTTP Status-Code 204: No Content to validate connection private static final int VALID_SERVER_RESPONSE = HTTP_NO_CONTENT; @Test(expected = NullPointerException.class) public void shouldThrow_whenTryingToInstantiateWithNullBuilder() { new WalledGardenInternetObservingStrategy(NULL_BUILDER); } @Test public void shouldSubscribeCorrectly_whenCreatedFromDefaultFactory() { InternetObservingStrategy sut = WalledGardenInternetObservingStrategy.create(); sut.observe().test().assertSubscribed(); } @Test public void shouldSubscribeCorrectly_whenCreatedFromDetailedBuilder() { InternetObservingStrategy sut = detailedStrategyBuilder().build(); sut.observe().test().assertSubscribed(); } @Test public void shouldThrow_whenTryingToObserveInvalidEndpoint() { InternetObservingStrategy sut = builder().endpoint(INVALID_HOST).build(); assertThat(sut.observe().blockingFirst()).isFalse(); } @Test public void shouldReturnInternetConnectionIsTrue() throws IOException, InternetObservingStrategyException { WalledGardenInternetObservingStrategy sut = spy(detailedStrategyBuilder().build()); HttpURLConnection urlConnection = mock(HttpURLConnection.class); doReturn(VALID_SERVER_RESPONSE).when(urlConnection).getResponseCode(); doReturn(urlConnection).when(sut).buildUrlConnection(any(URL.class)); assertThat(sut.observe().blockingFirst()).isTrue(); } @Test public void shouldReturnInternetConnectionIsTrue_whenValidServerResponse() throws InterruptedException, IOException { setServerWithHttpStatusResponse(VALID_SERVER_RESPONSE); InternetObservingStrategy sut = buildStrategy(); assertThat(sut.observe().blockingFirst()).isTrue(); } @Test public void shouldLogError_whenProblemGettingResponseCode() throws IOException, InternetObservingStrategyException { WalledGardenInternetObservingStrategy sut = spy(detailedStrategyBuilder().build()); HttpURLConnection urlConnection = mock(HttpURLConnection.class); doThrow(IOException.class).when(urlConnection).getResponseCode(); doReturn(urlConnection).when(sut).buildUrlConnection(any(URL.class)); assertThat(sut.observe().blockingFirst()).isFalse(); verify(sut).onError(anyString(), any(Exception.class)); } @Test public void shouldReturnInternetConnectionIsFalse_whenInvalidServerResponse() throws IOException { setServerWithHttpStatusResponse(INVALID_SERVER_RESPONSE); InternetObservingStrategy sut = buildStrategy(); assertThat(sut.observe().blockingFirst()).isFalse(); } private WalledGardenInternetObservingStrategy.Builder detailedStrategyBuilder() { return builder().delay(VALID_DELAY).interval(VALID_INTERVAL).timeout(VALID_TIMEOUT_MS) .endpoint(VALID_ENDPOINT); } @Override protected EndpointInternetObservingStrategy.Builder strategyBuilder() { return builder(); } }
truthiswill/intellij-community
python/testData/resolve/KeywordArgument.py
<gh_stars>1-10 def foo(bar=True): pass foo(bar=False) # <ref>
kll5h/ShinetechOA
src/main/java/com/mossle/api/user/MockAccountAliasConverter.java
package com.mossle.api.user; public class MockAccountAliasConverter implements AccountAliasConverter { public String convertAlias(String alias) { return alias; } }
DarrenPaulWright/hord
tests/Schema/Schema.test.js
import displayValue from 'display-value'; import { clone, deepEqual } from 'object-agent'; import { assert, Enum } from 'type-enforcer'; import { Schema } from '../../index.js'; import Model from '../../src/Model.js'; import { schemaTestTypes } from '../helpers/testValues.js'; const parseName = (data) => { return data.name === 'function' ? 'function' : (data.name.length === 1 ? data.name : data.name.charAt(0).toUpperCase() + data.name.slice(1)); }; describe('Schema', () => { describe('.validate', () => { schemaTestTypes.forEach((data) => { data.true.forEach((datum) => { it(`should NOT return an error for a value that matches a ${data.name}`, () => { const item = { testKey: datum }; const schema = new Schema({ testKey: data.value }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it(`should NOT return an error for a value that matches a ${data.name} and isRequired=true`, () => { const item = { testKey: datum }; const schema = new Schema({ testKey: { type: data.value, isRequired: true } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it(`should return an error for a value of undefined when the type is ${data.name} and isRequired=true`, () => { const item = { testKey: undefined }; const schema = new Schema({ testKey: { type: data.value, isRequired: true } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'A value is required', path: 'testKey', value: undefined, item }]); }); it(`should NOT return an error for a value of undefined when the type is ${data.name} and isRequired=true and a default value is given`, () => { const item = { testKey: undefined }; const schema = new Schema({ testKey: { type: data.value, isRequired: true, default: data.true[0] } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it(`should NOT return an error for a value that matches a ${data.name} in a nested object`, () => { const item = { testKey: { testKey2: datum } }; const schema = new Schema({ testKey: { testKey2: data.value } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it(`should return an error for a key with a ${data.name} not in the schema`, () => { const item = { testKey: 'test string', testKey2: datum }; const schema = new Schema({ testKey: String }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Key found that isn\'t in the schema', path: 'testKey2', value: datum, item }]); }); it(`should NOT return an error for a ${data.name} in an array`, () => { const item = { testKey: [datum] }; const schema = new Schema({ testKey: [] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it(`should NOT return an error for a key that matches a ${data.name} in an object in an array`, () => { const item = { testKey: [{ testKey2: datum }] }; const schema = new Schema({ testKey: [{ testKey2: data.value }] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); }); data.false.forEach((datum) => { if (datum === undefined || deepEqual(datum, {})) { return; } it(`should return an error for a value of ${displayValue(datum)} that doesn't match a ${data.name}`, () => { const item = { testKey: datum }; const schema = new Schema({ testKey: data.value }); const errors = schema.validate(item); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey', value: datum, item }]); } }); it(`should return an error for a value of ${displayValue(datum)} that doesn\'t match a ${data.name} in a nested object`, () => { const item = { testKey: { testKey2: datum } }; const schema = new Schema({ testKey: { testKey2: data.value } }); const errors = schema.validate(item); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey.testKey2', value: datum, item }]); } }); it(`should return an error for a value of ${displayValue(datum)} that doesn\'t match a ${data.name} in an object in an array`, () => { const item = { testKey: [{ testKey2: datum }] }; const schema = new Schema({ testKey: [{ testKey2: data.value }] }); const errors = schema.validate(item); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey.0.testKey2', value: datum, item }]); } }); }); data.coerceTrue.forEach((datum) => { it(`should NOT return an error for a value that is coercable to ${data.name}`, () => { const item = { testKey: datum }; const schema = new Schema({ testKey: { type: data.value, coerce: true } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); }); data.coerceFalse.forEach((datum) => { if (datum === undefined || deepEqual(datum, {})) { return; } it(`should return an error for a value that is not coercable to ${data.name}`, () => { const item = { testKey: datum }; const schema = new Schema({ testKey: { type: data.value, coerce: true } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey', value: datum, item }]); }); }); }); it('should NOT mutate the item being validated', () => { const item = { testKey: [], testKey2: 'something' }; const clonedItem = clone(item); const schema = new Schema({ testKey: [], testKey2: String }); schema.validate(item); assert.equal(item, clonedItem); }); it('should NOT return an error for a key that matches an array', () => { const item = { testKey: [], testKey2: 'something' }; const schema = new Schema({ testKey: [], testKey2: String }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should NOT return an error for a key that matches null', () => { const item = { testKey: null }; const schema = new Schema({ testKey: null }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should NOT return an error for a key that matches String or null', () => { const item = { testKey: null }; const schema = new Schema({ testKey: [String, null] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a key that doesn\'t match an array', () => { const item = { testKey: 'inValid' }; const schema = new Schema({ testKey: [] }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey', value: 'inValid', item }]); }); it('should NOT return an error for a key that matches empty nested arrays', () => { const item = { testKey: [ ['test1', 'test2'], ['test3', 'test4', 'test5'] ] }; const schema = new Schema({ testKey: [ [] ] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a key that doesn\'t match empty nested arrays', () => { const item = { testKey: ['test1', 'test2'] }; const schema = new Schema({ testKey: [ [] ] }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.0', value: 'test1', item }, { error: 'Value should be a Array', path: 'testKey.1', value: 'test2', item }]); }); it('should NOT return errors for multiple items in an array', () => { const item = { testKey: ['test1', 'test2', 'test3'] }; const schema = new Schema({ testKey: [ [String] ] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a bad type amongst multiple items in an array', () => { const item = { testKey: ['test1', 3, 'test3'] }; const schema = new Schema({ testKey: [ [String] ] }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a String', path: 'testKey.1', value: 3, item }]); }); it('should NOT return an error for a good value when multiple types are given', () => { const item = { testKey: ['test1', 3, 'test3'] }; const schema = new Schema({ testKey: [ [String, Number] ] }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a bad value when multiple types are given', () => { const item = { testKey: ['test1', 3, 'test3', true] }; const schema = new Schema({ testKey: [ [String, Number] ] }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a String OR Value should be a Number', path: 'testKey.3', value: true, item }]); }); it('should NOT return an error for a key that matches a nested array', () => { const item = { testKey: { testKey2: [] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should NOT return an error for objects in an empty array', () => { const item = { testKey: { testKey2: [{ testKey3: 'test' }] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should NOT return an error for an empty array', () => { const item = { testKey: { testKey2: [] } }; const schema = new Schema({ testKey: { testKey2: [{ testKey3: String }] } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for an empty array that should be an object', () => { const item = { testKey: [] }; const schema = new Schema({ testKey: { testKey2: [{ testKey3: String }] } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Object', path: 'testKey', value: [], item }]); }); it('should NOT return an error for an empty array that can have strings', () => { const item = { testKey: [] }; const schema = new Schema({ testKey: { type: Array, content: String } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a key that doesn\'t match a nested array', () => { const item = { testKey: { testKey2: 'inValid' } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.testKey2', value: 'inValid', item }]); }); it('should NOT return an error for a key that matches a String in a nested array', () => { const item = { testKey: { testKey2: ['asdf'] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a key that doesn\'t match a String in a nested array', () => { const item = { testKey: { testKey2: 'inValid' } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.testKey2', value: 'inValid', item }]); }); it('should NOT return an error for a key when then schema has \'*\'', () => { const item = { testKey: { testKey2: 'inValid' }, unspecified: 'test', another: 3 }; const schema = new Schema({ testKey: { testKey2: String }, '*': '*' }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should validate a specific path', () => { const item = { testKey: { testKey2: 'valid', testKey3: 10 } }; const schema = new Schema({ testKey: { testKey2: String, testKey3: String } }); let errors = schema.validate(item, 'testKey.testKey2'); assert.equal(errors, []); errors = schema.validate(item, 'testKey.testKey3'); assert.equal(errors, [{ error: 'Value should be a String', path: 'testKey.testKey3', value: 10, item }]); }); describe('array length', () => { it('should NOT return an error for an array length greater than minLength', () => { const item = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, minLength: 2 } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for an array length less than minLength', () => { const item = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, minLength: 3 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: ['test', 'test'], item }]); }); it('should NOT return an error for an array length less than maxLength', () => { const item = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, maxLength: 2 } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for an array length greater than maxLength', () => { const item = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, maxLength: 1 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: ['test', 'test'], item }]); }); }); describe('numeric', () => { it('should NOT return an error for an integer greater than min', () => { const item = { testKey: 0 }; const schema = new Schema({ testKey: { type: 'integer', min: 0 } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should NOT return an error for an integer less than max', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', max: 20 } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for an integer less than min', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', min: 20 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should NOT return an error for an integer less than min if clamp===true', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', min: 20, clamp: true } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should return an error for an integer greater than max', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', max: 10 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should NOT return an error for an integer greater than max if clamp===true', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', max: 10, clamp: true } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should NOT return an error for a number greater than min', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, min: 10 } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should NOT return an error for a number less than max', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, max: 20 } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a number less than min', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, min: 20 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should NOT return an error for a number less than min if clamp===true', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, min: 20, clamp: true } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should return an error for a number greater than max', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, max: 10 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should NOT return an error for a number greater than max if clamp===true', () => { const item = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, max: 10, clamp: true } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should NOT return an error for a string that can be coerced into a number within a range', () => { const item = { testKey: '8' }; const schema = new Schema({ testKey: { type: Number, min: 0, max: 10, coerce: true } }); const errors = schema.validate(item); assert.equal(errors, []); }); it('should return an error for a non-number when a range is given', () => { const item = { testKey: 'test' }; const schema = new Schema({ testKey: { type: Number, max: 10 } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Number', path: 'testKey', value: 'test', item }]); }); }); describe('enum', () => { const things = new Enum({ thing1: 'thing 1', thing2: 'thing 2' }); it('should throw an error if enum is not given', () => { assert.throws(() => { new Schema({ testKey: { type: Enum } }); }, 'Enum types must provide an enum'); }); it('should NOT return an error for a value that is in an enum', () => { const item = { testKey: 'thing 1' }; const schema = new Schema({ testKey: { type: Enum, enum: things } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); it('should return an error for a value that is not in an enum', () => { const item = { testKey: 'something' }; const schema = new Schema({ testKey: { type: Enum, enum: things } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Enum', path: 'testKey', value: 'something', item }]); }); it('should return an error for a value that is not in an enum or a number', () => { const item = { testKey: 'something' }; const schema = new Schema({ testKey: { type: [Enum, Number], enum: things } }); const errors = schema.validate(item); assert.equal(errors, [{ error: 'Value should be a Enum OR Value should be a Number', path: 'testKey', value: 'something', item }]); }); it('should NOT return an error for a value that is in an enum or a number', () => { const item = { testKey: 10 }; const schema = new Schema({ testKey: { type: [Enum, Number], enum: things } }); const errors = schema.validate(item); assert.is(errors.length, 0); }); }); }); describe('.enforce', () => { schemaTestTypes.forEach((data) => { data.true.forEach((datum) => { if (datum === undefined || deepEqual(datum, {})) { return; } it(`should NOT modify the value ${displayValue(datum)} that matches a ${data.name}`, () => { const item = { testKey: datum }; const output = { testKey: datum }; const schema = new Schema({ testKey: data.value }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it(`should NOT modify the value ${displayValue(datum)} that matches a ${data.name} and isRequired=true`, () => { const item = { testKey: datum }; const output = clone(item); const schema = new Schema({ testKey: { type: data.value, isRequired: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); if (data.value !== '*') { it(`should modify a value of undefined when the type is ${data.name} and isRequired=true`, () => { const item = { testKey: undefined }; const output = { testKey: null }; const schema = new Schema({ testKey: { type: data.value, isRequired: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'A value is required', path: 'testKey', value: undefined, item }]); }); it(`should NOT modify the value undefined when the type is ${data.name} and isRequired=true and a default value is given`, () => { const item = { testKey: undefined }; const output = { testKey: data.true[0] }; const schema = new Schema({ testKey: { type: data.value, isRequired: true, default: data.true[0] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); } it(`should NOT modify the value ${displayValue(datum)} that matches a ${data.name} in a nested object`, () => { const item = { testKey: { testKey2: datum } }; const output = { testKey: { testKey2: datum } }; const schema = new Schema({ testKey: { testKey2: data.value } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it(`should unset a key with a ${data.name} not in the schema`, () => { const item = { testKey: 'test string', testKey2: datum }; const output = { testKey: 'test string' }; const schema = new Schema({ testKey: String }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Key found that isn\'t in the schema', path: 'testKey2', value: undefined, item }]); }); it(`should NOT remove a ${data.name} in an array`, () => { const item = { testKey: [datum] }; const output = { testKey: [datum] }; const schema = new Schema({ testKey: [] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it(`should NOT modify the value ${displayValue(datum)} that matches a ${data.name} in an object in an array`, () => { const item = { testKey: [{ testKey2: datum }] }; const output = { testKey: [{ testKey2: datum }] }; const schema = new Schema({ testKey: [{ testKey2: data.value }] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); }); data.false.forEach((datum) => { if (datum === undefined || deepEqual(datum, {})) { return; } it(`should modify a value of ${displayValue(datum)} that doesn't match a ${data.name}`, () => { const item = { testKey: datum }; const output = {}; const schema = new Schema({ testKey: data.value }); const errors = schema.enforce(item); assert.equal(item, output); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey', value: datum, item }]); } }); it(`should modify a value of ${displayValue(datum)} that doesn\'t match a ${data.name} in a nested object`, () => { const item = { testKey: { testKey2: datum } }; const output = {}; const schema = new Schema({ testKey: { testKey2: data.value } }); const errors = schema.enforce(item); assert.equal(item, output); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey.testKey2', value: datum, item }]); } }); it(`should modify a value of ${displayValue(datum)} that doesn\'t match a ${data.name} in an object in an array`, () => { const item = { testKey: [{ testKey2: datum }] }; const output = {}; const schema = new Schema({ testKey: [{ testKey2: data.value }] }); const errors = schema.enforce(item); assert.equal(item, output); if (data.name === 'Schema') { assert.atLeast(errors.length, 1); } else { assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey.0.testKey2', value: datum, item }]); } }); }); data.coerceTrue.forEach((datum) => { it(`should NOT modify the value ${displayValue(datum)} that is coercable to ${data.name}`, () => { const item = { testKey: datum }; const output = { testKey: data.enforce(datum, null, true) }; const schema = new Schema({ testKey: { type: data.value, coerce: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); }); data.coerceFalse.forEach((datum) => { if (datum === undefined || deepEqual(datum, {})) { return; } it(`should modify a value that is not coercable to ${data.name}`, () => { const item = { testKey: datum }; const output = {}; const schema = new Schema({ testKey: { type: data.value, coerce: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a ' + parseName(data), path: 'testKey', value: datum, item }]); }); }); }); it('should NOT modify a key that matches an array', () => { const item = { testKey: [], testKey2: 'something' }; const output = { testKey2: 'something' }; const schema = new Schema({ testKey: [], testKey2: String }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify a key that matches null', () => { const item = { testKey: null }; const output = { testKey: null }; const schema = new Schema({ testKey: null }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify a key that matches String or null', () => { const item = { testKey: null }; const output = { testKey: null }; const schema = new Schema({ testKey: [String, null] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a key that doesn\'t match an array', () => { const item = { testKey: 'inValid' }; const output = {}; const schema = new Schema({ testKey: [] }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey', value: 'inValid', item }]); }); it('should NOT modify a key that matches empty nested arrays', () => { const item = { testKey: [ ['test1', 'test2'], ['test3', 'test4', 'test5'] ] }; const output = { testKey: [ ['test1', 'test2'], ['test3', 'test4', 'test5'] ] }; const schema = new Schema({ testKey: [ [] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a key that doesn\'t match empty nested arrays', () => { const item = { testKey: ['test1', 'test2'] }; const output = {}; const schema = new Schema({ testKey: [ [] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.0', value: 'test1', item }, { error: 'Value should be a Array', path: 'testKey.1', value: 'test2', item }]); }); it('should NOT return errors for multiple items in an array', () => { const item = { testKey: ['test1', 'test2', 'test3'] }; const output = { testKey: ['test1', 'test2', 'test3'] }; const schema = new Schema({ testKey: [ [String] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a bad type amongst multiple items in an array', () => { const item = { testKey: ['test1', 3, 'test3'] }; const output = { testKey: ['test1', 'test3'] }; const schema = new Schema({ testKey: [ [String] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a String', path: 'testKey.1', value: 3, item }]); }); it('should NOT modify a good value when multiple types are given', () => { const item = { testKey: ['test1', 3, 'test3'] }; const output = { testKey: ['test1', 3, 'test3'] }; const schema = new Schema({ testKey: [ [String, Number] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a bad value when multiple types are given', () => { const item = { testKey: ['test1', 3, 'test3', true] }; const output = { testKey: ['test1', 3, 'test3'] }; const schema = new Schema({ testKey: [ [String, Number] ] }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a String OR Value should be a Number', path: 'testKey.3', value: true, item }]); }); it('should NOT modify a key that matches a nested array', () => { const item = { testKey: { testKey2: ['test'] } }; const output = { testKey: { testKey2: ['test'] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify objects in an empty array', () => { const item = { testKey: { testKey2: [{ testKey3: 'test' }] } }; const output = { testKey: { testKey2: [{ testKey3: 'test' }] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should remove an empty array', () => { const item = { testKey: { testKey2: [] } }; const output = {}; const schema = new Schema({ testKey: { testKey2: [{ testKey3: String }] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify an empty array that should be an object', () => { const item = { testKey: [] }; const output = {}; const schema = new Schema({ testKey: { testKey2: [{ testKey3: String }] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Object', path: 'testKey', value: [], item }]); }); it('should NOT modify an empty array that can have strings if isRequired=true', () => { const item = { testKey: [] }; const output = { testKey: [] }; const schema = new Schema({ testKey: { type: Array, isRequired: true, content: String } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify an empty object if isRequired=false', () => { const item = { testKey: {} }; const output = {}; const schema = new Schema({ testKey: { type: Object, content: String } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify an empty object if isRequired=true', () => { const item = { testKey: {} }; const output = { testKey: {} }; const schema = new Schema({ testKey: { type: Object, isRequired: true, content: String } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should set a value to a previous value if isRequired=true', () => { const item = { testKey: 10 }; const output = { testKey: 'previous' }; const schema = new Schema({ testKey: { type: String, isRequired: true } }); const errors = schema.enforce(item, 'testKey', 'previous'); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a String', path: 'testKey', value: 10, item }]); }); it('should modify a key that doesn\'t match a nested array', () => { const item = { testKey: { testKey2: 'inValid' } }; const output = {}; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.testKey2', value: 'inValid', item }]); }); it('should NOT modify a key that matches a String in a nested array', () => { const item = { testKey: { testKey2: ['asdf'] } }; const output = { testKey: { testKey2: ['asdf'] } }; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a key that doesn\'t match a String in a nested array', () => { const item = { testKey: { testKey2: 'inValid' } }; const output = {}; const schema = new Schema({ testKey: { testKey2: [] } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Array', path: 'testKey.testKey2', value: 'inValid', item }]); }); it('should NOT return an error for a key when then schema has \'*\'', () => { const item = { testKey: { testKey2: 'inValid' }, unspecified: 'test', another: 3 }; const output = { testKey: { testKey2: 'inValid' }, unspecified: 'test', another: 3 }; const schema = new Schema({ testKey: { testKey2: String }, '*': '*' }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should enforce a specific path', () => { const item = { testKey: { testKey2: 'valid', testKey3: 10 } }; const schema = new Schema({ testKey: { testKey2: String, testKey3: String } }); let errors = schema.enforce(item, 'testKey.testKey2'); assert.equal(errors, []); errors = schema.enforce(item, 'testKey.testKey3'); assert.equal(errors, [{ error: 'Value should be a String', path: 'testKey.testKey3', value: 10, item }]); }); describe('array length', () => { it('should NOT modify an array length greater than minLength', () => { const item = { testKey: ['test', 'test'] }; const output = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, minLength: 2 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should delete an array if length is less than minLength', () => { const item = { testKey: ['test', 'test'] }; const output = {}; const schema = new Schema({ testKey: { type: Array, minLength: 3, isRequired: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: ['test', 'test'], item }]); }); it('should modify an array length less than minLength if clamp: true', () => { const item = { testKey: ['test', 'test'] }; const output = { testKey: ['test', 'test', undefined] }; const schema = new Schema({ testKey: { type: Array, minLength: 3, isRequired: true, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should NOT modify an array length less than maxLength', () => { const item = { testKey: ['test', 'test'] }; const output = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, maxLength: 2 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should delete an array if length greater than maxLength', () => { const item = { testKey: ['test', 'test'] }; const output = {}; const schema = new Schema({ testKey: { type: Array, maxLength: 1 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: ['test', 'test'], item }]); }); it('should modify an array length greater than maxLength if clamp: true', () => { const item = { testKey: ['test', 'test', 'test'] }; const output = { testKey: ['test', 'test'] }; const schema = new Schema({ testKey: { type: Array, maxLength: 2, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); }); describe('string length', () => { it('should NOT modify a string length greater than minLength', () => { const item = { testKey: 'test' }; const output = { testKey: 'test' }; const schema = new Schema({ testKey: { type: String, minLength: 2 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should delete a string if length is less than minLength', () => { const item = { testKey: 'test' }; const output = {}; const schema = new Schema({ testKey: { type: String, minLength: 5, isRequired: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: 'test', item }]); }); it('should modify a string length less than minLength if clamp: true', () => { const item = { testKey: 'test' }; const output = { testKey: 'test' }; const schema = new Schema({ testKey: { type: String, minLength: 3, isRequired: true, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should NOT modify a string length less than maxLength', () => { const item = { testKey: 'test' }; const output = { testKey: 'test' }; const schema = new Schema({ testKey: { type: String, maxLength: 6 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should delete a string if length greater than maxLength', () => { const item = { testKey: 'test' }; const output = {}; const schema = new Schema({ testKey: { type: String, maxLength: 1 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Length is outside range', path: 'testKey', value: 'test', item }]); }); it('should modify a string length greater than maxLength if clamp: true', () => { const item = { testKey: 'test' }; const output = { testKey: 'te' }; const schema = new Schema({ testKey: { type: String, maxLength: 2, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); }); describe('numeric', () => { it('should NOT modify an integer greater than min', () => { const item = { testKey: 12 }; const output = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', min: 10 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify an integer less than max', () => { const item = { testKey: 12 }; const output = { testKey: 12 }; const schema = new Schema({ testKey: { type: 'integer', max: 20 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify an integer less than min if clamp:true', () => { const item = { testKey: 12 }; const output = { testKey: 20 }; const schema = new Schema({ testKey: { type: 'integer', min: 20, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should remove an integer less than min', () => { const item = { testKey: 12 }; const output = {}; const schema = new Schema({ testKey: { type: 'integer', min: 20 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should modify an integer greater than max if clamp:true', () => { const item = { testKey: 12 }; const output = { testKey: 10 }; const schema = new Schema({ testKey: { type: 'integer', max: 10, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should remove an integer greater than max', () => { const item = { testKey: 12 }; const output = {}; const schema = new Schema({ testKey: { type: 'integer', max: 10 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should NOT modify a number greater than min', () => { const item = { testKey: 12 }; const output = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, min: 10 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should NOT modify a number less than max', () => { const item = { testKey: 12 }; const output = { testKey: 12 }; const schema = new Schema({ testKey: { type: Number, max: 20 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a number less than min if clamp:true', () => { const item = { testKey: 12 }; const output = { testKey: 20 }; const schema = new Schema({ testKey: { type: Number, min: 20, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should remove a number less than min', () => { const item = { testKey: 12 }; const output = {}; const schema = new Schema({ testKey: { type: Number, min: 20 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should modify a number greater than max if clamp:true', () => { const item = { testKey: 12 }; const output = { testKey: 10 }; const schema = new Schema({ testKey: { type: Number, max: 10, clamp: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should remove a number greater than max', () => { const item = { testKey: 12 }; const output = {}; const schema = new Schema({ testKey: { type: Number, max: 10 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value is outside range', path: 'testKey', value: 12, item }]); }); it('should coerce a number within a range', () => { const item = { testKey: '8' }; const output = { testKey: 8 }; const schema = new Schema({ testKey: { type: Number, min: 0, max: 10, coerce: true } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, []); }); it('should modify a non-number when a range is given', () => { const item = { testKey: 'test' }; const output = {}; const schema = new Schema({ testKey: { type: Number, max: 10 } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Number', path: 'testKey', value: 'test', item }]); }); }); describe('enum', () => { const things = new Enum({ thing1: 'thing 1', thing2: 'thing 2' }); it('should NOT modify a value that is in an enum', () => { const item = { testKey: 'thing 1' }; const output = { testKey: 'thing 1' }; const schema = new Schema({ testKey: { type: Enum, enum: things } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); it('should modify a value that is not in an enum', () => { const item = { testKey: 'something' }; const output = {}; const schema = new Schema({ testKey: { type: Enum, enum: things } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Enum', path: 'testKey', value: 'something', item }]); }); it('should modify a value that is not in an enum or a number', () => { const item = { testKey: 'something' }; const output = {}; const schema = new Schema({ testKey: { type: [Enum, Number], enum: things } }); const errors = schema.enforce(item); assert.equal(item, output); assert.equal(errors, [{ error: 'Value should be a Enum OR Value should be a Number', path: 'testKey', value: 'something', item }]); }); it('should NOT modify a value that is in an enum or a number', () => { const item = { testKey: 10 }; const output = { testKey: 10 }; const schema = new Schema({ testKey: { type: [Enum, Number], enum: things } }); const errors = schema.enforce(item); assert.equal(item, output); assert.is(errors.length, 0); }); }); }); describe('.eachRule', () => { it('should call the callback for every rule', () => { let total = 0; let testVar = 0; const subSchema = new Schema({ testKey3: [{ level2: Number }], testKey4: String }); const schema = new Schema({ testKey: [{ level2: subSchema }], testKey2: String }); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule) { testVar++; } if (deepEqual(path, 'testKey') && rule) { testVar++; } if (deepEqual(path, 'testKey.0') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3.0') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3.0.level2') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey4') && rule) { testVar++; } if (deepEqual(path, 'testKey2') && rule) { testVar++; } }); assert.is(total, 9); assert.is(testVar, 9); }); it('should call the callback for every rule with nested models', () => { let total = 0; let testVar = 0; const subModel = new Model({ testKey3: [{ level2: Number }], testKey4: String }); const schema = new Schema({ testKey: [{ level2: subModel }], testKey2: String }); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule) { testVar++; } if (deepEqual(path, 'testKey') && rule) { testVar++; } if (deepEqual(path, 'testKey.0') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3.0') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey3.0.level2') && rule) { testVar++; } if (deepEqual(path, 'testKey.0.level2.testKey4') && rule) { testVar++; } if (deepEqual(path, 'testKey2') && rule) { testVar++; } }); assert.is(total, 9); assert.is(testVar, 9); }); it('should stop calling the callback after true is returned', () => { let total = 0; let testVar = 0; const schema = new Schema({ testKey: [{ level2: Number }], testKey2: String }); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule) { testVar++; } if (deepEqual(path, 'testKey') && rule) { testVar++; } if (deepEqual(path, 'testKey.0') && rule) { testVar++; return true; } if (deepEqual(path, 'testKey.0.level2') && rule) { testVar++; } if (deepEqual(path, 'testKey2') && rule) { testVar++; } }); assert.is(total, 4); assert.is(testVar, 4); }); }); describe('.extend', () => { it('should accept undefined', () => { let total = 0; let testVar = 0; const schema = new Schema({ testKey: [{ level2: Number }], testKey2: String, testKey3: Date }); const result = schema.extend(); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === String) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); result.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === String) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); assert.is(total, 12); assert.is(testVar, 12); assert.notIs(schema, result); }); it('should accept an object', () => { let total = 0; let testVar = 0; const schema = new Schema({ testKey: [{ level2: Number }], testKey2: String, testKey3: Date }); const result = schema.extend({ testKey: [{ level2: 'integer' }], testKey2: Number }); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === String) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); result.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === 'integer') { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); assert.is(total, 12); assert.is(testVar, 12); }); it('should accept an instance of Schema', () => { let total = 0; let testVar = 0; const schema = new Schema({ testKey: [{ level2: Number }], testKey2: String, testKey3: Date }); const schema2 = new Schema({ testKey: [{ level2: 'integer' }], testKey2: Number }); const result = schema.extend(schema2); schema.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === String) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); schema2.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === 'integer') { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === Number) { testVar++; } }); result.eachRule((path, rule) => { total++; if (deepEqual(path, '') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey') && rule.types[0].type === Array) { testVar++; } if (deepEqual(path, 'testKey.0') && rule.types[0].type === Object) { testVar++; } if (deepEqual(path, 'testKey.0.level2') && rule.types[0].type === 'integer') { testVar++; } if (deepEqual(path, 'testKey2') && rule.types[0].type === Number) { testVar++; } if (deepEqual(path, 'testKey3') && rule.types[0].type === Date) { testVar++; } }); assert.is(total, 17); assert.is(testVar, 17); }); }); });
braymar/afl
qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/cpu/armv7/mx7ulp/scg.c
<filename>qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/cpu/armv7/mx7ulp/scg.c /* * Copyright (C) 2016 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <div64.h> #include <asm/io.h> #include <errno.h> #include <asm/arch/imx-regs.h> #include <asm/arch/pcc.h> #include <asm/arch/sys_proto.h> DECLARE_GLOBAL_DATA_PTR; scg_p scg1_regs = (scg_p)SCG1_RBASE; static u32 scg_src_get_rate(enum scg_clk clksrc) { u32 reg; switch (clksrc) { case SCG_SOSC_CLK: reg = readl(&scg1_regs->sosccsr); if (!(reg & SCG_SOSC_CSR_SOSCVLD_MASK)) return 0; return 24000000; case SCG_FIRC_CLK: reg = readl(&scg1_regs->firccsr); if (!(reg & SCG_FIRC_CSR_FIRCVLD_MASK)) return 0; return 48000000; case SCG_SIRC_CLK: reg = readl(&scg1_regs->sirccsr); if (!(reg & SCG_SIRC_CSR_SIRCVLD_MASK)) return 0; return 16000000; case SCG_ROSC_CLK: reg = readl(&scg1_regs->rtccsr); if (!(reg & SCG_ROSC_CSR_ROSCVLD_MASK)) return 0; return 32768; default: break; } return 0; } static u32 scg_sircdiv_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask; switch (clk) { case SCG_SIRC_DIV1_CLK: mask = SCG_SIRCDIV_DIV1_MASK; shift = SCG_SIRCDIV_DIV1_SHIFT; break; case SCG_SIRC_DIV2_CLK: mask = SCG_SIRCDIV_DIV2_MASK; shift = SCG_SIRCDIV_DIV2_SHIFT; break; case SCG_SIRC_DIV3_CLK: mask = SCG_SIRCDIV_DIV3_MASK; shift = SCG_SIRCDIV_DIV3_SHIFT; break; default: return 0; } reg = readl(&scg1_regs->sirccsr); if (!(reg & SCG_SIRC_CSR_SIRCVLD_MASK)) return 0; reg = readl(&scg1_regs->sircdiv); val = (reg & mask) >> shift; if (!val) /*clock disabled*/ return 0; rate = scg_src_get_rate(SCG_SIRC_CLK); rate = rate / (1 << (val - 1)); return rate; } static u32 scg_fircdiv_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask; switch (clk) { case SCG_FIRC_DIV1_CLK: mask = SCG_FIRCDIV_DIV1_MASK; shift = SCG_FIRCDIV_DIV1_SHIFT; break; case SCG_FIRC_DIV2_CLK: mask = SCG_FIRCDIV_DIV2_MASK; shift = SCG_FIRCDIV_DIV2_SHIFT; break; case SCG_FIRC_DIV3_CLK: mask = SCG_FIRCDIV_DIV3_MASK; shift = SCG_FIRCDIV_DIV3_SHIFT; break; default: return 0; } reg = readl(&scg1_regs->firccsr); if (!(reg & SCG_FIRC_CSR_FIRCVLD_MASK)) return 0; reg = readl(&scg1_regs->fircdiv); val = (reg & mask) >> shift; if (!val) /*clock disabled*/ return 0; rate = scg_src_get_rate(SCG_FIRC_CLK); rate = rate / (1 << (val - 1)); return rate; } static u32 scg_soscdiv_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask; switch (clk) { case SCG_SOSC_DIV1_CLK: mask = SCG_SOSCDIV_DIV1_MASK; shift = SCG_SOSCDIV_DIV1_SHIFT; break; case SCG_SOSC_DIV2_CLK: mask = SCG_SOSCDIV_DIV2_MASK; shift = SCG_SOSCDIV_DIV2_SHIFT; break; case SCG_SOSC_DIV3_CLK: mask = SCG_SOSCDIV_DIV3_MASK; shift = SCG_SOSCDIV_DIV3_SHIFT; break; default: return 0; } reg = readl(&scg1_regs->sosccsr); if (!(reg & SCG_SOSC_CSR_SOSCVLD_MASK)) return 0; reg = readl(&scg1_regs->soscdiv); val = (reg & mask) >> shift; if (!val) /*clock disabled*/ return 0; rate = scg_src_get_rate(SCG_SOSC_CLK); rate = rate / (1 << (val - 1)); return rate; } static u32 scg_apll_pfd_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask, gate, valid; switch (clk) { case SCG_APLL_PFD0_CLK: gate = SCG_PLL_PFD0_GATE_MASK; valid = SCG_PLL_PFD0_VALID_MASK; mask = SCG_PLL_PFD0_FRAC_MASK; shift = SCG_PLL_PFD0_FRAC_SHIFT; break; case SCG_APLL_PFD1_CLK: gate = SCG_PLL_PFD1_GATE_MASK; valid = SCG_PLL_PFD1_VALID_MASK; mask = SCG_PLL_PFD1_FRAC_MASK; shift = SCG_PLL_PFD1_FRAC_SHIFT; break; case SCG_APLL_PFD2_CLK: gate = SCG_PLL_PFD2_GATE_MASK; valid = SCG_PLL_PFD2_VALID_MASK; mask = SCG_PLL_PFD2_FRAC_MASK; shift = SCG_PLL_PFD2_FRAC_SHIFT; break; case SCG_APLL_PFD3_CLK: gate = SCG_PLL_PFD3_GATE_MASK; valid = SCG_PLL_PFD3_VALID_MASK; mask = SCG_PLL_PFD3_FRAC_MASK; shift = SCG_PLL_PFD3_FRAC_SHIFT; break; default: return 0; } reg = readl(&scg1_regs->apllpfd); if (reg & gate || !(reg & valid)) return 0; clk_debug("scg_apll_pfd_get_rate reg 0x%x\n", reg); val = (reg & mask) >> shift; rate = decode_pll(PLL_A7_APLL); rate = rate / val * 18; clk_debug("scg_apll_pfd_get_rate rate %u\n", rate); return rate; } static u32 scg_spll_pfd_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask, gate, valid; switch (clk) { case SCG_SPLL_PFD0_CLK: gate = SCG_PLL_PFD0_GATE_MASK; valid = SCG_PLL_PFD0_VALID_MASK; mask = SCG_PLL_PFD0_FRAC_MASK; shift = SCG_PLL_PFD0_FRAC_SHIFT; break; case SCG_SPLL_PFD1_CLK: gate = SCG_PLL_PFD1_GATE_MASK; valid = SCG_PLL_PFD1_VALID_MASK; mask = SCG_PLL_PFD1_FRAC_MASK; shift = SCG_PLL_PFD1_FRAC_SHIFT; break; case SCG_SPLL_PFD2_CLK: gate = SCG_PLL_PFD2_GATE_MASK; valid = SCG_PLL_PFD2_VALID_MASK; mask = SCG_PLL_PFD2_FRAC_MASK; shift = SCG_PLL_PFD2_FRAC_SHIFT; break; case SCG_SPLL_PFD3_CLK: gate = SCG_PLL_PFD3_GATE_MASK; valid = SCG_PLL_PFD3_VALID_MASK; mask = SCG_PLL_PFD3_FRAC_MASK; shift = SCG_PLL_PFD3_FRAC_SHIFT; break; default: return 0; } reg = readl(&scg1_regs->spllpfd); if (reg & gate || !(reg & valid)) return 0; clk_debug("scg_spll_pfd_get_rate reg 0x%x\n", reg); val = (reg & mask) >> shift; rate = decode_pll(PLL_A7_SPLL); rate = rate / val * 18; clk_debug("scg_spll_pfd_get_rate rate %u\n", rate); return rate; } static u32 scg_apll_get_rate(void) { u32 reg, val, rate; reg = readl(&scg1_regs->apllcfg); val = (reg & SCG_PLL_CFG_PLLSEL_MASK) >> SCG_PLL_CFG_PLLSEL_SHIFT; if (!val) { /* APLL clock after two dividers */ rate = decode_pll(PLL_A7_APLL); val = (reg & SCG_PLL_CFG_POSTDIV1_MASK) >> SCG_PLL_CFG_POSTDIV1_SHIFT; rate = rate / (val + 1); val = (reg & SCG_PLL_CFG_POSTDIV2_MASK) >> SCG_PLL_CFG_POSTDIV2_SHIFT; rate = rate / (val + 1); } else { /* APLL PFD clock */ val = (reg & SCG_PLL_CFG_PFDSEL_MASK) >> SCG_PLL_CFG_PFDSEL_SHIFT; rate = scg_apll_pfd_get_rate(SCG_APLL_PFD0_CLK + val); } return rate; } static u32 scg_spll_get_rate(void) { u32 reg, val, rate; reg = readl(&scg1_regs->spllcfg); val = (reg & SCG_PLL_CFG_PLLSEL_MASK) >> SCG_PLL_CFG_PLLSEL_SHIFT; clk_debug("scg_spll_get_rate reg 0x%x\n", reg); if (!val) { /* APLL clock after two dividers */ rate = decode_pll(PLL_A7_SPLL); val = (reg & SCG_PLL_CFG_POSTDIV1_MASK) >> SCG_PLL_CFG_POSTDIV1_SHIFT; rate = rate / (val + 1); val = (reg & SCG_PLL_CFG_POSTDIV2_MASK) >> SCG_PLL_CFG_POSTDIV2_SHIFT; rate = rate / (val + 1); clk_debug("scg_spll_get_rate SPLL %u\n", rate); } else { /* APLL PFD clock */ val = (reg & SCG_PLL_CFG_PFDSEL_MASK) >> SCG_PLL_CFG_PFDSEL_SHIFT; rate = scg_spll_pfd_get_rate(SCG_SPLL_PFD0_CLK + val); clk_debug("scg_spll_get_rate PFD %u\n", rate); } return rate; } static u32 scg_ddr_get_rate(void) { u32 reg, val, rate, div; reg = readl(&scg1_regs->ddrccr); val = (reg & SCG_DDRCCR_DDRCS_MASK) >> SCG_DDRCCR_DDRCS_SHIFT; div = (reg & SCG_DDRCCR_DDRDIV_MASK) >> SCG_DDRCCR_DDRDIV_SHIFT; if (!div) return 0; if (!val) { reg = readl(&scg1_regs->apllcfg); val = (reg & SCG_PLL_CFG_PFDSEL_MASK) >> SCG_PLL_CFG_PFDSEL_SHIFT; rate = scg_apll_pfd_get_rate(SCG_APLL_PFD0_CLK + val); } else { rate = decode_pll(PLL_USB); } rate = rate / (1 << (div - 1)); return rate; } static u32 scg_nic_get_rate(enum scg_clk clk) { u32 reg, val, rate; u32 shift, mask; reg = readl(&scg1_regs->niccsr); val = (reg & SCG_NICCSR_NICCS_MASK) >> SCG_NICCSR_NICCS_SHIFT; clk_debug("scg_nic_get_rate niccsr 0x%x\n", reg); if (!val) rate = scg_src_get_rate(SCG_FIRC_CLK); else rate = scg_ddr_get_rate(); clk_debug("scg_nic_get_rate parent rate %u\n", rate); val = (reg & SCG_NICCSR_NIC0DIV_MASK) >> SCG_NICCSR_NIC0DIV_SHIFT; rate = rate / (val + 1); clk_debug("scg_nic_get_rate NIC0 rate %u\n", rate); switch (clk) { case SCG_NIC0_CLK: return rate; case SCG_GPU_CLK: mask = SCG_NICCSR_GPUDIV_MASK; shift = SCG_NICCSR_GPUDIV_SHIFT; break; case SCG_NIC1_EXT_CLK: case SCG_NIC1_BUS_CLK: case SCG_NIC1_CLK: mask = SCG_NICCSR_NIC1DIV_MASK; shift = SCG_NICCSR_NIC1DIV_SHIFT; break; default: return 0; } val = (reg & mask) >> shift; rate = rate / (val + 1); clk_debug("scg_nic_get_rate NIC1 rate %u\n", rate); switch (clk) { case SCG_GPU_CLK: case SCG_NIC1_CLK: return rate; case SCG_NIC1_EXT_CLK: mask = SCG_NICCSR_NIC1EXTDIV_MASK; shift = SCG_NICCSR_NIC1EXTDIV_SHIFT; break; case SCG_NIC1_BUS_CLK: mask = SCG_NICCSR_NIC1BUSDIV_MASK; shift = SCG_NICCSR_NIC1BUSDIV_SHIFT; break; default: return 0; } val = (reg & mask) >> shift; rate = rate / (val + 1); clk_debug("scg_nic_get_rate NIC1 bus rate %u\n", rate); return rate; } static enum scg_clk scg_scs_array[4] = { SCG_SOSC_CLK, SCG_SIRC_CLK, SCG_FIRC_CLK, SCG_ROSC_CLK, }; static u32 scg_sys_get_rate(enum scg_clk clk) { u32 reg, val, rate; if (clk != SCG_CORE_CLK && clk != SCG_BUS_CLK) return 0; reg = readl(&scg1_regs->csr); val = (reg & SCG_CCR_SCS_MASK) >> SCG_CCR_SCS_SHIFT; clk_debug("scg_sys_get_rate reg 0x%x\n", reg); switch (val) { case SCG_SCS_SYS_OSC: case SCG_SCS_SLOW_IRC: case SCG_SCS_FAST_IRC: case SCG_SCS_RTC_OSC: rate = scg_src_get_rate(scg_scs_array[val]); break; case 5: rate = scg_apll_get_rate(); break; case 6: rate = scg_spll_get_rate(); break; default: return 0; } clk_debug("scg_sys_get_rate parent rate %u\n", rate); val = (reg & SCG_CCR_DIVCORE_MASK) >> SCG_CCR_DIVCORE_SHIFT; rate = rate / (val + 1); if (clk == SCG_BUS_CLK) { val = (reg & SCG_CCR_DIVBUS_MASK) >> SCG_CCR_DIVBUS_SHIFT; rate = rate / (val + 1); } return rate; } u32 decode_pll(enum pll_clocks pll) { u32 reg, pre_div, infreq, mult; u32 num, denom; /* * Alought there are four choices for the bypass src, * we choose OSC_24M which is the default set in ROM. */ switch (pll) { case PLL_A7_SPLL: reg = readl(&scg1_regs->spllcsr); if (!(reg & SCG_SPLL_CSR_SPLLVLD_MASK)) return 0; reg = readl(&scg1_regs->spllcfg); pre_div = (reg & SCG_PLL_CFG_PREDIV_MASK) >> SCG_PLL_CFG_PREDIV_SHIFT; pre_div += 1; mult = (reg & SCG1_SPLL_CFG_MULT_MASK) >> SCG_PLL_CFG_MULT_SHIFT; infreq = (reg & SCG_PLL_CFG_CLKSRC_MASK) >> SCG_PLL_CFG_CLKSRC_SHIFT; if (!infreq) infreq = scg_src_get_rate(SCG_SOSC_CLK); else infreq = scg_src_get_rate(SCG_FIRC_CLK); num = readl(&scg1_regs->spllnum); denom = readl(&scg1_regs->splldenom); infreq = infreq / pre_div; return infreq * mult + infreq * num / denom; case PLL_A7_APLL: reg = readl(&scg1_regs->apllcsr); if (!(reg & SCG_APLL_CSR_APLLVLD_MASK)) return 0; reg = readl(&scg1_regs->apllcfg); pre_div = (reg & SCG_PLL_CFG_PREDIV_MASK) >> SCG_PLL_CFG_PREDIV_SHIFT; pre_div += 1; mult = (reg & SCG_APLL_CFG_MULT_MASK) >> SCG_PLL_CFG_MULT_SHIFT; infreq = (reg & SCG_PLL_CFG_CLKSRC_MASK) >> SCG_PLL_CFG_CLKSRC_SHIFT; if (!infreq) infreq = scg_src_get_rate(SCG_SOSC_CLK); else infreq = scg_src_get_rate(SCG_FIRC_CLK); num = readl(&scg1_regs->apllnum); denom = readl(&scg1_regs->aplldenom); infreq = infreq / pre_div; return infreq * mult + infreq * num / denom; case PLL_USB: reg = readl(&scg1_regs->upllcsr); if (!(reg & SCG_UPLL_CSR_UPLLVLD_MASK)) return 0; return 480000000u; case PLL_MIPI: return 480000000u; default: printf("Unsupported pll clocks %d\n", pll); break; } return 0; } u32 scg_clk_get_rate(enum scg_clk clk) { switch (clk) { case SCG_SIRC_DIV1_CLK: case SCG_SIRC_DIV2_CLK: case SCG_SIRC_DIV3_CLK: return scg_sircdiv_get_rate(clk); case SCG_FIRC_DIV1_CLK: case SCG_FIRC_DIV2_CLK: case SCG_FIRC_DIV3_CLK: return scg_fircdiv_get_rate(clk); case SCG_SOSC_DIV1_CLK: case SCG_SOSC_DIV2_CLK: case SCG_SOSC_DIV3_CLK: return scg_soscdiv_get_rate(clk); case SCG_CORE_CLK: case SCG_BUS_CLK: return scg_sys_get_rate(clk); case SCG_SPLL_PFD0_CLK: case SCG_SPLL_PFD1_CLK: case SCG_SPLL_PFD2_CLK: case SCG_SPLL_PFD3_CLK: return scg_spll_pfd_get_rate(clk); case SCG_APLL_PFD0_CLK: case SCG_APLL_PFD1_CLK: case SCG_APLL_PFD2_CLK: case SCG_APLL_PFD3_CLK: return scg_apll_pfd_get_rate(clk); case SCG_DDR_CLK: return scg_ddr_get_rate(); case SCG_NIC0_CLK: case SCG_GPU_CLK: case SCG_NIC1_CLK: case SCG_NIC1_BUS_CLK: case SCG_NIC1_EXT_CLK: return scg_nic_get_rate(clk); case USB_PLL_OUT: return decode_pll(PLL_USB); case MIPI_PLL_OUT: return decode_pll(PLL_MIPI); case SCG_SOSC_CLK: case SCG_FIRC_CLK: case SCG_SIRC_CLK: case SCG_ROSC_CLK: return scg_src_get_rate(clk); default: return 0; } } int scg_enable_pll_pfd(enum scg_clk clk, u32 frac) { u32 reg; u32 shift, mask, gate, valid; u32 addr; if (frac < 12 || frac > 35) return -EINVAL; switch (clk) { case SCG_SPLL_PFD0_CLK: case SCG_APLL_PFD0_CLK: gate = SCG_PLL_PFD0_GATE_MASK; valid = SCG_PLL_PFD0_VALID_MASK; mask = SCG_PLL_PFD0_FRAC_MASK; shift = SCG_PLL_PFD0_FRAC_SHIFT; if (clk == SCG_SPLL_PFD0_CLK) addr = (u32)(&scg1_regs->spllpfd); else addr = (u32)(&scg1_regs->apllpfd); break; case SCG_SPLL_PFD1_CLK: case SCG_APLL_PFD1_CLK: gate = SCG_PLL_PFD1_GATE_MASK; valid = SCG_PLL_PFD1_VALID_MASK; mask = SCG_PLL_PFD1_FRAC_MASK; shift = SCG_PLL_PFD1_FRAC_SHIFT; if (clk == SCG_SPLL_PFD1_CLK) addr = (u32)(&scg1_regs->spllpfd); else addr = (u32)(&scg1_regs->apllpfd); break; case SCG_SPLL_PFD2_CLK: case SCG_APLL_PFD2_CLK: gate = SCG_PLL_PFD2_GATE_MASK; valid = SCG_PLL_PFD2_VALID_MASK; mask = SCG_PLL_PFD2_FRAC_MASK; shift = SCG_PLL_PFD2_FRAC_SHIFT; if (clk == SCG_SPLL_PFD2_CLK) addr = (u32)(&scg1_regs->spllpfd); else addr = (u32)(&scg1_regs->apllpfd); break; case SCG_SPLL_PFD3_CLK: case SCG_APLL_PFD3_CLK: gate = SCG_PLL_PFD3_GATE_MASK; valid = SCG_PLL_PFD3_VALID_MASK; mask = SCG_PLL_PFD3_FRAC_MASK; shift = SCG_PLL_PFD3_FRAC_SHIFT; if (clk == SCG_SPLL_PFD3_CLK) addr = (u32)(&scg1_regs->spllpfd); else addr = (u32)(&scg1_regs->apllpfd); break; default: return -EINVAL; } /* Gate the PFD */ reg = readl(addr); reg |= gate; writel(reg, addr); /* Write Frac divider */ reg &= ~mask; reg |= (frac << shift) & mask; writel(reg, addr); /* * Un-gate the PFD * (Need un-gate before checking valid, not align with RM) */ reg &= ~gate; writel(reg, addr); /* Wait for PFD clock being valid */ do { reg = readl(addr); } while (!(reg & valid)); return 0; } #define SIM_MISC_CTRL0_USB_PLL_EN_MASK (0x1 << 2) int scg_enable_usb_pll(bool usb_control) { u32 sosc_rate; s32 timeout = 1000000; u32 reg; struct usbphy_regs *usbphy = (struct usbphy_regs *)USBPHY_RBASE; sosc_rate = scg_src_get_rate(SCG_SOSC_CLK); if (!sosc_rate) return -EPERM; reg = readl(SIM0_RBASE + 0x3C); if (usb_control) reg &= ~SIM_MISC_CTRL0_USB_PLL_EN_MASK; else reg |= SIM_MISC_CTRL0_USB_PLL_EN_MASK; writel(reg, SIM0_RBASE + 0x3C); if (!(readl(&usbphy->usb1_pll_480_ctrl) & PLL_USB_LOCK_MASK)) { writel(0x1c00000, &usbphy->usb1_pll_480_ctrl_clr); switch (sosc_rate) { case 24000000: writel(0xc00000, &usbphy->usb1_pll_480_ctrl_set); break; case 30000000: writel(0x800000, &usbphy->usb1_pll_480_ctrl_set); break; case 19200000: writel(0x1400000, &usbphy->usb1_pll_480_ctrl_set); break; default: writel(0xc00000, &usbphy->usb1_pll_480_ctrl_set); break; } /* Enable the regulator first */ writel(PLL_USB_REG_ENABLE_MASK, &usbphy->usb1_pll_480_ctrl_set); /* Wait at least 15us */ udelay(15); /* Enable the power */ writel(PLL_USB_PWR_MASK, &usbphy->usb1_pll_480_ctrl_set); /* Wait lock */ while (timeout--) { if (readl(&usbphy->usb1_pll_480_ctrl) & PLL_USB_LOCK_MASK) break; } if (timeout <= 0) { /* If timeout, we power down the pll */ writel(PLL_USB_PWR_MASK, &usbphy->usb1_pll_480_ctrl_clr); return -ETIME; } } /* Clear the bypass */ writel(PLL_USB_BYPASS_MASK, &usbphy->usb1_pll_480_ctrl_clr); /* Enable the PLL clock out to USB */ writel((PLL_USB_EN_USB_CLKS_MASK | PLL_USB_ENABLE_MASK), &usbphy->usb1_pll_480_ctrl_set); if (!usb_control) { while (timeout--) { if (readl(&scg1_regs->upllcsr) & SCG_UPLL_CSR_UPLLVLD_MASK) break; } if (timeout <= 0) { reg = readl(SIM0_RBASE + 0x3C); reg &= ~SIM_MISC_CTRL0_USB_PLL_EN_MASK; writel(reg, SIM0_RBASE + 0x3C); return -ETIME; } } return 0; } /* A7 domain system clock source is SPLL */ #define SCG1_RCCR_SCS_NUM ((SCG_SCS_SYS_PLL) << SCG_CCR_SCS_SHIFT) /* A7 Core clck = SPLL PFD0 / 1 = 500MHz / 1 = 500MHz */ #define SCG1_RCCR_DIVCORE_NUM ((0x0) << SCG_CCR_DIVCORE_SHIFT) #define SCG1_RCCR_CFG_MASK (SCG_CCR_SCS_MASK | SCG_CCR_DIVBUS_MASK) /* A7 Plat clck = A7 Core Clock / 2 = 250MHz / 1 = 250MHz */ #define SCG1_RCCR_DIVBUS_NUM ((0x1) << SCG_CCR_DIVBUS_SHIFT) #define SCG1_RCCR_CFG_NUM (SCG1_RCCR_SCS_NUM | SCG1_RCCR_DIVBUS_NUM) void scg_a7_rccr_init(void) { u32 rccr_reg_val = 0; rccr_reg_val = readl(&scg1_regs->rccr); rccr_reg_val &= (~SCG1_RCCR_CFG_MASK); rccr_reg_val |= (SCG1_RCCR_CFG_NUM); writel(rccr_reg_val, &scg1_regs->rccr); } /* POSTDIV2 = 1 */ #define SCG1_SPLL_CFG_POSTDIV2_NUM ((0x0) << SCG_PLL_CFG_POSTDIV2_SHIFT) /* POSTDIV1 = 1 */ #define SCG1_SPLL_CFG_POSTDIV1_NUM ((0x0) << SCG_PLL_CFG_POSTDIV1_SHIFT) /* MULT = 22 */ #define SCG1_SPLL_CFG_MULT_NUM ((22) << SCG_PLL_CFG_MULT_SHIFT) /* PFD0 output clock selected */ #define SCG1_SPLL_CFG_PFDSEL_NUM ((0) << SCG_PLL_CFG_PFDSEL_SHIFT) /* PREDIV = 1 */ #define SCG1_SPLL_CFG_PREDIV_NUM ((0x0) << SCG_PLL_CFG_PREDIV_SHIFT) /* SPLL output clocks (including PFD outputs) selected */ #define SCG1_SPLL_CFG_BYPASS_NUM ((0x0) << SCG_PLL_CFG_BYPASS_SHIFT) /* SPLL PFD output clock selected */ #define SCG1_SPLL_CFG_PLLSEL_NUM ((0x1) << SCG_PLL_CFG_PLLSEL_SHIFT) /* Clock source is System OSC */ #define SCG1_SPLL_CFG_CLKSRC_NUM ((0x0) << SCG_PLL_CFG_CLKSRC_SHIFT) #define SCG1_SPLL_CFG_NUM_24M_OSC (SCG1_SPLL_CFG_POSTDIV2_NUM | \ SCG1_SPLL_CFG_POSTDIV1_NUM | \ (22 << SCG_PLL_CFG_MULT_SHIFT) | \ SCG1_SPLL_CFG_PFDSEL_NUM | \ SCG1_SPLL_CFG_PREDIV_NUM | \ SCG1_SPLL_CFG_BYPASS_NUM | \ SCG1_SPLL_CFG_PLLSEL_NUM | \ SCG1_SPLL_CFG_CLKSRC_NUM) /*413Mhz = A7 SPLL(528MHz) * 18/23 */ #define SCG1_SPLL_PFD0_FRAC_NUM ((23) << SCG_PLL_PFD0_FRAC_SHIFT) void scg_a7_spll_init(void) { u32 val = 0; /* Disable A7 System PLL */ val = readl(&scg1_regs->spllcsr); val &= ~SCG_SPLL_CSR_SPLLEN_MASK; writel(val, &scg1_regs->spllcsr); /* * Per block guide, * "When changing PFD values, it is recommneded PFDx clock * gets gated first by writing a value of 1 to PFDx_CLKGATE register, * then program the new PFD value, then poll the PFDx_VALID * flag to set before writing a value of 0 to PFDx_CLKGATE * to ungate the PFDx clock and allow PFDx clock to run" */ /* Gate off A7 SPLL PFD0 ~ PDF4 */ val = readl(&scg1_regs->spllpfd); val |= (SCG_PLL_PFD3_GATE_MASK | SCG_PLL_PFD2_GATE_MASK | SCG_PLL_PFD1_GATE_MASK | SCG_PLL_PFD0_GATE_MASK); writel(val, &scg1_regs->spllpfd); /* ================ A7 SPLL Configuration Start ============== */ /* Configure A7 System PLL */ writel(SCG1_SPLL_CFG_NUM_24M_OSC, &scg1_regs->spllcfg); /* Enable A7 System PLL */ val = readl(&scg1_regs->spllcsr); val |= SCG_SPLL_CSR_SPLLEN_MASK; writel(val, &scg1_regs->spllcsr); /* Wait for A7 SPLL clock ready */ while (!(readl(&scg1_regs->spllcsr) & SCG_SPLL_CSR_SPLLVLD_MASK)) ; /* Configure A7 SPLL PFD0 */ val = readl(&scg1_regs->spllpfd); val &= ~SCG_PLL_PFD0_FRAC_MASK; val |= SCG1_SPLL_PFD0_FRAC_NUM; writel(val, &scg1_regs->spllpfd); /* Un-gate A7 SPLL PFD0 */ val = readl(&scg1_regs->spllpfd); val &= ~SCG_PLL_PFD0_GATE_MASK; writel(val, &scg1_regs->spllpfd); /* Wait for A7 SPLL PFD0 clock being valid */ while (!(readl(&scg1_regs->spllpfd) & SCG_PLL_PFD0_VALID_MASK)) ; /* ================ A7 SPLL Configuration End ============== */ } /* DDR clock source is APLL PFD0 (396MHz) */ #define SCG1_DDRCCR_DDRCS_NUM ((0x0) << SCG_DDRCCR_DDRCS_SHIFT) /* DDR clock = APLL PFD0 / 1 = 396MHz / 1 = 396MHz */ #define SCG1_DDRCCR_DDRDIV_NUM ((0x1) << SCG_DDRCCR_DDRDIV_SHIFT) /* DDR clock = APLL PFD0 / 2 = 396MHz / 2 = 198MHz */ #define SCG1_DDRCCR_DDRDIV_LF_NUM ((0x2) << SCG_DDRCCR_DDRDIV_SHIFT) #define SCG1_DDRCCR_CFG_NUM (SCG1_DDRCCR_DDRCS_NUM | \ SCG1_DDRCCR_DDRDIV_NUM) #define SCG1_DDRCCR_CFG_LF_NUM (SCG1_DDRCCR_DDRCS_NUM | \ SCG1_DDRCCR_DDRDIV_LF_NUM) void scg_a7_ddrclk_init(void) { writel(SCG1_DDRCCR_CFG_NUM, &scg1_regs->ddrccr); } /* SCG1(A7) APLLCFG configurations */ /* divide by 1 <<28 */ #define SCG1_APLL_CFG_POSTDIV2_NUM ((0x0) << SCG_PLL_CFG_POSTDIV2_SHIFT) /* divide by 1 <<24 */ #define SCG1_APLL_CFG_POSTDIV1_NUM ((0x0) << SCG_PLL_CFG_POSTDIV1_SHIFT) /* MULT is 22 <<16 */ #define SCG1_APLL_CFG_MULT_NUM ((22) << SCG_PLL_CFG_MULT_SHIFT) /* PFD0 output clock selected <<14 */ #define SCG1_APLL_CFG_PFDSEL_NUM ((0) << SCG_PLL_CFG_PFDSEL_SHIFT) /* PREDIV = 1 <<8 */ #define SCG1_APLL_CFG_PREDIV_NUM ((0x0) << SCG_PLL_CFG_PREDIV_SHIFT) /* APLL output clocks (including PFD outputs) selected <<2 */ #define SCG1_APLL_CFG_BYPASS_NUM ((0x0) << SCG_PLL_CFG_BYPASS_SHIFT) /* APLL PFD output clock selected <<1 */ #define SCG1_APLL_CFG_PLLSEL_NUM ((0x0) << SCG_PLL_CFG_PLLSEL_SHIFT) /* Clock source is System OSC <<0 */ #define SCG1_APLL_CFG_CLKSRC_NUM ((0x0) << SCG_PLL_CFG_CLKSRC_SHIFT) /* * A7 APLL = 24MHz / 1 * 22 / 1 / 1 = 528MHz, * system PLL is sourced from APLL, * APLL clock source is system OSC (24MHz) */ #define SCG1_APLL_CFG_NUM_24M_OSC (SCG1_APLL_CFG_POSTDIV2_NUM | \ SCG1_APLL_CFG_POSTDIV1_NUM | \ (22 << SCG_PLL_CFG_MULT_SHIFT) | \ SCG1_APLL_CFG_PFDSEL_NUM | \ SCG1_APLL_CFG_PREDIV_NUM | \ SCG1_APLL_CFG_BYPASS_NUM | \ SCG1_APLL_CFG_PLLSEL_NUM | \ SCG1_APLL_CFG_CLKSRC_NUM) /* PFD0 Freq = A7 APLL(528MHz) * 18 / 27 = 352MHz */ #define SCG1_APLL_PFD0_FRAC_NUM (27) void scg_a7_apll_init(void) { u32 val = 0; /* Disable A7 Auxiliary PLL */ val = readl(&scg1_regs->apllcsr); val &= ~SCG_APLL_CSR_APLLEN_MASK; writel(val, &scg1_regs->apllcsr); /* Gate off A7 APLL PFD0 ~ PDF4 */ val = readl(&scg1_regs->apllpfd); val |= 0x80808080; writel(val, &scg1_regs->apllpfd); /* ================ A7 APLL Configuration Start ============== */ /* Configure A7 Auxiliary PLL */ writel(SCG1_APLL_CFG_NUM_24M_OSC, &scg1_regs->apllcfg); /* Enable A7 Auxiliary PLL */ val = readl(&scg1_regs->apllcsr); val |= SCG_APLL_CSR_APLLEN_MASK; writel(val, &scg1_regs->apllcsr); /* Wait for A7 APLL clock ready */ while (!(readl(&scg1_regs->apllcsr) & SCG_APLL_CSR_APLLVLD_MASK)) ; /* Configure A7 APLL PFD0 */ val = readl(&scg1_regs->apllpfd); val &= ~SCG_PLL_PFD0_FRAC_MASK; val |= SCG1_APLL_PFD0_FRAC_NUM; writel(val, &scg1_regs->apllpfd); /* Un-gate A7 APLL PFD0 */ val = readl(&scg1_regs->apllpfd); val &= ~SCG_PLL_PFD0_GATE_MASK; writel(val, &scg1_regs->apllpfd); /* Wait for A7 APLL PFD0 clock being valid */ while (!(readl(&scg1_regs->apllpfd) & SCG_PLL_PFD0_VALID_MASK)) ; } /* SCG1(A7) FIRC DIV configurations */ /* Disable FIRC DIV3 */ #define SCG1_FIRCDIV_DIV3_NUM ((0x0) << SCG_FIRCDIV_DIV3_SHIFT) /* FIRC DIV2 = 48MHz / 1 = 48MHz */ #define SCG1_FIRCDIV_DIV2_NUM ((0x1) << SCG_FIRCDIV_DIV2_SHIFT) /* Disable FIRC DIV1 */ #define SCG1_FIRCDIV_DIV1_NUM ((0x0) << SCG_FIRCDIV_DIV1_SHIFT) void scg_a7_firc_init(void) { /* Wait for FIRC clock ready */ while (!(readl(&scg1_regs->firccsr) & SCG_FIRC_CSR_FIRCVLD_MASK)) ; /* Configure A7 FIRC DIV1 ~ DIV3 */ writel((SCG1_FIRCDIV_DIV3_NUM | SCG1_FIRCDIV_DIV2_NUM | SCG1_FIRCDIV_DIV1_NUM), &scg1_regs->fircdiv); } /* SCG1(A7) NICCCR configurations */ /* NIC clock source is DDR clock (396/198MHz) */ #define SCG1_NICCCR_NICCS_NUM ((0x1) << SCG_NICCCR_NICCS_SHIFT) /* NIC0 clock = DDR Clock / 2 = 396MHz / 2 = 198MHz */ #define SCG1_NICCCR_NIC0_DIV_NUM ((0x1) << SCG_NICCCR_NIC0_DIV_SHIFT) /* NIC0 clock = DDR Clock / 1 = 198MHz / 1 = 198MHz */ #define SCG1_NICCCR_NIC0_DIV_LF_NUM ((0x0) << SCG_NICCCR_NIC0_DIV_SHIFT) /* NIC1 clock = NIC0 Clock / 1 = 198MHz / 2 = 198MHz */ #define SCG1_NICCCR_NIC1_DIV_NUM ((0x0) << SCG_NICCCR_NIC1_DIV_SHIFT) /* NIC1 bus clock = NIC1 Clock / 3 = 198MHz / 3 = 66MHz */ #define SCG1_NICCCR_NIC1_DIVBUS_NUM ((0x2) << SCG_NICCCR_NIC1_DIVBUS_SHIFT) #define SCG1_NICCCR_CFG_NUM (SCG1_NICCCR_NICCS_NUM | \ SCG1_NICCCR_NIC0_DIV_NUM | \ SCG1_NICCCR_NIC1_DIV_NUM | \ SCG1_NICCCR_NIC1_DIVBUS_NUM) void scg_a7_nicclk_init(void) { writel(SCG1_NICCCR_CFG_NUM, &scg1_regs->nicccr); } /* SCG1(A7) FIRC DIV configurations */ /* Enable FIRC DIV3 */ #define SCG1_SOSCDIV_DIV3_NUM ((0x1) << SCG_SOSCDIV_DIV3_SHIFT) /* FIRC DIV2 = 48MHz / 1 = 48MHz */ #define SCG1_SOSCDIV_DIV2_NUM ((0x1) << SCG_SOSCDIV_DIV2_SHIFT) /* Enable FIRC DIV1 */ #define SCG1_SOSCDIV_DIV1_NUM ((0x1) << SCG_SOSCDIV_DIV1_SHIFT) void scg_a7_soscdiv_init(void) { /* Wait for FIRC clock ready */ while (!(readl(&scg1_regs->sosccsr) & SCG_SOSC_CSR_SOSCVLD_MASK)) ; /* Configure A7 FIRC DIV1 ~ DIV3 */ writel((SCG1_SOSCDIV_DIV3_NUM | SCG1_SOSCDIV_DIV2_NUM | SCG1_SOSCDIV_DIV1_NUM), &scg1_regs->soscdiv); } void scg_a7_sys_clk_sel(enum scg_sys_src clk) { u32 rccr_reg_val = 0; clk_debug("%s: system clock selected as %s\n", "[SCG]", clk == SCG_SCS_SYS_OSC ? "SYS_OSC" : clk == SCG_SCS_SLOW_IRC ? "SLOW_IRC" : clk == SCG_SCS_FAST_IRC ? "FAST_IRC" : clk == SCG_SCS_RTC_OSC ? "RTC_OSC" : clk == SCG_SCS_AUX_PLL ? "AUX_PLL" : clk == SCG_SCS_SYS_PLL ? "SYS_PLL" : clk == SCG_SCS_USBPHY_PLL ? "USBPHY_PLL" : "Invalid source" ); rccr_reg_val = readl(&scg1_regs->rccr); rccr_reg_val &= ~SCG_CCR_SCS_MASK; rccr_reg_val |= (clk << SCG_CCR_SCS_SHIFT); writel(rccr_reg_val, &scg1_regs->rccr); } void scg_a7_info(void) { debug("SCG Version: 0x%x\n", readl(&scg1_regs->verid)); debug("SCG Parameter: 0x%x\n", readl(&scg1_regs->param)); debug("SCG RCCR Value: 0x%x\n", readl(&scg1_regs->rccr)); debug("SCG Clock Status: 0x%x\n", readl(&scg1_regs->csr)); }
jemiahlee/18xx
lib/engine/game/g_1856/step/nationalization_payoff.rb
# frozen_string_literal: true require_relative '../../../step/base' # require_relative 'tokener' module Engine module Game module G1856 module Step class NationalizationPayoff < Engine::Step::Base # To get to re-use view code from 18MEX we will slightly abuse merge and pass # Merge - Merge the corporation into the CGR # Pass - Payoff the loan debt owed by the corporation ACTIONS = %w[merge pass].freeze def actions(_entity) return [] unless merge_ongoing? ACTIONS end def active_entities merge_ongoing? ? [@game.nationalizables.first].compact : [] end def merge_target @game.national end def merge_name "Merge into #{@game.national.name}" end def mergeable_type(corporation) "Corporations that can merge with #{corporation.name}" end def mergeable(_corporation) return [] unless merge_ongoing? [@game.nationalizables.first] end def override_entities @game.nationalizables end def show_other_players true end def active? merge_ongoing? end def blocking? merge_ongoing? end def description 'Nationalization - Loan payoffs' end def amount_owed 100 * @game.nationalizables.first.loans.size end def pass_description "Pay #{@game.format_currency(amount_owed - @game.nationalizables.first.cash)} to cover loans" end def process_merge(action) @game.merge_major(action.corporation) end def process_pass(_action) presidential_contribution = amount_owed - @game.nationalizables.first.cash @game.nationalization_president_payoff(@game.nationalizables.first, presidential_contribution) end private def merge_ongoing? @game.nationalizables.any? end end end end end end
Adxell/practicewithjavaScript
js/boolean/boolean.js
<filename>js/boolean/boolean.js<gh_stars>1-10 const flag = new Boolean(); console.log(flag); console.log("--------Creating Boolean objects with an initial value of false ----------") let bNoParam = new Boolean(); console.log(bNoParam); let bZero = new Boolean(0); console.log(bZero); let bNull = new Boolean(null); console.log(bNull); let bEmptyString = new Boolean(""); console.log(bEmptyString); let bfalse = new Boolean(false); console.log(bfalse); console.log("--------Creating Boolean objects with an initial value of true ----------") let btrue = new Boolean(true); console.log(btrue); let btrueString = new Boolean('true'); console.log(btrueString); let bfalseString = new Boolean('false'); console.log(bfalseString) let bSuLin = new Boolean('Su Lin'); console.log(bSuLin); let bArrayProto= new Boolean([]); console.log(bArrayProto); let bObjProto = new Boolean({}); console.log(bObjProto);
mJiyan/mercedes-coding-challenge
server/node_modules/swagger-node-runner/fittings/cors.js
'use strict'; var debug = require('debug')('pipes:fittings'); var CORS = require('cors'); // config options: https://www.npmjs.com/package/cors module.exports = function create(fittingDef) { debug('cors config: %j', fittingDef); var middleware = CORS(fittingDef); return function cors(context, cb) { debug('cors exec'); middleware(context.request, context.response, cb); } };
YANG-DB/netflix-graph
src/test/java/com/netflix/nfgraph/compressed/HashSetTest.java
<gh_stars>100-1000 /* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.nfgraph.compressed; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.netflix.nfgraph.OrdinalSet; import com.netflix.nfgraph.compressor.HashedPropertyBuilder; import com.netflix.nfgraph.util.ByteArrayBuffer; import com.netflix.nfgraph.util.ByteArrayReader; import com.netflix.nfgraph.util.ByteData; import org.junit.Test; public class HashSetTest extends EncodedConnectionSetTest { @Override protected ByteData generateCompressedData(OrdinalSet ordinals) { ByteArrayBuffer buf = new ByteArrayBuffer(); HashedPropertyBuilder builder = new HashedPropertyBuilder(buf); builder.buildProperty(ordinals); dataLength = buf.length(); return buf.getData(); } @Override protected OrdinalSet createOrdinalSet() { ByteArrayReader reader = new ByteArrayReader(data, 0, dataLength); return new HashSetOrdinalSet(reader); } @Override protected int maximumTotalOrdinals() { return 100000; } @Test public void singleOrdinal127IsSizedAppropriately() { ByteArrayBuffer buf = new ByteArrayBuffer(); HashedPropertyBuilder builder = new HashedPropertyBuilder(buf); builder.buildProperty(new SingleOrdinalSet(127)); ByteArrayReader reader = new ByteArrayReader(buf.getData(), 0, buf.length()); OrdinalSet set = new HashSetOrdinalSet(reader); assertTrue(set.contains(127)); assertFalse(set.contains(128)); } }
sfa119f/2018-TowerDefence
game-engine/domain/src/main/java/za/co/entelect/challenge/commands/IronCurtainCommand.java
<reponame>sfa119f/2018-TowerDefence<filename>game-engine/domain/src/main/java/za/co/entelect/challenge/commands/IronCurtainCommand.java package za.co.entelect.challenge.commands; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import za.co.entelect.challenge.config.GameConfig; import za.co.entelect.challenge.entities.TowerDefenseGameMap; import za.co.entelect.challenge.entities.TowerDefensePlayer; import za.co.entelect.challenge.game.contracts.command.Command; import za.co.entelect.challenge.game.contracts.exceptions.InvalidCommandException; import za.co.entelect.challenge.game.contracts.game.GamePlayer; import za.co.entelect.challenge.game.contracts.map.GameMap; public class IronCurtainCommand implements Command { private static final Logger log = LogManager.getLogger(IronCurtainCommand.class); @Override public void performCommand(GameMap gameMap, GamePlayer gamePlayer) throws InvalidCommandException { TowerDefensePlayer currentPlayer = (TowerDefensePlayer) gamePlayer; TowerDefenseGameMap currentGameMap = (TowerDefenseGameMap) gameMap; if (!currentPlayer.canPlaceIronCurtain()) { int resetPeriod = GameConfig.getIroncurtainResetPeriod(); logAndThrowException( String.format("Cannot place the Iron Curtain consecutively, wait until [%d] rounds have elapsed", resetPeriod - (currentGameMap.getCurrentRound() % resetPeriod))); } else if (currentPlayer.getEnergy() < GameConfig.getIroncurtainPrice()) { logAndThrowException(String.format("Not enough energy to setup the Iron Curtain, you need at least[%d] energy", GameConfig.getIroncurtainPrice())); } else if (currentPlayer.getActiveIronCurtainTimeLeft() >= 1) { // Because the command is parsed right before the previous IronCurtain will be removed, use 1 (one) so that // players are allowed to place IronCurtains in a continuous time period. logAndThrowException( String.format("You can only have one [1] active Iron Curtain at any time")); } currentGameMap.activateIronCurtain(currentPlayer); try { currentPlayer.removeEnergy(GameConfig.getIroncurtainPrice()); } catch (Exception e) { log.error(e); } } private void logAndThrowException(String errorString) throws InvalidCommandException { log.error(errorString); throw new InvalidCommandException(errorString); } }
opencolleges/oc-component-library
lib/radio-set/radio-set.js
// * React imports import PropTypes from 'prop-types'; import React from 'react'; // * utility imports import find from '../utilities/js/find'; import prefix from '../utilities/js/prefix'; // * child imports import OCGrid from '../grid'; import OCGridItem from '../grid-item'; import OCCard from '../card'; import OCRadio from '../radio'; // * React component export default class OCRadioSet extends React.Component { constructor(props) { super(props); const radiosArray = []; props.radios.map(radio => { radiosArray.push(radio.value); }); this.state = { value: radiosArray.indexOf(this.props.value) !== -1 ? this.props.value : '', error: find('radio-set--error', this.props.modifiers), success: find('radio-set--success', this.props.modifiers), disabled: this.props.disabled }; } componentDidUpdate(prevProps) { if (prevProps.disabled !== this.props.disabled) { this.setState({ disabled: this.props.disabled }); } if (prevProps.modifiers !== this.props.modifiers) { this.setState({ error: find('radio-set--error', this.props.modifiers), success: find('radio-set--success', this.props.modifiers) }); } } handleChange = value => { this.setState({ value: value, error: false, success: false }); this.props.onChange(value, this.props.name); }; render() { const { props, state, handleChange } = this; let classNames = prefix('radio-set'); state.error && (classNames += ` ${prefix('radio-set--error')}`); state.success && (classNames += ` ${prefix('radio-set--success')}`); props.className && (classNames += ` ${props.className}`); return ( <fieldset className={classNames} style={props.style}> <OCGrid modifiers="grid--gutter-x-fixed"> {props.radios.map((radio, index) => ( <OCGridItem key={index} modifiers="grid__item--s-12 grid__item--m-6 grid__item--align-end"> {props.cards ? ( <OCCard modifiers="card--s card--layer-1 card--clickable"> <OCRadio id={radio.id} modifiers={ state.value === radio.value ? state.error ? 'radio--error' : state.success ? 'radio--success' : null : null } className={radio.className} style={radio.style} name={props.name} value={radio.value} disabled={state.disabled} readOnly={props.readOnly} required={props.required && index === 0} checked={state.value === radio.value} onChange={handleChange}> {radio.label} </OCRadio> </OCCard> ) : ( <OCRadio id={radio.id} modifiers={ state.value === radio.value ? state.error ? 'radio--error' : state.success ? 'radio--success' : null : null } className={radio.className} style={radio.style} name={props.name} value={radio.value} disabled={state.disabled} readOnly={props.readOnly} required={props.required && index === 0} checked={state.value === radio.value} onChange={handleChange}> {radio.label} </OCRadio> )} </OCGridItem> ))} </OCGrid> <div className={prefix('radio-set__border')} /> {(state.error || state.success) && props.message && ( <span className={prefix('radio-set__message')}>{props.message}</span> )} </fieldset> ); } } OCRadioSet.propTypes = { radios: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string, className: PropTypes.string, style: PropTypes.object, value: PropTypes.string.isRequired, label: PropTypes.string.isRequired }) ).isRequired, name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disabled: PropTypes.bool, readOnly: PropTypes.bool, required: PropTypes.bool, message: PropTypes.string, value: PropTypes.string, onChange: PropTypes.func, modifiers: PropTypes.string, className: PropTypes.string, style: PropTypes.object }; OCRadioSet.defaultProps = { onChange: () => {} };
Elvis-rugamba/fan7-bn-backend
src/utils/event.util.js
/* eslint-disable import/no-cycle */ import EventEmitter from 'events'; import NotificationService from '../services/notification.service'; export const eventEmitter = new EventEmitter(); export default () => { eventEmitter.on('notification', NotificationService.send); };