text
stringlengths
2
1.04M
meta
dict
using Universal.Portable.Business; namespace Universal.Portable.Infrastructure.Interfaces { public interface ICypher { byte[] Encrypt(byte[] data, string key); byte[] Decrypt(byte[] data, string key); Key GenerateKeys(); } }
{ "content_hash": "6be944778c1b1692a7af5a4ce41d1e32", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 54, "avg_line_length": 23.818181818181817, "alnum_prop": 0.6603053435114504, "repo_name": "rnemtz/programming.net", "id": "7e872148c4bfe6dc0df4cb0344e94c0b9fe6ea7e", "size": "264", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "E33RMARTINEZHW11/Universal.Portable.Infrastructure/Interfaces/ICypher.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "992198" } ], "symlink_target": "" }
import COMMAND from '../../../session/command'; import FileListWrapper from './file-list-wrapper'; import * as Browser from '../../utils/browser'; import * as HiddenInfo from './hidden-info'; import Promise from 'pinkie'; import { GetUploadedFilesServiceMessage, StoreUploadedFilesServiceMessage } from '../../../typings/upload'; import Transport from '../../transport'; import nativeMethods from '../native-methods'; // NOTE: https://html.spec.whatwg.org/multipage/forms.html#fakepath-srsly. const FAKE_PATH_STRING = 'C:\\fakepath\\'; export default class UploadInfoManager { uploadInfo: any; constructor (private readonly _transport: Transport) { this.uploadInfo = []; } static _getFileListData (fileList) { const data = []; for (const file of fileList) data.push(file.base64); return data; } static formatValue (fileNames: string | string[]) { let value = ''; fileNames = typeof fileNames === 'string' ? [fileNames] : fileNames; if (fileNames && fileNames.length) { if (Browser.isWebKit) value = FAKE_PATH_STRING + fileNames[0].split('/').pop(); else return fileNames[0].split('/').pop(); } return value; } static getFileNames (fileList, value) { const result = []; if (fileList) { for (const file of fileList) result.push(file.name); } else if (value.lastIndexOf('\\') !== -1) result.push(value.substr(value.lastIndexOf('\\') + 1)); return result; } loadFilesInfoFromServer (filePaths: string | string[]) { return this._transport.asyncServiceMsg({ cmd: COMMAND.getUploadedFiles, filePaths: typeof filePaths === 'string' ? [filePaths] : filePaths } as GetUploadedFilesServiceMessage); } static prepareFileListWrapper (filesInfo) { const errs = []; const validFilesInfo = []; for (const fileInfo of filesInfo) { if (fileInfo.err) errs.push(fileInfo); else validFilesInfo.push(fileInfo); } return { errs: errs, fileList: new FileListWrapper(validFilesInfo) }; } sendFilesInfoToServer (fileList, fileNames) { return this._transport.asyncServiceMsg({ cmd: COMMAND.uploadFiles, data: UploadInfoManager._getFileListData(fileList), fileNames: fileNames } as StoreUploadedFilesServiceMessage); } clearUploadInfo (input) { const inputInfo = this.getUploadInfo(input); if (inputInfo) { /*eslint-disable no-restricted-properties*/ inputInfo.files = new FileListWrapper([]); inputInfo.value = ''; /*eslint-enable no-restricted-properties*/ return HiddenInfo.removeInputInfo(input); } return null; } getFiles (input) { const inputInfo = this.getUploadInfo(input); // eslint-disable-next-line no-restricted-properties return inputInfo ? inputInfo.files : new FileListWrapper([]); } getUploadInfo (input) { for (const uploadInfoItem of this.uploadInfo) { if (uploadInfoItem.input === input) return uploadInfoItem; } return null; } getValue (input) { const inputInfo = this.getUploadInfo(input); // eslint-disable-next-line no-restricted-properties return inputInfo ? inputInfo.value : ''; } loadFileListData (_input, fileList) { if (!fileList.length) return Promise.resolve(new FileListWrapper([])); return new Promise(resolve => { const fileReader = new FileReader(); const readedFiles = []; let index = 0; let file = fileList[index]; fileReader.addEventListener('load', (e: ProgressEvent<FileReader>) => { const info: any = { type: file.type, name: file.name }; if (typeof file.lastModified === 'number') info.lastModified = file.lastModified; if (file.lastModifiedDate) info.lastModifiedDate = file.lastModifiedDate; const dataUrl = nativeMethods.eventTargetGetter.call(e).result as string; readedFiles.push({ data: dataUrl.substr(dataUrl.indexOf(',') + 1), blob: file.slice(0, file.size), info }); if (fileList[++index]) { file = fileList[index]; fileReader.readAsDataURL(file); } else resolve(new FileListWrapper(readedFiles)); }); fileReader.readAsDataURL(file); }); } setUploadInfo (input, fileList, value) { let inputInfo = this.getUploadInfo(input); if (!inputInfo) { inputInfo = { input: input }; this.uploadInfo.push(inputInfo); } /*eslint-disable no-restricted-properties*/ inputInfo.files = fileList; inputInfo.value = value; /*eslint-enable no-restricted-properties*/ HiddenInfo.addInputInfo(input, fileList, value); } }
{ "content_hash": "78d19b5ea7d90c276fbb07acccb8fe69", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 107, "avg_line_length": 30.005434782608695, "alnum_prop": 0.555334178590835, "repo_name": "LavrovArtem/testcafe-hammerhead", "id": "d167c20c04c5d02801a2a9b8036b8068f777f31f", "size": "5521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/sandbox/upload/info-manager.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14668" }, { "name": "HTML", "bytes": "118637" }, { "name": "JavaScript", "bytes": "1373657" }, { "name": "Mustache", "bytes": "949" }, { "name": "Shell", "bytes": "485" }, { "name": "TypeScript", "bytes": "1115200" } ], "symlink_target": "" }
package com.indielist.web.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; /** * @author jsingh on 15-01-17. */ @Controller public class ManagementController { private static final Logger log = LogManager.getLogger(); }
{ "content_hash": "0da846461586cc4f253ed4092b149246", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 61, "avg_line_length": 23.285714285714285, "alnum_prop": 0.7760736196319018, "repo_name": "cointify/indielist", "id": "03f30aa57ec090bceade8133868522eb7d840fc5", "size": "326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "indie-web/src/main/java/com/indielist/web/controller/ManagementController.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "118794" }, { "name": "Java", "bytes": "27105" }, { "name": "JavaScript", "bytes": "40546" } ], "symlink_target": "" }
package svc import ( "context" "os" "path/filepath" "sync" "syscall" wsvc "golang.org/x/sys/windows/svc" ) // Create variables for svc and signal functions so we can mock them in tests var svcIsWindowsService = wsvc.IsWindowsService var svcRun = wsvc.Run type windowsService struct { i Service errSync sync.Mutex stopStartErr error isWindowsService bool signals []os.Signal Name string ctx context.Context } // Run runs an implementation of the Service interface. // // Run will block until the Windows Service is stopped or Ctrl+C is pressed if // running from the console. // // Stopping the Windows Service and Ctrl+C will call the Service's Stop method to // initiate a graceful shutdown. // // Note that WM_CLOSE is not handled (end task) and the Service's Stop method will // not be called. // // The sig parameter is to keep parity with the non-Windows API. Only syscall.SIGINT // (Ctrl+C) can be handled on Windows. Nevertheless, you can override the default // signals which are handled by specifying sig. func Run(service Service, sig ...os.Signal) error { var err error isWindowsService, err := svcIsWindowsService() if err != nil { return err } if len(sig) == 0 { sig = []os.Signal{syscall.SIGINT} } var ctx context.Context if s, ok := service.(Context); ok { ctx = s.Context() } else { ctx = context.Background() } ws := &windowsService{ i: service, isWindowsService: isWindowsService, signals: sig, ctx: ctx, } if ws.IsWindowsService() { // the working directory for a Windows Service is C:\Windows\System32 // this is almost certainly not what the user wants. dir := filepath.Dir(os.Args[0]) if err = os.Chdir(dir); err != nil { return err } } if err = service.Init(ws); err != nil { return err } return ws.run() } func (ws *windowsService) setError(err error) { ws.errSync.Lock() ws.stopStartErr = err ws.errSync.Unlock() } func (ws *windowsService) getError() error { ws.errSync.Lock() err := ws.stopStartErr ws.errSync.Unlock() return err } func (ws *windowsService) IsWindowsService() bool { return ws.isWindowsService } func (ws *windowsService) run() error { ws.setError(nil) if ws.IsWindowsService() { // Return error messages from start and stop routines // that get executed in the Execute method. // Guarded with a mutex as it may run a different thread // (callback from Windows). runErr := svcRun(ws.Name, ws) startStopErr := ws.getError() if startStopErr != nil { return startStopErr } if runErr != nil { return runErr } return nil } err := ws.i.Start() if err != nil { return err } signalChan := make(chan os.Signal, 1) signalNotify(signalChan, ws.signals...) select { case <-signalChan: case <-ws.ctx.Done(): } err = ws.i.Stop() return err } // Execute is invoked by Windows func (ws *windowsService) Execute(args []string, r <-chan wsvc.ChangeRequest, changes chan<- wsvc.Status) (bool, uint32) { const cmdsAccepted = wsvc.AcceptStop | wsvc.AcceptShutdown changes <- wsvc.Status{State: wsvc.StartPending} if err := ws.i.Start(); err != nil { ws.setError(err) return true, 1 } changes <- wsvc.Status{State: wsvc.Running, Accepts: cmdsAccepted} for { var c wsvc.ChangeRequest select { case c = <-r: case <-ws.ctx.Done(): c = wsvc.ChangeRequest{Cmd: wsvc.Stop} } switch c.Cmd { case wsvc.Interrogate: changes <- c.CurrentStatus case wsvc.Stop, wsvc.Shutdown: changes <- wsvc.Status{State: wsvc.StopPending} err := ws.i.Stop() if err != nil { ws.setError(err) return true, 2 } return false, 0 default: } } }
{ "content_hash": "559338223e6060c58d8a520657fee785", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 122, "avg_line_length": 21.958823529411763, "alnum_prop": 0.667827484596839, "repo_name": "judwhite/go-svc", "id": "b03c36b5c387c6729044a14fecc3f8c3f6b41bcd", "size": "3752", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "svc_windows.go", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "461" }, { "name": "Go", "bytes": "21872" }, { "name": "Shell", "bytes": "5160" } ], "symlink_target": "" }
<?php require_once BASE_PATH.'/modules/dicomextractor/constant/module.php'; /** Install the dicomextractor module. */ class Dicomextractor_InstallScript extends MIDASModuleInstallScript { /** @var string */ public $moduleName = 'dicomextractor'; /** Post database install. */ public function postInstall() { /** @var SettingModel $settingModel */ $settingModel = MidasLoader::loadModel('Setting'); $settingModel->setConfig(DICOMEXTRACTOR_DCM2XML_COMMAND_KEY, DICOMEXTRACTOR_DCM2XML_COMMAND_DEFAULT_VALUE, $this->moduleName); $settingModel->setConfig(DICOMEXTRACTOR_DCMJ2PNM_COMMAND_KEY, DICOMEXTRACTOR_DCMJ2PNM_COMMAND_DEFAULT_VALUE, $this->moduleName); $settingModel->setConfig(DICOMEXTRACTOR_DCMFTEST_COMMAND_KEY, DICOMEXTRACTOR_DCMFTEST_COMMAND_DEFAULT_VALUE, $this->moduleName); $settingModel->setConfig(DICOMEXTRACTOR_DCMDICTPATH_KEY, DICOMEXTRACTOR_DCMDICTPATH_DEFAULT_VALUE, $this->moduleName); } }
{ "content_hash": "c8d2fdee68f2fe3019f7e77915f4051a", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 136, "avg_line_length": 44.63636363636363, "alnum_prop": 0.7372708757637475, "repo_name": "jcfr/Midas", "id": "d622f0727cf9dfd88f33940f13d1942e7d48a978", "size": "1838", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/dicomextractor/database/InstallScript.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "4461" }, { "name": "CMake", "bytes": "105576" }, { "name": "CSS", "bytes": "237418" }, { "name": "HTML", "bytes": "523713" }, { "name": "Java", "bytes": "502251" }, { "name": "JavaScript", "bytes": "2381487" }, { "name": "PHP", "bytes": "3876121" }, { "name": "Python", "bytes": "109105" }, { "name": "Shell", "bytes": "798" } ], "symlink_target": "" }
<?php namespace Acme\StoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * EAVAttributeValue * * @ORM\Table() * @ORM\Entity */ class EAVAttributeValue { /** * @var string * * @ORM\Id * @ORM\Column(name="ValueId", type="string", length=32) * @ORM\GeneratedValue(strategy="NONE") */ private $ValueId; /** * @var integer * * @ORM\Column(name="AttributeId", type="integer", length=11) */ private $AttributeId; /** * @var integer * * @ORM\Column(name="AttributeSetId", type="integer", length=11) */ private $AttributeSetId; /** * @var string * * @ORM\Column(name="Value", type="string", length=255) */ private $Value; /** * @ORM\ManyToOne(targetEntity="EAVEntity", inversedBy="attributes") * @ORM\JoinColumn(name="EntityId", referencedColumnName="EntityId") */ private $entity; /** * @ORM\ManyToOne(targetEntity="MetaEAVAttribute", inversedBy="values") * @ORM\JoinColumn(name="AttributeId", referencedColumnName="AttributeId") */ private $attributeMeta; /** * @ORM\ManyToOne(targetEntity="MetaEAVAttributeSet", inversedBy="values") * @ORM\JoinColumn(name="AttributeSetId", referencedColumnName="AttributeSetId") */ private $attributeSetMeta; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set ValueId * * @param \char $valueId * @return EAVAttributeValue */ public function setValueId($valueId) { $this->ValueId = $valueId; return $this; } /** * Get ValueId * * @return \char */ public function getValueId() { return $this->ValueId; } /** * Set AttributeId * * @param \int $attributeId * @return EAVAttributeValue */ public function setAttributeId($attributeId) { $this->AttributeId = $attributeId; return $this; } /** * Get AttributeId * * @return \int */ public function getAttributeId() { return $this->AttributeId; } /** * Set Value * * @param \varchar $value * @return EAVAttributeValue */ public function setValue($value) { $this->Value = $value; return $this; } /** * Get Value * * @return \varchar */ public function getValue() { return $this->Value; } /** * Set entity * * @param \Acme\StoreBundle\Entity\EAVEntity $entity * @return EAVAttributeValue */ public function setEntity(\Acme\StoreBundle\Entity\EAVEntity $entity = null) { $this->entity = $entity; return $this; } /** * Get entity * * @return \Acme\StoreBundle\Entity\EAVEntity */ public function getEntity() { return $this->entity; } /** * Set attributeMeta * * @param \Acme\StoreBundle\Entity\MetaEAVAttribute $attributeMeta * @return EAVAttributeValue */ public function setAttributeMeta(\Acme\StoreBundle\Entity\MetaEAVAttribute $attributeMeta = null) { $this->attributeMeta = $attributeMeta; return $this; } /** * Get attributeMeta * * @return \Acme\StoreBundle\Entity\MetaEAVAttribute */ public function getAttributeMeta() { return $this->attributeMeta; } /** * Set attributeSetMeta * * @param \Acme\StoreBundle\Entity\MetaEAVAttributeSet $attributeSetMeta * @return EAVAttributeValue */ public function setAttributeSetMeta(\Acme\StoreBundle\Entity\MetaEAVAttributeSet $attributeSetMeta = null) { $this->attributeSetMeta = $attributeSetMeta; return $this; } /** * Get attributeSetMeta * * @return \Acme\StoreBundle\Entity\MetaEAVAttributeSet */ public function getAttributeSetMeta() { return $this->attributeSetMeta; } /** * Set AttributeSetId * * @param integer $attributeSetId * @return EAVAttributeValue */ public function setAttributeSetId($attributeSetId) { $this->AttributeSetId = $attributeSetId; return $this; } /** * Get AttributeSetId * * @return integer */ public function getAttributeSetId() { return $this->AttributeSetId; } }
{ "content_hash": "0965496887740c3a0c5e06c65e90641f", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 110, "avg_line_length": 19.61802575107296, "alnum_prop": 0.5633340625683658, "repo_name": "goranpavlovic/TvProgramApp", "id": "450574c84004c406638c4fef59898bf74e121348", "size": "4571", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Acme/StoreBundle/Entity/EAVAttributeValue.php", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "541508" }, { "name": "PHP", "bytes": "155479" }, { "name": "Perl", "bytes": "1091" }, { "name": "Shell", "bytes": "248" } ], "symlink_target": "" }
set -ue docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD" docker build -t kontena/haproxy:latest . docker push kontena/haproxy:latest
{ "content_hash": "078284d70795543acc30d93daeebabe7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 56, "avg_line_length": 23.666666666666668, "alnum_prop": 0.7605633802816901, "repo_name": "kontena/kontena-haproxy", "id": "f28a8a8d62f2c60f2b407b4d59b17ed98220be50", "size": "154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/latest.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "26050" }, { "name": "Shell", "bytes": "803" } ], "symlink_target": "" }
raise "only works with 1 Coordinator" if Coordinator.count != 1 coordinator = Coordinator.last Assignment.update_all coordinator_id: coordinator.id Contract.update_all coordinator_id: coordinator.id
{ "content_hash": "a2c52b72834f1cb2ca80a0735b147f0b", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 63, "avg_line_length": 33.5, "alnum_prop": 0.8109452736318408, "repo_name": "oraclekit/smart_oracle", "id": "dc1efd3568eca1ce4ecf4e89c919dbafa003f8a3", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "script/161025_associate_coordinator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "826" }, { "name": "HTML", "bytes": "6007" }, { "name": "JavaScript", "bytes": "638" }, { "name": "Ruby", "bytes": "442357" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if !defined(DISABLE_SPARSE_TENSORS) #pragma once #include "core/framework/data_types.h" #include "core/framework/tensor_shape.h" #include "core/framework/tensor.h" struct OrtValue; namespace onnxruntime { class IDataTransfer; class DataTransferManager; /** * @brief This is a Sparse Format enumeration * * */ enum class SparseFormat : uint32_t { kUndefined = 0x0U, // For completeness kCoo = 0x1U, // 1-D or 2-D indices kCsrc = 0x1U << 1, // Both CSR(C) kBlockSparse = 0x1U << 2 // as in OpenAI }; std::ostream& operator<<(std::ostream&, SparseFormat); /** * @brief This class implements SparseTensor. * This class holds sparse non-zero data (values) and sparse format * specific indices. There are two main uses for the class (similar to that of Tensor) * - one is to re-present model sparse inputs. Such inputs typically reside * in user allocated buffers that are not owned by SparseTensor instance and the instance * serves as a facade to expose user allocated buffers. Such buffers should already * contain proper values and format specific indices. * Use the first constructor * to instantiate SparseTensor and supply values_data pointer. Use*() functions can * be used to supply pointers to format specific indices. These buffers are used as is * and will not be modified or deallocated by the instance. However, the lifespan of the buffers * must eclipse the lifespan of the SparseTensor instance. * * - Represent sparse data that is a result of format conversion or a computation result. Use second constructor * to supply a desired allocator. Use Make*() format specific interfaces to supply values and format * specific indices. The specified data will be copied into an internally allocated buffer. Internally, we will represent a SparseTensor as a single contiguous buffer that * contains values followed by format specific indices. We use Tensors to project * values and indices into various parts of buffer. */ class SparseTensor final { public: /// <summary> /// This constructs an instance that points to user defined buffers. /// Make use of Use* functions to supply format specific indices that /// reside in the user supplied buffers. The instance constructed this way /// will not copy data. The lifespan of supplied buffers is expected to eclipse /// the lifespan of the sparse tensor instance. /// </summary> /// <param name="elt_type">MlDataType</param> /// <param name="dense_shape">a shape of original tensor in dense form</param> /// <param name="values_shape">shape for user supplied values. Use {0} shape for fully sparse tensors.</param> /// <param name="values_data">a pointer to values. Use nullptr for fully sparse tensors.</param> /// <param name="location">description of the user allocated memory</param> SparseTensor(MLDataType elt_type, const TensorShape& dense_shape, const TensorShape& values_shape, void* values_data, const OrtMemoryInfo& location); /// <summary> /// Use this constructor to hold sparse data in the buffer /// allocated with the specified allocator. Use Make*() methods /// to populate the instance with data which will be copied into the /// allocated buffer. /// </summary> /// <param name="elt_type"></param> /// <param name="dense_shape"></param> /// <param name="allocator"></param> SparseTensor(MLDataType elt_type, const TensorShape& dense_shape, std::shared_ptr<IAllocator> allocator); SparseTensor() noexcept; ~SparseTensor(); ORT_DISALLOW_COPY_AND_ASSIGNMENT(SparseTensor); /// <summary> /// The factory function creates an instance of SparseTensor on the heap /// using appropriate constructor and initializes OrtValue instance wit it. /// </summary> /// <param name="elt_type">element data type</param> /// <param name="dense_shape">dense shape of the sparse tensor</param> /// <param name="values_shape">values shape. Use {0} for fully sparse tensors.</param> /// <param name="values_data">pointer to a user allocated buffer. Use nullptr for fully sparse tensors.</param> /// <param name="location">description of the user allocated buffer</param> /// <param name="ort_value">default constructed input/output ort_value</param> static void InitOrtValue(MLDataType elt_type, const TensorShape& dense_shape, const TensorShape& values_shape, void* values_data, const OrtMemoryInfo& location, OrtValue& ort_value); /// <summary> /// The factory function creates an instance of SparseTensor on the heap /// using appropriate constructor and initializes OrtValue instance wit it. /// </summary> /// <param name="elt_type">element data type</param> /// <param name="dense_shape">dense shape of the sparse tensor</param> /// <param name="allocator">allocator to use</param> /// <param name="ort_value">default constructed input/output ort_value</param> static void InitOrtValue(MLDataType elt_type, const TensorShape& dense_shape, std::shared_ptr<IAllocator> allocator, OrtValue& ort_value); /// <summary> /// The function will check if the OrtValue is allocated /// fetch the containing SparseTensor instance or throw if it /// does not contain one. It will check that the SparseTensor has /// sparse format set (i.e. fully constructed). /// </summary> /// <param name="v">OrtValue instance</param> /// <returns>const SparseTensor Reference</returns> static const SparseTensor& GetSparseTensorFromOrtValue(const OrtValue& v); /// <summary> /// /// The function will check if the OrtValue is allocated /// fetch the containing SparseTensor instance or throw if it /// does not contain one. It will check that the SparseTensor does not /// have sparse format set and will return non-const ref to so indices /// can be added to it. /// </summary> /// <param name="v">OrtValue</param> /// <returns>non-const reference to SparseTensor</returns> static SparseTensor& GetSparseTensorFromOrtValue(OrtValue& v); /// <summary> // Returns the number of non-zero values (aka "NNZ") // For block sparse formats this may include some zeros in the blocks // are considered non-zero. /// </summary> /// <returns>nnz</returns> size_t NumValues() const { return static_cast<size_t>(values_.Shape().Size()); } /// <summary> /// Read only accessor to non-zero values /// </summary> /// <returns></returns> const Tensor& Values() const noexcept { return values_; } SparseTensor(SparseTensor&& o) noexcept; SparseTensor& operator=(SparseTensor&& o) noexcept; /// <summary> /// Returns SparseFormat that the instance currently holds /// if the value returned in kUndefined, the instance is not populated /// </summary> /// <returns>format enum</returns> SparseFormat Format() const noexcept { return format_; } /// <summary> /// Returns a would be dense_shape /// </summary> /// <returns>reference to dense_shape</returns> const TensorShape& DenseShape() const noexcept { return dense_shape_; } /// <summary> /// Calculates and returns how much this fully initialized SparseTensor data (would) /// occupy in a contiguous allocation block, or, in fact, occupies if it owns the buffer. /// </summary> /// <returns>required allocation size</returns> int64_t RequiredAllocationSize() const noexcept; /// <summary> /// Returns Tensor element type enum. /// Useful for type dispatching /// </summary> /// <returns></returns> int32_t GetElementType() const { return ml_data_type_->GetDataType(); } /// <summary> /// Return Element MLDataType /// </summary> /// <returns></returns> MLDataType DataType() const noexcept { return ml_data_type_; } /// <summary> /// Test for string type /// </summary> /// <returns>true if tensor values are strings</returns> bool IsDataTypeString() const { return utils::IsPrimitiveDataType<std::string>(ml_data_type_); } /// <summary> /// Checks if the Tensor contains data type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns>true if tensor contains data of type T</returns> template <class T> bool IsDataType() const { return utils::IsPrimitiveDataType<T>(ml_data_type_); } const OrtMemoryInfo& Location() const noexcept { return location_; } /// <summary> /// Read only access to Coo indices /// </summary> class CooView { public: explicit CooView(const Tensor& indices) noexcept : indices_(indices) {} const Tensor& Indices() const noexcept { return indices_; } private: std::reference_wrapper<const Tensor> indices_; }; /// <summary> /// Returns Coo index view /// </summary> /// <returns>CooView instance</returns> CooView AsCoo() const; /// <summary> /// Uses COO index contained in the user allocated buffer along with the values buffer passed on /// to the constructor. The buffer is used as is and its lifespan must eclipse the lifespan of the sparse /// tensor instance. The OrtMemoryInfo (location) of the index is assumed to be the same as values. /// /// The index size must either exactly match the number of values in which case /// index shape would be 1-D (values_count) or it must be twice the number of values /// in which case its shape would be 2-D (values_count, 2) /// </summary> /// <param name="indices">user allocated buffer span. Use empty span for fully sparse tensors.</param> /// <returns>Status</returns> Status UseCooIndices(gsl::span<int64_t> indices); /// <summary> /// The method allocates a single contiguous buffer and copies specified values /// and indices into it using supplied IDataTransfer. /// /// The indices size must either exactly match the number of values in which case /// indices shape would be 1-D (values_count) or it must be twice the number of values /// in which case its shape would be 2-D (values_count, 2). /// /// Values shape is supplied at construction time and its Size() must match values_count. /// </summary> /// <param name="values_count">Use 0 for fully sparse tensors.</param> /// <param name="values_data">pointer to a buffer to be copied. Use nullptr for fully sparse tensors.</param> /// <param name="indices"></param> /// <returns></returns> Status MakeCooData(const IDataTransfer& data_transfer, const OrtMemoryInfo& data_location, size_t values_count, const void* values_data, gsl::span<const int64_t> indices); /// <summary> /// The method allocates a single contiguous buffer and creates instances of std::strings in it, with /// copies of the supplied zero-terminated strings followed by COO indices. /// All data is assumed to be on CPU and the allocator supplied must be /// a CPU based allocator. /// </summary> /// <param name="string_count">use 0 for fully sparse tensors</param> /// <param name="strings">array of char* pointers. use nullptr for fully sparse tensors</param> /// <param name="indices">span of indices. Use empty span for fully sparse tensors.</param> /// <returns>Status</returns> Status MakeCooStrings(size_t string_count, const char* const* strings, gsl::span<const int64_t> indices); /// <summary> /// Gives mutable access to Coo buffers so they can be populated /// </summary> class CooMutator { public: CooMutator(Tensor& values, Tensor& indices) noexcept : values_(values), indices_(indices) {} Tensor& Values() noexcept { return values_; } Tensor& Indices() noexcept { return indices_; } private: std::reference_wrapper<Tensor> values_; std::reference_wrapper<Tensor> indices_; }; /// <summary> /// Allocates memory for values and index and returns a mutator so /// data can be copied into the buffer. /// </summary> /// <param name="values_count">use 0 for fully sparse tensors</param> /// <param name="index_count">use 0 for fully sparse tensors</param> /// <returns></returns> CooMutator MakeCooData(size_t values_count, size_t index_count); /// <summary> /// Read only access to Csr indices /// </summary> class CsrView { public: CsrView(const Tensor& inner, const Tensor& outer) noexcept : inner_(inner), outer_(outer) {} const Tensor& Inner() const noexcept { return inner_; } const Tensor& Outer() const noexcept { return outer_; } private: std::reference_wrapper<const Tensor> inner_; std::reference_wrapper<const Tensor> outer_; }; /// <summary> /// Returns Csr indices read only view /// </summary> /// <returns></returns> CsrView AsCsr() const; /// <summary> /// This function will use Csr indices contained within the user allocated buffers. /// The lifespan of the buffers must eclipse the lifespan of sparse tensor instance. /// </summary> /// <param name="inner_index">User allocated buffer span. use empty span for fully sparse tensors</param> /// <param name="outer_index">User allocated buffer span. Use empty span for fully sparse tensors</param> /// <returns></returns> Status UseCsrIndices(gsl::span<int64_t> inner_index, gsl::span<int64_t> outer_index); /// <summary> /// The function will allocate a single contiguous buffer and will copy values /// and indices into it. /// </summary> /// <param name="data_transfer"></param> /// <param name="data_location"></param> /// <param name="values_count">use 0 for fully sparse tensors</param> /// <param name="values_data">pointer to data to be copied. Use nullptr for fully sparse tensors.</param> /// <param name="inner_index">inner index to be copied. Use empty span for fully sparse tensors.</param> /// <param name="outer_index">outer index to be copied. Use empty span for fully sparse tensors.</param> /// <returns></returns> Status MakeCsrData(const IDataTransfer& data_transfer, const OrtMemoryInfo& data_location, size_t values_count, const void* values_data, gsl::span<const int64_t> inner_index, gsl::span<const int64_t> outer_index); /// <summary> /// The method allocates a single contiguous buffer and creates instances of std::strings in it, with /// copies of the supplied zero-terminated strings followed by COO indices. /// All data is assumed to be on CPU and the allocator supplied must be /// a CPU based allocator /// </summary> /// <param name="string_count"></param> /// <param name="strings">array of char* pointers</param> /// <param name="inner_index">inner index to be copied. Use empty span for fully sparse tensors.</param> /// <param name="outer_index">outer index to be copied. Use empty span for fully sparse tensors.</param> /// <returns></returns> Status MakeCsrStrings(size_t string_count, const char* const* strings, gsl::span<const int64_t> inner_index, gsl::span<const int64_t> outer_index); /// <summary> /// Give writable access to Csr values and indices /// </summary> class CsrMutator { public: CsrMutator(Tensor& values, Tensor& inner, Tensor& outer) noexcept : values_(values), inner_(inner), outer_(outer) {} Tensor& Values() const noexcept { return values_; } Tensor& Inner() const noexcept { return inner_; } Tensor& Outer() const noexcept { return outer_; } private: std::reference_wrapper<Tensor> values_; std::reference_wrapper<Tensor> inner_; std::reference_wrapper<Tensor> outer_; }; /// <summary> /// Allocates memory for values and index and returns mutator so /// data can be populated. /// </summary> /// <param name="values_count">Use 0 for fully sparse tensors.</param> /// <param name="inner_index_count">Use 0 for fully sparse tensors.</param> /// <param name="outer_index_count">Use 0 for fully sparse tensors.</param> /// <returns></returns> CsrMutator MakeCsrData(size_t values_count, size_t inner_index_count, size_t outer_index_count); /// <summary> /// Read only access to BlockSparse index /// </summary> class BlockSparseView { public: explicit BlockSparseView(const Tensor& indices) noexcept : indices_(indices) {} const Tensor& Indices() const noexcept { return indices_; } private: std::reference_wrapper<const Tensor> indices_; }; /// <summary> /// Return BlockSparseIndex view /// </summary> /// <returns>an instance of BlockSparseView</returns> BlockSparseView AsBlockSparse() const; /// <summary> /// Use blocksparse indices contained in the user allocated buffer. The shape of the index /// must be 2-D and must contain one tuple per each of the value blocks that /// were supplied to the constructor. The supplied buffer lifespan must eclipse the life /// of sparse tensor instance. /// </summary> /// <param name="indices_shape">Use {0} for fully sparse tensors.</param> /// <param name="indices_data">Ptr to user allocated buffer. Use nullptr for fully spare tensors.</param> /// <returns></returns> Status UseBlockSparseIndices(const TensorShape& indices_shape, int32_t* indices_data); /// <summary> /// The function allocates a single contiguous buffer and copies values and index /// into it. The shape of the values is expected to be at least 3-D but may contain more /// dimensions. At the very minimum it should be (num_blocks, block_size, block_size). /// // The shape of the index is must be at least 2-D and must contain one tuple per each of // the value blocks that were supplied to the constructor. Each index tuple is a // (row, col) coordinates of the values block in a dense matrix. /// </summary> /// <param name="data_transfer"></param> /// <param name="data_location"></param> /// <param name="values_shape">The shape is expected to be at least 3-D. However, use {0} for fully sparse tensors.</param> /// <param name="values_data">Pointer to a data to be copied. Use nullptr for fully sparse tensors.</param> /// <param name="indices_shape">The shape is expected to be 2-D. However, you can use {0} for fully sparse tensors.</param> /// <param name="indices_data">Pointer to index data to be copied. Use nullptr for fully sparse tensors.</param> /// <returns></returns> Status MakeBlockSparseData(const IDataTransfer& data_transfer, const OrtMemoryInfo& data_location, const TensorShape& values_shape, const void* values_data, const TensorShape& indices_shape, const int32_t* indices_data); /// <summary> /// The method allocates a single contiguous buffer and creates instances of std::strings in it, with /// copies of the supplied zero-terminated strings followed by COO indices. /// All data is assumed to be on CPU and the allocator supplied must be /// a CPU based allocator. /// </summary> /// <param name="values_shape">Use {0} shape for fully sparse tensors</param> /// <param name="strings">array of char* ptrs, use nullptr for fully sparse tensor</param> /// <param name="indices_shape">Use {0} for fully sparse tensors</param> /// <param name="indices_data">use nullptr for fully sparse tensors</param> /// <returns></returns> Status MakeBlockSparseStrings(const TensorShape& values_shape, const char* const* strings, const TensorShape& indices_shape, const int32_t* indices_data); /// <summary> /// Mutable data access /// </summary> class BlockSparseMutator { public: BlockSparseMutator(Tensor& values, Tensor& indices) noexcept : values_(values), indices_(indices) {} Tensor& Values() noexcept { return values_; } Tensor& Indices() noexcept { return indices_; } private: std::reference_wrapper<Tensor> values_; std::reference_wrapper<Tensor> indices_; }; /// <summary> /// Allocates memory for values and index and returns mutator so /// data can be populated /// </summary> /// <param name="values_shape">Shape is expected to be 3-D, use {0} for fully sparse tensors</param> /// <param name="indices_shape">Shape is expected to be 2-D, use {0} for fully sparse tensors </param> /// <returns></returns> BlockSparseMutator MakeBlockSparseData(const TensorShape& values_shape, const TensorShape& indices_shape); /// <summary> /// X-device copy. Destination tensor must have allocator set. /// </summary> /// <param name="data_transfer_manager"></param> /// <param name="exec_q_id"></param> /// <param name="dst_tensor"></param> /// <returns></returns> Status Copy(const DataTransferManager& data_transfer_manager, int exec_q_id, SparseTensor& dst_tensor) const; /// <summary> /// X-device copy. Destination tensor must have allocator set. /// </summary> /// <param name="dst_tensor"></param> /// <returns></returns> Status Copy(const IDataTransfer& data_transfer, SparseTensor& dst_tensor, int exec_q_id) const; private: Status AllocateBuffer(int64_t buffer_size, size_t num_values); void ReleaseBuffer(); void* IndicesStart(int64_t values_bytes); const void* IndicesStart(int64_t values_bytes) const; Status ValidateBlockSparseShapes(const TensorShape& values_shape, const TensorShape& index_shape) const; std::vector<int64_t> GetCooIndexDims(size_t values_count, size_t index_size) const; void InitCooIndex(const TensorShape& index_shape, int64_t* index_data); Status ValidateCsrIndices(size_t values_count, size_t inner_size, size_t outer_size) const; void InitCsrIndices(size_t inner_size, const int64_t* inner, size_t outer_size, const int64_t* outer); void InitBlockSparseIndices(const TensorShape& indices_shape, int32_t* indices_data); SparseFormat format_; // sparse format enum value TensorShape dense_shape_; // a shape of a corresponding dense tensor const PrimitiveDataTypeBase* ml_data_type_; // MLDataType for contained values AllocatorPtr allocator_; // Allocator or nullptr when using user supplied buffers OrtMemoryInfo location_; // Memory info where data resides. When allocator is supplied, // location_ is obtained from the allocator. void* p_data_; // Allocated buffer ptr, or nullptr when using user supplied buffers int64_t buffer_size_; // Allocated buffer size or zero when using user supplied buffers. Tensor values_; // Tensor instance that holds a values buffer information either user supplied or // to a beginning of p_data_, before format specific indices. std::vector<Tensor> format_data_; // A collection of format specific indices. They contain pointers to either a // user supplied buffers or to portions of contiguous buffer p_data_. }; } // namespace onnxruntime #endif
{ "content_hash": "c6c6f561a2fcd5b198495177fa0b87a1", "timestamp": "", "source": "github", "line_count": 534, "max_line_length": 128, "avg_line_length": 43.87265917602996, "alnum_prop": 0.6762421034659382, "repo_name": "microsoft/onnxruntime", "id": "fa1ad2771117f42590c9efb7f1b9c57a6b9304d7", "size": "23428", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "include/onnxruntime/core/framework/sparse_tensor.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1763425" }, { "name": "Batchfile", "bytes": "17040" }, { "name": "C", "bytes": "955390" }, { "name": "C#", "bytes": "2304597" }, { "name": "C++", "bytes": "39435305" }, { "name": "CMake", "bytes": "514764" }, { "name": "CSS", "bytes": "138431" }, { "name": "Cuda", "bytes": "1104338" }, { "name": "Dockerfile", "bytes": "8089" }, { "name": "HLSL", "bytes": "11234" }, { "name": "HTML", "bytes": "5933" }, { "name": "Java", "bytes": "418665" }, { "name": "JavaScript", "bytes": "212575" }, { "name": "Jupyter Notebook", "bytes": "218327" }, { "name": "Kotlin", "bytes": "4653" }, { "name": "Liquid", "bytes": "5457" }, { "name": "NASL", "bytes": "2628" }, { "name": "Objective-C", "bytes": "151027" }, { "name": "Objective-C++", "bytes": "107084" }, { "name": "Pascal", "bytes": "9597" }, { "name": "PowerShell", "bytes": "16419" }, { "name": "Python", "bytes": "5041661" }, { "name": "Roff", "bytes": "27539" }, { "name": "Ruby", "bytes": "3545" }, { "name": "Shell", "bytes": "116513" }, { "name": "Swift", "bytes": "115" }, { "name": "TypeScript", "bytes": "973087" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>axiomatic-abp: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.11.dev / axiomatic-abp - dev</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> axiomatic-abp <small> dev <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-14 07:23:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-14 07:23:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.0 Official release 4.10.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;dev@clarus.me&quot; homepage: &quot;https://github.com/coq-contribs/axiomatic-abp&quot; license: &quot;Proprietary&quot; build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;Make&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/AxiomaticABP&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {= &quot;dev&quot;} ] tags: [ &quot;keyword:alternating bit protocol&quot; &quot;keyword:process calculi&quot; &quot;keyword:reactive systems&quot; &quot;category:Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols&quot; ] authors: [ &quot;Jan Friso Groote &lt;&gt;&quot; ] synopsis: &quot;Verification of an axiomatisation of the Alternating Bit Protocol.&quot; description: &quot;&quot;&quot; The Alternating Bit Protocol is expressed in an axiomatized calculi of process. Correctness is proven.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;git+https://github.com/coq-contribs/axiomatic-abp.git#master&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-axiomatic-abp.dev coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - coq-axiomatic-abp -&gt; coq &gt;= dev Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-axiomatic-abp.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "c75ab7e4f186db9484e3f0075e51dae1", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 232, "avg_line_length": 41.07878787878788, "alnum_prop": 0.5441133077604013, "repo_name": "coq-bench/coq-bench.github.io", "id": "d0ae290c0a525ea4c5cead9a1b317e2dda4e8c6f", "size": "6780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.0-2.0.6/extra-dev/8.11.dev/axiomatic-abp/dev.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package db import ( "testing" . "github.com/smartystreets/goconvey/convey" "github.com/jojopoper/horizon/test" ) func TestCoreOfferPageByAddressQuery(t *testing.T) { test.LoadScenario("trades") Convey("CoreOfferPageByAddressQuery", t, func() { makeQuery := func(c string, o string, l int32, a string) CoreOfferPageByAddressQuery { pq, err := NewPageQuery(c, o, l) So(err, ShouldBeNil) return CoreOfferPageByAddressQuery{ SqlQuery: SqlQuery{core}, PageQuery: pq, Address: a, } } var records []CoreOfferRecord Convey("works with native offers", func() { MustSelect(ctx, makeQuery("", "asc", 0, "GCXKG6RN4ONIEPCMNFB732A436Z5PNDSRLGWK7GBLCMQLIFO4S7EYWVU"), &records) So(len(records), ShouldEqual, 1) }) Convey("filters properly", func() { MustSelect(ctx, makeQuery("", "desc", 0, "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H"), &records) So(len(records), ShouldEqual, 0) MustSelect(ctx, makeQuery("", "asc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &records) So(len(records), ShouldEqual, 3) }) Convey("orders properly", func() { // asc orders ascending by id MustSelect(ctx, makeQuery("", "asc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &records) So(records, ShouldBeOrderedAscending, func(r interface{}) int64 { So(r, ShouldHaveSameTypeAs, CoreOfferRecord{}) return r.(CoreOfferRecord).OfferID }) // desc orders descending by id MustSelect(ctx, makeQuery("", "desc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &records) So(records, ShouldBeOrderedDescending, func(r interface{}) int64 { So(r, ShouldHaveSameTypeAs, CoreOfferRecord{}) return r.(CoreOfferRecord).OfferID }) }) Convey("limits properly", func() { // returns number specified MustSelect(ctx, makeQuery("", "asc", 2, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &records) So(len(records), ShouldEqual, 2) // returns all rows if limit is higher MustSelect(ctx, makeQuery("", "asc", 10, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &records) So(len(records), ShouldEqual, 3) }) Convey("cursor works properly", func() { var record CoreOfferRecord // lowest id if ordered ascending and no cursor MustGet(ctx, makeQuery("", "asc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &record) So(record.OfferID, ShouldEqual, 1) // highest id if ordered descending and no cursor MustGet(ctx, makeQuery("", "desc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &record) So(record.OfferID, ShouldEqual, 3) // starts after the cursor if ordered ascending MustGet(ctx, makeQuery("1", "asc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &record) So(record.OfferID, ShouldEqual, 2) // starts before the cursor if ordered descending MustGet(ctx, makeQuery("3", "desc", 0, "GA5WBPYA5Y4WAEHXWR2UKO2UO4BUGHUQ74EUPKON2QHV4WRHOIRNKKH2"), &record) So(record.OfferID, ShouldEqual, 2) }) }) }
{ "content_hash": "c800d9c94507499de9fb198e3e5de9b4", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 114, "avg_line_length": 33.934065934065934, "alnum_prop": 0.7240932642487047, "repo_name": "jojopoper/horizon", "id": "7abd638f01ab52b22244c48a47dfd60f7027aff3", "size": "3088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/github.com/jojopoper/horizon/db/query_core_offer_page_by_address_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "API Blueprint", "bytes": "18901" }, { "name": "Go", "bytes": "255792" }, { "name": "Ruby", "bytes": "1672" }, { "name": "Shell", "bytes": "743" } ], "symlink_target": "" }
- Ensure the bug was not already reported by searching on GitHub under [Issues](https://github.com/3runoDesign/setRobot/issues). - If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/3runoDesign/setRobot/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring. ### Did you write a patch that fixes a bug or do you intend to add a new feature or change an existing one? - Open a new GitHub pull request with the patch. - Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. Thanks! ❤️ ❤️ ❤️
{ "content_hash": "fd7c37e13c198d9dba6b103683f654b0", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 184, "avg_line_length": 69.45454545454545, "alnum_prop": 0.7709424083769634, "repo_name": "3runoDesign/setRobot", "id": "ae27be7b3d07b4453dbbf7c800f5fbb70c10f8c1", "size": "834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4512" }, { "name": "HTML", "bytes": "29890" }, { "name": "JavaScript", "bytes": "2215" }, { "name": "PHP", "bytes": "61249" }, { "name": "Vue", "bytes": "2309" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Evo C++ Library v0.5.1: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Evo C++ Library v0.5.1 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',false,false,'search.php','Search'); }); </script> <div id="main-nav"></div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceevo.html">evo</a></li><li class="navelem"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">SysNativeTimeStamp Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#aa5771d3c6c1b377e6cd5a03d206c163a">convert_local_dt</a>(DT &amp;dt) const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a31a2941a584a4757fa06a5fb9a8f60e1">convert_local_dt_notz</a>(DT &amp;dt) const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#acb1ed9f184bebbf3c0d1e8dea0920ab9">convert_utc_dt</a>(DT &amp;dt) const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a197de777de01192951a3f41b36fe8541">Fields</a> typedef</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#aba6f1a7b947b9ae82b74e7be9d55926d">get_msec</a>() const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a4bdfc558eb739ae986073dc235115899">get_nsec</a>() const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#ad578dd53740c42cff3ca6146cfd1ac7c">get_unix_timestamp</a>() const</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a0ee90ee0d39d5b2fa777c66b92f181de">operator=</a>(const SysNativeTimeStamp &amp;src)</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#ac1db9d194d6552f16dba2d9f925b2bd2">SEC_PER_MIN</a></td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a62bbebcdc34a8056c32d0b1a26026717">set</a>()</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#afbffbd03d61af6e98e7005797210fb0f">set_utc</a>()</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#acf886dc16242f7bb334d31258dac2ff3">SysNativeTimeStamp</a>()</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a64c7947ed0290e2b5ec1d6e3207bf276">SysNativeTimeStamp</a>(const SysNativeTimeStamp &amp;src)</td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html#a21be78b2818c91cb205885b8a6f5aed8">ts</a></td><td class="entry"><a class="el" href="structevo_1_1_sys_native_time_stamp.html">SysNativeTimeStamp</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue May 7 2019 18:17:44 for Evo C++ Library v0.5.1 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
{ "content_hash": "779c99e3e1213a8138a4028fc01cc8ea", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 364, "avg_line_length": 93.42465753424658, "alnum_prop": 0.7042521994134897, "repo_name": "jlctools/evo", "id": "f32f87f8d7596cbe2edc2d9f1ba4c2b04bf9742a", "size": "6820", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/evo-0.5.1/html/structevo_1_1_sys_native_time_stamp-members.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "646" }, { "name": "C++", "bytes": "2559085" }, { "name": "Shell", "bytes": "708" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>{% block title %}{{ page_title|default(_('Project')) }}{% endblock %}</title> <meta name="description" content="Fbone (Flask bone) is a Flask (Python microframework) template/bootstrap/boilerplate application."> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="Shortcut Icon" href="{{ url_for('static', filename='img/favicon.png') }}" type="image/x-icon"> {% block css %} {% assets "css_all" -%} <link rel="stylesheet" href="{{ ASSET_URL }}"> {%- endassets %} {% endblock %} {% block css_style %} {% endblock %} {% block js_top %} <script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script> <script type="text/javascript"> var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script> {% endblock %} </head> <body> {% include "macros/_ask_user_to_update_ie.html" %} {% block topbar %} <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{ url_for('frontend.index') }}">Manekineko</a> </div> {% if current_user.is_authenticated() %} <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type='text' class="form-control" name='keywords' value='{{ keywords|default('') }}' placeholder='Search' /> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <div class="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> {% if current_user.is_admin() %} <li><a href="{{ url_for('admin.index') }}">{{ current_user.name }}</a></li> {% else %} <li><a href="{{ url_for('user.index') }}">{{ current_user.name }}</a></li> {% endif %} <li><a href="{{ url_for('settings.profile') }}">{{_('Settings')}}</a></li> <li><a href="{{ url_for('frontend.logout') }}">{{_('Log out')}}</a></li> </ul> </div> {% else %} <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="{{ url_for('frontend.signup') }}">{{_('Sign up')}}</a></li> <li><a href="{{ url_for('frontend.login') }}">{{_('Sign in')}}</a></li> </ul> </div><!--/.nav-collapse --> {% endif %} </div> </nav> {% endblock %} {% block container %} <div class="container"> <div class="page-header"> {% block body %} {% endblock %} </div> </div> {% endblock %} <footer class="footer"> <ul class="footer-links"> <li>{{_('&copy;')}}</li> <li><a href='https://github.com/frankV/manekineko'>{{_('About')}}</a></li> <li class="muted">&middot;</li> <li><a href='{{ url_for('frontend.help') }}'>{{_('Help')}}</a></li> <li class="muted">&middot;</li> <li><a href='#'>{{_('Terms')}}</a></li> </ul> </footer> {% block js_btm %} <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> {% assets "js_vendor" -%} <script src="{{ ASSET_URL }}"></script> {% endassets %} {% endblock %} {% block extra_js %} {% endblock %} {% block ga %} {% include "macros/_google_analytics.html" %} {% endblock %} </body> </html>
{ "content_hash": "8f24954cb6d8f9622827d4973b7e282a", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 154, "avg_line_length": 39.5045045045045, "alnum_prop": 0.5062713797035348, "repo_name": "frankV/manekineko", "id": "f35a3ac96e3522a315d0a8b0531c3fd3014ab9aa", "size": "4385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fbone/templates/layouts/base.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16586" }, { "name": "HTML", "bytes": "23823" }, { "name": "JavaScript", "bytes": "1058" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "80143" } ], "symlink_target": "" }
#import "WPTableViewSectionHeaderFooterView.h" #import "WPTableViewCell.h" #import "WPStyleGuide.h" #import "WPDeviceIdentification.h" #import "NSString+Util.h" @interface WPTableViewSectionHeaderFooterView () @property (nonatomic, strong) UILabel *titleLabel; @end @implementation WPTableViewSectionHeaderFooterView - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier { return [self initWithReuseIdentifier:reuseIdentifier style:WPTableViewSectionStyleHeader]; } - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier style:(WPTableViewSectionStyle)style { NSParameterAssert(style == WPTableViewSectionStyleHeader || style == WPTableViewSectionStyleFooter); self = [super initWithReuseIdentifier:reuseIdentifier]; if (self) { _style = style; [self setupSubviews]; } return self; } - (void)setupSubviews { BOOL isHeader = self.style == WPTableViewSectionStyleHeader; UIEdgeInsets titleInsets = isHeader ? [[self class] headerTitleInsets] : [[self class] footerTitleInsets]; UIColor *titleColor = isHeader ? [[self class] headerTitleColor] : [[self class] footerTitleColor]; UIFont *titleFont = isHeader ? [[self class] headerTitleFont] : [[self class] footerTitleFont]; // Title Label UILabel *titleLabel = [UILabel new]; titleLabel.textAlignment = NSTextAlignmentLeft; titleLabel.numberOfLines = 0; titleLabel.lineBreakMode = NSLineBreakByWordWrapping; titleLabel.font = titleFont; titleLabel.textColor = titleColor; titleLabel.backgroundColor = [UIColor clearColor]; titleLabel.shadowOffset = CGSizeZero; [self addSubview:titleLabel]; // Background UIView *backgroundView = [UIView new]; backgroundView.backgroundColor = [UIColor clearColor]; // Initialize Prperties _uppercase = isHeader; _titleLabel = titleLabel; _titleInsets = titleInsets; self.backgroundView = backgroundView; // Make sure this view is laid ut [self setNeedsLayout]; } #pragma mark - Overriden Properties /** Note: The purpose of the following overrides are to prevent UI glitches, caused by users accessing the default textLabel and detailTextLabel provided by the superclass. We're effectively disabling those fields! */ - (UILabel *)textLabel { return nil; } - (UILabel *)detailTextLabel { return nil; } #pragma mark - Properties - (NSString *)title { return self.titleLabel.text; } - (void)setTitle:(NSString *)title { self.titleLabel.text = self.uppercase ? [title uppercaseStringWithLocale:[NSLocale currentLocale]] : title; [self setNeedsLayout]; } - (NSAttributedString *)attributedTitle { return self.titleLabel.attributedText; } - (void)setAttributedTitle:(NSAttributedString *)attributedTitle { if (self.uppercase) { NSString *title = [[attributedTitle string] uppercaseStringWithLocale:[NSLocale currentLocale]]; // If we're uppercasing the title then we'll need to copy any existing attributes... NSMutableArray *attributes = [NSMutableArray new]; [attributedTitle enumerateAttributesInRange:NSMakeRange(0, [attributedTitle length]) options:0 usingBlock:^(NSDictionary *attr, NSRange range, BOOL *stop) { [attributes addObject:@{ @"attr": attr, @"range": [NSValue valueWithRange:range] }]; }]; NSMutableAttributedString *uppercaseTitle = [[NSMutableAttributedString alloc] initWithString:title]; // And then apply them to a new uppercased string for (NSDictionary *attribute in attributes) { [uppercaseTitle setAttributes:attribute[@"attr"] range:[attribute[@"range"] rangeValue]]; } attributedTitle = uppercaseTitle; } self.titleLabel.attributedText = attributedTitle; [self setNeedsLayout]; } - (UIColor *)titleColor { return self.titleLabel.textColor; } - (void)setTitleColor:(UIColor *)color { self.titleLabel.textColor = color; } - (UIFont *)titleFont { return self.titleLabel.font; } - (void)setTitleFont:(UIFont *)titleFont { self.titleLabel.font = titleFont; [self setNeedsLayout]; } - (void)setTitleAlignment:(NSTextAlignment)textAlignment { self.titleLabel.textAlignment = textAlignment; } - (NSTextAlignment)titleAlignment { return self.titleLabel.textAlignment; } - (void)setTitleInsets:(UIEdgeInsets)titleInsets { _titleInsets = titleInsets; [self setNeedsLayout]; } - (void)setUppercase:(BOOL)uppercase { _uppercase = uppercase; [self setNeedsLayout]; } #pragma mark - Layout - (void)layoutSubviews { [super layoutSubviews]; CGFloat sectionWidth = CGRectGetWidth(self.bounds); CGFloat titleWidth = [[self class] titleLabelWidthFromSectionWidth:sectionWidth titleInsets:self.titleInsets]; CGSize titleSize = [[self class] sizeForTitle:self.titleLabel.text titleWidth:titleWidth font:self.titleFont]; CGFloat padding = (sectionWidth - titleWidth) * 0.5; self.titleLabel.frame = CGRectIntegral(CGRectMake(padding, self.titleInsets.top, titleWidth, titleSize.height)); } #pragma mark - Public Static Helpers + (CGFloat)heightForHeader:(NSString *)headerText width:(CGFloat)width { return [self heightForText:headerText width:width titleInsets:[self headerTitleInsets] font:[self headerTitleFont]]; } + (CGFloat)heightForFooter:(NSString *)footerText width:(CGFloat)width { return [self heightForText:footerText width:width titleInsets:[self footerTitleInsets] font:[self footerTitleFont]]; } + (CGFloat)heightForText:(NSString *)text width:(CGFloat)width titleInsets:(UIEdgeInsets)titleInsets font:(UIFont *)font { if (text.length == 0) { return 0.0; } CGFloat titleWidth = [self titleLabelWidthFromSectionWidth:width titleInsets:titleInsets]; CGSize titleSize = [self sizeForTitle:text titleWidth:titleWidth font:font]; return titleSize.height + titleInsets.top + titleInsets.bottom; } #pragma mark - Private Methods + (CGSize)sizeForTitle:(NSString *)title titleWidth:(CGFloat)titleWidth font:(UIFont *)font { return [title suggestedSizeWithFont:font width:titleWidth]; } + (CGFloat)titleLabelWidthFromSectionWidth:(CGFloat)sectionWidth titleInsets:(UIEdgeInsets)titleInsets { CGFloat fixedWidth = self.fixedWidth; CGFloat titleLabelWidth = (fixedWidth > 0) ? MIN(fixedWidth, sectionWidth) : sectionWidth; return titleLabelWidth - titleInsets.left - titleInsets.right; } + (CGFloat)fixedWidth { return [WPDeviceIdentification isiPad] ? WPTableViewFixedWidth : 0.0; } #pragma mark - Defaults + (UIEdgeInsets)headerTitleInsets { return UIEdgeInsetsMake(21.0, 16.0, 8.0, 16.0); } + (UIEdgeInsets)footerTitleInsets { return UIEdgeInsetsMake(6.0, 16.0, 24.0, 16.0); } + (UIColor *)headerTitleColor { return [WPStyleGuide whisperGrey]; } + (UIColor *)footerTitleColor { return [WPStyleGuide greyDarken10]; } + (UIFont *)headerTitleFont { return [WPStyleGuide tableviewSectionHeaderFont]; } + (UIFont *)footerTitleFont { return [WPStyleGuide subtitleFont]; } @end
{ "content_hash": "07ade213ef1dbdf6c80a158741ab0512", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 129, "avg_line_length": 26.93040293040293, "alnum_prop": 0.7060663764961915, "repo_name": "pzhtpf/WordPress-Editor-iOS-Extension", "id": "5b291a658cc0a9de4bfd5512efb282c8231e2da5", "size": "7352", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Example/Pods/WordPress-iOS-Shared/WordPress-iOS-Shared/Core/WPTableViewSectionHeaderFooterView.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6608" }, { "name": "CSS", "bytes": "12584" }, { "name": "HTML", "bytes": "3052" }, { "name": "JavaScript", "bytes": "489372" }, { "name": "Objective-C", "bytes": "1560080" }, { "name": "Ruby", "bytes": "2683" }, { "name": "Shell", "bytes": "19252" }, { "name": "Swift", "bytes": "8269" } ], "symlink_target": "" }
<!-- @license Apache-2.0 Copyright (c) 2018 The Stdlib 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. --> # isPRNGLike > Test if a value is PRNG-like. <section class="usage"> ## Usage ```javascript var isPRNGLike = require( '@stdlib/assert/is-prng-like' ); ``` #### isPRNGLike( value ) Tests if a value is PRNG-like. ```javascript var randu = require( '@stdlib/random/base/randu' ); var bool = isPRNGLike( randu ); // returns true ``` </section> <!-- /.usage --> <section class="notes"> ## Notes - The function is **not** rigorous and only checks for the existence of particular properties which **should** be bound to a seedable pseudorandom number generator (PRNG) function. The function's main use case is for testing that a provided `value` (loosely) conforms to a particular interface. </section> <!-- /.notes --> <section class="examples"> ## Examples <!-- eslint no-undef: "error" --> ```javascript var randu = require( '@stdlib/random/base/randu' ); var isPRNGLike = require( '@stdlib/assert/is-prng-like' ); var bool = isPRNGLike( randu ); // returns true bool = isPRNGLike( [ 1, 2, 3, 4 ] ); // returns false bool = isPRNGLike( {} ); // returns false bool = isPRNGLike( null ); // returns false ``` </section> <!-- /.examples --> <!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. --> <section class="related"> </section> <!-- /.related --> <!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. --> <section class="links"> </section> <!-- /.links -->
{ "content_hash": "b2a9af34f190b176ad97b65db8ea8965", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 296, "avg_line_length": 21.444444444444443, "alnum_prop": 0.6947715496938295, "repo_name": "stdlib-js/stdlib", "id": "725e4d458a90ab4fe5a66fcd647f70a4f2e30904", "size": "2123", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/node_modules/@stdlib/assert/is-prng-like/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "21739" }, { "name": "C", "bytes": "15336495" }, { "name": "C++", "bytes": "1349482" }, { "name": "CSS", "bytes": "58039" }, { "name": "Fortran", "bytes": "198059" }, { "name": "HTML", "bytes": "56181" }, { "name": "Handlebars", "bytes": "16114" }, { "name": "JavaScript", "bytes": "85975525" }, { "name": "Julia", "bytes": "1508654" }, { "name": "Makefile", "bytes": "4806816" }, { "name": "Python", "bytes": "3343697" }, { "name": "R", "bytes": "576612" }, { "name": "Shell", "bytes": "559315" }, { "name": "TypeScript", "bytes": "19309407" }, { "name": "WebAssembly", "bytes": "5980" } ], "symlink_target": "" }
angular.module('rapid-build').run(['$rootScope', 'ENV', ($rootScope, ENV) => { $rootScope.env = ENV; }]);
{ "content_hash": "d0f6bfc2281f4b4d1aec862832faabcf", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 78, "avg_line_length": 21.6, "alnum_prop": 0.6018518518518519, "repo_name": "rapid-build-ui/rapid-build-ui.io", "id": "5167b6b46544fec89515a8ad4885aac02abcc3d3", "size": "108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/scripts/runs/run-set-env-const.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "76540" }, { "name": "CoffeeScript", "bytes": "34525" }, { "name": "HTML", "bytes": "78861" }, { "name": "JavaScript", "bytes": "144760" } ], "symlink_target": "" }
var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); var _ = require('lodash'); var path = require('path'); var helpers = require('../../helpers'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); this.log(yosay( 'Welcome to the awesome ' + chalk.red('slack-slash') + ' app generator!' )); this.log('This generator will create a new ' + chalk.red('slack-slash') + ' app.'); this.log('To create a new slack-slash handler instead, run ' + chalk.yellow('yo slack-slash:handler') + '.\n'); var prompts = [{ type: 'input', name: 'appName', message: 'Name your app:', default: 'slack-slash' }, { type: 'confirm', name: 'initialHandlers', message: 'Set up inital handlers?', default: false }, { type: 'input', name: 'handlers', message: 'List handlers to use (comma separated):', validate: helpers.stringNotEmpty, filter: helpers.filterHandlers, when: function (answers) { return answers.initialHandlers; } }]; this.prompt(prompts, function (props) { this.props = props; done(); }.bind(this)); }, handlersSetup: function () { if (this.props.handlers && this.props.handlers.length) { var done = this.async(); var prompts = []; _.each(this.props.handlers, function (handler) { var commandPrompt = { type: 'input', name: handler + '_command', message: 'What is the /:command for ' + handler + '?', filter: helpers.cleanSlashCmd, default: handler }; var tokenVarPrompt = { type: 'input', name: handler + '_token', message: 'Environment variable for your slack token:', default: helpers.pkgToTokenVar(handler) }; prompts.push(commandPrompt, tokenVarPrompt); }); this.prompt(prompts, function (props) { _.assign(this.props, props); done(); }.bind(this)); } }, createHandlersObj: function () { var self = this; this.props.h = []; _.each(this.props.handlers, function (handler) { self.props.h.push({ pkgName: handler, command: self.props[handler + '_command'], token: self.props[handler + '_token'] }); }); }, paths: function () { // Save app into directory with app name this.destinationRoot(this.props.appName + '/'); }, writing: { app: function () { var self = this; var basePath = path.join(__dirname, '..', '..'); var ssPath = path.join(basePath, 'node_modules', 'slack-slash'); var ssFiles = ['.npmignore', 'LICENSE.md', 'README.md', 'server.js']; var ssPackage = require(path.join(ssPath, 'package.json')); this.props.pkg = JSON.stringify({ scripts: ssPackage.scripts, keywords: ssPackage.keywords, dependencies: ssPackage.scripts }, null, 2).replace(/^\{/, '').replace(/\}$/, ''); _.each(ssFiles, function (file) { self.fs.copy( path.join(ssPath, file), self.destinationPath(file) ); }); this.fs.copyTpl( this.templatePath('www'), this.destinationPath('bin', '/www'), this.props ); this.fs.copy( path.join(ssPath, 'routes', '*'), this.destinationPath('routes') ); }, templates: function () { this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), this.props ); this.fs.copyTpl( this.templatePath('_handlers.json'), this.destinationPath('handlers.json'), this.props ); this.fs.copy( this.templatePath('jshintrc'), this.destinationPath('.jshintrc') ); } }, install: function () { this.npmInstall(); }, end: function () { var handlersMsg = 'Be sure to set your handler token environment variables '; var noHandlersMsg = 'Now go add some handlers '; var endMsg = 'then run ' + chalk.yellow('npm start') + ' to start the app.\n'; this.log('\nCongratulations! ' + chalk.red(this.props.appName) + ' is now installed.\n'); this.log((this.props.initialHandlers ? handlersMsg : noHandlersMsg) + endMsg); } });
{ "content_hash": "cf31dcd0cbb84308ed679f37bcd8dd30", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 115, "avg_line_length": 28.23076923076923, "alnum_prop": 0.5678928247048138, "repo_name": "dowjones/generator-slack-slash", "id": "3c5aed9cc52dc870624785a4cdc7fc0e948afe23", "size": "4404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/app/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16536" } ], "symlink_target": "" }
/* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" /* ImageMagick Macintosh PICT Methods. */ #define ReadPixmap(pixmap) \ { \ pixmap.version=(short) ReadBlobMSBShort(image); \ pixmap.pack_type=(short) ReadBlobMSBShort(image); \ pixmap.pack_size=ReadBlobMSBLong(image); \ pixmap.horizontal_resolution=1UL*ReadBlobMSBShort(image); \ (void) ReadBlobMSBShort(image); \ pixmap.vertical_resolution=1UL*ReadBlobMSBShort(image); \ (void) ReadBlobMSBShort(image); \ pixmap.pixel_type=(short) ReadBlobMSBShort(image); \ pixmap.bits_per_pixel=(short) ReadBlobMSBShort(image); \ pixmap.component_count=(short) ReadBlobMSBShort(image); \ pixmap.component_size=(short) ReadBlobMSBShort(image); \ pixmap.plane_bytes=ReadBlobMSBLong(image); \ pixmap.table=ReadBlobMSBLong(image); \ pixmap.reserved=ReadBlobMSBLong(image); \ if ((EOFBlob(image) != MagickFalse) || (pixmap.bits_per_pixel <= 0) || \ (pixmap.bits_per_pixel > 32) || (pixmap.component_count <= 0) || \ (pixmap.component_count > 4) || (pixmap.component_size <= 0)) \ ThrowReaderException(CorruptImageError,"ImproperImageHeader"); \ } typedef struct _PICTCode { const char *name; ssize_t length; const char *description; } PICTCode; typedef struct _PICTPixmap { short version, pack_type; size_t pack_size, horizontal_resolution, vertical_resolution; short pixel_type, bits_per_pixel, component_count, component_size; size_t plane_bytes, table, reserved; } PICTPixmap; typedef struct _PICTRectangle { short top, left, bottom, right; } PICTRectangle; static const PICTCode codes[] = { /* 0x00 */ { "NOP", 0, "nop" }, /* 0x01 */ { "Clip", 0, "clip" }, /* 0x02 */ { "BkPat", 8, "background pattern" }, /* 0x03 */ { "TxFont", 2, "text font (word)" }, /* 0x04 */ { "TxFace", 1, "text face (byte)" }, /* 0x05 */ { "TxMode", 2, "text mode (word)" }, /* 0x06 */ { "SpExtra", 4, "space extra (fixed point)" }, /* 0x07 */ { "PnSize", 4, "pen size (point)" }, /* 0x08 */ { "PnMode", 2, "pen mode (word)" }, /* 0x09 */ { "PnPat", 8, "pen pattern" }, /* 0x0a */ { "FillPat", 8, "fill pattern" }, /* 0x0b */ { "OvSize", 4, "oval size (point)" }, /* 0x0c */ { "Origin", 4, "dh, dv (word)" }, /* 0x0d */ { "TxSize", 2, "text size (word)" }, /* 0x0e */ { "FgColor", 4, "foreground color (ssize_tword)" }, /* 0x0f */ { "BkColor", 4, "background color (ssize_tword)" }, /* 0x10 */ { "TxRatio", 8, "numerator (point), denominator (point)" }, /* 0x11 */ { "Version", 1, "version (byte)" }, /* 0x12 */ { "BkPixPat", 0, "color background pattern" }, /* 0x13 */ { "PnPixPat", 0, "color pen pattern" }, /* 0x14 */ { "FillPixPat", 0, "color fill pattern" }, /* 0x15 */ { "PnLocHFrac", 2, "fractional pen position" }, /* 0x16 */ { "ChExtra", 2, "extra for each character" }, /* 0x17 */ { "reserved", 0, "reserved for Apple use" }, /* 0x18 */ { "reserved", 0, "reserved for Apple use" }, /* 0x19 */ { "reserved", 0, "reserved for Apple use" }, /* 0x1a */ { "RGBFgCol", 6, "RGB foreColor" }, /* 0x1b */ { "RGBBkCol", 6, "RGB backColor" }, /* 0x1c */ { "HiliteMode", 0, "hilite mode flag" }, /* 0x1d */ { "HiliteColor", 6, "RGB hilite color" }, /* 0x1e */ { "DefHilite", 0, "Use default hilite color" }, /* 0x1f */ { "OpColor", 6, "RGB OpColor for arithmetic modes" }, /* 0x20 */ { "Line", 8, "pnLoc (point), newPt (point)" }, /* 0x21 */ { "LineFrom", 4, "newPt (point)" }, /* 0x22 */ { "ShortLine", 6, "pnLoc (point, dh, dv (-128 .. 127))" }, /* 0x23 */ { "ShortLineFrom", 2, "dh, dv (-128 .. 127)" }, /* 0x24 */ { "reserved", -1, "reserved for Apple use" }, /* 0x25 */ { "reserved", -1, "reserved for Apple use" }, /* 0x26 */ { "reserved", -1, "reserved for Apple use" }, /* 0x27 */ { "reserved", -1, "reserved for Apple use" }, /* 0x28 */ { "LongText", 0, "txLoc (point), count (0..255), text" }, /* 0x29 */ { "DHText", 0, "dh (0..255), count (0..255), text" }, /* 0x2a */ { "DVText", 0, "dv (0..255), count (0..255), text" }, /* 0x2b */ { "DHDVText", 0, "dh, dv (0..255), count (0..255), text" }, /* 0x2c */ { "reserved", -1, "reserved for Apple use" }, /* 0x2d */ { "reserved", -1, "reserved for Apple use" }, /* 0x2e */ { "reserved", -1, "reserved for Apple use" }, /* 0x2f */ { "reserved", -1, "reserved for Apple use" }, /* 0x30 */ { "frameRect", 8, "rect" }, /* 0x31 */ { "paintRect", 8, "rect" }, /* 0x32 */ { "eraseRect", 8, "rect" }, /* 0x33 */ { "invertRect", 8, "rect" }, /* 0x34 */ { "fillRect", 8, "rect" }, /* 0x35 */ { "reserved", 8, "reserved for Apple use" }, /* 0x36 */ { "reserved", 8, "reserved for Apple use" }, /* 0x37 */ { "reserved", 8, "reserved for Apple use" }, /* 0x38 */ { "frameSameRect", 0, "rect" }, /* 0x39 */ { "paintSameRect", 0, "rect" }, /* 0x3a */ { "eraseSameRect", 0, "rect" }, /* 0x3b */ { "invertSameRect", 0, "rect" }, /* 0x3c */ { "fillSameRect", 0, "rect" }, /* 0x3d */ { "reserved", 0, "reserved for Apple use" }, /* 0x3e */ { "reserved", 0, "reserved for Apple use" }, /* 0x3f */ { "reserved", 0, "reserved for Apple use" }, /* 0x40 */ { "frameRRect", 8, "rect" }, /* 0x41 */ { "paintRRect", 8, "rect" }, /* 0x42 */ { "eraseRRect", 8, "rect" }, /* 0x43 */ { "invertRRect", 8, "rect" }, /* 0x44 */ { "fillRRrect", 8, "rect" }, /* 0x45 */ { "reserved", 8, "reserved for Apple use" }, /* 0x46 */ { "reserved", 8, "reserved for Apple use" }, /* 0x47 */ { "reserved", 8, "reserved for Apple use" }, /* 0x48 */ { "frameSameRRect", 0, "rect" }, /* 0x49 */ { "paintSameRRect", 0, "rect" }, /* 0x4a */ { "eraseSameRRect", 0, "rect" }, /* 0x4b */ { "invertSameRRect", 0, "rect" }, /* 0x4c */ { "fillSameRRect", 0, "rect" }, /* 0x4d */ { "reserved", 0, "reserved for Apple use" }, /* 0x4e */ { "reserved", 0, "reserved for Apple use" }, /* 0x4f */ { "reserved", 0, "reserved for Apple use" }, /* 0x50 */ { "frameOval", 8, "rect" }, /* 0x51 */ { "paintOval", 8, "rect" }, /* 0x52 */ { "eraseOval", 8, "rect" }, /* 0x53 */ { "invertOval", 8, "rect" }, /* 0x54 */ { "fillOval", 8, "rect" }, /* 0x55 */ { "reserved", 8, "reserved for Apple use" }, /* 0x56 */ { "reserved", 8, "reserved for Apple use" }, /* 0x57 */ { "reserved", 8, "reserved for Apple use" }, /* 0x58 */ { "frameSameOval", 0, "rect" }, /* 0x59 */ { "paintSameOval", 0, "rect" }, /* 0x5a */ { "eraseSameOval", 0, "rect" }, /* 0x5b */ { "invertSameOval", 0, "rect" }, /* 0x5c */ { "fillSameOval", 0, "rect" }, /* 0x5d */ { "reserved", 0, "reserved for Apple use" }, /* 0x5e */ { "reserved", 0, "reserved for Apple use" }, /* 0x5f */ { "reserved", 0, "reserved for Apple use" }, /* 0x60 */ { "frameArc", 12, "rect, startAngle, arcAngle" }, /* 0x61 */ { "paintArc", 12, "rect, startAngle, arcAngle" }, /* 0x62 */ { "eraseArc", 12, "rect, startAngle, arcAngle" }, /* 0x63 */ { "invertArc", 12, "rect, startAngle, arcAngle" }, /* 0x64 */ { "fillArc", 12, "rect, startAngle, arcAngle" }, /* 0x65 */ { "reserved", 12, "reserved for Apple use" }, /* 0x66 */ { "reserved", 12, "reserved for Apple use" }, /* 0x67 */ { "reserved", 12, "reserved for Apple use" }, /* 0x68 */ { "frameSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x69 */ { "paintSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6a */ { "eraseSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6b */ { "invertSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6c */ { "fillSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6d */ { "reserved", 4, "reserved for Apple use" }, /* 0x6e */ { "reserved", 4, "reserved for Apple use" }, /* 0x6f */ { "reserved", 4, "reserved for Apple use" }, /* 0x70 */ { "framePoly", 0, "poly" }, /* 0x71 */ { "paintPoly", 0, "poly" }, /* 0x72 */ { "erasePoly", 0, "poly" }, /* 0x73 */ { "invertPoly", 0, "poly" }, /* 0x74 */ { "fillPoly", 0, "poly" }, /* 0x75 */ { "reserved", 0, "reserved for Apple use" }, /* 0x76 */ { "reserved", 0, "reserved for Apple use" }, /* 0x77 */ { "reserved", 0, "reserved for Apple use" }, /* 0x78 */ { "frameSamePoly", 0, "poly (NYI)" }, /* 0x79 */ { "paintSamePoly", 0, "poly (NYI)" }, /* 0x7a */ { "eraseSamePoly", 0, "poly (NYI)" }, /* 0x7b */ { "invertSamePoly", 0, "poly (NYI)" }, /* 0x7c */ { "fillSamePoly", 0, "poly (NYI)" }, /* 0x7d */ { "reserved", 0, "reserved for Apple use" }, /* 0x7e */ { "reserved", 0, "reserved for Apple use" }, /* 0x7f */ { "reserved", 0, "reserved for Apple use" }, /* 0x80 */ { "frameRgn", 0, "region" }, /* 0x81 */ { "paintRgn", 0, "region" }, /* 0x82 */ { "eraseRgn", 0, "region" }, /* 0x83 */ { "invertRgn", 0, "region" }, /* 0x84 */ { "fillRgn", 0, "region" }, /* 0x85 */ { "reserved", 0, "reserved for Apple use" }, /* 0x86 */ { "reserved", 0, "reserved for Apple use" }, /* 0x87 */ { "reserved", 0, "reserved for Apple use" }, /* 0x88 */ { "frameSameRgn", 0, "region (NYI)" }, /* 0x89 */ { "paintSameRgn", 0, "region (NYI)" }, /* 0x8a */ { "eraseSameRgn", 0, "region (NYI)" }, /* 0x8b */ { "invertSameRgn", 0, "region (NYI)" }, /* 0x8c */ { "fillSameRgn", 0, "region (NYI)" }, /* 0x8d */ { "reserved", 0, "reserved for Apple use" }, /* 0x8e */ { "reserved", 0, "reserved for Apple use" }, /* 0x8f */ { "reserved", 0, "reserved for Apple use" }, /* 0x90 */ { "BitsRect", 0, "copybits, rect clipped" }, /* 0x91 */ { "BitsRgn", 0, "copybits, rgn clipped" }, /* 0x92 */ { "reserved", -1, "reserved for Apple use" }, /* 0x93 */ { "reserved", -1, "reserved for Apple use" }, /* 0x94 */ { "reserved", -1, "reserved for Apple use" }, /* 0x95 */ { "reserved", -1, "reserved for Apple use" }, /* 0x96 */ { "reserved", -1, "reserved for Apple use" }, /* 0x97 */ { "reserved", -1, "reserved for Apple use" }, /* 0x98 */ { "PackBitsRect", 0, "packed copybits, rect clipped" }, /* 0x99 */ { "PackBitsRgn", 0, "packed copybits, rgn clipped" }, /* 0x9a */ { "DirectBitsRect", 0, "PixMap, srcRect, dstRect, mode, PixData" }, /* 0x9b */ { "DirectBitsRgn", 0, "PixMap, srcRect, dstRect, mode, maskRgn, PixData" }, /* 0x9c */ { "reserved", -1, "reserved for Apple use" }, /* 0x9d */ { "reserved", -1, "reserved for Apple use" }, /* 0x9e */ { "reserved", -1, "reserved for Apple use" }, /* 0x9f */ { "reserved", -1, "reserved for Apple use" }, /* 0xa0 */ { "ShortComment", 2, "kind (word)" }, /* 0xa1 */ { "LongComment", 0, "kind (word), size (word), data" } }; /* Forward declarations. */ static MagickBooleanType WritePICTImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage decompresses an image via Macintosh pack bits decoding for % Macintosh PICT images. % % The format of the DecodeImage method is: % % unsigned char *DecodeImage(Image *blob,Image *image, % size_t bytes_per_line,const int bits_per_pixel, % unsigned size_t extent) % % A description of each parameter follows: % % o image_info: the image info. % % o blob,image: the address of a structure of type Image. % % o bytes_per_line: This integer identifies the number of bytes in a % scanline. % % o bits_per_pixel: the number of bits in a pixel. % % o extent: the number of pixels allocated. % */ static unsigned char *ExpandBuffer(unsigned char *pixels, MagickSizeType *bytes_per_line,const unsigned int bits_per_pixel) { register ssize_t i; register unsigned char *p, *q; static unsigned char scanline[8*256]; p=pixels; q=scanline; switch (bits_per_pixel) { case 8: case 16: case 32: return(pixels); case 4: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 4) & 0xff; *q++=(*p & 15); p++; } *bytes_per_line*=2; break; } case 2: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 6) & 0x03; *q++=(*p >> 4) & 0x03; *q++=(*p >> 2) & 0x03; *q++=(*p & 3); p++; } *bytes_per_line*=4; break; } case 1: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 7) & 0x01; *q++=(*p >> 6) & 0x01; *q++=(*p >> 5) & 0x01; *q++=(*p >> 4) & 0x01; *q++=(*p >> 3) & 0x01; *q++=(*p >> 2) & 0x01; *q++=(*p >> 1) & 0x01; *q++=(*p & 0x01); p++; } *bytes_per_line*=8; break; } default: break; } return(scanline); } static unsigned char *DecodeImage(Image *blob,Image *image, size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent, ExceptionInfo *exception) { MagickSizeType number_pixels; register ssize_t i; register unsigned char *p, *q; size_t bytes_per_pixel, length, row_bytes, scanline_length, width; ssize_t count, j, y; unsigned char *pixels, *scanline; /* Determine pixel buffer size. */ if (bits_per_pixel <= 8) bytes_per_line&=0x7fff; width=image->columns; bytes_per_pixel=1; if (bits_per_pixel == 16) { bytes_per_pixel=2; width*=2; } else if (bits_per_pixel == 32) width*=image->alpha_trait ? 4 : 3; if (bytes_per_line == 0) bytes_per_line=width; row_bytes=(size_t) (image->columns | 0x8000); if (image->storage_class == DirectClass) row_bytes=(size_t) ((4*image->columns) | 0x8000); /* Allocate pixel and scanline buffer. */ pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) return((unsigned char *) NULL); *extent=row_bytes*image->rows*sizeof(*pixels); (void) ResetMagickMemory(pixels,0,*extent); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) return((unsigned char *) NULL); if (bytes_per_line < 8) { /* Pixels are already uncompressed. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width*GetPixelChannels(image);; number_pixels=bytes_per_line; count=ReadBlob(blob,(size_t) number_pixels,scanline); if (count != (ssize_t) number_pixels) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'", image->filename); break; } p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel); if ((q+number_pixels) > (pixels+(*extent))) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'", image->filename); break; } (void) CopyMagickMemory(q,p,(size_t) number_pixels); } scanline=(unsigned char *) RelinquishMagickMemory(scanline); return(pixels); } /* Uncompress RLE pixels into uncompressed pixel buffer. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width; if (bytes_per_line > 200) scanline_length=ReadBlobMSBShort(blob); else scanline_length=1UL*ReadBlobByte(blob); if (scanline_length >= row_bytes) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'",image->filename); break; } count=ReadBlob(blob,scanline_length,scanline); if (count != (ssize_t) scanline_length) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnableToUncompressImage","`%s'",image->filename); break; } for (j=0; j < (ssize_t) scanline_length; ) if ((scanline[j] & 0x80) == 0) { length=(size_t) ((scanline[j] & 0xff)+1); number_pixels=length*bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); if ((q-pixels+number_pixels) <= *extent) (void) CopyMagickMemory(q,p,(size_t) number_pixels); q+=number_pixels; j+=(ssize_t) (length*bytes_per_pixel+1); } else { length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2); number_pixels=bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); for (i=0; i < (ssize_t) length; i++) { if ((q-pixels+number_pixels) <= *extent) (void) CopyMagickMemory(q,p,(size_t) number_pixels); q+=number_pixels; } j+=(ssize_t) bytes_per_pixel+1; } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via Macintosh pack bits encoding % for Macintosh PICT images. % % The format of the EncodeImage method is: % % size_t EncodeImage(Image *image,const unsigned char *scanline, % const size_t bytes_per_line,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o scanline: A pointer to an array of characters to pack. % % o bytes_per_line: the number of bytes in a scanline. % % o pixels: A pointer to an array of characters where the packed % characters are stored. % */ static size_t EncodeImage(Image *image,const unsigned char *scanline, const size_t bytes_per_line,unsigned char *pixels) { #define MaxCount 128 #define MaxPackbitsRunlength 128 register const unsigned char *p; register ssize_t i; register unsigned char *q; size_t length; ssize_t count, repeat_count, runlength; unsigned char index; /* Pack scanline. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(scanline != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); count=0; runlength=0; p=scanline+(bytes_per_line-1); q=pixels; index=(*p); for (i=(ssize_t) bytes_per_line-1; i >= 0; i--) { if (index == *p) runlength++; else { if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } runlength=1; } index=(*p); p--; } if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } if (count > 0) *q++=(unsigned char) (count-1); /* Write the number of and the packed length. */ length=(size_t) (q-pixels); if (bytes_per_line > 200) { (void) WriteBlobMSBShort(image,(unsigned short) length); length+=2; } else { (void) WriteBlobByte(image,(unsigned char) length); length++; } while (q != pixels) { q--; (void) WriteBlobByte(image,*q); } return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P I C T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPICT()() returns MagickTrue if the image format type, identified by the % magick string, is PICT. % % The format of the ReadPICTImage method is: % % MagickBooleanType IsPICT(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPICT(const unsigned char *magick,const size_t length) { if (length < 12) return(MagickFalse); /* Embedded OLE2 macintosh have "PICT" instead of 512 platform header. */ if (memcmp(magick,"PICT",4) == 0) return(MagickTrue); if (length < 528) return(MagickFalse); if (memcmp(magick+522,"\000\021\002\377\014\000",6) == 0) return(MagickTrue); return(MagickFalse); } #if !defined(macintosh) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPICTImage() reads an Apple Macintosh QuickDraw/PICT image file % and returns it. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the ReadPICTImage method is: % % Image *ReadPICTImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadRectangle(Image *image,PICTRectangle *rectangle) { rectangle->top=(short) ReadBlobMSBShort(image); rectangle->left=(short) ReadBlobMSBShort(image); rectangle->bottom=(short) ReadBlobMSBShort(image); rectangle->right=(short) ReadBlobMSBShort(image); if ((EOFBlob(image) != MagickFalse) || (rectangle->left > rectangle->right) || (rectangle->top > rectangle->bottom)) return(MagickFalse); return(MagickTrue); } static Image *ReadPICTImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MagickPathExtent], header_ole[4]; Image *image; int c, code; MagickBooleanType jpeg, status; PICTRectangle frame; PICTPixmap pixmap; Quantum index; register Quantum *q; register ssize_t i, x; size_t extent, length; ssize_t count, flags, j, version, y; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PICT header. */ pixmap.bits_per_pixel=0; pixmap.component_count=0; /* Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2. */ header_ole[0]=ReadBlobByte(image); header_ole[1]=ReadBlobByte(image); header_ole[2]=ReadBlobByte(image); header_ole[3]=ReadBlobByte(image); if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && (header_ole[2] == 0x43) && (header_ole[3] == 0x54 ))) for (i=0; i < 508; i++) if (ReadBlobByte(image) == EOF) break; (void) ReadBlobMSBShort(image); /* skip picture size */ if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); while ((c=ReadBlobByte(image)) == 0) ; if (c != 0x11) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); version=ReadBlobByte(image); if (version == 2) { c=ReadBlobByte(image); if (c != 0xff) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } else if (version != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || (frame.bottom < 0) || (frame.left >= frame.right) || (frame.top >= frame.bottom)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Create black canvas. */ flags=0; image->depth=8; image->columns=1UL*(frame.right-frame.left); image->rows=1UL*(frame.bottom-frame.top); image->resolution.x=DefaultResolution; image->resolution.y=DefaultResolution; image->units=UndefinedResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Interpret PICT opcodes. */ jpeg=MagickFalse; for (code=0; EOFBlob(image) == MagickFalse; ) { if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((version == 1) || ((TellBlob(image) % 2) != 0)) code=ReadBlobByte(image); if (version == 2) code=ReadBlobMSBSignedShort(image); if (code < 0) break; if (code > 0xa1) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code); } else { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %04X %s: %s",code,codes[code].name,codes[code].description); switch (code) { case 0x01: { /* Clipping rectangle. */ length=ReadBlobMSBShort(image); if (length != 0x000a) { for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) break; image->columns=1UL*(frame.right-frame.left); image->rows=1UL*(frame.bottom-frame.top); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); break; } case 0x12: case 0x13: case 0x14: { ssize_t pattern; size_t height, width; /* Skip pattern definition. */ pattern=1L*ReadBlobMSBShort(image); for (i=0; i < 8; i++) if (ReadBlobByte(image) == EOF) break; if (pattern == 2) { for (i=0; i < 5; i++) if (ReadBlobByte(image) == EOF) break; break; } if (pattern != 1) ThrowReaderException(CorruptImageError,"UnknownPatternType"); length=ReadBlobMSBShort(image); if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); ReadPixmap(pixmap); image->depth=1UL*pixmap.component_size; image->resolution.x=1.0*pixmap.horizontal_resolution; image->resolution.y=1.0*pixmap.vertical_resolution; image->units=PixelsPerInchResolution; (void) ReadBlobMSBLong(image); flags=1L*ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); for (i=0; i <= (ssize_t) length; i++) (void) ReadBlobMSBLong(image); width=1UL*(frame.bottom-frame.top); height=1UL*(frame.right-frame.left); if (pixmap.bits_per_pixel <= 8) length&=0x7fff; if (pixmap.bits_per_pixel == 16) width<<=1; if (length == 0) length=width; if (length < 8) { for (i=0; i < (ssize_t) (length*height); i++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (int) height; j++) if (length > 200) { for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (ssize_t) ReadBlobByte(image); j++) if (ReadBlobByte(image) == EOF) break; break; } case 0x1b: { /* Initialize image background color. */ image->background_color.red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); break; } case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { /* Skip polygon or region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } case 0x90: case 0x91: case 0x98: case 0x99: case 0x9a: case 0x9b: { Image *tile_image; PICTRectangle source, destination; register unsigned char *p; size_t j; ssize_t bytes_per_line; unsigned char *pixels; /* Pixmap clipped by a rectangle. */ bytes_per_line=0; if ((code != 0x9a) && (code != 0x9b)) bytes_per_line=1L*ReadBlobMSBShort(image); else { (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); } if (ReadRectangle(image,&frame) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize tile image. */ tile_image=CloneImage(image,1UL*(frame.right-frame.left), 1UL*(frame.bottom-frame.top),MagickTrue,exception); if (tile_image == (Image *) NULL) return((Image *) NULL); if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) { ReadPixmap(pixmap); tile_image->depth=1UL*pixmap.component_size; tile_image->alpha_trait=pixmap.component_count == 4 ? BlendPixelTrait : UndefinedPixelTrait; tile_image->resolution.x=(double) pixmap.horizontal_resolution; tile_image->resolution.y=(double) pixmap.vertical_resolution; tile_image->units=PixelsPerInchResolution; if (tile_image->alpha_trait != UndefinedPixelTrait) image->alpha_trait=tile_image->alpha_trait; } if ((code != 0x9a) && (code != 0x9b)) { /* Initialize colormap. */ tile_image->colors=2; if ((bytes_per_line & 0x8000) != 0) { (void) ReadBlobMSBLong(image); flags=1L*ReadBlobMSBShort(image); tile_image->colors=1UL*ReadBlobMSBShort(image)+1; } status=AcquireImageColormap(tile_image,tile_image->colors, exception); if (status == MagickFalse) { tile_image=DestroyImage(tile_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if ((bytes_per_line & 0x8000) != 0) { for (i=0; i < (ssize_t) tile_image->colors; i++) { j=ReadBlobMSBShort(image) % tile_image->colors; if ((flags & 0x8000) != 0) j=(size_t) i; tile_image->colormap[j].red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); } } else { for (i=0; i < (ssize_t) tile_image->colors; i++) { tile_image->colormap[i].red=(Quantum) (QuantumRange- tile_image->colormap[i].red); tile_image->colormap[i].green=(Quantum) (QuantumRange- tile_image->colormap[i].green); tile_image->colormap[i].blue=(Quantum) (QuantumRange- tile_image->colormap[i].blue); } } } if (ReadRectangle(image,&source) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (ReadRectangle(image,&destination) == MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlobMSBShort(image); if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) { /* Skip region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; } if ((code != 0x9a) && (code != 0x9b) && (bytes_per_line & 0x8000) == 0) pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1,&extent, exception); else pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1U* pixmap.bits_per_pixel,&extent,exception); if (pixels == (unsigned char *) NULL) { tile_image=DestroyImage(tile_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* Convert PICT tile image to pixel packets. */ p=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { if (p > (pixels+extent+image->columns)) ThrowReaderException(CorruptImageError,"NotEnoughPixelData"); q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { if (tile_image->storage_class == PseudoClass) { index=ConstrainColormapIndex(tile_image,*p,exception); SetPixelIndex(tile_image,index,q); SetPixelRed(tile_image, tile_image->colormap[(ssize_t) index].red,q); SetPixelGreen(tile_image, tile_image->colormap[(ssize_t) index].green,q); SetPixelBlue(tile_image, tile_image->colormap[(ssize_t) index].blue,q); } else { if (pixmap.bits_per_pixel == 16) { i=(*p++); j=(*p); SetPixelRed(tile_image,ScaleCharToQuantum( (unsigned char) ((i & 0x7c) << 1)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( (unsigned char) (((i & 0x03) << 6) | ((j & 0xe0) >> 2))),q); SetPixelBlue(tile_image,ScaleCharToQuantum( (unsigned char) ((j & 0x1f) << 3)),q); } else if (tile_image->alpha_trait == UndefinedPixelTrait) { if (p > (pixels+extent+2*image->columns)) ThrowReaderException(CorruptImageError, "NotEnoughPixelData"); SetPixelRed(tile_image,ScaleCharToQuantum(*p),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); } else { if (p > (pixels+extent+3*image->columns)) ThrowReaderException(CorruptImageError, "NotEnoughPixelData"); SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q); SetPixelRed(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+3*tile_image->columns)),q); } } p++; q+=GetPixelChannels(tile_image); } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; if ((tile_image->storage_class == DirectClass) && (pixmap.bits_per_pixel != 16)) { p+=(pixmap.component_count-1)*tile_image->columns; if (p < pixels) break; } status=SetImageProgress(image,LoadImageTag,y,tile_image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (jpeg == MagickFalse) if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) (void) CompositeImage(image,tile_image,CopyCompositeOp, MagickTrue,destination.left,destination.top,exception); tile_image=DestroyImage(tile_image); break; } case 0xa1: { unsigned char *info; size_t type; /* Comment. */ type=ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); if (length == 0) break; (void) ReadBlobMSBLong(image); length-=4; if (length == 0) break; info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); if (info == (unsigned char *) NULL) break; count=ReadBlob(image,length,info); if (count != (ssize_t) length) ThrowReaderException(ResourceLimitError,"UnableToReadImageData"); switch (type) { case 0xe0: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); break; } case 0x1f2: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"iptc",profile,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); profile=DestroyStringInfo(profile); break; } default: break; } info=(unsigned char *) RelinquishMagickMemory(info); break; } default: { /* Skip to next op code. */ if (codes[code].length == -1) (void) ReadBlobMSBShort(image); else for (i=0; i < (ssize_t) codes[code].length; i++) if (ReadBlobByte(image) == EOF) break; } } } if (code == 0xc00) { /* Skip header. */ for (i=0; i < 24; i++) if (ReadBlobByte(image) == EOF) break; continue; } if (((code >= 0xb0) && (code <= 0xcf)) || ((code >= 0x8000) && (code <= 0x80ff))) continue; if (code == 0x8200) { FILE *file; Image *tile_image; ImageInfo *read_info; int unique_file; /* Embedded JPEG. */ jpeg=MagickTrue; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(read_info->filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(read_info->filename); (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=ReadBlobMSBLong(image); if (length > 154) { for (i=0; i < 6; i++) (void) ReadBlobMSBLong(image); if (ReadRectangle(image,&frame) == MagickFalse) { (void) fclose(file); (void) RelinquishUniqueFileResource(read_info->filename); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < 122; i++) if (ReadBlobByte(image) == EOF) break; for (i=0; i < (ssize_t) (length-154); i++) { c=ReadBlobByte(image); if (c == EOF) break; (void) fputc(c,file); } } (void) fclose(file); (void) close(unique_file); tile_image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) continue; (void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g", (double) MagickMax(image->columns,tile_image->columns), (double) MagickMax(image->rows,tile_image->rows)); (void) SetImageExtent(image, MagickMax(image->columns,tile_image->columns), MagickMax(image->rows,tile_image->rows),exception); (void) TransformImageColorspace(image,tile_image->colorspace,exception); (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue, frame.left,frame.right,exception); image->compression=tile_image->compression; tile_image=DestroyImage(tile_image); continue; } if ((code == 0xff) || (code == 0xffff)) break; if (((code >= 0xd0) && (code <= 0xfe)) || ((code >= 0x8100) && (code <= 0xffff))) { /* Skip reserved. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } if ((code >= 0x100) && (code <= 0x7fff)) { /* Skip reserved. */ length=(size_t) ((code >> 7) & 0xff); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPICTImage() adds attributes for the PICT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPICTImage method is: % % size_t RegisterPICTImage(void) % */ ModuleExport size_t RegisterPICTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PICT","PCT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PICT","PICT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPICTImage() removes format registrations made by the % PICT module from the list of supported formats. % % The format of the UnregisterPICTImage method is: % % UnregisterPICTImage(void) % */ ModuleExport void UnregisterPICTImage(void) { (void) UnregisterMagickInfo("PCT"); (void) UnregisterMagickInfo("PICT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePICTImage() writes an image to a file in the Apple Macintosh % QuickDraw/PICT image format. % % The format of the WritePICTImage method is: % % MagickBooleanType WritePICTImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define MaxCount 128 #define PictCropRegionOp 0x01 #define PictEndOfPictureOp 0xff #define PictJPEGOp 0x8200 #define PictInfoOp 0x0C00 #define PictInfoSize 512 #define PictPixmapOp 0x9A #define PictPICTOp 0x98 #define PictVersion 0x11 const StringInfo *profile; double x_resolution, y_resolution; MagickBooleanType status; MagickOffsetType offset; PICTPixmap pixmap; PICTRectangle bounds, crop_rectangle, destination_rectangle, frame_rectangle, size_rectangle, source_rectangle; register const Quantum *p; register ssize_t i, x; size_t bytes_per_line, count, row_bytes, storage_class; ssize_t y; unsigned char *buffer, *packed_scanline, *scanline; unsigned short base_address, transfer_mode; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns > 65535L) || (image->rows > 65535L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Initialize image info. */ size_rectangle.top=0; size_rectangle.left=0; size_rectangle.bottom=(short) image->rows; size_rectangle.right=(short) image->columns; frame_rectangle=size_rectangle; crop_rectangle=size_rectangle; source_rectangle=size_rectangle; destination_rectangle=size_rectangle; base_address=0xff; row_bytes=image->columns; bounds.top=0; bounds.left=0; bounds.bottom=(short) image->rows; bounds.right=(short) image->columns; pixmap.version=0; pixmap.pack_type=0; pixmap.pack_size=0; pixmap.pixel_type=0; pixmap.bits_per_pixel=8; pixmap.component_count=1; pixmap.component_size=8; pixmap.plane_bytes=0; pixmap.table=0; pixmap.reserved=0; transfer_mode=0; x_resolution=image->resolution.x != 0.0 ? image->resolution.x : DefaultResolution; y_resolution=image->resolution.y != 0.0 ? image->resolution.y : DefaultResolution; storage_class=image->storage_class; if (image_info->compression == JPEGCompression) storage_class=DirectClass; if (storage_class == DirectClass) { pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; pixmap.pixel_type=16; pixmap.bits_per_pixel=32; pixmap.pack_type=0x04; transfer_mode=0x40; row_bytes=4*image->columns; } /* Allocate memory. */ bytes_per_line=image->columns; if (storage_class == DirectClass) bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) (row_bytes+MaxCount),sizeof(*packed_scanline)); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); if ((buffer == (unsigned char *) NULL) || (packed_scanline == (unsigned char *) NULL) || (scanline == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(scanline,0,row_bytes); (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); /* Write header, header size, size bounding box, version, and reserved. */ (void) ResetMagickMemory(buffer,0,PictInfoSize); (void) WriteBlob(image,PictInfoSize,buffer); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); (void) WriteBlobMSBShort(image,PictVersion); (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ (void) WriteBlobMSBShort(image,PictInfoOp); (void) WriteBlobMSBLong(image,0xFFFE0000UL); /* Write full size of the file, resolution, frame bounding box, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); (void) WriteBlobMSBLong(image,0x00000000L); profile=GetImageProfile(image,"iptc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0x1f2); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobString(image,"8BIM"); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); } profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,4); (void) WriteBlobMSBLong(image,0x00000002UL); } /* Write crop region opcode and crop bounding box. */ (void) WriteBlobMSBShort(image,PictCropRegionOp); (void) WriteBlobMSBShort(image,0xa); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); if (image_info->compression == JPEGCompression) { Image *jpeg_image; ImageInfo *jpeg_info; size_t length; unsigned char *blob; jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } jpeg_info=CloneImageInfo(image_info); (void) CopyMagickString(jpeg_info->magick,"JPEG",MagickPathExtent); length=0; blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, exception); jpeg_info=DestroyImageInfo(jpeg_info); if (blob == (unsigned char *) NULL) return(MagickFalse); jpeg_image=DestroyImage(jpeg_image); (void) WriteBlobMSBShort(image,PictJPEGOp); (void) WriteBlobMSBLong(image,(unsigned int) length+154); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00010000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00010000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x40000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00400000UL); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00566A70UL); (void) WriteBlobMSBLong(image,0x65670000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000001UL); (void) WriteBlobMSBLong(image,0x00016170UL); (void) WriteBlobMSBLong(image,0x706C0000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x87AC0001UL); (void) WriteBlobMSBLong(image,0x0B466F74UL); (void) WriteBlobMSBLong(image,0x6F202D20UL); (void) WriteBlobMSBLong(image,0x4A504547UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x00000000UL); (void) WriteBlobMSBLong(image,0x0018FFFFUL); (void) WriteBlob(image,length,blob); if ((length & 0x01) != 0) (void) WriteBlobByte(image,'\0'); blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Write picture opcode, row bytes, and picture bounding box, and version. */ if (storage_class == PseudoClass) (void) WriteBlobMSBShort(image,PictPICTOp); else { (void) WriteBlobMSBShort(image,PictPixmapOp); (void) WriteBlobMSBLong(image,(size_t) base_address); } (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); /* Write pack type, pack size, resolution, pixel type, and pixel size. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); /* Write component count, size, plane bytes, table size, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); if (storage_class == PseudoClass) { /* Write image colormap. */ (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ (void) WriteBlobMSBShort(image,0L); /* color flags */ (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); for (i=0; i < (ssize_t) image->colors; i++) { (void) WriteBlobMSBShort(image,(unsigned short) i); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].red)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].green)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].blue)); } } /* Write source and destination rectangle. */ (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); /* Write picture data. */ count=0; if (storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { scanline[x]=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image_info->compression == JPEGCompression) { (void) ResetMagickMemory(scanline,0,row_bytes); for (y=0; y < (ssize_t) image->rows; y++) count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); } else { register unsigned char *blue, *green, *opacity, *red; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; opacity=scanline+3*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; if (image->alpha_trait != UndefinedPixelTrait) { opacity=scanline; red=scanline+image->columns; green=scanline+2*image->columns; blue=scanline+3*image->columns; } for (x=0; x < (ssize_t) image->columns; x++) { *red++=ScaleQuantumToChar(GetPixelRed(image,p)); *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->alpha_trait != UndefinedPixelTrait) *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if ((count & 0x01) != 0) (void) WriteBlobByte(image,'\0'); (void) WriteBlobMSBShort(image,PictEndOfPictureOp); offset=TellBlob(image); offset=SeekBlob(image,512,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) offset); scanline=(unsigned char *) RelinquishMagickMemory(scanline); packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); (void) CloseBlob(image); return(MagickTrue); }
{ "content_hash": "f601c605071832f5137ed37535a8acf2", "timestamp": "", "source": "github", "line_count": 2000, "max_line_length": 90, "avg_line_length": 35.327, "alnum_prop": 0.5292835508251479, "repo_name": "jachitech/AndroidPrebuiltPackages", "id": "7e6035004138d68bd1f6c41772ebab5df42aa9f6", "size": "73303", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "packages/ImageMagick-7.0.4-5/coders/pict.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1238157" }, { "name": "C", "bytes": "19001599" }, { "name": "C++", "bytes": "889722" }, { "name": "CMake", "bytes": "47784" }, { "name": "CSS", "bytes": "68583" }, { "name": "HTML", "bytes": "4620405" }, { "name": "Java", "bytes": "210203" }, { "name": "JavaScript", "bytes": "34594" }, { "name": "M4", "bytes": "251417" }, { "name": "Makefile", "bytes": "2153287" }, { "name": "PHP", "bytes": "1140224" }, { "name": "Perl", "bytes": "243893" }, { "name": "Roff", "bytes": "159209" }, { "name": "Shell", "bytes": "945463" }, { "name": "Tcl", "bytes": "20736" }, { "name": "XS", "bytes": "479644" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_34) on Wed Oct 23 13:33:58 EDT 2013 --> <TITLE> Uses of Interface org.hibernate.hql.spi.MultiTableBulkIdStrategy.DeleteHandler (Hibernate JavaDocs) </TITLE> <META NAME="date" CONTENT="2013-10-23"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.hibernate.hql.spi.MultiTableBulkIdStrategy.DeleteHandler (Hibernate JavaDocs)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/hibernate/hql/spi//class-useMultiTableBulkIdStrategy.DeleteHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MultiTableBulkIdStrategy.DeleteHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Interface<br>org.hibernate.hql.spi.MultiTableBulkIdStrategy.DeleteHandler</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.hibernate.hql.spi"><B>org.hibernate.hql.spi</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.hibernate.hql.spi"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A> in <A HREF="../../../../../org/hibernate/hql/spi/package-summary.html">org.hibernate.hql.spi</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../org/hibernate/hql/spi/package-summary.html">org.hibernate.hql.spi</A> that implement <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/hibernate/hql/spi/TableBasedDeleteHandlerImpl.html" title="class in org.hibernate.hql.spi">TableBasedDeleteHandlerImpl</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/hibernate/hql/spi/package-summary.html">org.hibernate.hql.spi</A> that return <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></CODE></FONT></TD> <TD><CODE><B>PersistentTableBulkIdStrategy.</B><B><A HREF="../../../../../org/hibernate/hql/spi/PersistentTableBulkIdStrategy.html#buildDeleteHandler(org.hibernate.engine.spi.SessionFactoryImplementor, org.hibernate.hql.internal.ast.HqlSqlWalker)">buildDeleteHandler</A></B>(<A HREF="../../../../../org/hibernate/engine/spi/SessionFactoryImplementor.html" title="interface in org.hibernate.engine.spi">SessionFactoryImplementor</A>&nbsp;factory, <A HREF="../../../../../org/hibernate/hql/internal/ast/HqlSqlWalker.html" title="class in org.hibernate.hql.internal.ast">HqlSqlWalker</A>&nbsp;walker)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></CODE></FONT></TD> <TD><CODE><B>TemporaryTableBulkIdStrategy.</B><B><A HREF="../../../../../org/hibernate/hql/spi/TemporaryTableBulkIdStrategy.html#buildDeleteHandler(org.hibernate.engine.spi.SessionFactoryImplementor, org.hibernate.hql.internal.ast.HqlSqlWalker)">buildDeleteHandler</A></B>(<A HREF="../../../../../org/hibernate/engine/spi/SessionFactoryImplementor.html" title="interface in org.hibernate.engine.spi">SessionFactoryImplementor</A>&nbsp;factory, <A HREF="../../../../../org/hibernate/hql/internal/ast/HqlSqlWalker.html" title="class in org.hibernate.hql.internal.ast">HqlSqlWalker</A>&nbsp;walker)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi">MultiTableBulkIdStrategy.DeleteHandler</A></CODE></FONT></TD> <TD><CODE><B>MultiTableBulkIdStrategy.</B><B><A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.html#buildDeleteHandler(org.hibernate.engine.spi.SessionFactoryImplementor, org.hibernate.hql.internal.ast.HqlSqlWalker)">buildDeleteHandler</A></B>(<A HREF="../../../../../org/hibernate/engine/spi/SessionFactoryImplementor.html" title="interface in org.hibernate.engine.spi">SessionFactoryImplementor</A>&nbsp;factory, <A HREF="../../../../../org/hibernate/hql/internal/ast/HqlSqlWalker.html" title="class in org.hibernate.hql.internal.ast">HqlSqlWalker</A>&nbsp;walker)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Build a handler capable of handling the bulk delete indicated by the given walker.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/hql/spi/MultiTableBulkIdStrategy.DeleteHandler.html" title="interface in org.hibernate.hql.spi"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/hibernate/hql/spi//class-useMultiTableBulkIdStrategy.DeleteHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MultiTableBulkIdStrategy.DeleteHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2001-2013 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved. </BODY> </HTML>
{ "content_hash": "3dbebd8400da7085be00d67095794063", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 445, "avg_line_length": 54.93488372093023, "alnum_prop": 0.6627719922106511, "repo_name": "HerrB92/obp", "id": "99dd3d6b8342ce8d759c5b1d20b776930a50a217", "size": "11811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/documentation/javadocs/org/hibernate/hql/spi/class-use/MultiTableBulkIdStrategy.DeleteHandler.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "181658" }, { "name": "Groovy", "bytes": "98685" }, { "name": "Java", "bytes": "34621856" }, { "name": "JavaScript", "bytes": "356255" }, { "name": "Shell", "bytes": "194" }, { "name": "XSLT", "bytes": "21372" } ], "symlink_target": "" }
class Notification < ApplicationRecord enum level: %i[info warning danger] enum notification_type: %i[global] # ================ # = Associations = # ================ has_and_belongs_to_many :users, dependent: :destroy, join_table: 'notification_acknowledgements' # =============== # = Validations = # =============== validates :notification_type, presence: { message: PRESENCE_MESSAGE } validates :title, presence: { message: PRESENCE_MESSAGE } validates :level, presence: { message: PRESENCE_MESSAGE } validates :body, presence: { message: PRESENCE_MESSAGE } validates :dismissable, inclusion: { in: BOOLEAN_VALUES } validates :enabled, inclusion: { in: BOOLEAN_VALUES } validates :starts_at, presence: { message: PRESENCE_MESSAGE }, after: { date: Date.today, on: :create } validates :expires_at, presence: { message: PRESENCE_MESSAGE }, after: { date: Date.tomorrow, on: :create } # ========== # = Scopes = # ========== scope :active, (lambda do where('starts_at <= :now and :now < expires_at', now: Time.now).where(enabled: true) end) scope :active_per_user, (lambda do |user| if user.present? acknowledgement_ids = user.notifications.pluck(:id) active.where.not(id: acknowledgement_ids) else active.where(dismissable: false) end end) # Has the Notification been acknowledged by the given user ? # If no user is given, currently logged in user (if any) is the default # # Returns Boolean def acknowledged?(user) dismissable? && user.present? && users.include?(user) end end
{ "content_hash": "dfcf14b3b723e7e30196af222e7a132f", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 88, "avg_line_length": 28.879310344827587, "alnum_prop": 0.6131343283582089, "repo_name": "DMPRoadmap/roadmap", "id": "b26be026f74f1181880457dd67a7dd58f1db45fe", "size": "2200", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/models/notification.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "147543" }, { "name": "HTML", "bytes": "455968" }, { "name": "JavaScript", "bytes": "336934" }, { "name": "Procfile", "bytes": "67" }, { "name": "Ruby", "bytes": "1818346" }, { "name": "SCSS", "bytes": "29447" }, { "name": "XSLT", "bytes": "11471" } ], "symlink_target": "" }
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {- | Module : Data.RTree.Strict Copyright : Copyright (c) 2015, Birte Wagner, Sebastian Philipp License : MIT Maintainer : Birte Wagner, Sebastian Philipp (sebastian@spawnhost.de) Stability : experimental Portability: not portable This is the Strict version of 'Data.RTree.RTree' the following property should be true (by using 'GHC.AssertNF.isNF' ) : >>> propNF :: RTree a -> IO Bool >>> propNF e = isNF $! e -} module Data.RTree.Strict ( -- * 'MBB' MBB , MBB.mbb -- * Data Type , RTree () , toLazy , toStrict -- * Constructors , empty , singleton -- * Modification , insert , insertWith , delete , mapMaybe -- ** Merging , union , unionWith -- * Searching and Properties , lookup , intersectWithKey , intersect , lookupRange , lookupRangeWithKey , lookupContainsRange , lookupContainsRangeWithKey , length , null , keys , values -- * Lists , fromList , toList ) where import Prelude hiding (lookup, length, null, map) import Data.Binary import Data.Function (on) import qualified Data.List as L (length) import qualified Data.Maybe as Maybe (mapMaybe) import Data.Semigroup import Data.Typeable (Typeable) import Control.DeepSeq (NFData) import GHC.Generics (Generic) --import Data.RTree.Base hiding (RTree, singleton, fromList, insertWith, unionDistinctWith, unionWith, insert, mapMaybe, union, fromList', unionDistinct, unionDistinctSplit) import qualified Data.RTree.Base as Lazy import Data.RTree.MBB hiding (mbb) import qualified Data.RTree.MBB as MBB newtype RTree a = RTree {toLazy' :: Lazy.RTree a} deriving (Show, Eq, Typeable, Generic, NFData, Binary, Monoid, Semigroup) -- | converts a lazy RTree into a strict RTree -- /O(n)/ toStrict :: Lazy.RTree a -> RTree a toStrict t = map id (RTree t) -- | converts a strict RTree into a lazy RTree -- /O(1)/ toLazy :: RTree a -> Lazy.RTree a toLazy = toLazy' -- --------------- -- smart constuctors -- | creates an empty tree empty :: RTree a empty = RTree Lazy.Empty -- | returns 'True', if empty -- -- prop> null empty = True null :: RTree a -> Bool null = Lazy.null . toLazy -- | creates a single element tree singleton :: MBB -> a -> RTree a singleton mbb !x = RTree $ Lazy.Leaf mbb x -- ---------------------------------- -- Lists -- | creates a tree out of pairs fromList :: [(MBB, a)] -> RTree a fromList l = RTree $ fromList' $ (toLazy . (uncurry singleton)) <$> l -- | merges all singletons into a single tree. fromList' :: [Lazy.RTree a] -> Lazy.RTree a fromList' [] = Lazy.empty fromList' ts = foldr1 unionDistinct ts -- | creates a list of pairs out of a tree -- -- prop> toList t = zip (keys t) (values t) toList :: RTree a -> [(MBB, a)] toList = Lazy.toList . toLazy -- | returns all keys in this tree -- -- prop> toList t = zip (keys t) (values t) keys :: RTree a -> [MBB] keys = Lazy.keys . toLazy -- | returns all values in this tree -- -- prop> toList t = zip (keys t) (values t) values :: RTree a -> [a] values = Lazy.values . toLazy -- ---------------------------------- -- insert -- | Inserts an element whith the given 'MBB' and a value in a tree. The combining function will be used if the value already exists. insertWith :: (a -> a -> a) -> MBB -> a -> RTree a -> RTree a insertWith f mbb e oldRoot = RTree $ insertWithStrictLazy f mbb e (toLazy oldRoot) insertWithStrictLazy :: (a -> a -> a) -> MBB -> a -> Lazy.RTree a -> Lazy.RTree a insertWithStrictLazy f mbb e oldRoot = unionDistinctWith f (toLazy $ singleton mbb e) oldRoot -- | Inserts an element whith the given 'MBB' and a value in a tree. An existing value will be overwritten with the given one. -- -- prop> insert = insertWith const insert :: MBB -> a -> RTree a -> RTree a insert = insertWith const simpleMergeEqNode :: (a -> a -> a) -> Lazy.RTree a -> Lazy.RTree a -> Lazy.RTree a simpleMergeEqNode f l@Lazy.Leaf{} r = Lazy.Leaf (Lazy.getMBB l) $! (on f Lazy.getElem l r) simpleMergeEqNode _ l _ = l -- | Unifies left and right 'RTree'. Will create invalid trees, if the tree is not a leaf and contains 'MBB's which -- also exists in the left tree. Much faster than union, though. unionDistinctWith :: (a -> a -> a) -> Lazy.RTree a -> Lazy.RTree a -> Lazy.RTree a unionDistinctWith _ Lazy.Empty{} t = t unionDistinctWith _ t Lazy.Empty{} = t unionDistinctWith f t1@Lazy.Leaf{} t2@Lazy.Leaf{} | on (==) Lazy.getMBB t1 t2 = simpleMergeEqNode f t1 t2 | otherwise = Lazy.createNodeWithChildren [t1, t2] -- root case unionDistinctWith f left right | Lazy.depth left > Lazy.depth right = unionDistinctWith f right left | Lazy.depth left == Lazy.depth right = fromList' $ (Lazy.getChildren left) ++ [right] | (L.length $ Lazy.getChildren newNode) > Lazy.n = Lazy.createNodeWithChildren $ Lazy.splitNode newNode | otherwise = newNode where newNode = addLeaf f left right -- | Unifies left and right 'RTree'. Will create invalid trees, if the tree is not a leaf and contains 'MBB's which -- also exists in the left tree. Much faster than union, though. unionDistinct :: Lazy.RTree a -> Lazy.RTree a -> Lazy.RTree a unionDistinct = unionDistinctWith const addLeaf :: (a -> a -> a) -> Lazy.RTree a -> Lazy.RTree a -> Lazy.RTree a addLeaf f left right | Lazy.depth left + 1 == Lazy.depth right = Lazy.node (newNode `Lazy.unionMBB'` right) (newNode : nonEq) | otherwise = Lazy.node (left `Lazy.unionMBB'` right) newChildren where newChildren = findNodeWithMinimalAreaIncrease f left (Lazy.getChildren right) (eq, nonEq) = Lazy.partition (on (==) Lazy.getMBB left) $ Lazy.getChildren right newNode = case eq of [] -> left [x] -> simpleMergeEqNode f left x _ -> error "addLeaf: invalid RTree" findNodeWithMinimalAreaIncrease :: (a -> a -> a) -> Lazy.RTree a -> [Lazy.RTree a] -> [Lazy.RTree a] findNodeWithMinimalAreaIncrease f leaf children = splitMinimal xsAndIncrease where -- xsAndIncrease :: [(RTree a, Double)] xsAndIncrease = zip children ((Lazy.areaIncreasesWith leaf) <$> children) minimalIncrease = minimum $ snd <$> xsAndIncrease -- xsAndIncrease' :: [(RTree a, Double)] splitMinimal [] = [] splitMinimal ((t,mbb):xs) | mbb == minimalIncrease = unionDistinctSplit f leaf t ++ (fst <$> xs) | otherwise = t : splitMinimal xs unionDistinctSplit :: (a -> a -> a) -> Lazy.RTree a -> Lazy.RTree a -> [Lazy.RTree a] unionDistinctSplit f leaf e | (L.length $ Lazy.getChildren newLeaf) > Lazy.n = Lazy.splitNode newLeaf | otherwise = [newLeaf] where newLeaf = addLeaf f leaf e -- ----------------- -- lookup -- | returns the value if it exists in the tree lookup :: MBB -> RTree a -> Maybe a lookup mbb = Lazy.lookup mbb . toLazy -- | returns all keys and values, which intersect with the given bounding box. intersectWithKey :: MBB -> RTree a -> [(MBB, a)] intersectWithKey mbb = Lazy.intersectWithKey mbb . toLazy -- | returns all values, which intersect with the given bounding box intersect :: MBB -> RTree a -> [a] intersect mbb = Lazy.intersect mbb . toLazy -- | returns all keys and values, which are located in the given bounding box. lookupRangeWithKey :: MBB -> RTree a -> [(MBB, a)] lookupRangeWithKey mbb = Lazy.lookupRangeWithKey mbb . toLazy -- | returns all values, which are located in the given bounding box. lookupRange :: MBB -> RTree a -> [a] lookupRange mbb = Lazy.lookupRange mbb . toLazy -- | returns all keys and values containing the given bounding box lookupContainsRangeWithKey :: MBB -> RTree a -> [(MBB, a)] lookupContainsRangeWithKey mbb = Lazy.lookupContainsRangeWithKey mbb . toLazy -- | returns all values containing the given bounding box lookupContainsRange :: MBB -> RTree a -> [a] lookupContainsRange mbb = Lazy.lookupContainsRange mbb .toLazy -- ----------- -- delete -- | Delete a key and its value from the RTree. When the key is not a member of the tree, the original tree is returned. delete :: MBB -> RTree a -> RTree a delete mbb = RTree . Lazy.delete mbb . toLazy -- --------------- -- | Unifies the first and the second tree into one. The combining function is used for elemets which exists in both trees. unionWith :: (a -> a -> a) -> RTree a -> RTree a -> RTree a unionWith f' l' r' = RTree $ unionWith' f' (toLazy l') (toLazy r') where unionWith' _ l Lazy.Empty = l unionWith' _ Lazy.Empty r = r unionWith' f t1 t2 | Lazy.depth t1 <= Lazy.depth t2 = foldr (uncurry (insertWithStrictLazy f)) t2 (Lazy.toList t1) | otherwise = unionWith' f t2 t1 -- | Unifies the first and the second tree into one. -- If an 'MBB' is a key in both trees, the value from the left tree is chosen. -- -- prop> union = unionWith const union :: RTree a -> RTree a -> RTree a union = unionWith const -- | map, which also filters Nothing values mapMaybe :: (a -> Maybe b) -> RTree a -> RTree b mapMaybe f t = fromList $ Maybe.mapMaybe func $ toList t where func (mbb,x) = case f x of Nothing -> Nothing Just x' -> Just (mbb, x') -- | maps strictly over the 'RTree' map :: (a -> b) -> RTree a -> RTree b map f' = RTree . map' f' . toLazy where map' f (Lazy.Node4 mbb x y z w) = Lazy.Node4 mbb (map' f x) (map' f y) (map' f z) (map' f w) map' f (Lazy.Node3 mbb x y z) = Lazy.Node3 mbb (map' f x) (map' f y) (map' f z) map' f (Lazy.Node2 mbb x y) = Lazy.Node2 mbb (map' f x) (map' f y) map' f (Lazy.Node mbb xs) = Lazy.Node mbb (map' f <$> xs) map' f (Lazy.Leaf mbb e) = toLazy $ singleton mbb (f e) map' _ Lazy.Empty = Lazy.Empty -- ---------------------- -- | returns the number of elements in a tree length :: RTree a -> Int length = Lazy.length . toLazy -- | 'RTree' is not really a Functor. -- Because this law doesn't hold: -- -- prop> fmap id = id instance Functor RTree where fmap = map
{ "content_hash": "11e8b27396605036aae59a0ef11148f8", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 183, "avg_line_length": 34.966442953020135, "alnum_prop": 0.6324376199616123, "repo_name": "sebastian-philipp/r-tree", "id": "d67a4ffad7cacfcf228411e623ac8e2528398e9c", "size": "10420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Data/RTree/Strict.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "50389" }, { "name": "Makefile", "bytes": "284" } ], "symlink_target": "" }
Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/humweb/menus-module). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Running Tests ``` bash $ phpunit ``` **Happy coding**!
{ "content_hash": "eb0067c34954c4dbc875dae675c7148a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 302, "avg_line_length": 39.666666666666664, "alnum_prop": 0.7336134453781512, "repo_name": "humweb/menus-module", "id": "adc1f5e0447b62779608c9060cec7c4e714d18a7", "size": "1206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/CONTRIBUTING.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "12541" }, { "name": "PHP", "bytes": "33795" } ], "symlink_target": "" }
To refer to these instructions while editing the flow, open [the github page](Sync%20new%20attendee%20from%20Eventbrite%20to%20lead%20in%20Insightly_instructions.md) (opens in a new window). 1. Click **Create flow** to start using the template. 2. Connect to the following accounts by using your credentials: - **Eventbrite** - **Insightly** 3. To start the flow, in the banner, open the options menu [⋮] and click **Start flow**. The flow is started when a new attendee is created in Eventbrite.
{ "content_hash": "bc49a2fa01248213f25328acfee0c32b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 190, "avg_line_length": 56.888888888888886, "alnum_prop": 0.740234375, "repo_name": "ot4i/app-connect-templates", "id": "00cd7ddf815c04f3680987c5aa321f16b8f4a6db", "size": "514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/markdown/Sync new attendee from Eventbrite to lead in Insightly_instructions.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4108" } ], "symlink_target": "" }
""" BenchmarkDefinition model """ import datetime from django.db import models from django.db.models import signals from django.dispatch.dispatcher import receiver from app.logic.commandrepo.models.CommandSetModel import CommandSetEntry class BenchmarkDefinitionEntry(models.Model): """ Benchmark Definition """ VERY_LOW = 0 LOW = 1 NORMAL = 2 HIGH = 3 VERY_HIGH = 4 PROPRITY_TYPE = ( (VERY_LOW, 'VeryLow'), (LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'), (VERY_HIGH, 'VeryHigh'), ) name = models.CharField(default='Default benchmark name', max_length=128) layout = models.ForeignKey('bluesteel.BluesteelLayoutEntry', related_name='benchmark_layout') project = models.ForeignKey('bluesteel.BluesteelProjectEntry', related_name='benchmark_project') command_set = models.ForeignKey('commandrepo.CommandSetEntry', related_name='benchmark_command_set') priority = models.IntegerField(choices=PROPRITY_TYPE, default=NORMAL) active = models.BooleanField(default=False) revision = models.IntegerField(default=0) max_fluctuation_percent = models.IntegerField(default=0) max_weeks_old_notify = models.IntegerField(default=1) max_benchmark_date = models.DateTimeField(default=datetime.datetime( 1970, 1, 1, 0, 0, 0, 0, tzinfo=datetime.timezone.utc)) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) def __unicode__(self): return u'Benchmark Definition id:{0} name:{1}'.format( self.id, self.name, ) def as_object(self): """ Returns Benchmark Definition as an object""" month_names = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] obj = {} obj['id'] = self.id obj['name'] = self.name obj['layout'] = {} obj['layout']['id'] = self.layout.id obj['layout']['name'] = self.layout.name obj['layout']['uuid'] = self.layout.get_uuid() obj['project'] = {} obj['project']['id'] = self.project.id obj['project']['name'] = self.project.name obj['project']['uuid'] = self.project.get_uuid() obj['project']['git_project_folder_search_path'] = self.project.git_project_folder_search_path obj['command_set'] = self.command_set.as_object() obj['priority'] = {} obj['priority']['current'] = self.priority obj['priority']['names'] = ['VERY LOW', 'LOW', 'NORMAL', 'HIGH', 'VERY HIGH'] obj['active'] = self.active obj['revision'] = self.revision obj['max_fluctuation_percent'] = self.max_fluctuation_percent obj['max_weeks_old_notify'] = {} obj['max_weeks_old_notify']['current_value'] = self.max_weeks_old_notify obj['max_weeks_old_notify']['current_name'] = '' obj['max_weeks_old_notify']['names'] = self.get_max_weeks_old_names_and_values() obj['max_benchmark_date'] = {} obj['max_benchmark_date']['year'] = self.max_benchmark_date.year obj['max_benchmark_date']['month'] = {} obj['max_benchmark_date']['month']['number'] = self.max_benchmark_date.month obj['max_benchmark_date']['month']['name'] = month_names[self.max_benchmark_date.month - 1] obj['max_benchmark_date']['day'] = self.max_benchmark_date.day for val in obj['max_weeks_old_notify']['names']: if val['current']: obj['max_weeks_old_notify']['current_name'] = val['name'] return obj def increment_revision(self): self.revision = self.revision + 1 self.save() def get_max_weeks_old_names_and_values(self): """ Returns names, values, and current for all the possible weeks available """ values = [ {'name' : 'Allways', 'weeks' : -1}, {'name' : 'Never', 'weeks' : 0}, {'name' : '1 Week', 'weeks' : 1}, {'name' : '2 Weeks', 'weeks' : 2}, {'name' : '3 Weeks', 'weeks' : 3}, {'name' : '1 Month', 'weeks' : 4}, {'name' : '2 Months', 'weeks' : 8}, {'name' : '3 Months', 'weeks' : 12}, {'name' : '4 Months', 'weeks' : 16}, {'name' : '5 Months', 'weeks' : 20}, {'name' : '6 Months', 'weeks' : 24}, {'name' : '1 Year', 'weeks' : 52}, {'name' : '2 Years', 'weeks' : 104}, {'name' : '3 Years', 'weeks' : 156}, {'name' : '4 Years', 'weeks' : 208}, {'name' : '5 Years', 'weeks' : 260}, {'name' : '10 Years', 'weeks' : 520} ] for val in values: val['current'] = val['weeks'] == self.max_weeks_old_notify return values @receiver(models.signals.post_delete) def benchmark_def_entry_post_delete(sender, instance, **kwargs): """ This function will delete the command_set on any delete of this model """ del kwargs if isinstance(instance, BenchmarkDefinitionEntry) and (sender == BenchmarkDefinitionEntry): signals.post_delete.disconnect(benchmark_def_entry_post_delete, sender=BenchmarkDefinitionEntry) try: if instance.command_set and instance.command_set.id is not None: instance.command_set.delete() except CommandSetEntry.DoesNotExist: pass signals.post_delete.connect(benchmark_def_entry_post_delete, sender=BenchmarkDefinitionEntry)
{ "content_hash": "aee4d9f43e62a31a28a35fc017bb65ca", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 104, "avg_line_length": 40.4, "alnum_prop": 0.5836280056577087, "repo_name": "imvu/bluesteel", "id": "651503a08effc65425ff37d9e724a74ca9778286", "size": "5656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/logic/benchmark/models/BenchmarkDefinitionModel.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16828" }, { "name": "HTML", "bytes": "119014" }, { "name": "JavaScript", "bytes": "36015" }, { "name": "Python", "bytes": "1220104" } ], "symlink_target": "" }
@implementation FMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
{ "content_hash": "25dae73e778e5f9abc812efc9ee45f94", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 281, "avg_line_length": 51.111111111111114, "alnum_prop": 0.7885869565217392, "repo_name": "nicfzhou/FMLibrary", "id": "c1d6f76fd18e6a9d9307a6a94dfcf83ff39adf65", "size": "2004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/FMLibrary/FMAppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "65880" }, { "name": "Ruby", "bytes": "2745" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_162) on Wed Sep 25 19:26:34 PDT 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JsonTypeName (Jackson-annotations 2.10.0 API)</title> <meta name="date" content="2019-09-25"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="JsonTypeName (Jackson-annotations 2.10.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../com/fasterxml/jackson/annotation/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JsonTypeName.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/fasterxml/jackson/annotation/JsonTypeInfo.None.html" title="class in com.fasterxml.jackson.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/fasterxml/jackson/annotation/JsonUnwrapped.html" title="annotation in com.fasterxml.jackson.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/fasterxml/jackson/annotation/JsonTypeName.html" target="_top">Frames</a></li> <li><a href="JsonTypeName.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.fasterxml.jackson.annotation</div> <h2 title="Annotation Type JsonTypeName" class="title">Annotation Type JsonTypeName</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Target.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>={<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html?is-external=true#ANNOTATION_TYPE" title="class or interface in java.lang.annotation">ANNOTATION_TYPE</a>,<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html?is-external=true#TYPE" title="class or interface in java.lang.annotation">TYPE</a>}) <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Retention.html?is-external=true#value--" title="class or interface in java.lang.annotation">value</a>=<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/RetentionPolicy.html?is-external=true#RUNTIME" title="class or interface in java.lang.annotation">RUNTIME</a>) public @interface <span class="memberNameLabel">JsonTypeName</span></pre> <div class="block">Annotation used for binding logical name that the annotated class has. Used with <a href="../../../../com/fasterxml/jackson/annotation/JsonTypeInfo.html" title="annotation in com.fasterxml.jackson.annotation"><code>JsonTypeInfo</code></a> (and specifically its <a href="../../../../com/fasterxml/jackson/annotation/JsonTypeInfo.html#use--"><code>JsonTypeInfo.use()</code></a> property) to establish relationship between type names and types.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>tatu</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.optional.element.summary"> <!-- --> </a> <h3>Optional Element Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation"> <caption><span>Optional Elements</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Optional Element and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/fasterxml/jackson/annotation/JsonTypeName.html#value--">value</a></span></code> <div class="block">Logical type name for annotated type.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation.type.element.detail"> <!-- --> </a> <h3>Element Detail</h3> <a name="value--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>value</h4> <pre>public abstract&nbsp;<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;value</pre> <div class="block">Logical type name for annotated type. If missing (or defined as Empty String), defaults to using non-qualified class name as the type.</div> <dl> <dt>Default:</dt> <dd>""</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../com/fasterxml/jackson/annotation/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/JsonTypeName.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/fasterxml/jackson/annotation/JsonTypeInfo.None.html" title="class in com.fasterxml.jackson.annotation"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/fasterxml/jackson/annotation/JsonUnwrapped.html" title="annotation in com.fasterxml.jackson.annotation"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/fasterxml/jackson/annotation/JsonTypeName.html" target="_top">Frames</a></li> <li><a href="JsonTypeName.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation.type.optional.element.summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#annotation.type.element.detail">Element</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2008&#x2013;2019 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "a114194cd6f0a729aec46c193684ac22", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 709, "avg_line_length": 42.2532751091703, "alnum_prop": 0.6655642827614717, "repo_name": "FasterXML/jackson-annotations", "id": "10a8906c774e788d746e9a66542a16a78e4deb56", "size": "9676", "binary": false, "copies": "1", "ref": "refs/heads/2.15", "path": "docs/javadoc/2.10/com/fasterxml/jackson/annotation/JsonTypeName.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "241575" }, { "name": "Logos", "bytes": "7816" } ], "symlink_target": "" }
package com.zulip.android.networking.response.events; import com.google.gson.annotations.SerializedName; import com.zulip.android.models.Presence; public class PresenceWrapper extends EventsBranch { @SerializedName("server_timestamp") private double serverTimestamp; @SerializedName("email") private String email; @SerializedName("presence") private Presence presence; public Presence getPresence() { return presence; } public double getServerTimestamp() { return serverTimestamp; } public String getEmail() { return email; } }
{ "content_hash": "6a06d78e098603da2123d390fc343bfc", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 53, "avg_line_length": 21, "alnum_prop": 0.7060755336617406, "repo_name": "saketkumar95/zulip-android", "id": "9e5b83ae304b37f493472d2c39e9bb45c531f3eb", "size": "609", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/zulip/android/networking/response/events/PresenceWrapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "21993" }, { "name": "Java", "bytes": "453509" } ], "symlink_target": "" }
package org.apache.sshd.server.kex; import java.security.KeyPair; import java.security.PublicKey; import org.apache.sshd.common.Digest; import org.apache.sshd.common.KeyExchange; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.Signature; import org.apache.sshd.common.SshConstants; import org.apache.sshd.common.SshException; import org.apache.sshd.common.digest.SHA1; import org.apache.sshd.common.kex.DH; import org.apache.sshd.common.session.AbstractSession; import org.apache.sshd.common.util.Buffer; import org.apache.sshd.common.util.BufferUtils; import org.apache.sshd.server.session.ServerSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * TODO Add javadoc * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public abstract class AbstractDHGServer implements KeyExchange { private final Log log = LogFactory.getLog(getClass()); private ServerSession session; private byte[] V_S; private byte[] V_C; private byte[] I_S; private byte[] I_C; private Digest sha; private DH dh; private byte[] e; private byte[] f; private byte[] K; private byte[] H; public void init(AbstractSession s, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception { if (!(s instanceof ServerSession)) { throw new IllegalStateException("Using a server side KeyExchange on a client"); } session = (ServerSession) s; this.V_S = V_S; this.V_C = V_C; this.I_S = I_S; this.I_C = I_C; sha = new SHA1(); sha.init(); dh = new DH(); initDH(dh); f = dh.getE(); } protected abstract void initDH(DH dh); public boolean next(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); if (cmd != SshConstants.Message.SSH_MSG_KEXDH_INIT) { throw new SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, "Protocol error: expected packet " + SshConstants.Message.SSH_MSG_KEXDH_INIT + ", got " + cmd); } log.info("Received SSH_MSG_KEXDH_INIT"); e = buffer.getMPIntAsBytes(); dh.setF(e); K = dh.getK(); byte[] K_S; KeyPair kp = session.getHostKey(); String algo = session.getNegociated(SshConstants.PROPOSAL_SERVER_HOST_KEY_ALGS); Signature sig = NamedFactory.Utils.create(session.getFactoryManager().getSignatureFactories(), algo); sig.init(kp.getPublic(), kp.getPrivate()); buffer = new Buffer(); buffer.putRawPublicKey(kp.getPublic()); K_S = buffer.getCompactData(); buffer.clear(); buffer.putString(V_C); buffer.putString(V_S); buffer.putString(I_C); buffer.putString(I_S); buffer.putString(K_S); buffer.putMPInt(e); buffer.putMPInt(f); buffer.putMPInt(K); sha.update(buffer.array(), 0, buffer.available()); H = sha.digest(); byte[] sigH; buffer.clear(); sig.update(H, 0, H.length); buffer.putString(algo); buffer.putString(sig.sign()); sigH = buffer.getCompactData(); if (log.isDebugEnabled()) { log.debug("K_S: "+BufferUtils.printHex(K_S)); log.debug("f: "+ BufferUtils.printHex(f)); log.debug("sigH: "+ BufferUtils.printHex(sigH)); } // Send response log.info("Send SSH_MSG_KEXDH_REPLY"); buffer.clear(); buffer.rpos(5); buffer.wpos(5); buffer.putCommand(SshConstants.Message.SSH_MSG_KEXDH_REPLY_KEX_DH_GEX_GROUP); buffer.putString(K_S); buffer.putString(f); buffer.putString(sigH); session.writePacket(buffer); return true; } public Digest getHash() { return sha; } public byte[] getH() { return H; } public byte[] getK() { return K; } public PublicKey getServerKey() { return session.getHostKey().getPublic(); } }
{ "content_hash": "975918c65110619e85e34c9a3a6664c1", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 130, "avg_line_length": 30.470588235294116, "alnum_prop": 0.6163127413127413, "repo_name": "Fob/Asynchronous-SSHD", "id": "57a948d9430a8932ebe6d48b0c5805d1fe31397f", "size": "4951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sshd-core/src/main/java/org/apache/sshd/server/kex/AbstractDHGServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "691373" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "65498f758a1743ac3dd2eae450c6505e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "9d9164f84ed5846a7ad449a48ef64d49831458a8", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Dryopteris/Dryopteris parachinensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
""" cal_lib.py - Ellipsoid into Sphere calibration library based upon numpy and linalg Copyright (C) 2012 Fabio Varesano <fabio at varesano dot net> Development of this code has been supported by the Department of Computer Science, Universita' degli Studi di Torino, Italy within the Piemonte Project http://www.piemonte.di.unito.it/ This program is free software: you can redistribute it and/or modify it under the terms of the version 3 GNU General Public License 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, see <http://www.gnu.org/licenses/>. """ import numpy from numpy import linalg def calibrate(x, y, z): H = numpy.array([x, y, z, -y**2, -z**2, numpy.ones([len(x), 1])]) H = numpy.transpose(H) w = x**2 (X, residues, rank, shape) = linalg.lstsq(H, w) OSx = X[0] / 2 OSy = X[1] / (2 * X[3]) OSz = X[2] / (2 * X[4]) A = X[5] + OSx**2 + X[3] * OSy**2 + X[4] * OSz**2 B = A / X[3] C = A / X[4] SCx = numpy.sqrt(A) SCy = numpy.sqrt(B) SCz = numpy.sqrt(C) # type conversion from numpy.float64 to standard python floats offsets = [OSx, OSy, OSz] scale = [SCx, SCy, SCz] offsets = map(numpy.asscalar, offsets) scale = map(numpy.asscalar, scale) return (offsets, scale) def calibrate_from_file(file_name): samples_f = open(file_name, 'r') samples_x = [] samples_y = [] samples_z = [] for line in samples_f: reading = line.split() if len(reading) == 3: samples_x.append(int(reading[0])) samples_y.append(int(reading[1])) samples_z.append(int(reading[2])) return calibrate(numpy.array(samples_x), numpy.array(samples_y), numpy.array(samples_z)) def compute_calibrate_data(data, offsets, scale): output = [[], [], []] for i in range(len(data[0])): output[0].append((data[0][i] - offsets[0]) / scale[0]) output[1].append((data[1][i] - offsets[1]) / scale[1]) output[2].append((data[2][i] - offsets[2]) / scale[2]) return output if __name__ == "__main__": print "Calibrating from acc.txt" (offsets, scale) = calibrate_from_file("acc.txt") print "Offsets:" print offsets print "Scales:" print scale print "Calibrating from magn.txt" (offsets, scale) = calibrate_from_file("magn.txt") print "Offsets:" print offsets print "Scales:" print scale
{ "content_hash": "082ccc7f0ad837f2febdce4ee6dae4bd", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 90, "avg_line_length": 27.416666666666668, "alnum_prop": 0.6610942249240122, "repo_name": "murix/beaglebonequadcopter", "id": "739a8192539a7c812272c7f962450b830e49308f", "size": "2632", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "quad-calibration/cal_lib.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3621" }, { "name": "C", "bytes": "42473" }, { "name": "C#", "bytes": "34092" }, { "name": "C++", "bytes": "259027" }, { "name": "CSS", "bytes": "3569" }, { "name": "HTML", "bytes": "388060" }, { "name": "Java", "bytes": "709061" }, { "name": "Makefile", "bytes": "104" }, { "name": "Processing", "bytes": "420991" }, { "name": "Python", "bytes": "24000" }, { "name": "Shell", "bytes": "1689" }, { "name": "XML", "bytes": "76829" } ], "symlink_target": "" }
START_ATF_NAMESPACE namespace vc_attributes { template<> struct hookAttribute { const char *event; const char *source; const char *handler; const char *receiver; }; }; // end namespace vc_attributes END_ATF_NAMESPACE
{ "content_hash": "6de28dd150b738e081e5e66850d671f6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 37, "avg_line_length": 23.76923076923077, "alnum_prop": 0.5372168284789643, "repo_name": "goodwinxp/Yorozuya", "id": "11004e51a2d269337c1de2a05ec987f22d251cec", "size": "461", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/ATF/__hookAttribute.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "207291" }, { "name": "C++", "bytes": "21670817" } ], "symlink_target": "" }
import React, { Component } from "react"; import { css } from "glamor"; class DaySwitcher extends Component { state = { selectedDay: 0 }; changeDay(day, index) { this.props.changeDay(day); this.setState({ selectedDay: index }); } render() { // truncate slider width to 3 decimals const sliderWidth = Math.trunc(100000 / this.props.days.length) / 1000; const sliderCss = { position: "absolute", left: `${this.state.selectedDay * sliderWidth}%`, top: 0, height: "44px", backgroundColor: "#00205B", borderRadius: "20px", width: `${sliderWidth}%`, zIndex: 2, transition: "left 0.3s ease" }; const navBarCss = css({ display: "grid", gridTemplateColumns: `repeat(${this.props.days.length}, 1fr)`, width: "66%", "@media screen and (max-width: 760px)": { width: "100%" }, maxWidth: "600px", margin: "20px auto 35px auto", backgroundColor: "#FFFFFF", height: "44px", position: "relative", zIndex: 2, border: "0.5px solid #00205B", borderRadius: "100px", "> button.dayItem": { textAlign: "center", lineHeight: "44px", textTransform: "uppercase", fontWeight: "bold", cursor: "pointer", background: "none", border: "none", fontSize: "18px", zIndex: 3, transition: "color 1s ease" }, "> button.dayItem.selectedDay": { color: "white" }, "> button.dayItem:not(.selectedDay)": { color: "#4d4d4d" }, "> button.dayItem:not(.selectedDay):hover": { color: "#00205B" } }); const navItems = this.props.days.map((day, i) => ( <button key={day} onClick={() => this.changeDay(day, i)} className={ this.state.selectedDay === i ? "selectedDay dayItem" : "dayItem" } > Day {i + 1} </button> )); return ( <div {...navBarCss}> {navItems} <div role="none presentation" css={{ ...sliderCss }} /> </div> ); } } export default DaySwitcher;
{ "content_hash": "81201a91b0839516c0ab13c9725c56a8", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 75, "avg_line_length": 24.735632183908045, "alnum_prop": 0.5343866171003717, "repo_name": "QHacks/QHacks-Website", "id": "0aea41d05feb0fe62dc64f1f046d71e66589604d", "size": "2152", "binary": false, "copies": "1", "ref": "refs/heads/qhacks-2021", "path": "src/components/DaySwitcher.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13800" }, { "name": "HTML", "bytes": "40327" }, { "name": "JavaScript", "bytes": "27898" } ], "symlink_target": "" }
using System; using System.Linq; using System.Windows; namespace GoldenAnvil.Utility.Windows.Theme { public static class ThemesUtility { public static ResourceDictionary CurrentThemeDictionary { get; private set; } public static readonly DependencyProperty CurrentThemeUrlProperty = DependencyProperty.RegisterAttached("CurrentThemeUrl", typeof(Uri), typeof(ThemesUtility), new UIPropertyMetadata(null, OnCurrentThemeDictionaryChanged)); public static Uri GetCurrentThemeUrl(DependencyObject d) { return (Uri) d.GetValue(CurrentThemeUrlProperty); } public static void SetCurrentThemeUrl(DependencyObject d, Uri value) { d.SetValue(CurrentThemeUrlProperty, value); } public static readonly DependencyProperty ShouldInvalidateOnThemeChangeProperty = DependencyProperty.RegisterAttached("ShouldInvalidateOnThemeChange", typeof(bool), typeof(ThemesUtility), new UIPropertyMetadata(false, OnShouldInvalidateOnThemeChangeChanged)); public static bool GetShouldInvalidateOnThemeChange(DependencyObject d) { return (bool) d.GetValue(ShouldInvalidateOnThemeChangeProperty); } public static void SetShouldInvalidateOnThemeChange(DependencyObject d, bool value) { d.SetValue(ShouldInvalidateOnThemeChangeProperty, value); } public static readonly RoutedEvent NeedsInvalidateVisualEvent = EventManager.RegisterRoutedEvent("NeedsInvalidate", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(ThemesUtility)); public static void AddNeedsInvalidateVisualHandler(DependencyObject d, RoutedEventHandler handler) { if (d is UIElement element) element.AddHandler(NeedsInvalidateVisualEvent, handler); } public static void RemoveNeedsInvalidateVisualHandler(DependencyObject d, RoutedEventHandler handler) { if (d is UIElement element) element.RemoveHandler(NeedsInvalidateVisualEvent, handler); } private static void OnCurrentThemeDictionaryChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is FrameworkElement element) ApplyTheme(element, GetCurrentThemeUrl(d)); } private static void ApplyTheme(FrameworkElement element, Uri dictionaryUri) { var existingDictionaries = element.Resources.MergedDictionaries.OfType<ThemeResourceDIctionary>().ToList(); foreach (var dictionary in existingDictionaries) element.Resources.MergedDictionaries.Remove(dictionary); if (dictionaryUri != null) { CurrentThemeDictionary = new ThemeResourceDIctionary { Source = dictionaryUri }; element.Resources.MergedDictionaries.Insert(0, CurrentThemeDictionary); } else { CurrentThemeDictionary = null; } element.RaiseEvent(new RoutedEventArgs(NeedsInvalidateVisualEvent)); } private static void OnShouldInvalidateOnThemeChangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is UIElement element) { var value = d.GetValue(ShouldInvalidateOnThemeChangeProperty); if (value == DependencyProperty.UnsetValue || ((bool) value) == false) RemoveNeedsInvalidateVisualHandler(element, OnNeedsInvalidate); else if ((bool) value) AddNeedsInvalidateVisualHandler(element, OnNeedsInvalidate); } } private static void OnNeedsInvalidate(object sender, RoutedEventArgs e) { if (sender is UIElement element) { element.InvalidateVisual(); element.InvalidateArrange(); } } private sealed class ThemeResourceDIctionary : ResourceDictionary { } } }
{ "content_hash": "1f70383aa5b3dacd97f0e61e091742ea", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 261, "avg_line_length": 34.66, "alnum_prop": 0.7893825735718407, "repo_name": "SaberSnail/GoldenAnvil.Utility", "id": "95651b2e5d713c95131d41b104fe98b7c0b7fa92", "size": "3468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GoldenAnvil.Utility.Windows/Theme/ThemesUtility.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "114982" } ], "symlink_target": "" }
#ifndef AST_h #define AST_h 1 #include "config.h" #include "parser.h" #include "structures.h" #include "sym_table.h" typedef struct Expr Expr; typedef struct Arg_List Arg_List; typedef struct Stmt Stmt; typedef struct Cond_Arm Cond_Arm; typedef struct Except_Arm Except_Arm; typedef struct Scatter Scatter; struct Expr_Binary { Expr *lhs, *rhs; }; enum Arg_Kind { ARG_NORMAL, ARG_SPLICE }; struct Arg_List { Arg_List *next; enum Arg_Kind kind; Expr *expr; }; enum Scatter_Kind { SCAT_REQUIRED, SCAT_OPTIONAL, SCAT_REST }; struct Scatter { Scatter *next; enum Scatter_Kind kind; int id; Expr *expr; /* These fields for convenience during code generation and decompiling */ int label, next_label; }; struct Expr_Call { unsigned func; Arg_List *args; }; struct Expr_Verb { Expr *obj, *verb; Arg_List *args; }; struct Expr_Range { Expr *base, *from, *to; }; struct Expr_Cond { Expr *condition, *consequent, *alternate; }; struct Expr_Catch { Expr *try; Arg_List *codes; Expr *except; }; enum Expr_Kind { EXPR_VAR, EXPR_ID, EXPR_PROP, EXPR_VERB, EXPR_INDEX, EXPR_RANGE, EXPR_ASGN, EXPR_CALL, EXPR_PLUS, EXPR_MINUS, EXPR_TIMES, EXPR_DIVIDE, EXPR_MOD, EXPR_EXP, EXPR_NEGATE, EXPR_AND, EXPR_OR, EXPR_NOT, EXPR_EQ, EXPR_NE, EXPR_LT, EXPR_LE, EXPR_GT, EXPR_GE, EXPR_IN, EXPR_LIST, EXPR_COND, EXPR_CATCH, EXPR_LENGTH, EXPR_SCATTER, SizeOf_Expr_Kind /* The last element is also the number of elements... */ }; union Expr_Data { Var var; int id; struct Expr_Binary bin; struct Expr_Call call; struct Expr_Verb verb; struct Expr_Range range; struct Expr_Cond cond; struct Expr_Catch catch; Expr *expr; Arg_List *list; Scatter *scatter; }; struct Expr { enum Expr_Kind kind; union Expr_Data e; }; struct Cond_Arm { Cond_Arm *next; Expr *condition; Stmt *stmt; }; struct Except_Arm { Except_Arm *next; int id; Arg_List *codes; Stmt *stmt; /* This field is for convenience during code generation and decompiling */ int label; }; struct Stmt_Cond { Cond_Arm *arms; Stmt *otherwise; }; struct Stmt_List { int id; Expr *expr; Stmt *body; }; struct Stmt_Range { int id; Expr *from, *to; Stmt *body; }; struct Stmt_Loop { int id; Expr *condition; Stmt *body; }; struct Stmt_Fork { int id; Expr *time; Stmt *body; }; struct Stmt_Catch { Stmt *body; Except_Arm *excepts; }; struct Stmt_Finally { Stmt *body; Stmt *handler; }; enum Stmt_Kind { STMT_COND, STMT_LIST, STMT_RANGE, STMT_WHILE, STMT_FORK, STMT_EXPR, STMT_RETURN, STMT_TRY_EXCEPT, STMT_TRY_FINALLY, STMT_BREAK, STMT_CONTINUE }; union Stmt_Data { struct Stmt_Cond cond; struct Stmt_List list; struct Stmt_Range range; struct Stmt_Loop loop; struct Stmt_Fork fork; struct Stmt_Catch catch; struct Stmt_Finally finally; Expr *expr; int exit; }; struct Stmt { Stmt *next; enum Stmt_Kind kind; union Stmt_Data s; }; extern void begin_code_allocation(void); extern void end_code_allocation(int); extern Stmt *alloc_stmt(enum Stmt_Kind); extern Cond_Arm *alloc_cond_arm(Expr *, Stmt *); extern Expr *alloc_expr(enum Expr_Kind); extern Expr *alloc_var(var_type); extern Expr *alloc_binary(enum Expr_Kind, Expr *, Expr *); extern Expr *alloc_verb(Expr *, Expr *, Arg_List *); extern Arg_List *alloc_arg_list(enum Arg_Kind, Expr *); extern Except_Arm *alloc_except(int, Arg_List *, Stmt *); extern Scatter *alloc_scatter(enum Scatter_Kind, int, Expr *); extern char *alloc_string(const char *); extern double *alloc_float(double); extern void dealloc_node(void *); extern void dealloc_string(char *); extern void free_stmt(Stmt *); #endif /* !AST_h */ /* * $Log: ast.h,v $ * Revision 1.3 1998/12/14 13:17:28 nop * Merge UNSAFE_OPTS (ref fixups); fix Log tag placement to fit CVS whims * * Revision 1.2 1997/03/03 04:18:22 nop * GNU Indent normalization * * Revision 1.1.1.1 1997/03/03 03:45:02 nop * LambdaMOO 1.8.0p5 * * Revision 2.3 1996/02/08 05:59:43 pavel * Updated copyright notice for 1996. Added exponentiation expression, named * WHILE loops, BREAK and CONTINUE statements, support for floating-point. * Release 1.8.0beta1. * * Revision 2.2 1996/01/16 07:13:43 pavel * Add support for scattering assignment. Release 1.8.0alpha6. * * Revision 2.1 1995/12/31 03:14:38 pavel * Added EXPR_LENGTH. Release 1.8.0alpha4. * * Revision 2.0 1995/11/30 04:50:19 pavel * New baseline version, corresponding to release 1.8.0alpha1. * * Revision 1.8 1992/10/23 23:03:47 pavel * Added copyright notice. * * Revision 1.7 1992/10/21 03:02:35 pavel * Converted to use new automatic configuration system. * * Revision 1.6 1992/08/31 22:21:43 pjames * Changed some `char *'s to `const char *' * * Revision 1.5 1992/08/28 23:13:36 pjames * Added ASGN_RANGE to assignment type enumeration. * Added range arm to assigment union. * * Revision 1.4 1992/08/14 00:15:28 pavel * Removed trailing comma in an enumeration. * * Revision 1.3 1992/08/14 00:01:11 pavel * Converted to a typedef of `var_type' = `enum var_type'. * * Revision 1.2 1992/07/30 21:21:21 pjames * Removed max_stack from AST structures. * * Revision 1.1 1992/07/20 23:23:12 pavel * Initial RCS-controlled version. */
{ "content_hash": "149ed7c9cec1660761628b8a65357dcf", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 78, "avg_line_length": 21.888, "alnum_prop": 0.6567982456140351, "repo_name": "coyotebringsfire/MuMoo", "id": "cb31d7f5a505b243053735150d9d0f0a0321c24c", "size": "6398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MOO-1.8.1/ast.h", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "20333" } ], "symlink_target": "" }
%% $Date: 2012-07-06 17:42:54#$ %% $Revision: 148 $ \index{temp\_static\_cnrm} \algdesc{Static Temperature} { %%%%%% Algorithm name %%%%%% temp\_static\_cnrm } { %%%%%% Algorithm summary %%%%%% Calculates static temperature of the air from total temperature. This method applies to probe types such as the Rosemount. } { %%%%%% Category %%%%%% Thermodynamics } { %%%%%% Inputs %%%%%% $T_t$ & Vector & Measured total temperature [K] \\ ${\Delta}P$ & Vector & Dynamic pressure [hPa] \\ $P_s$ & Vector & Static pressure [hPa] \\ $r_f$ & Coeff. & Probe recovery coefficient \\ $R_a/c_{pa}$ & Coeff. & Gas constant of air divided by specific heat of air at constant pressure } { %%%%%% Outputs %%%%%% $T_s$ & Vector & Static temperature [K] } { %%%%%% Formula %%%%%% \begin{displaymath} T_s = \frac{T_t}{1+r_f \left(\left(1+\frac{\Delta P}{P_s}\right)^{R_a/c_{pa}}-1\right)} \nonumber \end{displaymath} } { %%%%%% Author %%%%%% CNRM/GMEI/TRAMM } { %%%%%% References %%%%%% }
{ "content_hash": "c7530572f65b1b86effdf084100a2cba", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 98, "avg_line_length": 28.647058823529413, "alnum_prop": 0.6047227926078029, "repo_name": "eufarn7sp/egads-eufar", "id": "8206bd1ff563aaf25b133f715e821a474ccaf928", "size": "974", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Documentation/EGADS Algorithm Handbook - LATEX/algorithms/thermodynamics/temp_static_cnrm.tex", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "309547" } ], "symlink_target": "" }
package com.bkromhout.ruqus; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.google.auto.common.SuperficialValidation; import com.squareup.javapoet.*; import javax.annotation.processing.Messager; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.MirroredTypesException; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; import java.util.*; /** * Processes all classes annotated with {@link Transformer} in order to generate a file with information about all * transformers for Ruqus to use at runtime (instead of doing a ton of reflection). */ class TransformerDataBuilder { private final Messager messager; private static HashSet<String> realClassNames; private static HashSet<String> realNAClassNames; private static HashMap<String, String> visibleNames; private static HashMap<String, String> visibleNANames; private static HashMap<String, Integer> numArgsMap; private static HashMap<String, ClassName> classMap; private static HashMap<ClassName, HashSet<String>> typesMap; TransformerDataBuilder(Messager messager) { this.messager = messager; realClassNames = new HashSet<>(); realNAClassNames = new HashSet<>(); visibleNames = new HashMap<>(); visibleNANames = new HashMap<>(); numArgsMap = new HashMap<>(); classMap = new HashMap<>(); typesMap = new HashMap<>(); } boolean hasClasses() { return !classMap.isEmpty(); } /** * Process all classes annotated with {@link Transformer} and get information needed to generate the transformer * data file. */ void buildTransformerData(RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(Transformer.class)) { if (!SuperficialValidation.validateElement(element)) continue; if (element.getKind() != ElementKind.CLASS) { error(element, "@Transformer annotations can only be applied to classes!"); continue; } TypeElement typeElement = MoreElements.asType(element); // Get ClassName object, we'll store this so that we can write out a real type later. ClassName className = ClassName.get(typeElement); // Get real class name. String realName = className.toString(); // Get attributes from Transformer annotation. Transformer tAnnot = typeElement.getAnnotation(Transformer.class); String visibleName = tAnnot.name(); List<ClassName> validTypes = getValidTypes(tAnnot); Integer numArgs = tAnnot.numArgs(); Boolean isNoArgs = tAnnot.isNoArgs(); // Validate this transformer class. if (!isValidTransformerClass(typeElement, className, visibleName, validTypes, numArgs, isNoArgs)) continue; // Store information about this transformer so we can write it out later. if (isNoArgs) { realNAClassNames.add(realName); visibleNANames.put(realName, visibleName); } else { realClassNames.add(realName); visibleNames.put(realName, visibleName); numArgsMap.put(realName, numArgs); processValidTypes(realName, validTypes); } classMap.put(realName, className); } } private List<ClassName> getValidTypes(Transformer tAnnot) { List<ClassName> validTypes = new ArrayList<>(); try { // The code smells are strong here, thanks Java API devs... tAnnot.validArgTypes(); } catch (MirroredTypesException e) { for (TypeMirror mirror : e.getTypeMirrors()) validTypes.add(ClassName.get(MoreTypes.asTypeElement(mirror))); } return validTypes; } private void processValidTypes(String realName, List<ClassName> validTypes) { for (ClassName type : validTypes) { if (!typesMap.containsKey(type)) typesMap.put(type, new HashSet<String>()); typesMap.get(type).add(realName); } } private boolean isValidTransformerClass(TypeElement element, ClassName className, String visibleName, List<ClassName> validTypes, Integer numArgs, Boolean isNoArgs) { // Must extend (directly or indirectly) RUQTransformer. if (!Utils.isSubtypeOfType(element.asType(), TypeNames.RUQ_TRANS.toString())) { error(element, "Failed while processing \"%s\" because transformer classes must extend (either directly " + "or indirectly) %s, but instead it extends %s.", ClassName.get(element).toString(), TypeNames.RUQ_TRANS.toString(), element.getSuperclass().toString()); return false; } // Ensure that visible name is non-null and non-empty. if (visibleName == null || visibleName.isEmpty()) { error(element, "Failed while processing \"%s\" because its @Transformer annotation is malformed; name " + "must be non-null and non-empty", className.toString()); return false; } // If this isn't a no-args transformer and numArgs > 0, ensure that we have an array of types. if (!isNoArgs && numArgs != 0 && (validTypes == null || validTypes.isEmpty())) { error(element, "Failed while processing \"%s\" because its @Transformer annotation is malformed; the " + "validArgTypes array must be non-null and non-empty if isNoArgs = false and numArgs > 0.", className.toString()); return false; } // Ensure we don't have any duplicated visible names for each type of transformer. if (isNoArgs && visibleNANames.values().contains(visibleName)) { error(element, "Failed while processing \"%s\" because there is already a no-args transformer class " + "which has the visible name \"%s\"; Ruqus currently cannot handle having multiple no-args " + "transformer classes with the same visible name.", className.toString(), visibleName); return false; } else if (visibleNames.values().contains(visibleName)) { error(element, "Failed while processing \"%s\" because there is already a normal transformer class which " + "has the visible name \"%s\"; Ruqus currently cannot handle having multiple normal transformer " + "classes with the same visible name.", className.toString(), visibleName); return false; } // Must be public and non-abstract. return element.getModifiers().contains(Modifier.PUBLIC) && !element.getModifiers().contains(Modifier.ABSTRACT); } /** * Build the JavaFile object which will create the "Ruqus$$RuqusTransformerData.java" file. * @return JavaFile. */ JavaFile brewTransformerDataFile() { String genClassName = nextTDataClassName(); ClassName genClassType = ClassName.get(C.GEN_PKG, genClassName); // Build static instance var. FieldSpec instanceField = FieldSpec.builder(TypeNames.TRANS_DATA, "INSTANCE", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("new $T()", genClassType) .build(); // Build static init block. CodeBlock.Builder staticBlockBuilder = CodeBlock.builder(); // Loop through real names. String addRealNameStmt = "realNames.add($S)"; staticBlockBuilder.add("// Add real names of normal transformers.\n"); for (String realName : realClassNames) staticBlockBuilder.addStatement(addRealNameStmt, realName); // Loop through real no arg names. String addNARealNameStmt = "realNoArgNames.add($S)"; staticBlockBuilder.add("// Add real names of no-args transformers.\n"); for (String realNAName : realNAClassNames) staticBlockBuilder.addStatement(addNARealNameStmt, realNAName); // Loop through visible names. String addVisibleNameStmt = "visibleNames.put($S, $S)"; staticBlockBuilder.add("// Add visible names of normal transformers.\n"); for (Map.Entry<String, String> entry : visibleNames.entrySet()) staticBlockBuilder.addStatement(addVisibleNameStmt, entry.getKey(), entry.getValue()); // Loop through visible no arg names. String addVisibleNANameStmt = "visibleNoArgNames.put($S, $S)"; staticBlockBuilder.add("// Add visible names of no-arg transformers.\n"); for (Map.Entry<String, String> entry : visibleNANames.entrySet()) staticBlockBuilder.addStatement(addVisibleNANameStmt, entry.getKey(), entry.getValue()); // Loop through number of arguments values. String addNumArgsStmt = "numArgs.put($S, $L)"; staticBlockBuilder.add("// Add number of arguments values.\n"); for (Map.Entry<String, Integer> entry : numArgsMap.entrySet()) staticBlockBuilder.addStatement(addNumArgsStmt, entry.getKey(), entry.getValue()); // Loop through transformer class object names. String addClassStmt = "instanceMap.put($S, new $T())"; staticBlockBuilder.add("// Add transformer class instances.\n"); for (Map.Entry<String, ClassName> entry : classMap.entrySet()) staticBlockBuilder.addStatement(addClassStmt, entry.getKey(), entry.getValue()); // Loop through valid types to names map. staticBlockBuilder.add("// Map types to the names of transformers which accept them.\n"); for (Map.Entry<ClassName, HashSet<String>> entry : typesMap.entrySet()) { staticBlockBuilder.add("typesToNames.put($T.class, new HashSet<String>() {{\n", entry.getKey()) .indent(); // Add the names of transformers for this type. for (String s : entry.getValue()) staticBlockBuilder.addStatement("add($S)", s); staticBlockBuilder.unindent() .add("}});\n"); } // Loop through valid types to visible names map. staticBlockBuilder.add("// Map types to the visible names of transformers which accept them.\n"); for (Map.Entry<ClassName, HashSet<String>> entry : typesMap.entrySet()) { staticBlockBuilder.add("typesToVisibleNames.put($T.class, new $T() {{\n", entry.getKey(), TypeNames.S_HASH_SET) .indent(); // Add the names of transformers for this type. for (String s : entry.getValue()) staticBlockBuilder.addStatement("add($S)", visibleNames.get(s)); staticBlockBuilder.unindent() .add("}});\n"); } // Finally, build this code block. CodeBlock staticBlock = staticBlockBuilder.build(); // Build class. TypeSpec clazz = TypeSpec.classBuilder(genClassName) .superclass(TypeNames.TRANS_DATA) .addModifiers(Modifier.FINAL) .addField(instanceField) .addStaticBlock(staticBlock) .build(); typesMap.put(genClassType, new HashSet<String>() {{ add("Test"); }}); // Build file and return it. messager.printMessage(Diagnostic.Kind.NOTE, "Creating " + genClassType.simpleName()); return JavaFile.builder(C.GEN_PKG, clazz) .addFileComment(C.GEN_CODE_FILE_COMMENT) .build(); } private String nextTDataClassName() { // Figure out what number we'll need to append to the end of the class name. String base = C.GEN_PKG_PREFIX + C.GEN_TRANSFORMER_DATA_CLASS_NAME; int num = 1; while (true) { try { Class.forName(base + String.valueOf(num)); } catch (ClassNotFoundException e) { // This class isn't already taken, so we can generate it. Break out of this loop. return C.GEN_TRANSFORMER_DATA_CLASS_NAME + String.valueOf(num); } num++; } } private void error(Element e, String msg, Object... args) { messager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e); } }
{ "content_hash": "351a4b431b4003e4974dd99079b04a01", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 120, "avg_line_length": 48.53409090909091, "alnum_prop": 0.6260048388355577, "repo_name": "bkromhout/Ruqus", "id": "ab5696d0d6c044c1b744ad8b1143d8e3347c5e6c", "size": "12813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ruqus-compiler/src/main/java/com/bkromhout/ruqus/TransformerDataBuilder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "271614" } ], "symlink_target": "" }
require 'test_helper' class IntroexamTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
{ "content_hash": "6881f5b82fb31f2df968a8762a9c16f1", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 45, "avg_line_length": 17.571428571428573, "alnum_prop": 0.6991869918699187, "repo_name": "rememberlenny/image-drop-newsletter-generation", "id": "4eacb69ee04765b2f9e4acf985a137dc894b26c2", "size": "123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/models/introexam_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2340" }, { "name": "CoffeeScript", "bytes": "422" }, { "name": "HTML", "bytes": "41277" }, { "name": "JavaScript", "bytes": "1468" }, { "name": "Ruby", "bytes": "35446" } ], "symlink_target": "" }
var from = require('from2') module.exports = readStream function readStream (core, id, opts) { if (!opts) opts = {} var start = opts.start || 0 var limit = opts.limit || Infinity var feed = core.get(id, opts) var stream = from.obj(read) stream.id = id stream.blocks = feed.blocks feed.ready(onready) return stream function read (size, cb) { if (limit-- === 0) return cb(null, null) feed.get(start++, cb) } function onready () { stream.blocks = feed.blocks stream.emit('ready') } }
{ "content_hash": "f01502da3c10b039a9332f8a2e73b91d", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 44, "avg_line_length": 21.08, "alnum_prop": 0.6280834914611005, "repo_name": "piedshag/hypercore", "id": "5fb2a78b0c7ef362d738430768a5a6b048c25c85", "size": "527", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/read-stream.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "37220" }, { "name": "Protocol Buffer", "bytes": "962" } ], "symlink_target": "" }
def glTypesNice(types): """Make types into English words""" return types.replace('_',' ').title() def getLatLong(latitude, longitude): """returns the combination of latitude and longitude as required for ElasticSearch""" return latitude+", "+longitude
{ "content_hash": "111fe4297690b01e492199a7394eda7e", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 86, "avg_line_length": 36.57142857142857, "alnum_prop": 0.73828125, "repo_name": "usc-isi-i2/image-metadata-enhancement", "id": "b86dfe064f5bf64fa73fe54646cda6555d4a6ffa", "size": "258", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "karma/python/google.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12808" }, { "name": "HTML", "bytes": "510175" }, { "name": "Java", "bytes": "255900" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Python", "bytes": "18094" } ], "symlink_target": "" }
import logging import uuid from kubernetes import client from kubeflow.fairing import utils from kubeflow.fairing.builders.base_builder import BaseBuilder from kubeflow.fairing.builders import dockerfile from kubeflow.fairing.constants import constants from kubeflow.fairing.kubernetes.manager import KubeManager logger = logging.getLogger(__name__) class ClusterBuilder(BaseBuilder): """Builds a docker image in a Kubernetes cluster. """ def __init__(self, registry=None, image_name=constants.DEFAULT_IMAGE_NAME, context_source=None, preprocessor=None, push=True, base_image=constants.DEFAULT_BASE_IMAGE, pod_spec_mutators=None, namespace=None, dockerfile_path=None, cleanup=False, executable_path_prefix=None): super().__init__( registry=registry, image_name=image_name, push=push, preprocessor=preprocessor, base_image=base_image, dockerfile_path=dockerfile_path) self.manager = KubeManager() if context_source is None: raise RuntimeError("context_source is not specified") self.context_source = context_source self.pod_spec_mutators = pod_spec_mutators or [] self.namespace = namespace or utils.get_default_target_namespace() self.cleanup = cleanup self.executable_path_prefix = executable_path_prefix def build(self): logging.info("Building image using cluster builder.") docker_command = self.preprocessor.get_command() logger.warning("Docker command: {}".format(docker_command)) if not docker_command: logger.warning("Not setting a command for the output docker image.") install_reqs_before_copy = self.preprocessor.is_requirements_txt_file_present() if self.dockerfile_path: dockerfile_path = self.dockerfile_path else: dockerfile_path = dockerfile.write_dockerfile( docker_command=docker_command, path_prefix=self.preprocessor.path_prefix, base_image=self.base_image, install_reqs_before_copy=install_reqs_before_copy, executable_path_prefix=self.executable_path_prefix ) self.preprocessor.output_map[dockerfile_path] = 'Dockerfile' context_path, context_hash = self.preprocessor.context_tar_gz() self.image_tag = self.full_image_name(context_hash) self.context_source.prepare(context_path) labels = {'fairing-builder': 'kaniko'} labels['fairing-build-id'] = str(uuid.uuid1()) pod_spec = self.context_source.generate_pod_spec( self.image_tag, self.push) for fn in self.pod_spec_mutators: fn(self.manager, pod_spec, self.namespace) pod_spec_template = client.V1PodTemplateSpec( metadata=client.V1ObjectMeta( generate_name="fairing-builder-", labels=labels, namespace=self.namespace, annotations={"sidecar.istio.io/inject": "false"}, ), spec=pod_spec ) job_spec = client.V1JobSpec( template=pod_spec_template, parallelism=1, completions=1, backoff_limit=0, ) build_job = client.V1Job( api_version="batch/v1", kind="Job", metadata=client.V1ObjectMeta( generate_name="fairing-builder-", labels=labels, ), spec=job_spec ) created_job = client. \ BatchV1Api(). \ create_namespaced_job(self.namespace, build_job) self.manager.log( name=created_job.metadata.name, namespace=created_job.metadata.namespace, selectors=labels, container="kaniko") # Invoke upstream clean ups self.context_source.cleanup() # Cleanup build_job if requested by user # Otherwise build_job will be cleaned up by Kubernetes GC if self.cleanup: logging.warning("Cleaning up job {}...".format(created_job.metadata.name)) client. \ BatchV1Api(). \ delete_namespaced_job( created_job.metadata.name, created_job.metadata.namespace, body=client.V1DeleteOptions(propagation_policy='Foreground') )
{ "content_hash": "6857ecf07252024ca5dbce866337ed27", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 87, "avg_line_length": 38.396694214876035, "alnum_prop": 0.5891089108910891, "repo_name": "kubeflow/fairing", "id": "37e36b306170b580eaf9cf1625f1da56f1da1968", "size": "4646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kubeflow/fairing/builders/cluster/cluster.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2103" }, { "name": "Jsonnet", "bytes": "2440311" }, { "name": "Jupyter Notebook", "bytes": "1573" }, { "name": "Python", "bytes": "523314" }, { "name": "Shell", "bytes": "439" } ], "symlink_target": "" }
namespace google { namespace protobuf { namespace internal { namespace { } // namespace } // namespace internal } // namespace protobuf } // namespace google #include <google/protobuf/port_undef.inc>
{ "content_hash": "b98580d7d22f17cb7e3938ee6afb8a60", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 41, "avg_line_length": 17.25, "alnum_prop": 0.7198067632850241, "repo_name": "chromium/chromium", "id": "f1ed951c790934135307c8b3865ed165bf32ba18", "size": "2800", "binary": false, "copies": "18", "ref": "refs/heads/main", "path": "third_party/protobuf/src/google/protobuf/wire_format_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.terasology.logic.inventory.action; import org.terasology.module.sandbox.API; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.AbstractConsumableEvent; /** * @deprecated Use InventoryManager method instead. */ @API @Deprecated public class SwitchItemAction extends AbstractConsumableEvent { private EntityRef instigator; private EntityRef to; private int slotFrom; private int slotTo; public SwitchItemAction(EntityRef instigator, int slotFrom, EntityRef to, int slotTo) { this.instigator = instigator; this.to = to; this.slotFrom = slotFrom; this.slotTo = slotTo; } public EntityRef getTo() { return to; } public int getSlotFrom() { return slotFrom; } public int getSlotTo() { return slotTo; } public EntityRef getInstigator() { return instigator; } }
{ "content_hash": "b32bb9bcb61661f2e92776332d1f4bcb", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 91, "avg_line_length": 22.902439024390244, "alnum_prop": 0.6879659211927582, "repo_name": "MarcinSc/Terasology", "id": "2ee47e17d7f9c01d5318833d9e8211dc701ea5da", "size": "1535", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "engine/src/main/java/org/terasology/logic/inventory/action/SwitchItemAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "GLSL", "bytes": "109450" }, { "name": "Groovy", "bytes": "1996" }, { "name": "Java", "bytes": "6395686" }, { "name": "Protocol Buffer", "bytes": "9493" }, { "name": "Shell", "bytes": "7873" } ], "symlink_target": "" }
/* ??? Eventually more and more of this stuff can go to cpu-independent files. Keep that in mind. */ #include "sysdep.h" #include <stdio.h> #include "ansidecl.h" #include "dis-asm.h" #include "bfd.h" #include "symcat.h" #include "libiberty.h" #include "m32r-desc.h" #include "m32r-opc.h" #include "opintl.h" /* Default text to print if an instruction isn't recognized. */ #define UNKNOWN_INSN_MSG _("*unknown*") static void print_normal (CGEN_CPU_DESC, void *, long, unsigned int, bfd_vma, int); static void print_address (CGEN_CPU_DESC, void *, bfd_vma, unsigned int, bfd_vma, int) ATTRIBUTE_UNUSED; static void print_keyword (CGEN_CPU_DESC, void *, CGEN_KEYWORD *, long, unsigned int) ATTRIBUTE_UNUSED; static void print_insn_normal (CGEN_CPU_DESC, void *, const CGEN_INSN *, CGEN_FIELDS *, bfd_vma, int); static int print_insn (CGEN_CPU_DESC, bfd_vma, disassemble_info *, bfd_byte *, unsigned); static int default_print_insn (CGEN_CPU_DESC, bfd_vma, disassemble_info *) ATTRIBUTE_UNUSED; static int read_insn (CGEN_CPU_DESC, bfd_vma, disassemble_info *, bfd_byte *, int, CGEN_EXTRACT_INFO *, unsigned long *); /* -- disassembler routines inserted here */ /* -- dis.c */ static void print_hash PARAMS ((CGEN_CPU_DESC, PTR, long, unsigned, bfd_vma, int)); static int my_print_insn PARAMS ((CGEN_CPU_DESC, bfd_vma, disassemble_info *)); /* Immediate values are prefixed with '#'. */ #define CGEN_PRINT_NORMAL(cd, info, value, attrs, pc, length) \ do \ { \ if (CGEN_BOOL_ATTR ((attrs), CGEN_OPERAND_HASH_PREFIX)) \ (*info->fprintf_func) (info->stream, "#"); \ } \ while (0) /* Handle '#' prefixes as operands. */ static void print_hash (cd, dis_info, value, attrs, pc, length) CGEN_CPU_DESC cd ATTRIBUTE_UNUSED; PTR dis_info; long value ATTRIBUTE_UNUSED; unsigned int attrs ATTRIBUTE_UNUSED; bfd_vma pc ATTRIBUTE_UNUSED; int length ATTRIBUTE_UNUSED; { disassemble_info *info = (disassemble_info *) dis_info; (*info->fprintf_func) (info->stream, "#"); } #undef CGEN_PRINT_INSN #define CGEN_PRINT_INSN my_print_insn static int my_print_insn (cd, pc, info) CGEN_CPU_DESC cd; bfd_vma pc; disassemble_info *info; { char buffer[CGEN_MAX_INSN_SIZE]; char *buf = buffer; int status; int buflen = (pc & 3) == 0 ? 4 : 2; int big_p = CGEN_CPU_INSN_ENDIAN (cd) == CGEN_ENDIAN_BIG; char *x; /* Read the base part of the insn. */ status = (*info->read_memory_func) (pc - ((!big_p && (pc & 3) != 0) ? 2 : 0), buf, buflen, info); if (status != 0) { (*info->memory_error_func) (status, pc, info); return -1; } /* 32 bit insn? */ x = (big_p ? &buf[0] : &buf[3]); if ((pc & 3) == 0 && (*x & 0x80) != 0) return print_insn (cd, pc, info, buf, buflen); /* Print the first insn. */ if ((pc & 3) == 0) { buf += (big_p ? 0 : 2); if (print_insn (cd, pc, info, buf, 2) == 0) (*info->fprintf_func) (info->stream, UNKNOWN_INSN_MSG); buf += (big_p ? 2 : -2); } x = (big_p ? &buf[0] : &buf[1]); if (*x & 0x80) { /* Parallel. */ (*info->fprintf_func) (info->stream, " || "); *x &= 0x7f; } else (*info->fprintf_func) (info->stream, " -> "); /* The "& 3" is to pass a consistent address. Parallel insns arguably both begin on the word boundary. Also, branch insns are calculated relative to the word boundary. */ if (print_insn (cd, pc & ~ (bfd_vma) 3, info, buf, 2) == 0) (*info->fprintf_func) (info->stream, UNKNOWN_INSN_MSG); return (pc & 3) ? 2 : 4; } /* -- */ void m32r_cgen_print_operand (CGEN_CPU_DESC, int, PTR, CGEN_FIELDS *, void const *, bfd_vma, int); /* Main entry point for printing operands. XINFO is a `void *' and not a `disassemble_info *' to not put a requirement of dis-asm.h on cgen.h. This function is basically just a big switch statement. Earlier versions used tables to look up the function to use, but - if the table contains both assembler and disassembler functions then the disassembler contains much of the assembler and vice-versa, - there's a lot of inlining possibilities as things grow, - using a switch statement avoids the function call overhead. This function could be moved into `print_insn_normal', but keeping it separate makes clear the interface between `print_insn_normal' and each of the handlers. */ void m32r_cgen_print_operand (CGEN_CPU_DESC cd, int opindex, void * xinfo, CGEN_FIELDS *fields, void const *attrs ATTRIBUTE_UNUSED, bfd_vma pc, int length) { disassemble_info *info = (disassemble_info *) xinfo; switch (opindex) { case M32R_OPERAND_ACC : print_keyword (cd, info, & m32r_cgen_opval_h_accums, fields->f_acc, 0); break; case M32R_OPERAND_ACCD : print_keyword (cd, info, & m32r_cgen_opval_h_accums, fields->f_accd, 0); break; case M32R_OPERAND_ACCS : print_keyword (cd, info, & m32r_cgen_opval_h_accums, fields->f_accs, 0); break; case M32R_OPERAND_DCR : print_keyword (cd, info, & m32r_cgen_opval_cr_names, fields->f_r1, 0); break; case M32R_OPERAND_DISP16 : print_address (cd, info, fields->f_disp16, 0|(1<<CGEN_OPERAND_RELOC)|(1<<CGEN_OPERAND_PCREL_ADDR), pc, length); break; case M32R_OPERAND_DISP24 : print_address (cd, info, fields->f_disp24, 0|(1<<CGEN_OPERAND_RELAX)|(1<<CGEN_OPERAND_RELOC)|(1<<CGEN_OPERAND_PCREL_ADDR), pc, length); break; case M32R_OPERAND_DISP8 : print_address (cd, info, fields->f_disp8, 0|(1<<CGEN_OPERAND_RELAX)|(1<<CGEN_OPERAND_RELOC)|(1<<CGEN_OPERAND_PCREL_ADDR), pc, length); break; case M32R_OPERAND_DR : print_keyword (cd, info, & m32r_cgen_opval_gr_names, fields->f_r1, 0); break; case M32R_OPERAND_HASH : print_hash (cd, info, 0, 0|(1<<CGEN_OPERAND_SIGNED), pc, length); break; case M32R_OPERAND_HI16 : print_normal (cd, info, fields->f_hi16, 0|(1<<CGEN_OPERAND_SIGN_OPT), pc, length); break; case M32R_OPERAND_IMM1 : print_normal (cd, info, fields->f_imm1, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_SCR : print_keyword (cd, info, & m32r_cgen_opval_cr_names, fields->f_r2, 0); break; case M32R_OPERAND_SIMM16 : print_normal (cd, info, fields->f_simm16, 0|(1<<CGEN_OPERAND_SIGNED)|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_SIMM8 : print_normal (cd, info, fields->f_simm8, 0|(1<<CGEN_OPERAND_SIGNED)|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_SLO16 : print_normal (cd, info, fields->f_simm16, 0|(1<<CGEN_OPERAND_SIGNED), pc, length); break; case M32R_OPERAND_SR : print_keyword (cd, info, & m32r_cgen_opval_gr_names, fields->f_r2, 0); break; case M32R_OPERAND_SRC1 : print_keyword (cd, info, & m32r_cgen_opval_gr_names, fields->f_r1, 0); break; case M32R_OPERAND_SRC2 : print_keyword (cd, info, & m32r_cgen_opval_gr_names, fields->f_r2, 0); break; case M32R_OPERAND_UIMM16 : print_normal (cd, info, fields->f_uimm16, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_UIMM24 : print_address (cd, info, fields->f_uimm24, 0|(1<<CGEN_OPERAND_HASH_PREFIX)|(1<<CGEN_OPERAND_RELOC)|(1<<CGEN_OPERAND_ABS_ADDR), pc, length); break; case M32R_OPERAND_UIMM3 : print_normal (cd, info, fields->f_uimm3, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_UIMM4 : print_normal (cd, info, fields->f_uimm4, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_UIMM5 : print_normal (cd, info, fields->f_uimm5, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_UIMM8 : print_normal (cd, info, fields->f_uimm8, 0|(1<<CGEN_OPERAND_HASH_PREFIX), pc, length); break; case M32R_OPERAND_ULO16 : print_normal (cd, info, fields->f_uimm16, 0, pc, length); break; default : /* xgettext:c-format */ fprintf (stderr, _("Unrecognized field %d while printing insn.\n"), opindex); abort (); } } cgen_print_fn * const m32r_cgen_print_handlers[] = { print_insn_normal, }; void m32r_cgen_init_dis (CGEN_CPU_DESC cd) { m32r_cgen_init_opcode_table (cd); m32r_cgen_init_ibld_table (cd); cd->print_handlers = & m32r_cgen_print_handlers[0]; cd->print_operand = m32r_cgen_print_operand; } /* Default print handler. */ static void print_normal (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED, void *dis_info, long value, unsigned int attrs, bfd_vma pc ATTRIBUTE_UNUSED, int length ATTRIBUTE_UNUSED) { disassemble_info *info = (disassemble_info *) dis_info; #ifdef CGEN_PRINT_NORMAL CGEN_PRINT_NORMAL (cd, info, value, attrs, pc, length); #endif /* Print the operand as directed by the attributes. */ if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_SEM_ONLY)) ; /* nothing to do */ else if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_SIGNED)) (*info->fprintf_func) (info->stream, "%ld", value); else (*info->fprintf_func) (info->stream, "0x%lx", value); } /* Default address handler. */ static void print_address (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED, void *dis_info, bfd_vma value, unsigned int attrs, bfd_vma pc ATTRIBUTE_UNUSED, int length ATTRIBUTE_UNUSED) { disassemble_info *info = (disassemble_info *) dis_info; #ifdef CGEN_PRINT_ADDRESS CGEN_PRINT_ADDRESS (cd, info, value, attrs, pc, length); #endif /* Print the operand as directed by the attributes. */ if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_SEM_ONLY)) ; /* nothing to do */ else if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_PCREL_ADDR)) (*info->print_address_func) (value, info); else if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_ABS_ADDR)) (*info->print_address_func) (value, info); else if (CGEN_BOOL_ATTR (attrs, CGEN_OPERAND_SIGNED)) (*info->fprintf_func) (info->stream, "%ld", (long) value); else (*info->fprintf_func) (info->stream, "0x%lx", (long) value); } /* Keyword print handler. */ static void print_keyword (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED, void *dis_info, CGEN_KEYWORD *keyword_table, long value, unsigned int attrs ATTRIBUTE_UNUSED) { disassemble_info *info = (disassemble_info *) dis_info; const CGEN_KEYWORD_ENTRY *ke; ke = cgen_keyword_lookup_value (keyword_table, value); if (ke != NULL) (*info->fprintf_func) (info->stream, "%s", ke->name); else (*info->fprintf_func) (info->stream, "???"); } /* Default insn printer. DIS_INFO is defined as `void *' so the disassembler needn't know anything about disassemble_info. */ static void print_insn_normal (CGEN_CPU_DESC cd, void *dis_info, const CGEN_INSN *insn, CGEN_FIELDS *fields, bfd_vma pc, int length) { const CGEN_SYNTAX *syntax = CGEN_INSN_SYNTAX (insn); disassemble_info *info = (disassemble_info *) dis_info; const CGEN_SYNTAX_CHAR_TYPE *syn; CGEN_INIT_PRINT (cd); for (syn = CGEN_SYNTAX_STRING (syntax); *syn; ++syn) { if (CGEN_SYNTAX_MNEMONIC_P (*syn)) { (*info->fprintf_func) (info->stream, "%s", CGEN_INSN_MNEMONIC (insn)); continue; } if (CGEN_SYNTAX_CHAR_P (*syn)) { (*info->fprintf_func) (info->stream, "%c", CGEN_SYNTAX_CHAR (*syn)); continue; } /* We have an operand. */ m32r_cgen_print_operand (cd, CGEN_SYNTAX_FIELD (*syn), info, fields, CGEN_INSN_ATTRS (insn), pc, length); } } /* Subroutine of print_insn. Reads an insn into the given buffers and updates the extract info. Returns 0 if all is well, non-zero otherwise. */ static int read_insn (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED, bfd_vma pc, disassemble_info *info, bfd_byte *buf, int buflen, CGEN_EXTRACT_INFO *ex_info, unsigned long *insn_value) { int status = (*info->read_memory_func) (pc, buf, buflen, info); if (status != 0) { (*info->memory_error_func) (status, pc, info); return -1; } ex_info->dis_info = info; ex_info->valid = (1 << buflen) - 1; ex_info->insn_bytes = buf; *insn_value = bfd_get_bits (buf, buflen * 8, info->endian == BFD_ENDIAN_BIG); return 0; } /* Utility to print an insn. BUF is the base part of the insn, target byte order, BUFLEN bytes long. The result is the size of the insn in bytes or zero for an unknown insn or -1 if an error occurs fetching data (memory_error_func will have been called). */ static int print_insn (CGEN_CPU_DESC cd, bfd_vma pc, disassemble_info *info, bfd_byte *buf, unsigned int buflen) { CGEN_INSN_INT insn_value; const CGEN_INSN_LIST *insn_list; CGEN_EXTRACT_INFO ex_info; int basesize; /* Extract base part of instruction, just in case CGEN_DIS_* uses it. */ basesize = cd->base_insn_bitsize < buflen * 8 ? cd->base_insn_bitsize : buflen * 8; insn_value = cgen_get_insn_value (cd, buf, basesize); /* Fill in ex_info fields like read_insn would. Don't actually call read_insn, since the incoming buffer is already read (and possibly modified a la m32r). */ ex_info.valid = (1 << buflen) - 1; ex_info.dis_info = info; ex_info.insn_bytes = buf; /* The instructions are stored in hash lists. Pick the first one and keep trying until we find the right one. */ insn_list = CGEN_DIS_LOOKUP_INSN (cd, (char *) buf, insn_value); while (insn_list != NULL) { const CGEN_INSN *insn = insn_list->insn; CGEN_FIELDS fields; int length; unsigned long insn_value_cropped; #ifdef CGEN_VALIDATE_INSN_SUPPORTED /* Not needed as insn shouldn't be in hash lists if not supported. */ /* Supported by this cpu? */ if (! m32r_cgen_insn_supported (cd, insn)) { insn_list = CGEN_DIS_NEXT_INSN (insn_list); continue; } #endif /* Basic bit mask must be correct. */ /* ??? May wish to allow target to defer this check until the extract handler. */ /* Base size may exceed this instruction's size. Extract the relevant part from the buffer. */ if ((unsigned) (CGEN_INSN_BITSIZE (insn) / 8) < buflen && (unsigned) (CGEN_INSN_BITSIZE (insn) / 8) <= sizeof (unsigned long)) insn_value_cropped = bfd_get_bits (buf, CGEN_INSN_BITSIZE (insn), info->endian == BFD_ENDIAN_BIG); else insn_value_cropped = insn_value; if ((insn_value_cropped & CGEN_INSN_BASE_MASK (insn)) == CGEN_INSN_BASE_VALUE (insn)) { /* Printing is handled in two passes. The first pass parses the machine insn and extracts the fields. The second pass prints them. */ /* Make sure the entire insn is loaded into insn_value, if it can fit. */ if (((unsigned) CGEN_INSN_BITSIZE (insn) > cd->base_insn_bitsize) && (unsigned) (CGEN_INSN_BITSIZE (insn) / 8) <= sizeof (unsigned long)) { unsigned long full_insn_value; int rc = read_insn (cd, pc, info, buf, CGEN_INSN_BITSIZE (insn) / 8, & ex_info, & full_insn_value); if (rc != 0) return rc; length = CGEN_EXTRACT_FN (cd, insn) (cd, insn, &ex_info, full_insn_value, &fields, pc); } else length = CGEN_EXTRACT_FN (cd, insn) (cd, insn, &ex_info, insn_value_cropped, &fields, pc); /* length < 0 -> error */ if (length < 0) return length; if (length > 0) { CGEN_PRINT_FN (cd, insn) (cd, info, insn, &fields, pc, length); /* length is in bits, result is in bytes */ return length / 8; } } insn_list = CGEN_DIS_NEXT_INSN (insn_list); } return 0; } /* Default value for CGEN_PRINT_INSN. The result is the size of the insn in bytes or zero for an unknown insn or -1 if an error occured fetching bytes. */ #ifndef CGEN_PRINT_INSN #define CGEN_PRINT_INSN default_print_insn #endif static int default_print_insn (CGEN_CPU_DESC cd, bfd_vma pc, disassemble_info *info) { bfd_byte buf[CGEN_MAX_INSN_SIZE]; int buflen; int status; /* Attempt to read the base part of the insn. */ buflen = cd->base_insn_bitsize / 8; status = (*info->read_memory_func) (pc, buf, buflen, info); /* Try again with the minimum part, if min < base. */ if (status != 0 && (cd->min_insn_bitsize < cd->base_insn_bitsize)) { buflen = cd->min_insn_bitsize / 8; status = (*info->read_memory_func) (pc, buf, buflen, info); } if (status != 0) { (*info->memory_error_func) (status, pc, info); return -1; } return print_insn (cd, pc, info, buf, buflen); } /* Main entry point. Print one instruction from PC on INFO->STREAM. Return the size of the instruction (in bytes). */ typedef struct cpu_desc_list { struct cpu_desc_list *next; int isa; int mach; int endian; CGEN_CPU_DESC cd; } cpu_desc_list; int print_insn_m32r (bfd_vma pc, disassemble_info *info) { static cpu_desc_list *cd_list = 0; cpu_desc_list *cl = 0; static CGEN_CPU_DESC cd = 0; static int prev_isa; static int prev_mach; static int prev_endian; int length; int isa,mach; int endian = (info->endian == BFD_ENDIAN_BIG ? CGEN_ENDIAN_BIG : CGEN_ENDIAN_LITTLE); enum bfd_architecture arch; /* ??? gdb will set mach but leave the architecture as "unknown" */ #ifndef CGEN_BFD_ARCH #define CGEN_BFD_ARCH bfd_arch_m32r #endif arch = info->arch; if (arch == bfd_arch_unknown) arch = CGEN_BFD_ARCH; /* There's no standard way to compute the machine or isa number so we leave it to the target. */ #ifdef CGEN_COMPUTE_MACH mach = CGEN_COMPUTE_MACH (info); #else mach = info->mach; #endif #ifdef CGEN_COMPUTE_ISA isa = CGEN_COMPUTE_ISA (info); #else isa = info->insn_sets; #endif /* If we've switched cpu's, try to find a handle we've used before */ if (cd && (isa != prev_isa || mach != prev_mach || endian != prev_endian)) { cd = 0; for (cl = cd_list; cl; cl = cl->next) { if (cl->isa == isa && cl->mach == mach && cl->endian == endian) { cd = cl->cd; break; } } } /* If we haven't initialized yet, initialize the opcode table. */ if (! cd) { const bfd_arch_info_type *arch_type = bfd_lookup_arch (arch, mach); const char *mach_name; if (!arch_type) abort (); mach_name = arch_type->printable_name; prev_isa = isa; prev_mach = mach; prev_endian = endian; cd = m32r_cgen_cpu_open (CGEN_CPU_OPEN_ISAS, prev_isa, CGEN_CPU_OPEN_BFDMACH, mach_name, CGEN_CPU_OPEN_ENDIAN, prev_endian, CGEN_CPU_OPEN_END); if (!cd) abort (); /* save this away for future reference */ cl = xmalloc (sizeof (struct cpu_desc_list)); cl->cd = cd; cl->isa = isa; cl->mach = mach; cl->endian = endian; cl->next = cd_list; cd_list = cl; m32r_cgen_init_dis (cd); } /* We try to have as much common code as possible. But at this point some targets need to take over. */ /* ??? Some targets may need a hook elsewhere. Try to avoid this, but if not possible try to move this hook elsewhere rather than have two hooks. */ length = CGEN_PRINT_INSN (cd, pc, info); if (length > 0) return length; if (length < 0) return -1; (*info->fprintf_func) (info->stream, UNKNOWN_INSN_MSG); return cd->default_insn_bitsize / 8; }
{ "content_hash": "400acf8c6ab8162086ef22dfa327f02d", "timestamp": "", "source": "github", "line_count": 658, "max_line_length": 145, "avg_line_length": 29.86626139817629, "alnum_prop": 0.620242214532872, "repo_name": "shaotuanchen/sunflower_exp", "id": "ac82c7425a4a0bb09c87b1db1969d396432e90f0", "size": "20666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/source/binutils-2.16.1/opcodes/m32r-dis.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
#include "mitkPlanarFigure.h" #include "mitkGeometry2D.h" #include "mitkProperties.h" #include <mitkProportionalTimeGeometry.h> #include "algorithm" mitk::PlanarFigure::PlanarFigure() : m_SelectedControlPoint( -1 ), m_PreviewControlPointVisible( false ), m_FigurePlaced( false ), m_Geometry2D( NULL ), m_PolyLineUpToDate(false), m_HelperLinesUpToDate(false), m_FeaturesUpToDate(false), m_FeaturesMTime( 0 ) { m_HelperPolyLinesToBePainted = BoolContainerType::New(); m_DisplaySize.first = 0.0; m_DisplaySize.second = 0; this->SetProperty( "closed", mitk::BoolProperty::New( false ) ); // Currently only single-time-step geometries are supported this->InitializeTimeGeometry( 1 ); } mitk::PlanarFigure::~PlanarFigure() { } mitk::PlanarFigure::PlanarFigure(const Self& other) : BaseData(other), m_ControlPoints(other.m_ControlPoints), m_NumberOfControlPoints(other.m_NumberOfControlPoints), m_SelectedControlPoint(other.m_SelectedControlPoint), m_PolyLines(other.m_PolyLines), m_HelperPolyLines(other.m_HelperPolyLines), m_HelperPolyLinesToBePainted(other.m_HelperPolyLinesToBePainted->Clone()), m_PreviewControlPoint(other.m_PreviewControlPoint), m_PreviewControlPointVisible(other.m_PreviewControlPointVisible), m_FigurePlaced(other.m_FigurePlaced), m_Geometry2D(other.m_Geometry2D), // do not clone since SetGeometry2D() doesn't clone either m_PolyLineUpToDate(other.m_PolyLineUpToDate), m_HelperLinesUpToDate(other.m_HelperLinesUpToDate), m_FeaturesUpToDate(other.m_FeaturesUpToDate), m_Features(other.m_Features), m_FeaturesMTime(other.m_FeaturesMTime), m_DisplaySize(other.m_DisplaySize) { } void mitk::PlanarFigure::SetGeometry2D( mitk::Geometry2D *geometry ) { this->SetGeometry( geometry ); m_Geometry2D = dynamic_cast<Geometry2D *>(GetGeometry(0));//geometry; } const mitk::Geometry2D *mitk::PlanarFigure::GetGeometry2D() const { return m_Geometry2D; } bool mitk::PlanarFigure::IsClosed() const { mitk::BoolProperty* closed = dynamic_cast< mitk::BoolProperty* >( this->GetProperty( "closed" ).GetPointer() ); if ( closed != NULL ) { return closed->GetValue(); } return false; } void mitk::PlanarFigure::PlaceFigure( const mitk::Point2D& point ) { for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i ) { m_ControlPoints.push_back( this->ApplyControlPointConstraints( i, point ) ); } m_FigurePlaced = true; m_SelectedControlPoint = 1; } bool mitk::PlanarFigure::AddControlPoint( const mitk::Point2D& point, int position ) { // if we already have the maximum number of control points, do nothing if ( m_NumberOfControlPoints < this->GetMaximumNumberOfControlPoints() ) { // if position has not been defined or position would be the last control point, just append the new one // we also append a new point if we click onto the line between the first two control-points if the second control-point is selected // -> special case for PlanarCross if ( position == -1 || position > (int)m_NumberOfControlPoints-1 || (position == 1 && m_SelectedControlPoint == 2) ) { if ( m_ControlPoints.size() > this->GetMaximumNumberOfControlPoints()-1 ) { // get rid of deprecated control points in the list. This is necessary // as ::ResetNumberOfControlPoints() only sets the member, does not resize the list! m_ControlPoints.resize( this->GetNumberOfControlPoints() ); } m_ControlPoints.push_back( this->ApplyControlPointConstraints( m_NumberOfControlPoints, point ) ); m_SelectedControlPoint = m_NumberOfControlPoints; } else { // insert the point at the given position and set it as selected point ControlPointListType::iterator iter = m_ControlPoints.begin() + position; m_ControlPoints.insert( iter, this->ApplyControlPointConstraints( position, point ) ); for( unsigned int i = 0; i < m_ControlPoints.size(); ++i ) { if( point == m_ControlPoints.at(i) ) { m_SelectedControlPoint = i; } } } // polylines & helperpolylines need to be repainted m_PolyLineUpToDate = false; m_HelperLinesUpToDate = false; m_FeaturesUpToDate = false; // one control point more ++m_NumberOfControlPoints; return true; } else { return false; } } bool mitk::PlanarFigure::SetControlPoint( unsigned int index, const Point2D& point, bool createIfDoesNotExist ) { bool controlPointSetCorrectly = false; if (createIfDoesNotExist) { if ( m_NumberOfControlPoints <= index ) { m_ControlPoints.push_back( this->ApplyControlPointConstraints( index, point ) ); m_NumberOfControlPoints++; } else { m_ControlPoints.at( index ) = this->ApplyControlPointConstraints( index, point ); } controlPointSetCorrectly = true; } else if ( index < m_NumberOfControlPoints ) { m_ControlPoints.at( index ) = this->ApplyControlPointConstraints( index, point ); controlPointSetCorrectly = true; } else { return false; } if ( controlPointSetCorrectly ) { m_PolyLineUpToDate = false; m_HelperLinesUpToDate = false; m_FeaturesUpToDate = false; } return controlPointSetCorrectly; } bool mitk::PlanarFigure::SetCurrentControlPoint( const Point2D& point ) { if ( (m_SelectedControlPoint < 0) || (m_SelectedControlPoint >= (int)m_NumberOfControlPoints) ) { return false; } return this->SetControlPoint(m_SelectedControlPoint, point, false); } unsigned int mitk::PlanarFigure::GetNumberOfControlPoints() const { return m_NumberOfControlPoints; } bool mitk::PlanarFigure::SelectControlPoint( unsigned int index ) { if ( index < this->GetNumberOfControlPoints() ) { m_SelectedControlPoint = index; return true; } else { return false; } } bool mitk::PlanarFigure::DeselectControlPoint() { bool wasSelected = ( m_SelectedControlPoint != -1); m_SelectedControlPoint = -1; return wasSelected; } void mitk::PlanarFigure::SetPreviewControlPoint( const Point2D& point ) { m_PreviewControlPoint = point; m_PreviewControlPointVisible = true; } void mitk::PlanarFigure::ResetPreviewContolPoint() { m_PreviewControlPointVisible = false; } mitk::Point2D mitk::PlanarFigure::GetPreviewControlPoint() { return m_PreviewControlPoint; } bool mitk::PlanarFigure::IsPreviewControlPointVisible() { return m_PreviewControlPointVisible; } mitk::Point2D mitk::PlanarFigure::GetControlPoint( unsigned int index ) const { if ( index < m_NumberOfControlPoints ) { return m_ControlPoints.at( index ); } itkExceptionMacro( << "GetControlPoint(): Invalid index!" ); } mitk::Point3D mitk::PlanarFigure::GetWorldControlPoint( unsigned int index ) const { Point3D point3D; if ( (m_Geometry2D != NULL) && (index < m_NumberOfControlPoints) ) { m_Geometry2D->Map( m_ControlPoints.at( index ), point3D ); return point3D; } itkExceptionMacro( << "GetWorldControlPoint(): Invalid index!" ); } const mitk::PlanarFigure::PolyLineType mitk::PlanarFigure::GetPolyLine(unsigned int index) { mitk::PlanarFigure::PolyLineType polyLine; if ( index > m_PolyLines.size() || !m_PolyLineUpToDate ) { this->GeneratePolyLine(); m_PolyLineUpToDate = true; } return m_PolyLines.at( index );; } const mitk::PlanarFigure::PolyLineType mitk::PlanarFigure::GetPolyLine(unsigned int index) const { return m_PolyLines.at( index ); } void mitk::PlanarFigure::ClearPolyLines() { for ( std::vector<PolyLineType>::size_type i=0; i<m_PolyLines.size(); i++ ) { m_PolyLines.at( i ).clear(); } m_PolyLineUpToDate = false; } const mitk::PlanarFigure::PolyLineType mitk::PlanarFigure::GetHelperPolyLine( unsigned int index, double mmPerDisplayUnit, unsigned int displayHeight ) { mitk::PlanarFigure::PolyLineType helperPolyLine; if ( index < m_HelperPolyLines.size() ) { // m_HelperLinesUpToDate does not cover changes in zoom-level, so we have to check previous values of the // two parameters as well if ( !m_HelperLinesUpToDate || m_DisplaySize.first != mmPerDisplayUnit || m_DisplaySize.second != displayHeight ) { this->GenerateHelperPolyLine(mmPerDisplayUnit, displayHeight); m_HelperLinesUpToDate = true; // store these parameters to be able to check next time if somebody zoomed in or out m_DisplaySize.first = mmPerDisplayUnit; m_DisplaySize.second = displayHeight; } helperPolyLine = m_HelperPolyLines.at(index); } return helperPolyLine; } void mitk::PlanarFigure::ClearHelperPolyLines() { for ( std::vector<PolyLineType>::size_type i=0; i<m_HelperPolyLines.size(); i++ ) { m_HelperPolyLines.at(i).clear(); } m_HelperLinesUpToDate = false; } /** \brief Returns the number of features available for this PlanarFigure * (such as, radius, area, ...). */ unsigned int mitk::PlanarFigure::GetNumberOfFeatures() const { return m_Features.size(); } const char *mitk::PlanarFigure::GetFeatureName( unsigned int index ) const { if ( index < m_Features.size() ) { return m_Features[index].Name.c_str(); } else { return NULL; } } const char *mitk::PlanarFigure::GetFeatureUnit( unsigned int index ) const { if ( index < m_Features.size() ) { return m_Features[index].Unit.c_str(); } else { return NULL; } } double mitk::PlanarFigure::GetQuantity( unsigned int index ) const { if ( index < m_Features.size() ) { return m_Features[index].Quantity; } else { return 0.0; } } bool mitk::PlanarFigure::IsFeatureActive( unsigned int index ) const { if ( index < m_Features.size() ) { return m_Features[index].Active; } else { return false; } } bool mitk::PlanarFigure::IsFeatureVisible( unsigned int index ) const { if ( index < m_Features.size() ) { return m_Features[index].Visible; } else { return false; } } void mitk::PlanarFigure::SetFeatureVisible( unsigned int index, bool visible ) { if ( index < m_Features.size() ) { m_Features[index].Visible = visible; } } void mitk::PlanarFigure::EvaluateFeatures() { if ( !m_FeaturesUpToDate || !m_PolyLineUpToDate ) { if ( !m_PolyLineUpToDate ) { this->GeneratePolyLine(); } this->EvaluateFeaturesInternal(); m_FeaturesUpToDate = true; } } void mitk::PlanarFigure::UpdateOutputInformation() { // Bounds are NOT calculated here, since the Geometry2D defines a fixed // frame (= bounds) for the planar figure. Superclass::UpdateOutputInformation(); this->GetTimeGeometry()->Update(); } void mitk::PlanarFigure::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::PlanarFigure::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::PlanarFigure::VerifyRequestedRegion() { return true; } void mitk::PlanarFigure::SetRequestedRegion(const itk::DataObject * /*data*/ ) { } void mitk::PlanarFigure::ResetNumberOfControlPoints( int numberOfControlPoints ) { // DO NOT resize the list here, will cause crash!! m_NumberOfControlPoints = numberOfControlPoints; } mitk::Point2D mitk::PlanarFigure::ApplyControlPointConstraints( unsigned int /*index*/, const Point2D& point ) { if ( m_Geometry2D == NULL ) { return point; } Point2D indexPoint; m_Geometry2D->WorldToIndex( point, indexPoint ); BoundingBox::BoundsArrayType bounds = m_Geometry2D->GetBounds(); if ( indexPoint[0] < bounds[0] ) { indexPoint[0] = bounds[0]; } if ( indexPoint[0] > bounds[1] ) { indexPoint[0] = bounds[1]; } if ( indexPoint[1] < bounds[2] ) { indexPoint[1] = bounds[2]; } if ( indexPoint[1] > bounds[3] ) { indexPoint[1] = bounds[3]; } Point2D constrainedPoint; m_Geometry2D->IndexToWorld( indexPoint, constrainedPoint ); return constrainedPoint; } unsigned int mitk::PlanarFigure::AddFeature( const char *featureName, const char *unitName ) { unsigned int index = m_Features.size(); Feature newFeature( featureName, unitName ); m_Features.push_back( newFeature ); return index; } void mitk::PlanarFigure::SetFeatureName( unsigned int index, const char *featureName ) { if ( index < m_Features.size() ) { m_Features[index].Name = featureName; } } void mitk::PlanarFigure::SetFeatureUnit( unsigned int index, const char *unitName ) { if ( index < m_Features.size() ) { m_Features[index].Unit = unitName; } } void mitk::PlanarFigure::SetQuantity( unsigned int index, double quantity ) { if ( index < m_Features.size() ) { m_Features[index].Quantity = quantity; } } void mitk::PlanarFigure::ActivateFeature( unsigned int index ) { if ( index < m_Features.size() ) { m_Features[index].Active = true; } } void mitk::PlanarFigure::DeactivateFeature( unsigned int index ) { if ( index < m_Features.size() ) { m_Features[index].Active = false; } } void mitk::PlanarFigure::InitializeTimeSlicedGeometry( unsigned int timeSteps ) { InitializeTimeGeometry(timeSteps); } void mitk::PlanarFigure::InitializeTimeGeometry( unsigned int timeSteps ) { mitk::Geometry2D::Pointer geometry2D = mitk::Geometry2D::New(); geometry2D->Initialize(); if ( timeSteps > 1 ) { mitk::ScalarType timeBounds[] = {0.0, 1.0}; geometry2D->SetTimeBounds( timeBounds ); } // The geometry is propagated automatically to all time steps, // if EvenlyTimed is true... ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); timeGeometry->Initialize(geometry2D, timeSteps); SetTimeGeometry(timeGeometry); } void mitk::PlanarFigure::PrintSelf( std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); os << indent << this->GetNameOfClass() << ":\n"; if (this->IsClosed()) os << indent << "This figure is closed\n"; else os << indent << "This figure is not closed\n"; os << indent << "Minimum number of control points: " << this->GetMinimumNumberOfControlPoints() << std::endl; os << indent << "Maximum number of control points: " << this->GetMaximumNumberOfControlPoints() << std::endl; os << indent << "Current number of control points: " << this->GetNumberOfControlPoints() << std::endl; os << indent << "Control points:" << std::endl; for ( unsigned int i = 0; i < this->GetNumberOfControlPoints(); ++i ) { //os << indent.GetNextIndent() << i << ": " << m_ControlPoints->ElementAt( i ) << std::endl; os << indent.GetNextIndent() << i << ": " << m_ControlPoints.at( i ) << std::endl; } os << indent << "Geometry:\n"; this->GetGeometry2D()->Print(os, indent.GetNextIndent()); } unsigned short mitk::PlanarFigure::GetPolyLinesSize() { if ( !m_PolyLineUpToDate ) { this->GeneratePolyLine(); m_PolyLineUpToDate = true; } return m_PolyLines.size(); } unsigned short mitk::PlanarFigure::GetHelperPolyLinesSize() { return m_HelperPolyLines.size(); } bool mitk::PlanarFigure::IsHelperToBePainted(unsigned int index) { return m_HelperPolyLinesToBePainted->GetElement( index ); } bool mitk::PlanarFigure::ResetOnPointSelect() { return false; } void mitk::PlanarFigure::RemoveControlPoint( unsigned int index ) { if ( index > m_ControlPoints.size() ) return; if ( (m_ControlPoints.size() -1) < this->GetMinimumNumberOfControlPoints() ) return; ControlPointListType::iterator iter; iter = m_ControlPoints.begin() + index; m_ControlPoints.erase( iter ); m_PolyLineUpToDate = false; m_HelperLinesUpToDate = false; m_FeaturesUpToDate = false; --m_NumberOfControlPoints; } void mitk::PlanarFigure::RemoveLastControlPoint() { RemoveControlPoint( m_ControlPoints.size()-1 ); } void mitk::PlanarFigure::DeepCopy(Self::Pointer oldFigure) { //DeepCopy only same types of planar figures //Notice to get typeid polymorph you have to use the *operator if(typeid(*oldFigure) != typeid(*this)) { itkExceptionMacro( << "DeepCopy(): Inconsistent type of source (" << typeid(*oldFigure).name() << ") and destination figure (" << typeid(*this).name() << ")!" ); return; } m_ControlPoints.clear(); this->ClearPolyLines(); this->ClearHelperPolyLines(); // clone base data members SetPropertyList(oldFigure->GetPropertyList()->Clone()); /// deep copy members m_FigurePlaced = oldFigure->m_FigurePlaced; m_SelectedControlPoint = oldFigure->m_SelectedControlPoint; m_FeaturesMTime = oldFigure->m_FeaturesMTime; m_Features = oldFigure->m_Features; m_NumberOfControlPoints = oldFigure->m_NumberOfControlPoints; //copy geometry 2D of planar figure Geometry2D::Pointer affineGeometry = oldFigure->m_Geometry2D->Clone(); SetGeometry2D(affineGeometry.GetPointer()); for(unsigned long index=0; index < oldFigure->GetNumberOfControlPoints(); index++) { m_ControlPoints.push_back( oldFigure->GetControlPoint( index )); } //After setting the control points we can generate the polylines this->GeneratePolyLine(); } void mitk::PlanarFigure::SetNumberOfPolyLines( unsigned int numberOfPolyLines ) { m_PolyLines.resize(numberOfPolyLines); } void mitk::PlanarFigure::SetNumberOfHelperPolyLines( unsigned int numberOfHerlperPolyLines ) { m_HelperPolyLines.resize(numberOfHerlperPolyLines); } void mitk::PlanarFigure::AppendPointToPolyLine( unsigned int index, PolyLineElement element ) { if ( index < m_PolyLines.size() ) { m_PolyLines.at( index ).push_back( element ); m_PolyLineUpToDate = false; } else { MITK_ERROR << "Tried to add point to PolyLine " << index+1 << ", although only " << m_PolyLines.size() << " exists"; } } void mitk::PlanarFigure::AppendPointToHelperPolyLine( unsigned int index, PolyLineElement element ) { if ( index < m_HelperPolyLines.size() ) { m_HelperPolyLines.at( index ).push_back( element ); m_HelperLinesUpToDate = false; } else { MITK_ERROR << "Tried to add point to HelperPolyLine " << index+1 << ", although only " << m_HelperPolyLines.size() << " exists"; } }
{ "content_hash": "90fe752b9985b3ef7ffd78391be062f0", "timestamp": "", "source": "github", "line_count": 721, "max_line_length": 165, "avg_line_length": 25.309292649098474, "alnum_prop": 0.6881302060499781, "repo_name": "rfloca/MITK", "id": "cc828c0761acb0010a3ffc27bb253b9e78afa5cf", "size": "18746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/PlanarFigure/DataManagement/mitkPlanarFigure.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2999153" }, { "name": "C++", "bytes": "23962453" }, { "name": "CSS", "bytes": "52056" }, { "name": "IDL", "bytes": "5583" }, { "name": "Java", "bytes": "350330" }, { "name": "JavaScript", "bytes": "287239" }, { "name": "Objective-C", "bytes": "513480" }, { "name": "Perl", "bytes": "982" }, { "name": "Python", "bytes": "7545" }, { "name": "Shell", "bytes": "5789" }, { "name": "TeX", "bytes": "1204" }, { "name": "XSLT", "bytes": "30684" } ], "symlink_target": "" }
#ifndef SCROLLING_BUFFER_IS_DEFINED #define SCROLLING_BUFFER_IS_DEFINED #ifdef ARDUINO #include <alib-c/includes/alib_error.h> #else #include <alib-c/alib_error.h> #endif extern "C" { #include <inttypes.h> #include <stdlib.h> #include <string.h> } namespace alib { #ifndef SB_SIFT_BUFF_SIZE #define SB_SIFT_BUFF_SIZE 32 #endif #ifndef SB_DEFAULT_BUFF_SIZE #define SB_DEFAULT_BUFF_SIZE 32 #endif /* Object used to efficiently store data into a single buffer that may need to be wrapped, * meaning that if a buffer of 32 bytes long is full, then 5 more bytes is appended to it, then * the new data would be placed at the beginning of the internal buffer. Use ability should be similar * to any other buffer/array object. */ class ScrollingBuffer { private: uint8_t* buff; uint8_t* buffBegin; size_t buffSize; size_t buffCount; /* Moves 'buffBegin' to the beginning of the buffer with an offset of * ('buffBegin' - buffer end). */ void wrapBuffBegin(); /* Gets the pointer of the given index. */ uint8_t* getPtr(size_t index) const; int getIndex(uint8_t* ptr); public: /* Constructors */ void init(); void init(size_t bufferSize); ScrollingBuffer(); ScrollingBuffer(size_t bufferSize); static ScrollingBuffer* NEW(); static ScrollingBuffer* NEW(size_t bufferSize); /****************/ /* Adds a new value to the buffer, but will not remove any old values. */ int append(uint8_t b); /* Appends an array to the buffer, but will not remove any old values. */ int append(uint8_t* data, size_t dataLen); /* Adds a new value to the buffer. If the buffer is already full, then * the oldest data will be written over. */ void pushOn(uint8_t b); /* Similar to 'pushOn(uint8_t)', except that an array is pushed on instead of a single byte. * If the buffer must wrap over old data, old data will be overwritten without warning. */ void pushOn(uint8_t* data, size_t dataLen); #if 0 void sift(); #endif /* Getters */ /* Pulls the first byte out of the scrolling buffer. * Data pulled off is no longer available in the buffer. */ int pullOff(); /* Pulls an array of bytes out from the beginning the scrolling buffer. * The returned value is dynamically allocated and MUST BE FREED BY THE CALLER. * * Data pulled off is no longer available in the buffer. */ uint8_t* pullOff(size_t* count); void clear(); /* Gets the byte at the given index of the scrolling buffer. * This is the index relative to the beginning of the buffer, not the * beginning of the internal buffer. */ int16_t get(size_t index) const; size_t count()const; size_t size()const; /***********/ /* Setters */ void setSize(size_t size); /***********/ /* Operator Overloads */ int16_t operator[](size_t index); /**********************/ /* Destructors */ ~ScrollingBuffer(); static void FREE(ScrollingBuffer* sb); static void DEL(ScrollingBuffer** sb); /***************/ }; } #endif
{ "content_hash": "e16eccc484e3c8069ca83cd1d08ef694", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 104, "avg_line_length": 26.839285714285715, "alnum_prop": 0.6706586826347305, "repo_name": "acs9307/alib-cpp", "id": "3740718b99fb4f8a9f9d3e33f56eecbda3d6c50a", "size": "3006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "includes/ScrollingBuffer.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "605" }, { "name": "C++", "bytes": "52640" }, { "name": "Makefile", "bytes": "757" }, { "name": "Python", "bytes": "1471" } ], "symlink_target": "" }
var previousMobird = root.Mobird; var Mobird = function(obj) { if (obj instanceof Mobird) { return obj; } if (!(this instanceof Mobird)) { return new Mobird(obj); } this._wrapped = obj; }; Mobird.VERSION = '0.2.1'; Mobird.$ = $; Mobird.noConflict = function() { root.Mobird = previousMobird; return this; };
{ "content_hash": "f77602d2904722ec1763f167b1d32f66", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 34, "avg_line_length": 16.65, "alnum_prop": 0.6336336336336337, "repo_name": "pinkpoppy/practice", "id": "bfb29ceabcd775fcd11dc1830266874f69d89c16", "size": "333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mobrid/packages/core/mobird.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355435" }, { "name": "HTML", "bytes": "91049" }, { "name": "JavaScript", "bytes": "2114546" }, { "name": "PHP", "bytes": "5297" } ], "symlink_target": "" }
package com.android.internal.app; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.DialogFragment; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import com.android.internal.R; /** * Shows a dialog with actions to take on a chooser target */ public class ResolverTargetActionsDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { private static final String NAME_KEY = "componentName"; private static final String PINNED_KEY = "pinned"; private static final String TITLE_KEY = "title"; // Sync with R.array.resolver_target_actions_* resources private static final int TOGGLE_PIN_INDEX = 0; private static final int APP_INFO_INDEX = 1; public ResolverTargetActionsDialogFragment() { } public ResolverTargetActionsDialogFragment(CharSequence title, ComponentName name, boolean pinned) { Bundle args = new Bundle(); args.putCharSequence(TITLE_KEY, title); args.putParcelable(NAME_KEY, name); args.putBoolean(PINNED_KEY, pinned); setArguments(args); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Bundle args = getArguments(); final int itemRes = args.getBoolean(PINNED_KEY, false) ? R.array.resolver_target_actions_unpin : R.array.resolver_target_actions_pin; return new Builder(getContext()) .setCancelable(true) .setItems(itemRes, this) .setTitle(args.getCharSequence(TITLE_KEY)) .create(); } @Override public void onClick(DialogInterface dialog, int which) { final Bundle args = getArguments(); ComponentName name = args.getParcelable(NAME_KEY); switch (which) { case TOGGLE_PIN_INDEX: SharedPreferences sp = ChooserActivity.getPinnedSharedPrefs(getContext()); final String key = name.flattenToString(); boolean currentVal = sp.getBoolean(name.flattenToString(), false); if (currentVal) { sp.edit().remove(key).apply(); } else { sp.edit().putBoolean(key, true).apply(); } // Force the chooser to requery and resort things getActivity().recreate(); break; case APP_INFO_INDEX: Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) .setData(Uri.fromParts("package", name.getPackageName(), null)) .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); startActivity(in); break; } dismiss(); } }
{ "content_hash": "22eae3b049fbefb6e896ea30b8f98254", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 96, "avg_line_length": 35.654761904761905, "alnum_prop": 0.6320534223706177, "repo_name": "xorware/android_frameworks_base", "id": "8156f79f3be3bcb8d68cbc46ced5c627fdabe40d", "size": "3614", "binary": false, "copies": "3", "ref": "refs/heads/n", "path": "core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "167132" }, { "name": "C++", "bytes": "7092455" }, { "name": "GLSL", "bytes": "20654" }, { "name": "HTML", "bytes": "224185" }, { "name": "Java", "bytes": "78926513" }, { "name": "Makefile", "bytes": "420231" }, { "name": "Python", "bytes": "42309" }, { "name": "RenderScript", "bytes": "153826" }, { "name": "Shell", "bytes": "21079" } ], "symlink_target": "" }
<?php namespace Nicmart\Benchmark; class MachineData { public static $opcacheExtenstions = array( 'apc' => array('Alternative PHP Cache (APC)', 'apc.enabled'), 'eaccelerator' => array('eAccelerator', 'eaccelerator.enabled'), 'xcache' => array('XCache', null), 'Zend OPcache' => array('Zend OPcache', 'opcache.enable') ); public function phpVersion() { return phpversion(); } /** * @return array */ public function opcodeCacheData() { $cacheData = array( ); foreach (static::$opcacheExtenstions as $name => $data) { list($title, $iniSetting) = $data; if ($this->hasCache($name, $iniSetting)) { $cacheData['title'] = $title; $cacheData['name'] = $name; $ref = new \ReflectionExtension($name); $cacheData['version'] = $ref->getVersion(); $cacheData['settings'] = $ref->getINIEntries(); break; } } return $cacheData; } private function hasCache($name, $iniSetting) { return extension_loaded($name) && ($iniSetting === null || ini_get($iniSetting)); } }
{ "content_hash": "279d9e41738b88ed35845874eb9345cd", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 89, "avg_line_length": 24.431372549019606, "alnum_prop": 0.5240770465489567, "repo_name": "nicmart/Benchmark", "id": "70cd1f04be4d11f389944d5d77b4dfe14006714f", "size": "1470", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nicmart/Benchmark/MachineData.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "23136" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ja"> <head> <!-- Generated by javadoc (1.8.0_252) on Mon Jul 06 12:25:12 JST 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>概要リスト (Device Connect SDK for Android)</title> <meta name="date" content="2020-07-06"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <div class="indexHeader"><span><a href="allclasses-frame.html" target="packageFrame">すべてのクラス</a></span></div> <div class="indexContainer"> <h2 title="パッケージ">パッケージ</h2> <ul title="パッケージ"> <li><a href="org/deviceconnect/android/cipher/signature/package-frame.html" target="packageFrame">org.deviceconnect.android.cipher.signature</a></li> <li><a href="org/deviceconnect/message/package-frame.html" target="packageFrame">org.deviceconnect.message</a></li> <li><a href="org/deviceconnect/message/entity/package-frame.html" target="packageFrame">org.deviceconnect.message.entity</a></li> <li><a href="org/deviceconnect/message/intent/message/package-frame.html" target="packageFrame">org.deviceconnect.message.intent.message</a></li> <li><a href="org/deviceconnect/profile/package-frame.html" target="packageFrame">org.deviceconnect.profile</a></li> <li><a href="org/deviceconnect/utils/package-frame.html" target="packageFrame">org.deviceconnect.utils</a></li> </ul> </div> <p>&nbsp;</p> </body> </html>
{ "content_hash": "4f092ad4bed554291e0f883670327495", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 149, "avg_line_length": 56.592592592592595, "alnum_prop": 0.731020942408377, "repo_name": "DeviceConnect/DeviceConnect-Docs", "id": "3cebba2d47f9ba5a0681d0bca180312a89ae1680", "size": "1582", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "Specification/API_Reference/Android_SDK/overview-frame.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "65446" }, { "name": "HTML", "bytes": "15427775" }, { "name": "JavaScript", "bytes": "53778" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using MetaDslx.Core; using MetaDslx.Compiler; using MetaDslx.Compiler.Binding; using MetaDslx.Languages.Soal.Symbols; namespace MetaDslx.Languages.Soal.Binding { public class SoalSymbolBuilder : SymbolBuilder { public SoalSymbolBuilder(CompilationBase compilation) : base(compilation) { } private SoalFactory _factory; private SoalFactory Factory { get { if (_factory == null) { Interlocked.CompareExchange(ref _factory, new SoalFactory(this.ModelBuilder), null); } return _factory; } } protected override MutableSymbol CreateSymbolCore(Type symbolType) { return this.Factory.Create(symbolType); } } }
{ "content_hash": "6687891146f53d50e4080f9f292f8695", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 104, "avg_line_length": 24.275, "alnum_prop": 0.615859938208033, "repo_name": "dbogancs/soal-cs", "id": "15ecc2d273970ef294dbe5a73336ba80ca84e36b", "size": "1099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/Main/MetaDslx.Languages.Soal/Binding/SoalSymbolBuilder.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "3977551" }, { "name": "Objective-C++", "bytes": "5243" } ], "symlink_target": "" }
<div class="placeholder-animation" [ngStyle]="{'height': height, 'width': width}"> </div>
{ "content_hash": "23df916648995f68bb3bbae928a513be", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 52, "avg_line_length": 31.666666666666668, "alnum_prop": 0.631578947368421, "repo_name": "Ismaestro/angular2-tour-of-heroes", "id": "6fc1b517d7787c1d36229132ea53bf67310b69d1", "size": "95", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/shared/components/loading-placeholder/loading-placeholder.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2811" }, { "name": "HTML", "bytes": "9717" }, { "name": "JavaScript", "bytes": "1745" }, { "name": "TypeScript", "bytes": "20996" } ], "symlink_target": "" }
using System; namespace Manatee.Json.Console.Logging { /// <summary> /// Logger type initialization /// </summary> public static class Log { private static Type _logType = typeof(NullLog); /// <summary> /// Sets up logging to be with a certain type /// </summary> /// <typeparam name="T">The type of ILog for the application to use</typeparam> public static void InitializeWith<T>() where T : ILog, new() { _logType = typeof(T); } /// <summary> /// Initializes a new instance of a logger for an object. /// This should be done only once per object name. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns>ILog instance for an object if log type has been initialized; otherwise null</returns> public static ILog GetLoggerFor(Type objectType) { var logger = Activator.CreateInstance(_logType) as ILog; logger?.InitializeFor(objectType); return logger; } } }
{ "content_hash": "a42839d060312519ab348451a8236b55", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 101, "avg_line_length": 27.02857142857143, "alnum_prop": 0.6775898520084567, "repo_name": "gregsdennis/Manatee.Json", "id": "acf0faa1c4a4142650d06d49197e74bc7e2315b1", "size": "948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Manatee.Json.Console/Logging/Log.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "104" }, { "name": "C#", "bytes": "1343886" }, { "name": "CSS", "bytes": "136473" }, { "name": "JavaScript", "bytes": "163934" }, { "name": "Liquid", "bytes": "5641" }, { "name": "PowerShell", "bytes": "245" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_13) on Wed Apr 02 19:28:39 CDT 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> CaseInsensitiveLetterState (cpptasks 1.0b5 API) </TITLE> <META NAME="keywords" CONTENT="net.sf.antcontrib.cpptasks.parser.CaseInsensitiveLetterState class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="CaseInsensitiveLetterState (cpptasks 1.0b5 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CaseInsensitiveLetterState.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/BranchState.html" title="class in net.sf.antcontrib.cpptasks.parser"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/CParser.html" title="class in net.sf.antcontrib.cpptasks.parser"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?net/sf/antcontrib/cpptasks/parser/CaseInsensitiveLetterState.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CaseInsensitiveLetterState.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> net.sf.antcontrib.cpptasks.parser</FONT> <BR> Class CaseInsensitiveLetterState</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">net.sf.antcontrib.cpptasks.parser.AbstractParserState</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>net.sf.antcontrib.cpptasks.parser.CaseInsensitiveLetterState</B> </PRE> <HR> <DL> <DT><PRE>public final class <B>CaseInsensitiveLetterState</B><DT>extends <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A></DL> </PRE> <P> This parser state checks consumed characters against a specific character (case insensitive). <P> <P> <DL> <DT><B>Author:</B></DT> <DD>Curt Arnold</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/CaseInsensitiveLetterState.html#CaseInsensitiveLetterState(net.sf.antcontrib.cpptasks.parser.AbstractParser, char, net.sf.antcontrib.cpptasks.parser.AbstractParserState, net.sf.antcontrib.cpptasks.parser.AbstractParserState)">CaseInsensitiveLetterState</A></B>(<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParser.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParser</A>&nbsp;parser, char&nbsp;matchLetter, <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A>&nbsp;nextStateArg, <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A>&nbsp;noMatchStateArg)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Constructor.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/CaseInsensitiveLetterState.html#consume(char)">consume</A></B>(char&nbsp;ch)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Consumes a character and returns the next state for the parser.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_net.sf.antcontrib.cpptasks.parser.AbstractParserState"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class net.sf.antcontrib.cpptasks.parser.<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html#getParser()">getParser</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="CaseInsensitiveLetterState(net.sf.antcontrib.cpptasks.parser.AbstractParser, char, net.sf.antcontrib.cpptasks.parser.AbstractParserState, net.sf.antcontrib.cpptasks.parser.AbstractParserState)"><!-- --></A><H3> CaseInsensitiveLetterState</H3> <PRE> public <B>CaseInsensitiveLetterState</B>(<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParser.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParser</A>&nbsp;parser, char&nbsp;matchLetter, <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A>&nbsp;nextStateArg, <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A>&nbsp;noMatchStateArg)</PRE> <DL> <DD>Constructor. <P> <DL> <DT><B>Parameters:</B><DD><CODE>parser</CODE> - parser<DD><CODE>matchLetter</CODE> - letter to match<DD><CODE>nextStateArg</CODE> - next state if a match on the letter<DD><CODE>noMatchStateArg</CODE> - state if no match on letter</DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="consume(char)"><!-- --></A><H3> consume</H3> <PRE> public <A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A> <B>consume</B>(char&nbsp;ch)</PRE> <DL> <DD>Consumes a character and returns the next state for the parser. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html#consume(char)">consume</A></CODE> in class <CODE><A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/AbstractParserState.html" title="class in net.sf.antcontrib.cpptasks.parser">AbstractParserState</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>ch</CODE> - next character <DT><B>Returns:</B><DD>the configured nextState if ch is the expected character or the configure noMatchState otherwise.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CaseInsensitiveLetterState.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/BranchState.html" title="class in net.sf.antcontrib.cpptasks.parser"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../net/sf/antcontrib/cpptasks/parser/CParser.html" title="class in net.sf.antcontrib.cpptasks.parser"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?net/sf/antcontrib/cpptasks/parser/CaseInsensitiveLetterState.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CaseInsensitiveLetterState.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright © 2001-2008 <a href="http://ant-contrib.sourceforge.net">Ant-Contrib Project</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "f751ed02a84671b570854e5b42c79f09", "timestamp": "", "source": "github", "line_count": 286, "max_line_length": 493, "avg_line_length": 50.68531468531469, "alnum_prop": 0.653628587196468, "repo_name": "flax3lbs/cpptasks-parallel", "id": "e6a9cd90cf41bed9f33dc4c87371d003f471f157", "size": "14496", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "site/apidocs/net/sf/antcontrib/cpptasks/parser/CaseInsensitiveLetterState.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "881" }, { "name": "CSS", "bytes": "7505" }, { "name": "HTML", "bytes": "10453721" }, { "name": "Java", "bytes": "1230712" }, { "name": "XSLT", "bytes": "8485" } ], "symlink_target": "" }
/* * 07/28/2008 * * RtfGenerator.java - Generates RTF via a simple Java API. * * This library is distributed under a modified BSD license. See the included * LICENSE file for details. */ package org.fife.ui.rsyntaxtextarea; import java.awt.*; import java.util.ArrayList; import java.util.List; import org.fife.ui.rtextarea.RTextArea; /** * Generates RTF text via a simple Java API.<p> * * The following RTF features are supported: * <ul> * <li>Fonts * <li>Font sizes * <li>Foreground and background colors * <li>Bold, italic, and underline * </ul> * * The RTF generated isn't really "optimized," but it will do, especially for * small amounts of text, such as what's common when copy-and-pasting. It * tries to be sufficient for the use case of copying syntax highlighted * code: * <ul> * <li>It assumes that tokens changing foreground color often is fairly * common. * <li>It assumes that background highlighting is fairly uncommon. * </ul> * * @author Robert Futrell * @version 1.1 */ public class RtfGenerator { private Color mainBG; private List<Font> fontList; private List<Color> colorList; private StringBuilder document; private boolean lastWasControlWord; private int lastFontIndex; private int lastFGIndex; private boolean lastBold; private boolean lastItalic; private int lastFontSize; /** * Java2D assumes a 72 dpi screen resolution, but on Windows the screen * resolution is either 96 dpi or 120 dpi, depending on your font display * settings. This is an attempt to make the RTF generated match the * size of what's displayed in the RSyntaxTextArea. */ private int screenRes; /** * The default font size for RTF. This is point size, in half * points. */ private static final int DEFAULT_FONT_SIZE = 12;//24; /** * Constructor. * * @param mainBG The main background color to use. */ public RtfGenerator(Color mainBG) { this.mainBG = mainBG; fontList = new ArrayList<>(1); // Usually only 1. colorList = new ArrayList<>(1); // Usually only 1. document = new StringBuilder(); reset(); } /** * Adds a newline to the RTF document. * * @see #appendToDoc(String, Font, Color, Color) */ public void appendNewline() { document.append("\\line"); document.append('\n'); // Just for ease of reading RTF. lastWasControlWord = false; } /** * Appends styled text to the RTF document being generated. * * @param text The text to append. * @param f The font of the text. If this is <code>null</code>, the * default font is used. * @param fg The foreground of the text. If this is <code>null</code>, * the default foreground color is used. * @param bg The background color of the text. If this is * <code>null</code>, the default background color is used. * @see #appendNewline() */ public void appendToDoc(String text, Font f, Color fg, Color bg) { appendToDoc(text, f, fg, bg, false); } /** * Appends styled text to the RTF document being generated. * * @param text The text to append. * @param f The font of the text. If this is <code>null</code>, the * default font is used. * @param bg The background color of the text. If this is * <code>null</code>, the default background color is used. * @param underline Whether the text should be underlined. * @see #appendNewline() */ public void appendToDocNoFG(String text, Font f, Color bg, boolean underline) { appendToDoc(text, f, null, bg, underline, false); } /** * Appends styled text to the RTF document being generated. * * @param text The text to append. * @param f The font of the text. If this is <code>null</code>, the * default font is used. * @param fg The foreground of the text. If this is <code>null</code>, * the default foreground color is used. * @param bg The background color of the text. If this is * <code>null</code>, the default background color is used. * @param underline Whether the text should be underlined. * @see #appendNewline() */ public void appendToDoc(String text, Font f, Color fg, Color bg, boolean underline) { appendToDoc(text, f, fg, bg, underline, true); } /** * Appends styled text to the RTF document being generated. * * @param text The text to append. * @param f The font of the text. If this is <code>null</code>, the * default font is used. * @param fg The foreground of the text. If this is <code>null</code>, * the default foreground color is used. * @param bg The background color of the text. If this is * <code>null</code>, the default background color is used. * @param underline Whether the text should be underlined. * @param setFG Whether the foreground specified by <code>fg</code> should * be honored (if it is non-<code>null</code>). * @see #appendNewline() */ public void appendToDoc(String text, Font f, Color fg, Color bg, boolean underline, boolean setFG) { if (text!=null) { // Set font to use, if different from last addition. int fontIndex = f==null ? 0 : (getFontIndex(fontList, f)+1); if (fontIndex!=lastFontIndex) { document.append("\\f").append(fontIndex); lastFontIndex = fontIndex; lastWasControlWord = true; } // Set styles to use. if (f!=null) { int fontSize = fixFontSize(f.getSize2D()*2); // Half points! if (fontSize!=lastFontSize) { document.append("\\fs").append(fontSize); lastFontSize = fontSize; lastWasControlWord = true; } if (f.isBold()!=lastBold) { document.append(lastBold ? "\\b0" : "\\b"); lastBold = !lastBold; lastWasControlWord = true; } if (f.isItalic()!=lastItalic) { document.append(lastItalic ? "\\i0" : "\\i"); lastItalic = !lastItalic; lastWasControlWord = true; } } else { // No font specified - assume neither bold nor italic. if (lastFontSize!=DEFAULT_FONT_SIZE) { document.append("\\fs").append(DEFAULT_FONT_SIZE); lastFontSize = DEFAULT_FONT_SIZE; lastWasControlWord = true; } if (lastBold) { document.append("\\b0"); lastBold = false; lastWasControlWord = true; } if (lastItalic) { document.append("\\i0"); lastItalic = false; lastWasControlWord = true; } } if (underline) { document.append("\\ul"); lastWasControlWord = true; } // Set the foreground color. if (setFG) { int fgIndex = 0; if (fg!=null) { // null => fg color index 0 fgIndex = getColorIndex(colorList, fg)+1; } if (fgIndex!=lastFGIndex) { document.append("\\cf").append(fgIndex); lastFGIndex = fgIndex; lastWasControlWord = true; } } // Set the background color. if (bg!=null) { int pos = getColorIndex(colorList, bg); document.append("\\highlight").append(pos+1); lastWasControlWord = true; } if (lastWasControlWord) { document.append(' '); // Delimiter lastWasControlWord = false; } escapeAndAdd(document, text); // Reset everything that was set for this text fragment. if (bg!=null) { document.append("\\highlight0"); lastWasControlWord = true; } if (underline) { document.append("\\ul0"); lastWasControlWord = true; } } } /** * Appends some text to a buffer, with special care taken for special * characters as defined by the RTF spec. * * <ul> * <li>All tab characters are replaced with the string * "<code>\tab</code>" * <li>'\', '{' and '}' are changed to "\\", "\{" and "\}" * </ul> * * @param text The text to append (with tab chars substituted). * @param sb The buffer to append to. */ private void escapeAndAdd(StringBuilder sb, String text) { int count = text.length(); for (int i=0; i<count; i++) { char ch = text.charAt(i); switch (ch) { case '\t': // Micro-optimization: for syntax highlighting with // tab indentation, there are often multiple tabs // back-to-back at the start of lines, so don't put // spaces between each "\tab". sb.append("\\tab"); while ((++i<count) && text.charAt(i)=='\t') { sb.append("\\tab"); } sb.append(' '); i--; // We read one too far. break; case '\\': case '{': case '}': sb.append('\\').append(ch); break; default: if (ch <= 127) { sb.append(ch); } else { // Trailing space for delimiter sb.append("\\u").append((int)ch).append(' '); } break; } } } /** * Returns a font point size, adjusted for the current screen resolution.<p> * * Java2D assumes 72 dpi. On systems with larger dpi (Windows, GTK, etc.), * font rendering will appear too small if we simply return a Java "Font" * object's getSize() value. We need to adjust it for the screen * resolution. * * @param pointSize A Java Font's point size, as returned from * <code>getSize2D()</code>. * @return The font point size, adjusted for the current screen resolution. * This will allow other applications to render fonts the same * size as they appear in the Java application. */ private int fixFontSize(float pointSize) { if (screenRes!=72) { // Java2D assumes 72 dpi pointSize = Math.round(pointSize*72f/screenRes); } return (int)pointSize; } /** * Returns the index of the specified item in a list. If the item * is not in the list, it is added, and its new index is returned. * * @param list The list (possibly) containing the item. * @param item The item to get the index of. * @return The index of the item. */ private static int getColorIndex(List<Color> list, Color item) { int pos = list.indexOf(item); if (pos==-1) { list.add(item); pos = list.size()-1; } return pos; } private String getColorTableRtf() { // Example: // "{\\colortbl ;\\red255\\green0\\blue0;\\red0\\green0\\blue255; }" StringBuilder sb = new StringBuilder(); sb.append("{\\colortbl ;"); for (Color c : colorList) { sb.append("\\red").append(c.getRed()); sb.append("\\green").append(c.getGreen()); sb.append("\\blue").append(c.getBlue()); sb.append(';'); } sb.append("}"); return sb.toString(); } /** * Returns the index of the specified font in a list of fonts. This * method only checks for a font by its family name; its attributes such * as bold and italic are ignored.<p> * * If the font is not in the list, it is added, and its new index is * returned. * * @param list The list (possibly) containing the font. * @param font The font to get the index of. * @return The index of the font. */ private static int getFontIndex(List<Font> list, Font font) { String fontName = font.getFamily(); for (int i=0; i<list.size(); i++) { Font font2 = list.get(i); if (font2.getFamily().equals(fontName)) { return i; } } list.add(font); return list.size()-1; } private String getFontTableRtf() { // Example: // "{\\fonttbl{\\f0\\fmodern\\fcharset0 Courier;}}" StringBuilder sb = new StringBuilder(); // Workaround for text areas using the Java logical font "Monospaced" // by default. There's no way to know what it's mapped to, so we // just search for a monospaced font on the system. String monoFamilyName = getMonospacedFontFamily(); sb.append("{\\fonttbl{\\f0\\fnil\\fcharset0 ").append(monoFamilyName).append(";}"); for (int i=0; i<fontList.size(); i++) { Font f = fontList.get(i); String familyName = f.getFamily(); if (familyName.equals(Font.MONOSPACED)) { familyName = monoFamilyName; } sb.append("{\\f").append(i+1).append("\\fnil\\fcharset0 "); sb.append(familyName).append(";}"); } sb.append('}'); return sb.toString(); } /** * Returns a good "default" monospaced font to use when Java's logical * font "Monospaced" is found. * * @return The monospaced font family to use. */ private static String getMonospacedFontFamily() { String family = RTextArea.getDefaultFont().getFamily(); if (Font.MONOSPACED.equals(family)) { family = "Courier"; } return family; } /** * Returns the RTF document created by this generator. * * @return The RTF document, as a <code>String</code>. */ public String getRtf() { // Add background to the color table before adding it to our buffer int mainBGIndex = getColorIndex(colorList, mainBG); StringBuilder sb = new StringBuilder(); sb.append("{"); // Header sb.append("\\rtf1\\ansi\\ansicpg1252"); sb.append("\\deff0"); // First font in font table is the default sb.append("\\deflang1033"); sb.append("\\viewkind4"); // "Normal" view sb.append("\\uc\\pard\\f0"); sb.append("\\fs20"); // Font size in half-points (default 24) sb.append(getFontTableRtf()).append('\n'); sb.append(getColorTableRtf()).append('\n'); // Content int bgIndex = mainBGIndex + 1; sb.append("\\cb").append(bgIndex).append(' '); lastWasControlWord = true; if (document.length() > 0) { document.append("\\line"); // Forced line break } sb.append(document); sb.append("}"); //System.err.println("*** " + sb.length()); return sb.toString(); } /** * Resets this generator. All document information and content is * cleared. */ public void reset() { fontList.clear(); colorList.clear(); document.setLength(0); lastWasControlWord = false; lastFontIndex = 0; lastFGIndex = 0; lastBold = false; lastItalic = false; lastFontSize = DEFAULT_FONT_SIZE; // Dummy resolution when running headless screenRes = GraphicsEnvironment.isHeadless() ? 72 : Toolkit.getDefaultToolkit().getScreenResolution(); } }
{ "content_hash": "91ccf79f6df70657b8fba614ba9f38e5", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 85, "avg_line_length": 27.65995975855131, "alnum_prop": 0.6424674474430785, "repo_name": "bobbylight/RSyntaxTextArea", "id": "b4edc1f8f59a13014757514e7a668fcb92d4a475", "size": "13747", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RSyntaxTextArea/src/main/java/org/fife/ui/rsyntaxtextarea/RtfGenerator.java", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "1253" }, { "name": "Java", "bytes": "2905050" }, { "name": "Lex", "bytes": "971151" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Consp. fung. (Leipzig) 126 (1805) #### Original name Uredo menthae var. violae Alb. & Schwein. ### Remarks null
{ "content_hash": "34df2089bf18d82582794554a8f960d0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 13.461538461538462, "alnum_prop": 0.6857142857142857, "repo_name": "mdoering/backbone", "id": "202afe6744ec4459c21727f1b8ccaa82abfccb09", "size": "240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Uredo/Uredo menthae/Uredo menthae violae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "60448f7cf5c5f0ed66551ecb58d022fe", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "aeb62ced9096a4bfeac995ca1061fe507cd59d7a", "size": "212", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Chromista/Oomycota/Oomycetes/Peronosporales/Peronosporaceae/Peronospora/Peronospora aparines/ Syn. Peronospora calotheca aparines/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace backend\controllers; use Yii; use backend\models\Locations; use backend\models\LocationsSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\helpers\Json; /** * LocationsController implements the CRUD actions for Locations model. */ class LocationsController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Locations models. * @return mixed */ public function actionIndex() { $searchModel = new LocationsSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } public function actionGetCityProvince($zipCode) { $location = Locations::find()->where(['zip_code'=>$zipCode])->one(); echo Json::encode($location); } /** * Displays a single Locations model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Locations model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Locations(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->location_id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Locations model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->location_id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Locations model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Locations model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Locations the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Locations::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
{ "content_hash": "7249e38a4af57855291dddf378ed76cb", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 85, "avg_line_length": 26.21875, "alnum_prop": 0.5443980929678188, "repo_name": "kitsabrahams/advanced", "id": "04d1c20d429408ff44da6a4d2e360db03c6b49a4", "size": "3356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/controllers/LocationsController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2728" }, { "name": "JavaScript", "bytes": "173" }, { "name": "PHP", "bytes": "215851" }, { "name": "Shell", "bytes": "1541" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; using System.Threading.Tasks; namespace Exchange.StockPriceGenerator { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } } }
{ "content_hash": "44cb49465a5d016e2be9f2f65a5dc497", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 23.263157894736842, "alnum_prop": 0.7239819004524887, "repo_name": "Zabaa/Exchange", "id": "9bd626eb51000e6c3e0e889558170177975cd1ca", "size": "444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Exchange.StockPriceGenerator/ProjectInstaller.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "99" }, { "name": "C#", "bytes": "197725" }, { "name": "CSS", "bytes": "60148" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "466324" } ], "symlink_target": "" }
FactoryGirl.define do factory :shopart_credit_card, :class => 'Shopart::CreditCard' do end end
{ "content_hash": "a2c15b1bb7202b2edf6cdb296907af00", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 66, "avg_line_length": 17.5, "alnum_prop": 0.6952380952380952, "repo_name": "Shayol/Shopart", "id": "e149b19252065afc9fb3e7b44f1bdc460f52d858", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories/shopart_credit_cards.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2440" }, { "name": "HTML", "bytes": "19968" }, { "name": "JavaScript", "bytes": "1862" }, { "name": "Ruby", "bytes": "48976" } ], "symlink_target": "" }
Sample source code below will display you how to manage a complex task like read barcode from live video cam (wpf) with barcode reader sdk in VB.NET. ByteScout Barcode Suite is the bundle that privides 3 SDK products to generate barcodes (Barcode SDK), read barcodes (Barcode Reaer SDK) and read and write spreadsheets (Spreadsheet SDK) and you can use it to read barcode from live video cam (wpf) with barcode reader sdk with VB.NET. The following code snippet for ByteScout Barcode Suite works best when you need to quickly read barcode from live video cam (wpf) with barcode reader sdk in your VB.NET application. Simply copy and paste in your VB.NET project or application you and then run your app! Further improvement of the code will make it more robust. If you want to try other source code samples then the free trial version of ByteScout Barcode Suite is available for download from our website. Just try other source code samples for VB.NET. ## REQUEST FREE TECH SUPPORT [Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Barcode%20Suite%20Question) or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Barcode%20Suite%20Question) ## ON-PREMISE OFFLINE SDK [Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme) [Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme) [Sign Up For Online Training](https://academy.bytescout.com/) ## ON-DEMAND REST WEB API [Get your API key](https://pdf.co/documentation/api?utm_source=github-readme) [Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme) [Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API) ## VIDEO REVIEW [https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8) <!-- code block begin --> ##### ****Application.xaml.vb:** ``` Class Application ' Application-level events, such as Startup, Exit, and DispatcherUnhandledException ' can be handled in this file. End Class ``` <!-- code block end --> <!-- code block begin --> ##### ****MainWindow.xaml.vb:** ``` Imports System.ComponentModel Imports System.Drawing Imports System.Drawing.Imaging Imports System.IO Imports System.Reflection Imports System.Threading Imports System.Windows.Threading Imports Bytescout.BarCodeReader Imports TouchlessLib Public Class MainWindow ' Touchless lib manager object (to use it you should have TouchlessLib.dll and WebCamLib.dll) Private _touchlessMgr As TouchlessMgr ' USED IN POPUP MODE ONLY (see ShowScanPopup() method) ' Close or not on the first barcode found ' (results are saved in m_foundBarcodes) Public Property CloseOnFirstBarcodeFound As Boolean = False ' Indicates if the form is closed Public Property IsClosed As Boolean = False ' Background processing object Private _backgroundWorker As New BackgroundWorker() ' Barcode type to scan Private _barcodeTypeToFind As New BarcodeTypeSelector() ' Array with decoded barcodes from the last scanning session. Public Property FoundBarcodes As FoundBarcode() = Nothing ' Scanning delay (ms); default is to scan every 800 ms. Const ScanDelay As Integer = 800 ' Internal varaible to indicate the status. Public Shared Status As Boolean = True Public Sub New() InitializeComponent() lblScanning.Visibility = Visibility.Collapsed _backgroundWorker.WorkerSupportsCancellation = True AddHandler _backgroundWorker.DoWork, AddressOf BackgroundWorker_DoWork AddHandler _backgroundWorker.RunWorkerCompleted, AddressOf BackgroundWorker_RunWorkerCompleted End Sub Delegate Sub MyDelegate() ' Searches for barcodes in bitmap object Private Function FindBarcodes(bitmap As Bitmap) As FoundBarcode() Dim reader As New Bytescout.BarCodeReader.Reader() Try reader.RegistrationName = "demo" reader.RegistrationKey = "demo" Me.Dispatcher.Invoke(DispatcherPriority.Normal, Sub() UpdateBarcodeTypeToFindFromCombobox()) reader.BarcodeTypesToFind = _barcodeTypeToFind ' ----------------------------------------------------------------------- ' NOTE: We can read barcodes from specific page to increase performance . ' For sample please refer to "Decoding barcodes from PDF by pages" program. ' ----------------------------------------------------------------------- Dim result As FoundBarcode() = reader.ReadFrom(bitmap) Dim timeNow As String = String.Format("{0:HH:mm:ss:tt}", DateTime.Now) Dispatcher.Invoke(DispatcherPriority.Normal, Sub() If result IsNot Nothing And result.Length > 0 Then textAreaBarcodes.SelectAll() textAreaBarcodes.Selection.Text = Environment.NewLine & "Time: " & timeNow & Environment.NewLine ' insert barcodes into text box For Each barcode As FoundBarcode In result ' make a sound that we found the barcode Console.Beep() 'form the string with barcode value Dim barcodeValue As String = String.Format("Found: {0} {1}" & Environment.NewLine, barcode.Type, barcode.Value) ' add barcode to the text area output textAreaBarcodes.AppendText(barcodeValue & Environment.NewLine) ' add barcode to the list of saved barcodes lblFoundBarcodes.Content = String.Format("Found {0} barcodes:", result.Length) Next End If ' make "Scanning..." label flicker If lblScanning.Visibility = Visibility.Collapsed Then lblScanning.Visibility = Visibility.Visible Else lblScanning.Visibility = Visibility.Collapsed End If End Sub) ' return found barcodes Return result Finally reader.Dispose() End Try End Function ' Updates barcode type filter according with combobox selection Private Sub UpdateBarcodeTypeToFindFromCombobox() Dim selectedItemText As String = cbBarCodeType.Text If String.IsNullOrEmpty(selectedItemText) Then Throw New Exception("Empty barcode type selection.") _barcodeTypeToFind.Reset() ' Iterate through BarcodeTypeSelector bool properties ' and enable property by barcode name selected in the combobox For Each propertyInfo As PropertyInfo In GetType(BarcodeTypeSelector).GetProperties() ' Skip readonly properties If Not propertyInfo.CanWrite Then Continue For End If If propertyInfo.Name = selectedItemText Then propertyInfo.SetValue(_barcodeTypeToFind, True, Nothing) End If Next End Sub Private Sub Window_Loaded(sender As System.Object, e As RoutedEventArgs) Handles MyBase.Loaded 'Populate barcode types into the combobox PopulateBarcodeTypesCombobox() InitCamera() StartDecoding() End Sub Private Sub InitCamera() Try ' Create Touchless lib manager to work with video camera _touchlessMgr = New TouchlessMgr() ' Iterate through available video camera devices For Each camera As Camera In _touchlessMgr.Cameras ' Add to list of available camera devices cbCamera.Items.Add(camera) Next ' Select first available camera cbCamera.SelectedItem = _touchlessMgr.Cameras(0) ' Setting default image dimensions; see also camera selection event. _touchlessMgr.Cameras(0).CaptureWidth = Integer.Parse(tbCameraWidth.Text) _touchlessMgr.Cameras(0).CaptureHeight = Integer.Parse(tbCameraHeight.Text) Catch exception As Exception MessageBox.Show("No video camera available. Please connect camera." + Environment.NewLine + exception.Message) End Try End Sub Sub StartDecoding() UpdateCameraSelection() ' Clear the text box output Dim txt As New TextRange(textAreaBarcodes.Document.ContentStart, textAreaBarcodes.Document.ContentEnd) txt.Text = "" ' Clean list of found barcodes FoundBarcodes = Nothing ' Check camera selected If cbCamera.SelectedIndex <> -1 Then ' Set status Status = True ' Update UI buttons btnStart.IsEnabled = False btnStop.IsEnabled = True cbBarCodeType.IsEnabled = False cbCamera.IsEnabled = False tbCameraHeight.IsEnabled = False tbCameraWidth.IsEnabled = False lblScanning.Content = "Scanning..." ' Start the decoding thread _backgroundWorker.RunWorkerAsync(CloseOnFirstBarcodeFound) Else MessageBox.Show("Please select camera") End If End Sub Private Sub Window_Closing(sender As System.Object, e As CancelEventArgs) Handles MyBase.Closing Deinitialize() End Sub Private Sub cbCamera_SelectionChanged(sender As System.Object, e As SelectionChangedEventArgs) Handles cbCamera.SelectionChanged UpdateCameraSelection() End Sub Private Sub btnStart_Click(sender As System.Object, e As RoutedEventArgs) Handles btnStart.Click StartDecoding() End Sub Private Sub btnStop_Click(sender As System.Object, e As RoutedEventArgs) Handles btnStop.Click StopDecoding() End Sub Private Sub btnExit_Click(sender As System.Object, e As RoutedEventArgs) Handles btnExit.Click Close() End Sub Private Sub btnTryPopup_Click(sender As System.Object, e As RoutedEventArgs) Handles btnTryPopup.Click ' Stop scan if any StopDecoding() ' Deinit the current camera DeinitCamera() ShowScanPopup() ' Reinit current camera InitCamera() End Sub Sub BackgroundWorker_DoWork(sender As Object, e As DoWorkEventArgs) Dim worker As BackgroundWorker = sender Dim closeOnFirstBarcode As Boolean = e.Argument While True ' Work till user canceled the scan If worker.CancellationPending Then e.Cancel = True Return End If ' Get current frame bitmap from camera using Touchless lib Dim bitmap As Bitmap = _touchlessMgr.CurrentCamera.GetCurrentImage() ' Search barcodes Dim result As FoundBarcode() = Nothing If bitmap IsNot Nothing Then result = FindBarcodes(bitmap) ' Check if we need to stop on first barcode found If closeOnFirstBarcode AndAlso result IsNot Nothing AndAlso result.Length > 0 Then e.Result = result Return End If ' Wait a little to lower CPU load Thread.Sleep(ScanDelay) End While End Sub Sub BackgroundWorker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) ' Clear last results FoundBarcodes = Nothing If e.Cancelled Then lblScanning.Content = "Canceled" ElseIf e.Error IsNot Nothing Then lblScanning.Content = "Error: " & e.Error.Message Else lblScanning.Content = "Done." FoundBarcodes = e.Result End If StopDecoding() End Sub ' Update picture box with the latest frame from video camera Sub CurrentCamera_OnImageCaptured(sender As Object, e As CameraEventArgs) ' You can change image dimensions if needed '_touchlessMgr.CurrentCamera.CaptureWidth = 320 '_touchlessMgr.CurrentCamera.CaptureHeight = 240 Dispatcher.Invoke(DispatcherPriority.Normal, Sub() If _touchlessMgr IsNot Nothing Then pictureVideoPreview.BeginInit() Dim imageSource As BitmapImage = BitmapToImageSource(_touchlessMgr.CurrentCamera.GetCurrentImage(), ImageFormat.Png) Dim st = New ScaleTransform() st.ScaleX = 320.0F / imageSource.PixelWidth st.ScaleY = 240.0F / imageSource.PixelHeight pictureVideoPreview.Source = New TransformedBitmap(imageSource, st) pictureVideoPreview.EndInit() pictureVideoPreview.UpdateLayout() End If End Sub) End Sub Function BitmapToImageSource(bitmap As Bitmap, imageFormat As ImageFormat) As BitmapImage Using memoryStream As New MemoryStream bitmap.Save(memoryStream, imageFormat) memoryStream.Position = 0 Dim bitmapImage As New BitmapImage() bitmapImage.BeginInit() bitmapImage.StreamSource = memoryStream bitmapImage.CacheOption = BitmapCacheOption.OnLoad bitmapImage.EndInit() Return bitmapImage End Using End Function Sub StopDecoding() _backgroundWorker.CancelAsync() ' Update UI elements lblScanning.Visibility = Visibility.Collapsed ' Change working status Status = False btnStart.IsEnabled = True btnStop.IsEnabled = False cbBarCodeType.IsEnabled = True cbCamera.IsEnabled = True tbCameraHeight.IsEnabled = True tbCameraWidth.IsEnabled = True If CloseOnFirstBarcodeFound Then If FoundBarcodes IsNot Nothing AndAlso FoundBarcodes.Length > 0 Then Close() End If End If End Sub Sub UpdateCameraSelection() If cbCamera.Items.Count > 0 And cbCamera.SelectedIndex > -1 Then If _touchlessMgr.CurrentCamera IsNot Nothing Then RemoveHandler _touchlessMgr.CurrentCamera.OnImageCaptured, AddressOf CurrentCamera_OnImageCaptured End If _touchlessMgr.CurrentCamera = Nothing Dim currentCamera As Camera = _touchlessMgr.Cameras(cbCamera.SelectedIndex) ' Setting camera output image dimensions currentCamera.CaptureWidth = Integer.Parse(tbCameraWidth.Text) currentCamera.CaptureHeight = Integer.Parse(tbCameraHeight.Text) _touchlessMgr.CurrentCamera = currentCamera AddHandler _touchlessMgr.CurrentCamera.OnImageCaptured, AddressOf CurrentCamera_OnImageCaptured End If End Sub Sub PopulateBarcodeTypesCombobox() cbBarCodeType.Items.Clear() Dim items As New List(Of String)() For Each propertyInfo As PropertyInfo In GetType(BarcodeTypeSelector).GetProperties() ' Skip readonly properties If Not propertyInfo.CanWrite Then Continue For End If items.Add(propertyInfo.Name) Next items.Sort() cbBarCodeType.ItemsSource = items ' Select first item in combobox (first is "Find All") cbBarCodeType.SelectedItem = cbBarCodeType.Items(0) End Sub Sub Deinitialize() ' Cancel decoding thread _backgroundWorker.CancelAsync() ' Deinit camera DeinitCamera() ' Mark as closed _isClosed = True End Sub Sub DeinitCamera() If _touchlessMgr IsNot Nothing Then RemoveHandler _touchlessMgr.CurrentCamera.OnImageCaptured, AddressOf CurrentCamera_OnImageCaptured _touchlessMgr.CurrentCamera = Nothing End If If cbCamera.SelectedItem IsNot Nothing Then cbCamera.SelectedItem = Nothing End If cbCamera.Items.Clear() _touchlessMgr = Nothing Thread.Sleep(500) End Sub Sub ShowScanPopup() ' Create another MainWindow instance to scan barcodes Dim popup As New MainWindow() ' Set new popup position shifted by 20 pixels popup.Left = Left + 20 popup.Top = Top + 20 ' Set the new popup window to close on first found barcode popup.CloseOnFirstBarcodeFound = True ' Hide btnTryPopup button popup.btnTryPopup.Visibility = Visibility.Hidden popup.btnStop.Visibility = Visibility.Hidden popup.btnStart.Visibility = Visibility.Hidden ' Set the popup title popup.Title = "POPUP DIALOG - ONE-TIME SCAN" ' Show the dialog popup.Show() ' Now wait while the popup is closed (it will be closed on barcode found or canceled) While Not popup.IsClosed ' HACK: Simulate "DoEvents" Dispatcher.Invoke(DispatcherPriority.Background, Sub() Thread.Sleep(20)) Thread.Sleep(20) End While ' Checking if one-time scan dialog found barcodes If popup.FoundBarcodes IsNot Nothing AndAlso popup.FoundBarcodes.Length > 0 Then MessageBox.Show("Popup scan found the barcode: " & Environment.NewLine & popup.FoundBarcodes(0).Value, "POPUP RESULT") Else MessageBox.Show("Popup canceled. Returning to the main window") End If ' Close the dialog popup.Close() End Sub End Class ``` <!-- code block end --> <!-- code block begin --> ##### ****ReadFromVideoCamera.VS2010.WPF.vbproj:** ``` <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">x86</Platform> <ProjectGuid>{FF0390C3-47FC-4247-898F-9E59E60ED369}</ProjectGuid> <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids> <OutputType>WinExe</OutputType> <RootNamespace>ReadFromVideoCamera.VS2010.WPF</RootNamespace> <AssemblyName>ReadFromVideoCamera.VS2010.WPF</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> <MyType>Custom</MyType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <PlatformTarget>x86</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <IncrementalBuild>true</IncrementalBuild> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>ReadFromVideoCamera.VS2010.WPF.xml</DocumentationFile> <NoWarn>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036,42314</NoWarn> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> <PlatformTarget>x86</PlatformTarget> <DebugType>pdbonly</DebugType> <DebugSymbols>false</DebugSymbols> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <IncrementalBuild>false</IncrementalBuild> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>ReadFromVideoCamera.VS2010.WPF.xml</DocumentationFile> <NoWarn>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036,42314</NoWarn> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>Off</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <ItemGroup> <Reference Include="Bytescout.BarCodeReader"> <HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net4.00\Bytescout.BarCodeReader.dll</HintPath> </Reference> <Reference Include="System.Core" /> <Reference Include="System.Drawing" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> <Reference Include="System.Xaml"> <RequiredTargetFramework>4.0</RequiredTargetFramework> </Reference> <Reference Include="TouchlessLib, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <HintPath>.\TouchlessLib.dll</HintPath> </Reference> <Reference Include="WindowsBase" /> <Reference Include="PresentationCore" /> <Reference Include="PresentationFramework" /> </ItemGroup> <ItemGroup> <ApplicationDefinition Include="Application.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> </ApplicationDefinition> <Compile Include="Application.xaml.vb"> <DependentUpon>Application.xaml</DependentUpon> <SubType>Code</SubType> </Compile> </ItemGroup> <ItemGroup> <Import Include="System.Linq" /> <Import Include="System.Xml.Linq" /> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> <Import Include="System.Windows" /> <Import Include="System.Windows.Controls" /> <Import Include="System.Windows.Data" /> <Import Include="System.Windows.Documents" /> <Import Include="System.Windows.Input" /> <Import Include="System.Windows.Shapes" /> <Import Include="System.Windows.Media" /> <Import Include="System.Windows.Media.Imaging" /> <Import Include="System.Windows.Navigation" /> </ItemGroup> <ItemGroup> <Compile Include="MainWindow.xaml.vb"> <DependentUpon>MainWindow.xaml</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Page Include="MainWindow.xaml"> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> </Page> </ItemGroup> <ItemGroup> <Content Include="TouchlessLib.dll" /> <Content Include="WebCamLib.dll"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> </Project> ``` <!-- code block end -->
{ "content_hash": "161263640adcae677042e653781380f6", "timestamp": "", "source": "github", "line_count": 662, "max_line_length": 435, "avg_line_length": 35.60422960725076, "alnum_prop": 0.6388629613915995, "repo_name": "bytescout/ByteScout-SDK-SourceCode", "id": "8e1177abd87639e0205876df7a384641f2926030", "size": "23792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Barcode Suite/VB.NET/Read barcode from live video cam (wpf) with barcode reader sdk/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "364116" }, { "name": "Apex", "bytes": "243500" }, { "name": "Batchfile", "bytes": "151832" }, { "name": "C", "bytes": "224568" }, { "name": "C#", "bytes": "12909855" }, { "name": "C++", "bytes": "440474" }, { "name": "CSS", "bytes": "56817" }, { "name": "Classic ASP", "bytes": "46655" }, { "name": "Dockerfile", "bytes": "776" }, { "name": "Gherkin", "bytes": "3386" }, { "name": "HTML", "bytes": "17276296" }, { "name": "Java", "bytes": "1483408" }, { "name": "JavaScript", "bytes": "3033610" }, { "name": "PHP", "bytes": "838746" }, { "name": "Pascal", "bytes": "398090" }, { "name": "PowerShell", "bytes": "715204" }, { "name": "Python", "bytes": "703542" }, { "name": "QMake", "bytes": "880" }, { "name": "TSQL", "bytes": "3080" }, { "name": "VBA", "bytes": "383773" }, { "name": "VBScript", "bytes": "1504410" }, { "name": "Visual Basic .NET", "bytes": "9489450" } ], "symlink_target": "" }
package edu.mit.spacenet.gui.element; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import edu.mit.spacenet.domain.ClassOfSupply; import edu.mit.spacenet.domain.element.PropulsiveVehicle; import edu.mit.spacenet.domain.element.ResourceTank; import edu.mit.spacenet.domain.resource.GenericResource; import edu.mit.spacenet.domain.resource.I_Resource; import edu.mit.spacenet.gui.SpaceNetFrame; import edu.mit.spacenet.gui.component.UnitsWrapper; import edu.mit.spacenet.gui.renderer.ResourceListCellRenderer; import edu.mit.spacenet.util.GlobalParameters; /** * The element panel for viewing and editing propulsive vehicle-specific inputs. * * @author Paul Grogan, ptgrogan@mit.edu * @author Ivo Ferreira */ public class PropulsiveVehiclePanel extends AbstractElementPanel { private static final long serialVersionUID = 6335483106289763369L; private PropulsiveVehicle vehicle; private JCheckBox omsCheck, rcsCheck, sharedCheck; private SpinnerNumberModel omsIspModel, maxOmsFuelModel, omsFuelModel, rcsIspModel, maxRcsFuelModel, rcsFuelModel; private JSpinner omsIspSpinner, maxOmsFuelSpinner, omsFuelSpinner, rcsIspSpinner, maxRcsFuelSpinner, rcsFuelSpinner; private UnitsWrapper maxOmsFuelWrapper, omsFuelWrapper, maxRcsFuelWrapper, rcsFuelWrapper; private JComboBox omsResourceCombo, rcsResourceCombo; /** * Instantiates a new propulsive vehicle panel. * * @param elementDialog the element dialog * @param vehicle the vehicle */ public PropulsiveVehiclePanel(ElementDialog elementDialog, PropulsiveVehicle vehicle) { super(elementDialog, vehicle); this.vehicle = vehicle; buildPanel(); initialize(); } private void buildPanel() { setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); JPanel omsPanel = new JPanel(); omsPanel.setLayout(new GridBagLayout()); omsPanel.setBorder(BorderFactory.createTitledBorder("OMS Engine")); add(omsPanel); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 1; c.weightx = 0; omsPanel.add(new JLabel("Isp: "), c); c.gridy++; omsPanel.add(new JLabel("Fuel Type: "), c); c.gridy++; omsPanel.add(new JLabel("Max Fuel: "), c); c.gridy++; if(getElementDialog().getDataSourceDialog()==null) omsPanel.add(new JLabel("Initial Fuel: "), c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.NONE; c.weightx = 1; omsCheck = new JCheckBox("OMS Capabilities"); omsPanel.add(omsCheck, c); c.gridy++; omsIspModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,0.1); omsIspSpinner = new JSpinner(omsIspModel); omsIspSpinner.setPreferredSize(new Dimension(50,20)); omsPanel.add(new UnitsWrapper(omsIspSpinner, "s"), c); omsIspSpinner.setToolTipText("Specific impulse of orbital maneuvering system [seconds]"); c.gridy++; omsResourceCombo = new JComboBox(); omsResourceCombo.setRenderer(new ResourceListCellRenderer()); omsResourceCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED && omsResourceCombo.getSelectedItem() != null && omsResourceCombo.getSelectedItem() instanceof I_Resource) { String fuelUnits = ((I_Resource)omsResourceCombo.getSelectedItem()).getUnits(); maxOmsFuelWrapper.setUnits(fuelUnits); omsFuelWrapper.setUnits(fuelUnits); } } }); omsPanel.add(omsResourceCombo, c); c.gridy++; maxOmsFuelModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,GlobalParameters.getMassPrecision()); maxOmsFuelSpinner = new JSpinner(maxOmsFuelModel); maxOmsFuelSpinner.setPreferredSize(new Dimension(150,20)); maxOmsFuelSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { omsFuelSpinner.setValue(maxOmsFuelSpinner.getValue()); } }); maxOmsFuelWrapper = new UnitsWrapper(maxOmsFuelSpinner, ""); omsPanel.add(maxOmsFuelWrapper, c); maxOmsFuelSpinner.setToolTipText("Maximum amount of orbital maneuvering system fuel"); c.gridy++; omsFuelModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,GlobalParameters.getMassPrecision()); omsFuelSpinner = new JSpinner(omsFuelModel); omsFuelSpinner.setPreferredSize(new Dimension(150,20)); omsFuelWrapper = new UnitsWrapper(omsFuelSpinner, ""); if(getElementDialog().getDataSourceDialog()==null) omsPanel.add(omsFuelWrapper, c); omsFuelSpinner.setToolTipText("Initial amount of orbital maneuvering system fuel"); JPanel rcsPanel = new JPanel(); rcsPanel.setLayout(new GridBagLayout()); rcsPanel.setBorder(BorderFactory.createTitledBorder("RCS Engine")); add(rcsPanel); c = new GridBagConstraints(); c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.LINE_END; c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 1; c.weightx = 0; rcsPanel.add(new JLabel("Isp: "), c); c.gridy+=2; rcsPanel.add(new JLabel("Fuel Type: "), c); c.gridy++; rcsPanel.add(new JLabel("Max Fuel: "), c); c.gridy++; if(getElementDialog().getDataSourceDialog()==null) rcsPanel.add(new JLabel("Initial Fuel: "), c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.NONE; c.weightx = 1; rcsCheck = new JCheckBox("RCS Capabilities"); rcsPanel.add(rcsCheck, c); c.gridy++; rcsIspModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,0.1); rcsIspSpinner = new JSpinner(rcsIspModel); rcsIspSpinner.setPreferredSize(new Dimension(50,20)); rcsPanel.add(new UnitsWrapper(rcsIspSpinner, "s"), c); rcsIspSpinner.setToolTipText("Specific impulse of reaction control system [seconds]"); c.gridy++; sharedCheck = new JCheckBox("Shared OMS Fuel Tank"); sharedCheck.setOpaque(false); rcsPanel.add(sharedCheck, c); sharedCheck.setToolTipText("Share fuel between the orbital maneuvering and reaction control systems"); c.gridy++; rcsResourceCombo = new JComboBox(); rcsResourceCombo.setRenderer(new ResourceListCellRenderer()); rcsResourceCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED && rcsResourceCombo.getSelectedItem() != null && rcsResourceCombo.getSelectedItem() instanceof I_Resource) { String fuelUnits = ((I_Resource)rcsResourceCombo.getSelectedItem()).getUnits(); maxRcsFuelWrapper.setUnits(fuelUnits); rcsFuelWrapper.setUnits(fuelUnits); } } }); rcsPanel.add(rcsResourceCombo, c); c.gridy++; maxRcsFuelModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,GlobalParameters.getMassPrecision()); maxRcsFuelSpinner = new JSpinner(maxRcsFuelModel); maxRcsFuelSpinner.setPreferredSize(new Dimension(150,20)); maxRcsFuelSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { rcsFuelSpinner.setValue(maxRcsFuelSpinner.getValue()); } }); maxRcsFuelWrapper = new UnitsWrapper(maxRcsFuelSpinner, ""); rcsPanel.add(maxRcsFuelWrapper, c); maxRcsFuelSpinner.setToolTipText("Maximum amount of reaction control system fuel"); c.gridy++; rcsFuelModel = new SpinnerNumberModel(0,0,Double.MAX_VALUE,GlobalParameters.getMassPrecision()); rcsFuelSpinner = new JSpinner(rcsFuelModel); rcsFuelSpinner.setPreferredSize(new Dimension(150,20)); rcsFuelWrapper = new UnitsWrapper(rcsFuelSpinner, ""); if(getElementDialog().getDataSourceDialog()==null) rcsPanel.add(rcsFuelWrapper, c); rcsFuelSpinner.setToolTipText("Initial amount of reaction control system fuel"); } /** * Initializes the panel components for a new propulsive vehicle. */ private void initialize() { omsResourceCombo.addItem(null); rcsResourceCombo.addItem(null); for(I_Resource r : SpaceNetFrame.getInstance().getScenarioPanel().getScenario().getDataSource().getResourceLibrary()) { if(r.getClassOfSupply().equals(ClassOfSupply.COS1) || r.getClassOfSupply().isSubclassOf(ClassOfSupply.COS1)) { omsResourceCombo.addItem(r); rcsResourceCombo.addItem(r); } } for(ClassOfSupply cos : ClassOfSupply.values()) { if(cos.equals(ClassOfSupply.COS1) || cos.isSubclassOf(ClassOfSupply.COS1)) { omsResourceCombo.addItem(new GenericResource(cos)); rcsResourceCombo.addItem(new GenericResource(cos)); } } if(vehicle.getOmsIsp() > 0) omsCheck.setSelected(true); else omsCheck.setSelected(false); if(vehicle.getRcsIsp() > 0) rcsCheck.setSelected(true); else rcsCheck.setSelected(false); if(vehicle.getOmsFuelTank() == vehicle.getRcsFuelTank()) sharedCheck.setSelected(true); else sharedCheck.setSelected(false); omsCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { repaint(); } }); rcsCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { repaint(); } }); sharedCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { repaint(); } }); if(omsCheck.isSelected()) { omsIspModel.setValue(vehicle.getOmsIsp()); if(vehicle.getOmsFuelTank() != null) { maxOmsFuelModel.setValue(vehicle.getOmsFuelTank().getMaxAmount()); omsFuelModel.setValue(vehicle.getOmsFuelTank().getAmount()); omsResourceCombo.setSelectedItem(vehicle.getOmsFuelTank().getResource()); } } if(rcsCheck.isSelected() && sharedCheck.isSelected()) { rcsIspModel.setValue(vehicle.getRcsIsp()); } else if(rcsCheck.isSelected()) { rcsIspModel.setValue(vehicle.getRcsIsp()); if(vehicle.getRcsFuelTank() != null) { maxRcsFuelModel.setValue(vehicle.getRcsFuelTank().getMaxAmount()); rcsFuelModel.setValue(vehicle.getRcsFuelTank().getAmount()); rcsResourceCombo.setSelectedItem(vehicle.getRcsFuelTank().getResource()); } } repaint(); } /* (non-Javadoc) * @see javax.swing.JComponent#paint(java.awt.Graphics) */ public void paint(Graphics g) { super.paint(g); if(omsCheck.isSelected()) { omsIspSpinner.setEnabled(true); maxOmsFuelSpinner.setEnabled(true); omsFuelSpinner.setEnabled(true); omsResourceCombo.setEnabled(true); } else { omsIspModel.setValue(0); omsIspSpinner.setEnabled(false); maxOmsFuelModel.setValue(0); maxOmsFuelSpinner.setEnabled(false); omsFuelModel.setValue(0); omsFuelSpinner.setEnabled(false); omsResourceCombo.setSelectedItem(null); omsResourceCombo.setEnabled(false); } if(rcsCheck.isSelected() && sharedCheck.isSelected()) { rcsIspSpinner.setEnabled(true); sharedCheck.setEnabled(true); maxRcsFuelModel.setValue(0); maxRcsFuelSpinner.setEnabled(false); rcsFuelModel.setValue(0); rcsFuelSpinner.setEnabled(false); rcsResourceCombo.setSelectedItem(null); rcsResourceCombo.setEnabled(false); } else if(rcsCheck.isSelected()) { rcsIspSpinner.setEnabled(true); sharedCheck.setEnabled(true); maxRcsFuelSpinner.setEnabled(true); rcsFuelSpinner.setEnabled(true); rcsResourceCombo.setEnabled(true); } else { sharedCheck.setSelected(false); sharedCheck.setEnabled(false); rcsIspModel.setValue(0); rcsIspSpinner.setEnabled(false); maxRcsFuelModel.setValue(0); maxRcsFuelSpinner.setEnabled(false); rcsFuelModel.setValue(0); rcsFuelSpinner.setEnabled(false); rcsResourceCombo.setSelectedItem(null); rcsResourceCombo.setEnabled(false); } } /* (non-Javadoc) * @see edu.mit.spacenet.gui.element.AbstractElementPanel#getElement() */ @Override public PropulsiveVehicle getElement() { return vehicle; } /* (non-Javadoc) * @see edu.mit.spacenet.gui.element.AbstractElementPanel#saveElement() */ @Override public void saveElement() { if(omsCheck.isSelected()) { vehicle.setOmsIsp(omsIspModel.getNumber().doubleValue()); ResourceTank omsFuelTank; if(vehicle.getOmsFuelTank()!=null) omsFuelTank = vehicle.getOmsFuelTank(); else { omsFuelTank = new ResourceTank(); vehicle.setOmsFuelTank(omsFuelTank); } omsFuelTank.setMaxAmount(maxOmsFuelModel.getNumber().doubleValue()); omsFuelTank.setAmount(Math.min(maxOmsFuelModel.getNumber().doubleValue(), omsFuelModel.getNumber().doubleValue())); omsFuelTank.setResource((I_Resource)omsResourceCombo.getSelectedItem()); } else { vehicle.setOmsIsp(0); vehicle.setOmsFuelTank(null); } if(rcsCheck.isSelected() && !sharedCheck.isSelected()) { vehicle.setRcsIsp(rcsIspModel.getNumber().doubleValue()); ResourceTank rcsFuelTank; if(vehicle.getRcsFuelTank()!=null) rcsFuelTank = vehicle.getRcsFuelTank(); else { rcsFuelTank = new ResourceTank(); vehicle.setRcsFuelTank(rcsFuelTank); } rcsFuelTank.setMaxAmount(maxRcsFuelModel.getNumber().doubleValue()); rcsFuelTank.setAmount(Math.min(maxRcsFuelModel.getNumber().doubleValue(), rcsFuelModel.getNumber().doubleValue())); rcsFuelTank.setResource((I_Resource)rcsResourceCombo.getSelectedItem()); } else if(rcsCheck.isSelected() && sharedCheck.isSelected()) { vehicle.setRcsIsp(rcsIspModel.getNumber().doubleValue()); vehicle.setRcsFuelTank(vehicle.getOmsFuelTank()); } else { vehicle.setRcsIsp(0); vehicle.setRcsFuelTank(null); } } /* (non-Javadoc) * @see edu.mit.spacenet.gui.element.AbstractElementPanel#isElementValid() */ @Override public boolean isElementValid() { if((maxOmsFuelModel.getNumber().doubleValue() > 0 || omsFuelModel.getNumber().doubleValue() > 0) && omsResourceCombo.getSelectedItem()==null) return false; if((maxRcsFuelModel.getNumber().doubleValue() > 0 || rcsFuelModel.getNumber().doubleValue() > 0) && rcsResourceCombo.getSelectedItem()==null) return false; return true; } /* (non-Javadoc) * @see edu.mit.spacenet.gui.element.AbstractElementPanel#isVerticallyExpandable() */ public boolean isVerticallyExpandable() { return false; } }
{ "content_hash": "126dd6ae76c50ee1fa9ed3c7a311c9fb", "timestamp": "", "source": "github", "line_count": 414, "max_line_length": 121, "avg_line_length": 35.08454106280193, "alnum_prop": 0.7435456110154905, "repo_name": "ptgrogan/spacenet", "id": "fc71fad301c626fcccb45fcd6735adc567091754", "size": "15149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/mit/spacenet/gui/element/PropulsiveVehiclePanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1909744" } ], "symlink_target": "" }
class FailJob < ActiveJob::Base include ActiveJob::Locking::Unique self.lock_acquire_time = 2 # We want the job ids to be all the same for testing def lock_key(index, sleep_time) self.class.name end # Pass in index so we can distinguish different jobs def perform(index, sleep_time) raise(ArgumentError, 'Job failed') end end
{ "content_hash": "f9bfe6042cdb1c605e4c8c9f4c97ac6f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 54, "avg_line_length": 23.466666666666665, "alnum_prop": 0.7159090909090909, "repo_name": "cfis/activejob-locking", "id": "140285d5dd5dc171aed0ecd64c89ea345518d9c4", "size": "352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/jobs/fail_job.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21384" } ], "symlink_target": "" }
 using EliteDangerousCore; using EliteDangerousCore.EDSM; using System; using System.Collections.Generic; using System.Windows.Forms; namespace EDDiscovery.UserControls.Search { public class DataGridViewStarResults : DataGridView { public bool CheckEDSM { get; set; } public Action<HistoryEntry> GotoEntryClicked = null; private EDDiscoveryForm discoveryform; public DataGridViewStarResults() { ContextMenuStrip cms = new ContextMenuStrip(); ContextMenuStrip = cms; cms.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { new System.Windows.Forms.ToolStripMenuItem(), new System.Windows.Forms.ToolStripMenuItem(), new System.Windows.Forms.ToolStripMenuItem(), new System.Windows.Forms.ToolStripMenuItem() }); cms.Name = "historyContextMenu"; cms.Size = new System.Drawing.Size(187, 70); cms.Items[0].Size = new System.Drawing.Size(186, 22); cms.Items[0].Text = "Go to star on 3D Map"; cms.Items[0].Name = "3d"; cms.Items[0].Click += new System.EventHandler(this.mapGotoStartoolStripMenuItem_Click); cms.Items[1].Size = new System.Drawing.Size(186, 22); cms.Items[1].Text = "View on EDSM"; cms.Items[1].Name = "EDSM"; cms.Items[1].Click += new System.EventHandler(this.viewOnEDSMToolStripMenuItem_Click); cms.Items[2].Size = new System.Drawing.Size(186, 22); cms.Items[2].Text = "View Data On Entry"; cms.Items[2].Name = "Data"; cms.Items[2].Click += new System.EventHandler(this.viewScanOfSystemToolStripMenuItem_Click); cms.Items[3].Text = "Go to entry on grid"; cms.Items[3].Name = "Data"; cms.Items[3].Click += new System.EventHandler(this.GotoEntryToolStripMenuItem_Click); CellDoubleClick += cellDoubleClick; MouseDown += mouseDown; BaseUtils.Translator.Instance.Translate(cms, this); } public void Init(EDDiscoveryForm frm) { discoveryform = frm; } Object rightclicktag = null; int rightclickrow = -1; private void mouseDown(object sender, MouseEventArgs e) { this.HandleClickOnDataGrid(e, out int unusedleftclickrow, out rightclickrow); rightclicktag = (rightclickrow != -1) ? Rows[rightclickrow].Tag : null; ContextMenuStrip.Items[3].Enabled = rightclicktag is HistoryEntry; } private ISystem SysFrom(Object t) // given tag, find the isystem { if (t is HistoryEntry) return ((HistoryEntry)t).System; else return (ISystem)t; } private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e) { if (rightclicktag != null) { this.Cursor = Cursors.WaitCursor; EDSMClass edsm = new EDSMClass(); long? id_edsm = SysFrom(rightclicktag).EDSMID; if (id_edsm == 0) { id_edsm = null; } if (!edsm.ShowSystemInEDSM(SysFrom(rightclicktag).Name, id_edsm)) ExtendedControls.MessageBoxTheme.Show(FindForm(), "System could not be found - has not been synched or EDSM is unavailable"); this.Cursor = Cursors.Default; } } private void mapGotoStartoolStripMenuItem_Click(object sender, EventArgs e) { if (rightclicktag != null) { this.Cursor = Cursors.WaitCursor; if (!discoveryform.Map.Is3DMapsRunning) // if not running, click the 3dmap button discoveryform.Open3DMap(null); this.Cursor = Cursors.Default; if (discoveryform.Map.Is3DMapsRunning) // double check here! for paranoia. { if (discoveryform.Map.MoveToSystem(SysFrom(rightclicktag))) discoveryform.Map.Show(); } } } private void GotoEntryToolStripMenuItem_Click(object sender, EventArgs e) { if (rightclicktag != null) { GotoEntryClicked?.Invoke(rightclicktag as HistoryEntry); } } private void viewScanOfSystemToolStripMenuItem_Click(object sender, EventArgs e) { ShowScanPopOut(rightclicktag); } private void cellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) ShowScanPopOut(Rows[e.RowIndex].Tag); } void ShowScanPopOut(Object tag) // tag can be a Isystem or an He.. output depends on it. { ScanDisplayForm.ShowScanOrMarketForm(this.FindForm(), tag, CheckEDSM, discoveryform.history); } public void Excel(int columnsout) { if (Rows.Count == 0) { ExtendedControls.MessageBoxTheme.Show(FindForm(), "No data to export", "Export EDSM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "Export Current View" }, disablestartendtime: true); if (frm.ShowDialog(FindForm()) == DialogResult.OK) { if (frm.SelectedIndex == 0) { BaseUtils.CSVWriteGrid grd = new BaseUtils.CSVWriteGrid(); grd.SetCSVDelimiter(frm.Comma); grd.GetLineStatus += delegate (int r) { if (r < Rows.Count) { return BaseUtils.CSVWriteGrid.LineStatus.OK; } else return BaseUtils.CSVWriteGrid.LineStatus.EOF; }; List<string> colh = new List<string>(); for (int i = 0; i < columnsout; i++) colh.Add(Columns[i].HeaderText); colh.AddRange(new string[] { "X", "Y", "Z", "ID" }); grd.GetHeader += delegate (int c) { return (c < colh.Count && frm.IncludeHeader) ? colh[c] : null; }; grd.GetLine += delegate (int r) { DataGridViewRow rw = Rows[r]; ISystem sys = SysFrom(rw.Tag); List<Object> data = new List<object>(); for (int i = 0; i < columnsout; i++) data.Add(rw.Cells[i].Value); data.Add(sys.X.ToString("0.#")); data.Add(sys.Y.ToString("0.#")); data.Add(sys.Z.ToString("0.#")); data.Add(sys.EDSMID); return data.ToArray(); }; grd.WriteGrid(frm.Path, frm.AutoOpen, FindForm()); } } } } }
{ "content_hash": "020a20346d6ca18db4085f5932f14f5c", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 152, "avg_line_length": 36.38423645320197, "alnum_prop": 0.5231519090170593, "repo_name": "klightspeed/EDDiscovery", "id": "007347dde2f362dc0859c02a56d6aa55422d83d7", "size": "8067", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EDDiscovery/UserControls/Helpers/DataGridViewStarResults.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "613" }, { "name": "C#", "bytes": "2305551" }, { "name": "CSS", "bytes": "7520" }, { "name": "HTML", "bytes": "32790" }, { "name": "Inno Setup", "bytes": "4038" }, { "name": "JavaScript", "bytes": "32299" }, { "name": "Rich Text Format", "bytes": "63135" } ], "symlink_target": "" }
@interface UIFont (SigmarOne) + (instancetype)sigmarOneFontOfSize:(CGFloat)size; @end
{ "content_hash": "f45096f2f219b889e1d57dd443614499", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 50, "avg_line_length": 14.833333333333334, "alnum_prop": 0.7752808988764045, "repo_name": "parakeety/GoogleFontsiOS", "id": "30715cbb305071539c1810c057dad7cda4071e7e", "size": "113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pod/Classes/sigmarone/UIFont+SigmarOne.h", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "556602" }, { "name": "Objective-C", "bytes": "700172" }, { "name": "Ruby", "bytes": "185508" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Common.Core; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; namespace Microsoft.UnitTests.Core.XUnit { internal sealed class AssemblyRunner : XunitTestAssemblyRunner { private readonly XunitTestEnvironment _testEnvironment; private IReadOnlyDictionary<Type, object> _assemblyFixtureMappings; private IList<AssemblyLoaderAttribute> _assemblyLoaders; public AssemblyRunner(ITestAssembly testAssembly, IEnumerable<IXunitTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions, XunitTestEnvironment testEnvironment) : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions) { _testEnvironment = testEnvironment; } protected override async Task AfterTestAssemblyStartingAsync() { await base.AfterTestAssemblyStartingAsync(); _assemblyLoaders = AssemblyLoaderAttribute.GetAssemblyLoaders(TestAssembly.Assembly); foreach (var assemblyLoader in _assemblyLoaders) { assemblyLoader.Initialize(); } var assembly = TestAssembly.Assembly; var importedAssemblyFixtureTypes = assembly.GetCustomAttributes(typeof(AssemblyFixtureImportAttribute)) .SelectMany(ai => ai.GetConstructorArguments()) .OfType<Type[]>() .SelectMany(a => a); var assemblyFixtureTypes = assembly.GetTypes(false) .Where(t => t.GetCustomAttributes(typeof(AssemblyFixtureAttribute).AssemblyQualifiedName).Any()) .Select(t => t.ToRuntimeType()) .Concat(importedAssemblyFixtureTypes) .ToList(); var fixtures = new Dictionary<Type, object>(); foreach (var type in assemblyFixtureTypes) { await Aggregator.RunAsync(() => AddAssemblyFixtureAsync(fixtures, type)); } _assemblyFixtureMappings = new ReadOnlyDictionary<Type, object>(fixtures); } protected override async Task BeforeTestAssemblyFinishedAsync() { foreach (var asyncLifetime in _assemblyFixtureMappings.Values.OfType<IAsyncLifetime>()) { await Aggregator.RunAsync(asyncLifetime.DisposeAsync); } foreach (var disposable in _assemblyFixtureMappings.Values.OfType<IDisposable>()) { Aggregator.Run(disposable.Dispose); } foreach (var assemblyLoader in _assemblyLoaders) { assemblyLoader.Dispose(); } await base.BeforeTestAssemblyFinishedAsync(); } protected override Task<RunSummary> RunTestCollectionAsync(IMessageBus messageBus, ITestCollection testCollection, IEnumerable<IXunitTestCase> testCases, CancellationTokenSource cancellationTokenSource) { return new CollectionRunner(testCollection, testCases, DiagnosticMessageSink, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource, _assemblyFixtureMappings, _testEnvironment).RunAsync(); } private static async Task AddAssemblyFixtureAsync(IDictionary<Type, object> fixtures, Type fixtureType) { var fixture = Activator.CreateInstance(fixtureType); if (fixture is IAsyncLifetime asyncLifetime) { await asyncLifetime.InitializeAsync(); } if (typeof(ITestMainThreadFixture).IsAssignableFrom(fixtureType)) { fixtures[typeof(ITestMainThreadFixture)] = fixture; } fixtures[fixtureType] = fixture; var methodFixtureTypes = MethodFixtureProvider.GetFactoryMethods(fixtureType).Select(mi => mi.ReturnType); foreach (var type in methodFixtureTypes) { fixtures[type] = fixture; } } private static bool IsGenericType(Type t) => t.GetTypeInfo().IsGenericType; } }
{ "content_hash": "70eacea6f154ff02bb3a55fbbb901d88", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 254, "avg_line_length": 46.02105263157895, "alnum_prop": 0.6898444647758463, "repo_name": "karthiknadig/RTVS", "id": "dd9f0e6acee42dff13701a3b7789a37f969f0708", "size": "4374", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/UnitTests/Core/Impl/XUnit/AssemblyRunner.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "189" }, { "name": "C", "bytes": "14326" }, { "name": "C#", "bytes": "8026482" }, { "name": "C++", "bytes": "31801" }, { "name": "CMake", "bytes": "1617" }, { "name": "CSS", "bytes": "4389" }, { "name": "HTML", "bytes": "8339" }, { "name": "M4", "bytes": "1854" }, { "name": "PLSQL", "bytes": "283" }, { "name": "PowerShell", "bytes": "729" }, { "name": "R", "bytes": "332447" }, { "name": "Rebol", "bytes": "436" }, { "name": "Roff", "bytes": "2612" }, { "name": "SQLPL", "bytes": "1116" }, { "name": "Shell", "bytes": "13837" }, { "name": "TypeScript", "bytes": "22792" }, { "name": "XSLT", "bytes": "421" } ], "symlink_target": "" }
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../../app/controllers/users'); // Setting up the users profile api app.route('/users/me').get(users.me); app.route('/users').put(users.update); app.route('/users/accounts').delete(users.removeOAuthProvider); // Setting up the users password api app.route('/users/password').post(users.changePassword); app.route('/auth/forgot').post(users.forgot); app.route('/auth/reset/:token').get(users.validateResetToken); app.route('/auth/reset/:token').post(users.reset); // Setting up the users authentication api app.route('/auth/signup').post(users.signup); app.route('/auth/signin').post(users.signin); app.route('/auth/signout').get(users.signout); // Setting the facebook oauth routes app.route('/auth/facebook').get(passport.authenticate('facebook', { scope: ['email'] })); app.route('/auth/facebook/callback').get(users.oauthCallback('facebook')); // Setting the twitter oauth routes app.route('/auth/twitter').get(passport.authenticate('twitter')); app.route('/auth/twitter/callback').get(users.oauthCallback('twitter')); // Setting the mapmyfitness oauth routes app.route('/auth/mapmyfitness').get(passport.authenticate('mapmyfitness')); app.route('/auth/mapmyfitness/callback').get(users.oauthCallback('mapmyfitness')); // Setting the runkeeper oauth routes app.route('/auth/runkeeper').get(passport.authenticate('runkeeper')); app.route('/auth/runkeeper/callback').get(users.oauthCallback('runkeeper')); // Setting the google oauth routes app.route('/auth/google').get(passport.authenticate('google', { scope: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] })); app.route('/auth/google/callback').get(users.oauthCallback('google')); // Setting the linkedin oauth routes app.route('/auth/linkedin').get(passport.authenticate('linkedin')); app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin')); // Setting the github oauth routes app.route('/auth/github').get(passport.authenticate('github')); app.route('/auth/github/callback').get(users.oauthCallback('github')); // Finish by binding the user middleware app.param('userId', users.userByID); };
{ "content_hash": "daa9911b807d8e80c6e802b0a3936bd8", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 83, "avg_line_length": 36.01538461538462, "alnum_prop": 0.7197778727039726, "repo_name": "chipjacks/runlab", "id": "0eec678f8694a6f91e093e7266e4e5fdcbe579fa", "size": "2341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/routes/users.server.routes.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1001" }, { "name": "JavaScript", "bytes": "108657" }, { "name": "Perl", "bytes": "48" }, { "name": "Shell", "bytes": "669" } ], "symlink_target": "" }
Django Annotations extended framework ```python # Now class Author: @djangotation.annotation(Count('book')) def book_count(self): return self.book_set.count() # Future class Author: book_count = djangotation.tations.count('book') book_count_book_count = djangotation.tations.sum('book_count', 'book_count') other_book_count = djangotation.tations.count('book', groups=['books']) # Author.objects.annotate_books() # Author.objects.annotate_group('books') # Author.objects.annotate_groups(['books']) # Uber Future class Book: page_count = djangotation.tations.count('page') class Author: page_count = djangotation.tations.count('book__page_count') # Might need to be with a custom F() class :/ @djangotation.annotation(Count('book__page_count')) def other_page_count(self): return operator.add(book.page_set.count() for book in author.book_set.all()) ```
{ "content_hash": "8238479e7da431c964e5daced3b20d27", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 84, "avg_line_length": 24.894736842105264, "alnum_prop": 0.6754756871035941, "repo_name": "CyboLabs/Djangotation", "id": "093fd9e1a2a93a2d26be58c8e0c073c22e507412", "size": "961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "10968" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Annls mycol. 29: 253 (1931) #### Original name Schiffnerula trachysperma Petr. ### Remarks null
{ "content_hash": "e53dbce8069cb902f647983da52f8817", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 12.23076923076923, "alnum_prop": 0.710691823899371, "repo_name": "mdoering/backbone", "id": "cd6eef13411cecb0165db34408d2f84253866cd3", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Englerulaceae/Schiffnerula/Schiffnerula trachysperma/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
1. Please speak English, this is the language everybody of us can speak and write. 2. Please ask questions or config/deploy problems on our pREST channel: https://gitter.im/nuveo/prest 3. Please take a moment to search that an issue doesn't already exist. 4. Please give all relevant information below for bug reports, incomplete details will be handled as an invalid report. **You MUST delete the content above including this line before posting, otherwise your issue will be invalid.** - pREST version (or commit ref): - pREST endpoint: - PostgreSQL version: - Operating system: - Go version: - Log gist: ## Description ...
{ "content_hash": "91517c20c7b30cdbcdb855366981a77f", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 119, "avg_line_length": 37.05882352941177, "alnum_prop": 0.7666666666666667, "repo_name": "henriquechehad/prest", "id": "026f7fde414fae4ad0ac95b148ca2916bde1cd30", "size": "630", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/issue_template.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "111407" }, { "name": "Makefile", "bytes": "1326" }, { "name": "Shell", "bytes": "2921" } ], "symlink_target": "" }
 #pragma once #include <aws/serverlessrepo/ServerlessApplicationRepository_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ServerlessApplicationRepository { namespace Model { /** * <p>A nested application summary.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/serverlessrepo-2017-09-08/ApplicationDependencySummary">AWS * API Reference</a></p> */ class AWS_SERVERLESSAPPLICATIONREPOSITORY_API ApplicationDependencySummary { public: ApplicationDependencySummary(); ApplicationDependencySummary(Aws::Utils::Json::JsonView jsonValue); ApplicationDependencySummary& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline const Aws::String& GetApplicationId() const{ return m_applicationId; } /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline bool ApplicationIdHasBeenSet() const { return m_applicationIdHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline void SetApplicationId(const Aws::String& value) { m_applicationIdHasBeenSet = true; m_applicationId = value; } /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline void SetApplicationId(Aws::String&& value) { m_applicationIdHasBeenSet = true; m_applicationId = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline void SetApplicationId(const char* value) { m_applicationIdHasBeenSet = true; m_applicationId.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline ApplicationDependencySummary& WithApplicationId(const Aws::String& value) { SetApplicationId(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline ApplicationDependencySummary& WithApplicationId(Aws::String&& value) { SetApplicationId(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the nested application.</p> */ inline ApplicationDependencySummary& WithApplicationId(const char* value) { SetApplicationId(value); return *this;} /** * <p>The semantic version of the nested application.</p> */ inline const Aws::String& GetSemanticVersion() const{ return m_semanticVersion; } /** * <p>The semantic version of the nested application.</p> */ inline bool SemanticVersionHasBeenSet() const { return m_semanticVersionHasBeenSet; } /** * <p>The semantic version of the nested application.</p> */ inline void SetSemanticVersion(const Aws::String& value) { m_semanticVersionHasBeenSet = true; m_semanticVersion = value; } /** * <p>The semantic version of the nested application.</p> */ inline void SetSemanticVersion(Aws::String&& value) { m_semanticVersionHasBeenSet = true; m_semanticVersion = std::move(value); } /** * <p>The semantic version of the nested application.</p> */ inline void SetSemanticVersion(const char* value) { m_semanticVersionHasBeenSet = true; m_semanticVersion.assign(value); } /** * <p>The semantic version of the nested application.</p> */ inline ApplicationDependencySummary& WithSemanticVersion(const Aws::String& value) { SetSemanticVersion(value); return *this;} /** * <p>The semantic version of the nested application.</p> */ inline ApplicationDependencySummary& WithSemanticVersion(Aws::String&& value) { SetSemanticVersion(std::move(value)); return *this;} /** * <p>The semantic version of the nested application.</p> */ inline ApplicationDependencySummary& WithSemanticVersion(const char* value) { SetSemanticVersion(value); return *this;} private: Aws::String m_applicationId; bool m_applicationIdHasBeenSet; Aws::String m_semanticVersion; bool m_semanticVersionHasBeenSet; }; } // namespace Model } // namespace ServerlessApplicationRepository } // namespace Aws
{ "content_hash": "8d02345a768bb062ec36af27980c6acd", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 136, "avg_line_length": 33.86046511627907, "alnum_prop": 0.69253663003663, "repo_name": "jt70471/aws-sdk-cpp", "id": "784a657d7e6ce2d858774f911916c03aed67cac4", "size": "4487", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-serverlessrepo/include/aws/serverlessrepo/model/ApplicationDependencySummary.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0 , hashGenesisBlock ) ( 422 , uint256("0x0000073440afdbc70401709f042a2ef9f2856904d0a8cd559204a61d3a284934") ) ( 22364 , uint256("0x000006e184a56f9e8acabe33eaf2734150d2ae50a33b259fde531b4f74efde18") ) ; // TestNet has no checkpoints static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, hashGenesisBlockTestNet ); bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } // ppcoin: synchronized checkpoint (centrally broadcasted) uint256 hashSyncCheckpoint = 0; uint256 hashPendingCheckpoint = 0; CSyncCheckpoint checkpointMessage; CSyncCheckpoint checkpointMessagePending; uint256 hashInvalidCheckpoint = 0; CCriticalSection cs_hashSyncCheckpoint; // ppcoin: get last synchronized checkpoint CBlockIndex* GetLastSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); if (!mapBlockIndex.count(hashSyncCheckpoint)) error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str()); else return mapBlockIndex[hashSyncCheckpoint]; return NULL; } // ppcoin: only descendant of current sync-checkpoint is allowed bool ValidateSyncCheckpoint(uint256 hashCheckpoint) { if (!mapBlockIndex.count(hashSyncCheckpoint)) return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str()); if (!mapBlockIndex.count(hashCheckpoint)) return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str()); CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint]; CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint]; if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight) { // Received an older checkpoint, trace back from current checkpoint // to the same height of the received checkpoint to verify // that current checkpoint should be a descendant block CBlockIndex* pindex = pindexSyncCheckpoint; while (pindex->nHeight > pindexCheckpointRecv->nHeight) if (!(pindex = pindex->pprev)) return error("ValidateSyncCheckpoint: pprev null - block index structure failure"); if (pindex->GetBlockHash() != hashCheckpoint) { hashInvalidCheckpoint = hashCheckpoint; return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str()); } return false; // ignore older checkpoint } // Received checkpoint should be a descendant block of the current // checkpoint. Trace back to the same height of current checkpoint // to verify. CBlockIndex* pindex = pindexCheckpointRecv; while (pindex->nHeight > pindexSyncCheckpoint->nHeight) if (!(pindex = pindex->pprev)) return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure"); if (pindex->GetBlockHash() != hashSyncCheckpoint) { hashInvalidCheckpoint = hashCheckpoint; return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str()); } return true; } bool WriteSyncCheckpoint(const uint256& hashCheckpoint) { CTxDB txdb; txdb.TxnBegin(); if (!txdb.WriteSyncCheckpoint(hashCheckpoint)) { txdb.TxnAbort(); return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str()); } if (!txdb.TxnCommit()) return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str()); Checkpoints::hashSyncCheckpoint = hashCheckpoint; return true; } bool AcceptPendingSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint)) { if (!ValidateSyncCheckpoint(hashPendingCheckpoint)) { hashPendingCheckpoint = 0; checkpointMessagePending.SetNull(); return false; } CTxDB txdb; CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint]; if (!pindexCheckpoint->IsInMainChain()) { CBlock block; if (!block.ReadFromDisk(pindexCheckpoint)) return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); if (!block.SetBestChain(txdb, pindexCheckpoint)) { hashInvalidCheckpoint = hashPendingCheckpoint; return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); } } if (!WriteSyncCheckpoint(hashPendingCheckpoint)) return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str()); hashPendingCheckpoint = 0; checkpointMessage = checkpointMessagePending; checkpointMessagePending.SetNull(); printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str()); // relay the checkpoint if (!checkpointMessage.IsNull()) { BOOST_FOREACH(CNode* pnode, vNodes) checkpointMessage.RelayTo(pnode); } return true; } return false; } // Automatically select a suitable sync-checkpoint uint256 AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight)) pindex = pindex->pprev; return pindex->GetBlockHash(); } // Check against synchronized checkpoint bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev) { if (fTestNet) return true; // Testnet has no checkpoints int nHeight = pindexPrev->nHeight + 1; LOCK(cs_hashSyncCheckpoint); // sync-checkpoint should always be accepted block assert(mapBlockIndex.count(hashSyncCheckpoint)); const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint]; if (nHeight > pindexSync->nHeight) { // trace back to same height as sync-checkpoint const CBlockIndex* pindex = pindexPrev; while (pindex->nHeight > pindexSync->nHeight) if (!(pindex = pindex->pprev)) return error("CheckSync: pprev null - block index structure failure"); if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint) return false; // only descendant of sync-checkpoint can pass check } if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint) return false; // same height with sync-checkpoint if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock)) return false; // lower height than sync-checkpoint return true; } bool WantedByPendingSyncCheckpoint(uint256 hashBlock) { LOCK(cs_hashSyncCheckpoint); if (hashPendingCheckpoint == 0) return false; if (hashBlock == hashPendingCheckpoint) return true; if (mapOrphanBlocks.count(hashPendingCheckpoint) && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint])) return true; return false; } // ppcoin: reset synchronized checkpoint to last hardened checkpoint bool ResetSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); const uint256& hash = mapCheckpoints.rbegin()->second; if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain()) { // checkpoint block accepted but not yet in main chain printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str()); CTxDB txdb; CBlock block; if (!block.ReadFromDisk(mapBlockIndex[hash])) return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str()); if (!block.SetBestChain(txdb, mapBlockIndex[hash])) { return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str()); } } else if(!mapBlockIndex.count(hash)) { // checkpoint block not yet accepted hashPendingCheckpoint = hash; checkpointMessagePending.SetNull(); printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str()); } BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain()) { if (!WriteSyncCheckpoint(hash)) return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str()); printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str()); return true; } } return false; } void AskForPendingSyncCheckpoint(CNode* pfrom) { LOCK(cs_hashSyncCheckpoint); if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint))) pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint)); } bool SetCheckpointPrivKey(std::string strPrivKey) { // Test signing a sync-checkpoint with genesis block CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey); CKey key; key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return false; // Test signing successful, proceed CSyncCheckpoint::strMasterPrivKey = strPrivKey; return true; } bool SendSyncCheckpoint(uint256 hashCheckpoint) { CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = hashCheckpoint; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); if (CSyncCheckpoint::strMasterPrivKey.empty()) return error("SendSyncCheckpoint: Checkpoint master key unavailable."); std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey); CKey key; key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?"); if(!checkpoint.ProcessSyncCheckpoint(NULL)) { printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n"); return false; } // Relay checkpoint { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } return true; } // Is the sync-checkpoint outside maturity window? bool IsMatureSyncCheckpoint() { LOCK(cs_hashSyncCheckpoint); // sync-checkpoint should always be accepted block assert(mapBlockIndex.count(hashSyncCheckpoint)); const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint]; return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity || pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime()); } } // ppcoin: sync-checkpoint master key const std::string CSyncCheckpoint::strMasterPubKey = "049F2C10997604217E7238A4C5CF2843570ADA001D1A247B228A7C5583ACD0F762A3130D0C4331EB262E3D0EB516AE6F7B0B1ADA43275013F8552A83A7C621B1D9"; std::string CSyncCheckpoint::strMasterPrivKey = ""; // ppcoin: verify signature of sync-checkpoint message bool CSyncCheckpoint::CheckSignature() { CKey key; if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey))) return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CSyncCheckpoint::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedSyncCheckpoint*)this; return true; } // ppcoin: process synchronized checkpoint bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom) { if (!CheckSignature()) return false; LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!mapBlockIndex.count(hashCheckpoint)) { // We haven't received the checkpoint chain, keep the checkpoint as pending Checkpoints::hashPendingCheckpoint = hashCheckpoint; Checkpoints::checkpointMessagePending = *this; printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str()); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, hashCheckpoint); // ask directly as well in case rejected earlier by duplicate // proof-of-stake because getblocks may not get it this time pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint)); } return false; } if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint)) return false; CTxDB txdb; CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint]; if (!pindexCheckpoint->IsInMainChain()) { // checkpoint chain received but not yet main chain CBlock block; if (!block.ReadFromDisk(pindexCheckpoint)) return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str()); if (!block.SetBestChain(txdb, pindexCheckpoint)) { Checkpoints::hashInvalidCheckpoint = hashCheckpoint; return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str()); } } if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint)) return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str()); Checkpoints::checkpointMessage = *this; Checkpoints::hashPendingCheckpoint = 0; Checkpoints::checkpointMessagePending.SetNull(); printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str()); return true; }
{ "content_hash": "ee83fde8637dd917dd7c9f5227712baf", "timestamp": "", "source": "github", "line_count": 406, "max_line_length": 200, "avg_line_length": 43.37684729064039, "alnum_prop": 0.6541366191584805, "repo_name": "DustCoinProject/DustCoin", "id": "5c9e58d454c52c2ffdaf6b9275133fe70d03632a", "size": "17978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/checkpoints.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "750142" }, { "name": "C++", "bytes": "2717375" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "11965" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3536" }, { "name": "Python", "bytes": "2819" }, { "name": "QMake", "bytes": "15014" }, { "name": "Shell", "bytes": "8201" } ], "symlink_target": "" }
// https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js /** * MicroEvent - to make any js object an event emitter (server or browser) * * - pure javascript - server compatible, browser compatible * - dont rely on the browser doms * - super simple - you get it immediatly, no mistery, no magic involved * * - create a MicroEventDebug with goodies to debug * - make it safer to use */ var MicroEvent = function(){}; MicroEvent.prototype = { bind : function(event, fct){ this._events = this._events || {}; this._events[event] = this._events[event] || []; this._events[event].push(fct); }, unbind : function(event, fct){ this._events = this._events || {}; if( event in this._events === false ) return; this._events[event].splice(this._events[event].indexOf(fct), 1); }, trigger : function(event /* , args... */){ this._events = this._events || {}; if( event in this._events === false ) return; for(var i = 0; i < this._events[event].length; i++){ this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); } } }; /** * mixin will delegate all MicroEvent.js function in the destination object * * - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent * * @param {Object} the object which will support MicroEvent */ MicroEvent.mixin = function(destObject){ var props = ['bind', 'unbind', 'trigger']; for(var i = 0; i < props.length; i ++){ if( typeof destObject === 'function' ){ destObject.prototype[props[i]] = MicroEvent.prototype[props[i]]; }else{ destObject[props[i]] = MicroEvent.prototype[props[i]]; } } return destObject; } // export in common js if( typeof module !== "undefined" && ('exports' in module)){ module.exports = MicroEvent; }
{ "content_hash": "3c224cf5ceec79cf17e836fb4812e46e", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 83, "avg_line_length": 32.03508771929825, "alnum_prop": 0.6423877327491785, "repo_name": "qiu-deqing/snippet", "id": "c601413db378066108ad72242f27e5ed1293bed6", "size": "1826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/microevent.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5882" }, { "name": "JavaScript", "bytes": "29512" } ], "symlink_target": "" }
package client.app.configuration.usergroups.gui.def; import share.core.constants.Constants; import client.core.gui.components.ExtendedTable; public class GUISearchUserGroups { public static final String PATH = Constants.GUI_BASE_PATH + "configuration/usergroups/gui/xml/search_user_groups"; public enum Literals { LIST_PDF } public ExtendedTable list = null; }
{ "content_hash": "073f51d83bb094bb42b75275d78bcfdb", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 115, "avg_line_length": 24.25, "alnum_prop": 0.7577319587628866, "repo_name": "vndly/saas", "id": "aefae5185b28d8a51f36da2dc4179d1d0ac38786", "size": "388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/client/app/configuration/usergroups/gui/def/GUISearchUserGroups.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "594322" } ], "symlink_target": "" }
package com.pedro.encoder.input.decoder; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaCodec; import android.media.MediaDataSource; import android.media.MediaExtractor; import android.media.MediaFormat; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import java.io.FileDescriptor; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; public abstract class BaseDecoder { protected String TAG = "BaseDecoder"; protected MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); protected MediaExtractor extractor; protected MediaCodec codec; protected volatile boolean running = false; protected MediaFormat mediaFormat; private HandlerThread handlerThread; protected String mime = ""; protected boolean loopMode = false; private volatile long startTs = 0; protected long duration; protected final Object sync = new Object(); private volatile long lastExtractorTs = 0; //Avoid decode while change output surface protected AtomicBoolean pause = new AtomicBoolean(false); public boolean initExtractor(String filePath) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(filePath); return extract(extractor); } public boolean initExtractor(FileDescriptor fileDescriptor) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(fileDescriptor); return extract(extractor); } @RequiresApi(api = Build.VERSION_CODES.N) public boolean initExtractor(AssetFileDescriptor assetFileDescriptor) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(assetFileDescriptor); return extract(extractor); } @RequiresApi(api = Build.VERSION_CODES.M) public boolean initExtractor(MediaDataSource mediaDataSource) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(mediaDataSource); return extract(extractor); } public boolean initExtractor(String filePath, Map<String, String> headers) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(filePath, headers); return extract(extractor); } public boolean initExtractor(FileDescriptor fileDescriptor, long offset, long length) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(fileDescriptor, offset, length); return extract(extractor); } public boolean initExtractor(Context context, Uri uri, Map<String, String> headers) throws IOException { extractor = new MediaExtractor(); extractor.setDataSource(context, uri, headers); return extract(extractor); } public void start() { Log.i(TAG, "start decoder"); running = true; handlerThread = new HandlerThread(TAG); handlerThread.start(); Handler handler = new Handler(handlerThread.getLooper()); codec.start(); handler.post(() -> { try { decode(); } catch (IllegalStateException e) { Log.i(TAG, "Decoding error", e); } catch (NullPointerException e) { Log.i(TAG, "Decoder maybe was stopped"); Log.i(TAG, "Decoding error", e); } }); } public void stop() { Log.i(TAG, "stop decoder"); running = false; stopDecoder(); lastExtractorTs = 0; startTs = 0; if (extractor != null) { extractor.release(); extractor = null; mime = ""; } } protected boolean prepare(Surface surface) { try { codec = MediaCodec.createDecoderByType(mime); codec.configure(mediaFormat, surface, null, 0); return true; } catch (IOException e) { Log.e(TAG, "Prepare decoder error:", e); return false; } } protected void resetCodec(Surface surface) { boolean wasRunning = running; stopDecoder(); prepare(surface); if (wasRunning) { start(); } } protected void stopDecoder() { running = false; if (handlerThread != null) { if (handlerThread.getLooper() != null) { if (handlerThread.getLooper().getThread() != null) { handlerThread.getLooper().getThread().interrupt(); } handlerThread.getLooper().quit(); } handlerThread.quit(); if (codec != null) { try { codec.flush(); } catch (IllegalStateException ignored) { } } //wait for thread to die for 500ms. try { handlerThread.getLooper().getThread().join(500); } catch (Exception ignored) { } handlerThread = null; } try { codec.stop(); codec.release(); codec = null; } catch (IllegalStateException | NullPointerException e) { codec = null; } } public void moveTo(double time) { synchronized (sync) { extractor.seekTo((long) (time * 10E5), MediaExtractor.SEEK_TO_CLOSEST_SYNC); lastExtractorTs = extractor.getSampleTime(); } } public void setLoopMode(boolean loopMode) { this.loopMode = loopMode; } public boolean isLoopMode() { return loopMode; } public double getDuration() { return duration / 10E5; } public double getTime() { if (running) { return extractor.getSampleTime() / 10E5; } else { return 0; } } protected abstract boolean extract(MediaExtractor extractor); protected abstract boolean decodeOutput(ByteBuffer outputBuffer); protected abstract void finished(); private void decode() { ByteBuffer[] inputBuffers = codec.getInputBuffers(); ByteBuffer[] outputBuffers = codec.getOutputBuffers(); startTs = System.nanoTime() / 1000; long sleepTime = 0; long accumulativeTs = 0; while (running) { synchronized (sync) { if (pause.get()) continue; int inIndex = codec.dequeueInputBuffer(10000); int sampleSize = 0; if (inIndex >= 0) { ByteBuffer buffer = inputBuffers[inIndex]; sampleSize = extractor.readSampleData(buffer, 0); long ts = System.nanoTime() / 1000 - startTs; long extractorTs = extractor.getSampleTime(); accumulativeTs += extractorTs - lastExtractorTs; lastExtractorTs = extractor.getSampleTime(); if (accumulativeTs > ts) sleepTime = accumulativeTs - ts; if (sampleSize < 0) { if (!loopMode) { codec.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM); } } else { codec.queueInputBuffer(inIndex, 0, sampleSize, ts + sleepTime, 0); extractor.advance(); } } int outIndex = codec.dequeueOutputBuffer(bufferInfo, 10000); if (outIndex >= 0) { if (!sleep(sleepTime / 1000)) return; boolean render = decodeOutput(outputBuffers[outIndex]); codec.releaseOutputBuffer(outIndex, render && bufferInfo.size != 0); } else if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0 || sampleSize < 0) { Log.i(TAG, "end of file"); if (loopMode) { moveTo(0); } else { finished(); break; } } } } } private boolean sleep(long sleepTime) { try { Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } }
{ "content_hash": "e54598cf784e1aa4657e95c4cb5bdc9d", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 102, "avg_line_length": 29.44015444015444, "alnum_prop": 0.6575737704918033, "repo_name": "pedroSG94/rtmp-rtsp-stream-client-java", "id": "856fcc938c5694b93dd5c2f12c8375c3925060aa", "size": "8218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "encoder/src/main/java/com/pedro/encoder/input/decoder/BaseDecoder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "40954" }, { "name": "Java", "bytes": "998594" }, { "name": "Kotlin", "bytes": "391012" } ], "symlink_target": "" }
SNOMED is distributed in multiple "modules". Each module makes a set of assertions about a collection of SNOMED CT concepts. SNOMED CT International is composed of two modules: * International Release, Core Module (900000000000207008) * SNOMED CT Model Component Module (900000000000012004) (aka. "Metadata module") While the SNOMED CT core module is dependent on parts of the SNOMED CT Model Component Module, normally only a small subset of the metadata module concepts are included in the OWL representation of the core module. The SNOMED CT US Edition (731000124108) includes both the International Core module and the Model Component module. It does, however, add some concepts, de-activate some descriptions, add some new ones, etc. ## International Release Core and Model Component imports The general notion is that the International Release, Core Module could use an ```owl:import``` to include the Model Component module if so desired -- the approach would be to generate both the SNOMED International Core module (using US English) and the SNOMED International Model Component module (using US and GB English...) ```bash > SNOMEDToOWL -o sct_core_us.ttl ~/data/terminology/SNOMEDCT/SnomedCT_RF2Release_INT_20160731/Snapshot sct_core_us.json > SNOMEDToOWL -o sct_metadata_us_gb.ttl ~/data/terminology/SNOMEDCT/SnomedCT_RF2Release_INT_20160731/Snapshot sct_metadata_us_gb.json ``` We could then load ```sct_core_us.ttl``` into Protege and note that the SNOMED CT Model Component (metadata) section has limited content -- only the concepts declared as members of the core module + their ancestors: ![Protege Image](images/sct_core_us.png) We can then import the Model Component Module: ![Protege Image](images/sct_core_import.png) which completely fills out the metadata section: ![Protege Image](images/sct_core_plus_metadata.png) Note that the SNOMED CT concept ```410662002 | Concept model attribute |``` and its descendants are represented as OWL ObjectProperties. Concept model attribute and its descendants are included in *every* module representation. All other descendants of ```106237007 | Linkage concept |``` are currently represented as OWL Classes and only in the Model Component module. ![Protege Image](images/sct_core_object_properties.png) ## US Edition and International Edition imports We could generate the inferred US Edition (using US english) and the inferred SNOMED CT Core: ```bash > SNOMEDToOWL -o us_edition_us_inferred.ttl ~/data/terminology/SNOMEDCT/SnomedCT_RF2Release_US1000124_20160301/Snapshot/ us_edition_us_inferred.json > SNOMEDToOWL -o sct_core_us_inferred.ttl ~/data/terminology/SNOMEDCT/SnomedCT_RF2Release_INT_20160731/Snapshot sct_core_us_inferred.json ``` When the US edition is loaded by itself, we only get what has been defined or changed plus all of the core concept references: ![Protege Image](images/us_edition_stand_alone.png) If we then import the SNOMED International Core: ![Protege Image](images/us_edition_core_import.png) Where we then find the additions properly positioned: ![Protege Image](images/us_edition_and_core.png) It is interesting to note that there are a number of concepts that aren't recognized: ![Protege Image](images/us_edition_unclassified.png) Some of these are references to SCT International Metadata -- the US edition is partly dependent on it. We can import the core metadata: ![Protege Image](images/us_edition_metadata_import.png) Which resolves some of the references: ![Protege Image](images/us_edition_including_metadata_1.png) The remainder, however, turn out to be retired concepts, which simply do not appear in the OWL representation. ```69960004 | Antineoplastic chemotherapy regimen (procedure) |```, ```185972007 | Patient on waiting list for op (finding) |```, and ```81877007 | Housing problems (finding) |``` are all retired. ![Protege Image](images/us_edition_including_metadata_2.png) It turns out that there are a couple of issues with this approach: 1. The US Edition is not "monotonic" -- it actually changes parts of the International release. As an example, it deactivates the FSN for concept ```407309009 | Escherichia coli, serotype Orough (organism) |``` and substitutes ```Escherichia coli serogroup Orough (organism)``` in its place. The import described above doesn't show this, as, by *importing* the International Release, we end up with two names. One possible solution to this would be to generate both the International and US Edition from the US RF2 release files. One would want to create a different ontology URI for the result, however, as the US "view" of SNOMED CT International is not the same as the international view. 2. The US edition sometimes changes descriptions for concepts. It changes the module identifier for the description itself, but it doesn't change the corresponding records in the Language refset. As an example the description entry below: ![Protege Image](images/us_edition_rf2_description.png) Has this entry in the language refset: ![Protege Image](images/us_edition_rf2_language.png)
{ "content_hash": "0f30ffc176230f7e309fcf4a69379b7d", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 695, "avg_line_length": 62.09756097560975, "alnum_prop": 0.7826001571091908, "repo_name": "hsolbrig/SNOMEDToOWL", "id": "fce5b1a894f3fedb50ff7728106ffd99f0b3a74f", "size": "5112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "77179" }, { "name": "Python", "bytes": "71893" }, { "name": "Shell", "bytes": "1625" } ], "symlink_target": "" }
package com.salton123.mengmei.model.bmob; import com.salton123.mengmei.model.bean.User; import java.util.List; import cn.bmob.v3.BmobObject; /** * User: 巫金生(newSalton@outlook.com) * Date: 2016/9/5 22:45 * Time: 22:45 * Description: */ public class VoiceEntity extends BmobObject { private int id; private int versionCode; private User userEntity; private String userId; private String website; private String title; private String describe; private String from; private String image_cover; private String voiceUrl ; private long createTime; private long updateTime; private List<String> tags; private List<String> favoriteUserIds; private List<String> imageList; public List<String> getFavoriteUserIds() { return favoriteUserIds; } public void setFavoriteUserIds(List<String> favoriteUserIds) { this.favoriteUserIds = favoriteUserIds; } public String getVoiceUrl() { return voiceUrl; } public void setVoiceUrl(String voiceUrl) { this.voiceUrl = voiceUrl; } public String getImage_cover() { return image_cover; } public void setImage_cover(String image_cover) { this.image_cover = image_cover; } public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } public List<String> getImageList() { return imageList; } public void setImageList(List<String> imageList) { this.imageList = imageList; } public User getUserEntity() { return userEntity; } public void setUserEntity(User userEntity) { this.userEntity = userEntity; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public long getUpdateTime() { return updateTime; } public void setUpdateTime(long updateTime) { this.updateTime = updateTime; } }
{ "content_hash": "b98c424ddf8b60cf9482cfa132f71e86", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 66, "avg_line_length": 20.973856209150327, "alnum_prop": 0.5923963851667186, "repo_name": "456838/usefulCode", "id": "e6b6aaac6b6f28c7185f1f5a6669f384fe81f2d0", "size": "3215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YHamburgGit/app/src/main/java/com/salton123/mengmei/model/bmob/VoiceEntity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6258" }, { "name": "HTML", "bytes": "245591" }, { "name": "Java", "bytes": "1498326" }, { "name": "Python", "bytes": "454881" }, { "name": "Shell", "bytes": "10632" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_72) on Wed May 13 11:47:42 EDT 2015 --> <title>Cassandra.insert_result._Fields (apache-cassandra API)</title> <meta name="date" content="2015-05-13"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Cassandra.insert_result._Fields (apache-cassandra API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Cassandra.insert_result._Fields.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.login_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" target="_top">Frames</a></li> <li><a href="Cassandra.insert_result._Fields.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.cassandra.thrift</div> <h2 title="Enum Cassandra.insert_result._Fields" class="title">Enum Cassandra.insert_result._Fields</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.lang.Enum&lt;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&gt;</li> <li> <ul class="inheritance"> <li>org.apache.cassandra.thrift.Cassandra.insert_result._Fields</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Comparable&lt;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&gt;, org.apache.thrift.TFieldIdEnum</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result.html" title="class in org.apache.cassandra.thrift">Cassandra.insert_result</a></dd> </dl> <hr> <br> <pre>public static enum <span class="strong">Cassandra.insert_result._Fields</span> extends java.lang.Enum&lt;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&gt; implements org.apache.thrift.TFieldIdEnum</pre> <div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_summary"> <!-- --> </a> <h3>Enum Constant Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation"> <caption><span>Enum Constants</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Enum Constant and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#IRE">IRE</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#TE">TE</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#UE">UE</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#findByName(java.lang.String)">findByName</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Find the _Fields constant that matches name, or null if its not found.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#findByThriftId(int)">findByThriftId</a></strong>(int&nbsp;fieldId)</code> <div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</a></strong>(int&nbsp;fieldId)</code> <div class="block">Find the _Fields constant that matches fieldId, throwing an exception if it is not found.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#getFieldName()">getFieldName</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>short</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#getThriftFieldId()">getThriftFieldId</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>[]</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html#values()">values</a></strong>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Enum</h3> <code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ENUM CONSTANT DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="enum_constant_detail"> <!-- --> </a> <h3>Enum Constant Detail</h3> <a name="IRE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IRE</h4> <pre>public static final&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a> IRE</pre> </li> </ul> <a name="UE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>UE</h4> <pre>public static final&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a> UE</pre> </li> </ul> <a name="TE"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>TE</h4> <pre>public static final&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a> TE</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="values()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>values</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>[]&nbsp;values()</pre> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: <pre> for (Cassandra.insert_result._Fields c : Cassandra.insert_result._Fields.values()) &nbsp; System.out.println(c); </pre></div> <dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl> </li> </ul> <a name="valueOf(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>valueOf</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&nbsp;valueOf(java.lang.String&nbsp;name)</pre> <div class="block">Returns the enum constant of this type with the specified name. The string must match <i>exactly</i> an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd> <dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd> <dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl> </li> </ul> <a name="findByThriftId(int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>findByThriftId</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&nbsp;findByThriftId(int&nbsp;fieldId)</pre> <div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div> </li> </ul> <a name="findByThriftIdOrThrow(int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>findByThriftIdOrThrow</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&nbsp;findByThriftIdOrThrow(int&nbsp;fieldId)</pre> <div class="block">Find the _Fields constant that matches fieldId, throwing an exception if it is not found.</div> </li> </ul> <a name="findByName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>findByName</h4> <pre>public static&nbsp;<a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.insert_result._Fields</a>&nbsp;findByName(java.lang.String&nbsp;name)</pre> <div class="block">Find the _Fields constant that matches name, or null if its not found.</div> </li> </ul> <a name="getThriftFieldId()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getThriftFieldId</h4> <pre>public&nbsp;short&nbsp;getThriftFieldId()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>getThriftFieldId</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TFieldIdEnum</code></dd> </dl> </li> </ul> <a name="getFieldName()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getFieldName</h4> <pre>public&nbsp;java.lang.String&nbsp;getFieldName()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>getFieldName</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TFieldIdEnum</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Cassandra.insert_result._Fields.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.insert_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.login_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html" target="_top">Frames</a></li> <li><a href="Cassandra.insert_result._Fields.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2015 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "ad6d31a0da5b93a2e2333f7b100d2395", "timestamp": "", "source": "github", "line_count": 422, "max_line_length": 257, "avg_line_length": 42.7345971563981, "alnum_prop": 0.6728956415659311, "repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet", "id": "9f8b65b070294af793c1edeaf5c41b59efc060a8", "size": "18034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apache-cassandra-2.0.15/javadoc/org/apache/cassandra/thrift/Cassandra.insert_result._Fields.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "59670" }, { "name": "PowerShell", "bytes": "37758" }, { "name": "Python", "bytes": "622552" }, { "name": "Shell", "bytes": "100474" }, { "name": "Thrift", "bytes": "78926" } ], "symlink_target": "" }
require_relative 'persistent_service.rb' require_relative 'non_persistent_service.rb'
{ "content_hash": "f2885d5ca06c148629f06dddf29631ae", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 44, "avg_line_length": 29, "alnum_prop": 0.8160919540229885, "repo_name": "EnginesOS/System", "id": "2cba25dfc25a4f0b6fae22ae5f6796698ca8051d", "size": "87", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/server/api/containers/service/service/routes.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "101320" }, { "name": "HTML", "bytes": "4478768" }, { "name": "JavaScript", "bytes": "72060" }, { "name": "Makefile", "bytes": "40933" }, { "name": "Ruby", "bytes": "844890" }, { "name": "Shell", "bytes": "118832" }, { "name": "TSQL", "bytes": "3205" } ], "symlink_target": "" }
package com.weygo.weygophone.pages.shopcart.model; import com.weygo.weygophone.pages.tabs.home.model.WGHomeFloorContentGoodItem; /** * Created by muma on 2017/8/18. */ public class WGShopCartGoodItem extends WGHomeFloorContentGoodItem { public Integer goodCount; public long shopCartId; }
{ "content_hash": "f7c86950c7ccd521600be5165c0ca6a3", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 77, "avg_line_length": 21.714285714285715, "alnum_prop": 0.7796052631578947, "repo_name": "mumabinggan/WeygoPhone", "id": "aa3103073a33ea82ac2df5cbff53a26ef7f17fae", "size": "304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/weygo/weygophone/pages/shopcart/model/WGShopCartGoodItem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1091817" } ], "symlink_target": "" }
class CreateProducts < ActiveRecord::Migration[5.0] def change create_table :products do |t| t.string :name t.string :location t.boolean :available t.timestamps end end end
{ "content_hash": "184bbbc572de1e8a009e43ae77b2c570", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 51, "avg_line_length": 19.09090909090909, "alnum_prop": 0.6476190476190476, "repo_name": "jeyavel-velankani/Jel_Apps", "id": "1bf2c16dec046470719a195ed7021ba9eaea38af", "size": "210", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JelAPIs/db/migrate/20161206054012_create_products.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1360" }, { "name": "CSS", "bytes": "237195" }, { "name": "CoffeeScript", "bytes": "17717" }, { "name": "Gherkin", "bytes": "126424" }, { "name": "HTML", "bytes": "913329" }, { "name": "JavaScript", "bytes": "624095" }, { "name": "Ruby", "bytes": "2672963" }, { "name": "Shell", "bytes": "1249" } ], "symlink_target": "" }
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ #include "org_haggle_Interface.h" #include "javaclass.h" #include <libhaggle/haggle.h> /* * Class: org_haggle_Interface * Method: nativeFree * Signature: ()V */ JNIEXPORT void JNICALL Java_org_haggle_Interface_nativeFree(JNIEnv *env, jobject obj) { haggle_interface_free((haggle_interface_t *)get_native_handle(env, JCLASS_INTERFACE, obj)); } /* * Class: org_haggle_Interface * Method: getType * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_haggle_Interface_getType(JNIEnv *env, jobject obj) { return haggle_interface_get_type((haggle_interface_t *)get_native_handle(env, JCLASS_INTERFACE, obj)); } /* * Class: org_haggle_Interface * Method: getStatus * Signature: ()I */ JNIEXPORT jint JNICALL Java_org_haggle_Interface_getStatus(JNIEnv *env, jobject obj) { return haggle_interface_get_status((haggle_interface_t *)get_native_handle(env, JCLASS_INTERFACE, obj)); } /* * Class: org_haggle_Interface * Method: getName * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_haggle_Interface_getName(JNIEnv *env, jobject obj) { return (*env)->NewStringUTF(env, haggle_interface_get_name((haggle_interface_t *)get_native_handle(env, JCLASS_INTERFACE, obj))); } /* * Class: org_haggle_Interface * Method: getIdentifierString * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_haggle_Interface_getIdentifierString(JNIEnv *env, jobject obj) { return (*env)->NewStringUTF(env, haggle_interface_get_identifier_str((haggle_interface_t *)get_native_handle(env, JCLASS_INTERFACE, obj))); }
{ "content_hash": "3f92d037335c90c9110b79b045683582", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 147, "avg_line_length": 30.25, "alnum_prop": 0.7001180637544274, "repo_name": "eebenson/haggle", "id": "ae2491b0158492e1826ad86fa70dd5e8016d6df8", "size": "1694", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/libhaggle/jni/native/org_haggle_Interface.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "293764" }, { "name": "Batchfile", "bytes": "77580" }, { "name": "C", "bytes": "24586143" }, { "name": "C#", "bytes": "212445" }, { "name": "C++", "bytes": "2229611" }, { "name": "DIGITAL Command Language", "bytes": "266280" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "Groff", "bytes": "9605" }, { "name": "HTML", "bytes": "1135" }, { "name": "Java", "bytes": "121512" }, { "name": "JavaScript", "bytes": "30528" }, { "name": "Logos", "bytes": "108920" }, { "name": "Makefile", "bytes": "729529" }, { "name": "Objective-C", "bytes": "23883" }, { "name": "Objective-C++", "bytes": "21203" }, { "name": "Perl", "bytes": "1745154" }, { "name": "Perl6", "bytes": "27602" }, { "name": "Prolog", "bytes": "29150" }, { "name": "Python", "bytes": "100993" }, { "name": "Rebol", "bytes": "106436" }, { "name": "Scheme", "bytes": "4249" }, { "name": "Shell", "bytes": "471702" }, { "name": "XS", "bytes": "4319" }, { "name": "XSLT", "bytes": "10468" }, { "name": "eC", "bytes": "4568" } ], "symlink_target": "" }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include <tuple> #include "v8-globals.h" #include "Basics/debugging.h" #include "Basics/StaticStrings.h" #include "Basics/system-functions.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" TRI_v8_global_t::TRI_v8_global_t( arangodb::application_features::ApplicationServer& server, arangodb::V8SecurityFeature& v8security, arangodb::HttpEndpointProvider& endpoints, arangodb::application_features::CommunicationFeaturePhase& comm, #ifdef USE_ENTERPRISE arangodb::EncryptionFeature& encryption, #endif v8::Isolate* isolate, size_t id) : AgencyTempl(), AgentTempl(), ClusterInfoTempl(), ServerStateTempl(), ClusterCommTempl(), ArangoErrorTempl(), VocbaseColTempl(), VocbaseViewTempl(), VocbaseReplicatedLogTempl(), VocbaseTempl(), EnvTempl(), UsersTempl(), GeneralGraphModuleTempl(), GeneralGraphTempl(), #ifdef USE_ENTERPRISE SmartGraphTempl(), #endif BufferTempl(), StreamQueryCursorTempl(), BufferConstant(), DeleteConstant(), GetConstant(), HeadConstant(), OptionsConstant(), PatchConstant(), PostConstant(), PutConstant(), AddressKey(), AllowDirtyReadsKey(), AllowUseDatabaseKey(), AuthorizedKey(), BodyFromFileKey(), BodyKey(), ClientKey(), CodeKey(), ContentTypeKey(), CoordTransactionIDKey(), DatabaseKey(), DomainKey(), EndpointKey(), ErrorKey(), ErrorMessageKey(), ErrorNumKey(), HeadersKey(), HttpOnlyKey(), IdKey(), IsAdminUser(), InitTimeoutKey(), IsRestoreKey(), IsSystemKey(), KeepNullKey(), KeyOptionsKey(), LengthKey(), LifeTimeKey(), MergeObjectsKey(), NameKey(), OperationIDKey(), OverwriteKey(), OverwriteModeKey(), SkipDocumentValidationKey(), ParametersKey(), PathKey(), PrefixKey(), PortKey(), PortTypeKey(), ProtocolKey(), RawSuffixKey(), RequestBodyKey(), RawRequestBodyKey(), RequestTypeKey(), ResponseCodeKey(), ReturnNewKey(), ReturnOldKey(), SecureKey(), ServerKey(), ShardIDKey(), SilentKey(), SingleRequestKey(), StatusKey(), SuffixKey(), TimeoutKey(), ToJsonKey(), TransformationsKey(), UrlKey(), UserKey(), ValueKey(), VersionKeyHidden(), WaitForSyncKey(), _DbCacheKey(), _DbNameKey(), _IdKey(), _KeyKey(), _RevKey(), _FromKey(), _ToKey(), _currentRequest(), _currentResponse(), _transactionContext(nullptr), _expressionContext(nullptr), _vocbase(nullptr), _activeExternals(0), _canceled(false), _securityContext( arangodb::JavaScriptSecurityContext::createRestrictedContext()), _inForcedCollect(false), _id(id), _lastMaxTime(TRI_microtime()), _countOfTimes(0), _heapMax(0), _heapLow(0), _server{server}, _v8security{v8security}, _endpoints{endpoints}, #ifdef USE_ENTERPRISE _encryption{encryption}, #endif _comm{comm} { v8::HandleScope scope(isolate); BufferConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "Buffer")); DeleteConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "DELETE")); GetConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "GET")); HeadConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "HEAD")); OptionsConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "OPTIONS")); PatchConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "PATCH")); PostConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "POST")); PutConstant.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "PUT")); AddressKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "address")); AllowDirtyReadsKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "allowDirtyReads")); AllowUseDatabaseKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "allowUseDatabase")); AuthorizedKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "authorized")); BodyFromFileKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "bodyFromFile")); BodyKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "body")); ClientKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "client")); CodeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "code")); ContentTypeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "contentType")); CookiesKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "cookies")); CoordTransactionIDKey.Reset( isolate, TRI_V8_ASCII_STRING(isolate, "coordTransactionID")); DatabaseKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "database")); DomainKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "domain")); EndpointKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "endpoint")); ErrorKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "error")); ErrorMessageKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "errorMessage")); ErrorNumKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "errorNum")); HeadersKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "headers")); HttpOnlyKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "httpOnly")); IdKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "id")); IsAdminUser.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "isAdminUser")); InitTimeoutKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "initTimeout")); IsRestoreKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "isRestore")); IsSynchronousReplicationKey.Reset( isolate, TRI_V8_ASCII_STRING(isolate, "isSynchronousReplication")); IsSystemKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "isSystem")); KeepNullKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "keepNull")); KeyOptionsKey.Reset( isolate, TRI_V8_ASCII_STD_STRING(isolate, arangodb::StaticStrings::KeyOptions)); LengthKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "length")); LifeTimeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "lifeTime")); MergeObjectsKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "mergeObjects")); NameKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "name")); OperationIDKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "operationID")); OverwriteKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "overwrite")); OverwriteModeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "overwriteMode")); SkipDocumentValidationKey.Reset( isolate, TRI_V8_ASCII_STRING(isolate, "skipDocumentValidation")); ParametersKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "parameters")); PathKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "path")); PrefixKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "prefix")); PortKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "port")); PortTypeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "portType")); ProtocolKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "protocol")); RawSuffixKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "rawSuffix")); RequestBodyKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "requestBody")); RawRequestBodyKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "rawRequestBody")); RequestTypeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "requestType")); ResponseCodeKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "responseCode")); ReturnNewKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "returnNew")); ReturnOldKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "returnOld")); SecureKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "secure")); ServerKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "server")); ShardIDKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "shardID")); SilentKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "silent")); SingleRequestKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "singleRequest")); StatusKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "status")); SuffixKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "suffix")); TimeoutKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "timeout")); ToJsonKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "toJSON")); TransformationsKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "transformations")); UrlKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "url")); UserKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "user")); ValueKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "value")); VersionKeyHidden.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "*version")); WaitForSyncKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "waitForSync")); CompactKey.Reset(isolate, TRI_V8_ASCII_STD_STRING( isolate, arangodb::StaticStrings::Compact)); _DbCacheKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "__dbcache__")); _DbNameKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_dbName")); _IdKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_id")); _KeyKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_key")); _RevKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_rev")); _FromKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_from")); _ToKey.Reset(isolate, TRI_V8_ASCII_STRING(isolate, "_to")); } TRI_v8_global_t::SharedPtrPersistent::SharedPtrPersistent( v8::Isolate& isolateRef, std::shared_ptr<void> const& value) : _isolate(isolateRef), _value(value) { auto* isolate = &isolateRef; TRI_GET_GLOBALS(); _persistent.Reset(isolate, v8::External::New(isolate, value.get())); _persistent.SetWeak( this, [](v8::WeakCallbackInfo<SharedPtrPersistent> const& data) -> void { // callback auto isolate = data.GetIsolate(); auto* persistent = data.GetParameter(); TRI_GET_GLOBALS(); auto* key = persistent->_value.get(); // same key as used in emplace(...) LOG_TOPIC("44ea7", TRACE, arangodb::Logger::V8) << "Weak UnWrapping ptr " << key << " Context ID: " << v8g->_id; auto count = v8g->JSSharedPtrs.erase(key); TRI_ASSERT(count) << "Did not find weak value the value for '" << key << "' in the registry! Context ID: " << v8g->_id; // zero indicates that v8g was probably deallocated // before calling the v8::WeakCallbackInfo::Callback }, v8::WeakCallbackType::kFinalizer); v8g->increaseActiveExternals(); } TRI_v8_global_t::SharedPtrPersistent::~SharedPtrPersistent() { auto* isolate = &_isolate; TRI_GET_GLOBALS(); v8g->decreaseActiveExternals(); // dispose and clear the persistent handle (SIGSEGV here may // indicate that v8::Isolate was already deallocated) _persistent.Reset(); } /*static*/ std::pair<TRI_v8_global_t::SharedPtrPersistent&, bool> TRI_v8_global_t::SharedPtrPersistent::emplace( v8::Isolate& isolateRef, std::shared_ptr<void> const& value) { auto* isolate = &isolateRef; TRI_GET_GLOBALS(); auto entry = v8g->JSSharedPtrs.try_emplace(value.get(), isolateRef, value); return std::pair<SharedPtrPersistent&, bool>(entry.first->second, entry.second); } TRI_v8_global_t::~TRI_v8_global_t() = default; /// @brief returns a global context TRI_v8_global_t* TRI_GetV8Globals(v8::Isolate* isolate) { TRI_GET_GLOBALS(); TRI_ASSERT(v8g != nullptr); return v8g; } /// @brief adds a method to an object bool TRI_AddMethodVocbase( v8::Isolate* isolate, v8::Handle<v8::ObjectTemplate> tpl, v8::Handle<v8::String> name, void (*func)(v8::FunctionCallbackInfo<v8::Value> const&), bool isHidden) { if (isHidden) { // hidden method tpl->Set(name, v8::FunctionTemplate::New(isolate, func), v8::DontEnum); } else { // normal method tpl->Set(name, v8::FunctionTemplate::New(isolate, func)); } return true; } /// @brief adds a global function to the given context bool TRI_AddGlobalFunctionVocbase( v8::Isolate* isolate, v8::Handle<v8::String> name, void (*func)(v8::FunctionCallbackInfo<v8::Value> const&), bool isHidden) { // all global functions are read-only if (isHidden) { return isolate->GetCurrentContext() ->Global() ->DefineOwnProperty( TRI_IGETC, name, v8::FunctionTemplate::New(isolate, func) ->GetFunction(TRI_IGETC) .FromMaybe(v8::Local<v8::Function>()), static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)) .FromMaybe(false); } else { return isolate->GetCurrentContext() ->Global() ->DefineOwnProperty(TRI_IGETC, name, v8::FunctionTemplate::New(isolate, func) ->GetFunction(TRI_IGETC) .FromMaybe(v8::Local<v8::Function>()), v8::ReadOnly) .FromMaybe(false); } } /// @brief adds a global function to the given context bool TRI_AddGlobalFunctionVocbase(v8::Isolate* isolate, v8::Handle<v8::String> name, v8::Handle<v8::Function> func, bool isHidden) { // all global functions are read-only if (isHidden) { return isolate->GetCurrentContext() ->Global() ->DefineOwnProperty( TRI_IGETC, name, func, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)) .FromMaybe(false); } else { return isolate->GetCurrentContext() ->Global() ->DefineOwnProperty(TRI_IGETC, name, func, v8::ReadOnly) .FromMaybe(false); } } /// @brief adds a global read-only variable to the given context bool TRI_AddGlobalVariableVocbase(v8::Isolate* isolate, v8::Handle<v8::String> name, v8::Handle<v8::Value> value) { // all global variables are read-only return isolate->GetCurrentContext() ->Global() ->DefineOwnProperty(TRI_IGETC, name, value, v8::ReadOnly) .FromMaybe(false); } template<> v8::Local<v8::String> v8Utf8StringFactoryT<std::string_view>( v8::Isolate* isolate, std::string_view const& arg) { return v8Utf8StringFactory(isolate, arg.data(), arg.size()); } template<> v8::Local<v8::String> v8Utf8StringFactoryT<std::string>( v8::Isolate* isolate, std::string const& arg) { return v8Utf8StringFactory(isolate, arg.data(), arg.size()); } template<> v8::Local<v8::String> v8Utf8StringFactoryT<char const*>( v8::Isolate* isolate, char const* const& arg) { return v8Utf8StringFactory(isolate, arg, strlen(arg)); } template<> v8::Local<v8::String> v8Utf8StringFactoryT<arangodb::basics::StringBuffer>( v8::Isolate* isolate, arangodb::basics::StringBuffer const& arg) { return v8Utf8StringFactory(isolate, arg.data(), arg.size()); }
{ "content_hash": "e7af26bbe9dc196e63ecd29c0475700f", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 80, "avg_line_length": 38.042959427207634, "alnum_prop": 0.6528230865746549, "repo_name": "wiltonlazary/arangodb", "id": "c31452e48320208989a13fc41362464be9e3a301", "size": "15940", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "lib/V8/v8-globals.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "C", "bytes": "309788" }, { "name": "C++", "bytes": "34723629" }, { "name": "CMake", "bytes": "383904" }, { "name": "CSS", "bytes": "210549" }, { "name": "EJS", "bytes": "231166" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "33741286" }, { "name": "LLVM", "bytes": "14975" }, { "name": "NASL", "bytes": "269512" }, { "name": "NSIS", "bytes": "47138" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "7869" }, { "name": "Python", "bytes": "184352" }, { "name": "SCSS", "bytes": "255542" }, { "name": "Shell", "bytes": "134504" }, { "name": "TypeScript", "bytes": "179074" }, { "name": "Yacc", "bytes": "79620" } ], "symlink_target": "" }
/** * index * @author: oldj * @homepage: https://oldj.net */ import { useModel } from '@@/plugin-model/useModel' import { Box, Flex, HStack, IconButton } from '@chakra-ui/react' import ItemIcon from '@renderer/components/ItemIcon' import SwitchButton from '@renderer/components/SwitchButton' import ConfigMenu from '@renderer/components/TopBar/ConfigMenu' import { actions, agent } from '@renderer/core/agent' import useOnBroadcast from '@renderer/core/useOnBroadcast' import events from '@root/common/events' import React, { useEffect, useState } from 'react' import { BiHistory, BiPlus, BiSidebar, BiX } from 'react-icons/bi' import styles from './index.less' interface IProps { show_left_panel: boolean use_system_window_frame: boolean } export default (props: IProps) => { const { show_left_panel, use_system_window_frame } = props const { lang } = useModel('useI18n') const { isHostsInTrashcan, current_hosts, isReadOnly } = useModel('useHostsData') const [is_on, setIsOn] = useState(!!current_hosts?.on) const show_toggle_switch = !show_left_panel && current_hosts && !isHostsInTrashcan(current_hosts.id) const show_history = !current_hosts const show_close_button = agent.platform === 'linux' && !use_system_window_frame || agent.platform !== 'darwin' && agent.platform !== 'linux' useEffect(() => { setIsOn(!!current_hosts?.on) }, [current_hosts]) useOnBroadcast( events.set_hosts_on_status, (id: string, on: boolean) => { if (current_hosts && current_hosts.id === id) { setIsOn(on) } }, [current_hosts], ) return ( <div className={styles.root}> <Flex align="center" className={styles.left}> <IconButton aria-label="Toggle sidebar" icon={<BiSidebar />} onClick={() => { agent.broadcast(events.toggle_left_pannel, !show_left_panel) }} variant="ghost" mr={1} /> <IconButton aria-label="Add" icon={<BiPlus />} onClick={() => agent.broadcast(events.add_new)} variant="ghost" /> </Flex> <Box className={styles.title_wrapper}> <HStack className={styles.title}> {current_hosts ? ( <> <span className={styles.hosts_icon}> <ItemIcon type={current_hosts.type} is_collapsed={!current_hosts.folder_open} /> </span> <span className={styles.hosts_title}> {current_hosts.title || lang.untitled} </span> </> ) : ( <> <span className={styles.hosts_icon}> <ItemIcon type="system" /> </span> <span className={styles.hosts_title}>{lang.system_hosts}</span> </> )} {isReadOnly(current_hosts) ? ( <span className={styles.read_only}>{lang.read_only}</span> ) : null} </HStack> </Box> <Flex align="center" justifyContent="flex-end" className={styles.right}> {show_toggle_switch ? ( <Box mr={3}> <SwitchButton on={is_on} onChange={(on) => { current_hosts && agent.broadcast(events.toggle_item, current_hosts.id, on) }} /> </Box> ) : null} {show_history ? ( <IconButton aria-label="Show history" icon={<BiHistory />} variant="ghost" onClick={() => agent.broadcast(events.show_history)} /> ) : null} <ConfigMenu /> {show_close_button ? ( <IconButton aria-label="Close window" fontSize="20px" icon={<BiX />} variant="ghost" onClick={() => actions.closeMainWindow()} /> ) : null} </Flex> </div> ) }
{ "content_hash": "7e802ae7a2555ece84c1f1208efaf63c", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 143, "avg_line_length": 29.91044776119403, "alnum_prop": 0.5399201596806387, "repo_name": "oldj/SwitchHosts", "id": "a0dfb31838a46907f9cfbb1d065213b89b23a7ba", "size": "4008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/renderer/components/TopBar/index.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "9339" }, { "name": "Less", "bytes": "30038" }, { "name": "Shell", "bytes": "10" }, { "name": "TypeScript", "bytes": "291394" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <ldswebml type="image" uri="/media-library/images/temples/denver-colorado#denver-temple-lds-999518" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its"> <search-meta> <uri-title its:translate="no">denver-temple-lds-999518</uri-title> <source>denver-temple-lds-999518</source> <publication-type its:translate="no">image</publication-type> <media-type its:translate="no">image</media-type> <publication value="ldsorg">LDS.org</publication> <publication-date value="2012-12-14">2012-12-14</publication-date> <title/> <description/> <collections> <collection its:translate="no">global-search</collection> <collection its:translate="no">media</collection> <collection its:translate="no">images</collection> </collections> <subjects> <subject>Denver Colorado Temple</subject> <subject>Temples</subject> </subjects> </search-meta> <no-search> <path>http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-gallery.jpg</path> <images> <small its:translate="no">http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-thumbnail.jpg</small> </images> <download-urls> <download-url> <label>Mobile</label> <size>160 KB</size> <path>http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-mobile.jpg</path> </download-url> <download-url> <label>Tablet</label> <size>224 KB</size> <path>http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-tablet.jpg</path> </download-url> <download-url> <label>Print</label> <size>505 KB</size> <path>http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-print.jpg</path> </download-url> <download-url> <label>Wallpaper</label> <size>823 KB</size> <path>http://media.ldscdn.org/images/media-library/temples/denver-colorado/denver-temple-lds-999518-wallpaper.jpg</path> </download-url> </download-urls> </no-search> </ldswebml>
{ "content_hash": "5c336181d91aa6b8ae3572573757cb57", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 187, "avg_line_length": 50.44, "alnum_prop": 0.6094369547977796, "repo_name": "freshie/ml-taxonomies", "id": "826cf1267a5a572fed7ce192d1a737ef5742a327", "size": "2522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roxy/data/gospel-topical-explorer-v2/content/images/denver-temple-lds-999518.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4422" }, { "name": "CSS", "bytes": "38665" }, { "name": "HTML", "bytes": "356" }, { "name": "JavaScript", "bytes": "411651" }, { "name": "Ruby", "bytes": "259121" }, { "name": "Shell", "bytes": "7329" }, { "name": "XQuery", "bytes": "857170" }, { "name": "XSLT", "bytes": "13753" } ], "symlink_target": "" }
package jef.database.query.function; import java.util.Collections; import java.util.List; import javax.persistence.PersistenceException; import jef.database.jsqlparser.expression.Function; import jef.database.jsqlparser.expression.operators.relational.ExpressionList; import jef.database.jsqlparser.visitor.Expression; import jef.tools.ArrayUtils; /** * A function which takes no arguments * * @author Michi */ public class NoArgSQLFunction implements SQLFunction { private boolean hasParenthesesIfNoArguments; private String name; public NoArgSQLFunction(String name) { this(name, true); } public NoArgSQLFunction(String name, boolean hasParenthesesIfNoArguments) { this.hasParenthesesIfNoArguments = hasParenthesesIfNoArguments; this.name = name; } public boolean hasArguments() { return false; } public boolean hasParenthesesIfNoArguments() { return hasParenthesesIfNoArguments; } public String getName() { return name; } @SuppressWarnings("unchecked") public Expression renderExpression(List<Expression> args){ if ( args.size()>0 ) { throw new PersistenceException("function takes no arguments: " + name); } Function func=new Function(name); if(hasParenthesesIfNoArguments){ func.setParameters(new ExpressionList(Collections.EMPTY_LIST)); } return func; } public boolean needEscape() { return false; } public String[] requiresUserFunction() { return ArrayUtils.EMPTY_STRING_ARRAY; } }
{ "content_hash": "2e81f4c749c9faf675aa334b7077ebdf", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 79, "avg_line_length": 23.88888888888889, "alnum_prop": 0.746843853820598, "repo_name": "xuse/ef-orm", "id": "ac976d28edc8e417506ec87c8106dffae3e9897e", "size": "2546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common-orm/src/main/java/jef/database/query/function/NoArgSQLFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "245" }, { "name": "Java", "bytes": "8573985" }, { "name": "Lua", "bytes": "30" }, { "name": "PLSQL", "bytes": "671" }, { "name": "PLpgSQL", "bytes": "185" }, { "name": "SQLPL", "bytes": "413" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title> Mocha/Chai/Expect: Example 1 </title> <link rel="stylesheet" href="../mocha.css" type="text/css"> </head> <body> <!-- Mocha will be displaying test cases report --> <div id="mocha"></div> <!-- Include mocha --> <script src="../mocha.js"></script> <!-- Include chai --> <script src="../chai.js"></script> <!-- Specify Mocha BDD setup --> <script type="text/javascript"> mocha.setup('bdd'); </script> <!-- Include test cases file --> <script src="tests.js"></script> <!-- Run Mocha; once all tests are loaded from tests.js --> <script type="text/javascript"> mocha.run(); </script> </body> </html>
{ "content_hash": "af55c4712b543c5bf1bf87d92d3084fc", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 67, "avg_line_length": 24.470588235294116, "alnum_prop": 0.4879807692307692, "repo_name": "hegdeashwin/learning-mocha-chai", "id": "c71d1177b166a209366b7693790d2796f90d5a92", "size": "832", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "codes/example1/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4242" }, { "name": "HTML", "bytes": "458174" }, { "name": "JavaScript", "bytes": "286151" } ], "symlink_target": "" }
module TwitterShuwei class Tweet attr_accessor :id, :created_at, :text, :user def initialize attributes attributes.keys.each { |k| instance_variable_set("@#{k}", attributes[k]) if respond_to?(k) } end end end
{ "content_hash": "d43acc387de4871b9910400c80ce13d3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 98, "avg_line_length": 25.666666666666668, "alnum_prop": 0.6666666666666666, "repo_name": "fsw0723/twitter_shuwei", "id": "458721c1bbd09b1e9465a553a0d287e8a0edbcd4", "size": "231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/twitter_shuwei/tweet.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "27154" } ], "symlink_target": "" }
package middlewares import ( "context" "fmt" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "runtime" "testing" "github.com/containous/traefik/middlewares/accesslog" shellwords "github.com/mattn/go-shellwords" "github.com/stretchr/testify/assert" ) type logtestResponseWriter struct{} var ( logger *Logger logfileName = "traefikTestLogger.log" logfilePath string helloWorld = "Hello, World" testBackendName = "http://127.0.0.1/testBackend" testFrontendName = "testFrontend" testStatus = 123 testHostname = "TestHost" testUsername = "TestUser" testPath = "http://testpath" testPort = 8181 testProto = "HTTP/0.0" testMethod = "POST" testReferer = "testReferer" testUserAgent = "testUserAgent" testBackend2FrontendMap = map[string]string{ testBackendName: testFrontendName, } printedLogdata bool ) func TestLogger(t *testing.T) { if runtime.GOOS == "windows" { logfilePath = filepath.Join(os.Getenv("TEMP"), logfileName) } else { logfilePath = filepath.Join("/tmp", logfileName) } logger = NewLogger(logfilePath) defer cleanup() SetBackend2FrontendMap(&testBackend2FrontendMap) r := &http.Request{ Header: map[string][]string{ "User-Agent": {testUserAgent}, "Referer": {testReferer}, }, Proto: testProto, Host: testHostname, Method: testMethod, RemoteAddr: fmt.Sprintf("%s:%d", testHostname, testPort), URL: &url.URL{ User: url.UserPassword(testUsername, ""), Path: testPath, }, } // Temporary - until new access logger is fully implemented // create the data table and populate frontend and backend core := make(accesslog.CoreLogData) logDataTable := &accesslog.LogData{Core: core, Request: r.Header} logDataTable.Core[accesslog.FrontendName] = testFrontendName logDataTable.Core[accesslog.BackendURL] = testBackendName req := r.WithContext(context.WithValue(r.Context(), accesslog.DataTableKey, logDataTable)) logger.ServeHTTP(&logtestResponseWriter{}, req, LogWriterTestHandlerFunc) if logdata, err := ioutil.ReadFile(logfilePath); err != nil { fmt.Printf("%s\n%s\n", string(logdata), err.Error()) assert.Nil(t, err) } else if tokens, err := shellwords.Parse(string(logdata)); err != nil { fmt.Printf("%s\n", err.Error()) assert.Nil(t, err) } else if assert.Equal(t, 14, len(tokens), printLogdata(logdata)) { assert.Equal(t, testHostname, tokens[0], printLogdata(logdata)) assert.Equal(t, testUsername, tokens[2], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%s %s %s", testMethod, testPath, testProto), tokens[5], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%d", testStatus), tokens[6], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%d", len(helloWorld)), tokens[7], printLogdata(logdata)) assert.Equal(t, testReferer, tokens[8], printLogdata(logdata)) assert.Equal(t, testUserAgent, tokens[9], printLogdata(logdata)) assert.Equal(t, "1", tokens[10], printLogdata(logdata)) assert.Equal(t, testFrontendName, tokens[11], printLogdata(logdata)) assert.Equal(t, testBackendName, tokens[12], printLogdata(logdata)) } } func cleanup() { logger.Close() os.Remove(logfilePath) } func printLogdata(logdata []byte) string { return fmt.Sprintf( "\nExpected: %s\n"+ "Actual: %s", "TestHost - TestUser [13/Apr/2016:07:14:19 -0700] \"POST http://testpath HTTP/0.0\" 123 12 \"testReferer\" \"testUserAgent\" 1 \"testFrontend\" \"http://127.0.0.1/testBackend\" 1ms", string(logdata)) } func LogWriterTestHandlerFunc(rw http.ResponseWriter, r *http.Request) { rw.Write([]byte(helloWorld)) rw.WriteHeader(testStatus) saveBackendNameForLogger(r, testBackendName) } func (lrw *logtestResponseWriter) Header() http.Header { return map[string][]string{} } func (lrw *logtestResponseWriter) Write(b []byte) (int, error) { return len(b), nil } func (lrw *logtestResponseWriter) WriteHeader(s int) { }
{ "content_hash": "d11df0bf2c1143a567b8519e3414d772", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 184, "avg_line_length": 31.929133858267715, "alnum_prop": 0.6855733662145499, "repo_name": "yyekhlef/traefik", "id": "9038d6679fbc31924b61b35504a6cb3c61281d5d", "size": "4055", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "middlewares/logger_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1551" }, { "name": "Go", "bytes": "695287" }, { "name": "HTML", "bytes": "7528" }, { "name": "JavaScript", "bytes": "23898" }, { "name": "Makefile", "bytes": "3090" }, { "name": "Shell", "bytes": "17463" } ], "symlink_target": "" }
import itertools from ...core import Add, Equality, Integer, Mul, Pow, Rational, S, Symbol, oo from ...core.function import _coeff_isneg from ...logic import true from ...utilities import default_sort_key, group from ..conventions import requires_partial from ..printer import Printer from ..str import sstr from .pretty_symbology import (annotated, greek_unicode, hobj, pretty_atom, pretty_symbol, pretty_use_unicode, vobj, xobj, xsym) from .stringpict import prettyForm, stringPict # rename for usage from outside pprint_use_unicode = pretty_use_unicode class PrettyPrinter(Printer): """Printer, which converts an expression into 2D ASCII-art figure.""" printmethod = '_pretty' _default_settings = { 'order': None, 'full_prec': 'auto', 'use_unicode': None, 'wrap_line': True, 'num_columns': None, } def __init__(self, settings=None): Printer.__init__(self, settings) self.emptyPrinter = lambda x: prettyForm(str(x)) @property def _use_unicode(self): if self._settings['use_unicode']: return True else: return pretty_use_unicode() def doprint(self, expr): return self._print(expr).render(**self._settings) # empty op so _print(stringPict) returns the same def _print_stringPict(self, e): return e def _print_atan2(self, e): pform = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm(*pform.left('atan2')) return pform def _print_Symbol(self, e): symb = pretty_symbol(e.name) return prettyForm(symb) _print_Dummy = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Float(self, e): # we will use StrPrinter's Float printer, but we need to handle the # full_prec ourselves, according to the self._print_level full_prec = self._settings['full_prec'] if full_prec == 'auto': full_prec = self._print_level == 1 return prettyForm(sstr(e, full_prec=full_prec)) def _print_Atom(self, e): try: # print atoms like Exp1 or Pi return prettyForm(pretty_atom(e.__class__.__name__)) except KeyError: return self.emptyPrinter(e) # Infinity inherits from Number, so we have to override _print_XXX order _print_Infinity = _print_Atom _print_NegativeInfinity = _print_Atom _print_EmptySet = _print_Atom _print_Naturals = _print_Atom _print_Naturals0 = _print_Atom _print_Integers = _print_Atom _print_Rationals = _print_Atom _print_Reals = _print_Atom def _print_subfactorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('!')) return pform def _print_factorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!')) return pform def _print_factorial2(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!!')) return pform def _print_binomial(self, e): n, k = e.args n_pform = self._print(n) k_pform = self._print(k) bar = ' '*max(n_pform.width(), k_pform.width()) pform = prettyForm(*k_pform.above(bar)) pform = prettyForm(*pform.above(n_pform)) pform = prettyForm(*pform.parens('(', ')')) pform.baseline = (pform.baseline + 1)//2 return pform def _print_Relational(self, e): op = prettyForm(' ' + xsym(e.rel_op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Not(self, e): from ...logic import Equivalent, Implies if self._use_unicode: arg = e.args[0] pform = self._print(arg) if isinstance(arg, Equivalent): return self._print_Equivalent(arg, altchar='\N{NOT IDENTICAL TO}') if isinstance(arg, Implies): return self._print_Implies(arg, altchar='\N{RIGHTWARDS ARROW WITH STROKE}') if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) return prettyForm(*pform.left('\N{NOT SIGN}')) else: return self._print_Function(e) def __print_Boolean(self, e, char, sort=True): args = e.args if sort: args = sorted(e.args, key=default_sort_key) arg = args[0] pform = self._print(arg) if arg.is_Boolean and (not arg.is_Not and not arg.is_Atom): pform = prettyForm(*pform.parens()) for arg in args[1:]: pform_arg = self._print(arg) if arg.is_Boolean and (not arg.is_Not and not arg.is_Atom): pform_arg = prettyForm(*pform_arg.parens()) pform = prettyForm(*pform.right(f' {char} ')) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_And(self, e): if self._use_unicode: return self.__print_Boolean(e, '\N{LOGICAL AND}') else: return self._print_Function(e, sort=True) def _print_Or(self, e): if self._use_unicode: return self.__print_Boolean(e, '\N{LOGICAL OR}') else: return self._print_Function(e, sort=True) def _print_Xor(self, e): if self._use_unicode: return self.__print_Boolean(e, '\N{XOR}') else: return self._print_Function(e, sort=True) def _print_Nand(self, e): if self._use_unicode: return self.__print_Boolean(e, '\N{NAND}') else: return self._print_Function(e, sort=True) def _print_Nor(self, e): if self._use_unicode: return self.__print_Boolean(e, '\N{NOR}') else: return self._print_Function(e, sort=True) def _print_Implies(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or '\N{RIGHTWARDS ARROW}', sort=False) else: return self._print_Function(e) def _print_Equivalent(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or '\N{IDENTICAL TO}') else: return self._print_Function(e, sort=True) def _print_conjugate(self, e): pform = self._print(e.args[0]) return prettyForm( *pform.above( hobj('_', pform.width())) ) def _print_Abs(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('|', '|')) return pform _print_Determinant = _print_Abs def _print_floor(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lfloor', 'rfloor')) return pform else: return self._print_Function(e) def _print_ceiling(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lceil', 'rceil')) return pform else: return self._print_Function(e) def _print_Derivative(self, deriv): if requires_partial(deriv) and self._use_unicode: deriv_symbol = '\N{PARTIAL DIFFERENTIAL}' else: deriv_symbol = r'd' syms = list(reversed(deriv.variables)) x = None for sym, num in group(syms, multiple=False): s = self._print(sym) ds = prettyForm(*s.left(deriv_symbol)) if num > 1: ds = ds**prettyForm(str(num)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if len(syms) > 1: pform = pform**prettyForm(str(len(syms))) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: x = lim[0] # Create bar based on the height of the argument h = arg.height() H = h + 2 # XXX hack! ascii_mode = not self._use_unicode if ascii_mode: H += 2 vint = vobj('int', H) # Construct the pretty form with the integral sign and the argument pform = prettyForm(vint) pform.baseline = arg.baseline + ( H - h)//2 # covering the whole argument if len(lim) > 1: # Create pretty forms for endpoints, if definite integral. # Do not print empty endpoints. if len(lim) == 2: prettyA = prettyForm('') prettyB = self._print(lim[1]) if len(lim) == 3: prettyA = self._print(lim[1]) prettyB = self._print(lim[2]) if ascii_mode: # XXX hack # Add spacing so that endpoint can more easily be # identified with the correct integral sign spc = max(1, 3 - prettyB.width()) prettyB = prettyForm(*prettyB.left(' ' * spc)) spc = max(1, 4 - prettyA.width()) prettyA = prettyForm(*prettyA.right(' ' * spc)) pform = prettyForm(*pform.above(prettyB)) pform = prettyForm(*pform.below(prettyA)) if not ascii_mode: # XXX hack pform = prettyForm(*pform.right(' ')) if firstterm: s = pform # first term firstterm = False else: s = prettyForm(*s.left(pform)) pform = prettyForm(*arg.left(s)) pform.binding = prettyForm.MUL return pform def _print_Product(self, expr): func = expr.term pretty_func = self._print(func) horizontal_chr = xobj('_', 1) corner_chr = xobj('_', 1) vertical_chr = xobj('|', 1) if self._use_unicode: # use unicode corners horizontal_chr = xobj('-', 1) corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}' func_height = pretty_func.height() first = True max_upper = 0 sign_height = 0 for lim in expr.limits: width = (func_height + 2) * 5 // 3 - 2 sign_lines = [] sign_lines.append(corner_chr + (horizontal_chr*width) + corner_chr) for i in range(func_height + 1): sign_lines.append(vertical_chr + (' '*width) + vertical_chr) pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines)) pretty_upper = self._print(lim[2]) pretty_lower = self._print(Equality(lim[0], lim[1])) max_upper = max(max_upper, pretty_upper.height()) if first: sign_height = pretty_sign.height() pretty_sign = prettyForm(*pretty_sign.above(pretty_upper)) pretty_sign = prettyForm(*pretty_sign.below(pretty_lower)) if first: pretty_func.baseline = 0 first = False height = pretty_sign.height() padding = stringPict('') padding = prettyForm(*padding.stack(*[' ']*(height - 1))) pretty_sign = prettyForm(*pretty_sign.right(padding)) pretty_func = prettyForm(*pretty_sign.right(pretty_func)) pretty_func.baseline = max_upper + sign_height//2 pretty_func.binding = prettyForm.MUL return pretty_func def _print_Sum(self, expr): ascii_mode = not self._use_unicode def asum(hrequired, lower, upper, use_ascii): h = max(hrequired, 2) d = h//2 w = d + 1 more = hrequired % 2 lines = [] if use_ascii: lines.append('_'*w + ' ') lines.append(r'\%s`' % (' '*(w - 1))) for i in range(1, d): lines.append('%s\\%s' % (' '*i, ' '*(w - i))) if more: lines.append('%s)%s' % (' '*d, ' '*(w - d))) for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append('/' + '_'*(w - 1) + ',') return d, h + more, lines, 0 else: w = w + more d = d + more vsum = vobj('sum', 4) lines.append('_'*w) for i in range(d): lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1))) for i in reversed(range(d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*w) return d, h + 2*more, lines, more f = expr.function prettyF = self._print(f) if f.is_Add: # add parens prettyF = prettyForm(*prettyF.parens()) H = prettyF.height() + 2 # \sum \sum \sum ... first = True max_upper = 0 sign_height = 0 for lim in expr.limits: assert len(lim) == 3 # no support for indefinite sums yet prettyUpper = self._print(lim[2]) prettyLower = self._print(Equality(lim[0], lim[1], evaluate=False)) max_upper = max(max_upper, prettyUpper.height()) # Create sum sign based on the height of the argument d, h, slines, adjustment = asum( H, prettyLower.width(), prettyUpper.width(), ascii_mode) prettySign = stringPict('') prettySign = prettyForm(*prettySign.stack(*slines)) if first: sign_height = prettySign.height() prettySign = prettyForm(*prettySign.above(prettyUpper)) prettySign = prettyForm(*prettySign.below(prettyLower)) if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - prettyF.baseline) - adjustment first = False # put padding to the right pad = stringPict('') pad = prettyForm(*pad.stack(*[' ']*h)) prettySign = prettyForm(*prettySign.right(pad)) # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) prettyF.baseline = max_upper + sign_height//2 prettyF.binding = prettyForm.MUL return prettyF def _print_Limit(self, l): e, z, z0, dir = l.args E = self._print(e) if e.is_Add or e.is_Relational: E = prettyForm(*E.parens()) Lim = prettyForm('lim') LimArg = self._print(z) if self._use_unicode: LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}')) else: LimArg = prettyForm(*LimArg.right('->')) LimArg = prettyForm(*LimArg.right(self._print(z0))) if str(dir) == 'real' or z0 in (oo, -oo): dir = '' else: if self._use_unicode: dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == '+' else '\N{SUPERSCRIPT MINUS}' LimArg = prettyForm(*LimArg.right(self._print(dir))) Lim = prettyForm(*Lim.below(LimArg)) Lim = prettyForm(*Lim.right(E)) return Lim def _print_matrix_contents(self, e): """ This method factors out what is essentially grid printing. """ M = e # matrix Ms = {} # i,j -> pretty(M[i,j]) for i in range(M.rows): for j in range(M.cols): Ms[i, j] = self._print(M[i, j]) # h- and v- spacers hsep = 2 vsep = 1 # max width for columns maxw = [-1] * M.cols for j in range(M.cols): maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0]) # drawing result D = None for i in range(M.rows): D_row = None for j in range(M.cols): s = Ms[i, j] # reshape s to maxw # XXX this should be generalized, and go to stringPict.reshape ? assert s.width() <= maxw[j] # hcenter it, +0.5 to the right 2 # ( it's better to align formula starts for say 0 and r ) # XXX this is not good in all cases -- maybe introduce vbaseline? wdelta = maxw[j] - s.width() wleft = wdelta // 2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) # we don't need vcenter cells -- this is automatically done in # a pretty way because when their baselines are taking into # account in .right() if D_row is None: D_row = s # first box in a row continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) if D is None: D = prettyForm('') # Empty Matrix return D def _print_MatrixBase(self, e): D = self._print_matrix_contents(e) D.baseline = D.height()//2 D = prettyForm(*D.parens('[', ']')) return D _print_ImmutableMatrix = _print_MatrixBase _print_Matrix = _print_MatrixBase def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(', ')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*0 + 'tr')) return D def _print_MatrixElement(self, expr): from ...matrices import MatrixSymbol if (isinstance(expr.parent, MatrixSymbol) and expr.i.is_number and expr.j.is_number): return self._print( Symbol(expr.parent.name + f'_{expr.i:d}{expr.j:d}')) else: prettyFunc = self._print(expr.parent) prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', ').parens(left='[', right=']')[0] pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyIndices)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyIndices return pform def _print_Transpose(self, expr): pform = self._print(expr.arg) from ...matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(prettyForm('T')) return pform def _print_Adjoint(self, expr): pform = self._print(expr.arg) if self._use_unicode: dag = prettyForm('\N{DAGGER}') else: dag = prettyForm('+') from ...matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**dag return pform def _print_MatAdd(self, expr): return self._print_seq(expr.args, None, None, ' + ') def _print_MatMul(self, expr): args = list(expr.args) from ...matrices import MatAdd, HadamardProduct for i, a in enumerate(args): if (isinstance(a, (Add, MatAdd, HadamardProduct)) and len(expr.args) > 1): args[i] = prettyForm(*self._print(a).parens()) else: args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_MatPow(self, expr): pform = self._print(expr.base) from ...matrices import MatrixSymbol if not isinstance(expr.base, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(self._print(expr.exp)) return pform _print_MatrixSymbol = _print_Symbol def _print_BasisDependent(self, expr): from ...vector import Vector if not self._use_unicode: # pragma: no cover raise NotImplementedError('ASCII pretty printing of BasisDependent is not implemented') if expr == expr.zero: return prettyForm(expr.zero._pretty_form) o1 = [] vectstrs = [] if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key=lambda x: x[0].__str__()) for k, v in inneritems: # If the coef of the basis vector is 1 - we skip the 1 if v == 1: o1.append('' + k._pretty_form) # Same for -1 elif v == -1: o1.append('(-1) ' + k._pretty_form) else: # We always wrap the measure numbers in #parentheses arg_str = self._print(v).parens()[0] o1.append(arg_str + ' ' + k._pretty_form) vectstrs.append(k._pretty_form) # Fixing the newlines lengths = [] strs = [''] for i, partstr in enumerate(o1): # XXX: What is this hack? if '\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}', '\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max(len(x) for x in o1) for parts in o1: lengths.append(len(parts[0])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths) - 1))) if j == 0: strs[0] += parts[0] + ' + ' else: strs[j] += parts[j] + ' ' * (lengths[-1] - len(parts[j]) + 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths) - 1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm('\n'.join([s[:-3] for s in strs])) def _print_NDimArray(self, expr): from ...matrices import ImmutableMatrix if expr.rank() == 0: return self._print(expr[()]) level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] for outer_i in itertools.product(*shape_ranges): level_str[-1].append(expr[outer_i]) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append(level_str[back_outer_i+1]) else: level_str[back_outer_i].append(ImmutableMatrix(level_str[back_outer_i+1])) if len(level_str[back_outer_i + 1]) == 1: level_str[back_outer_i][-1] = ImmutableMatrix([[level_str[back_outer_i][-1]]]) even = not even level_str[back_outer_i+1] = [] out_expr = level_str[0][0] if expr.rank() % 2 == 1: out_expr = ImmutableMatrix([out_expr]) return self._print(out_expr) _print_ImmutableDenseNDimArray = _print_NDimArray _print_ImmutableSparseNDimArray = _print_NDimArray _print_MutableDenseNDimArray = _print_NDimArray _print_MutableSparseNDimArray = _print_NDimArray def _print_Piecewise(self, pexpr): P = {} for n, ec in enumerate(pexpr.args): P[n, 0] = self._print(ec.expr) if ec.cond == true: P[n, 1] = prettyForm('otherwise') else: P[n, 1] = prettyForm( *prettyForm('for ').right(self._print(ec.cond))) hsep = 2 vsep = 1 len_args = len(pexpr.args) # max widths maxw = [max(P[i, j].width() for i in range(len_args)) for j in range(2)] # FIXME: Refactor this code and matrix into some tabular environment. # drawing result D = None for i in range(len_args): D_row = None for j in range(2): p = P[i, j] assert p.width() <= maxw[j] wdelta = maxw[j] - p.width() wleft = wdelta // 2 wright = wdelta - wleft p = prettyForm(*p.right(' '*wright)) p = prettyForm(*p.left(' '*wleft)) if D_row is None: D_row = p continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(p)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens('{', '')) D.baseline = D.height()//2 D.binding = prettyForm.OPEN return D def _hprint_vec(self, v): D = None for a in v: p = a if D is None: D = p else: D = prettyForm(*D.right(', ')) D = prettyForm(*D.right(p)) if D is None: D = stringPict(' ') return D def _hprint_vseparator(self, p1, p2): tmp = prettyForm(*p1.right(p2)) sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline) return prettyForm(*p1.right(sep, p2)) def _print_hyper(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment ap = [self._print(a) for a in e.ap] bq = [self._print(b) for b in e.bq] P = self._print(e.argument) P.baseline = P.height()//2 # Drawing result - first create the ap, bq vectors D = None for v in [ap, bq]: D_row = self._hprint_vec(v) if D is None: D = D_row # first row in a picture else: D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the F symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('F') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) add = (sz + 1)//2 F = prettyForm(*F.left(self._print(len(e.ap)))) F = prettyForm(*F.right(self._print(len(e.bq)))) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_meijerg(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment v = {} v[(0, 0)] = [self._print(a) for a in e.an] v[(0, 1)] = [self._print(a) for a in e.aother] v[(1, 0)] = [self._print(b) for b in e.bm] v[(1, 1)] = [self._print(b) for b in e.bother] P = self._print(e.argument) P.baseline = P.height()//2 vp = {} for idx in v: vp[idx] = self._hprint_vec(v[idx]) for i in range(2): maxw = max(vp[(0, i)].width(), vp[(1, i)].width()) for j in range(2): s = vp[(j, i)] left = (maxw - s.width()) // 2 right = maxw - left - s.width() s = prettyForm(*s.left(' ' * left)) s = prettyForm(*s.right(' ' * right)) vp[(j, i)] = s D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)])) D1 = prettyForm(*D1.below(' ')) D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)])) D = prettyForm(*D1.below(D2)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the G symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('G') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) pp = self._print(len(e.ap)) pq = self._print(len(e.bq)) pm = self._print(len(e.bm)) pn = self._print(len(e.an)) def adjust(p1, p2): diff = p1.width() - p2.width() if diff == 0: return p1, p2 elif diff > 0: return p1, prettyForm(*p2.left(' '*diff)) else: return prettyForm(*p1.left(' '*-diff)), p2 pp, pm = adjust(pp, pm) pq, pn = adjust(pq, pn) pu = prettyForm(*pm.right(', ', pn)) pl = prettyForm(*pp.right(', ', pq)) ht = F.baseline - above - 2 pu = prettyForm(*pu.below('\n'*ht)) p = prettyForm(*pu.below(pl)) F.baseline = above F = prettyForm(*F.right(p)) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_Function(self, e, sort=False): # XXX works only for applied functions func = e.func args = e.args if sort: args = sorted(args, key=default_sort_key) func_name = func.__name__ prettyFunc = self._print(Symbol(func_name)) prettyArgs = prettyForm(*self._print_seq(args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_Lambda(self, e): vars, expr = e.args if self._use_unicode: arrow = ' \N{RIGHTWARDS ARROW FROM BAR} ' else: arrow = ' -> ' if len(vars) == 1: var_form = self._print(vars[0]) else: var_form = self._print(tuple(vars)) return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8) def _print_Order(self, expr): pform = self._print(expr.expr) if ((expr.point and any(p != 0 for p in expr.point)) or len(expr.variables) > 1): pform = prettyForm(*pform.right('; ')) if len(expr.variables) > 1: pform = prettyForm(*pform.right(self._print(expr.variables))) else: pform = prettyForm(*pform.right(self._print(expr.variables[0]))) if self._use_unicode: pform = prettyForm(*pform.right(' \N{RIGHTWARDS ARROW} ')) else: pform = prettyForm(*pform.right(' -> ')) if len(expr.point) > 1: pform = prettyForm(*pform.right(self._print(expr.point))) else: pform = prettyForm(*pform.right(self._print(expr.point[0]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('O')) return pform def _print_gamma(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['Gamma'])) return pform else: return self._print_Function(e) def _print_uppergamma(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.right(', ', self._print(e.args[1]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['Gamma'])) return pform else: return self._print_Function(e) def _print_lowergamma(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.right(', ', self._print(e.args[1]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['gamma'])) return pform else: return self._print_Function(e) def _print_DiracDelta(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) delta = self._print(greek_unicode['delta']) if len(e.args) > 1 and e.args[1] != 0: k = prettyForm(*self._print(e.args[1]).parens()) delta = delta**k pform = prettyForm(*pform.left(delta)) return pform else: return self._print_Function(e) def _print_expint(self, e): from ...core import Function if e.args[0].is_Integer and self._use_unicode: return self._print_Function(Function(f'E_{e.args[0]}')(e.args[1])) return self._print_Function(e) def _print_Chi(self, e): # This needs a special case since otherwise it comes out as greek # letter chi... prettyFunc = prettyForm('Chi') prettyArgs = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_elliptic_e(self, e): pforma0 = self._print(e.args[0]) if len(e.args) == 1: pform = pforma0 else: pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('E')) return pform def _print_elliptic_k(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('K')) return pform def _print_elliptic_f(self, e): pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('F')) return pform def _print_elliptic_pi(self, e): name = greek_unicode['Pi'] if self._use_unicode else 'Pi' pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) if len(e.args) == 2: pform = self._hprint_vseparator(pforma0, pforma1) else: pforma2 = self._print(e.args[2]) pforma = self._hprint_vseparator(pforma1, pforma2) pforma = prettyForm(*pforma.left('; ')) pform = prettyForm(*pforma.left(pforma0)) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(name)) return pform def _print_Mod(self, expr): pform = self._print(expr.args[0]) if pform.binding > prettyForm.MUL: pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right(' mod ')) pform = prettyForm(*pform.right(self._print(expr.args[1]))) pform.binding = prettyForm.OPEN return pform def _print_GoldenRatio(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('phi')) return self._print(Symbol('GoldenRatio')) def _print_EulerGamma(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('gamma')) return self._print(Symbol('EulerGamma')) def _print_Add(self, expr, order=None): if self.order == 'none': terms = list(expr.args) else: terms = expr.as_ordered_terms(order=order or self.order) pforms, indices = [], [] def pretty_negative(pform, index): """Prepend a minus sign to a pretty form.""" # TODO: Move this code to prettyForm if index == 0: if pform.height() > 1: pform_neg = '- ' else: pform_neg = '-' else: pform_neg = ' - ' if pform.binding > prettyForm.NEG: p = stringPict(*pform.parens()) else: p = pform p = stringPict.next(pform_neg, p) # Lower the binding to NEG, even if it was higher. Otherwise, it # will print as a + ( - (b)), instead of a - (b). return prettyForm(binding=prettyForm.NEG, *p) for i, term in enumerate(terms): if term.is_Mul and _coeff_isneg(term): coeff, other = term.as_coeff_mul(rational=False) pform = self._print(Mul(-coeff, *other, evaluate=False)) pforms.append(pretty_negative(pform, i)) elif term.is_Rational and term.denominator > 1: pforms.append(None) indices.append(i) elif term.is_Number and term < 0: pform = self._print(-term) pforms.append(pretty_negative(pform, i)) elif term.is_Relational: pforms.append(prettyForm(*self._print(term).parens())) else: pforms.append(self._print(term)) if indices: large = True for pform in pforms: if pform is not None and pform.height() > 1: break else: large = False for i in indices: term, negative = terms[i], False if term < 0: term, negative = -term, True if large: pform = prettyForm(str(term.numerator))/prettyForm(str(term.denominator)) else: pform = self._print(term) if negative: pform = pretty_negative(pform, i) pforms[i] = pform return prettyForm.__add__(*pforms) def _print_Mul(self, product): a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order != 'none': args = product.as_ordered_factors() else: args = product.args multiple_ones = len([x for x in args if x == 1]) > 1 # Gather terms for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not oo: if item.numerator != 1 or multiple_ones: a.append(Rational(item.numerator)) if item.denominator != 1: b.append(Rational(item.denominator)) else: a.append(item) from ...functions import Piecewise from ...concrete import Product, Sum from ...integrals import Integral # Convert to pretty forms. Add parens to Add instances if there # is more than one term in the numer/denom for i in range(len(a)): if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and isinstance(a[i], (Integral, Piecewise, Product, Sum))): a[i] = prettyForm(*self._print(a[i]).parens()) elif a[i].is_Relational: a[i] = prettyForm(*self._print(a[i]).parens()) else: a[i] = self._print(a[i]) for i in range(len(b)): if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and isinstance(b[i], (Integral, Piecewise, Product, Sum))): b[i] = prettyForm(*self._print(b[i]).parens()) else: b[i] = self._print(b[i]) # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(Integer(1)) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, expt): bpretty = self._print(base) # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ # Make exponent number to put above it if expt.is_Rational: exp = str(expt.denominator) if exp == '2': exp = '' else: exp = str(self._print(expt.args[0])) exp = exp.ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent rootsign = stringPict(exp + '\n' + rootsign) rootsign.baseline = 0 # Diagonal: length is one less than height of base linelength = bpretty.height() - 1 diagonal = stringPict('\n'.join( ' '*(linelength - i - 1) + _zZ + ' '*i for i in range(linelength) )) # Put baseline just below lowest line: next to exp diagonal.baseline = linelength - 1 # Make the root symbol rootsign = prettyForm(*rootsign.right(diagonal)) # Det the baseline to match contents to fix the height # but if the height of bpretty is one, the rootsign must be one higher rootsign.baseline = max(1, bpretty.baseline) # build result s = prettyForm(hobj('_', 2 + bpretty.width())) s = prettyForm(*bpretty.above(s)) s = prettyForm(*s.left(rootsign)) return s def _print_Pow(self, power): from ...simplify import fraction from ...series import Limit b, e = power.as_base_exp() if power.is_commutative and not e.is_Float: if e == -1: return prettyForm('1')/self._print(b) n, d = fraction(e) if n == 1 and d.is_Atom and not e.is_Integer: return self._print_nth_root(b, e) if e.is_Rational and e < 0: return prettyForm('1')/self._print(Pow(b, -e, evaluate=False)) if b.is_Relational or isinstance(b, Limit): return prettyForm(*self._print(b).parens()).__pow__(self._print(e)) return self._print(b)**self._print(e) def __print_numer_denom(self, p, q): if q == 1: if p < 0: return prettyForm(str(p), binding=prettyForm.NEG) else: return prettyForm(str(p)) elif abs(p) >= 10 and abs(q) >= 10: # If more than one digit in numer and denom, print larger fraction if p < 0: return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q)) # Old printing method: # pform = prettyForm(str(-p))/prettyForm(str(q)) # return prettyForm(binding=prettyForm.NEG, *pform.left('- ')) else: return prettyForm(str(p))/prettyForm(str(q)) def _print_Rational(self, expr): result = self.__print_numer_denom(expr.numerator, expr.denominator) if result is not None: return result else: return self.emptyPrinter(expr) def _print_ProductSet(self, p): prod_char = '\N{MULTIPLICATION SIGN}' if self._use_unicode else 'x' return self._print_seq(p.sets, None, None, f' {prod_char} ', parenthesize=lambda set: set.is_Union or set.is_Intersection or set.is_ProductSet) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_seq(items, '{', '}', ', ' ) def _print_set(self, l): return self._print_seq(sorted(l, key=default_sort_key), '{', '}') def _print_Range(self, s): if self._use_unicode: dots = '\N{HORIZONTAL ELLIPSIS}' else: dots = '...' if s.start == -oo: it = iter(s) printset = s.start, dots, s._last_element - s.step, s._last_element elif s.stop is oo or len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s._last_element else: printset = tuple(s) return self._print_seq(printset, '{', '}', ', ' ) def _print_Interval(self, i): if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return self._print_seq(i.args[:2], left, right) def _print_Intersection(self, u): delimiter = ' %s ' % pretty_atom('Intersection', 'n') return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Union or set.is_Complement) def _print_Union(self, u): union_delimiter = ' %s ' % pretty_atom('Union', 'U') return self._print_seq(u.args, None, None, union_delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Complement) def _print_SymmetricDifference(self, u): if not self._use_unicode: raise NotImplementedError('ASCII pretty printing of SymmetricDifference is not implemented') sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference') return self._print_seq(u.args, None, None, sym_delimeter) def _print_Complement(self, u): delimiter = r' \ ' return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) def _print_Contains(self, e): var, set = e.args if self._use_unicode: el = ' \N{ELEMENT OF} ' return prettyForm(*stringPict.next(self._print(var), el, self._print(set)), binding=8) else: return prettyForm(sstr(e)) def _print_seq(self, seq, left=None, right=None, delimiter=', ', parenthesize=lambda x: False): s = None for item in seq: pform = self._print(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else: s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') s = prettyForm(*s.parens(left, right, ifascii_nougly=True)) return s def join(self, delimiter, args): pform = None for arg in args: if pform is None: pform = arg else: pform = prettyForm(*pform.right(delimiter)) pform = prettyForm(*pform.right(arg)) if pform is None: return prettyForm('') else: return pform def _print_list(self, l): return self._print_seq(l, '[', ']') def _print_tuple(self, t): if len(t) == 1: ptuple = prettyForm(*stringPict.next(self._print(t[0]), ',')) return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True)) else: return self._print_seq(t, '(', ')') def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_dict(self, d): keys = sorted(d, key=default_sort_key) items = [] for k in keys: K = self._print(k) V = self._print(d[k]) s = prettyForm(*stringPict.next(K, ': ', V)) items.append(s) return self._print_seq(items, '{', '}') def _print_Dict(self, d): return self._print_dict(d) def _print_frozenset(self, s): items = sorted(s, key=default_sort_key) pretty = self._print_seq(items, '{', '}') pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True)) pretty = prettyForm(*stringPict.next(type(s).__name__, pretty)) return pretty def _print_PolyElement(self, poly): return prettyForm(sstr(poly)) def _print_FracElement(self, frac): return prettyForm(sstr(frac)) def _print_AlgebraicElement(self, expr): return self._print(expr.parent.to_expr(expr)) def _print_RootOf(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.free_symbols: args += expr.args[1:] else: args += [expr.index] pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootOf')) return pform def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootSum')) return pform def _print_FiniteField(self, expr): if self._use_unicode: form = '\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL F}_%d' else: form = 'GF(%d)' return prettyForm(pretty_symbol(form % expr.order)) def _print_IntegerRing(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}') else: return prettyForm('ZZ') def _print_RationalField(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}') else: return prettyForm('QQ') def _print_RealField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL R}' else: prefix = 'RR' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + '_' + str(domain.precision))) def _print_PolynomialRing(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm('order=').right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_FractionField(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm('order=').right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '(', ')') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_GroebnerBasis(self, basis): exprs = [ self._print_Add(arg, order=basis.order) for arg in basis.exprs ] exprs = prettyForm(*self.join(', ', exprs).parens(left='[', right=']')) gens = [ self._print(gen) for gen in basis.gens ] domain = prettyForm( *prettyForm('domain=').right(self._print(basis.domain))) order = prettyForm( *prettyForm('order=').right(self._print(basis.order))) pform = self.join(', ', [exprs] + gens + [domain, order]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(basis.__class__.__name__)) return pform def _print_Subs(self, e): pform = self._print(e.expr) pform = prettyForm(*pform.parens()) h = pform.height() if pform.height() > 1 else 2 rvert = stringPict(vobj('|', h), baseline=pform.baseline) pform = prettyForm(*pform.right(rvert)) b = pform.baseline pform.baseline = pform.height() - 1 pform = prettyForm(*pform.right(self._print_seq([ self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])), delimiter='') for v in zip(e.variables, e.point) ]))) pform.baseline = b return pform def _print_euler(self, e): pform = prettyForm('E') arg = self._print(e.args[0]) pform_arg = prettyForm(' '*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_catalan(self, e): pform = prettyForm('C') arg = self._print(e.args[0]) pform_arg = prettyForm(' '*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_KroneckerDelta(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.right((prettyForm(',')))) pform = prettyForm(*pform.right((self._print(e.args[1])))) if self._use_unicode: a = stringPict(pretty_symbol('delta')) else: a = stringPict('d') b = pform top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_RandomDomain(self, d): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.as_boolean()))) return pform def _print_BaseScalarField(self, field): string = field._coord_sys._names[field._index] return self._print(pretty_symbol(string)) def _print_BaseVectorField(self, field): s = '\N{PARTIAL DIFFERENTIAL}' + '_' + field._coord_sys._names[field._index] return self._print(pretty_symbol(s)) def _print_Tr(self, p): # TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left(f'{p.__class__.__name__}(')) pform = prettyForm(*pform.right(')')) return pform def pretty(expr, **settings): """Returns a string containing the prettified form of expr. For information on keyword arguments see pretty_print function. """ pp = PrettyPrinter(settings) # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def pretty_print(expr, **settings): """Prints expr in pretty form. pprint is just a shortcut for this function. Parameters ========== expr : expression the expression to print wrap_line : bool, optional line wrapping enabled/disabled, defaults to True num_columns : int or None, optional number of columns before line breaking (default to None which reads the terminal width), useful when using Diofant without terminal. use_unicode : bool or None, optional use unicode characters, such as the Greek letter pi instead of the string pi. full_prec : bool or string, optional use full precision. Default to "auto" order : bool or string, optional set to 'none' for long expressions if slow; default is None """ print(pretty(expr, **settings)) #: pprint = pretty_print
{ "content_hash": "75bc6515ad23699434c73cc966fb7c33", "timestamp": "", "source": "github", "line_count": 1744, "max_line_length": 104, "avg_line_length": 33.87442660550459, "alnum_prop": 0.5164446400460416, "repo_name": "skirpichev/omg", "id": "db16eb6c529b5d2c0bec464b3ace2e7e548038d5", "size": "59077", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "diofant/printing/pretty/pretty.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "10305079" } ], "symlink_target": "" }
define(function(require) { 'use strict'; var _ = require('underscore'); var Backgrid = require('bowerassets/backgrid/lib/backgrid'); /** * Cells should be removed durung dispose cycle */ Backgrid.Cell.prototype.keepElement = false; /** * Copied from backgrid. Removed unused in our project code which slow downs rendering */ Backgrid.Cell.prototype.initialize = function(options) { this.column = options.column; /* // Columns are always prepared in Oro.Datagrid if (!(this.column instanceof Column)) { this.column = new Column(this.column); } */ var column = this.column; var model = this.model; var $el = this.$el; var Formatter = Backgrid.resolveNameToClass(column.get('formatter') || this.formatter, 'Formatter'); if (!_.isFunction(Formatter.fromRaw) && !_.isFunction(Formatter.toRaw)) { Formatter = new Formatter(); } this.formatter = Formatter; this.editor = Backgrid.resolveNameToClass(this.editor, 'CellEditor'); this.listenTo(model, 'change:' + column.get('name'), function() { if (!$el.hasClass('editor')) { this.render(); } }); this.listenTo(model, 'backgrid:error', this.renderError); this.listenTo(column, 'change:editable change:sortable change:renderable', function(column) { var changed = column.changedAttributes(); for (var key in changed) { if (changed.hasOwnProperty(key)) { $el.toggleClass(key, changed[key]); } } }); /* // These three lines give performance slow down if (Backgrid.callByNeed(column.editable(), column, model)) $el.addClass('editable'); if (Backgrid.callByNeed(column.sortable(), column, model)) $el.addClass('sortable'); if (Backgrid.callByNeed(column.renderable(), column, model)) $el.addClass('renderable'); */ }; /** Render a text string in a table cell. The text is converted from the model's raw value for this cell's column. */ Backgrid.Cell.prototype.render = function() { var $el = this.$el; $el.empty(); var model = this.model; var columnName = this.column.get('name'); $el.text(this.formatter.fromRaw(model.get(columnName), model)); //$el.addClass(columnName); //this.updateStateClassesMaybe(); this.delegateEvents(); return this; }; /** * Event binding on each cell gives perfomance slow down * * Please find support code in ../datagrid/row.js */ Backgrid.Cell.prototype.delegatedEventBinding = true; var oldDelegateEvents = Backgrid.Cell.prototype.delegateEvents; Backgrid.Cell.prototype.delegateEvents = function() { if (_.isFunction(this.events)) { oldDelegateEvents.call(this); } }; var oldUndelegateEvents = Backgrid.Cell.prototype.undelegateEvents; Backgrid.Cell.prototype.undelegateEvents = function() { if (_.isFunction(this.events)) { oldUndelegateEvents.call(this); } }; return Backgrid; });
{ "content_hash": "716d0fb402c472321d04967625fbde1b", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 96, "avg_line_length": 33.32, "alnum_prop": 0.5876350540216086, "repo_name": "Djamy/platform", "id": "82a07e6b32506ffee569bff68adcd8d972803666", "size": "3332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Oro/Bundle/DataGridBundle/Resources/public/js/extend/backgrid.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "542736" }, { "name": "Gherkin", "bytes": "73480" }, { "name": "HTML", "bytes": "1633049" }, { "name": "JavaScript", "bytes": "3284434" }, { "name": "PHP", "bytes": "35536269" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "28544aa6aa55f22e84dc46e8a5a03c52", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "dbf50c4018ce87adfd96e2610682965980e938d8", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Relhania tricephala/ Syn. Polychaetia tricephala/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
title: "004" _template: council _layout: ifvcc-minimal circuitTitle: '4th Judicial Circuit Family Violence Coordinating Council ' counties: Christian, Clay, Clinton, Effingham, Fayette, Jasper, Marion, Montgomery, Shelby leadership: '<ul><li>Hon. James Eder - Chair </li><li>Hon. Ericka Sanders - Vice-Chair</li></ul>' coordinator: | Brenda Benton <br> 27390 W. 4th Street Road<br>Centralia, IL 62801 <br>618-533-1530 <br>Cell 618-292-6477 <br> <a href="mailto:mailto:brenda.benton56@gmail.com">brenda.benton56@gmail.com</a> committees: '<ul><li>Planning/Steering Committee </li><li>Helping Services/Education Committee </li><li>Law Enforcement/OVW Grant Committee </li><li>Common Ground Conference Planning Committee</li></ul>' publications: '<ul><li><a href="/assets/ifvcc/004/4th Circuit FVCC Fact Sheet.pdf">4th Judicial Circuit Family Violence Coordinating Council Fact Sheet</a></li><li><a href="/assets/ifvcc/004/fvccBROCHURE 9-17-14.pub">4th Judicial Circuit Family Violence Coordinating Council Brochure</a></li></ul>' socialMedia: 'Facebook: <a href="https://www.facebook.com/4thJudicialCircuitFVCC?fref=ts" target="_blank">https://www.facebook.com/4thJudicialCircuitFVCC?fref=ts</a>' ---
{ "content_hash": "bfccdcadc23ccd61be425488784808c1", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 298, "avg_line_length": 75.6875, "alnum_prop": 0.7522708505367465, "repo_name": "ICJIA/icjia-public-website", "id": "2fa17b78b04e6769637d1f70af653b98ad65abaf", "size": "1215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_content/97-ifvcc/_86-councils/2016-01-22-004.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "367162" }, { "name": "ColdFusion", "bytes": "738866" }, { "name": "HTML", "bytes": "1336629" }, { "name": "Hack", "bytes": "122" }, { "name": "Java", "bytes": "297102" }, { "name": "JavaScript", "bytes": "2129446" }, { "name": "Less", "bytes": "435531" }, { "name": "PHP", "bytes": "1064934" }, { "name": "PostScript", "bytes": "264446" }, { "name": "Rich Text Format", "bytes": "2495957" }, { "name": "SCSS", "bytes": "171915" }, { "name": "Sass", "bytes": "11555" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Parsonsia induplicata (F.Muell.) Markgr. ### Remarks null
{ "content_hash": "6232018e12e09dcbb28b98de3a5801ed", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 40, "avg_line_length": 12.461538461538462, "alnum_prop": 0.7222222222222222, "repo_name": "mdoering/backbone", "id": "61aeebf6b13a1b19da48c7f13a65b4c7acd1cca3", "size": "223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Parsonsia/Lyonsia induplicata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.24.2'" to load this file. \quit -- HERE goes your code to upgrade/downgrade ---- cdb_geocode_namedplace_point(city_name text) CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_namedplace_point(username text, orgname text, city_name text) RETURNS Geometry AS $$ import spiexceptions try: mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_namedplace($1, $2, $3) as point;", ["text", "text", "text"]) return plpy.execute(mapzen_plan, [username, orgname, city_name])[0]['point'] except spiexceptions.ExternalRoutineException as e: internal_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_internal_geocode_namedplace($1, $2, $3) as point;", ["text", "text", "text"]) return plpy.execute(internal_plan, [username, orgname, city_name])[0]['point'] $$ LANGUAGE plpythonu; ---- cdb_geocode_namedplace_point(city_name text, country_name text) CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_namedplace_point(username text, orgname text, city_name text, country_name text) RETURNS Geometry AS $$ import spiexceptions try: mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_namedplace($1, $2, $3, NULL, $4) as point;", ["text", "text", "text", "text"]) return plpy.execute(mapzen_plan, [username, orgname, city_name, country_name])[0]['point'] except spiexceptions.ExternalRoutineException as e: internal_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_internal_geocode_namedplace($1, $2, $3, NULL, $4) as point;", ["text", "text", "text", "text"]) return plpy.execute(internal_plan, [username, orgname, city_name, country_name])[0]['point'] $$ LANGUAGE plpythonu; ---- cdb_geocode_namedplace_point(city_name text, admin1_name text, country_name text) CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_namedplace_point(username text, orgname text, city_name text, admin1_name text, country_name text) RETURNS Geometry AS $$ import spiexceptions try: mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_namedplace($1, $2, $3, $4, $5) as point;", ["text", "text", "text", "text", "text"]) return plpy.execute(mapzen_plan, [username, orgname, city_name, admin1_name, country_name])[0]['point'] except spiexceptions.ExternalRoutineException as e: internal_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_internal_geocode_namedplace($1, $2, $3, $4, $5) as point;", ["text", "text", "text", "text", "text"]) return plpy.execute(internal_plan, [username, orgname, city_name, admin1_name, country_name])[0]['point'] $$ LANGUAGE plpythonu;
{ "content_hash": "6ad5410c611ad1cc8edc9722d885e324", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 171, "avg_line_length": 71.15789473684211, "alnum_prop": 0.7230029585798816, "repo_name": "CartoDB/geocoder-api", "id": "a1015d31693676b0942b95ef91fc06fce5c70fd5", "size": "2849", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/extension/old_versions/cdb_dataservices_server--0.24.1--0.24.2.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "1972" }, { "name": "Makefile", "bytes": "4323" }, { "name": "PLpgSQL", "bytes": "524518" }, { "name": "Python", "bytes": "94707" }, { "name": "Ruby", "bytes": "1745" }, { "name": "Shell", "bytes": "1105" } ], "symlink_target": "" }
package com.compositesw.services.system.admin.execute; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for executeNativeSqlRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="executeNativeSqlRequest"> * &lt;complexContent> * &lt;extension base="{http://www.compositesw.com/services/system/admin/execute}baseExecuteSqlRequest"> * &lt;sequence> * &lt;element name="dataSourcePath" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "executeNativeSqlRequest", propOrder = { "dataSourcePath" }) public class ExecuteNativeSqlRequest extends BaseExecuteSqlRequest { @XmlElement(required = true) protected String dataSourcePath; /** * Gets the value of the dataSourcePath property. * * @return * possible object is * {@link String } * */ public String getDataSourcePath() { return dataSourcePath; } /** * Sets the value of the dataSourcePath property. * * @param value * allowed object is * {@link String } * */ public void setDataSourcePath(String value) { this.dataSourcePath = value; } }
{ "content_hash": "7db5e87bed5c442ea04d3ef7d372114f", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 108, "avg_line_length": 26.078125, "alnum_prop": 0.6315158777711204, "repo_name": "cisco/PDTool", "id": "1861983a84001c8c487631bb4b2c755171481f27", "size": "1669", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CISAdminApi8.0.0/src/com/compositesw/services/system/admin/execute/ExecuteNativeSqlRequest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "961455" }, { "name": "HTML", "bytes": "844541" }, { "name": "Java", "bytes": "7869304" }, { "name": "Perl", "bytes": "9840" }, { "name": "Python", "bytes": "3299" }, { "name": "Shell", "bytes": "113115" }, { "name": "XSLT", "bytes": "242648" } ], "symlink_target": "" }
//go:build linux // +build linux package kuberuntime import ( "reflect" "strconv" "testing" "github.com/google/go-cmp/cmp" libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1" "k8s.io/kubernetes/pkg/features" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubelettypes "k8s.io/kubernetes/pkg/kubelet/types" ) func makeExpectedConfig(m *kubeGenericRuntimeManager, pod *v1.Pod, containerIndex int, enforceMemoryQoS bool) *runtimeapi.ContainerConfig { container := &pod.Spec.Containers[containerIndex] podIP := "" restartCount := 0 opts, _, _ := m.runtimeHelper.GenerateRunContainerOptions(pod, container, podIP, []string{podIP}) containerLogsPath := buildContainerLogsPath(container.Name, restartCount) restartCountUint32 := uint32(restartCount) envs := make([]*runtimeapi.KeyValue, len(opts.Envs)) l, _ := m.generateLinuxContainerConfig(container, pod, new(int64), "", nil, enforceMemoryQoS) expectedConfig := &runtimeapi.ContainerConfig{ Metadata: &runtimeapi.ContainerMetadata{ Name: container.Name, Attempt: restartCountUint32, }, Image: &runtimeapi.ImageSpec{Image: container.Image}, Command: container.Command, Args: []string(nil), WorkingDir: container.WorkingDir, Labels: newContainerLabels(container, pod), Annotations: newContainerAnnotations(container, pod, restartCount, opts), Devices: makeDevices(opts), Mounts: m.makeMounts(opts, container), LogPath: containerLogsPath, Stdin: container.Stdin, StdinOnce: container.StdinOnce, Tty: container.TTY, Linux: l, Envs: envs, } return expectedConfig } func TestGenerateContainerConfig(t *testing.T) { _, imageService, m, err := createTestRuntimeManager() assert.NoError(t, err) runAsUser := int64(1000) runAsGroup := int64(2000) pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, Command: []string{"testCommand"}, WorkingDir: "testWorkingDir", SecurityContext: &v1.SecurityContext{ RunAsUser: &runAsUser, RunAsGroup: &runAsGroup, }, }, }, }, } expectedConfig := makeExpectedConfig(m, pod, 0, false) containerConfig, _, err := m.generateContainerConfig(&pod.Spec.Containers[0], pod, 0, "", pod.Spec.Containers[0].Image, []string{}, nil) assert.NoError(t, err) assert.Equal(t, expectedConfig, containerConfig, "generate container config for kubelet runtime v1.") assert.Equal(t, runAsUser, containerConfig.GetLinux().GetSecurityContext().GetRunAsUser().GetValue(), "RunAsUser should be set") assert.Equal(t, runAsGroup, containerConfig.GetLinux().GetSecurityContext().GetRunAsGroup().GetValue(), "RunAsGroup should be set") runAsRoot := int64(0) runAsNonRootTrue := true podWithContainerSecurityContext := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, Command: []string{"testCommand"}, WorkingDir: "testWorkingDir", SecurityContext: &v1.SecurityContext{ RunAsNonRoot: &runAsNonRootTrue, RunAsUser: &runAsRoot, }, }, }, }, } _, _, err = m.generateContainerConfig(&podWithContainerSecurityContext.Spec.Containers[0], podWithContainerSecurityContext, 0, "", podWithContainerSecurityContext.Spec.Containers[0].Image, []string{}, nil) assert.Error(t, err) imageID, _ := imageService.PullImage(&runtimeapi.ImageSpec{Image: "busybox"}, nil, nil) resp, _ := imageService.ImageStatus(&runtimeapi.ImageSpec{Image: imageID}, false) resp.Image.Uid = nil resp.Image.Username = "test" podWithContainerSecurityContext.Spec.Containers[0].SecurityContext.RunAsUser = nil podWithContainerSecurityContext.Spec.Containers[0].SecurityContext.RunAsNonRoot = &runAsNonRootTrue _, _, err = m.generateContainerConfig(&podWithContainerSecurityContext.Spec.Containers[0], podWithContainerSecurityContext, 0, "", podWithContainerSecurityContext.Spec.Containers[0].Image, []string{}, nil) assert.Error(t, err, "RunAsNonRoot should fail for non-numeric username") } func TestGenerateLinuxContainerConfigResources(t *testing.T) { _, _, m, err := createTestRuntimeManager() m.cpuCFSQuota = true assert.NoError(t, err) tests := []struct { name string podResources v1.ResourceRequirements expected *runtimeapi.LinuxContainerResources }{ { name: "Request 128M/1C, Limit 256M/3C", podResources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("128Mi"), v1.ResourceCPU: resource.MustParse("1"), }, Limits: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("256Mi"), v1.ResourceCPU: resource.MustParse("3"), }, }, expected: &runtimeapi.LinuxContainerResources{ CpuPeriod: 100000, CpuQuota: 300000, CpuShares: 1024, MemoryLimitInBytes: 256 * 1024 * 1024, }, }, { name: "Request 128M/2C, No Limit", podResources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("128Mi"), v1.ResourceCPU: resource.MustParse("2"), }, }, expected: &runtimeapi.LinuxContainerResources{ CpuPeriod: 100000, CpuQuota: 0, CpuShares: 2048, MemoryLimitInBytes: 0, }, }, } for _, test := range tests { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, Command: []string{"testCommand"}, WorkingDir: "testWorkingDir", Resources: test.podResources, }, }, }, } linuxConfig, err := m.generateLinuxContainerConfig(&pod.Spec.Containers[0], pod, new(int64), "", nil, false) assert.NoError(t, err) assert.Equal(t, test.expected.CpuPeriod, linuxConfig.GetResources().CpuPeriod, test.name) assert.Equal(t, test.expected.CpuQuota, linuxConfig.GetResources().CpuQuota, test.name) assert.Equal(t, test.expected.CpuShares, linuxConfig.GetResources().CpuShares, test.name) assert.Equal(t, test.expected.MemoryLimitInBytes, linuxConfig.GetResources().MemoryLimitInBytes, test.name) } } func TestCalculateLinuxResources(t *testing.T) { _, _, m, err := createTestRuntimeManager() m.cpuCFSQuota = true assert.NoError(t, err) tests := []struct { name string cpuReq resource.Quantity cpuLim resource.Quantity memLim resource.Quantity expected *runtimeapi.LinuxContainerResources }{ { name: "Request128MBLimit256MB", cpuReq: resource.MustParse("1"), cpuLim: resource.MustParse("2"), memLim: resource.MustParse("128Mi"), expected: &runtimeapi.LinuxContainerResources{ CpuPeriod: 100000, CpuQuota: 200000, CpuShares: 1024, MemoryLimitInBytes: 134217728, }, }, { name: "RequestNoMemory", cpuReq: resource.MustParse("2"), cpuLim: resource.MustParse("8"), memLim: resource.MustParse("0"), expected: &runtimeapi.LinuxContainerResources{ CpuPeriod: 100000, CpuQuota: 800000, CpuShares: 2048, MemoryLimitInBytes: 0, }, }, } for _, test := range tests { linuxContainerResources := m.calculateLinuxResources(&test.cpuReq, &test.cpuLim, &test.memLim) assert.Equal(t, test.expected, linuxContainerResources) } } func TestGenerateContainerConfigWithMemoryQoSEnforced(t *testing.T) { _, _, m, err := createTestRuntimeManager() assert.NoError(t, err) pod1 := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, Command: []string{"testCommand"}, WorkingDir: "testWorkingDir", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("128Mi"), }, Limits: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("256Mi"), }, }, }, }, }, } pod2 := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "foo", Image: "busybox", ImagePullPolicy: v1.PullIfNotPresent, Command: []string{"testCommand"}, WorkingDir: "testWorkingDir", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceMemory: resource.MustParse("128Mi"), }, }, }, }, }, } memoryNodeAllocatable := resource.MustParse(fakeNodeAllocatableMemory) pod2MemoryHigh := float64(memoryNodeAllocatable.Value()) * m.memoryThrottlingFactor type expectedResult struct { containerConfig *runtimeapi.LinuxContainerConfig memoryLow int64 memoryHigh int64 } l1, _ := m.generateLinuxContainerConfig(&pod1.Spec.Containers[0], pod1, new(int64), "", nil, true) l2, _ := m.generateLinuxContainerConfig(&pod2.Spec.Containers[0], pod2, new(int64), "", nil, true) tests := []struct { name string pod *v1.Pod expected *expectedResult }{ { name: "Request128MBLimit256MB", pod: pod1, expected: &expectedResult{ l1, 128 * 1024 * 1024, int64(float64(256*1024*1024) * m.memoryThrottlingFactor), }, }, { name: "Request128MBWithoutLimit", pod: pod2, expected: &expectedResult{ l2, 128 * 1024 * 1024, int64(pod2MemoryHigh), }, }, } for _, test := range tests { linuxConfig, err := m.generateLinuxContainerConfig(&test.pod.Spec.Containers[0], test.pod, new(int64), "", nil, true) assert.NoError(t, err) assert.Equal(t, test.expected.containerConfig, linuxConfig, test.name) assert.Equal(t, linuxConfig.GetResources().GetUnified()["memory.min"], strconv.FormatInt(test.expected.memoryLow, 10), test.name) assert.Equal(t, linuxConfig.GetResources().GetUnified()["memory.high"], strconv.FormatInt(test.expected.memoryHigh, 10), test.name) } } func TestGetHugepageLimitsFromResources(t *testing.T) { var baseHugepage []*runtimeapi.HugepageLimit // For each page size, limit to 0. for _, pageSize := range libcontainercgroups.HugePageSizes() { baseHugepage = append(baseHugepage, &runtimeapi.HugepageLimit{ PageSize: pageSize, Limit: uint64(0), }) } tests := []struct { name string resources v1.ResourceRequirements expected []*runtimeapi.HugepageLimit }{ { name: "Success2MB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "hugepages-2Mi": resource.MustParse("2Mi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "2MB", Limit: 2097152, }, }, }, { name: "Success1GB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "hugepages-1Gi": resource.MustParse("2Gi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "1GB", Limit: 2147483648, }, }, }, { name: "Skip2MB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "hugepages-2MB": resource.MustParse("2Mi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "2MB", Limit: 0, }, }, }, { name: "Skip1GB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "hugepages-1GB": resource.MustParse("2Gi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "1GB", Limit: 0, }, }, }, { name: "Success2MBand1GB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceName(v1.ResourceCPU): resource.MustParse("0"), "hugepages-2Mi": resource.MustParse("2Mi"), "hugepages-1Gi": resource.MustParse("2Gi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "2MB", Limit: 2097152, }, { PageSize: "1GB", Limit: 2147483648, }, }, }, { name: "Skip2MBand1GB", resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceName(v1.ResourceCPU): resource.MustParse("0"), "hugepages-2MB": resource.MustParse("2Mi"), "hugepages-1GB": resource.MustParse("2Gi"), }, }, expected: []*runtimeapi.HugepageLimit{ { PageSize: "2MB", Limit: 0, }, { PageSize: "1GB", Limit: 0, }, }, }, } for _, test := range tests { // Validate if machine supports hugepage size that used in test case. machineHugepageSupport := true for _, hugepageLimit := range test.expected { hugepageSupport := false for _, pageSize := range libcontainercgroups.HugePageSizes() { if pageSize == hugepageLimit.PageSize { hugepageSupport = true break } } if !hugepageSupport { machineHugepageSupport = false break } } // Case of machine can't support hugepage size if !machineHugepageSupport { continue } expectedHugepages := baseHugepage for _, hugepage := range test.expected { for _, expectedHugepage := range expectedHugepages { if expectedHugepage.PageSize == hugepage.PageSize { expectedHugepage.Limit = hugepage.Limit } } } results := GetHugepageLimitsFromResources(test.resources) if !reflect.DeepEqual(expectedHugepages, results) { t.Errorf("%s test failed. Expected %v but got %v", test.name, expectedHugepages, results) } for _, hugepage := range baseHugepage { hugepage.Limit = uint64(0) } } } func TestGenerateLinuxContainerConfigNamespaces(t *testing.T) { _, _, m, err := createTestRuntimeManager() if err != nil { t.Fatalf("error creating test RuntimeManager: %v", err) } for _, tc := range []struct { name string pod *v1.Pod target *kubecontainer.ContainerID want *runtimeapi.NamespaceOption }{ { "Default namespaces", &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: "test"}, }, }, }, nil, &runtimeapi.NamespaceOption{ Pid: runtimeapi.NamespaceMode_CONTAINER, }, }, { "PID Namespace POD", &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: "test"}, }, ShareProcessNamespace: &[]bool{true}[0], }, }, nil, &runtimeapi.NamespaceOption{ Pid: runtimeapi.NamespaceMode_POD, }, }, { "PID Namespace TARGET", &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: "test"}, }, }, }, &kubecontainer.ContainerID{Type: "docker", ID: "really-long-id-string"}, &runtimeapi.NamespaceOption{ Pid: runtimeapi.NamespaceMode_TARGET, TargetId: "really-long-id-string", }, }, } { t.Run(tc.name, func(t *testing.T) { got, err := m.generateLinuxContainerConfig(&tc.pod.Spec.Containers[0], tc.pod, nil, "", tc.target, false) assert.NoError(t, err) if diff := cmp.Diff(tc.want, got.SecurityContext.NamespaceOptions); diff != "" { t.Errorf("%v: diff (-want +got):\n%v", t.Name(), diff) } }) } } func TestGenerateLinuxContainerConfigSwap(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.NodeSwap, true)() _, _, m, err := createTestRuntimeManager() if err != nil { t.Fatalf("error creating test RuntimeManager: %v", err) } m.machineInfo.MemoryCapacity = 1000000 containerName := "test" for _, tc := range []struct { name string swapSetting string pod *v1.Pod expected int64 }{ { name: "config unset, memory limit set", // no swap setting pod: &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{{ Name: containerName, Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "memory": resource.MustParse("1000"), }, Requests: v1.ResourceList{ "memory": resource.MustParse("1000"), }, }, }}, }, }, expected: 1000, }, { name: "config unset, no memory limit", // no swap setting pod: &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: containerName}, }, }, }, expected: 0, }, { // Note: behaviour will be the same as previous two cases name: "config set to LimitedSwap, memory limit set", swapSetting: kubelettypes.LimitedSwap, pod: &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{{ Name: containerName, Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ "memory": resource.MustParse("1000"), }, Requests: v1.ResourceList{ "memory": resource.MustParse("1000"), }, }, }}, }, }, expected: 1000, }, { name: "UnlimitedSwap enabled", swapSetting: kubelettypes.UnlimitedSwap, pod: &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: containerName}, }, }, }, expected: -1, }, } { t.Run(tc.name, func(t *testing.T) { m.memorySwapBehavior = tc.swapSetting actual, err := m.generateLinuxContainerConfig(&tc.pod.Spec.Containers[0], tc.pod, nil, "", nil, false) assert.NoError(t, err) assert.Equal(t, tc.expected, actual.Resources.MemorySwapLimitInBytes, "memory swap config for %s", tc.name) }) } }
{ "content_hash": "11678b6e63b537dc2b72c95022566722", "timestamp": "", "source": "github", "line_count": 669, "max_line_length": 206, "avg_line_length": 27.378176382660687, "alnum_prop": 0.6435903035597292, "repo_name": "openshift/kubernetes", "id": "1a50d96143fdfe629e38350e68d5520a4dec8025", "size": "18885", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "pkg/kubelet/kuberuntime/kuberuntime_container_linux_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "833" }, { "name": "C", "bytes": "3902" }, { "name": "Dockerfile", "bytes": "49999" }, { "name": "Go", "bytes": "63044202" }, { "name": "HTML", "bytes": "128" }, { "name": "Makefile", "bytes": "64400" }, { "name": "PowerShell", "bytes": "144474" }, { "name": "Python", "bytes": "23849" }, { "name": "Shell", "bytes": "1942079" }, { "name": "sed", "bytes": "1262" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/view_nav_bar"/> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="wrap_content"/> </ScrollView> </LinearLayout>
{ "content_hash": "de234f01c7eb7800f5eeaa981f37f965", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 30.8, "alnum_prop": 0.6493506493506493, "repo_name": "xebia-france/quiz-android", "id": "81b5abf6041332ac625c34f81c28d5020b7b06f7", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/app/src/main/res/layout/activity_quiz.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "575" }, { "name": "HTML", "bytes": "1769" }, { "name": "Java", "bytes": "32188" }, { "name": "JavaScript", "bytes": "5339" } ], "symlink_target": "" }
\hypertarget{namespaceodf_1_1odf2xhtml}{\section{odf.\+odf2xhtml Namespace Reference} \label{namespaceodf_1_1odf2xhtml}\index{odf.\+odf2xhtml@{odf.\+odf2xhtml}} } \subsection*{Classes} \begin{DoxyCompactItemize} \item class \hyperlink{classodf_1_1odf2xhtml_1_1ODF2XHTML}{O\+D\+F2\+X\+H\+T\+M\+L} \begin{DoxyCompactList}\small\item\em The \hyperlink{classodf_1_1odf2xhtml_1_1ODF2XHTML}{O\+D\+F2\+X\+H\+T\+M\+L} parses an O\+D\+F file and produces X\+H\+T\+M\+L. \end{DoxyCompactList}\item class \hyperlink{classodf_1_1odf2xhtml_1_1ODF2XHTMLembedded}{O\+D\+F2\+X\+H\+T\+M\+Lembedded} \begin{DoxyCompactList}\small\item\em The \hyperlink{classodf_1_1odf2xhtml_1_1ODF2XHTML}{O\+D\+F2\+X\+H\+T\+M\+L} parses an O\+D\+F file and produces X\+H\+T\+M\+L. \end{DoxyCompactList}\item class \hyperlink{classodf_1_1odf2xhtml_1_1StyleToCSS}{Style\+To\+C\+S\+S} \begin{DoxyCompactList}\small\item\em The purpose of the \hyperlink{classodf_1_1odf2xhtml_1_1StyleToCSS}{Style\+To\+C\+S\+S} class is to contain the rules to convert O\+D\+F styles to C\+S\+S2. \end{DoxyCompactList}\item class \hyperlink{classodf_1_1odf2xhtml_1_1TagStack}{Tag\+Stack} \end{DoxyCompactItemize} \subsection*{Variables} \begin{DoxyCompactItemize} \item dictionary \hyperlink{namespaceodf_1_1odf2xhtml_a45771f201b4cf26ab88c538306808fd7}{special\+\_\+styles} \end{DoxyCompactItemize} \subsection{Variable Documentation} \hypertarget{namespaceodf_1_1odf2xhtml_a45771f201b4cf26ab88c538306808fd7}{\index{odf\+::odf2xhtml@{odf\+::odf2xhtml}!special\+\_\+styles@{special\+\_\+styles}} \index{special\+\_\+styles@{special\+\_\+styles}!odf\+::odf2xhtml@{odf\+::odf2xhtml}} \subsubsection[{special\+\_\+styles}]{\setlength{\rightskip}{0pt plus 5cm}dictionary odf.\+odf2xhtml.\+special\+\_\+styles}}\label{namespaceodf_1_1odf2xhtml_a45771f201b4cf26ab88c538306808fd7} {\bfseries Initial value\+:} \begin{DoxyCode} 1 = \{ 2 \textcolor{stringliteral}{'S-Emphasis'}:\textcolor{stringliteral}{'em'}, 3 \textcolor{stringliteral}{'S-Citation'}:\textcolor{stringliteral}{'cite'}, 4 \textcolor{stringliteral}{'S-Strong\_20\_Emphasis'}:\textcolor{stringliteral}{'strong'}, 5 \textcolor{stringliteral}{'S-Variable'}:\textcolor{stringliteral}{'var'}, 6 \textcolor{stringliteral}{'S-Definition'}:\textcolor{stringliteral}{'dfn'}, 7 \textcolor{stringliteral}{'S-Teletype'}:\textcolor{stringliteral}{'tt'}, 8 \textcolor{stringliteral}{'P-Heading\_20\_1'}:\textcolor{stringliteral}{'h1'}, 9 \textcolor{stringliteral}{'P-Heading\_20\_2'}:\textcolor{stringliteral}{'h2'}, 10 \textcolor{stringliteral}{'P-Heading\_20\_3'}:\textcolor{stringliteral}{'h3'}, 11 \textcolor{stringliteral}{'P-Heading\_20\_4'}:\textcolor{stringliteral}{'h4'}, 12 \textcolor{stringliteral}{'P-Heading\_20\_5'}:\textcolor{stringliteral}{'h5'}, 13 \textcolor{stringliteral}{'P-Heading\_20\_6'}:\textcolor{stringliteral}{'h6'}, 14 \textcolor{comment}{# 'P-Caption':'caption',} 15 \textcolor{stringliteral}{'P-Addressee'}:\textcolor{stringliteral}{'address'}, 16 \textcolor{comment}{# 'P-List\_20\_Heading':'dt',} 17 \textcolor{comment}{# 'P-List\_20\_Contents':'dd',} 18 \textcolor{stringliteral}{'P-Preformatted\_20\_Text'}:\textcolor{stringliteral}{'pre'}, 19 \textcolor{comment}{# 'P-Table\_20\_Heading':'th',} 20 \textcolor{comment}{# 'P-Table\_20\_Contents':'td',} 21 \textcolor{comment}{# 'P-Text\_20\_body':'p'} 22 \} \end{DoxyCode} Definition at line 332 of file odf2xhtml.\+py.
{ "content_hash": "5f687345b56c928616048a8ead46385a", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 221, "avg_line_length": 63.888888888888886, "alnum_prop": 0.7226086956521739, "repo_name": "bossvn/odfpy", "id": "13192ec89a008d0945499189a910c3f08854ff38", "size": "3450", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/latex/namespaceodf_1_1odf2xhtml.tex", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groff", "bytes": "87314" }, { "name": "Makefile", "bytes": "9416" }, { "name": "Python", "bytes": "968475" }, { "name": "Shell", "bytes": "186" }, { "name": "Web Ontology Language", "bytes": "8434" }, { "name": "XSLT", "bytes": "31981" } ], "symlink_target": "" }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Mozu.Api.Contracts.Fulfillment { /// <summary> /// /// </summary> [DataContract] public class DashboardResponse { /// <summary> /// Gets or Sets ShipmentType /// </summary> [DataMember(Name="shipmentType", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentType")] public string ShipmentType { get; set; } /// <summary> /// Gets or Sets ShipmentTypeDisplayName /// </summary> [DataMember(Name="shipmentTypeDisplayName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentTypeDisplayName")] public string ShipmentTypeDisplayName { get; set; } /// <summary> /// Gets or Sets Steps /// </summary> [DataMember(Name="steps", EmitDefaultValue=false)] [JsonProperty(PropertyName = "steps")] public List<DashboardStep> Steps { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DashboardResponse {\n"); sb.Append(" ShipmentType: ").Append(ShipmentType).Append("\n"); sb.Append(" ShipmentTypeDisplayName: ").Append(ShipmentTypeDisplayName).Append("\n"); sb.Append(" Steps: ").Append(Steps).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
{ "content_hash": "5e5a04b2c03588c16d9176f515f4f292", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 92, "avg_line_length": 30.433333333333334, "alnum_prop": 0.6588170865279299, "repo_name": "Mozu/mozu-dotnet", "id": "c96e0c901837848a439ff27bc3ccc08481f6933e", "size": "1826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mozu.Api/Contracts/Fulfillment/DashboardResponse.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "279" }, { "name": "C#", "bytes": "8160653" }, { "name": "F#", "bytes": "1750" }, { "name": "PowerShell", "bytes": "3311" } ], "symlink_target": "" }