code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.example.kb.clearsky.model.api_specific; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class WeatherDescription { @SerializedName("id") @Expose private Integer weatherID; @SerializedName("main") @Expose private String mainCategory; @SerializedName("description") @Expose private String description; @SerializedName("icon") @Expose private String iconCode; public Integer getWeatherID() { return weatherID; } public void setWeatherID(Integer weatherID) { this.weatherID = weatherID; } public String getMainCategory() { return mainCategory; } public void setMainCategory(String mainCategory) { this.mainCategory = mainCategory; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIconCode() { return iconCode; } public void setIconCode(String iconCode) { this.iconCode = iconCode; } }
kolboch/ClearSkyApp
app/src/main/java/com/example/kb/clearsky/model/api_specific/WeatherDescription.java
Java
mit
1,145
// Generated on 2014-07-03 using // generator-webapp 0.5.0-rc.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // If you want to recursively match all subfolders, use: // 'test/spec/**/*.js' module.exports = function (grunt) { // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Configurable paths var config = { app: 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings config: config, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, js: { files: ['<%= config.app %>/scripts/{,*/}*.js'], tasks: ['jshint'], options: { livereload: true } }, jstest: { files: ['test/spec/{,*/}*.js'], tasks: ['test:watch'] }, gruntfile: { files: ['Gruntfile.js'] }, sass: { files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['sass:server', 'autoprefixer'] }, styles: { files: ['<%= config.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= config.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= config.app %>/images/{,*/}*' ] } }, // The actual grunt server settings connect: { options: { port: 9000, open: true, livereload: 35729, // Change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { middleware: function(connect) { return [ connect.static('.tmp'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, test: { options: { open: false, port: 9001, middleware: function(connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, dist: { options: { base: '<%= config.dist %>', livereload: false } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] }, server: '.tmp' }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= config.app %>/scripts/{,*/}*.js', '!<%= config.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, // Mocha testing framework configuration options mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html'] } } }, // Compiles Sass to CSS and generates necessary files if requested sass: { options: { sourcemap: true, loadPath: 'bower_components' }, dist: { files: [{ expand: true, cwd: '<%= config.app %>/styles', src: ['*.{scss,sass}'], dest: '.tmp/styles', ext: '.css' }] }, server: { files: [{ expand: true, cwd: '<%= config.app %>/styles', src: ['*.{scss,sass}'], dest: '.tmp/styles', ext: '.css' }] } }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the HTML file wiredep: { app: { ignorePath: new RegExp('^<%= config.app %>/|../'), src: ['<%= config.app %>/index.html'], }, sass: { src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'], ignorePath: /(\.\.\/){1,2}bower_components\// } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= config.dist %>/scripts/{,*/}*.js', '<%= config.dist %>/styles/{,*/}*.css', '<%= config.dist %>/images/{,*/}*.*', '<%= config.dist %>/styles/fonts/{,*/}*.*', '<%= config.dist %>/*.{ico,png}' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { options: { dest: '<%= config.dist %>' }, html: '<%= config.app %>/index.html' }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { options: { assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images'] }, html: ['<%= config.dist %>/{,*/}*.html'], css: ['<%= config.dist %>/styles/{,*/}*.css'] }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.{gif,jpeg,jpg,png}', dest: '<%= config.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.svg', dest: '<%= config.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeCommentsFromCDATA: true, removeEmptyAttributes: true, removeOptionalTags: true, removeRedundantAttributes: true, useShortDoctype: true }, files: [{ expand: true, cwd: '<%= config.dist %>', src: '{,*/}*.html', dest: '<%= config.dist %>' }] } }, // By default, your `index.html`'s <!-- Usemin block --> will take care // of minification. These next options are pre-configured if you do not // wish to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= config.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= config.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= config.dist %>/scripts/scripts.js': [ // '<%= config.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'images/{,*/}*.webp', '{,*/}*.html', 'styles/fonts/{,*/}*.*', 'fonts/{,*/}*.*' ] }, { expand: true, cwd: 'bower_components/Leaflet.awesome-markers/dist/images/', src: ['**'], dest: '<%= config.dist %>/styles/images' }, { expand: true, cwd: 'bower_components/font-awesome/fonts/', src: ['**'], dest: '<%= config.dist %>/fonts' } ] }, styles: { expand: true, dot: true, cwd: '<%= config.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Generates a custom Modernizr build that includes only the tests you // reference in your app modernizr: { dist: { devFile: 'bower_components/modernizr/modernizr.js', outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js', files: { src: [ '<%= config.dist %>/scripts/{,*/}*.js', '<%= config.dist %>/styles/{,*/}*.css', '!<%= config.dist %>/scripts/vendor/*' ] }, uglify: true } }, // Run some tasks in parallel to speed up build process concurrent: { server: [ 'sass:server', 'copy:styles' ], test: [ 'copy:styles' ], dist: [ 'sass', 'copy:styles', 'imagemin', 'svgmin' ] } }); grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) { if (grunt.option('allow-remote')) { grunt.config.set('connect.options.hostname', '0.0.0.0'); } if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', function (target) { if (target !== 'watch') { grunt.task.run([ 'clean:server', 'concurrent:test', 'autoprefixer' ]); } grunt.task.run([ 'connect:test', 'mocha' ]); }); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'cssmin', 'uglify', 'copy:dist', 'modernizr', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', //'test', 'build' ]); };
openchattanooga/chattanooga-bike-parking-locator
Gruntfile.js
JavaScript
mit
10,821
package no.westerdals.eksamen.app2; import android.content.DialogInterface; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import no.westerdals.eksamen.app2.Model.User; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private FirebaseAuth mAuth; private DatabaseReference mDatabase; EditText editTextUser; EditText editTextPass; Button loginButton; TextView signUpLink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); editTextUser = (EditText) findViewById(R.id.email_address); editTextPass = (EditText) findViewById(R.id.password_edit_text); loginButton = (Button) findViewById(R.id.btn_login); loginButton.setOnClickListener(this); signUpLink = (TextView) findViewById(R.id.link_signup); signUpLink.setOnClickListener(this); mDatabase = FirebaseDatabase.getInstance().getReference(); mAuth = FirebaseAuth.getInstance(); } @Override public void onStart() { super.onStart(); FirebaseUser currentUser = mAuth.getCurrentUser(); //opens main activity if already signed in if (currentUser != null) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); LoginActivity.this.startActivity(intent); finish(); } } private void signIn(String email, String password) { if (!validateForm()) { return; } mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { //FirebaseUser user = mAuth.getCurrentUser(); Intent intent = new Intent(LoginActivity.this, MainActivity.class); LoginActivity.this.startActivity(intent); } else { Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } /** * Signup is only with username and password. * Room number will be connected to user id in the reception. */ private void createAccount(String email, String password) { mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(LoginActivity.this, "User: " + user.getEmail() + " created", Toast.LENGTH_SHORT).show(); registerUserDetails(user); } else { // If sign in fails, display a message to the user. Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } private void registerUserDetails(FirebaseUser user) { writeNewUser(user.getUid(), user.getEmail(), ""); } private void writeNewUser(String userId, String email, String roomNumber) { User user = new User(email, roomNumber); mDatabase.child("users").child(userId).setValue(user); } //TODO: make better validation on email etc private boolean validateForm() { boolean validLogin = true; String email = editTextUser.getText().toString(); String password = editTextPass.getText().toString(); if (TextUtils.isEmpty(email)) { editTextUser.setError("Email address is required"); validLogin = false; } else editTextUser.setError(null); if (TextUtils.isEmpty(password)) { editTextPass.setError(" Password is required"); validLogin = false; } else editTextPass.setError(null); return validLogin; } @Override public void onClick(View v) { if (v.getId() == R.id.btn_login) { signIn(editTextUser.getText().toString(), editTextPass.getText().toString()); } else if (v.getId() == R.id.link_signup) { //createAccount(editTextUser.getText().toString(), editTextPass.getText().toString()); signupForm(); } } public void signupForm() { final AlertDialog.Builder signUpDialog = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.sign_up_form,(ViewGroup) findViewById(R.id.sign_up_form)); signUpDialog.setView(layout); final EditText emailAddress = (EditText) layout.findViewById(R.id.email_address); final EditText repeatEmailAddress = (EditText) layout.findViewById(R.id.repeat_email_address); final EditText password = (EditText) layout.findViewById(R.id.password_edit_text); final EditText repeatPassword = (EditText) layout.findViewById(R.id.repeat_password_edit_text); Button button = (Button) layout.findViewById(R.id.btn_sign_up); signUpDialog.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); signUpDialog.create(); final AlertDialog d = signUpDialog.show(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(validateSignUpForm(password, repeatPassword, emailAddress, repeatEmailAddress)) { createAccount(emailAddress.getText().toString(), password.getText().toString()); d.dismiss(); } } }); } private boolean validateSignUpForm(EditText password, EditText repeatPassword, EditText emailAdress, EditText repeatEmailAdress){ boolean validated = true; if (!TextUtils.equals(password.getText(), repeatPassword.getText())){ password.setError("Passwords not matching"); repeatPassword.setError("Passwords not matching"); validated = false; } else if(TextUtils.isEmpty(password.getText())){ password.setError("Cannot be empty"); validated = false; }else if(TextUtils.isEmpty(repeatPassword.getText())){ repeatPassword.setError("Cannot be empty"); validated = false; } else { password.setError(null); repeatPassword.setError(null); } if (!TextUtils.equals(emailAdress.getText(), repeatEmailAdress.getText())){ emailAdress.setError("Email not matching"); repeatEmailAdress.setError("Email not matching"); validated = false; } else if(TextUtils.isEmpty(emailAdress.getText())){ emailAdress.setError("Cannot be empty"); validated = false; }else if(TextUtils.isEmpty(repeatEmailAdress.getText())){ repeatEmailAdress.setError("Cannot be empty"); validated = false; } else { emailAdress.setError(null); repeatEmailAdress.setError(null); } return validated; } }
Mariusrik/schoolprojects
Mobil utvikling eksamen/hotelapplikasjon/src/main/java/no/westerdals/eksamen/app2/LoginActivity.java
Java
mit
8,745
import should from 'should'; import Schema from '../../src/schema'; const SIMPEL_OBJECT = { type: 'object', properties: { name: { type: 'string' } } }; describe('Schema', () => { describe('#getType', () => { it('should return string type for child', () => { const schema = new Schema(SIMPEL_OBJECT); schema.getType('name').should.equal('string'); }); }); describe('#isObject', () => { it('should return true with no path', () => { const schema = new Schema(SIMPEL_OBJECT); const r = schema.isObject(); r.should.equal(true); }); it('should return false with name path', () => { const schema = new Schema(SIMPEL_OBJECT); const r = schema.isObject('name'); r.should.equal(false); }); }); describe('#getProperties', () => { it('should return array with length same as properties', () => { const schema = new Schema(SIMPEL_OBJECT); const r = schema.getProperties(); Object.keys(r).length.should.equal(1); }); }); });
surikaterna/formr
test/schema/schema.js
JavaScript
mit
1,034
<?php namespace CE\UserBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('CEUserBundle:Default:index.html.twig', array('name' => $name)); } }
akraxx/site-ce
src/CE/UserBundle/Controller/DefaultController.php
PHP
mit
295
<?php namespace siigap\FichasBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use siigap\FichasBundle\Form\ConsultaPersonasType; use siigap\FichasBundle\Form\ConsultaViviendasType; use siigap\FichasBundle\Form\ConsultaFichasType; class ConsultasController extends Controller { public function consultaFichasAction(Request $request) { $form = $this->createForm(new ConsultaFichasType(), array()); return $this->render('siigapFichasBundle:Consultas:consultaFichas.html.twig', array('form'=>$form->createView())); } public function consultaFichasShowAction(Request $request) { $form = $this->createForm(new ConsultaFichasType(), array()); $form->handleRequest($request); if ($form->isValid()) { $results = $this->getDoctrine()->getRepository('siigapMainBundle:TsgFichasIdentificacion')->getFiltroFichas($form, $this->getUser()->getGobierno()); return $this->render('siigapFichasBundle:Consultas:consultaFichasShow.html.twig', array( 'datos' => $results['resultQuery'] )); } else { $errors = array(); $errors[]['message'] = 'Se ha producido un error desconocido. Es probable una manipulaci&oacute;n deliberada de los datos. '.$form->getErrorsAsString(); return $this->render('siigapMainBundle:Default:errores.html.twig', array('errors'=>$errors)); } } public function consultaViviendasAction(Request $request) { $options = array('codigoGeografico'=>$this->getUser()->getGobierno()->getCodigoGeografico()); $form = $this->createForm(new ConsultaViviendasType($options), array()); return $this->render('siigapFichasBundle:Consultas:consultaViviendas.html.twig', array('form'=>$form->createView())); } public function consultaViviendasShowAction(Request $request) { $options = array('codigoGeografico'=>$this->getUser()->getGobierno()->getCodigoGeografico()); $form = $this->createForm(new ConsultaViviendasType($options), array()); $form->handleRequest($request); if ($form->isValid()) { $results = $this->getDoctrine()->getRepository('siigapMainBundle:TsgViviendas')->getFiltroViviendas($form, $this->getUser()->getGobierno()); $datos = array(); $i = 0; foreach($results['resultQuery'] as $dato) { $datos[$i]['codigoVivienda'] = $dato->getCodigoVivienda(); $datos[$i]['geograficoMinimo'] = $dato->getGeograficoMinimo();//$this->getLocalidadMinima($dato->getGeograficoMinimo()); $datos[$i]['tipoConstruccion'] = $dato->getTipoConstruccion(); $datos[$i]['esMiduvi'] = ($dato->getEsMiduvi()) ? 'SI' : 'NO'; $datos[$i]['totalPersonas'] = count($dato->getPersonas()); $datos[$i]['idFicha'] = $dato->getFichaIdentificacion()->getId(); $datos[$i]['numeroFicha'] = $dato->getFichaIdentificacion()->getNumeroFicha(); $i++; } return $this->render('siigapFichasBundle:Consultas:consultaViviendasShow.html.twig', array( 'datos' => $datos )); } else { $errors = array(); $errors[]['message'] = 'Se ha producido un error desconocido. Es probable una manipulaci&oacute;n deliberada de los datos. '.$form->getErrorsAsString(); return $this->render('siigapMainBundle:Default:errores.html.twig', array('errors'=>$errors)); } } private function getLocalidadMinima($geograficoMinimo) { $result = ''; if ($geograficoMinimo->getPadre()) { $result .= $geograficoMinimo->getPadre()->getNombre(); } if ($geograficoMinimo->getPadre()->getPadre()) { $result .= ' - '.$geograficoMinimo->getPadre()->getPadre()->getNombre(); } $result .= ($result <> '') ? ' - '.$geograficoMinimo->getNombre() : $geograficoMinimo->getNombre(); return $result; } public function consultaPersonasAction(Request $request) { $form = $this->createForm(new ConsultaPersonasType(), array()); return $this->render('siigapFichasBundle:Consultas:consultaPersonas.html.twig', array('form'=>$form->createView())); } public function consultaPersonasShowAction(Request $request) { $form = $this->createForm(new ConsultaPersonasType(), array()); $form->handleRequest($request); if ($form->isValid()) { $results = $this->getDoctrine()->getRepository('siigapMainBundle:TsgPersonasVivienda')->getFiltroPersonas($form, $this->getUser()->getGobierno()); return $this->render('siigapFichasBundle:Consultas:consultaPersonasShow.html.twig', array( 'datos' => $results['resultQuery'] )); } else { $errors = array(); $errors[]['message'] = 'Se ha producido un error desconocido. Es probable una manipulaci&oacute;n deliberada de los datos. '.$form->getErrorsAsString(); return $this->render('siigapMainBundle:Default:errores.html.twig', array('errors'=>$errors)); } } public function consultaGrupoAtencionShowAction(Request $request) { $em = $this->getDoctrine()->getManager(); $nick = $request->get('name'); $grupoAtencion = $this->getDoctrine()->getRepository('siigapMainBundle:TsgGruposAtencion')->findOneByNick($nick); if (!$grupoAtencion) { throw $this->createNotFoundException('No se encontro el grupo de atencion solicitado.'); } $repository = $em->getRepository('siigapMainBundle:TsgPersonasVivienda'); $query = $repository->createQueryBuilder('tsp') ->innerJoin('tsp.grupoAtencion', 'tga') ->where('tga.id = :grupoAtencion')->setParameter('grupoAtencion', $grupoAtencion) ->getQuery(); $datos = $query->getResult(); return $this->render('siigapFichasBundle:Consultas:consultaPersonasShow.html.twig', array( 'datos' => $datos )); } public function consultaFichaCompletaShowAction(Request $request) { $id = $request->get('id'); $fichaIdentificacion = $this->getDoctrine()->getRepository('siigapMainBundle:TsgFichasIdentificacion')->findOneById($id); if (!$fichaIdentificacion) { throw $this->createNotFoundException('No se encontron los datos solicitados.'); } $existeVivienda = ($fichaIdentificacion->getVivienda()) ? true : false; return $this->render('siigapFichasBundle:Consultas:fichaCompletaShow.html.twig', array( 'fichaIdentificacion' => $fichaIdentificacion, 'existeVivienda' => $existeVivienda )); } }
isabelmonterob/iframe
src/siigap/FichasBundle/Controller/ConsultasController.php
PHP
mit
7,249
# lib/sleeping_king_studios/tasks/apps/bundle.rb require 'sleeping_king_studios/tasks/apps' module SleepingKingStudios::Tasks::Apps # Thor tasks for maintaing gem dependencies in semi-distributed applications. module Bundle; end end # module
sleepingkingstudios/sleeping_king_studios-tasks
lib/sleeping_king_studios/tasks/apps/bundle.rb
Ruby
mit
248
//------------------------------------------------------------------------------ // This code was generated by a tool. // // Tool : Bond Compiler 0.9.0.0 // File : DataPoint_types.cs // // Changes to this file may cause incorrect behavior and will be lost when // the code is regenerated. // <auto-generated /> //------------------------------------------------------------------------------ // suppress "Missing XML comment for publicly visible type or member" #pragma warning disable 1591 #region ReSharper warnings // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantUsingDirective #endregion namespace Microsoft.ApplicationInsights.Ingestion.Maestro.Contracts { using System.Collections.Generic; [System.CodeDom.Compiler.GeneratedCode("gbc", "0.9.0.0")] public partial class DataPoint { public string name { get; set; } public DataPointType kind { get; set; } public double value { get; set; } public int? count { get; set; } public double? min { get; set; } public double? max { get; set; } public double? stdDev { get; set; } public DataPoint() : this("AI.DataPoint", "DataPoint") {} protected DataPoint(string fullName, string name) { this.name = ""; kind = DataPointType.Measurement; } } } // AI
SoubhagyaDash/ApplicationInsights-Home
Samples/Mistral/src/maestro/src/Contracts/Generated/DataPoint.cs
C#
mit
1,563
#include "../platform.h" namespace Platform { void sleep(long seconds, long milliseconds) {} //stub int createWindow(char *title, int width, int height, int bpp, bool fullscreen) { return 0; } int closeWindow() { return 0; } void swapBuffers() {} void pump() { //do our work here... } void grabMouse() {} void ungrabMouse() {} void toggleGrabMouse() {} bool getActive() { return true; } void setActive( bool active ) {} void* getWindowHandle() { return (void*)0; } }
bargle/SympEngine
System/Platform/ios/platform.cpp
C++
mit
502
/****************************************************************************************** * Data Structures in C++ * ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3 * Junhui DENG, deng@tsinghua.edu.cn * Computer Science & Technology, Tsinghua University * Copyright (c) 2006-2013. All rights reserved. ******************************************************************************************/ /* * ÉìÕ¹Ê÷ * »ùÓÚBSTreeµÄÀ©³ä */ package dsa; public class SplayTree extends BSTree implements Dictionary { /**************************** ¹¹Ôì·½·¨ ****************************/ public SplayTree() { super(); } public SplayTree(BinTreePosition r) { super(r); } public SplayTree(BinTreePosition r, Comparator c) { super(r, c); } /**************************** ´Êµä·½·¨£¨¸²¸Ç¸¸ÀàBSTree£© ****************************/ //Èô´ÊµäÖдæÔÚÒÔkeyΪ¹Ø¼üÂëµÄÌõÄ¿£¬Ôò·µ»ØÆäÖеÄÒ»¸öÌõÄ¿£»·ñÔò£¬·µ»Ønull public Entry find(Object key) { if (isEmpty()) return null; BSTreeNode u = binSearch((BSTreeNode)root, key, C); root = moveToRoot(u); return (0 == C.compare(key, u.getKey())) ? (Entry)u.getElem() : null; } //²åÈëÌõÄ¿(key, value)£¬²¢·µ»Ø¸ÃÌõÄ¿ public Entry insert(Object key, Object value) { Entry e = super.insert(key, value);//µ÷Óø¸Àà·½·¨Íê³É²åÈë root = moveToRoot(lastV);//ÖØÐÂÆ½ºâ»¯ return e; } //Èô´ÊµäÖдæÔÚÒÔkeyΪ¹Ø¼üÂëµÄÌõÄ¿£¬Ôò½«Õª³ýÆäÖеÄÒ»¸ö²¢·µ»Ø£»·ñÔò£¬·µ»Ønull public Entry remove(Object key) { Entry e = super.remove(key);//µ÷Óø¸Àà·½·¨Íê³Éɾ³ý if (null != e && null != lastV) root = moveToRoot(lastV);//ÖØÐÂÆ½ºâ»¯ return e; } /**************************** ¸¨Öú·½·¨ ****************************/ //´Ó½Úµãz¿ªÊ¼£¬×ÔÉ϶øÏÂÖØÐÂÆ½ºâ»¯ protected static BinTreePosition moveToRoot(BinTreePosition z) { while (z.hasParent()) if (!z.getParent().hasParent()) if (z.isLChild()) z = zig(z); else z = zag(z); else if (z.isLChild()) if (z.getParent().isLChild()) z = zigzig(z); else z = zigzag(z); else if (z.getParent().isLChild()) z = zagzig(z); else z = zagzag(z); return z; } //vΪ×óº¢×Ó //˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÒ»²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zig(BinTreePosition v) { if (null != v && v.isLChild()) {//v±ØÐëÓи¸Ç×£¬¶øÇÒ±ØÐëÊÇ×óº¢×Ó BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ boolean asLChild = p.isLChild();//¸¸Ç×ÊÇ·ñ׿¸¸µÄ×óº¢×Ó v.secede();//Õª³öv£¨ÓÚÊÇpµÄ×óº¢×ÓΪ¿Õ£© BinTreePosition c = v.getRChild();//½«vµÄÓÒº¢×Ó if (null != c) p.attachL(c.secede());//×÷ΪpµÄ×óº¢×Ó p.secede();//Õª³ö¸¸Ç× v.attachR(p);//½«p×÷ΪvµÄÓÒº¢×Ó if (null != g)//Èô׿¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) g.attachL(v); else g.attachR(v); } return v; } //vΪÓÒº¢×Ó //ÄæÊ±ÕëÐýתv£¬Ê¹Ö®ÉÏÉýÒ»²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zag(BinTreePosition v) { if (null != v && v.isRChild()) {//v±ØÐëÓи¸Ç×£¬¶øÇÒ±ØÐëÊÇÓÒº¢×Ó BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ boolean asLChild = p.isLChild();//¸¸Ç×ÊÇ·ñ׿¸¸µÄ×óº¢×Ó v.secede();//Õª³öv£¨ÓÚÊÇpµÄ×óº¢×ÓΪ¿Õ£© BinTreePosition c = v.getLChild();//½«vµÄ×óº¢×Ó if (null != c) p.attachR(c.secede());//×÷ΪpµÄÓÒº¢×Ó p.secede();//Õª³ö¸¸Ç× v.attachL(p);//½«p×÷ΪvµÄ×óº¢×Ó if (null != g)//Èô׿¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) g.attachL(v); else g.attachR(v); } return v; } //vΪ×óº¢×Ó£¬¸¸Ç×Ϊ×óº¢×Ó //˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zigzig(BinTreePosition v) { if (null != v && v.isLChild() && v.hasParent() && v.getParent().isLChild()) { BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ BinTreePosition s = g.getParent();//Ôø×æ¸¸ boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó g.secede(); p.secede(); v.secede(); BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯ c = p.getRChild(); if (null != c) g.attachL(c.secede());//pµÄÓÒº¢×Ó×÷ΪgµÄ×óº¢×Ó c = v.getRChild(); if (null != c) p.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪpµÄ×óº¢×Ó p.attachR(g);//g×÷ΪpµÄÓÒº¢×Ó v.attachR(p);//p×÷ΪvµÄÓÒº¢×Ó if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) s.attachL(v); else s.attachR(v); } return v; } //vΪÓÒº¢×Ó£¬¸¸Ç×ΪÓÒº¢×Ó //˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zagzag(BinTreePosition v) { if (null != v && v.isRChild() && v.hasParent() && v.getParent().isRChild()) { BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ BinTreePosition s = g.getParent();//Ôø×æ¸¸ boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó g.secede(); p.secede(); v.secede(); BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯ c = p.getLChild(); if (null != c) g.attachR(c.secede());//pµÄ×óº¢×Ó×÷ΪgµÄÓÒº¢×Ó c = v.getLChild(); if (null != c) p.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪpµÄÓÒº¢×Ó p.attachL(g);//g×÷ΪpµÄ×óº¢×Ó v.attachL(p);//p×÷ΪvµÄ×óº¢×Ó if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) s.attachL(v); else s.attachR(v); } return v; } //vΪ×óº¢×Ó£¬¸¸Ç×ΪÓÒº¢×Ó //˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zigzag(BinTreePosition v) { if (null != v && v.isLChild() && v.hasParent() && v.getParent().isRChild()) { BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ BinTreePosition s = g.getParent();//Ôø×æ¸¸ boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó g.secede(); p.secede(); v.secede(); BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯ c = v.getLChild(); if (null != c) g.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪgµÄÓÒº¢×Ó c = v.getRChild(); if (null != c) p.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪpµÄ×óº¢×Ó v.attachL(g);//g×÷ΪvµÄ×óº¢×Ó v.attachR(p);//p×÷ΪvµÄÓÒº¢×Ó if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) s.attachL(v); else s.attachR(v); } return v; } //vΪÓÒº¢×Ó£¬¸¸Ç×Ϊ×óº¢×Ó //˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£© //·µ»ØÐµÄ×ÓÊ÷¸ù protected static BinTreePosition zagzig(BinTreePosition v) { if (null != v && v.isRChild() && v.hasParent() && v.getParent().isLChild()) { BinTreePosition p = v.getParent();//¸¸Ç× BinTreePosition g = p.getParent();//׿¸¸ BinTreePosition s = g.getParent();//Ôø×æ¸¸ boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó g.secede(); p.secede(); v.secede(); BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯ c = v.getRChild(); if (null != c) g.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪgµÄ×óº¢×Ó c = v.getLChild(); if (null != c) p.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪpµÄÓÒº¢×Ó v.attachR(g);//g×÷ΪvµÄÓÒº¢×Ó v.attachL(p);//p×÷ΪvµÄ×óº¢×Ó if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó if (asLChild) s.attachL(v); else s.attachR(v); } return v; } }
0704681032/Java8InAction
清华大学邓俊辉老师数据结构资料/dsa/src/_java/dsa/splaytree.java
Java
mit
8,076
namespace _01.Shapes.Common { using System; public static class Validator { private const int MIN_RANGE = 0; private const string MinRangeMessage = "{0} cannot be less or equal to 0"; public static void CheckIfZero(double element, string message = null) { if (element <= MIN_RANGE) { throw new ArgumentException(string.Format(MinRangeMessage, message)); } } } }
stoyanov7/TelerikAcademy
ProgrammingWithC#/03.C#ObjectOrientedProgramming/05.OOPPrinciplesPart2/Homework/01.Shapes/01.Shapes/Common/Validator.cs
C#
mit
491
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; }
Paralideres/clives
app/Http/Kernel.php
PHP
mit
1,789
module QA module Page module Project module Operations module Kubernetes class AddExisting < Page::Base view 'app/views/projects/clusters/user/_form.html.haml' do element :cluster_name, 'text_field :name' element :api_url, 'text_field :api_url' element :ca_certificate, 'text_area :ca_cert' element :token, 'text_field :token' element :add_cluster_button, "submit s_('ClusterIntegration|Add Kubernetes cluster')" end def set_cluster_name(name) fill_in 'cluster_name', with: name end def set_api_url(api_url) fill_in 'cluster_platform_kubernetes_attributes_api_url', with: api_url end def set_ca_certificate(ca_certificate) fill_in 'cluster_platform_kubernetes_attributes_ca_cert', with: ca_certificate end def set_token(token) fill_in 'cluster_platform_kubernetes_attributes_token', with: token end def add_cluster! click_on 'Add Kubernetes cluster' end end end end end end end
jirutka/gitlabhq
qa/qa/page/project/operations/kubernetes/add_existing.rb
Ruby
mit
1,227
import { key, PLAY, PAUSE, MUTE, UNMUTE, UPDATE_VOLUME, UPDATE_TIME, SET_SONG, SET_TIME, updateTime } from './actions' import { store } from '../store' let audio = new Audio() audio.addEventListener('timeupdate', event => store.dispatch(updateTime(event))) const initialState = { isPlaying: false, muted: false, volume: audio.volume, src: '', currentTime: '', duration: 0.0, completed: 0.0 } export const selectors = { audio: state => state[key].audio } export default function reducer (state = initialState, { type, payload }) { switch (type) { case PLAY: { audio.play() return { ...state, isPlaying: !state.isPlaying } } case PAUSE: { audio.pause() return { ...state, isPlaying: !state.isPlaying } } case MUTE: { audio.muted = true return { ...state, muted: true } } case UNMUTE: { audio.muted = false return { ...state, muted: false } } case UPDATE_TIME: { const { currentTime, duration, completed } = payload return { ...state, currentTime, duration, completed } } case UPDATE_VOLUME: { audio.volume = payload return { ...state, volume: payload } } case SET_TIME: { const newCurrentTime = state.currentTime * parseFloat(payload) / 100 audio.currentTime = newCurrentTime return { ...state, currentTime: newCurrentTime } } case SET_SONG: { audio.src = payload return { ...state, src: payload } } default: return state } }
shempignon/podcast-api
app/Resources/js/player/reducer.js
JavaScript
mit
1,630
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcademyEcosystem { public class EngineExtend : Engine { protected override void ExecuteBirthCommand(string[] commandWords) { switch (commandWords[1]) { case "wolf": { string name = commandWords[2]; Point location = Point.Parse(commandWords[3]); Wolf wolf = new Wolf(name, location); this.AddOrganism(wolf); break; } case "lion": { string name = commandWords[2]; Point location = Point.Parse(commandWords[3]); Lion lion = new Lion(name, location); this.AddOrganism(lion); break; } case "grass": { Point location = Point.Parse(commandWords[2]); Grass grass = new Grass(location); this.AddOrganism(grass); break; } case "boar": { string name = commandWords[2]; Point location = Point.Parse(commandWords[3]); Boar boar = new Boar(name, location); this.AddOrganism(boar); break; } case "zombie": { string name = commandWords[2]; Point location = Point.Parse(commandWords[3]); Zombie zombie = new Zombie(name, location); this.AddOrganism(zombie); break; } default: base.ExecuteBirthCommand(commandWords); break; } } } }
MystFan/TelerikAcademy
C# OOP/Exam Preparation/AcademyEcosystem/AcademyEcosystem/EngineExtend.cs
C#
mit
2,108
package simpl.typing; public final class ListType extends Type { public Type t; public ListType(Type t) { this.t = t; } @Override public boolean isEqualityType() { // TODO Done return t.isEqualityType(); } @Override public Substitution unify(Type t) throws TypeError { // TODO Done if (t instanceof TypeVar) { return t.unify(this); } else if (t instanceof ListType) { return this.t.unify(((ListType)t).t); } else { throw new TypeMismatchError(); } } @Override public boolean contains(TypeVar tv) { // TODO Done return t.contains(tv); } @Override public Type replace(TypeVar a, Type t) { // TODO Done return new ListType(this.t.replace(a, t)); } public String toString() { return t + " list"; } @Override public boolean equals(Type t) { if (t instanceof ListType) { return this.t.equals(((ListType)t).t); } return false; } }
MihawkHu/SimPl
src/simpl/typing/ListType.java
Java
mit
1,105
package com.felipecsl.gifimageview.app; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.felipecsl.gifimageview.library.GifImageView; import java.util.List; public class GifGridAdapter extends BaseAdapter { private final Context context; private final List<String> imageUrls; public GifGridAdapter(Context context, List<String> imageUrls) { this.context = context; this.imageUrls = imageUrls; } @Override public int getCount() { return imageUrls.size(); } @Override public Object getItem(int position) { return imageUrls.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final GifImageView imageView; if (convertView == null) { imageView = new GifImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setPadding(10, 10, 10, 10); int size = AbsListView.LayoutParams.WRAP_CONTENT; AbsListView.LayoutParams layoutParams = new GridView.LayoutParams(size, size); imageView.setLayoutParams(layoutParams); } else { imageView = (GifImageView) convertView; imageView.clear(); } new GifDataDownloader() { @Override protected void onPostExecute(final byte[] bytes) { imageView.setBytes(bytes); imageView.startAnimation(); } }.execute(imageUrls.get(position)); return imageView; } }
felipecsl/GifImageView
app/src/main/java/com/felipecsl/gifimageview/app/GifGridAdapter.java
Java
mit
1,665
/* eslint-env mocha */ import expect from 'expect'; import FunctionChecker from '../src/FunctionChecker.js'; import OptionsManager from '../src/OptionsManager.js'; import Structure from '../src/Structure.js'; describe('optionsManager', () => { let manager; beforeEach(() => { manager = new OptionsManager(); }); context('#constructor', () => { it('exposes .typeManager', () => { expect(manager.typeManager).toNotBe(undefined); }); }); context('#structure', () => { it('returns a Structure object', () => { expect(manager.structure('arg1', {type: 'string'})).toBeA(Structure); }); }); context('#check', () => { it('returns a FunctionChecker object', () => { expect(manager.check('customFunc')).toBeA(FunctionChecker); }); }); });
Jerskouille/options-manager
test/OptionsManager.js
JavaScript
mit
800
/** * C++ interface to a python PropertyNode() */ #include "pyprops.h" #include <string> #include <sstream> using std::string; using std::ostringstream; // 'cache' is a global c-string -> python unicode name cache. This // conversion is relatively costly in python3, so this cache save // repeating the work many times each frame. pyAttrCache cache; // Constructor pyPropertyNode::pyPropertyNode() { // printf("pyPropertyNode()\n"); pObj = NULL; } pyPropertyNode::pyPropertyNode(const pyPropertyNode &node) { // printf("visiting pyPropertyNode() copy constructor!\n"); pObj = node.pObj; Py_INCREF(pObj); } pyPropertyNode::pyPropertyNode(PyObject *p) { // printf("pyPropertyNode(pObj)\n"); pObj = p; } // Destructor. pyPropertyNode::~pyPropertyNode() { // printf("~pyPropertyNode destructor\n"); if ( pObj == NULL ) { printf("WARNING: calling destructor on null pyPropertyNode\n"); // Py_DECREF(pObj); } Py_XDECREF(pObj); pObj = NULL; } // Assignment operator pyPropertyNode & pyPropertyNode::operator= (const pyPropertyNode &node) { // printf("Visiting pyPropertyNode operator=\n"); if (this != &node) { // protect against invalid self-assignment if ( pObj != NULL ) { // 1: decrement current pObj reference because we are losing it // printf("decrementing existing pObj before overwritting it\n"); Py_DECREF(pObj); } // 2: copy new value to pObj pObj = node.pObj; // 3: increment pObj ref count because we just created another // reference to it. Py_INCREF(pObj); } // by convention, always return *this return *this; } // test if pObj has named child attribute bool pyPropertyNode::hasChild(const char *name) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { return true; } } return false; } // Return a pyPropertyNode object that points to the named child pyPropertyNode pyPropertyNode::getChild(const char *name, bool create) { if ( pObj == NULL ) { return pyPropertyNode(); } PyObject *pValue = PyObject_CallMethod(pObj, (char *)"getChild", (char *)"sb", name, create); if ( PyErr_Occurred() ) PyErr_Print(); if (pValue == NULL) { fprintf(stderr,"Call failed\n"); return pyPropertyNode(); } // give pValue over to the returned property node return pyPropertyNode(pValue); } pyPropertyNode pyPropertyNode::getChild(const char *name, int index, bool create) { if ( pObj == NULL ) { return pyPropertyNode(); } ostringstream ename; ename << name << '[' << index << ']'; // printf("ename = %s\n", ename.str().c_str()); return getChild(ename.str().c_str(), create); } // return true if pObj pointer is NULL bool pyPropertyNode::isNull() { return pObj == NULL; } // return length of attr if it is a list (enumerated) int pyPropertyNode::getLen(const char *name) { if ( pObj != NULL ) { PyObject *pValue = PyObject_CallMethod(pObj, (char *)"getLen", (char *)"s", name); if ( PyErr_Occurred() ) PyErr_Print(); if ( pValue != NULL ) { int len = PyLong_AsLong(pValue); Py_DECREF(pValue); return len; } } return 0; } // return true if pObj is a list (enumerated) void pyPropertyNode::setLen(const char *name, int size) { if ( pObj != NULL ) { PyObject *pValue = PyObject_CallMethod(pObj, (char *)"setLen", (char *)"si", name, size); if ( PyErr_Occurred() ) PyErr_Print(); if ( pValue != NULL ) { Py_DECREF(pValue); } } } // return true if pObj is a list (enumerated) void pyPropertyNode::setLen(const char *name, int size, double init_val) { if ( pObj != NULL ) { PyObject *pValue = PyObject_CallMethod(pObj, (char *)"setLen", (char *)"sif", name, size, init_val); if ( PyErr_Occurred() ) PyErr_Print(); if ( pValue != NULL ) { Py_DECREF(pValue); } } } // return true if pObj is a list (enumerated) vector <string> pyPropertyNode::getChildren(bool expand) { vector <string> result; if ( pObj != NULL ) { PyObject *pList = PyObject_CallMethod(pObj, (char *)"getChildren", (char *)"b", expand); if ( PyErr_Occurred() ) PyErr_Print(); if ( pList != NULL ) { if ( PyList_Check(pList) ) { int len = PyList_Size(pList); for ( int i = 0; i < len; i++ ) { PyObject *pItem = PyList_GetItem(pList, i); // note: PyList_GetItem doesn't give us ownership // of pItem so we should not decref() it. PyObject *pStr = PyObject_Str(pItem); result.push_back( (string)PyUnicode_AsUTF8(pStr) ); Py_DECREF(pStr); } } Py_DECREF(pList); } } return result; } // return true if pObj/name is leaf bool pyPropertyNode::isLeaf(const char *name) { if ( pObj == NULL ) { return false; } PyObject *pValue = PyObject_CallMethod(pObj, (char *)"isLeaf", (char *)"s", name); if ( PyErr_Occurred() ) PyErr_Print(); bool result = PyObject_IsTrue(pValue); Py_DECREF(pValue); return result; } // note: expects the calling layer to Py_DECREF(pAttr) double pyPropertyNode::PyObject2Double(const char *name, PyObject *pAttr) { double result = 0.0; if ( pAttr != NULL ) { if ( PyFloat_Check(pAttr) ) { result = PyFloat_AsDouble(pAttr); } else if ( PyLong_Check(pAttr) ) { result = PyLong_AsLong(pAttr); } else if ( PyLong_Check(pAttr) ) { result = PyLong_AsLong(pAttr); } else if ( PyBytes_Check(pAttr) ) { PyObject *pFloat = PyFloat_FromString(pAttr); if ( pFloat != NULL ) { result = PyFloat_AsDouble(pFloat); Py_DECREF(pFloat); } else { if ( PyErr_Occurred() ) PyErr_Print(); printf("WARNING: conversion from string to float failed\n"); PyObject *pStr = PyObject_Str(pAttr); const char *s = PyUnicode_AsUTF8(pStr); printf(" %s='%s'\n", name, s); Py_DECREF(pStr); } } else { printf("Unknown object type: '%s' ", pObj->ob_type->tp_name); PyObject *pStr = PyObject_Str(pObj); const char *s = PyUnicode_AsUTF8(pStr); printf(" %s='%s'\n", name, s); Py_DECREF(pStr); } } return result; } // note: expects the calling layer to Py_DECREF(pAttr) long pyPropertyNode::PyObject2Long(const char *name, PyObject *pAttr) { long result = 0; if ( pAttr != NULL ) { if ( PyLong_Check(pAttr) ) { result = PyLong_AsLong(pAttr); } else if ( PyFloat_Check(pAttr) ) { result = (long)PyFloat_AsDouble(pAttr); } else if ( PyBytes_Check(pAttr) ) { PyObject *pFloat = PyFloat_FromString(pAttr); if ( pFloat != NULL ) { result = PyFloat_AsDouble(pFloat); Py_DECREF(pFloat); } else { if ( PyErr_Occurred() ) PyErr_Print(); printf("WARNING: conversion from string to long failed\n"); PyObject *pStr = PyObject_Str(pAttr); const char *s = PyUnicode_AsUTF8(pStr); printf(" %s='%s'\n", name, s); Py_DECREF(pStr); } } else { printf("Unknown object type: '%s' ", pAttr->ob_type->tp_name); PyObject *pStr = PyObject_Str(pAttr); const char *s = PyUnicode_AsUTF8(pStr); printf(" %s='%s'\n", name, s); Py_DECREF(pStr); } } return result; } // value getters double pyPropertyNode::getDouble(const char *name) { double result = 0.0; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pAttr = PyObject_GetAttr(pObj, attrObj); if ( pAttr != NULL ) { result = PyObject2Double(name, pAttr); Py_DECREF(pAttr); } } } return result; } long pyPropertyNode::getLong(const char *name) { long result = 0; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pAttr = PyObject_GetAttr(pObj, attrObj); if ( pAttr != NULL ) { result = PyObject2Long(name, pAttr); Py_DECREF(pAttr); } } } return result; } bool pyPropertyNode::getBool(const char *name) { bool result = false; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pAttr = PyObject_GetAttr(pObj, attrObj); if ( pAttr != NULL ) { result = PyObject_IsTrue(pAttr); Py_DECREF(pAttr); } } } return result; } string pyPropertyNode::getString(const char *name) { string result = ""; if ( pObj != NULL ) { // test for normal vs. enumerated request char *pos = strchr((char *)name, '['); if ( pos == NULL ) { // normal request PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pAttr = PyObject_GetAttr(pObj, attrObj); if ( pAttr != NULL ) { PyObject *pStr = PyObject_Str(pAttr); if ( pStr != NULL ) { result = (string)PyUnicode_AsUTF8(pStr); Py_DECREF(pStr); } Py_DECREF(pAttr); } } } else { // enumerated request // this is a little goofy, but this code typically only runs // on an interactive telnet request, and we don't want to // modify the request string in place. string base = name; size_t basepos = base.find("["); if ( basepos != string::npos ) { base = base.substr(0, basepos); } pos++; int index = atoi(pos); result = getString(base.c_str(), index); // printf("%s %d %s\n", name, index, result.c_str()); } } return result; } // indexed value getters double pyPropertyNode::getDouble(const char *name, int index) { double result = 0.0; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pList = PyObject_GetAttr(pObj, attrObj); if ( pList != NULL ) { if ( PyList_Check(pList) ) { if ( index < PyList_Size(pList) ) { PyObject *pAttr = PyList_GetItem(pList, index); // note: PyList_GetItem doesn't give us ownership // of pAttr so we should not decref() it. if ( pAttr != NULL ) { result = PyObject2Double(name, pAttr); } } } else { printf("WARNING: request indexed value of plain node: %s!\n", name); } Py_DECREF(pList); } } } return result; } long pyPropertyNode::getLong(const char *name, int index) { long result = 0; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pList = PyObject_GetAttr(pObj, attrObj); if ( pList != NULL ) { if ( PyList_Check(pList) ) { if ( index < PyList_Size(pList) ) { PyObject *pAttr = PyList_GetItem(pList, index); // note: PyList_GetItem doesn't give us ownership // of pAttr so we should not decref() it. if ( pAttr != NULL ) { result = PyObject2Long(name, pAttr); } } } else { printf("WARNING: request indexed value of plain node: %s!\n", name); } Py_DECREF(pList); } } } return result; } string pyPropertyNode::getString(const char *name, int index) { string result = ""; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pList = PyObject_GetAttr(pObj, attrObj); if ( pList != NULL ) { if ( PyList_Check(pList) ) { if ( index < PyList_Size(pList) ) { PyObject *pAttr = PyList_GetItem(pList, index); // note: PyList_GetItem doesn't give us ownership // of pAttr so we should not decref() it. if ( pAttr != NULL ) { PyObject *pStr = PyObject_Str(pAttr); if ( pStr != NULL ) { result = (string)PyUnicode_AsUTF8(pStr); Py_DECREF(pStr); } } } } else { printf("WARNING: request indexed value of plain node: %s!\n", name); } Py_DECREF(pList); } } } return result; } bool pyPropertyNode::getBool(const char *name, int index) { bool result = false; if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); if ( PyObject_HasAttr(pObj, attrObj) ) { PyObject *pList = PyObject_GetAttr(pObj, attrObj); if ( pList != NULL ) { if ( PyList_Check(pList) ) { if ( index < PyList_Size(pList) ) { PyObject *pAttr = PyList_GetItem(pList, index); // note: PyList_GetItem doesn't give us ownership // of pAttr so we should not decref() it. if ( pAttr != NULL ) { result = PyObject_IsTrue(pAttr); } } } else { printf("WARNING: request indexed value of plain node: %s!\n", name); } Py_DECREF(pList); } } } return result; } // value setters bool pyPropertyNode::setDouble( const char *name, double val ) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); PyObject *pFloat = PyFloat_FromDouble(val); int result = PyObject_SetAttr(pObj, attrObj, pFloat); Py_DECREF(pFloat); return result != -1; } else { return false; } } bool pyPropertyNode::setLong( const char *name, long val ) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); PyObject *pLong = PyLong_FromLong(val); int result = PyObject_SetAttr(pObj, attrObj, pLong); Py_DECREF(pLong); return result != -1; } else { return false; } } bool pyPropertyNode::setBool( const char *name, bool val ) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); PyObject *pBool = PyBool_FromLong((long)val); int result = PyObject_SetAttr(pObj, attrObj, pBool); Py_DECREF(pBool); return result != -1; } else { return false; } } bool pyPropertyNode::setString( const char *name, string val ) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); PyObject *pString = PyUnicode_FromString(val.c_str()); int result = PyObject_SetAttr(pObj, attrObj, pString); Py_DECREF(pString); return result != -1; } else { return false; } } // indexed value setters bool pyPropertyNode::setDouble( const char *name, int index, double val ) { if ( pObj != NULL ) { PyObject *attrObj = cache.get_attr(name); PyObject *pList = PyObject_GetAttr(pObj, attrObj); if ( pList != NULL ) { if ( PyList_Check(pList) ) { if ( index < PyList_Size(pList) ) { PyObject *pFloat = PyFloat_FromDouble(val); // note setitem() steals the reference so we can't // decrement it PyList_SetItem(pList, index, pFloat ); } else { // index out of range } } else { // not a list } Py_DECREF(pList); } else { // list lookup failed } } else { return false; } return true; } // Return a pyPropertyNode object that points to the named child void pyPropertyNode::pretty_print() { if ( pObj == NULL ) { printf("pretty_print(): Null pyPropertyNode()\n"); } else { PyObject *pValue = PyObject_CallMethod(pObj, (char *)"pretty_print", (char *)""); if ( PyErr_Occurred() ) PyErr_Print(); if (pValue != NULL) { Py_DECREF(pValue); } else { fprintf(stderr,"Call failed\n"); } } } // These only need to be looked up once and then saved static PyObject *pModuleProps = NULL; static PyObject *pModuleJSON = NULL; static PyObject *pModuleXML = NULL; // This function must be called before any pyPropertyNode usage. It // imports the python props and props_json/xml modules. void pyPropsInit() { // python property system pModuleProps = PyImport_ImportModule("props"); if ( PyErr_Occurred() ) PyErr_Print(); if (pModuleProps == NULL) { fprintf(stderr, "Failed to load 'props'\n"); } // Json I/O system pModuleJSON = PyImport_ImportModule("props_json"); if ( PyErr_Occurred() ) PyErr_Print(); if (pModuleJSON == NULL) { fprintf(stderr, "Failed to load 'props_json'\n"); } // xml I/O system pModuleXML = PyImport_ImportModule("props_xml"); if ( PyErr_Occurred() ) PyErr_Print(); if (pModuleXML == NULL) { fprintf(stderr, "Failed to load 'props_xml'\n"); } } // This function can be called at exit to properly free resources // requested by init() extern void pyPropsCleanup(void) { printf("running pyPropsCleanup()\n"); Py_XDECREF(pModuleProps); Py_XDECREF(pModuleXML); } // Return a pyPropertyNode object that points to the specified path in // the property tree. This is a 'heavier' operation so it is // recommended to call this function from initialization routines and // save the result. Then use the pyPropertyNode for direct read/write // access in your update routines. pyPropertyNode pyGetNode(string abs_path, bool create) { PyObject *attrObj = cache.get_attr("getNode"); PyObject *pFuncGetNode = PyObject_GetAttr(pModuleProps, attrObj); if ( PyErr_Occurred() ) PyErr_Print(); if ( pFuncGetNode == NULL || ! PyCallable_Check(pFuncGetNode) ) { fprintf(stderr, "Cannot find function 'getNode()'\n"); return pyPropertyNode(); } // FIXME decref pFuncGetNode PyObject *pPath = PyUnicode_FromString(abs_path.c_str()); PyObject *pCreate = PyBool_FromLong(create); if (!pPath || !pCreate) { Py_XDECREF(pPath); Py_XDECREF(pCreate); fprintf(stderr, "Cannot convert argument\n"); return pyPropertyNode(); } PyObject *pValue = PyObject_CallFunctionObjArgs(pFuncGetNode, pPath, pCreate, NULL); if ( PyErr_Occurred() ) PyErr_Print(); Py_DECREF(pPath); Py_DECREF(pCreate); if (pValue != NULL) { // give pValue over to the returned property node /*printf("pyGetNode() success, creating pyPropertyNode\n"); pyPropertyNode tmp(pValue); printf("before return\n");*/ return pyPropertyNode(pValue); } else { printf("Call failed\n"); return pyPropertyNode(); } return pyPropertyNode(); } bool readXML(string filename, pyPropertyNode *node) { // getNode() function PyObject *pFuncLoad = PyObject_GetAttrString(pModuleXML, "load"); if ( PyErr_Occurred() ) PyErr_Print(); if ( pFuncLoad == NULL || ! PyCallable_Check(pFuncLoad) ) { fprintf(stderr, "Cannot find function 'load()'\n"); return false; } PyObject *pPath = PyBytes_FromString(filename.c_str()); if (!pPath || !node->pObj) { Py_XDECREF(pPath); Py_XDECREF(pFuncLoad); fprintf(stderr, "Cannot convert argument\n"); return false; } PyObject *pValue = PyObject_CallFunctionObjArgs(pFuncLoad, pPath, node->pObj, NULL); if ( PyErr_Occurred() ) PyErr_Print(); Py_DECREF(pPath); Py_DECREF(pFuncLoad); if (pValue != NULL) { // give pValue over to the returned property node bool result = PyObject_IsTrue(pValue); Py_DECREF(pValue); return result; } else { fprintf(stderr,"Call failed\n"); } return false; } bool writeXML(string filename, pyPropertyNode *node) { // getNode() function PyObject *pFuncSave = PyObject_GetAttrString(pModuleXML, "save"); if ( PyErr_Occurred() ) PyErr_Print(); if ( pFuncSave == NULL || ! PyCallable_Check(pFuncSave) ) { fprintf(stderr, "Cannot find function 'save()'\n"); return false; } PyObject *pPath = PyBytes_FromString(filename.c_str()); if (!pPath || !node->pObj) { Py_XDECREF(pPath); Py_XDECREF(pFuncSave); fprintf(stderr, "Cannot convert argument\n"); return false; } PyObject *pValue = PyObject_CallFunctionObjArgs(pFuncSave, pPath, node->pObj, NULL); if ( PyErr_Occurred() ) PyErr_Print(); Py_DECREF(pPath); Py_DECREF(pFuncSave); if (pValue != NULL) { // give pValue over to the returned property node bool result = PyObject_IsTrue(pValue); Py_DECREF(pValue); return result; } else { fprintf(stderr,"Call failed\n"); } return false; } bool readJSON(string filename, pyPropertyNode *node) { // getNode() function PyObject *pFuncLoad = PyObject_GetAttrString(pModuleJSON, "load"); if ( PyErr_Occurred() ) PyErr_Print(); if ( pFuncLoad == NULL || ! PyCallable_Check(pFuncLoad) ) { fprintf(stderr, "Cannot find function 'load()'\n"); return false; } PyObject *pPath = PyUnicode_FromString(filename.c_str()); if (!pPath || !node->pObj) { Py_XDECREF(pPath); Py_XDECREF(pFuncLoad); fprintf(stderr, "Cannot convert argument\n"); return false; } PyObject *pValue = PyObject_CallFunctionObjArgs(pFuncLoad, pPath, node->pObj, NULL); if ( PyErr_Occurred() ) PyErr_Print(); Py_DECREF(pPath); Py_DECREF(pFuncLoad); if (pValue != NULL) { // give pValue over to the returned property node bool result = PyObject_IsTrue(pValue); Py_DECREF(pValue); return result; } else { fprintf(stderr,"Call failed\n"); } return false; } bool writeJSON(string filename, pyPropertyNode *node) { // getNode() function PyObject *pFuncSave = PyObject_GetAttrString(pModuleJSON, "save"); if ( PyErr_Occurred() ) PyErr_Print(); if ( pFuncSave == NULL || ! PyCallable_Check(pFuncSave) ) { fprintf(stderr, "Cannot find function 'save()'\n"); return false; } PyObject *pPath = PyBytes_FromString(filename.c_str()); if (!pPath || !node->pObj) { Py_XDECREF(pPath); Py_XDECREF(pFuncSave); fprintf(stderr, "Cannot convert argument\n"); return false; } PyObject *pValue = PyObject_CallFunctionObjArgs(pFuncSave, pPath, node->pObj, NULL); if ( PyErr_Occurred() ) PyErr_Print(); Py_DECREF(pPath); Py_DECREF(pFuncSave); if (pValue != NULL) { // give pValue over to the returned property node bool result = PyObject_IsTrue(pValue); Py_DECREF(pValue); return result; } else { fprintf(stderr,"Call failed\n"); } return false; }
AuraUAS/aura-props
library/src/pyprops.cpp
C++
mit
21,619
// Copyright (c) 2014-2015 Oliver Eilhard. All rights reserved. // Use of this source code is governed by the MIT license. // See LICENSE file for details. package balancers import ( "net/http" "net/url" "sync" "time" ) // Connection is a single connection to a host. It is defined by a URL. // It also maintains state in the form that a connection can be broken. // TODO(oe) Not sure if this abstraction is necessary. type Connection interface { // URL to the host. URL() *url.URL // IsBroken must return true if the connection to URL is currently not available. IsBroken() bool } // HttpConnection is a HTTP connection to a host. // It implements the Connection interface and can be used by balancer // implementations. type HttpConnection struct { sync.Mutex url *url.URL broken bool heartbeatDuration time.Duration heartbeatStop chan bool } // NewHttpConnection creates a new HTTP connection to the given URL. func NewHttpConnection(url *url.URL) *HttpConnection { c := &HttpConnection{ url: url, heartbeatDuration: DefaultHeartbeatDuration, heartbeatStop: make(chan bool), } c.checkBroken() go c.heartbeat() return c } // Close this connection. func (c *HttpConnection) Close() error { c.Lock() defer c.Unlock() c.heartbeatStop <- true // wait for heartbeat ticker to stop c.broken = false return nil } // HeartbeatDuration sets the duration in which the connection is checked. func (c *HttpConnection) HeartbeatDuration(d time.Duration) *HttpConnection { c.Lock() defer c.Unlock() c.heartbeatStop <- true // wait for heartbeat ticker to stop c.broken = false c.heartbeatDuration = d go c.heartbeat() return c } // heartbeat periodically checks if the connection is broken. func (c *HttpConnection) heartbeat() { ticker := time.NewTicker(c.heartbeatDuration) for { select { case <-ticker.C: c.checkBroken() case <-c.heartbeatStop: return } } } // checkBroken checks if the HTTP connection is alive. func (c *HttpConnection) checkBroken() { c.Lock() defer c.Unlock() // TODO(oe) Can we use HEAD? req, err := http.NewRequest("GET", c.url.String(), nil) if err != nil { c.broken = true return } // Add UA to heartbeat requests. req.Header.Add("User-Agent", UserAgent) // Use a standard HTTP client with a timeout of 5 seconds. cl := &http.Client{Timeout: 5 * time.Second} res, err := cl.Do(req) if err == nil { defer res.Body.Close() if res.StatusCode == http.StatusOK { c.broken = false } else { c.broken = true } } else { c.broken = true } } // URL returns the URL of the HTTP connection. func (c *HttpConnection) URL() *url.URL { return c.url } // IsBroken returns true if the HTTP connection is currently broken. func (c *HttpConnection) IsBroken() bool { return c.broken }
olivere/balancers
connection.go
GO
mit
2,828
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.07.02 at 03:35:23 PM MSK // package ru.gov.zakupki.oos.signincoming._1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import ru.gov.zakupki.oos.types._1.ZfcsBankGuaranteeReturnInvalidType; /** * Пакет данных: * Сведения о недействительности информации о возвращении банковской гарантии или об освобождении от обязательств по банковской гарантии * * <p>Java class for bankGuaranteeReturnInvalid complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="bankGuaranteeReturnInvalid"> * &lt;complexContent> * &lt;extension base="{http://zakupki.gov.ru/oos/signIncoming/1}packetType"> * &lt;sequence> * &lt;element name="data" type="{http://zakupki.gov.ru/oos/types/1}zfcs_bankGuaranteeReturnInvalidType"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "bankGuaranteeReturnInvalid", propOrder = { "data" }) public class BankGuaranteeReturnInvalid extends PacketType { @XmlElement(required = true) protected ZfcsBankGuaranteeReturnInvalidType data; /** * Gets the value of the data property. * * @return * possible object is * {@link ZfcsBankGuaranteeReturnInvalidType } * */ public ZfcsBankGuaranteeReturnInvalidType getData() { return data; } /** * Sets the value of the data property. * * @param value * allowed object is * {@link ZfcsBankGuaranteeReturnInvalidType } * */ public void setData(ZfcsBankGuaranteeReturnInvalidType value) { this.data = value; } }
simokhov/schemas44
src/main/java/ru/gov/zakupki/oos/signincoming/_1/BankGuaranteeReturnInvalid.java
Java
mit
2,353
/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 2.1.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Modified by mwthinker, to use tabs in "dump" function and use fifo_map instead of std::map in order to keep the json order. Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform #include <array> // array #include <cassert> // assert #include <cctype> // isdigit #include <ciso646> // and, not, or #include <cmath> // isfinite, labs, ldexp, signbit #include <cstddef> // nullptr_t, ptrdiff_t, size_t #include <cstdint> // int64_t, uint64_t #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull #include <cstring> // strlen #include <forward_list> // forward_list #include <functional> // function, hash, less #include <initializer_list> // initializer_list #include <iomanip> // setw #include <iostream> // istream, ostream #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator #include <limits> // numeric_limits #include <locale> // locale #include <map> // map #include <memory> // addressof, allocator, allocator_traits, unique_ptr #include <numeric> // accumulate #include <sstream> // stringstream #include <stdexcept> // domain_error, invalid_argument, out_of_range #include <string> // getline, stoi, string, to_string #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type #include <utility> // declval, forward, make_pair, move, pair, swap #include <vector> // vector #include "fifo_map.hpp" // exclude unsupported compilers #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define JSON_DEPRECATED __declspec(deprecated) #else #define JSON_DEPRECATED #endif // allow to disable exceptions #if not defined(JSON_NOEXCEPTION) || defined(__EXCEPTIONS) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #else #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #endif /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief unnamed namespace with internal helper functions This namespace collects some functions that could not be defined inside the @ref basic_json class. @since version 2.1.0 */ namespace detail { /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) discarded ///< discarded by the the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string - furthermore, each type is not smaller than itself @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array<uint8_t, 8> order = {{ 0, // null 3, // object 4, // array 5, // string 1, // boolean 2, // integer 2, // unsigned 2, // float } }; // discarded values are not comparable if (lhs == value_t::discarded or rhs == value_t::discarded) { return false; } return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)]; } ///////////// // helpers // ///////////// // alias templates to reduce boilerplate template<bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; template<typename T> using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; // taken from http://stackoverflow.com/a/26936864/266378 template<typename T> using is_unscoped_enum = std::integral_constant<bool, std::is_convertible<T, int>::value and std::is_enum<T>::value>; /* Implementation of two C++17 constructs: conjunction, negation. This is needed to avoid evaluating all the traits in a condition For example: not std::is_same<void, T>::value and has_value_type<T>::value will not compile when T = void (on MSVC at least). Whereas conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will stop evaluating if negation<...>::value == false Please note that those constructs must be used with caution, since symbols can become very long quickly (which can slow down compilation and cause MSVC internal compiler errors). Only use it when you have to (see example ahead). */ template<class...> struct conjunction : std::true_type {}; template<class B1> struct conjunction<B1> : B1 {}; template<class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; template<class B> struct negation : std::integral_constant < bool, !B::value > {}; // dispatch utility (taken from ranges-v3) template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; ////////////////// // constructors // ////////////////// template<value_t> struct external_constructor; template<> struct external_constructor<value_t::boolean> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor<value_t::string> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_float> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { // replace infinity and NAN by null if (not std::isfinite(val)) { j = BasicJsonType{}; } else { j.m_type = value_t::number_float; j.m_value = val; } j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_unsigned> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_integer> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::array> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_type = value_t::array; j.m_value = arr; j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.assert_invariant(); } }; template<> struct external_constructor<value_t::object> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_type = value_t::object; j.m_value = obj; j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_type = value_t::object; j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); j.assert_invariant(); } }; //////////////////////// // has_/is_ functions // //////////////////////// /*! @brief Helper to determine whether there's a key_type for T. This helper is used to tell associative containers apart from other containers such as sequence containers. For instance, `std::map` passes the test as it contains a `mapped_type`, whereas `std::vector` fails the test. @sa http://stackoverflow.com/a/7728728/266378 @since version 1.0.0, overworked in version 2.0.6 */ #define NLOHMANN_JSON_HAS_HELPER(type) \ template<typename T> struct has_##type { \ private: \ template<typename U, typename = typename U::type> \ static int detect(U &&); \ static void detect(...); \ public: \ static constexpr bool value = \ std::is_integral<decltype(detect(std::declval<T>()))>::value; \ } NLOHMANN_JSON_HAS_HELPER(mapped_type); NLOHMANN_JSON_HAS_HELPER(key_type); NLOHMANN_JSON_HAS_HELPER(value_type); NLOHMANN_JSON_HAS_HELPER(iterator); #undef NLOHMANN_JSON_HAS_HELPER template<bool B, class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl : std::false_type {}; template<class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> { static constexpr auto value = std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value; }; template<class BasicJsonType, class CompatibleObjectType> struct is_compatible_object_type { static auto constexpr value = is_compatible_object_type_impl < conjunction<negation<std::is_same<void, CompatibleObjectType>>, has_mapped_type<CompatibleObjectType>, has_key_type<CompatibleObjectType>>::value, typename BasicJsonType::object_t, CompatibleObjectType >::value; }; template<typename BasicJsonType, typename T> struct is_basic_json_nested_type { static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or std::is_same<T, typename BasicJsonType::const_iterator>::value or std::is_same<T, typename BasicJsonType::reverse_iterator>::value or std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or std::is_same<T, typename BasicJsonType::json_pointer>::value; }; template<class BasicJsonType, class CompatibleArrayType> struct is_compatible_array_type { static auto constexpr value = conjunction<negation<std::is_same<void, CompatibleArrayType>>, negation<is_compatible_object_type< BasicJsonType, CompatibleArrayType>>, negation<std::is_constructible<typename BasicJsonType::string_t, CompatibleArrayType>>, negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>, has_value_type<CompatibleArrayType>, has_iterator<CompatibleArrayType>>::value; }; template<bool, typename, typename> struct is_compatible_integer_type_impl : std::false_type {}; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits<RealIntegerType>; using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; static constexpr auto value = std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and CompatibleLimits::is_integer and RealLimits::is_signed == CompatibleLimits::is_signed; }; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type { static constexpr auto value = is_compatible_integer_type_impl < std::is_integral<CompatibleNumberIntegerType>::value and not std::is_same<bool, CompatibleNumberIntegerType>::value, RealIntegerType, CompatibleNumberIntegerType > ::value; }; // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists template<typename BasicJsonType, typename T> struct has_from_json { private: // also check the return type of from_json template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json( std::declval<BasicJsonType>(), std::declval<T&>()))>::value>> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype( detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if JSONSerializer<T>::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template<typename BasicJsonType, typename T> struct has_non_default_from_json { private: template < typename U, typename = enable_if_t<std::is_same< T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if BasicJsonType::json_serializer<T>::to_json exists template<typename BasicJsonType, typename T> struct has_to_json { private: template<typename U, typename = decltype(uncvref_t<U>::to_json( std::declval<BasicJsonType&>(), std::declval<T>()))> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; ///////////// // to_json // ///////////// template<typename BasicJsonType, typename T, enable_if_t< std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor<value_t::boolean>::construct(j, b); } template<typename BasicJsonType, typename CompatibleString, enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor<value_t::string>::construct(j, s); } template<typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberUnsignedType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberIntegerType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); } template<typename BasicJsonType, typename UnscopedEnumType, enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0> void to_json(BasicJsonType& j, UnscopedEnumType e) noexcept { external_constructor<value_t::number_integer>::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor<value_t::array>::construct(j, arr); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& arr) { external_constructor<value_t::object>::construct(j, arr); } /////////////// // from_json // /////////////// // overloads for basic_json template parameters template<typename BasicJsonType, typename ArithmeticType, enable_if_t<std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } default: { JSON_THROW( std::domain_error("type must be number, but is " + j.type_name())); } } } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (not j.is_boolean()) { JSON_THROW(std::domain_error("type must be boolean, but is " + j.type_name())); } b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (not j.is_string()) { JSON_THROW(std::domain_error("type must be string, but is " + j.type_name())); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType, typename UnscopedEnumType, enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0> void from_json(const BasicJsonType& j, UnscopedEnumType& e) { typename std::underlying_type<UnscopedEnumType>::type val; get_arithmetic_value(j, val); e = static_cast<UnscopedEnumType>(val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) { if (not j.is_array()) { JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); } arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); } // forward_list doesn't have an insert method template<typename BasicJsonType, typename T, typename Allocator> void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) { // do not perform the check when user wants to retrieve jsons // (except when it's null.. ?) if (j.is_null()) { JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); } if (not std::is_same<T, BasicJsonType>::value) { if (not j.is_array()) { JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); } } for (auto it = j.rbegin(), end = j.rend(); it != end; ++it) { l.push_front(it->template get<T>()); } } template<typename BasicJsonType, typename CompatibleArrayType> void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>) { using std::begin; using std::end; std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename CompatibleArrayType> auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>) -> decltype( arr.reserve(std::declval<typename CompatibleArrayType::size_type>()), void()) { using std::begin; using std::end; arr.reserve(j.size()); std::transform( j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleArrayType& arr) { if (j.is_null()) { JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); } // when T == BasicJsonType, do not check if value_t is correct if (not std::is_same<typename CompatibleArrayType::value_type, BasicJsonType>::value) { if (not j.is_array()) { JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); } } from_json_array_impl(j, arr, priority_tag<1> {}); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleObjectType& obj) { if (not j.is_object()) { JSON_THROW(std::domain_error("type must be object, but is " + j.type_name())); } auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); using std::begin; using std::end; // we could avoid the assignment, but this might require a for loop, which // might be less efficient than the container constructor for some // containers (would it?) obj = CompatibleObjectType(begin(*inner_object), end(*inner_object)); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template<typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } case value_t::boolean: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); break; } default: { JSON_THROW(std::domain_error("type must be number, but is " + j.type_name())); } } } struct to_json_fn { private: template<typename BasicJsonType, typename T> auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) -> decltype(to_json(j, std::forward<T>(val)), void()) { return to_json(j, std::forward<T>(val)); } template<typename BasicJsonType, typename T> void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find to_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {}))) { return call(j, std::forward<T>(val), priority_tag<1> {}); } }; struct from_json_fn { private: template<typename BasicJsonType, typename T> auto call(const BasicJsonType& j, T& val, priority_tag<1>) const noexcept(noexcept(from_json(j, val))) -> decltype(from_json(j, val), void()) { return from_json(j, val); } template<typename BasicJsonType, typename T> void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find from_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(const BasicJsonType& j, T& val) const noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {}))) { return call(j, val, priority_tag<1> {}); } }; // taken from ranges-v3 template<typename T> struct static_const { static constexpr T value{}; }; template<typename T> constexpr T static_const<T>::value; } // namespace detail /// namespace to hold default `to_json` / `from_json` functions namespace { constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; } /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template<typename = void, typename = void> struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @param[in] j JSON value to read from @param[in,out] val value to write to */ template<typename BasicJsonType, typename ValueType> static void from_json(BasicJsonType&& j, ValueType& val) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) { ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template<typename BasicJsonType, typename ValueType> static void to_json(BasicJsonType& j, ValueType&& val) noexcept( noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) { ::nlohmann::to_json(j, std::forward<ValueType>(val)); } }; /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType): JSON values have [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](http://en.cppreference.com/w/cpp/concept/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. Modifed by mwthinker to use `fifo_map_compare<StringType>` instead of `std::map` @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from http://stackoverflow.com/a/9860911 @endinternal @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://rfc7159.net/rfc7159) @since version 1.0.0 @nosubgrouping */ template < template<typename U, typename V, typename... Args> class ObjectType = fifo_map, template<typename U, typename... Args> class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template<typename U> class AllocatorType = std::allocator, template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer > class basic_json { private: template<detail::value_t> friend struct detail::external_constructor; /// workaround type for MSVC using basic_json_t = basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer>; public: using value_t = detail::value_t; // forward declarations template<typename U> class iter_impl; template<typename Base> class json_reverse_iterator; class json_pointer; template<typename T, typename SFINAE> using json_serializer = JSONSerializer<T, SFINAE>; ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType<basic_json>; /// the type of an element pointer using pointer = typename std::allocator_traits<allocator_type>::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl<basic_json>; /// a const iterator for a basic_json container using const_iterator = iter_impl<const basic_json>; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @complexity Constant. @since 2.1.0 */ static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2017 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"] = { {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1} }; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ /*! @brief a type for an object [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less<StringType>` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less<std::string>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, later stored name/value pairs overwrite previously stored name/value pairs, leaving the used names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will be treated as equal and both stored as `{"key": 1}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not constraint explicitly. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 7159](http://rfc7159.net/rfc7159), because any order implements the specified "unordered" nature of JSON objects. Modifed by mwthinker to use `fifo_map_compare<StringType>` instead of `std::map` */ using object_t = ObjectType<StringType, basic_json, fifo_map_compare<StringType>, AllocatorType<std::pair<const StringType, basic_json>>>; /*! @brief a type for an array [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > @endcode #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not constraint explicitly. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; /*! @brief a type for a string [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 7159](http://rfc7159.net/rfc7159) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa @ref number_integer_t -- type for number values (integer) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /// @} private: /// helper for exception-safe object creation template<typename T, typename... Args> static T* create(Args&& ... args) { AllocatorType<T> alloc; auto deleter = [&](T * object) { alloc.deallocate(object, 1); }; std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter); alloc.construct(object.get(), std::forward<Args>(args)...); assert(object != nullptr); return object.release(); } //////////////////////// // JSON value storage // //////////////////////// /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create<object_t>(); break; } case value_t::array: { array = create<array_t>(); break; } case value_t::string: { string = create<string_t>(""); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { break; } default: { if (t == value_t::null) { JSON_THROW(std::domain_error("961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create<string_t>(value); } /// constructor for objects json_value(const object_t& value) { object = create<object_t>(value); } /// constructor for arrays json_value(const array_t& value) { array = create<array_t>(value); } }; /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. */ void assert_invariant() const { assert(m_type != value_t::object or m_value.object != nullptr); assert(m_type != value_t::array or m_value.array != nullptr); assert(m_type != value_t::string or m_value.string != nullptr); } public: ////////////////////////// // JSON parser callback // ////////////////////////// /*! @brief JSON callback events This enumeration lists the parser events that can trigger calling a callback function of type @ref parser_callback_t during parsing. @image html callback_events.png "Example when certain parse events are triggered" @since version 1.0.0 */ enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse(std::istream&, const parser_callback_t) or @ref parse(const CharT, const parser_callback_t), it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa @ref parse(std::istream&, parser_callback_t) or @ref parse(const CharT, const parser_callback_t) for examples @since version 1.0.0 */ using parser_callback_t = std::function<bool(int depth, parse_event_t event, basic_json& parsed)>; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @param[in] value_type the type of the value to create @complexity Constant. @throw std::bad_alloc if allocation for object, array, or string value fails @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @since version 1.0.0 */ basic_json(const value_t value_type) : m_type(value_type), m_value(value_type) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exsits. The constructor forwards the parameter @a val to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and `unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - @ref @ref json_serializer<U> has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t<CompatibleType>` @param[in] val the value to be forwarded @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @throw what `json_serializer<U>::to_json()` throws @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t<not std::is_base_of<std::istream, U>::value and not std::is_same<U, basic_json_t>::value and not detail::is_basic_json_nested_type< basic_json_t, U>::value and detail::has_to_json<basic_json, U>::value, int> = 0> basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json( std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) { JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has now way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(std::initializer_list<basic_json>) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(std::initializer_list<basic_json>) and @ref object(std::initializer_list<basic_json>). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw std::domain_error if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string; example: `"cannot create object from initializer list"` @complexity Linear in the size of the initializer list @a init. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array value from an initializer list @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(std::initializer_list<basic_json> init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const basic_json & element) { return element.is_array() and element.size() == 2 and element[0].is_string(); }); // adjust type if type deduction is not wanted if (not type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (manual_type == value_t::object and not is_an_object) { JSON_THROW(std::domain_error("cannot create object from initializer list")); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; std::for_each(init.begin(), init.end(), [this](const basic_json & element) { m_value.object->emplace(*(element[0].m_value.string), element[1]); }); } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create<array_t>(init); } assert_invariant(); } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @liveexample{The following code shows an example for the `array` function.,array} @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) -- create a JSON value from an initializer list @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object value from an initializer list @since version 1.0.0 */ static basic_json array(std::initializer_list<basic_json> init = std::initializer_list<basic_json>()) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(std::initializer_list<basic_json>), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(std::initializer_list<basic_json>, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw std::domain_error if @a init is not a pair whose first elements are strings; thrown by @ref basic_json(std::initializer_list<basic_json>, bool, value_t) @complexity Linear in the size of @a init. @liveexample{The following code shows an example for the `object` function.,object} @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) -- create a JSON value from an initializer list @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array value from an initializer list @since version 1.0.0 */ static basic_json object(std::initializer_list<basic_json> init = std::initializer_list<basic_json>()) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. As postcondition, `std::distance(begin(),end()) == cnt` holds. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @complexity Linear in @a cnt. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create<array_t>(cnt, val); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, std::out_of_range is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector`. - In case of a null type, std::domain_error is thrown. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion.** @throw std::domain_error if iterators are not compatible; that is, do not belong to the same JSON value; example: `"iterators are not compatible"` @throw std::out_of_range if iterators are for a primitive type (number, boolean, or string) where an out of range error can be detected easily; example: `"iterators out of range"` @throw std::bad_alloc if allocation for object, array, or string fails @throw std::domain_error if called with a null value; example: `"cannot use construct with iterators from null"` @complexity Linear in distance between @a first and @a last. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template<class InputIT, typename std::enable_if< std::is_same<InputIT, typename basic_json_t::iterator>::value or std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0> basic_json(InputIT first, InputIT last) { assert(first.m_object != nullptr); assert(last.m_object != nullptr); // make sure iterator fits the current value if (first.m_object != last.m_object) { JSON_THROW(std::domain_error("iterators are not compatible")); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) { JSON_THROW(std::out_of_range("iterators out of range")); } break; } default: { break; } } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: { JSON_THROW(std::domain_error("cannot use construct with iterators from " + first.m_object->type_name())); } } assert_invariant(); } /*! @brief construct a JSON value given an input stream @param[in,out] i stream to read a serialized JSON value from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @deprecated This constructor is deprecated and will be removed in version 3.0.0 to unify the interface of the library. Deserialization will be done by stream operators or by calling one of the `parse` functions, e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls like `json j(i);` for an input stream @a i need to be replaced by `json j = json::parse(i);`. See the example below. @liveexample{The example below demonstrates constructing a JSON value from a `std::stringstream` with and without callback function.,basic_json__istream} @since version 2.0.0, deprecated in version 2.0.3, to be removed in version 3.0.0 */ JSON_DEPRECATED explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) { *this = parser(i, cb).parse(); assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @complexity Linear in the size of @a other. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @throw std::bad_alloc if allocation for object, array, or string fails. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } default: { break; } } assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post @a other is a JSON null value @complexity Constant. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(); // invalidate payload other.m_type = value_t::null; other.m_value = {}; assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ reference& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() { assert_invariant(); switch (m_type) { case value_t::object: { AllocatorType<object_t> alloc; alloc.destroy(m_value.object); alloc.deallocate(m_value.object, 1); break; } case value_t::array: { AllocatorType<array_t> alloc; alloc.destroy(m_value.array); alloc.deallocate(m_value.array, 1); break; } case value_t::string: { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); break; } default: { // all other types need no specific destructor break; } } } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent parameter. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @return string containing the serialization of the JSON value @complexity Linear. @liveexample{The following example shows the effect of different @a indent parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0 */ string_t dump(const int indent = -1) const { std::stringstream ss; if (indent >= 0) { dump(ss, true, static_cast<unsigned int>(indent)); } else { dump(ss, false, 0); } return ss.str(); } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true iff the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa @ref is_structured() -- returns whether JSON value is structured @sa @ref is_null() -- returns whether JSON value is `null` @sa @ref is_string() -- returns whether JSON value is a string @sa @ref is_boolean() -- returns whether JSON value is a boolean @sa @ref is_number() -- returns whether JSON value is a number @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() or is_string() or is_boolean() or is_number(); } /*! @brief return whether type is structured This function returns true iff the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa @ref is_primitive() -- returns whether value is primitive @sa @ref is_array() -- returns whether value is an array @sa @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() or is_object(); } /*! @brief return whether value is null This function returns true iff the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return m_type == value_t::null; } /*! @brief return whether value is a boolean This function returns true iff the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return m_type == value_t::boolean; } /*! @brief return whether value is a number This function returns true iff the JSON value is a number. This includes both integer and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() or is_number_float(); } /*! @brief return whether value is an integer number This function returns true iff the JSON value is an integer or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa @ref is_number() -- check if value is a number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return m_type == value_t::number_integer or m_type == value_t::number_unsigned; } /*! @brief return whether value is an unsigned integer number This function returns true iff the JSON value is an unsigned integer number. This excludes floating-point and (signed) integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa @ref is_number() -- check if value is a number @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return m_type == value_t::number_unsigned; } /*! @brief return whether value is a floating-point number This function returns true iff the JSON value is a floating-point number. This excludes integer and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa @ref is_number() -- check if value is number @sa @ref is_number_integer() -- check if value is an integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return m_type == value_t::number_float; } /*! @brief return whether value is an object This function returns true iff the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return m_type == value_t::object; } /*! @brief return whether value is an array This function returns true iff the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return m_type == value_t::array; } /*! @brief return whether value is a string This function returns true iff the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return m_type == value_t::string; } /*! @brief return whether value is discarded This function returns true iff the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return m_type == value_t::discarded; } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (is_boolean()) { return m_value.boolean; } JSON_THROW(std::domain_error("type must be boolean, but is " + type_name())); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /*! @brief helper function to implement get_ref() This funcion helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw std::domain_error if ReferenceType does not match underlying value type of the current JSON */ template<typename ReferenceType, typename ThisType> static ReferenceType get_ref_impl(ThisType& obj) { // helper type using PointerType = typename std::add_pointer<ReferenceType>::type; // delegate the call to get_ptr<>() auto ptr = obj.template get_ptr<PointerType>(); if (ptr != nullptr) { return *ptr; } JSON_THROW(std::domain_error("incompatible ReferenceType for get_ref, actual type is " + obj.type_name())); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template < typename BasicJsonType, detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value, int> = 0 > basic_json get() const { return *this; } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const @ref basic_json&, ValueType&)`, and - @ref json_serializer<ValueType> does not have a `from_json()` method of the form `ValueType from_json(const @ref basic_json&)` @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t < not std::is_same<basic_json_t, ValueType>::value and detail::has_from_json<basic_json_t, ValueType>::value and not detail::has_non_default_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get<const basic_json_t>(), which is why we // still need the uncvref static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); static_assert(std::is_default_constructible<ValueType>::value, "types must be DefaultConstructible when used with get()"); ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer<ValueTypeCV>::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer<ValueType> has a `from_json()` method of the form `ValueType from_json(const @ref basic_json&)` @note If @ref json_serializer<ValueType> has both overloads of `from_json()`, this one is chosen. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) { static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); return JSONSerializer<ValueTypeCV>::from_json(*this); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get() noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (explicit) @copydoc get() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> constexpr const PointerType get() const noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get_ptr() noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value and std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0> constexpr const PointerType get_ptr() const noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast<const PointerType>(nullptr)); } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws std::domain_error otherwise @throw std::domain_error in case passed type @a ReferenceType is incompatible with the stored JSON value @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value and std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0> ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw std::domain_error in case passed type @a ValueType is incompatible to JSON, thrown by @ref get() const @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < not std::is_pointer<ValueType>::value and not std::is_same<ValueType, typename string_t::value_type>::value #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value #endif , int >::type = 0 > operator ValueType() const { // delegate the call to get<>() const return get<ValueType>(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw std::domain_error if the JSON value is not an array; example: `"cannot use at() with string"` @throw std::out_of_range if the index @a idx is out of range of the array; that is, `idx >= size()`; example: `"array index 7 is out of range"` @complexity Constant. @liveexample{The example below shows how array elements can be read and written using `at()`.,at__size_type} @since version 1.0.0 */ reference at(size_type idx) { // at only works for arrays if (is_array()) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(std::domain_error("cannot use at() with " + type_name())); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw std::domain_error if the JSON value is not an array; example: `"cannot use at() with string"` @throw std::out_of_range if the index @a idx is out of range of the array; that is, `idx >= size()`; example: `"array index 7 is out of range"` @complexity Constant. @liveexample{The example below shows how array elements can be read using `at()`.,at__size_type_const} @since version 1.0.0 */ const_reference at(size_type idx) const { // at only works for arrays if (is_array()) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(std::domain_error("cannot use at() with " + type_name())); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw std::domain_error if the JSON value is not an object; example: `"cannot use at() with boolean"` @throw std::out_of_range if the key @a key is is not stored in the object; that is, `find(key) == end()`; example: `"key "the fast" not found"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using `at()`.,at__object_t_key_type} @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference at(const typename object_t::key_type& key) { // at only works for objects if (is_object()) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(std::out_of_range("key '" + key + "' not found")); } } else { JSON_THROW(std::domain_error("cannot use at() with " + type_name())); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw std::domain_error if the JSON value is not an object; example: `"cannot use at() with boolean"` @throw std::out_of_range if the key @a key is is not stored in the object; that is, `find(key) == end()`; example: `"key "the fast" not found"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using `at()`.,at__object_t_key_type_const} @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (is_object()) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(std::out_of_range("key '" + key + "' not found")); } } else { JSON_THROW(std::domain_error("cannot use at() with " + type_name())); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw std::domain_error if JSON is not an array or null; example: `"cannot use operator[] with string"` @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create<array_t>(); assert_invariant(); } // operator[] only works for arrays if (is_array()) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { m_value.array->insert(m_value.array->end(), idx - m_value.array->size() + 1, basic_json()); } return m_value.array->operator[](idx); } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw std::domain_error if JSON is not an array; example: `"cannot use operator[] with null"` @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (is_array()) { return m_value.array->operator[](idx); } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw std::domain_error if JSON is not an object or null; example: `"cannot use operator[] with string"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } // operator[] only works for objects if (is_object()) { return m_value.object->operator[](key); } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw std::domain_error if JSON is not an object; example: `"cannot use operator[] with null"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (is_object()) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw std::domain_error if JSON is not an object or null; example: `"cannot use operator[] with string"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ template<typename T, std::size_t n> reference operator[](T * (&key)[n]) { return operator[](static_cast<const T>(key)); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @note This function is required for compatibility reasons with Clang. @param[in] key key of the element to access @return const reference to the element at key @a key @throw std::domain_error if JSON is not an object; example: `"cannot use operator[] with null"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ template<typename T, std::size_t n> const_reference operator[](T * (&key)[n]) const { return operator[](static_cast<const T>(key)); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw std::domain_error if JSON is not an object or null; example: `"cannot use operator[] with string"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (is_object()) { return m_value.object->operator[](key); } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw std::domain_error if JSON is not an object; example: `"cannot use operator[] with null"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> const_reference operator[](T* key) const { // at only works for objects if (is_object()) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(std::out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw std::domain_error if JSON is not an object; example: `"cannot use value() with null"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const typename object_t::key_type& key, ValueType default_value) const { // at only works for objects if (is_object()) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return *it; } return default_value; } else { JSON_THROW(std::domain_error("cannot use value() with " + type_name())); } } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(std::out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw std::domain_error if JSON is not an object; example: `"cannot use value() with null"` @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const json_pointer& ptr, ValueType default_value) const { // at only works for objects if (is_object()) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this); } JSON_CATCH (std::out_of_range&) { return default_value; } } JSON_THROW(std::domain_error("cannot use value() with " + type_name())); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw std::out_of_range when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw std::out_of_range when called on `null` value. @liveexample{The following code shows an example for `back()`.,back} @sa @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw std::domain_error if called on a `null` value; example: `"cannot use erase() with null"` @throw std::domain_error if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw std::out_of_range if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (this != pos.m_object) { JSON_THROW(std::domain_error("iterator does not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (not pos.m_it.primitive_iterator.is_begin()) { JSON_THROW(std::out_of_range("iterator out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: { JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); } } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw std::domain_error if called on a `null` value; example: `"cannot use erase() with null"` @throw std::domain_error if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw std::out_of_range if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (this != first.m_object or this != last.m_object) { JSON_THROW(std::domain_error("iterators do not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) { JSON_THROW(std::out_of_range("iterators out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: { JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); } } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw std::domain_error when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (is_object()) { return m_value.object->erase(key); } JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw std::domain_error when called on a type other than JSON array; example: `"cannot use erase() with null"` @throw std::out_of_range when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (is_array()) { if (idx >= size()) { JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); } m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); } else { JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @since version 1.0.0 */ iterator find(typename object_t::key_type key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief find an element in a JSON object @copydoc find(typename object_t::key_type) */ const_iterator find(typename object_t::key_type key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ size_type count(typename object_t::key_type key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(key) : 0; } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa @ref cbegin() -- returns a const iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa @ref begin() -- returns an iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa @ref cend() -- returns a const iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa @ref end() -- returns an iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa @ref crbegin() -- returns a const reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa @ref crend() -- returns a const reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa @ref rend() -- returns a reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } private: // forward declaration template<typename IteratorType> class iteration_proxy; public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. @note The name of this function is not yet final and may change in the future. */ static iteration_proxy<iterator> iterator_wrapper(reference cont) { return iteration_proxy<iterator>(cont); } /*! @copydoc iterator_wrapper(reference) */ static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont) { return iteration_proxy<const_iterator>(cont); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty Checks if a JSON value has no elements. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @sa @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` object | result of function object_t::size() array | result of function array_t::size() @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @liveexample{The following code calls `size()` on the different value types.,size} @sa @ref empty() -- checks whether the container is empty @sa @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @sa @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @complexity Linear in the size of the JSON value. @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: { break; } } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw std::domain_error when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (not(is_null() or is_array())) { JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) m_value.array->push_back(std::move(val)); // invalidate object val.m_type = value_t::null; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (not(is_null() or is_array())) { JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array m_value.array->push_back(val); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw std::domain_error when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (not(is_null() or is_object())) { JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array m_value.object->insert(val); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(std::initializer_list<basic_json> init) { if (is_object() and init.size() == 2 and init.begin()->is_string()) { const string_t key = *init.begin(); push_back(typename object_t::value_type(key, *(init.begin() + 1))); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(std::initializer_list<basic_json>) */ reference operator+=(std::initializer_list<basic_json> init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @throw std::domain_error when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8 */ template<class... Args> void emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (not(is_null() or is_array())) { JSON_THROW(std::domain_error("cannot use emplace_back() with " + type_name())); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) m_value.array->emplace_back(std::forward<Args>(args)...); } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw std::domain_error when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template<class... Args> std::pair<iterator, bool> emplace(Args&& ... args) { // emplace only works for null objects or arrays if (not(is_null() or is_object())) { JSON_THROW(std::domain_error("cannot use emplace() with " + type_name())); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward<Args>(args)...); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw std::domain_error if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw std::domain_error if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (is_array()) { // check if iterator pos fits to this JSON value if (pos.m_object != this) { JSON_THROW(std::domain_error("iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); return result; } JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw std::domain_error if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw std::domain_error if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (is_array()) { // check if iterator pos fits to this JSON value if (pos.m_object != this) { JSON_THROW(std::domain_error("iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); return result; } JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw std::domain_error if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw std::domain_error if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw std::domain_error if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw std::domain_error if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (not is_array()) { JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); } // check if iterator pos fits to this JSON value if (pos.m_object != this) { JSON_THROW(std::domain_error("iterator does not fit current value")); } // check if range iterators belong to the same JSON object if (first.m_object != last.m_object) { JSON_THROW(std::domain_error("iterators do not fit")); } if (first.m_object == this or last.m_object == this) { JSON_THROW(std::domain_error("passed iterators may not belong to container")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert( pos.m_it.array_iterator, first.m_it.array_iterator, last.m_it.array_iterator); return result; } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw std::domain_error if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw std::domain_error if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist) { // insert only works for arrays if (not is_array()) { JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); } // check if iterator pos fits to this JSON value if (pos.m_object != this) { JSON_THROW(std::domain_error("iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist); return result; } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw std::domain_error when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) { // swap only works for arrays if (is_array()) { std::swap(*(m_value.array), other); } else { JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw std::domain_error when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) { // swap only works for objects if (is_object()) { std::swap(*(m_value.object), other); } else { JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw std::domain_error when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) { // swap only works for strings if (is_string()) { std::swap(*(m_value.string), other); } else { JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same. - Integer and floating-point numbers are automatically converted before comparison. Floating-point numbers are compared indirectly: two floating-point numbers `f1` and `f2` are considered equal if neither `f1 > f2` nor `f2 > f1` holds. - Two JSON null values are equal. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: { return *lhs.m_value.array == *rhs.m_value.array; } case value_t::object: { return *lhs.m_value.object == *rhs.m_value.object; } case value_t::null: { return true; } case value_t::string: { return *lhs.m_value.string == *rhs.m_value.string; } case value_t::boolean: { return lhs.m_value.boolean == rhs.m_value.boolean; } case value_t::number_integer: { return lhs.m_value.number_integer == rhs.m_value.number_integer; } case value_t::number_unsigned: { return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; } case value_t::number_float: { return lhs.m_value.number_float == rhs.m_value.number_float; } default: { return false; } } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept { return (lhs == basic_json(rhs)); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) == rhs); } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return not (lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs != basic_json(rhs)); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) != rhs); } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: { return *lhs.m_value.array < *rhs.m_value.array; } case value_t::object: { return *lhs.m_value.object < *rhs.m_value.object; } case value_t::null: { return false; } case value_t::string: { return *lhs.m_value.string < *rhs.m_value.string; } case value_t::boolean: { return lhs.m_value.boolean < rhs.m_value.boolean; } case value_t::number_integer: { return lhs.m_value.number_integer < rhs.m_value.number_integer; } case value_t::number_unsigned: { return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; } case value_t::number_float: { return lhs.m_value.number_float < rhs.m_value.number_float; } default: { return false; } } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return not (rhs < lhs); } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return not (lhs <= rhs); } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return not (lhs < rhs); } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = (o.width() > 0); const auto indentation = (pretty_print ? o.width() : 0); // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization j.dump(o, pretty_print, static_cast<unsigned int>(indentation)); return o; } /*! @brief serialize to stream @copydoc operator<<(std::ostream&, const basic_json&) */ friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from an array This function reads from an array of 1-byte values. @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @param[in] array array to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @since version 2.0.3 */ template<class T, std::size_t N> static basic_json parse(T (&array)[N], const parser_callback_t cb = nullptr) { // delegate the call to the iterator-range parse overload return parse(std::begin(array), std::end(array), cb); } /*! @brief deserialize from string literal @tparam CharT character/literal type with size of 1 byte @param[in] s string literal to read a serialized JSON value from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @note String containers like `std::string` or @ref string_t can be parsed with @ref parse(const ContiguousContainer&, const parser_callback_t) @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @sa @ref parse(std::istream&, const parser_callback_t) for a version that reads from an input stream @since version 1.0.0 (originally for @ref string_t) */ template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral<typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> static basic_json parse(const CharT s, const parser_callback_t cb = nullptr) { return parser(reinterpret_cast<const char*>(s), cb).parse(); } /*! @brief deserialize from stream @param[in,out] i stream to read a serialized JSON value from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @sa @ref parse(const CharT, const parser_callback_t) for a version that reads from a string @since version 1.0.0 */ static basic_json parse(std::istream& i, const parser_callback_t cb = nullptr) { return parser(i, cb).parse(); } /*! @copydoc parse(std::istream&, const parser_callback_t) */ static basic_json parse(std::istream&& i, const parser_callback_t cb = nullptr) { return parser(i, cb).parse(); } /*! @brief deserialize from an iterator range with contiguous storage This function reads from an iterator range of a container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre The iterator range is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element in the range has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with noncompliant iterators and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @tparam IteratorType iterator of container with contiguous storage @param[in] first begin of the range to parse (included) @param[in] last end of the range to parse (excluded) @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an iterator range.,parse__iteratortype__parser_callback_t} @since version 2.0.3 */ template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr) { // assertion to check that the iterator range is indeed contiguous, // see http://stackoverflow.com/a/35008842/266378 for more discussion assert(std::accumulate(first, last, std::pair<bool, int>(true, 0), [&first](std::pair<bool, int> res, decltype(*first) val) { res.first &= (val == *(std::next(std::addressof(*first), res.second++))); return res; }).first); // assertion to check that each element is 1 byte long static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1, "each element in the iterator range must have the size of 1 byte"); // if iterator range is empty, create a parser with an empty string // to generate "unexpected EOF" error message if (std::distance(first, last) <= 0) { return parser("").parse(); } return parser(first, last, cb).parse(); } /*! @brief deserialize from a container with contiguous storage This function reads from a container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, and `std::initializer_list`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre The container storage is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with a noncompliant container and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @tparam ContiguousContainer container type with contiguous storage @param[in] c container to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 */ template<class ContiguousContainer, typename std::enable_if< not std::is_pointer<ContiguousContainer>::value and std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value , int>::type = 0> static basic_json parse(const ContiguousContainer& c, const parser_callback_t cb = nullptr) { // delegate the call to the iterator-range parse overload return parse(std::begin(c), std::end(c), cb); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw std::invalid_argument in case of parse errors @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator<<(basic_json& j, std::istream& i) { j = parser(i).parse(); return i; } /*! @brief deserialize from stream @copydoc operator<<(basic_json&, std::istream&) */ friend std::istream& operator>>(std::istream& i, basic_json& j) { j = parser(i).parse(); return i; } /// @} ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ private: /*! @note Some code in the switch cases has been copied, because otherwise copilers would complain about implicit fallthrough and there is no portable attribute to mute such warnings. */ template<typename T> static void add_to_vector(std::vector<uint8_t>& vec, size_t bytes, const T number) { assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8); switch (bytes) { case 8: { vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 070) & 0xff)); vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 060) & 0xff)); vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 050) & 0xff)); vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 040) & 0xff)); vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff)); vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff)); vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); vec.push_back(static_cast<uint8_t>(number & 0xff)); break; } case 4: { vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff)); vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff)); vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); vec.push_back(static_cast<uint8_t>(number & 0xff)); break; } case 2: { vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff)); vec.push_back(static_cast<uint8_t>(number & 0xff)); break; } case 1: { vec.push_back(static_cast<uint8_t>(number & 0xff)); break; } } } /*! @brief take sufficient bytes from a vector to fill an integer variable In the context of binary serialization formats, we need to read several bytes from a byte vector and combine them to multi-byte integral data types. @param[in] vec byte vector to read from @param[in] current_index the position in the vector after which to read @return the next sizeof(T) bytes from @a vec, in reverse order as T @tparam T the integral return type @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the vector @a vec to read In the for loop, the bytes from the vector are copied in reverse order into the return value. In the figures below, let sizeof(T)=4 and `i` be the loop variable. Precondition: vec: | | | a | b | c | d | T: | | | | | ^ ^ ^ ^ current_index i ptr sizeof(T) Postcondition: vec: | | | a | b | c | d | T: | d | c | b | a | ^ ^ ^ | i ptr current_index @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>. */ template<typename T> static T get_from_vector(const std::vector<uint8_t>& vec, const size_t current_index) { if (current_index + sizeof(T) + 1 > vec.size()) { JSON_THROW(std::out_of_range("cannot read " + std::to_string(sizeof(T)) + " bytes from vector")); } T result; auto* ptr = reinterpret_cast<uint8_t*>(&result); for (size_t i = 0; i < sizeof(T); ++i) { *ptr++ = vec[current_index + sizeof(T) - i]; } return result; } /*! @brief create a MessagePack serialization of a given JSON value This is a straightforward implementation of the MessagePack specification. @param[in] j JSON value to serialize @param[in,out] v byte vector to write the serialization to @sa https://github.com/msgpack/msgpack/blob/master/spec.md */ static void to_msgpack_internal(const basic_json& j, std::vector<uint8_t>& v) { switch (j.type()) { case value_t::null: { // nil v.push_back(0xc0); break; } case value_t::boolean: { // true and false v.push_back(j.m_value.boolean ? 0xc3 : 0xc2); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we // used the code from the value_t::number_unsigned case // here. if (j.m_value.number_unsigned < 128) { // positive fixnum add_to_vector(v, 1, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max()) { // uint 8 v.push_back(0xcc); add_to_vector(v, 1, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max()) { // uint 16 v.push_back(0xcd); add_to_vector(v, 2, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max()) { // uint 32 v.push_back(0xce); add_to_vector(v, 4, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max()) { // uint 64 v.push_back(0xcf); add_to_vector(v, 8, j.m_value.number_unsigned); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum add_to_vector(v, 1, j.m_value.number_integer); } else if (j.m_value.number_integer >= std::numeric_limits<int8_t>::min() and j.m_value.number_integer <= std::numeric_limits<int8_t>::max()) { // int 8 v.push_back(0xd0); add_to_vector(v, 1, j.m_value.number_integer); } else if (j.m_value.number_integer >= std::numeric_limits<int16_t>::min() and j.m_value.number_integer <= std::numeric_limits<int16_t>::max()) { // int 16 v.push_back(0xd1); add_to_vector(v, 2, j.m_value.number_integer); } else if (j.m_value.number_integer >= std::numeric_limits<int32_t>::min() and j.m_value.number_integer <= std::numeric_limits<int32_t>::max()) { // int 32 v.push_back(0xd2); add_to_vector(v, 4, j.m_value.number_integer); } else if (j.m_value.number_integer >= std::numeric_limits<int64_t>::min() and j.m_value.number_integer <= std::numeric_limits<int64_t>::max()) { // int 64 v.push_back(0xd3); add_to_vector(v, 8, j.m_value.number_integer); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum add_to_vector(v, 1, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max()) { // uint 8 v.push_back(0xcc); add_to_vector(v, 1, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max()) { // uint 16 v.push_back(0xcd); add_to_vector(v, 2, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max()) { // uint 32 v.push_back(0xce); add_to_vector(v, 4, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max()) { // uint 64 v.push_back(0xcf); add_to_vector(v, 8, j.m_value.number_unsigned); } break; } case value_t::number_float: { // float 64 v.push_back(0xcb); const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float)); for (size_t i = 0; i < 8; ++i) { v.push_back(helper[7 - i]); } break; } case value_t::string: { const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr v.push_back(static_cast<uint8_t>(0xa0 | N)); } else if (N <= 255) { // str 8 v.push_back(0xd9); add_to_vector(v, 1, N); } else if (N <= 65535) { // str 16 v.push_back(0xda); add_to_vector(v, 2, N); } else if (N <= 4294967295) { // str 32 v.push_back(0xdb); add_to_vector(v, 4, N); } // append string std::copy(j.m_value.string->begin(), j.m_value.string->end(), std::back_inserter(v)); break; } case value_t::array: { const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray v.push_back(static_cast<uint8_t>(0x90 | N)); } else if (N <= 0xffff) { // array 16 v.push_back(0xdc); add_to_vector(v, 2, N); } else if (N <= 0xffffffff) { // array 32 v.push_back(0xdd); add_to_vector(v, 4, N); } // append each element for (const auto& el : *j.m_value.array) { to_msgpack_internal(el, v); } break; } case value_t::object: { const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf))); } else if (N <= 65535) { // map 16 v.push_back(0xde); add_to_vector(v, 2, N); } else if (N <= 4294967295) { // map 32 v.push_back(0xdf); add_to_vector(v, 4, N); } // append each element for (const auto& el : *j.m_value.object) { to_msgpack_internal(el.first, v); to_msgpack_internal(el.second, v); } break; } default: { break; } } } /*! @brief create a CBOR serialization of a given JSON value This is a straightforward implementation of the CBOR specification. @param[in] j JSON value to serialize @param[in,out] v byte vector to write the serialization to @sa https://tools.ietf.org/html/rfc7049 */ static void to_cbor_internal(const basic_json& j, std::vector<uint8_t>& v) { switch (j.type()) { case value_t::null: { v.push_back(0xf6); break; } case value_t::boolean: { v.push_back(j.m_value.boolean ? 0xf5 : 0xf4); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { add_to_vector(v, 1, j.m_value.number_integer); } else if (j.m_value.number_integer <= std::numeric_limits<uint8_t>::max()) { v.push_back(0x18); // one-byte uint8_t add_to_vector(v, 1, j.m_value.number_integer); } else if (j.m_value.number_integer <= std::numeric_limits<uint16_t>::max()) { v.push_back(0x19); // two-byte uint16_t add_to_vector(v, 2, j.m_value.number_integer); } else if (j.m_value.number_integer <= std::numeric_limits<uint32_t>::max()) { v.push_back(0x1a); // four-byte uint32_t add_to_vector(v, 4, j.m_value.number_integer); } else { v.push_back(0x1b); // eight-byte uint64_t add_to_vector(v, 8, j.m_value.number_integer); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { v.push_back(static_cast<uint8_t>(0x20 + positive_number)); } else if (positive_number <= std::numeric_limits<uint8_t>::max()) { // int 8 v.push_back(0x38); add_to_vector(v, 1, positive_number); } else if (positive_number <= std::numeric_limits<uint16_t>::max()) { // int 16 v.push_back(0x39); add_to_vector(v, 2, positive_number); } else if (positive_number <= std::numeric_limits<uint32_t>::max()) { // int 32 v.push_back(0x3a); add_to_vector(v, 4, positive_number); } else { // int 64 v.push_back(0x3b); add_to_vector(v, 8, positive_number); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= 0xff) { v.push_back(0x18); // one-byte uint8_t add_to_vector(v, 1, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= 0xffff) { v.push_back(0x19); // two-byte uint16_t add_to_vector(v, 2, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= 0xffffffff) { v.push_back(0x1a); // four-byte uint32_t add_to_vector(v, 4, j.m_value.number_unsigned); } else if (j.m_value.number_unsigned <= 0xffffffffffffffff) { v.push_back(0x1b); // eight-byte uint64_t add_to_vector(v, 8, j.m_value.number_unsigned); } break; } case value_t::number_float: { // Double-Precision Float v.push_back(0xfb); const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float)); for (size_t i = 0; i < 8; ++i) { v.push_back(helper[7 - i]); } break; } case value_t::string: { const auto N = j.m_value.string->size(); if (N <= 0x17) { v.push_back(0x60 + static_cast<uint8_t>(N)); // 1 byte for string + size } else if (N <= 0xff) { v.push_back(0x78); // one-byte uint8_t for N add_to_vector(v, 1, N); } else if (N <= 0xffff) { v.push_back(0x79); // two-byte uint16_t for N add_to_vector(v, 2, N); } else if (N <= 0xffffffff) { v.push_back(0x7a); // four-byte uint32_t for N add_to_vector(v, 4, N); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { v.push_back(0x7b); // eight-byte uint64_t for N add_to_vector(v, 8, N); } // LCOV_EXCL_STOP // append string std::copy(j.m_value.string->begin(), j.m_value.string->end(), std::back_inserter(v)); break; } case value_t::array: { const auto N = j.m_value.array->size(); if (N <= 0x17) { v.push_back(0x80 + static_cast<uint8_t>(N)); // 1 byte for array + size } else if (N <= 0xff) { v.push_back(0x98); // one-byte uint8_t for N add_to_vector(v, 1, N); } else if (N <= 0xffff) { v.push_back(0x99); // two-byte uint16_t for N add_to_vector(v, 2, N); } else if (N <= 0xffffffff) { v.push_back(0x9a); // four-byte uint32_t for N add_to_vector(v, 4, N); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { v.push_back(0x9b); // eight-byte uint64_t for N add_to_vector(v, 8, N); } // LCOV_EXCL_STOP // append each element for (const auto& el : *j.m_value.array) { to_cbor_internal(el, v); } break; } case value_t::object: { const auto N = j.m_value.object->size(); if (N <= 0x17) { v.push_back(0xa0 + static_cast<uint8_t>(N)); // 1 byte for object + size } else if (N <= 0xff) { v.push_back(0xb8); add_to_vector(v, 1, N); // one-byte uint8_t for N } else if (N <= 0xffff) { v.push_back(0xb9); add_to_vector(v, 2, N); // two-byte uint16_t for N } else if (N <= 0xffffffff) { v.push_back(0xba); add_to_vector(v, 4, N); // four-byte uint32_t for N } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { v.push_back(0xbb); add_to_vector(v, 8, N); // eight-byte uint64_t for N } // LCOV_EXCL_STOP // append each element for (const auto& el : *j.m_value.object) { to_cbor_internal(el.first, v); to_cbor_internal(el.second, v); } break; } default: { break; } } } /* @brief checks if given lengths do not exceed the size of a given vector To secure the access to the byte vector during CBOR/MessagePack deserialization, bytes are copied from the vector into buffers. This function checks if the number of bytes to copy (@a len) does not exceed the size @s size of the vector. Additionally, an @a offset is given from where to start reading the bytes. This function checks whether reading the bytes is safe; that is, offset is a valid index in the vector, offset+len @param[in] size size of the byte vector @param[in] len number of bytes to read @param[in] offset offset where to start reading vec: x x x x x X X X X X ^ ^ ^ 0 offset len @throws out_of_range if `len > v.size()` */ static void check_length(const size_t size, const size_t len, const size_t offset) { // simple case: requested length is greater than the vector's length if (len > size or offset > size) { JSON_THROW(std::out_of_range("len out of range")); } // second case: adding offset would result in overflow if ((size > (std::numeric_limits<size_t>::max() - offset))) { JSON_THROW(std::out_of_range("len+offset out of range")); } // last case: reading past the end of the vector if (len + offset > size) { JSON_THROW(std::out_of_range("len+offset out of range")); } } /*! @brief create a JSON value from a given MessagePack vector @param[in] v MessagePack serialization @param[in] idx byte index to start reading from @a v @return deserialized JSON value @throw std::invalid_argument if unsupported features from MessagePack were used in the given vector @a v or if the input is not valid MessagePack @throw std::out_of_range if the given vector ends prematurely @sa https://github.com/msgpack/msgpack/blob/master/spec.md */ static basic_json from_msgpack_internal(const std::vector<uint8_t>& v, size_t& idx) { // make sure reading 1 byte is safe check_length(v.size(), 1, idx); // store and increment index const size_t current_idx = idx++; if (v[current_idx] <= 0xbf) { if (v[current_idx] <= 0x7f) // positive fixint { return v[current_idx]; } if (v[current_idx] <= 0x8f) // fixmap { basic_json result = value_t::object; const size_t len = v[current_idx] & 0x0f; for (size_t i = 0; i < len; ++i) { std::string key = from_msgpack_internal(v, idx); result[key] = from_msgpack_internal(v, idx); } return result; } else if (v[current_idx] <= 0x9f) // fixarray { basic_json result = value_t::array; const size_t len = v[current_idx] & 0x0f; for (size_t i = 0; i < len; ++i) { result.push_back(from_msgpack_internal(v, idx)); } return result; } else // fixstr { const size_t len = v[current_idx] & 0x1f; const size_t offset = current_idx + 1; idx += len; // skip content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } } else if (v[current_idx] >= 0xe0) // negative fixint { return static_cast<int8_t>(v[current_idx]); } else { switch (v[current_idx]) { case 0xc0: // nil { return value_t::null; } case 0xc2: // false { return false; } case 0xc3: // true { return true; } case 0xca: // float 32 { // copy bytes in reverse order into the double variable float res; for (size_t byte = 0; byte < sizeof(float); ++byte) { reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); } idx += sizeof(float); // skip content bytes return res; } case 0xcb: // float 64 { // copy bytes in reverse order into the double variable double res; for (size_t byte = 0; byte < sizeof(double); ++byte) { reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); } idx += sizeof(double); // skip content bytes return res; } case 0xcc: // uint 8 { idx += 1; // skip content byte return get_from_vector<uint8_t>(v, current_idx); } case 0xcd: // uint 16 { idx += 2; // skip 2 content bytes return get_from_vector<uint16_t>(v, current_idx); } case 0xce: // uint 32 { idx += 4; // skip 4 content bytes return get_from_vector<uint32_t>(v, current_idx); } case 0xcf: // uint 64 { idx += 8; // skip 8 content bytes return get_from_vector<uint64_t>(v, current_idx); } case 0xd0: // int 8 { idx += 1; // skip content byte return get_from_vector<int8_t>(v, current_idx); } case 0xd1: // int 16 { idx += 2; // skip 2 content bytes return get_from_vector<int16_t>(v, current_idx); } case 0xd2: // int 32 { idx += 4; // skip 4 content bytes return get_from_vector<int32_t>(v, current_idx); } case 0xd3: // int 64 { idx += 8; // skip 8 content bytes return get_from_vector<int64_t>(v, current_idx); } case 0xd9: // str 8 { const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); const size_t offset = current_idx + 2; idx += len + 1; // skip size byte + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0xda: // str 16 { const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); const size_t offset = current_idx + 3; idx += len + 2; // skip 2 size bytes + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0xdb: // str 32 { const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); const size_t offset = current_idx + 5; idx += len + 4; // skip 4 size bytes + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0xdc: // array 16 { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); idx += 2; // skip 2 size bytes for (size_t i = 0; i < len; ++i) { result.push_back(from_msgpack_internal(v, idx)); } return result; } case 0xdd: // array 32 { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); idx += 4; // skip 4 size bytes for (size_t i = 0; i < len; ++i) { result.push_back(from_msgpack_internal(v, idx)); } return result; } case 0xde: // map 16 { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); idx += 2; // skip 2 size bytes for (size_t i = 0; i < len; ++i) { std::string key = from_msgpack_internal(v, idx); result[key] = from_msgpack_internal(v, idx); } return result; } case 0xdf: // map 32 { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); idx += 4; // skip 4 size bytes for (size_t i = 0; i < len; ++i) { std::string key = from_msgpack_internal(v, idx); result[key] = from_msgpack_internal(v, idx); } return result; } default: { JSON_THROW(std::invalid_argument("error parsing a msgpack @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])))); } } } } /*! @brief create a JSON value from a given CBOR vector @param[in] v CBOR serialization @param[in] idx byte index to start reading from @a v @return deserialized JSON value @throw std::invalid_argument if unsupported features from CBOR were used in the given vector @a v or if the input is not valid CBOR @throw std::out_of_range if the given vector ends prematurely @sa https://tools.ietf.org/html/rfc7049 */ static basic_json from_cbor_internal(const std::vector<uint8_t>& v, size_t& idx) { // store and increment index const size_t current_idx = idx++; switch (v.at(current_idx)) { // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: { return v[current_idx]; } case 0x18: // Unsigned integer (one-byte uint8_t follows) { idx += 1; // skip content byte return get_from_vector<uint8_t>(v, current_idx); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { idx += 2; // skip 2 content bytes return get_from_vector<uint16_t>(v, current_idx); } case 0x1a: // Unsigned integer (four-byte uint32_t follows) { idx += 4; // skip 4 content bytes return get_from_vector<uint32_t>(v, current_idx); } case 0x1b: // Unsigned integer (eight-byte uint64_t follows) { idx += 8; // skip 8 content bytes return get_from_vector<uint64_t>(v, current_idx); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: { return static_cast<int8_t>(0x20 - 1 - v[current_idx]); } case 0x38: // Negative integer (one-byte uint8_t follows) { idx += 1; // skip content byte // must be uint8_t ! return static_cast<number_integer_t>(-1) - get_from_vector<uint8_t>(v, current_idx); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { idx += 2; // skip 2 content bytes return static_cast<number_integer_t>(-1) - get_from_vector<uint16_t>(v, current_idx); } case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) { idx += 4; // skip 4 content bytes return static_cast<number_integer_t>(-1) - get_from_vector<uint32_t>(v, current_idx); } case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) { idx += 8; // skip 8 content bytes return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_from_vector<uint64_t>(v, current_idx)); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { const auto len = static_cast<size_t>(v[current_idx] - 0x60); const size_t offset = current_idx + 1; idx += len; // skip content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); const size_t offset = current_idx + 2; idx += len + 1; // skip size byte + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); const size_t offset = current_idx + 3; idx += len + 2; // skip 2 size bytes + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) { const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); const size_t offset = current_idx + 5; idx += len + 4; // skip 4 size bytes + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) { const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); const size_t offset = current_idx + 9; idx += len + 8; // skip 8 size bytes + content bytes check_length(v.size(), len, offset); return std::string(reinterpret_cast<const char*>(v.data()) + offset, len); } case 0x7f: // UTF-8 string (indefinite length) { std::string result; while (v.at(idx) != 0xff) { string_t s = from_cbor_internal(v, idx); result += s; } // skip break byte (0xFF) idx += 1; return result; } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: { basic_json result = value_t::array; const auto len = static_cast<size_t>(v[current_idx] - 0x80); for (size_t i = 0; i < len; ++i) { result.push_back(from_cbor_internal(v, idx)); } return result; } case 0x98: // array (one-byte uint8_t for n follows) { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); idx += 1; // skip 1 size byte for (size_t i = 0; i < len; ++i) { result.push_back(from_cbor_internal(v, idx)); } return result; } case 0x99: // array (two-byte uint16_t for n follow) { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); idx += 2; // skip 4 size bytes for (size_t i = 0; i < len; ++i) { result.push_back(from_cbor_internal(v, idx)); } return result; } case 0x9a: // array (four-byte uint32_t for n follow) { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); idx += 4; // skip 4 size bytes for (size_t i = 0; i < len; ++i) { result.push_back(from_cbor_internal(v, idx)); } return result; } case 0x9b: // array (eight-byte uint64_t for n follow) { basic_json result = value_t::array; const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); idx += 8; // skip 8 size bytes for (size_t i = 0; i < len; ++i) { result.push_back(from_cbor_internal(v, idx)); } return result; } case 0x9f: // array (indefinite length) { basic_json result = value_t::array; while (v.at(idx) != 0xff) { result.push_back(from_cbor_internal(v, idx)); } // skip break byte (0xFF) idx += 1; return result; } // map (0x00..0x17 pairs of data items follow) case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: { basic_json result = value_t::object; const auto len = static_cast<size_t>(v[current_idx] - 0xa0); for (size_t i = 0; i < len; ++i) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } return result; } case 0xb8: // map (one-byte uint8_t for n follows) { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx)); idx += 1; // skip 1 size byte for (size_t i = 0; i < len; ++i) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } return result; } case 0xb9: // map (two-byte uint16_t for n follow) { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx)); idx += 2; // skip 2 size bytes for (size_t i = 0; i < len; ++i) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } return result; } case 0xba: // map (four-byte uint32_t for n follow) { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx)); idx += 4; // skip 4 size bytes for (size_t i = 0; i < len; ++i) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } return result; } case 0xbb: // map (eight-byte uint64_t for n follow) { basic_json result = value_t::object; const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx)); idx += 8; // skip 8 size bytes for (size_t i = 0; i < len; ++i) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } return result; } case 0xbf: // map (indefinite length) { basic_json result = value_t::object; while (v.at(idx) != 0xff) { std::string key = from_cbor_internal(v, idx); result[key] = from_cbor_internal(v, idx); } // skip break byte (0xFF) idx += 1; return result; } case 0xf4: // false { return false; } case 0xf5: // true { return true; } case 0xf6: // null { return value_t::null; } case 0xf9: // Half-Precision Float (two-byte IEEE 754) { idx += 2; // skip two content bytes // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added to // IEEE 754 in 2008, today's programming platforms often still // only have limited support for them. It is very easy to // include at least decoding support for them even without such // support. An example of a small decoder for half-precision // floating-point numbers in the C language is shown in Fig. 3. const int half = (v.at(current_idx + 1) << 8) + v.at(current_idx + 2); const int exp = (half >> 10) & 0x1f; const int mant = half & 0x3ff; double val; if (exp == 0) { val = std::ldexp(mant, -24); } else if (exp != 31) { val = std::ldexp(mant + 1024, exp - 25); } else { val = mant == 0 ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::quiet_NaN(); } return (half & 0x8000) != 0 ? -val : val; } case 0xfa: // Single-Precision Float (four-byte IEEE 754) { // copy bytes in reverse order into the float variable float res; for (size_t byte = 0; byte < sizeof(float); ++byte) { reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); } idx += sizeof(float); // skip content bytes return res; } case 0xfb: // Double-Precision Float (eight-byte IEEE 754) { // copy bytes in reverse order into the double variable double res; for (size_t byte = 0; byte < sizeof(double); ++byte) { reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); } idx += sizeof(double); // skip content bytes return res; } default: // anything else (0xFF is handled inside the other types) { JSON_THROW(std::invalid_argument("error parsing a CBOR @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])))); } } } public: /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @since version 2.0.9 */ static std::vector<uint8_t> to_msgpack(const basic_json& j) { std::vector<uint8_t> result; to_msgpack_internal(j, result); return result; } /*! @brief create a JSON value from a byte vector in MessagePack format Deserializes a given byte vector @a v to a JSON value using the MessagePack serialization format. @param[in] v a byte vector in MessagePack format @param[in] start_index the index to start reading from @a v (0 by default) @return deserialized JSON value @throw std::invalid_argument if unsupported features from MessagePack were used in the given vector @a v or if the input is not valid MessagePack @throw std::out_of_range if the given vector ends prematurely @complexity Linear in the size of the byte vector @a v. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa @ref to_msgpack(const basic_json&) for the analogous serialization @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the related CBOR format @since version 2.0.9, parameter @a start_index since 2.1.1 */ static basic_json from_msgpack(const std::vector<uint8_t>& v, const size_t start_index = 0) { size_t i = start_index; return from_msgpack_internal(v, i); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_msgpack(const basic_json& for the related MessagePack format @since version 2.0.9 */ static std::vector<uint8_t> to_cbor(const basic_json& j) { std::vector<uint8_t> result; to_cbor_internal(j, result); return result; } /*! @brief create a JSON value from a byte vector in CBOR format Deserializes a given byte vector @a v to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. @param[in] v a byte vector in CBOR format @param[in] start_index the index to start reading from @a v (0 by default) @return deserialized JSON value @throw std::invalid_argument if unsupported features from CBOR were used in the given vector @a v or if the input is not valid MessagePack @throw std::out_of_range if the given vector ends prematurely @complexity Linear in the size of the byte vector @a v. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa @ref to_cbor(const basic_json&) for the analogous serialization @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the related MessagePack format @since version 2.0.9, parameter @a start_index since 2.1.1 */ static basic_json from_cbor(const std::vector<uint8_t>& v, const size_t start_index = 0) { size_t i = start_index; return from_cbor_internal(v, i); } /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return basically a string representation of a the @a m_type member @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @since version 1.0.0, public since 2.1.0 */ std::string type_name() const { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::discarded: return "discarded"; default: return "number"; } } } private: /*! @brief calculates the extra space to escape a JSON string @param[in] s the string to escape @return the number of characters required to escape string @a s @complexity Linear in the length of string @a s. */ static std::size_t extra_space(const string_t& s) noexcept { return std::accumulate(s.begin(), s.end(), size_t{}, [](size_t res, typename string_t::value_type c) { switch (c) { case '"': case '\\': case '\b': case '\f': case '\n': case '\r': case '\t': { // from c (1 byte) to \x (2 bytes) return res + 1; } default: { if (c >= 0x00 and c <= 0x1f) { // from c (1 byte) to \uxxxx (6 bytes) return res + 5; } return res; } } }); } /*! @brief escape a string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. @param[in] s the string to escape @return the escaped string @complexity Linear in the length of string @a s. */ static string_t escape_string(const string_t& s) { const auto space = extra_space(s); if (space == 0) { return s; } // create a result string of necessary size string_t result(s.size() + space, '\\'); std::size_t pos = 0; for (const auto& c : s) { switch (c) { // quotation mark (0x22) case '"': { result[pos + 1] = '"'; pos += 2; break; } // reverse solidus (0x5c) case '\\': { // nothing to change pos += 2; break; } // backspace (0x08) case '\b': { result[pos + 1] = 'b'; pos += 2; break; } // formfeed (0x0c) case '\f': { result[pos + 1] = 'f'; pos += 2; break; } // newline (0x0a) case '\n': { result[pos + 1] = 'n'; pos += 2; break; } // carriage return (0x0d) case '\r': { result[pos + 1] = 'r'; pos += 2; break; } // horizontal tab (0x09) case '\t': { result[pos + 1] = 't'; pos += 2; break; } default: { if (c >= 0x00 and c <= 0x1f) { // convert a number 0..15 to its hex representation // (0..f) static const char hexify[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; // print character c as \uxxxx for (const char m : { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f] }) { result[++pos] = m; } ++pos; } else { // all other characters are added as-is result[pos++] = c; } break; } } } return result; } /*! @brief locale-independent serialization for built-in arithmetic types */ struct numtostr { public: template<typename NumberType> numtostr(NumberType value) { x_write(value, std::is_integral<NumberType>()); } const char* c_str() const { return m_buf.data(); } private: /// a (hopefully) large enough character buffer std::array < char, 64 > m_buf{{}}; template<typename NumberType> void x_write(NumberType x, /*is_integral=*/std::true_type) { // special case for "0" if (x == 0) { m_buf[0] = '0'; return; } const bool is_negative = x < 0; size_t i = 0; // spare 1 byte for '\0' while (x != 0 and i < m_buf.size() - 1) { const auto digit = std::labs(static_cast<long>(x % 10)); m_buf[i++] = static_cast<char>('0' + digit); x /= 10; } // make sure the number has been processed completely assert(x == 0); if (is_negative) { // make sure there is capacity for the '-' assert(i < m_buf.size() - 2); m_buf[i++] = '-'; } std::reverse(m_buf.begin(), m_buf.begin() + i); } template<typename NumberType> void x_write(NumberType x, /*is_integral=*/std::false_type) { // special case for 0.0 and -0.0 if (x == 0) { size_t i = 0; if (std::signbit(x)) { m_buf[i++] = '-'; } m_buf[i++] = '0'; m_buf[i++] = '.'; m_buf[i] = '0'; return; } // get number of digits for a text -> float -> text round-trip static constexpr auto d = std::numeric_limits<NumberType>::digits10; // the actual conversion const auto written_bytes = snprintf(m_buf.data(), m_buf.size(), "%.*g", d, x); // negative value indicates an error assert(written_bytes > 0); // check if buffer was large enough assert(static_cast<size_t>(written_bytes) < m_buf.size()); // read information from locale const auto loc = localeconv(); assert(loc != nullptr); const char thousands_sep = !loc->thousands_sep ? '\0' : loc->thousands_sep[0]; const char decimal_point = !loc->decimal_point ? '\0' : loc->decimal_point[0]; // erase thousands separator if (thousands_sep != '\0') { const auto end = std::remove(m_buf.begin(), m_buf.begin() + written_bytes, thousands_sep); std::fill(end, m_buf.end(), '\0'); } // convert decimal point to '.' if (decimal_point != '\0' and decimal_point != '.') { for (auto& c : m_buf) { if (c == decimal_point) { c = '.'; break; } } } // determine if need to append ".0" size_t i = 0; bool value_is_int_like = true; for (i = 0; i < m_buf.size(); ++i) { // break when end of number is reached if (m_buf[i] == '\0') { break; } // check if we find non-int character value_is_int_like = value_is_int_like and m_buf[i] != '.' and m_buf[i] != 'e' and m_buf[i] != 'E'; } if (value_is_int_like) { // there must be 2 bytes left for ".0" assert((i + 2) < m_buf.size()); // we write to the end of the number assert(m_buf[i] == '\0'); assert(m_buf[i - 1] != '\0'); // add ".0" m_buf[i] = '.'; m_buf[i + 1] = '0'; // the resulting string is properly terminated assert(m_buf[i + 2] == '\0'); } } }; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. Note that - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format @param[out] o stream to write to @param[in] pretty_print whether the output shall be pretty-printed @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(std::ostream& o, const bool pretty_print, const unsigned int indent_step, const unsigned int current_indent = 0) const { // variable to hold indentation for recursive calls unsigned int new_indent = current_indent; switch (m_type) { case value_t::object: { if (m_value.object->empty()) { o << "{}"; return; } o << "{"; // increase indentation if (pretty_print) { new_indent += indent_step; o << "\n"; } for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i) { if (i != m_value.object->cbegin()) { o << (pretty_print ? ",\n" : ","); } o << string_t(new_indent, '\t') << "\"" << escape_string(i->first) << "\":" << (pretty_print ? " " : ""); i->second.dump(o, pretty_print, indent_step, new_indent); } // decrease indentation if (pretty_print) { new_indent -= indent_step; o << "\n"; } o << string_t(new_indent, '\t') + "}"; return; } case value_t::array: { if (m_value.array->empty()) { o << "[]"; return; } o << "["; // increase indentation if (pretty_print) { new_indent += indent_step; o << "\n"; } for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i) { if (i != m_value.array->cbegin()) { o << (pretty_print ? ",\n" : ","); } o << string_t(new_indent, '\t'); i->dump(o, pretty_print, indent_step, new_indent); } // decrease indentation if (pretty_print) { new_indent -= indent_step; o << "\n"; } o << string_t(new_indent, '\t') << "]"; return; } case value_t::string: { o << string_t("\"") << escape_string(*m_value.string) << "\""; return; } case value_t::boolean: { o << (m_value.boolean ? "true" : "false"); return; } case value_t::number_integer: { o << numtostr(m_value.number_integer).c_str(); return; } case value_t::number_unsigned: { o << numtostr(m_value.number_unsigned).c_str(); return; } case value_t::number_float: { o << numtostr(m_value.number_float).c_str(); return; } case value_t::discarded: { o << "<discarded>"; return; } case value_t::null: { o << "null"; return; } } } private: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; private: /////////////// // iterators // /////////////// /*! @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { public: difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return (m_it == begin_value); } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return (m_it == end_value); } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return !(lhs == rhs); } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it <= rhs.m_it; } friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it > rhs.m_it; } friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it >= rhs.m_it; } primitive_iterator_t operator+(difference_type i) { auto result = *this; result += i; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it) { return os << it.m_it; } primitive_iterator_t& operator++() { ++m_it; return *this; } primitive_iterator_t operator++(int) { auto result = *this; m_it++; return result; } primitive_iterator_t& operator--() { --m_it; return *this; } primitive_iterator_t operator--(int) { auto result = *this; m_it--; return result; } primitive_iterator_t& operator+=(difference_type n) { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) { m_it -= n; return *this; } private: static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; /// iterator as signed integer type difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min(); }; /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ struct internal_iterator { /// iterator for JSON objects typename object_t::iterator object_iterator; /// iterator for JSON arrays typename array_t::iterator array_iterator; /// generic iterator for all other types primitive_iterator_t primitive_iterator; /// create an uninitialized internal_iterator internal_iterator() noexcept : object_iterator(), array_iterator(), primitive_iterator() {} }; /// proxy class for the iterator_wrapper functions template<typename IteratorType> class iteration_proxy { private: /// helper class for iteration class iteration_proxy_internal { private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) size_t array_index = 0; public: explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_internal& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_internal& operator++() { ++anchor; ++array_index; return *this; } /// inequality operator (needed for range-based for) bool operator!= (const iteration_proxy_internal& o) const { return anchor != o.anchor; } /// return key of the iterator typename basic_json::string_t key() const { assert(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { return std::to_string(array_index); } // use key from the object case value_t::object: { return anchor.key(); } // use an empty key for all primitive types default: { return ""; } } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_internal begin() noexcept { return iteration_proxy_internal(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_internal end() noexcept { return iteration_proxy_internal(container.end()); } }; public: /*! @brief a template for a random access iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. @since version 1.0.0, simplified in version 2.0.9 */ template<typename U> class iter_impl : public std::iterator<std::random_access_iterator_tag, U> { /// allow basic_json to access private members friend class basic_json; // make sure U is basic_json or const basic_json static_assert(std::is_same<U, basic_json>::value or std::is_same<U, const basic_json>::value, "iter_impl only accepts (const) basic_json"); public: /// the type of the values when the iterator is dereferenced using value_type = typename basic_json::value_type; /// a type to represent differences between iterators using difference_type = typename basic_json::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional<std::is_const<U>::value, typename basic_json::const_pointer, typename basic_json::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional<std::is_const<U>::value, typename basic_json::const_reference, typename basic_json::reference>::type; /// the category of the iterator using iterator_category = std::bidirectional_iterator_tag; /// default constructor iter_impl() = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case basic_json::value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /* Use operator `const_iterator` instead of `const_iterator(const iterator& other) noexcept` to avoid two class definitions for @ref iterator and @ref const_iterator. This function is only called if this class is an @ref iterator. If this class is a @ref const_iterator this function is not called. */ operator const_iterator() const { const_iterator ret; if (m_object) { ret.m_object = m_object; ret.m_it = m_it; } return ret; } /*! @brief copy constructor @param[in] other iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief copy assignment @param[in,out] other iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl& operator=(iter_impl other) noexcept( std::is_nothrow_move_constructible<pointer>::value and std::is_nothrow_move_assignable<pointer>::value and std::is_nothrow_move_constructible<internal_iterator>::value and std::is_nothrow_move_assignable<internal_iterator>::value ) { std::swap(m_object, other.m_object); std::swap(m_it, other.m_it); return *this; } private: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case basic_json::value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case basic_json::value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case basic_json::value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case basic_json::value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case basic_json::value_t::null: { JSON_THROW(std::out_of_range("cannot get value")); } default: { if (m_it.primitive_iterator.is_begin()) { return *m_object; } JSON_THROW(std::out_of_range("cannot get value")); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case basic_json::value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (m_it.primitive_iterator.is_begin()) { return m_object; } JSON_THROW(std::out_of_range("cannot get value")); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator++(int) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { std::advance(m_it.object_iterator, 1); break; } case basic_json::value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator--(int) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { std::advance(m_it.object_iterator, -1); break; } case basic_json::value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator==(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (m_object != other.m_object) { JSON_THROW(std::domain_error("cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { return (m_it.object_iterator == other.m_it.object_iterator); } case basic_json::value_t::array: { return (m_it.array_iterator == other.m_it.array_iterator); } default: { return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator!=(const iter_impl& other) const { return not operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (m_object != other.m_object) { JSON_THROW(std::domain_error("cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { JSON_THROW(std::domain_error("cannot compare order of object iterators")); } case basic_json::value_t::array: { return (m_it.array_iterator < other.m_it.array_iterator); } default: { return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return not other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return not operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return not operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { JSON_THROW(std::domain_error("cannot use offsets with object iterators")); } case basic_json::value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) { auto result = *this; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { JSON_THROW(std::domain_error("cannot use offsets with object iterators")); } case basic_json::value_t::array: { return m_it.array_iterator - other.m_it.array_iterator; } default: { return m_it.primitive_iterator - other.m_it.primitive_iterator; } } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { assert(m_object != nullptr); switch (m_object->m_type) { case basic_json::value_t::object: { JSON_THROW(std::domain_error("cannot use operator[] for object iterators")); } case basic_json::value_t::array: { return *std::next(m_it.array_iterator, n); } case basic_json::value_t::null: { JSON_THROW(std::out_of_range("cannot get value")); } default: { if (m_it.primitive_iterator.get_value() == -n) { return *m_object; } JSON_THROW(std::out_of_range("cannot get value")); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ typename object_t::key_type key() const { assert(m_object != nullptr); if (m_object->is_object()) { return m_it.object_iterator->first; } JSON_THROW(std::domain_error("cannot use key() for non-object iterators")); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } private: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator m_it = internal_iterator(); }; /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template<typename Base> class json_reverse_iterator : public std::reverse_iterator<Base> { public: /// shortcut to the reverse iterator adaptor using base_iterator = std::reverse_iterator<Base>; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator operator++(int) { return base_iterator::operator++(1); } /// pre-increment (++it) json_reverse_iterator& operator++() { base_iterator::operator++(); return *this; } /// post-decrement (it--) json_reverse_iterator operator--(int) { return base_iterator::operator--(1); } /// pre-decrement (--it) json_reverse_iterator& operator--() { base_iterator::operator--(); return *this; } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { base_iterator::operator+=(i); return *this; } /// add to iterator json_reverse_iterator operator+(difference_type i) const { auto result = *this; result += i; return result; } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { auto result = *this; result -= i; return result; } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return this->base() - other.base(); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator typename object_t::key_type key() const { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; private: ////////////////////// // lexer and parser // ////////////////////// /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. The core of it is a scanner generated by [re2c](http://re2c.org) that processes a buffer and recognizes tokens according to RFC 7159. */ class lexer { public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number() for actual value value_integer, ///< a signed integer -- use get_number() for actual value value_float, ///< an floating point number -- use get_number() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input ///< indicating the end of the input buffer }; /// the char type to use in the lexer using lexer_char_t = unsigned char; /// a lexer from a buffer with given length lexer(const lexer_char_t* buff, const size_t len) noexcept : m_content(buff) { assert(m_content != nullptr); m_start = m_cursor = m_content; m_limit = m_content + len; } /// a lexer from an input stream explicit lexer(std::istream& s) : m_stream(&s), m_line_buffer() { // immediately abort if stream is erroneous if (s.fail()) { JSON_THROW(std::invalid_argument("stream error")); } // fill buffer fill_line_buffer(); // skip UTF-8 byte-order mark if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF") { m_line_buffer[0] = ' '; m_line_buffer[1] = ' '; m_line_buffer[2] = ' '; } } // switch off unwanted functions (due to pointer members) lexer() = delete; lexer(const lexer&) = delete; lexer operator=(const lexer&) = delete; /*! @brief create a string from one or two Unicode code points There are two cases: (1) @a codepoint1 is in the Basic Multilingual Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2) @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to represent a code point above U+FFFF. @param[in] codepoint1 the code point (can be high surrogate) @param[in] codepoint2 the code point (can be low surrogate or 0) @return string representation of the code point; the length of the result string is between 1 and 4 characters. @throw std::out_of_range if code point is > 0x10ffff; example: `"code points above 0x10FFFF are invalid"` @throw std::invalid_argument if the low surrogate is invalid; example: `""missing or wrong low surrogate""` @complexity Constant. @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code> */ static string_t to_unicode(const std::size_t codepoint1, const std::size_t codepoint2 = 0) { // calculate the code point from the given code points std::size_t codepoint = codepoint1; // check if codepoint1 is a high surrogate if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF) { // check if codepoint2 is a low surrogate if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF) { codepoint = // high surrogate occupies the most significant 22 bits (codepoint1 << 10) // low surrogate occupies the least significant 15 bits + codepoint2 // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00; } else { JSON_THROW(std::invalid_argument("missing or wrong low surrogate")); } } string_t result; if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) result.append(1, static_cast<typename string_t::value_type>(codepoint)); } else if (codepoint <= 0x7ff) { // 2-byte characters: 110xxxxx 10xxxxxx result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F))); result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); } else if (codepoint <= 0xffff) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F))); result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F))); result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); } else if (codepoint <= 0x10ffff) { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07))); result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F))); result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F))); result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F))); } else { JSON_THROW(std::out_of_range("code points above 0x10FFFF are invalid")); } return result; } /// return name of values of type token_type (only used for errors) static std::string token_type_name(const token_type t) { switch (t) { case token_type::uninitialized: return "<uninitialized>"; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case lexer::token_type::value_unsigned: case lexer::token_type::value_integer: case lexer::token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return "<parse error>"; case token_type::end_of_input: return "end of input"; default: { // catch non-enum values return "unknown token"; // LCOV_EXCL_LINE } } } /*! This function implements a scanner for JSON. It is specified using regular expressions that try to follow RFC 7159 as close as possible. These regular expressions are then translated into a minimized deterministic finite automaton (DFA) by the tool [re2c](http://re2c.org). As a result, the translated code for this function consists of a large block of code with `goto` jumps. @return the class of the next token read from the buffer @complexity Linear in the length of the input.\n Proposition: The loop below will always terminate for finite input.\n Proof (by contradiction): Assume a finite input. To loop forever, the loop must never hit code with a `break` statement. The only code snippets without a `break` statement are the continue statements for whitespace and byte-order-marks. To loop forever, the input must be an infinite sequence of whitespace or byte-order-marks. This contradicts the assumption of finite input, q.e.d. */ token_type scan() { while (true) { // pointer for backtracking information m_marker = nullptr; // remember the begin of the token m_start = m_cursor; assert(m_start != nullptr); { lexer_char_t yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((m_limit - m_cursor) < 5) { fill_line_buffer(5); // LCOV_EXCL_LINE } yych = *m_cursor; if (yybm[0 + yych] & 32) { goto basic_json_parser_6; } if (yych <= '[') { if (yych <= '-') { if (yych <= '"') { if (yych <= 0x00) { goto basic_json_parser_2; } if (yych <= '!') { goto basic_json_parser_4; } goto basic_json_parser_9; } else { if (yych <= '+') { goto basic_json_parser_4; } if (yych <= ',') { goto basic_json_parser_10; } goto basic_json_parser_12; } } else { if (yych <= '9') { if (yych <= '/') { goto basic_json_parser_4; } if (yych <= '0') { goto basic_json_parser_13; } goto basic_json_parser_15; } else { if (yych <= ':') { goto basic_json_parser_17; } if (yych <= 'Z') { goto basic_json_parser_4; } goto basic_json_parser_19; } } } else { if (yych <= 'n') { if (yych <= 'e') { if (yych == ']') { goto basic_json_parser_21; } goto basic_json_parser_4; } else { if (yych <= 'f') { goto basic_json_parser_23; } if (yych <= 'm') { goto basic_json_parser_4; } goto basic_json_parser_24; } } else { if (yych <= 'z') { if (yych == 't') { goto basic_json_parser_25; } goto basic_json_parser_4; } else { if (yych <= '{') { goto basic_json_parser_26; } if (yych == '}') { goto basic_json_parser_28; } goto basic_json_parser_4; } } } basic_json_parser_2: ++m_cursor; { last_token_type = token_type::end_of_input; break; } basic_json_parser_4: ++m_cursor; basic_json_parser_5: { last_token_type = token_type::parse_error; break; } basic_json_parser_6: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yybm[0 + yych] & 32) { goto basic_json_parser_6; } { continue; } basic_json_parser_9: yyaccept = 0; yych = *(m_marker = ++m_cursor); if (yych <= 0x1F) { goto basic_json_parser_5; } if (yych <= 0x7F) { goto basic_json_parser_31; } if (yych <= 0xC1) { goto basic_json_parser_5; } if (yych <= 0xF4) { goto basic_json_parser_31; } goto basic_json_parser_5; basic_json_parser_10: ++m_cursor; { last_token_type = token_type::value_separator; break; } basic_json_parser_12: yych = *++m_cursor; if (yych <= '/') { goto basic_json_parser_5; } if (yych <= '0') { goto basic_json_parser_43; } if (yych <= '9') { goto basic_json_parser_45; } goto basic_json_parser_5; basic_json_parser_13: yyaccept = 1; yych = *(m_marker = ++m_cursor); if (yych <= '9') { if (yych == '.') { goto basic_json_parser_47; } if (yych >= '0') { goto basic_json_parser_48; } } else { if (yych <= 'E') { if (yych >= 'E') { goto basic_json_parser_51; } } else { if (yych == 'e') { goto basic_json_parser_51; } } } basic_json_parser_14: { last_token_type = token_type::value_unsigned; break; } basic_json_parser_15: yyaccept = 1; m_marker = ++m_cursor; if ((m_limit - m_cursor) < 3) { fill_line_buffer(3); // LCOV_EXCL_LINE } yych = *m_cursor; if (yybm[0 + yych] & 64) { goto basic_json_parser_15; } if (yych <= 'D') { if (yych == '.') { goto basic_json_parser_47; } goto basic_json_parser_14; } else { if (yych <= 'E') { goto basic_json_parser_51; } if (yych == 'e') { goto basic_json_parser_51; } goto basic_json_parser_14; } basic_json_parser_17: ++m_cursor; { last_token_type = token_type::name_separator; break; } basic_json_parser_19: ++m_cursor; { last_token_type = token_type::begin_array; break; } basic_json_parser_21: ++m_cursor; { last_token_type = token_type::end_array; break; } basic_json_parser_23: yyaccept = 0; yych = *(m_marker = ++m_cursor); if (yych == 'a') { goto basic_json_parser_52; } goto basic_json_parser_5; basic_json_parser_24: yyaccept = 0; yych = *(m_marker = ++m_cursor); if (yych == 'u') { goto basic_json_parser_53; } goto basic_json_parser_5; basic_json_parser_25: yyaccept = 0; yych = *(m_marker = ++m_cursor); if (yych == 'r') { goto basic_json_parser_54; } goto basic_json_parser_5; basic_json_parser_26: ++m_cursor; { last_token_type = token_type::begin_object; break; } basic_json_parser_28: ++m_cursor; { last_token_type = token_type::end_object; break; } basic_json_parser_30: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; basic_json_parser_31: if (yybm[0 + yych] & 128) { goto basic_json_parser_30; } if (yych <= 0xE0) { if (yych <= '\\') { if (yych <= 0x1F) { goto basic_json_parser_32; } if (yych <= '"') { goto basic_json_parser_33; } goto basic_json_parser_35; } else { if (yych <= 0xC1) { goto basic_json_parser_32; } if (yych <= 0xDF) { goto basic_json_parser_36; } goto basic_json_parser_37; } } else { if (yych <= 0xEF) { if (yych == 0xED) { goto basic_json_parser_39; } goto basic_json_parser_38; } else { if (yych <= 0xF0) { goto basic_json_parser_40; } if (yych <= 0xF3) { goto basic_json_parser_41; } if (yych <= 0xF4) { goto basic_json_parser_42; } } } basic_json_parser_32: m_cursor = m_marker; if (yyaccept <= 1) { if (yyaccept == 0) { goto basic_json_parser_5; } else { goto basic_json_parser_14; } } else { if (yyaccept == 2) { goto basic_json_parser_44; } else { goto basic_json_parser_58; } } basic_json_parser_33: ++m_cursor; { last_token_type = token_type::value_string; break; } basic_json_parser_35: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 'e') { if (yych <= '/') { if (yych == '"') { goto basic_json_parser_30; } if (yych <= '.') { goto basic_json_parser_32; } goto basic_json_parser_30; } else { if (yych <= '\\') { if (yych <= '[') { goto basic_json_parser_32; } goto basic_json_parser_30; } else { if (yych == 'b') { goto basic_json_parser_30; } goto basic_json_parser_32; } } } else { if (yych <= 'q') { if (yych <= 'f') { goto basic_json_parser_30; } if (yych == 'n') { goto basic_json_parser_30; } goto basic_json_parser_32; } else { if (yych <= 's') { if (yych <= 'r') { goto basic_json_parser_30; } goto basic_json_parser_32; } else { if (yych <= 't') { goto basic_json_parser_30; } if (yych <= 'u') { goto basic_json_parser_55; } goto basic_json_parser_32; } } } basic_json_parser_36: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x7F) { goto basic_json_parser_32; } if (yych <= 0xBF) { goto basic_json_parser_30; } goto basic_json_parser_32; basic_json_parser_37: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x9F) { goto basic_json_parser_32; } if (yych <= 0xBF) { goto basic_json_parser_36; } goto basic_json_parser_32; basic_json_parser_38: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x7F) { goto basic_json_parser_32; } if (yych <= 0xBF) { goto basic_json_parser_36; } goto basic_json_parser_32; basic_json_parser_39: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x7F) { goto basic_json_parser_32; } if (yych <= 0x9F) { goto basic_json_parser_36; } goto basic_json_parser_32; basic_json_parser_40: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x8F) { goto basic_json_parser_32; } if (yych <= 0xBF) { goto basic_json_parser_38; } goto basic_json_parser_32; basic_json_parser_41: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x7F) { goto basic_json_parser_32; } if (yych <= 0xBF) { goto basic_json_parser_38; } goto basic_json_parser_32; basic_json_parser_42: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 0x7F) { goto basic_json_parser_32; } if (yych <= 0x8F) { goto basic_json_parser_38; } goto basic_json_parser_32; basic_json_parser_43: yyaccept = 2; yych = *(m_marker = ++m_cursor); if (yych <= '9') { if (yych == '.') { goto basic_json_parser_47; } if (yych >= '0') { goto basic_json_parser_48; } } else { if (yych <= 'E') { if (yych >= 'E') { goto basic_json_parser_51; } } else { if (yych == 'e') { goto basic_json_parser_51; } } } basic_json_parser_44: { last_token_type = token_type::value_integer; break; } basic_json_parser_45: yyaccept = 2; m_marker = ++m_cursor; if ((m_limit - m_cursor) < 3) { fill_line_buffer(3); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '9') { if (yych == '.') { goto basic_json_parser_47; } if (yych <= '/') { goto basic_json_parser_44; } goto basic_json_parser_45; } else { if (yych <= 'E') { if (yych <= 'D') { goto basic_json_parser_44; } goto basic_json_parser_51; } else { if (yych == 'e') { goto basic_json_parser_51; } goto basic_json_parser_44; } } basic_json_parser_47: yych = *++m_cursor; if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_56; } goto basic_json_parser_32; basic_json_parser_48: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '/') { goto basic_json_parser_50; } if (yych <= '9') { goto basic_json_parser_48; } basic_json_parser_50: { last_token_type = token_type::parse_error; break; } basic_json_parser_51: yych = *++m_cursor; if (yych <= ',') { if (yych == '+') { goto basic_json_parser_59; } goto basic_json_parser_32; } else { if (yych <= '-') { goto basic_json_parser_59; } if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_60; } goto basic_json_parser_32; } basic_json_parser_52: yych = *++m_cursor; if (yych == 'l') { goto basic_json_parser_62; } goto basic_json_parser_32; basic_json_parser_53: yych = *++m_cursor; if (yych == 'l') { goto basic_json_parser_63; } goto basic_json_parser_32; basic_json_parser_54: yych = *++m_cursor; if (yych == 'u') { goto basic_json_parser_64; } goto basic_json_parser_32; basic_json_parser_55: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '@') { if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_65; } goto basic_json_parser_32; } else { if (yych <= 'F') { goto basic_json_parser_65; } if (yych <= '`') { goto basic_json_parser_32; } if (yych <= 'f') { goto basic_json_parser_65; } goto basic_json_parser_32; } basic_json_parser_56: yyaccept = 3; m_marker = ++m_cursor; if ((m_limit - m_cursor) < 3) { fill_line_buffer(3); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= 'D') { if (yych <= '/') { goto basic_json_parser_58; } if (yych <= '9') { goto basic_json_parser_56; } } else { if (yych <= 'E') { goto basic_json_parser_51; } if (yych == 'e') { goto basic_json_parser_51; } } basic_json_parser_58: { last_token_type = token_type::value_float; break; } basic_json_parser_59: yych = *++m_cursor; if (yych <= '/') { goto basic_json_parser_32; } if (yych >= ':') { goto basic_json_parser_32; } basic_json_parser_60: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '/') { goto basic_json_parser_58; } if (yych <= '9') { goto basic_json_parser_60; } goto basic_json_parser_58; basic_json_parser_62: yych = *++m_cursor; if (yych == 's') { goto basic_json_parser_66; } goto basic_json_parser_32; basic_json_parser_63: yych = *++m_cursor; if (yych == 'l') { goto basic_json_parser_67; } goto basic_json_parser_32; basic_json_parser_64: yych = *++m_cursor; if (yych == 'e') { goto basic_json_parser_69; } goto basic_json_parser_32; basic_json_parser_65: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '@') { if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_71; } goto basic_json_parser_32; } else { if (yych <= 'F') { goto basic_json_parser_71; } if (yych <= '`') { goto basic_json_parser_32; } if (yych <= 'f') { goto basic_json_parser_71; } goto basic_json_parser_32; } basic_json_parser_66: yych = *++m_cursor; if (yych == 'e') { goto basic_json_parser_72; } goto basic_json_parser_32; basic_json_parser_67: ++m_cursor; { last_token_type = token_type::literal_null; break; } basic_json_parser_69: ++m_cursor; { last_token_type = token_type::literal_true; break; } basic_json_parser_71: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '@') { if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_74; } goto basic_json_parser_32; } else { if (yych <= 'F') { goto basic_json_parser_74; } if (yych <= '`') { goto basic_json_parser_32; } if (yych <= 'f') { goto basic_json_parser_74; } goto basic_json_parser_32; } basic_json_parser_72: ++m_cursor; { last_token_type = token_type::literal_false; break; } basic_json_parser_74: ++m_cursor; if (m_limit <= m_cursor) { fill_line_buffer(1); // LCOV_EXCL_LINE } yych = *m_cursor; if (yych <= '@') { if (yych <= '/') { goto basic_json_parser_32; } if (yych <= '9') { goto basic_json_parser_30; } goto basic_json_parser_32; } else { if (yych <= 'F') { goto basic_json_parser_30; } if (yych <= '`') { goto basic_json_parser_32; } if (yych <= 'f') { goto basic_json_parser_30; } goto basic_json_parser_32; } } } return last_token_type; } /*! @brief append data from the stream to the line buffer This function is called by the scan() function when the end of the buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be incremented without leaving the limits of the line buffer. Note re2c decides when to call this function. If the lexer reads from contiguous storage, there is no trailing null byte. Therefore, this function must make sure to add these padding null bytes. If the lexer reads from an input stream, this function reads the next line of the input. @pre p p p p p p u u u u u x . . . . . . ^ ^ ^ ^ m_content m_start | m_limit m_cursor @post u u u u u x x x x x x x . . . . . . ^ ^ ^ | m_cursor m_limit m_start m_content */ void fill_line_buffer(size_t n = 0) { // if line buffer is used, m_content points to its data assert(m_line_buffer.empty() or m_content == reinterpret_cast<const lexer_char_t*>(m_line_buffer.data())); // if line buffer is used, m_limit is set past the end of its data assert(m_line_buffer.empty() or m_limit == m_content + m_line_buffer.size()); // pointer relationships assert(m_content <= m_start); assert(m_start <= m_cursor); assert(m_cursor <= m_limit); assert(m_marker == nullptr or m_marker <= m_limit); // number of processed characters (p) const auto num_processed_chars = static_cast<size_t>(m_start - m_content); // offset for m_marker wrt. to m_start const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start; // number of unprocessed characters (u) const auto offset_cursor = m_cursor - m_start; // no stream is used or end of file is reached if (m_stream == nullptr or m_stream->eof()) { // m_start may or may not be pointing into m_line_buffer at // this point. We trust the standard library to do the right // thing. See http://stackoverflow.com/q/28142011/266378 m_line_buffer.assign(m_start, m_limit); // append n characters to make sure that there is sufficient // space between m_cursor and m_limit m_line_buffer.append(1, '\x00'); if (n > 0) { m_line_buffer.append(n - 1, '\x01'); } } else { // delete processed characters from line buffer m_line_buffer.erase(0, num_processed_chars); // read next line from input stream m_line_buffer_tmp.clear(); std::getline(*m_stream, m_line_buffer_tmp, '\n'); // add line with newline symbol to the line buffer m_line_buffer += m_line_buffer_tmp; m_line_buffer.push_back('\n'); } // set pointers m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()); assert(m_content != nullptr); m_start = m_content; m_marker = m_start + offset_marker; m_cursor = m_start + offset_cursor; m_limit = m_start + m_line_buffer.size(); } /// return string representation of last read token string_t get_token_string() const { assert(m_start != nullptr); return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start), static_cast<size_t>(m_cursor - m_start)); } /*! @brief return string value for string tokens The function iterates the characters between the opening and closing quotes of the string value. The complete string is the range [m_start,m_cursor). Consequently, we iterate from m_start+1 to m_cursor-1. We differentiate two cases: 1. Escaped characters. In this case, a new character is constructed according to the nature of the escape. Some escapes create new characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape `"\\uxxxx"` need special care. In this case, to_unicode takes care of the construction of the values. 2. Unescaped characters are copied as is. @pre `m_cursor - m_start >= 2`, meaning the length of the last token is at least 2 bytes which is trivially true for any string (which consists of at least two quotes). " c1 c2 c3 ... " ^ ^ m_start m_cursor @complexity Linear in the length of the string.\n Lemma: The loop body will always terminate.\n Proof (by contradiction): Assume the loop body does not terminate. As the loop body does not contain another loop, one of the called functions must never return. The called functions are `std::strtoul` and to_unicode. Neither function can loop forever, so the loop body will never loop forever which contradicts the assumption that the loop body does not terminate, q.e.d.\n Lemma: The loop condition for the for loop is eventually false.\n Proof (by contradiction): Assume the loop does not terminate. Due to the above lemma, this can only be due to a tautological loop condition; that is, the loop condition i < m_cursor - 1 must always be true. Let x be the change of i for any loop iteration. Then m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This can be rephrased to m_cursor - m_start - 2 > x. With the precondition, we x <= 0, meaning that the loop condition holds indefinitely if i is always decreased. However, observe that the value of i is strictly increasing with each iteration, as it is incremented by 1 in the iteration expression and never decremented inside the loop body. Hence, the loop condition will eventually be false which contradicts the assumption that the loop condition is a tautology, q.e.d. @return string value of current token without opening and closing quotes @throw std::out_of_range if to_unicode fails */ string_t get_string() const { assert(m_cursor - m_start >= 2); string_t result; result.reserve(static_cast<size_t>(m_cursor - m_start - 2)); // iterate the result between the quotes for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i) { // find next escape character auto e = std::find(i, m_cursor - 1, '\\'); if (e != i) { // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705 for (auto k = i; k < e; k++) { result.push_back(static_cast<typename string_t::value_type>(*k)); } i = e - 1; // -1 because of ++i } else { // processing escaped character // read next character ++i; switch (*i) { // the default escapes case 't': { result += "\t"; break; } case 'b': { result += "\b"; break; } case 'f': { result += "\f"; break; } case 'n': { result += "\n"; break; } case 'r': { result += "\r"; break; } case '\\': { result += "\\"; break; } case '/': { result += "/"; break; } case '"': { result += "\""; break; } // unicode case 'u': { // get code xxxx from uxxxx auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1), 4).c_str(), nullptr, 16); // check if codepoint is a high surrogate if (codepoint >= 0xD800 and codepoint <= 0xDBFF) { // make sure there is a subsequent unicode if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u') { JSON_THROW(std::invalid_argument("missing low surrogate")); } // get code yyyy from uxxxx\uyyyy auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer> (i + 7), 4).c_str(), nullptr, 16); result += to_unicode(codepoint, codepoint2); // skip the next 10 characters (xxxx\uyyyy) i += 10; } else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF) { // we found a lone low surrogate JSON_THROW(std::invalid_argument("missing high surrogate")); } else { // add unicode character(s) result += to_unicode(codepoint); // skip the next four characters (xxxx) i += 4; } break; } } } } return result; } /*! @brief parse string into a built-in arithmetic type as if the current locale is POSIX. @note in floating-point case strtod may parse past the token's end - this is not an error @note any leading blanks are not handled */ struct strtonum { public: strtonum(const char* start, const char* end) : m_start(start), m_end(end) {} /*! @return true iff parsed successfully as number of type T @param[in,out] val shall contain parsed value, or undefined value if could not parse */ template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> bool to(T& val) const { return parse(val, std::is_integral<T>()); } private: const char* const m_start = nullptr; const char* const m_end = nullptr; // floating-point conversion // overloaded wrappers for strtod/strtof/strtold // that will be called from parse<floating_point_t> static void strtof(float& f, const char* str, char** endptr) { f = std::strtof(str, endptr); } static void strtof(double& f, const char* str, char** endptr) { f = std::strtod(str, endptr); } static void strtof(long double& f, const char* str, char** endptr) { f = std::strtold(str, endptr); } template<typename T> bool parse(T& value, /*is_integral=*/std::false_type) const { // replace decimal separator with locale-specific version, // when necessary; data will point to either the original // string, or buf, or tempstr containing the fixed string. std::string tempstr; std::array<char, 64> buf; const size_t len = static_cast<size_t>(m_end - m_start); // lexer will reject empty numbers assert(len > 0); // since dealing with strtod family of functions, we're // getting the decimal point char from the C locale facilities // instead of C++'s numpunct facet of the current std::locale const auto loc = localeconv(); assert(loc != nullptr); const char decimal_point_char = (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; const char* data = m_start; if (decimal_point_char != '.') { const size_t ds_pos = static_cast<size_t>(std::find(m_start, m_end, '.') - m_start); if (ds_pos != len) { // copy the data into the local buffer or tempstr, if // buffer is too small; replace decimal separator, and // update data to point to the modified bytes if ((len + 1) < buf.size()) { std::copy(m_start, m_end, buf.begin()); buf[len] = 0; buf[ds_pos] = decimal_point_char; data = buf.data(); } else { tempstr.assign(m_start, m_end); tempstr[ds_pos] = decimal_point_char; data = tempstr.c_str(); } } } char* endptr = nullptr; value = 0; // this calls appropriate overload depending on T strtof(value, data, &endptr); // parsing was successful iff strtof parsed exactly the number // of characters determined by the lexer (len) const bool ok = (endptr == (data + len)); if (ok and (value == static_cast<T>(0.0)) and (*data == '-')) { // some implementations forget to negate the zero value = -0.0; } return ok; } // integral conversion signed long long parse_integral(char** endptr, /*is_signed*/std::true_type) const { return std::strtoll(m_start, endptr, 10); } unsigned long long parse_integral(char** endptr, /*is_signed*/std::false_type) const { return std::strtoull(m_start, endptr, 10); } template<typename T> bool parse(T& value, /*is_integral=*/std::true_type) const { char* endptr = nullptr; errno = 0; // these are thread-local const auto x = parse_integral(&endptr, std::is_signed<T>()); // called right overload? static_assert(std::is_signed<T>() == std::is_signed<decltype(x)>(), ""); value = static_cast<T>(x); return (x == static_cast<decltype(x)>(value)) // x fits into destination T and (x < 0) == (value < 0) // preserved sign //and ((x != 0) or is_integral()) // strto[u]ll did nto fail and (errno == 0) // strto[u]ll did not overflow and (m_start < m_end) // token was not empty and (endptr == m_end); // parsed entire token exactly } }; /*! @brief return number value for number tokens This function translates the last token into the most appropriate number type (either integer, unsigned integer or floating point), which is passed back to the caller via the result parameter. integral numbers that don't fit into the the range of the respective type are parsed as number_float_t floating-point values do not satisfy std::isfinite predicate are converted to value_t::null throws if the entire string [m_start .. m_cursor) cannot be interpreted as a number @param[out] result @ref basic_json object to receive the number. @param[in] token the type of the number token */ bool get_number(basic_json& result, const token_type token) const { assert(m_start != nullptr); assert(m_start < m_cursor); assert((token == token_type::value_unsigned) or (token == token_type::value_integer) or (token == token_type::value_float)); strtonum num_converter(reinterpret_cast<const char*>(m_start), reinterpret_cast<const char*>(m_cursor)); switch (token) { case lexer::token_type::value_unsigned: { number_unsigned_t val; if (num_converter.to(val)) { // parsing successful result.m_type = value_t::number_unsigned; result.m_value = val; return true; } break; } case lexer::token_type::value_integer: { number_integer_t val; if (num_converter.to(val)) { // parsing successful result.m_type = value_t::number_integer; result.m_value = val; return true; } break; } default: { break; } } // parse float (either explicitly or because a previous conversion // failed) number_float_t val; if (num_converter.to(val)) { // parsing successful result.m_type = value_t::number_float; result.m_value = val; // replace infinity and NAN by null if (not std::isfinite(result.m_value.number_float)) { result.m_type = value_t::null; result.m_value = basic_json::json_value(); } return true; } // couldn't parse number in any format return false; } private: /// optional input stream std::istream* m_stream = nullptr; /// line buffer buffer for m_stream string_t m_line_buffer {}; /// used for filling m_line_buffer string_t m_line_buffer_tmp {}; /// the buffer pointer const lexer_char_t* m_content = nullptr; /// pointer to the beginning of the current symbol const lexer_char_t* m_start = nullptr; /// pointer for backtracking information const lexer_char_t* m_marker = nullptr; /// pointer to the current symbol const lexer_char_t* m_cursor = nullptr; /// pointer to the end of the buffer const lexer_char_t* m_limit = nullptr; /// the last token type token_type last_token_type = token_type::end_of_input; }; /*! @brief syntax analysis This class implements a recursive decent parser. */ class parser { public: /// a parser reading from a string literal parser(const char* buff, const parser_callback_t cb = nullptr) : callback(cb), m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff)) {} /// a parser reading from an input stream parser(std::istream& is, const parser_callback_t cb = nullptr) : callback(cb), m_lexer(is) {} /// a parser reading from an iterator range with contiguous storage template<class IteratorType, typename std::enable_if< std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value , int>::type = 0> parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr) : callback(cb), m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)), static_cast<size_t>(std::distance(first, last))) {} /// public parser interface basic_json parse() { // read first token get_token(); basic_json result = parse_internal(true); result.assert_invariant(); expect(lexer::token_type::end_of_input); // return parser result and replace it with null in case the // top-level value was discarded by the callback function return result.is_discarded() ? basic_json() : std::move(result); } private: /// the actual parser basic_json parse_internal(bool keep) { auto result = basic_json(value_t::discarded); switch (last_token) { case lexer::token_type::begin_object: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0))) { // explicitly set result to object to cope with {} result.m_type = value_t::object; result.m_value = value_t::object; } // read next token get_token(); // closing } -> we are done if (last_token == lexer::token_type::end_object) { get_token(); if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result = basic_json(value_t::discarded); } return result; } // no comma is expected here unexpect(lexer::token_type::value_separator); // otherwise: parse key-value pairs do { // ugly, but could be fixed with loop reorganization if (last_token == lexer::token_type::value_separator) { get_token(); } // store key expect(lexer::token_type::value_string); const auto key = m_lexer.get_string(); bool keep_tag = false; if (keep) { if (callback) { basic_json k(key); keep_tag = callback(depth, parse_event_t::key, k); } else { keep_tag = true; } } // parse separator (:) get_token(); expect(lexer::token_type::name_separator); // parse and add value get_token(); auto value = parse_internal(keep); if (keep and keep_tag and not value.is_discarded()) { result[key] = std::move(value); } } while (last_token == lexer::token_type::value_separator); // closing } expect(lexer::token_type::end_object); get_token(); if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result = basic_json(value_t::discarded); } return result; } case lexer::token_type::begin_array: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0))) { // explicitly set result to object to cope with [] result.m_type = value_t::array; result.m_value = value_t::array; } // read next token get_token(); // closing ] -> we are done if (last_token == lexer::token_type::end_array) { get_token(); if (callback and not callback(--depth, parse_event_t::array_end, result)) { result = basic_json(value_t::discarded); } return result; } // no comma is expected here unexpect(lexer::token_type::value_separator); // otherwise: parse values do { // ugly, but could be fixed with loop reorganization if (last_token == lexer::token_type::value_separator) { get_token(); } // parse value auto value = parse_internal(keep); if (keep and not value.is_discarded()) { result.push_back(std::move(value)); } } while (last_token == lexer::token_type::value_separator); // closing ] expect(lexer::token_type::end_array); get_token(); if (keep and callback and not callback(--depth, parse_event_t::array_end, result)) { result = basic_json(value_t::discarded); } return result; } case lexer::token_type::literal_null: { get_token(); result.m_type = value_t::null; break; } case lexer::token_type::value_string: { const auto s = m_lexer.get_string(); get_token(); result = basic_json(s); break; } case lexer::token_type::literal_true: { get_token(); result.m_type = value_t::boolean; result.m_value = true; break; } case lexer::token_type::literal_false: { get_token(); result.m_type = value_t::boolean; result.m_value = false; break; } case lexer::token_type::value_unsigned: case lexer::token_type::value_integer: case lexer::token_type::value_float: { m_lexer.get_number(result, last_token); get_token(); break; } default: { // the last token was unexpected unexpect(last_token); } } if (keep and callback and not callback(depth, parse_event_t::value, result)) { result = basic_json(value_t::discarded); } return result; } /// get next token from lexer typename lexer::token_type get_token() { last_token = m_lexer.scan(); return last_token; } void expect(typename lexer::token_type t) const { if (t != last_token) { std::string error_msg = "parse error - unexpected "; error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + "'") : lexer::token_type_name(last_token)); error_msg += "; expected " + lexer::token_type_name(t); JSON_THROW(std::invalid_argument(error_msg)); } } void unexpect(typename lexer::token_type t) const { if (t == last_token) { std::string error_msg = "parse error - unexpected "; error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + "'") : lexer::token_type_name(last_token)); JSON_THROW(std::invalid_argument(error_msg)); } } private: /// current level of recursion int depth = 0; /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token typename lexer::token_type last_token = lexer::token_type::uninitialized; /// the lexer lexer m_lexer; }; public: /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ class json_pointer { /// allow basic_json to access private members friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw std::domain_error if reference token is nonempty and does not begin with a slash (`/`); example: `"JSON pointer must be empty or begin with /"` @throw std::domain_error if a tilde (`~`) is not followed by `0` (representing `~`) or `1` (representing `/`); example: `"escape error: ~ must be followed with 0 or 1"` @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`., json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const noexcept { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } private: /// remove and return last reference pointer std::string pop_back() { if (is_root()) { JSON_THROW(std::domain_error("JSON pointer has no parent")); } auto last = reference_tokens.back(); reference_tokens.pop_back(); return last; } /// return whether pointer points to the root document bool is_root() const { return reference_tokens.empty(); } json_pointer top() const { if (is_root()) { JSON_THROW(std::domain_error("JSON pointer has no parent")); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. */ reference get_and_create(reference j) const { pointer result = &j; // in case no reference tokens exist, return a reference to the // JSON value j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->m_type) { case value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case value_t::array: { // create an entry in the array result = &result->operator[](static_cast<size_type>(std::stoi(reference_token))); break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: { JSON_THROW(std::domain_error("invalid value to unflatten")); } } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw std::out_of_range if the JSON pointer can not be resolved @throw std::domain_error if an array index begins with '0' @throw std::invalid_argument if an array index was not a number */ reference get_unchecked(pointer ptr) const { for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->m_type == value_t::null) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const char x) { return std::isdigit(x); }); // change value to array for numbers or "-" or to object // otherwise if (nums or reference_token == "-") { *ptr = value_t::array; } else { *ptr = value_t::object; } } switch (ptr->m_type) { case value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case value_t::array: { // error condition (cf. RFC 6901, Sect. 4) if (reference_token.size() > 1 and reference_token[0] == '0') { JSON_THROW(std::domain_error("array index must not begin with '0'")); } if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token))); } break; } default: { JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); } } } return *ptr; } reference get_checked(pointer ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case value_t::array: { if (reference_token == "-") { // "-" always fails the range check JSON_THROW(std::out_of_range("array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (reference_token.size() > 1 and reference_token[0] == '0') { JSON_THROW(std::domain_error("array index must not begin with '0'")); } // note: at performs range check ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); break; } default: { JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); } } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer */ const_reference get_unchecked(const_pointer ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case value_t::array: { if (reference_token == "-") { // "-" cannot be used for const access JSON_THROW(std::out_of_range("array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (reference_token.size() > 1 and reference_token[0] == '0') { JSON_THROW(std::domain_error("array index must not begin with '0'")); } // use unchecked array access ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token))); break; } default: { JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); } } } return *ptr; } const_reference get_checked(const_pointer ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case value_t::array: { if (reference_token == "-") { // "-" always fails the range check JSON_THROW(std::out_of_range("array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (reference_token.size() > 1 and reference_token[0] == '0') { JSON_THROW(std::domain_error("array index must not begin with '0'")); } // note: at performs range check ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); break; } default: { JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); } } } return *ptr; } /// split the string input to reference tokens static std::vector<std::string> split(const std::string& reference_string) { std::vector<std::string> result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (reference_string[0] != '/') { JSON_THROW(std::domain_error("JSON pointer must be empty or begin with '/'")); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == string::npos+1 = 0 start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { assert(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (pos == reference_token.size() - 1 or (reference_token[pos + 1] != '0' and reference_token[pos + 1] != '1')) { JSON_THROW(std::domain_error("escape error: '~' must be followed with '0' or '1'")); } } // finally, store the reference token unescape(reference_token); result.push_back(reference_token); } return result; } private: /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. @since version 2.0.0 */ static void replace_substring(std::string& s, const std::string& f, const std::string& t) { assert(not f.empty()); for ( size_t pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t pos = s.find(f, pos + t.size()) // find next occurrence of f ); } /// escape tilde and slash static std::string escape(std::string s) { // escape "~"" to "~0" and "/" to "~1" replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /// unescape tilde and slash static void unescape(std::string& s) { // first transform any occurrence of the sequence '~1' to '/' replace_substring(s, "~1", "/"); // then transform any occurrence of the sequence '~0' to '~' replace_substring(s, "~0", "~"); } /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ static void flatten(const std::string& reference_string, const basic_json& value, basic_json& result) { switch (value.m_type) { case value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON */ static basic_json unflatten(const basic_json& value) { if (not value.is_object()) { JSON_THROW(std::domain_error("only objects can be unflattened")); } basic_json result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (not element.second.is_primitive()) { JSON_THROW(std::domain_error("values in object must be primitive")); } // assign value to reference pointed to by JSON pointer; Note // that if the JSON pointer is "" (i.e., points to the whole // value), function get_and_create returns a reference to // result itself. An assignment will then create a primitive // value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } private: friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return lhs.reference_tokens == rhs.reference_tokens; } friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return !(lhs == rhs); } /// the reference tokens std::vector<std::string> reference_tokens {}; }; ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw std::out_of_range if the JSON pointer can not be resolved @throw std::domain_error if an array index begins with '0' @throw std::invalid_argument if an array index was not a number @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw std::out_of_range if the JSON pointer can not be resolved @throw std::domain_error if an array index begins with '0' @throw std::invalid_argument if an array index was not a number @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @complexity Constant. @throw std::out_of_range if the JSON pointer can not be resolved @throw std::domain_error if an array index begins with '0' @throw std::invalid_argument if an array index was not a number @liveexample{The behavior is shown in the example.,at_json_pointer} @since version 2.0.0 */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @complexity Constant. @throw std::out_of_range if the JSON pointer can not be resolved @throw std::domain_error if an array index begins with '0' @throw std::invalid_argument if an array index was not a number @liveexample{The behavior is shown in the example.,at_json_pointer_const} @since version 2.0.0 */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw std::out_of_range if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw invalid_argument if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.is_root()) { result = val; } else { // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = std::stoi(last_path); if (static_cast<size_type>(idx) > parent.size()) { // avoid undefined behavior JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); } else { // default case: insert add offset parent.insert(parent.begin() + static_cast<difference_type>(idx), val); } } break; } default: { // if there exists a parent it cannot be primitive assert(false); // LCOV_EXCL_LINE } } } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [&result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (it != parent.end()) { parent.erase(it); } else { JSON_THROW(std::out_of_range("key '" + last_path + "' not found")); } } else if (parent.is_array()) { // note erase performs range check parent.erase(static_cast<size_type>(std::stoi(last_path))); } }; // type check if (not json_patch.is_array()) { // a JSON patch must be an array of objects JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json& { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (it == val.m_value.object->end()) { JSON_THROW(std::invalid_argument(error_msg + " must have member '" + member + "'")); } // check if result is of type string if (string_type and not it->second.is_string()) { JSON_THROW(std::invalid_argument(error_msg + " must have string member '" + member + "'")); } // no error: return value return it->second; }; // type check if (not val.is_object()) { JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); } // collect mandatory members const std::string op = get_value("op", "op", true); const std::string path = get_value(op, "path", true); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const std::string from_path = get_value("move", "from", true); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const std::string from_path = get_value("copy", "from", true);; const json_pointer from_ptr(from_path); // the "from" location must exist - use at() result[ptr] = result.at(from_ptr); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_CATCH (std::out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (not success) { JSON_THROW(std::domain_error("unsuccessful: " + val.dump())); } break; } case patch_operations::invalid: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(std::invalid_argument("operation value '" + op + "' is invalid")); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa @ref patch -- apply a JSON patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); } else { switch (source.type()) { case value_t::array: { // first pass: traverse common elements size_t i = 0; while (i < source.size() and i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast<difference_type>(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/" + std::to_string(i)}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.begin(); it != source.end(); ++it) { // escape the key name to be used in a JSON patch const auto key = json_pointer::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path + "/" + key} })); } } // second pass: traverse other object's elements for (auto it = target.begin(); it != target.end(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto key = json_pointer::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } } return result; } /// @} }; ///////////// // presets // ///////////// /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( is_nothrow_move_constructible<nlohmann::json>::value and is_nothrow_move_assignable<nlohmann::json>::value ) { j1.swap(j2); } /// hash value for JSON objects template<> struct hash<nlohmann::json> { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { // a naive hashing via the string representation const auto& h = hash<nlohmann::json::string_t>(); return h(j.dump()); } }; } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_CATCH #undef JSON_DEPRECATED #undef JSON_THROW #undef JSON_TRY #endif
mwthinker/Tetris
nlohmann-json/src/json.hpp
C++
mit
448,254
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// DispatchInterface IHTMLDOMNode2 /// SupportByVersion MSHTML, 4 /// </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface)] public class IHTMLDOMNode2 : IHTMLDOMNode { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IHTMLDOMNode2); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public IHTMLDOMNode2(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IHTMLDOMNode2(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLDOMNode2(string progId) : base(progId) { } #endregion #region Properties #endregion #region Methods #endregion #pragma warning restore } }
NetOfficeFw/NetOffice
Source/MSHTML/DispatchInterfaces/IHTMLDOMNode2.cs
C#
mit
3,725
from . uuid64 import *
jdowner/uuid64
uuid64/__init__.py
Python
mit
23
class Product include Mongoid::Document field :_id, type: String, default: -> { name.to_s.parameterize } field :name, type: String field :price, type: BigDecimal field :released_on, type: Date validates_presence_of :name embeds_many :reviews end
xeraseth/Rails-Mongo
app/models/product.rb
Ruby
mit
262
require 'spec_helper' require 'penn_extranet_adapter.rb' describe PennExtranetAdapter do let(:valid_attributes) { { "username" => "XXXXXXX", "password" => "XXXXXXX" } } describe "valid_agent?" do it "should detect a valid" do x = PennExtranetAdapter.new valid_attributes["username"], "x" authenticated_agent = x.authenticated_agent x.valid_agent?.should == false end it "should detect an invalid agent" do x = PennExtranetAdapter.new valid_attributes["username"], valid_attributes["password"] authenticated_agent = x.authenticated_agent x.valid_agent?.should == true end end it "should save and relaod successfully" do x = PennExtranetAdapter.new valid_attributes["username"], valid_attributes["password"] authenticated_agent = x.authenticated_agent x.save_agent y = PennExtranetAdapter.new "x", "y" y.load_agent y.valid_agent?.should == true end end
eugyev/extranet-adapter-2
spec/lib/penn_extranet_adapter_spec.rb
Ruby
mit
965
class CreateNodes < ActiveRecord::Migration def change create_table :nodes do |t| t.string :name t.integer :map_id t.timestamps end add_index :nodes, :map_id add_index :nodes, [:map_id, :name], :unique => true end end
guivinicius/logistique
db/migrate/20140503135157_create_nodes.rb
Ruby
mit
258
angular.module('schemaForm').config( ['schemaFormProvider', 'schemaFormDecoratorsProvider', 'sfPathProvider', function(schemaFormProvider, schemaFormDecoratorsProvider, sfPathProvider) { var download = function(name, schema, options) { if (schema.type === 'string' && schema.format === 'download') { var f = schemaFormProvider.stdFormObj(name, schema, options); f.key = options.path; f.type = 'download'; options.lookup[sfPathProvider.stringify(options.path)] = f; return f; } }; schemaFormProvider.defaults.string.unshift(download); //Add to the bootstrap directive schemaFormDecoratorsProvider.addMapping( 'bootstrapDecorator', 'download', 'directives/decorators/bootstrap/download/angular-schema-form-download.html' ); schemaFormDecoratorsProvider.createDirective( 'download', 'directives/decorators/bootstrap/download/angular-schema-form-download.html' ); } ]); angular.module('schemaForm').directive('downloadOptions', function() { return { restrict : 'A', controller : function($scope, $rootScope) { $scope.notifyClick = function(ele) { $rootScope.$emit('DownloadTriggered', { element : ele }) }; }, link : function(scope, ele, attr) { angular.element(ele).click(function() { scope.notifyClick(ele); }); } }; });
rafialikhan/angular-schema-form-download
src/angular-schema-form-download.js
JavaScript
mit
1,602
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // 'use strict'; // global var data = { "taskCount": 0, "tasks": [] } var count = 0; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) function saveText(text, filename){ var a = document.createElement('a'); a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text)); a.setAttribute('download', filename); a.click() } function writeToFile(d1, d2){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.OpenTextFile("data2.json", 8, false, 0); fh.WriteLine(d1 + ',' + d2); fh.Close(); } /* * Function that is called when the document is ready. */ function initializePage() { // add any functionality and listeners you want here // Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); var saveTask = document.getElementById("saveTask"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("blarg")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } saveTask.onclick = function createDiv() { var newDiv = document.createElement("div"); //newDiv.id = "displayName"+count; newDiv.innerHTML = '<div class="panel panel-default">' + '<div class="panel-heading clearfix">' + '<h3 class="panel-title pull-left"><span id="displayName'+count+'"></span></h3>'+ '<a class="btn btn-primary pull-right" href="#">'+ '<i class="fa fa-pencil"></i>'+ 'Edit'+ '</a>'+ '</div>'+ '<div class="list-group">'+ '<div class="list-group-item">'+ '<p class="list-group-item-text">Reward</p>'+ '<h4 class="list-group-item-heading"><span id="displayReward'+count+'"></span></h4>'+ '</div>'+ '<div class="list-group-item">'+ '<p class="list-group-item-text"><span id="displayDescription'+count+'"></p>'+ '</div>'+ '</div>'+ '<div class="panel-footer">'+ '<small></small>'+ '</div>'+ '</div>'; var currentDiv = document.getElementById("tasks"); currentDiv.appendChild(newDiv); var a = document.getElementById('displayName'+count).innerHTML = document.getElementById("taskName").value; var b =document.getElementById('displayReward'+count).innerHTML = document.getElementById("taskReward").value; var c = document.getElementById('displayDescription'+count).innerHTML = document.getElementById("taskDescription").value; // I've tried a lot of json writing under here but it did not work , even simple ones data.tasks.push({ "taskName":a, "taskReward":b, "taskDescription":c }); data.taskCount++; count++; // writeData(); // USE THIS TO CLEAR LOCAL STORAGE // window.localStorage.clear(); //THIS SAVES CRAP TO LOCAL STORAGE. var json = JSON.stringify(data); localStorage.setItem('task'+count, json); var fs = require('fs'); fs.writeFile('data2.json', json, 'utf8', callback); // looping just to see whats in storage // for(var i = 0; i < 5; i++) // console.log(JSON.parse(localStorage.getItem('task'+i))) modal.style.display = "none"; return data; }; } },{"fs":2}],2:[function(require,module,exports){ },{}]},{},[1]);
odangitsdjang/CleaningApp
bundle.js
JavaScript
mit
4,338
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: "// CMT07 // Heath Tundra - (ma....."" pass elif i == 1: # PFT name line, e,g.: "//Decid. E.green ...." # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and "CMT" in line: #print "end of datablock, i=", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip("//").split() if len(secondline) >= 9: #print "Looks like a PFT header line!" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must provide only one of pftkey or pftnumber") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a "CMT datablock" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: "//Decid. E.green ...." pftlist = cmtdatablock[1].strip("//").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == "//": #print "passing line", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print "NOT IMPLEMENTED YET!" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append("// First line comment...") ll.append("// Second line comment (?? PFT string?)") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += "{:>12.6f} ".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the "reference order" list tokens = t[1].strip().lstrip("//").strip().split(":") tag = tokens[0] desc = "".join(tokens[1:]) print "Found tag:", tag, " Desc: ", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the "before comment" string, and the "after comment" string. The "after commnet" string will include the comment charachter. ''' cmtidx = line.find("//") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError("This function only makes sense on cmt_bgcvegetation.txt files.") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print "NOTE! Does not work correctly on non-PFT files yet!!" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print "{:>45s}: {}".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print "{:>45s}".format(i) # print "".join(get_CMT_datablock(i, 2)) # print "{:45s}".format("DONE") d = get_CMT_datablock(testFiles[4], 2) print "".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print "NOTE! Does not work correctly on non-PFT files yet!!"
tobeycarman/dvm-dos-tem
scripts/param_util.py
Python
mit
11,387
//This file is generated by btsgen. DO NOT EDIT. //operation sample data for OperationTypeCustom package samples func init() { sampleDataCustomOperation[2] = `{ "data": "466f6f626172", "fee": { "amount": 164678, "asset_id": "1.3.0" }, "id": 16, "payer": "1.2.30127", "required_auths": [ "1.2.30127" ] }` } //end of file
denkhaus/bitshares
gen/samples/customoperation_2.go
GO
mit
352
'use strict'; describe('service', function() { var countKeys = function(data) { var count = 0 for(var k in data) { count++; } return count; } // load modules beforeEach(module('mavrixAgenda')); // Test service availability it('check the existence of Storage factory', inject(function(usersSrv) { expect(usersSrv).toBeDefined(); })); // Test users it('testing set/get users', inject(function(usersSrv){ usersSrv.setCurrentUser("test-user"); var user = usersSrv.getCurrentUser(); expect(user).toBe("test-user"); })); });
jomarmar/mavrix-test
app/components/users/users.test.js
JavaScript
mit
606
<?php namespace User\UserBundle\Controller; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Reservable\ActivityBundle\Entity\Activity; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use User\UserBundle\Entity\Users; class ConsultController extends Controller { public function viewUsersAction() { if(!$this->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException(); } $allUsers = array(); $users = $this->getDoctrine() ->getRepository('UserUserBundle:Users') ->findAllUsers(); foreach($users as $oneUser){ //ldd($oneUser); $aux['userID'] = ucwords($oneUser->getID()); $aux['email'] = $oneUser->getEmail(); $aux['name'] = ucwords($oneUser->getName()); $aux['surname'] = ucwords($oneUser->getSurname()); $aux['phone'] = $oneUser->getPhoneNumber(); $aux['mobile'] = $oneUser->getMobileNumber(); $aux['lastLogin'] = $oneUser->getLastLogin(); $aux['active'] = $oneUser->isEnabled(); $role = $oneUser->getRole(); $aux['role'] = $role[0]; $aux['properties'] = array(); switch($role[0]){ case 'ROLE_USER': break; case 'ROLE_ADMIN': $aux['properties'] = $this->getUserProperties($oneUser->getID()); break; case 'ROLE_SUPER_ADMIN': break; } $allUsers[] = $aux; $auxEmail['ownerID'] = $oneUser->getID(); $auxEmail['email'] = $oneUser->getEmail(); $allEmails[] = $auxEmail; } return $this->render('UserUserBundle:Consult:viewUsers.html.twig', array('allUsers' => $allUsers, 'allEmails' => $allEmails)); } public function viewUsersModifAction($userId){ if(!$this->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException(); } $thisUser = $this->getDoctrine() ->getRepository('UserUserBundle:Users') ->getUserByUserID($userId); $thisUserData = array(); $thisUserData['name'] = $thisUser->getName(); $thisUserData['email'] = $thisUser->getEmail(); $thisUserData['id'] = $thisUser->getId(); $thisUserData['role'] = $thisUser->getRole(); $thisUserData['surname'] = $thisUser->getSurname(); $thisUserData['activeUser'] = ( $thisUser->isEnabled() ) ? 1 : 0 ; switch($thisUserData['role'][0]){ case 'ROLE_USER': break; case 'ROLE_ADMIN': $thisUserData['properties'] = $this->getUserProperties($thisUserData['id']); break; case 'ROLE_SUPER_ADMIN': break; } //ldd($thisUserData); return $this->render('UserUserBundle:Consult:viewUsersModif.html.twig', array('oneUser' => $thisUserData)); } public function deleteUserAction($userId){ if(!$this->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException(); } // Eliminar usuario $adminId = $this->get('security.context')->getToken()->getUser()->getId(); $changeOwner = $this->getDoctrine() ->getManager() ->createQuery("UPDATE ReservableActivityBundle:Activity a SET a.ownerID = " . $adminId . ", a.active = 0 WHERE a.ownerID = " . $userId) ->getResult(); $deleteOwner = $this->getDoctrine()->getManager() ->createQuery("DELETE FROM UserUserBundle:Users u WHERE u.id = " . $userId) ->getResult(); return $this->redirect($this->generateUrl('view_users', array(), 'prod')); } public function activeUserAction($userId){ if(!$this->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException(); } // Activar usuario $activeOwner = $this->getDoctrine()->getManager() ->createQuery("UPDATE UserUserBundle:Users u SET u.enabled = 1 WHERE u.id = " . $userId) ->getResult(); $request = $this->getRequest(); $env = ($this->get('kernel')->getEnvironment() == 'dev')? 'app_dev.php' : 'app.php' ; $url = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . '/' . $env . '/' . $request->getLocale() . '/view-users'; return $this->redirect($url); } public function deactiveUserAction($userId){ if(!$this->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException(); } // Activar usuario $deactiveOwner = $this->getDoctrine()->getManager() ->createQuery("UPDATE UserUserBundle:Users u SET u.enabled = 0 WHERE u.id = " . $userId) ->getResult(); $request = $this->getRequest(); $env = ($this->get('kernel')->getEnvironment() == 'dev')? 'app_dev.php' : 'app.php' ; $url = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . '/' . $env . '/' . $request->getLocale() . '/view-users'; return $this->redirect($url); } public function checkUserAction(){ $request = $this->getRequest(); $email = $request->request->get('email'); $google_id = $request->request->get('id'); $result = false; $user = $this->getDoctrine() ->getRepository('UserUserBundle:Users') ->findByEmail($email); if(!empty($user)){ $encoder_service = $this->get('security.encoder_factory'); $encoder = $encoder_service->getEncoder($user); $encoded_pass = $encoder->encodePassword($google_id, $user->getSalt()); if($encoded_pass == $user->getPassword()){ $result = true; } else{ $resultUpdatePassword = $this->getDoctrine() ->getManager() ->createQuery('UPDATE UserUserBundle:Users u SET u.password = \'' . $encoded_pass . '\' WHERE u.email = \'' . $email . '\'') ->getResult(); $result = $resultUpdatePassword; } } else{ // Guardamos el usuario y logueamos $user = new Users(); $salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36); $encoder_service = $this->get('security.encoder_factory'); $encoder = $encoder_service->getEncoder($user); $username = substr($email, 0, strpos($email, '@')); $user->setName($request->request->get('given_name')); $user->setSurname($request->request->get('family_name')); $user->setUsername($username); $user->setUsernameCanonical($username); $user->setEmail($email); $user->setEmailCanonical($email); $user->setSalt($salt); $user->setPassword($encoder->encodePassword($google_id, $salt)); $user->setRole('a:1:{i:0;s:9:"ROLE_USER";}'); $user->setEnabled(1); // extra $gplink = $request->request->get('link'); $picture = $request->request->get('picture'); $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); $result = true; } return new JsonResponse(array('response'=>$result)); } public function getUserProperties($userID){ $properties = $this->getDoctrine() ->getManager() ->createQuery('SELECT a FROM ReservableActivityBundle:Activity a WHERE a.ownerID = ' . $userID) ->getResult(); $result = array(); if(!empty($properties)){ foreach($properties as $oneProperty){ $aux['id'] = $oneProperty->getId(); $aux['name'] = $oneProperty->getName(); $aux['numBookings'] = $this->getNumBookings($oneProperty->getId()); $result[] = $aux; } } return $result; } public function getNumBookings($activityID){ $bookings = $this->getDoctrine() ->getManager() ->createQuery('SELECT count(b) FROM BookingsBookingBundle:Booking b WHERE b.activityID = ' . $activityID) ->getResult(); $num = 0; if(!empty($bookings)){ $num = $bookings[0][1]; } return $num; } }
silver819/alm-cristina
src/User/UserBundle/Controller/ConsultController.php
PHP
mit
8,653
var crossBrowser = function (browser, x, y) { if (browser === 'Firefox 39') { x = x - 490; y = y + 10; } else if (browser === 'MSIE 10') { x = x - 588.7037353; y = y + 3 - 0.32638931; } else if (browser === 'IE 11') { x = x - 641; y = y + 2.5; } else if (browser === 'Opera 12') { x = x - 500; } return { x: x, y: y } };
g-yonchev/DarkNStormy-JS-UI-and-DOM-TeamProject
ConnectTheDots/public/scripts/crossBrowsers.js
JavaScript
mit
421
<?php namespace App\Repositories; interface BaseRepository { public function paginateAll($perPage = 15, $pageName = 'page'); }
greatwitenorth/lumen-doctrine-hateoas
app/Repositories/BaseRepository.php
PHP
mit
128
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.impl; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier; import io.github.nucleuspowered.nucleus.core.scaffold.command.control.CommandControl; import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.ICommandModifier; import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection; import net.kyori.adventure.text.Component; import java.util.Optional; public class RequiresEconomyModifier implements ICommandModifier { @Override public Optional<Component> testRequirement(final ICommandContext source, final CommandControl control, final INucleusServiceCollection serviceCollection, final CommandModifier modifier) { if (!serviceCollection.economyServiceProvider().serviceExists()) { return Optional.of(serviceCollection.messageProvider().getMessageFor(source.cause().audience(), "command.economyrequired")); } return Optional.empty(); } }
NucleusPowered/Nucleus
nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/scaffold/command/modifier/impl/RequiresEconomyModifier.java
Java
mit
1,279
namespace Pote.CommandLine.Mocks { /// <summary> /// A verb with an optional option. /// </summary> public class VerbWithOptionalOption : Verb { /// <summary> /// Some helpful hint on how to use this verb. /// </summary> public override string Help { get { return "Some helpful hint"; } } /// <summary> /// The name of the verb. /// </summary> public override string Name { get { return "VerbWithOptionalOption"; } } /// <summary> /// Some option. /// </summary> [Option('i', "int", Help = "This is a helpful hint")] protected int MyOption { get; set; } /// <summary> /// Returns the value of <see cref="MyOption"/>. /// </summary> /// <returns>The value of <see cref="MyOption"/>.</returns> public override int Execute() { return MyOption; } } }
pawwkm/Pote.CommandLine
Pote.CommandLine.Tests/Mocks/VerbWithOptionalOption.cs
C#
mit
1,172
# -*- test-case-name: twisted.test.test_task,twisted.test.test_cooperator -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Scheduling utility methods and classes. @author: Jp Calderone """ __metaclass__ = type import time from zope.interface import implements from twisted.python import reflect from twisted.python.failure import Failure from twisted.internet import base, defer from twisted.internet.interfaces import IReactorTime class LoopingCall: """Call a function repeatedly. If C{f} returns a deferred, rescheduling will not take place until the deferred has fired. The result value is ignored. @ivar f: The function to call. @ivar a: A tuple of arguments to pass the function. @ivar kw: A dictionary of keyword arguments to pass to the function. @ivar clock: A provider of L{twisted.internet.interfaces.IReactorTime}. The default is L{twisted.internet.reactor}. Feel free to set this to something else, but it probably ought to be set *before* calling L{start}. @type running: C{bool} @ivar running: A flag which is C{True} while C{f} is scheduled to be called (or is currently being called). It is set to C{True} when L{start} is called and set to C{False} when L{stop} is called or if C{f} raises an exception. In either case, it will be C{False} by the time the C{Deferred} returned by L{start} fires its callback or errback. @type _expectNextCallAt: C{float} @ivar _expectNextCallAt: The time at which this instance most recently scheduled itself to run. @type _realLastTime: C{float} @ivar _realLastTime: When counting skips, the time at which the skip counter was last invoked. @type _runAtStart: C{bool} @ivar _runAtStart: A flag indicating whether the 'now' argument was passed to L{LoopingCall.start}. """ call = None running = False deferred = None interval = None _expectNextCallAt = 0.0 _runAtStart = False starttime = None def __init__(self, f, *a, **kw): self.f = f self.a = a self.kw = kw from twisted.internet import reactor self.clock = reactor def withCount(cls, countCallable): """ An alternate constructor for L{LoopingCall} that makes available the number of calls which should have occurred since it was last invoked. Note that this number is an C{int} value; It represents the discrete number of calls that should have been made. For example, if you are using a looping call to display an animation with discrete frames, this number would be the number of frames to advance. The count is normally 1, but can be higher. For example, if the reactor is blocked and takes too long to invoke the L{LoopingCall}, a Deferred returned from a previous call is not fired before an interval has elapsed, or if the callable itself blocks for longer than an interval, preventing I{itself} from being called. @param countCallable: A callable that will be invoked each time the resulting LoopingCall is run, with an integer specifying the number of calls that should have been invoked. @type countCallable: 1-argument callable which takes an C{int} @return: An instance of L{LoopingCall} with call counting enabled, which provides the count as the first positional argument. @rtype: L{LoopingCall} @since: 9.0 """ def counter(): now = self.clock.seconds() lastTime = self._realLastTime if lastTime is None: lastTime = self.starttime if self._runAtStart: lastTime -= self.interval self._realLastTime = now lastInterval = self._intervalOf(lastTime) thisInterval = self._intervalOf(now) count = thisInterval - lastInterval return countCallable(count) self = cls(counter) self._realLastTime = None return self withCount = classmethod(withCount) def _intervalOf(self, t): """ Determine the number of intervals passed as of the given point in time. @param t: The specified time (from the start of the L{LoopingCall}) to be measured in intervals @return: The C{int} number of intervals which have passed as of the given point in time. """ elapsedTime = t - self.starttime intervalNum = int(elapsedTime / self.interval) return intervalNum def start(self, interval, now=True): """ Start running function every interval seconds. @param interval: The number of seconds between calls. May be less than one. Precision will depend on the underlying platform, the available hardware, and the load on the system. @param now: If True, run this call right now. Otherwise, wait until the interval has elapsed before beginning. @return: A Deferred whose callback will be invoked with C{self} when C{self.stop} is called, or whose errback will be invoked when the function raises an exception or returned a deferred that has its errback invoked. """ assert not self.running, ("Tried to start an already running " "LoopingCall.") if interval < 0: raise ValueError, "interval must be >= 0" self.running = True d = self.deferred = defer.Deferred() self.starttime = self.clock.seconds() self._expectNextCallAt = self.starttime self.interval = interval self._runAtStart = now if now: self() else: self._reschedule() return d def stop(self): """Stop running function. """ assert self.running, ("Tried to stop a LoopingCall that was " "not running.") self.running = False if self.call is not None: self.call.cancel() self.call = None d, self.deferred = self.deferred, None d.callback(self) def reset(self): """ Skip the next iteration and reset the timer. @since: 11.1 """ assert self.running, ("Tried to reset a LoopingCall that was " "not running.") if self.call is not None: self.call.cancel() self.call = None self._expectNextCallAt = self.clock.seconds() self._reschedule() def __call__(self): def cb(result): if self.running: self._reschedule() else: d, self.deferred = self.deferred, None d.callback(self) def eb(failure): self.running = False d, self.deferred = self.deferred, None d.errback(failure) self.call = None d = defer.maybeDeferred(self.f, *self.a, **self.kw) d.addCallback(cb) d.addErrback(eb) def _reschedule(self): """ Schedule the next iteration of this looping call. """ if self.interval == 0: self.call = self.clock.callLater(0, self) return currentTime = self.clock.seconds() # Find how long is left until the interval comes around again. untilNextTime = (self._expectNextCallAt - currentTime) % self.interval # Make sure it is in the future, in case more than one interval worth # of time passed since the previous call was made. nextTime = max( self._expectNextCallAt + self.interval, currentTime + untilNextTime) # If the interval falls on the current time exactly, skip it and # schedule the call for the next interval. if nextTime == currentTime: nextTime += self.interval self._expectNextCallAt = nextTime self.call = self.clock.callLater(nextTime - currentTime, self) def __repr__(self): if hasattr(self.f, 'func_name'): func = self.f.func_name if hasattr(self.f, 'im_class'): func = self.f.im_class.__name__ + '.' + func else: func = reflect.safe_repr(self.f) return 'LoopingCall<%r>(%s, *%s, **%s)' % ( self.interval, func, reflect.safe_repr(self.a), reflect.safe_repr(self.kw)) class SchedulerError(Exception): """ The operation could not be completed because the scheduler or one of its tasks was in an invalid state. This exception should not be raised directly, but is a superclass of various scheduler-state-related exceptions. """ class SchedulerStopped(SchedulerError): """ The operation could not complete because the scheduler was stopped in progress or was already stopped. """ class TaskFinished(SchedulerError): """ The operation could not complete because the task was already completed, stopped, encountered an error or otherwise permanently stopped running. """ class TaskDone(TaskFinished): """ The operation could not complete because the task was already completed. """ class TaskStopped(TaskFinished): """ The operation could not complete because the task was stopped. """ class TaskFailed(TaskFinished): """ The operation could not complete because the task died with an unhandled error. """ class NotPaused(SchedulerError): """ This exception is raised when a task is resumed which was not previously paused. """ class _Timer(object): MAX_SLICE = 0.01 def __init__(self): self.end = time.time() + self.MAX_SLICE def __call__(self): return time.time() >= self.end _EPSILON = 0.00000001 def _defaultScheduler(x): from twisted.internet import reactor return reactor.callLater(_EPSILON, x) class CooperativeTask(object): """ A L{CooperativeTask} is a task object inside a L{Cooperator}, which can be paused, resumed, and stopped. It can also have its completion (or termination) monitored. @see: L{CooperativeTask.cooperate} @ivar _iterator: the iterator to iterate when this L{CooperativeTask} is asked to do work. @ivar _cooperator: the L{Cooperator} that this L{CooperativeTask} participates in, which is used to re-insert it upon resume. @ivar _deferreds: the list of L{defer.Deferred}s to fire when this task completes, fails, or finishes. @type _deferreds: L{list} @type _cooperator: L{Cooperator} @ivar _pauseCount: the number of times that this L{CooperativeTask} has been paused; if 0, it is running. @type _pauseCount: L{int} @ivar _completionState: The completion-state of this L{CooperativeTask}. C{None} if the task is not yet completed, an instance of L{TaskStopped} if C{stop} was called to stop this task early, of L{TaskFailed} if the application code in the iterator raised an exception which caused it to terminate, and of L{TaskDone} if it terminated normally via raising L{StopIteration}. @type _completionState: L{TaskFinished} """ def __init__(self, iterator, cooperator): """ A private constructor: to create a new L{CooperativeTask}, see L{Cooperator.cooperate}. """ self._iterator = iterator self._cooperator = cooperator self._deferreds = [] self._pauseCount = 0 self._completionState = None self._completionResult = None cooperator._addTask(self) def whenDone(self): """ Get a L{defer.Deferred} notification of when this task is complete. @return: a L{defer.Deferred} that fires with the C{iterator} that this L{CooperativeTask} was created with when the iterator has been exhausted (i.e. its C{next} method has raised L{StopIteration}), or fails with the exception raised by C{next} if it raises some other exception. @rtype: L{defer.Deferred} """ d = defer.Deferred() if self._completionState is None: self._deferreds.append(d) else: d.callback(self._completionResult) return d def pause(self): """ Pause this L{CooperativeTask}. Stop doing work until L{CooperativeTask.resume} is called. If C{pause} is called more than once, C{resume} must be called an equal number of times to resume this task. @raise TaskFinished: if this task has already finished or completed. """ self._checkFinish() self._pauseCount += 1 if self._pauseCount == 1: self._cooperator._removeTask(self) def resume(self): """ Resume processing of a paused L{CooperativeTask}. @raise NotPaused: if this L{CooperativeTask} is not paused. """ if self._pauseCount == 0: raise NotPaused() self._pauseCount -= 1 if self._pauseCount == 0 and self._completionState is None: self._cooperator._addTask(self) def _completeWith(self, completionState, deferredResult): """ @param completionState: a L{TaskFinished} exception or a subclass thereof, indicating what exception should be raised when subsequent operations are performed. @param deferredResult: the result to fire all the deferreds with. """ self._completionState = completionState self._completionResult = deferredResult if not self._pauseCount: self._cooperator._removeTask(self) # The Deferreds need to be invoked after all this is completed, because # a Deferred may want to manipulate other tasks in a Cooperator. For # example, if you call "stop()" on a cooperator in a callback on a # Deferred returned from whenDone(), this CooperativeTask must be gone # from the Cooperator by that point so that _completeWith is not # invoked reentrantly; that would cause these Deferreds to blow up with # an AlreadyCalledError, or the _removeTask to fail with a ValueError. for d in self._deferreds: d.callback(deferredResult) def stop(self): """ Stop further processing of this task. @raise TaskFinished: if this L{CooperativeTask} has previously completed, via C{stop}, completion, or failure. """ self._checkFinish() self._completeWith(TaskStopped(), Failure(TaskStopped())) def _checkFinish(self): """ If this task has been stopped, raise the appropriate subclass of L{TaskFinished}. """ if self._completionState is not None: raise self._completionState def _oneWorkUnit(self): """ Perform one unit of work for this task, retrieving one item from its iterator, stopping if there are no further items in the iterator, and pausing if the result was a L{defer.Deferred}. """ try: result = self._iterator.next() except StopIteration: self._completeWith(TaskDone(), self._iterator) except: self._completeWith(TaskFailed(), Failure()) else: if isinstance(result, defer.Deferred): self.pause() def failLater(f): self._completeWith(TaskFailed(), f) result.addCallbacks(lambda result: self.resume(), failLater) class Cooperator(object): """ Cooperative task scheduler. """ def __init__(self, terminationPredicateFactory=_Timer, scheduler=_defaultScheduler, started=True): """ Create a scheduler-like object to which iterators may be added. @param terminationPredicateFactory: A no-argument callable which will be invoked at the beginning of each step and should return a no-argument callable which will return True when the step should be terminated. The default factory is time-based and allows iterators to run for 1/100th of a second at a time. @param scheduler: A one-argument callable which takes a no-argument callable and should invoke it at some future point. This will be used to schedule each step of this Cooperator. @param started: A boolean which indicates whether iterators should be stepped as soon as they are added, or if they will be queued up until L{Cooperator.start} is called. """ self._tasks = [] self._metarator = iter(()) self._terminationPredicateFactory = terminationPredicateFactory self._scheduler = scheduler self._delayedCall = None self._stopped = False self._started = started def coiterate(self, iterator, doneDeferred=None): """ Add an iterator to the list of iterators this L{Cooperator} is currently running. @param doneDeferred: If specified, this will be the Deferred used as the completion deferred. It is suggested that you use the default, which creates a new Deferred for you. @return: a Deferred that will fire when the iterator finishes. """ if doneDeferred is None: doneDeferred = defer.Deferred() CooperativeTask(iterator, self).whenDone().chainDeferred(doneDeferred) return doneDeferred def cooperate(self, iterator): """ Start running the given iterator as a long-running cooperative task, by calling next() on it as a periodic timed event. @param iterator: the iterator to invoke. @return: a L{CooperativeTask} object representing this task. """ return CooperativeTask(iterator, self) def _addTask(self, task): """ Add a L{CooperativeTask} object to this L{Cooperator}. """ if self._stopped: self._tasks.append(task) # XXX silly, I know, but _completeWith # does the inverse task._completeWith(SchedulerStopped(), Failure(SchedulerStopped())) else: self._tasks.append(task) self._reschedule() def _removeTask(self, task): """ Remove a L{CooperativeTask} from this L{Cooperator}. """ self._tasks.remove(task) # If no work left to do, cancel the delayed call: if not self._tasks and self._delayedCall: self._delayedCall.cancel() self._delayedCall = None def _tasksWhileNotStopped(self): """ Yield all L{CooperativeTask} objects in a loop as long as this L{Cooperator}'s termination condition has not been met. """ terminator = self._terminationPredicateFactory() while self._tasks: for t in self._metarator: yield t if terminator(): return self._metarator = iter(self._tasks) def _tick(self): """ Run one scheduler tick. """ self._delayedCall = None for taskObj in self._tasksWhileNotStopped(): taskObj._oneWorkUnit() self._reschedule() _mustScheduleOnStart = False def _reschedule(self): if not self._started: self._mustScheduleOnStart = True return if self._delayedCall is None and self._tasks: self._delayedCall = self._scheduler(self._tick) def start(self): """ Begin scheduling steps. """ self._stopped = False self._started = True if self._mustScheduleOnStart: del self._mustScheduleOnStart self._reschedule() def stop(self): """ Stop scheduling steps. Errback the completion Deferreds of all iterators which have been added and forget about them. """ self._stopped = True for taskObj in self._tasks: taskObj._completeWith(SchedulerStopped(), Failure(SchedulerStopped())) self._tasks = [] if self._delayedCall is not None: self._delayedCall.cancel() self._delayedCall = None _theCooperator = Cooperator() def coiterate(iterator): """ Cooperatively iterate over the given iterator, dividing runtime between it and all other iterators which have been passed to this function and not yet exhausted. """ return _theCooperator.coiterate(iterator) def cooperate(iterator): """ Start running the given iterator as a long-running cooperative task, by calling next() on it as a periodic timed event. @param iterator: the iterator to invoke. @return: a L{CooperativeTask} object representing this task. """ return _theCooperator.cooperate(iterator) class Clock: """ Provide a deterministic, easily-controlled implementation of L{IReactorTime.callLater}. This is commonly useful for writing deterministic unit tests for code which schedules events using this API. """ implements(IReactorTime) rightNow = 0.0 def __init__(self): self.calls = [] def seconds(self): """ Pretend to be time.time(). This is used internally when an operation such as L{IDelayedCall.reset} needs to determine a a time value relative to the current time. @rtype: C{float} @return: The time which should be considered the current time. """ return self.rightNow def _sortCalls(self): """ Sort the pending calls according to the time they are scheduled. """ self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime())) def callLater(self, when, what, *a, **kw): """ See L{twisted.internet.interfaces.IReactorTime.callLater}. """ dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remove, lambda c: None, self.seconds) self.calls.append(dc) self._sortCalls() return dc def getDelayedCalls(self): """ See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls} """ return self.calls def advance(self, amount): """ Move time on this clock forward by the given amount and run whatever pending calls should be run. @type amount: C{float} @param amount: The number of seconds which to advance this clock's time. """ self.rightNow += amount self._sortCalls() while self.calls and self.calls[0].getTime() <= self.seconds(): call = self.calls.pop(0) call.called = 1 call.func(*call.args, **call.kw) self._sortCalls() def pump(self, timings): """ Advance incrementally by the given set of times. @type timings: iterable of C{float} """ for amount in timings: self.advance(amount) def deferLater(clock, delay, callable, *args, **kw): """ Call the given function after a certain period of time has passed. @type clock: L{IReactorTime} provider @param clock: The object which will be used to schedule the delayed call. @type delay: C{float} or C{int} @param delay: The number of seconds to wait before calling the function. @param callable: The object to call after the delay. @param *args: The positional arguments to pass to C{callable}. @param **kw: The keyword arguments to pass to C{callable}. @rtype: L{defer.Deferred} @return: A deferred that fires with the result of the callable when the specified time has elapsed. """ def deferLaterCancel(deferred): delayedCall.cancel() d = defer.Deferred(deferLaterCancel) d.addCallback(lambda ignored: callable(*args, **kw)) delayedCall = clock.callLater(delay, d.callback, None) return d __all__ = [ 'LoopingCall', 'Clock', 'SchedulerStopped', 'Cooperator', 'coiterate', 'deferLater', ]
Varriount/Colliberation
libs/twisted/internet/task.py
Python
mit
24,723
<?php namespace DUDEEGO\PlatformBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Vich\UploaderBundle\Form\Type\VichFileType; class EA_DocumentType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('PasseportName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('PasseportFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('CarteIdentiteName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('CarteIdentiteFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('BulletinNoteName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('BulletinNoteFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('BacName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('BacFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('CredentialName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('CredentialFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('LettreRecommendationName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('LettreRecommendationFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('LettreMotivationName', TextType::class, array( 'attr' => array('class' => 'form-control'), 'required' => false, 'empty_data' => null)) ->add('LettreMotivationFile', VichFileType::class, [ 'label' => 'Choissisez un document...', 'required' => false, 'allow_delete' => false, // optional, default is true 'download_link' => false, // optional, default is true ]) ->add('updatedAt') ->add('upload', SubmitType::class, array( 'attr' => array('class' => 'btn btn-primary'), )) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'DUDEEGO\PlatformBundle\Entity\EA_Document' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'dudeego_platformbundle_ea_document'; } }
HosseinChibane/CFPMS
src/DUDEEGO/PlatformBundle/Form/EA_DocumentType.php
PHP
mit
4,433
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-21 12:06 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('slug', models.SlugField(allow_unicode=True, unique=True)), ('description', models.TextField(blank=True, default='')), ('description_html', models.TextField(blank=True, default='', editable=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='GroupMember', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.Group')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_groups', to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='group', name='members', field=models.ManyToManyField(through='groups.GroupMember', to=settings.AUTH_USER_MODEL), ), migrations.AlterUniqueTogether( name='groupmember', unique_together=set([('group', 'user')]), ), ]
srijannnd/Login-and-Register-App-in-Django
simplesocial/groups/migrations/0001_initial.py
Python
mit
1,868
<?php namespace Kodix\Support\Traits\Component; use CComponentEngine; /** * This trait makes complex class easier to write * You just need to change setUrlTemplates404 method with your paths * * Class ComplexTrait * @package Malyusha\Helpers\Traits * * @property array $arParams */ trait ComplexTrait { public $page = ''; public $defaultPage = 'list'; /** * @var CComponentEngine instance */ public $engine; public $urlTemplates; public $variables = []; public $componentVariables; public $variablesAliases = []; public $urlTemplates404 = []; public $variableAliases404 = []; public function setUrlTemplates404() { $this->urlTemplates404 = [ "detail" => $this->arParams["SEF_URL_TEMPLATES"]["detail"], "section" => $this->arParams["SEF_URL_TEMPLATES"]["section"], ]; } public function boot() { $this->setUrlTemplates404(); $this->startEngine(); $this->makeTemplates(); $this->makeAliases(); $this->setPage(); $this->checkPage(); $this->makeResult(); } public function startEngine() { $this->engine = new CComponentEngine($this); if(\Bitrix\Main\Loader::includeModule('iblock')) { $this->engine->addGreedyPart("#SECTION_CODE_PATH#"); $this->engine->setResolveCallback(["CIBlockFindTools", "resolveComponentEngine"]); } } public function setPage() { $this->page = $this->engine->guessComponentPath( $this->arParams["SEF_FOLDER"], $this->urlTemplates, $this->variables ); } public function checkPage() { if(!$this->page) { if($this->arParams['SHOW_404'] == 'Y') show404(); else $this->page = $this->defaultPage; } CComponentEngine::InitComponentVariables($this->page, $this->componentVariables, $this->variablesAliases, $this->variables); } public function makeTemplates() { $this->urlTemplates = CComponentEngine::MakeComponentUrlTemplates($this->urlTemplates404, $this->arParams["SEF_URL_TEMPLATES"]); } public function makeAliases() { $this->variablesAliases = CComponentEngine::MakeComponentVariableAliases($this->variableAliases404, $this->arParams["VARIABLE_ALIASES"]); } public function makeResult() { $this->arResult = [ "FOLDER" => $this->arParams["SEF_FOLDER"], "URL_TEMPLATES" => $this->urlTemplates, "VARIABLES" => $this->variables, "ALIASES" => $this->variablesAliases, ]; } }
malyusha/kodix
src/Support/Traits/Component/ComplexTrait.php
PHP
mit
2,709
/* * Background sketch * Author: Uriel Sade * Date: Feb. 22, 2017 */ var canvas; var time_x, time_y, time_z, time_inc; var field = []; var particles = []; var rows, cols; var scl = 20; function setup() { canvas = createCanvas(windowWidth, windowHeight); canvas.position(0,0); canvas.style('z-value', '-1'); canvas.style('opacity', '0.99'); background(0,0,0,0); rows = 25; scl = floor(height/rows); cols = floor(width/scl); time_inc = 0.2; time_x = time_y = time_z = 0; for(var i = 0; i < 20; i++){ particles[i] = new Particle(); } } function draw(){ background(0,0,0,10); fill(255); // text("by Uriel Sade", width/40, height- height/40); noFill(); field = []; time_y = 0; for(var y = 0; y < rows; y++){ time_x = 0; for(var x = 0; x < cols; x++){ push(); translate(x*scl + scl/2, y*scl + scl/2); var direction_vector = p5.Vector.fromAngle(noise(time_x, time_y, time_z)*2*PI + PI); rotate(direction_vector.heading()); stroke(0,255,0, 7); strokeWeight(1); line(-scl/6,0,scl/6,0); pop(); field[y* cols + x] = direction_vector; time_x += time_inc; } time_y += time_inc; time_z += 0.0002; } updateParticles(); } function updateParticles(){ for(var i = 0; i < particles.length; i++){ particles[i].accelerate(field); } } function windowResized(){ setup(); }
urielsade/urielsade.github.io
flowfield.js
JavaScript
mit
1,411
package org.knowm.xchange.bitstamp.service.marketdata; import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.bitstamp.BitstampExchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.service.polling.marketdata.PollingMarketDataService; /** * @author timmolter */ public class TickerFetchIntegration { @Test public void tickerFetchTest() throws Exception { Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName()); PollingMarketDataService marketDataService = exchange.getPollingMarketDataService(); Ticker ticker = marketDataService.getTicker(new CurrencyPair("BTC", "USD")); System.out.println(ticker.toString()); assertThat(ticker).isNotNull(); } }
mmithril/XChange
xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/service/marketdata/TickerFetchIntegration.java
Java
mit
929
FactoryBot.define do factory :status do sequence(:label) { |n| "President #{n}" } end end
piwam/piwam
spec/factories/statuses.rb
Ruby
mit
98
<?php /* Unsafe sample input : get the field UserData from the variable $_POST sanitize : use of the function addslashes construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_POST['UserData']; $tainted = addslashes($tainted); //flaw $var = header(sprintf("Location: '%s'", $tainted)); ?>
stivalet/PHP-Vulnerability-test-suite
URF/CWE_601/unsafe/CWE_601__POST__func_addslashes__header_url-sprintf_%s_simple_quote.php
PHP
mit
1,224
print 'Immettere un raggio: ' raggio_stringa = gets raggio = raggio_stringa.to_i area = raggio * raggio * Math::PI puts "L'area del cerchio di raggio #{raggio} e' #{area}"
guildenstern70/rubyerails
src/AreaDelCerchio.rb
Ruby
mit
173
'use strict'; /* Filters */ angular.module('multi-screen-demo.filters', [ ]). // create your own filter here filter('yourFilterName', function () { return function () { return; }; });
drejkim/multi-screen-demo
public/js/filters.js
JavaScript
mit
193
package com.github.gv2011.util.bytes; import static com.github.gv2011.testutil.Assert.assertThat; import static com.github.gv2011.testutil.Matchers.is; import org.junit.Test; import com.github.gv2011.util.BeanUtils; import com.github.gv2011.util.icol.ICollections; import com.github.gv2011.util.json.JsonUtils; public class DataTypeTest { @Test public void test() { final String encoded = "multipart/related; boundary=example-2; start=\"<950118.AEBH@XIson.com>\"; type=\"Text/x-Okie\"" ; final DataType type = DataType.parse(encoded); assertThat(type.getClass(), is(DataTypeImp.class)); assertThat(type.primaryType(), is("multipart")); assertThat(type.subType(), is("related")); assertThat(type.baseType(), is(DataType.parse("multipart/related"))); assertThat(type.parameters(), is( ICollections.mapBuilder() .put("boundary", "example-2") .put("start", "<950118.AEBH@XIson.com>") .put("type", "Text/x-Okie") .build() )); assertThat(type.toString(), is(encoded)); assertThat( BeanUtils.typeRegistry().beanType(DataType.class).toJson(type), is(JsonUtils.jsonFactory().primitive(encoded)) ); } @Test(expected=IllegalStateException.class) public void testValidation() { BeanUtils.beanBuilder(DataType.class) .set(DataType::primaryType).to("multipart") .set(DataType::subType).to("@") .build() ; } @Test//(expected=IllegalStateException.class) public void testValidation2() { BeanUtils.beanBuilder(DataType.class) .set(DataType::primaryType).to("multipart") .set(DataType::subType).to("related") .build() ; } }
gv2011/util
test/src/test/java/com/github/gv2011/util/bytes/DataTypeTest.java
Java
mit
1,762
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <std__vector.hpp> START_ATF_NAMESPACE #pragma pack(push, 8) struct CUnmannedTraderGroupDivisionVersionInfo { int m_iType; std::vector<unsigned long> m_vecuiVersion; public: CUnmannedTraderGroupDivisionVersionInfo(struct CUnmannedTraderGroupDivisionVersionInfo* lhs); void ctor_CUnmannedTraderGroupDivisionVersionInfo(struct CUnmannedTraderGroupDivisionVersionInfo* lhs); CUnmannedTraderGroupDivisionVersionInfo(int iType, unsigned int uiMaxCnt); void ctor_CUnmannedTraderGroupDivisionVersionInfo(int iType, unsigned int uiMaxCnt); bool GetVersion(char byClass, unsigned int* dwVer); bool IncreaseVersion(char byClass); bool IsEmpty(); ~CUnmannedTraderGroupDivisionVersionInfo(); void dtor_CUnmannedTraderGroupDivisionVersionInfo(); }; #pragma pack(pop) static_assert(ATF::checkSize<CUnmannedTraderGroupDivisionVersionInfo, 48>(), "CUnmannedTraderGroupDivisionVersionInfo"); END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/CUnmannedTraderGroupDivisionVersionInfo.hpp
C++
mit
1,173
<?php /* Version: 1.0 Author: Artur Sułkowski Website: http://artursulkowski.pl */ class ControllerModuleBreadcrumbBackgroundImage extends Controller { private $error = array(); public function index() { $this->language->load('module/breadcrumb_background_image'); $this->document->setTitle('Breadcrumb Background Image'); $this->load->model('setting/setting'); // Dodawanie plików css i js do <head> $this->document->addStyle('view/stylesheet/breadcrumb_background_image.css'); // Zapisywanie modułu if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('breadcrumb_background_image', $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('module/breadcrumb_background_image', 'token=' . $this->session->data['token'], 'SSL')); } // Wyświetlanie powiadomień if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } if (isset($this->session->data['success'])) { $data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $data['success'] = ''; } $data['action'] = $this->url->link('module/breadcrumb_background_image', 'token=' . $this->session->data['token'], 'SSL'); $data['token'] = $this->session->data['token']; // Ładowanie listy modułów $data['modules'] = array(); if (isset($this->request->post['breadcrumb_background_image_module'])) { $data['modules'] = $this->request->post['breadcrumb_background_image_module']; } elseif ($this->config->get('breadcrumb_background_image_module')) { $data['modules'] = $this->config->get('breadcrumb_background_image_module'); } // Layouts $this->load->model('design/layout'); $data['layouts'] = $this->model_design_layout->getLayouts(); // Languages $this->load->model('localisation/language'); $data['languages'] = $this->model_localisation_language->getLanguages(); $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => 'Modules', 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => 'Breadcrumb Background Image', 'href' => $this->url->link('module/breadcrumb_background_image', 'token=' . $this->session->data['token'], 'SSL') ); $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); // No image $this->load->model('tool/image'); $data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100); $this->response->setOutput($this->load->view('module/breadcrumb_background_image.tpl', $data)); } protected function validate() { if (!$this->user->hasPermission('modify', 'module/breadcrumb_background_image')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->error) { return true; } else { return false; } } } ?>
monkdaf/skuter77-opencart
admin/controller/module/breadcrumb_background_image.php
PHP
mit
3,475
package com.kata.businessrules; import org.w3c.dom.Document; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; import com.kata.businessrules.products.Product; public class MainModule extends AbstractModule { @Override protected void configure() { installDummyModules(); bind(new TypeLiteral<RuleEngineLoader<Document>>() { }); } private void installDummyModules() { bind(ReceiptGenerator.class).toInstance(new ReceiptGenerator() { @Override public Receipt generateReceipt(User customer, Product product) { return null; } }); bind(UserRepository.class).toInstance(new UserRepository() { @Override public User getById(String id) { return null; } }); bind(ProductRepository.class).toInstance(new ProductRepository() { @Override public <T extends Product> T getById(String id) { return null; } }); } }
a-ostrovsky/business_rules_kata
src/main/java/com/kata/businessrules/MainModule.java
Java
mit
895
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { WeatherComponent } from './components/weather.component'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule ], declarations: [ AppComponent, WeatherComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
tvinoths/weather
src/app/app.module.ts
TypeScript
mit
518
namespace MachineLearning { public enum CallbackFrequency : byte { Never = 0, EachExample = 1, EachError = 2, EachEpoch = 3, EachNEpochs = 4 } }
Artem-Romanenia/machine-learning
MachineLearning/CallbackFrequency.cs
C#
mit
200
<?php namespace Ems\Contracts\Foundation; use Ems\Contracts\Core\AppliesToResource; use Ems\Contracts\Validation\ValidatorFactory; use Ems\Contracts\Core\HasMethodHooks; use Ems\Contracts\Core\Extendable; /** * The InputNormalizerFactory is the factory for the InputNormalizer objects. * You should categorize the input by its type (http.browser.get, http.browser.post) * http.browser.delete, http.api.get, console.linux.argv, http.js.get,...whatever) * The segment count has to be 3. * * Assign a callable which configures the created InputNormalizer for use * with the desired adjustments/casts/validator. * The extension gets the normalizer, inputType, the resource, the locale. * Wildcard segments are allowed. If your callable matches many inputTypes * all of em will be called. * To overwrite a extension you have to use the same pattern as the assign one. * * If you want to support a new type just call $factory->extend('http.browser.get', fn(){}); * If then a matching input normalizer is created, youre callable receives the * normalizer and its up to the callable which adjustments, casting, validation * should run. * Just like this: * $factory->extend('http.*.post', function ($normalizer, $inputType, $resource, $locale) { * $normalizer->adjust('to_null|no_method|remove_token|xtype_adjust') * ->validate(true) * ->cast('to_nested|xtype_cast'); * }); * * Then when using the normalizer in a controller, request, import or so just * call $factory->normalizer('http.browser.post')->normalize($input) * and all the globally assigned processors will process the input. * * If you use InputNormalizerFactory::onBefore('adjust') (or validate or cast) * your listener will be copied to every created normalizer. * * If you want to have your listener only in one instance of a normalizer (this * is mostly the case) you should hook into the normalizer: * InputNormalizerFactory::normalizer('http.api.get')->onAfter('adjust', fn(){}); * * The pattern wildcards are processed by priority. Higher priority extensions * are called later (cause they have the last word). * example: * http.browser.get -> *.*.* * -> http.*.* * -> *.browser.* * -> *.*.get * -> http.browser.* * -> http.*.get * -> *.browser.get * -> http.browser.get * * Basic proposals for often used input types are: * * http.browser.$method * http.js.$method * http.json-api.$method * file.import.csv * console.bash.argv * console.cron.argv * console.windows.pipe * **/ interface InputNormalizerFactory extends Extendable, HasMethodHooks { /** * Return a matching InputNormalizer for $inputType and optionally $resource * * @param string $inputType * @param string|AppliesToResource $resource (optional) * @param string $locale * * @return array **/ public function normalizer($inputType, $resource=null, $locale=null); /** * Return the default adjust input processor. It is mainly used to add your * globally available adjusters via InputNormalizerFactory::adjuster()->extend() * * @return InputProcessor **/ public function adjuster(); /** * Return the ValidatorFactory used by the InputNormalizerFactory. This is * just to have access to all dependencies. * * @return ValidatorFactory **/ public function validatorFactory(); /** * Return the default cast input processor. It is mainly used to add your * globally available casters via InputNormalizerFactory::caster()->extend() * * @return InputProcessor **/ public function caster(); }
mtils/php-ems
src/Ems/Contracts/Foundation/InputNormalizerFactory.php
PHP
mit
3,811
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HorseTrack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HorseTrack")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("16bf1cc4-a18a-411e-923b-e952ca9e91cc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
yorgov/HorseTrack
HorseTrack/Properties/AssemblyInfo.cs
C#
mit
1,333
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.UtmConverter = factory(); } }(this, function () { ////////////////////////////////////////////////////////////////////////////////////////////////// // BEGIN ORIGINAL LIBRARY ////////////////////////////////////////////////////////////////////////////////////////////////// var pi = Math.PI; /* Ellipsoid model constants (actual values here are for WGS84) */ var sm_a = 6378137.0; var sm_b = 6356752.314; var sm_EccSquared = 6.69437999013e-03; var UTMScaleFactor = 0.9996; /* * DegToRad * * Converts degrees to radians. * */ function DegToRad (deg) { return (deg / 180.0 * pi) } /* * RadToDeg * * Converts radians to degrees. * */ function RadToDeg (rad) { return (rad / pi * 180.0) } /* * ArcLengthOfMeridian * * Computes the ellipsoidal distance from the equator to a point at a * given latitude. * * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., * GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994. * * Inputs: * phi - Latitude of the point, in radians. * * Globals: * sm_a - Ellipsoid model major axis. * sm_b - Ellipsoid model minor axis. * * Returns: * The ellipsoidal distance of the point from the equator, in meters. * */ function ArcLengthOfMeridian (phi) { var alpha, beta, gamma, delta, epsilon, n; var result; /* Precalculate n */ n = (sm_a - sm_b) / (sm_a + sm_b); /* Precalculate alpha */ alpha = ((sm_a + sm_b) / 2.0) * (1.0 + (Math.pow (n, 2.0) / 4.0) + (Math.pow (n, 4.0) / 64.0)); /* Precalculate beta */ beta = (-3.0 * n / 2.0) + (9.0 * Math.pow (n, 3.0) / 16.0) + (-3.0 * Math.pow (n, 5.0) / 32.0); /* Precalculate gamma */ gamma = (15.0 * Math.pow (n, 2.0) / 16.0) + (-15.0 * Math.pow (n, 4.0) / 32.0); /* Precalculate delta */ delta = (-35.0 * Math.pow (n, 3.0) / 48.0) + (105.0 * Math.pow (n, 5.0) / 256.0); /* Precalculate epsilon */ epsilon = (315.0 * Math.pow (n, 4.0) / 512.0); /* Now calculate the sum of the series and return */ result = alpha * (phi + (beta * Math.sin (2.0 * phi)) + (gamma * Math.sin (4.0 * phi)) + (delta * Math.sin (6.0 * phi)) + (epsilon * Math.sin (8.0 * phi))); return result; } /* * UTMCentralMeridian * * Determines the central meridian for the given UTM zone. * * Inputs: * zone - An integer value designating the UTM zone, range [1,60]. * * Returns: * The central meridian for the given UTM zone, in radians, or zero * if the UTM zone parameter is outside the range [1,60]. * Range of the central meridian is the radian equivalent of [-177,+177]. * */ function UTMCentralMeridian (zone) { var cmeridian; cmeridian = DegToRad (-183.0 + (zone * 6.0)); return cmeridian; } /* * FootpointLatitude * * Computes the footpoint latitude for use in converting transverse * Mercator coordinates to ellipsoidal coordinates. * * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., * GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994. * * Inputs: * y - The UTM northing coordinate, in meters. * * Returns: * The footpoint latitude, in radians. * */ function FootpointLatitude (y) { var y_, alpha_, beta_, gamma_, delta_, epsilon_, n; var result; /* Precalculate n (Eq. 10.18) */ n = (sm_a - sm_b) / (sm_a + sm_b); /* Precalculate alpha_ (Eq. 10.22) */ /* (Same as alpha in Eq. 10.17) */ alpha_ = ((sm_a + sm_b) / 2.0) * (1 + (Math.pow (n, 2.0) / 4) + (Math.pow (n, 4.0) / 64)); /* Precalculate y_ (Eq. 10.23) */ y_ = y / alpha_; /* Precalculate beta_ (Eq. 10.22) */ beta_ = (3.0 * n / 2.0) + (-27.0 * Math.pow (n, 3.0) / 32.0) + (269.0 * Math.pow (n, 5.0) / 512.0); /* Precalculate gamma_ (Eq. 10.22) */ gamma_ = (21.0 * Math.pow (n, 2.0) / 16.0) + (-55.0 * Math.pow (n, 4.0) / 32.0); /* Precalculate delta_ (Eq. 10.22) */ delta_ = (151.0 * Math.pow (n, 3.0) / 96.0) + (-417.0 * Math.pow (n, 5.0) / 128.0); /* Precalculate epsilon_ (Eq. 10.22) */ epsilon_ = (1097.0 * Math.pow (n, 4.0) / 512.0); /* Now calculate the sum of the series (Eq. 10.21) */ result = y_ + (beta_ * Math.sin (2.0 * y_)) + (gamma_ * Math.sin (4.0 * y_)) + (delta_ * Math.sin (6.0 * y_)) + (epsilon_ * Math.sin (8.0 * y_)); return result; } /* * MapLatLonToXY * * Converts a latitude/longitude pair to x and y coordinates in the * Transverse Mercator projection. Note that Transverse Mercator is not * the same as UTM; a scale factor is required to convert between them. * * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., * GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994. * * Inputs: * phi - Latitude of the point, in radians. * lambda - Longitude of the point, in radians. * lambda0 - Longitude of the central meridian to be used, in radians. * * Outputs: * xy - A 2-element array containing the x and y coordinates * of the computed point. * * Returns: * The function does not return a value. * */ function MapLatLonToXY (phi, lambda, lambda0, xy) { var N, nu2, ep2, t, t2, l; var l3coef, l4coef, l5coef, l6coef, l7coef, l8coef; var tmp; /* Precalculate ep2 */ ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0); /* Precalculate nu2 */ nu2 = ep2 * Math.pow (Math.cos (phi), 2.0); /* Precalculate N */ N = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nu2)); /* Precalculate t */ t = Math.tan (phi); t2 = t * t; tmp = (t2 * t2 * t2) - Math.pow (t, 6.0); /* Precalculate l */ l = lambda - lambda0; /* Precalculate coefficients for l**n in the equations below so a normal human being can read the expressions for easting and northing -- l**1 and l**2 have coefficients of 1.0 */ l3coef = 1.0 - t2 + nu2; l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2); l5coef = 5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2 - 58.0 * t2 * nu2; l6coef = 61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2 - 330.0 * t2 * nu2; l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2); l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2); /* Calculate easting (x) */ xy[0] = N * Math.cos (phi) * l + (N / 6.0 * Math.pow (Math.cos (phi), 3.0) * l3coef * Math.pow (l, 3.0)) + (N / 120.0 * Math.pow (Math.cos (phi), 5.0) * l5coef * Math.pow (l, 5.0)) + (N / 5040.0 * Math.pow (Math.cos (phi), 7.0) * l7coef * Math.pow (l, 7.0)); /* Calculate northing (y) */ xy[1] = ArcLengthOfMeridian (phi) + (t / 2.0 * N * Math.pow (Math.cos (phi), 2.0) * Math.pow (l, 2.0)) + (t / 24.0 * N * Math.pow (Math.cos (phi), 4.0) * l4coef * Math.pow (l, 4.0)) + (t / 720.0 * N * Math.pow (Math.cos (phi), 6.0) * l6coef * Math.pow (l, 6.0)) + (t / 40320.0 * N * Math.pow (Math.cos (phi), 8.0) * l8coef * Math.pow (l, 8.0)); return; } /* * MapXYToLatLon * * Converts x and y coordinates in the Transverse Mercator projection to * a latitude/longitude pair. Note that Transverse Mercator is not * the same as UTM; a scale factor is required to convert between them. * * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., * GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994. * * Inputs: * x - The easting of the point, in meters. * y - The northing of the point, in meters. * lambda0 - Longitude of the central meridian to be used, in radians. * * Outputs: * philambda - A 2-element containing the latitude and longitude * in radians. * * Returns: * The function does not return a value. * * Remarks: * The local variables Nf, nuf2, tf, and tf2 serve the same purpose as * N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect * to the footpoint latitude phif. * * x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and * to optimize computations. * */ function MapXYToLatLon (x, y, lambda0, philambda) { var phif, Nf, Nfpow, nuf2, ep2, tf, tf2, tf4, cf; var x1frac, x2frac, x3frac, x4frac, x5frac, x6frac, x7frac, x8frac; var x2poly, x3poly, x4poly, x5poly, x6poly, x7poly, x8poly; /* Get the value of phif, the footpoint latitude. */ phif = FootpointLatitude (y); /* Precalculate ep2 */ ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0); /* Precalculate cos (phif) */ cf = Math.cos (phif); /* Precalculate nuf2 */ nuf2 = ep2 * Math.pow (cf, 2.0); /* Precalculate Nf and initialize Nfpow */ Nf = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nuf2)); Nfpow = Nf; /* Precalculate tf */ tf = Math.tan (phif); tf2 = tf * tf; tf4 = tf2 * tf2; /* Precalculate fractional coefficients for x**n in the equations below to simplify the expressions for latitude and longitude. */ x1frac = 1.0 / (Nfpow * cf); Nfpow *= Nf; /* now equals Nf**2) */ x2frac = tf / (2.0 * Nfpow); Nfpow *= Nf; /* now equals Nf**3) */ x3frac = 1.0 / (6.0 * Nfpow * cf); Nfpow *= Nf; /* now equals Nf**4) */ x4frac = tf / (24.0 * Nfpow); Nfpow *= Nf; /* now equals Nf**5) */ x5frac = 1.0 / (120.0 * Nfpow * cf); Nfpow *= Nf; /* now equals Nf**6) */ x6frac = tf / (720.0 * Nfpow); Nfpow *= Nf; /* now equals Nf**7) */ x7frac = 1.0 / (5040.0 * Nfpow * cf); Nfpow *= Nf; /* now equals Nf**8) */ x8frac = tf / (40320.0 * Nfpow); /* Precalculate polynomial coefficients for x**n. -- x**1 does not have a polynomial coefficient. */ x2poly = -1.0 - nuf2; x3poly = -1.0 - 2 * tf2 - nuf2; x4poly = 5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2 - 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2); x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2; x6poly = -61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2 + 162.0 * tf2 * nuf2; x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2); x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2); /* Calculate latitude */ philambda[0] = phif + x2frac * x2poly * (x * x) + x4frac * x4poly * Math.pow (x, 4.0) + x6frac * x6poly * Math.pow (x, 6.0) + x8frac * x8poly * Math.pow (x, 8.0); /* Calculate longitude */ philambda[1] = lambda0 + x1frac * x + x3frac * x3poly * Math.pow (x, 3.0) + x5frac * x5poly * Math.pow (x, 5.0) + x7frac * x7poly * Math.pow (x, 7.0); return; } /* * LatLonToUTMXY * * Converts a latitude/longitude pair to x and y coordinates in the * Universal Transverse Mercator projection. * * Inputs: * lat - Latitude of the point, in radians. * lon - Longitude of the point, in radians. * zone - UTM zone to be used for calculating values for x and y. * If zone is less than 1 or greater than 60, the routine * will determine the appropriate zone from the value of lon. * * Outputs: * xy - A 2-element array where the UTM x and y values will be stored. * * Returns: * The UTM zone used for calculating the values of x and y. * */ function LatLonToUTMXY (lat, lon, zone, xy) { MapLatLonToXY (lat, lon, UTMCentralMeridian (zone), xy); /* Adjust easting and northing for UTM system. */ xy[0] = xy[0] * UTMScaleFactor + 500000.0; xy[1] = xy[1] * UTMScaleFactor; if (xy[1] < 0.0) xy[1] = xy[1] + 10000000.0; return zone; } /* * UTMXYToLatLon * * Converts x and y coordinates in the Universal Transverse Mercator * projection to a latitude/longitude pair. * * Inputs: * x - The easting of the point, in meters. * y - The northing of the point, in meters. * zone - The UTM zone in which the point lies. * southhemi - True if the point is in the southern hemisphere; * false otherwise. * * Outputs: * latlon - A 2-element array containing the latitude and * longitude of the point, in radians. * * Returns: * The function does not return a value. * */ function UTMXYToLatLon (x, y, zone, southhemi, latlon) { var cmeridian; x -= 500000.0; x /= UTMScaleFactor; /* If in southern hemisphere, adjust y accordingly. */ if (southhemi) y -= 10000000.0; y /= UTMScaleFactor; cmeridian = UTMCentralMeridian (zone); MapXYToLatLon (x, y, cmeridian, latlon); return; } /* * btnToUTM_OnClick * * Called when the btnToUTM button is clicked. * */ function btnToUTM_OnClick () { var xy = new Array(2); if (isNaN (parseFloat (document.frmConverter.txtLongitude.value))) { alert ("Please enter a valid longitude in the lon field."); return false; } lon = parseFloat (document.frmConverter.txtLongitude.value); if ((lon < -180.0) || (180.0 <= lon)) { alert ("The longitude you entered is out of range. " + "Please enter a number in the range [-180, 180)."); return false; } if (isNaN (parseFloat (document.frmConverter.txtLatitude.value))) { alert ("Please enter a valid latitude in the lat field."); return false; } lat = parseFloat (document.frmConverter.txtLatitude.value); if ((lat < -90.0) || (90.0 < lat)) { alert ("The latitude you entered is out of range. " + "Please enter a number in the range [-90, 90]."); return false; } // Compute the UTM zone. zone = Math.floor ((lon + 180.0) / 6) + 1; zone = LatLonToUTMXY (DegToRad (lat), DegToRad (lon), zone, xy); /* Set the output controls. */ document.frmConverter.txtX.value = xy[0]; document.frmConverter.txtY.value = xy[1]; document.frmConverter.txtZone.value = zone; if (lat < 0) // Set the S button. document.frmConverter.rbtnHemisphere[1].checked = true; else // Set the N button. document.frmConverter.rbtnHemisphere[0].checked = true; return true; } /* * btnToGeographic_OnClick * * Called when the btnToGeographic button is clicked. * */ function btnToGeographic_OnClick () { latlon = new Array(2); var x, y, zone, southhemi; if (isNaN (parseFloat (document.frmConverter.txtX.value))) { alert ("Please enter a valid easting in the x field."); return false; } x = parseFloat (document.frmConverter.txtX.value); if (isNaN (parseFloat (document.frmConverter.txtY.value))) { alert ("Please enter a valid northing in the y field."); return false; } y = parseFloat (document.frmConverter.txtY.value); if (isNaN (parseInt (document.frmConverter.txtZone.value))) { alert ("Please enter a valid UTM zone in the zone field."); return false; } zone = parseFloat (document.frmConverter.txtZone.value); if ((zone < 1) || (60 < zone)) { alert ("The UTM zone you entered is out of range. " + "Please enter a number in the range [1, 60]."); return false; } if (document.frmConverter.rbtnHemisphere[1].checked == true) southhemi = true; else southhemi = false; UTMXYToLatLon (x, y, zone, southhemi, latlon); document.frmConverter.txtLongitude.value = RadToDeg (latlon[1]); document.frmConverter.txtLatitude.value = RadToDeg (latlon[0]); return true; } ////////////////////////////////////////////////////////////////////////////////////////////////// // END ORIGINAL LIBRARY ////////////////////////////////////////////////////////////////////////////////////////////////// var UtmConverter = function() { // Currently no additional construction. }; /** * @param {Object} args * @param {Array|Object} args.coord - The WGS84 coordinate as an array in the form * <code>[longitude, latitude]</code> or an object in the form * <code>{longitude: 0, latitude: 0}</code>. * @return {Object} result * @return {Object} result.coord - The UTM coordinate. * @return {Number} result.coord.x * @return {Number} result.coord.y * @return {Number} result.zone - The UTM zone. * @return {Boolean} result.isSouthern - Whether the coordinate is in the southern hemisphere. */ UtmConverter.prototype.toUtm = function(args) { var coord = coordToArray(args.coord, 'longitude', 'latitude'); var lon = coord[0]; var lat = coord[1]; if (lon == null || (lon < -180) || (180 <= lon)) { throw new Error('Longitude must be in range [-180, 180).'); } if (lat == null || (lat < -90) || (90 < lat)) { throw new Error('Latitude must be in range [-90, 90).'); } var zone = Math.floor((lon + 180) / 6) + 1; zone = LatLonToUTMXY(DegToRad(lat), DegToRad(lon), zone, coord); return { coord: {x: coord[0], y: coord[1]}, zone: zone, isSouthern: lat < 0 }; }; /** * @param {Object} args * @param {Array|Object} args.coord - The UTM coordinate as an array in the form * <code>[x, y]</code> or an object in the form <code>{x: 0, y: 0}</code>. * @param {Object} args.coord - The UTM coordinate. * @param {Number} args.zone - The UTM zone. * @param {Boolean} args.isSouthern - Whether the coordinate is in the southern hemisphere. * @return {Object} result * @return {Object} result.coord - The WGS84 coordinate. * @return {Number} result.longitude - The longitude in degrees. * @return {Number} result.latitude - The latitude in degrees. */ UtmConverter.prototype.toWgs = function(args) { var coord = coordToArray(args.coord, 'x', 'y'); var x = coord[0]; var y = coord[1]; var zone = args.zone; if (zone == null || (zone < 1) || (60 < zone)) { throw new Error('The UTM zone must be in the range [1, 60].'); } UTMXYToLatLon(x, y, zone, args.isSouthern, coord); return { coord: {longitude: RadToDeg(coord[1]), latitude: RadToDeg(coord[0])} } } function coordToArray(coord, xProp, yProp) { // Handle the object as an array. if (coord.length === undefined) { return [coord[xProp], coord[yProp]]; } else { // Clone the coord to avoid modifying the input. return Array.prototype.slice.apply(coord); } } return UtmConverter; }));
urbanetic/utm-converter
src/converter.js
JavaScript
mit
19,752
import loudRejection from 'loud-rejection'; import { fireEvent, getByTestId, getByText } from '@testing-library/dom'; import { act, screen } from '@testing-library/react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { addApiMock, clearAll, getDropdown, getHistory, render, minimalCache, addToCache, } from '../../helpers/test/helper'; import { Breakpoints } from '../../models/utils'; import MailHeader from './MailHeader'; loudRejection(); const getProps = () => ({ labelID: 'labelID', elementID: undefined, location: getHistory().location, history: getHistory(), breakpoints: {} as Breakpoints, onSearch: jest.fn(), expanded: true, onToggleExpand: jest.fn(), onOpenShortcutsModal: jest.fn(), }); const user = { Email: 'Email', DisplayName: 'DisplayName', Name: 'Name', hasPaidMail: false, UsedSpace: 10, MaxSpace: 100, }; describe('MailHeader', () => { let props: ReturnType<typeof getProps>; const setup = async () => { minimalCache(); addToCache('User', user); addApiMock('payments/plans', () => ({})); addApiMock('contacts/v4/contacts', () => ({ Contacts: [] })); props = getProps(); const result = await render(<MailHeader {...props} />, false); const searchForm = result.getByRole('search'); const openAdvanced = async () => { const advancedDropdownButton = getByTestId(searchForm, 'dropdown-button'); fireEvent.click(advancedDropdownButton); const dropdown = await getDropdown(); const submitButton = dropdown.querySelector('button[type="submit"]') as HTMLButtonElement; const submit = () => fireEvent.click(submitButton); return { dropdown, submitButton, submit }; }; return { ...result, searchForm, openAdvanced }; }; // Not found better to test // It's hard to override sso mode constant const assertAppLink = (element: HTMLElement, href: string) => { const link = element.closest('a'); expect(link?.getAttribute('href')).toBe(href); }; afterEach(clearAll); describe('Core features', () => { it('should redirect on inbox when click on logo', async () => { const { getByText } = await setup(); const logo = getByText('ProtonMail'); fireEvent.click(logo); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/inbox'); }); it('should open app dropdown', async () => { const { getByTitle } = await setup(); const appsButton = getByTitle('Proton applications'); fireEvent.click(appsButton); const dropdown = await getDropdown(); getByText(dropdown, 'Mail'); getByText(dropdown, 'Calendar'); getByText(dropdown, 'VPN'); }); it('should open contacts widget', async () => { const { getByText: getByTextHeader } = await setup(); const contactsButton = getByTextHeader('Contacts'); fireEvent.click(contactsButton); const dropdown = await getDropdown(); getByText(dropdown, 'Contacts'); getByText(dropdown, 'Groups'); getByText(dropdown, 'Settings'); }); it('should open settings', async () => { const { getByText: getByTextHeader } = await setup(); const settingsButton = getByTextHeader('Settings'); fireEvent.click(settingsButton); const dropdown = await getDropdown(); const settingsLink = getByText(dropdown, 'settings', { exact: false }); assertAppLink(settingsLink, '/mail'); }); it('should open user dropdown', async () => { const { getByText: getByTextHeader } = await setup(); const userButton = getByTextHeader(user.DisplayName); fireEvent.click(userButton); const dropdown = await getDropdown(); const { textContent } = dropdown; expect(textContent).toContain('Proton introduction'); expect(textContent).toContain('Get help'); expect(textContent).toContain('Proton shop'); expect(textContent).toContain('Sign out'); }); it('should show upgrade button', async () => { const { getByText } = await setup(); const upgradeLabel = getByText('Upgrade'); assertAppLink(upgradeLabel, '/mail/dashboard'); }); it('should show upgrade button', async () => { const { getByText } = await setup(); const upgradeLabel = getByText('Upgrade'); assertAppLink(upgradeLabel, '/mail/dashboard'); }); }); describe('Search features', () => { it('should search with search bar', async () => { const searchTerm = 'test'; const { searchForm } = await setup(); const searchInput = searchForm.querySelector('input') as HTMLInputElement; fireEvent.change(searchInput, { target: { value: searchTerm } }); act(() => { fireEvent.submit(searchForm); }); expect(props.onSearch).toHaveBeenCalledWith(searchTerm, undefined); }); it('should search with keyword in advanced search', async () => { const searchTerm = 'test'; const { searchForm, openAdvanced, rerender } = await setup(); const { submit } = await openAdvanced(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/inbox'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); await rerender(<MailHeader {...props} />); const searchInput = searchForm.querySelector('input') as HTMLInputElement; expect(searchInput.value).toBe(searchTerm); }); it('should search with keyword and location', async () => { const searchTerm = 'test'; const { openAdvanced } = await setup(); const { submit } = await openAdvanced(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); const draftButton = screen.getByTestId(`location-${MAILBOX_LABEL_IDS.DRAFTS}`); fireEvent.click(draftButton); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/drafts'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); }); }); });
ProtonMail/WebClient
applications/mail/src/app/components/header/MailHeader.test.tsx
TypeScript
mit
7,113
package edu.cmu.hcii.whyline.analysis; import java.util.SortedSet; import java.util.TreeSet; import edu.cmu.hcii.whyline.bytecode.MethodInfo; import edu.cmu.hcii.whyline.source.JavaSourceFile; import edu.cmu.hcii.whyline.source.Line; import edu.cmu.hcii.whyline.source.Token; import edu.cmu.hcii.whyline.ui.WhylineUI; /** * @author Andrew J. Ko * */ public class FindOverriders implements SearchResultsInterface { private final MethodInfo method; private final WhylineUI whylineUI; private final SortedSet<Token> overriders = new TreeSet<Token>(); public FindOverriders(WhylineUI whylineUI, MethodInfo method) { this.whylineUI = whylineUI; this.method = method; for(MethodInfo m : method.getOverriders()) { JavaSourceFile source = m.getClassfile().getSourceFile(); if(source != null) { Line line = source.getTokenForMethodName(m).getLine(); overriders.addAll(line.getTokensAfterFirstNonWhitespaceToken()); } } } public String getResultsDescription() { return "overriders of " + method.getInternalName(); } public String getCurrentStatus() { return "Done."; } public SortedSet<Token> getResults() { return overriders; } public boolean isDone() { return true; } }
andyjko/whyline
edu/cmu/hcii/whyline/analysis/FindOverriders.java
Java
mit
1,239
var searchData= [ ['neighbours',['neighbours',['../struct_parser_1_1_cell_atom_grammar.html#a6367dce3041506f4112c82e2ba5998a9',1,'Parser::CellAtomGrammar']]], ['newgrid',['newGrid',['../struct_compiler_1_1_state.html#a3a949d5132b7854fee15d6d13344652c',1,'Compiler::State']]] ];
CompilerTeaching/CompilerTeaching.github.io
cellatom/doxygen/search/variables_b.js
JavaScript
mit
282
<?php /** * Whoops - php errors for cool kids * @author Filipe Dobreira <http://github.com/filp> */ namespace Whoops\Handler; use Whoops\Handler\HandlerInterface; use Whoops\Exception\Inspector; use Whoops\Run; use Exception; /** * Abstract implementation of a Handler. */ abstract class Handler implements HandlerInterface { /** * Return constants that can be returned from Handler::handle * to message the handler walker. */ const DONE = 0x10; // returning this is optional, only exists for // semantic purposes const LAST_HANDLER = 0x20; const QUIT = 0x30; /** * @var Run */ private $run; /** * @var Inspector $inspector */ private $inspector; /** * @var Exception $exception */ private $exception; /** * @param Run $run */ public function setRun(Run $run) { $this->run = $run; } /** * @return Run */ protected function getRun() { return $this->run; } /** * @param Inspector $inspector */ public function setInspector(Inspector $inspector) { $this->inspector = $inspector; } /** * @return Inspector */ protected function getInspector() { return $this->inspector; } /** * @param Exception $exception */ public function setException(Exception $exception) { $this->exception = $exception; } /** * @return Exception */ protected function getException() { return $this->exception; } }
wissamdagher/Temenos-T24-COB-Monitor
vendor/filp/whoops/src/Whoops/Handler/Handler.php
PHP
mit
1,572
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit1d7f3d8d9f8bff4ff374c7338c3d8879 { public static $files = array( 'ce89ade1b84217abfd74bd4c84863dc1' => __DIR__ . '/..' . '/nizarii/arma-rcon-class/arc.php', ); public static $prefixLengthsPsr4 = array( 'v' => array( 'voku\\db\\' => 8, 'voku\\cache\\' => 11, 'voku\\' => 5, ), 'P' => array( 'PageCache\\' => 10, ), ); public static $prefixDirsPsr4 = array( 'voku\\db\\' => array( 0 => __DIR__ . '/..' . '/voku/simple-mysqli/src/voku/db', ), 'voku\\cache\\' => array( 0 => __DIR__ . '/..' . '/voku/simple-cache/src/voku/cache', ), 'voku\\' => array( 0 => __DIR__ . '/..' . '/voku/portable-utf8/src/voku', ), 'PageCache\\' => array( 0 => __DIR__ . '/..' . '/mmamedov/page-cache/src', ), ); public static $classMap = array( 'Normalizer' => __DIR__ . '/..' . '/voku/portable-utf8/src/Normalizer.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit1d7f3d8d9f8bff4ff374c7338c3d8879::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit1d7f3d8d9f8bff4ff374c7338c3d8879::$prefixDirsPsr4; $loader->classMap = ComposerStaticInit1d7f3d8d9f8bff4ff374c7338c3d8879::$classMap; }, null, ClassLoader::class); } }
Itsmadhatter/Exile-Admin-Panel
vendor/composer/autoload_static.php
PHP
mit
1,768
#include <algorithm> #include <iterator> #include <vector> #include "ihanoi.hpp" #include "aim.hpp" // Algorithm to be tested template <int from, int other, int to> struct ApplyMapping { std::pair<std::size_t, std::size_t> operator()(std::pair<std::size_t, std::size_t> const& move) { static_assert(from != other && other != to && to != from, "Sticks must have different IDs"); static_assert(from == 0 || other == 0 || to == 0, "Stick #0 not found"); static_assert(from == 1 || other == 1 || to == 1, "Stick #1 not found"); static_assert(from == 2 || other == 2 || to == 2, "Stick #2 not found"); return std::make_pair(move.first == 0 ? from : (move.first == 1 ? other : to), move.second == 0 ? from : (move.second == 1 ? other : to)); } }; void hanoi(IHanoi& tower) { if (tower.height_of(0) == 0) { return; } const unsigned int height = tower.height_of(0); std::vector<std::pair<std::size_t, std::size_t>> moves; moves.reserve((1 << height) -1); // Solution contains 2 ^ height -1 moves at the end of the execution for (unsigned int i = 1 ; i != height+1 ; ++i) { // At the beginning of this iteration we have: // - moves: contains the list of moves necessary to move a HanoiTower of size (i-1) // from 0 to 2 (stick id) std::size_t size_previous = moves.size(); moves.push_back(std::make_pair(0, 2)); std::copy(moves.begin(), std::next(moves.begin(), size_previous), std::back_inserter(moves)); std::transform(moves.begin(), std::next(moves.begin(), size_previous), moves.begin(), ApplyMapping<0,2,1>()); // we move a tower of size (i-1) from stick #0 to stick #1 std::transform(std::next(moves.begin(), size_previous+1), moves.end(), std::next(moves.begin(), size_previous+1), ApplyMapping<1,0,2>()); // we move a tower of size (i-1) from stick #1 to stick #2 } for (auto const& move : moves) { tower.move(move.second, move.first); } }
dubzzz/various-algorithms
algorithms/recurse/hanoi-towers/implem_iterative_no_stack.cpp
C++
mit
1,956
package statsd import ( "context" "fmt" "hash/adler32" "sync" "github.com/ash2k/stager/wait" "github.com/atlassian/gostatsd" "github.com/atlassian/gostatsd/pkg/statser" ) // AggregatorFactory creates Aggregator objects. type AggregatorFactory interface { // Create creates Aggregator objects. Create() Aggregator } // AggregatorFactoryFunc type is an adapter to allow the use of ordinary functions as AggregatorFactory. type AggregatorFactoryFunc func() Aggregator // Create calls f(). func (f AggregatorFactoryFunc) Create() Aggregator { return f() } // MetricDispatcher dispatches incoming metrics to corresponding aggregators. type MetricDispatcher struct { numWorkers int workers map[uint16]*worker } // NewMetricDispatcher creates a new NewMetricDispatcher with provided configuration. func NewMetricDispatcher(numWorkers int, perWorkerBufferSize int, af AggregatorFactory) *MetricDispatcher { workers := make(map[uint16]*worker, numWorkers) n := uint16(numWorkers) for i := uint16(0); i < n; i++ { workers[i] = &worker{ aggr: af.Create(), metricsQueue: make(chan *gostatsd.Metric, perWorkerBufferSize), processChan: make(chan *processCommand), id: i, } } return &MetricDispatcher{ numWorkers: numWorkers, workers: workers, } } // Run runs the MetricDispatcher. func (d *MetricDispatcher) Run(ctx context.Context) { var wg wait.Group defer func() { for _, worker := range d.workers { close(worker.metricsQueue) // Close channel to terminate worker } wg.Wait() // Wait for all workers to finish }() for _, worker := range d.workers { wg.Start(worker.work) } // Work until asked to stop <-ctx.Done() } func (d *MetricDispatcher) RunMetrics(ctx context.Context, statser statser.Statser) { var wg wait.Group defer wg.Wait() for _, worker := range d.workers { worker := worker wg.Start(func() { worker.runMetrics(ctx, statser) }) } d.Process(ctx, func(aggrId uint16, aggr Aggregator) { tag := fmt.Sprintf("aggregator_id:%d", aggrId) aggr.TrackMetrics(statser.WithTags(gostatsd.Tags{tag})) }) } // DispatchMetric dispatches metric to a corresponding Aggregator. func (d *MetricDispatcher) DispatchMetric(ctx context.Context, m *gostatsd.Metric) error { hash := adler32.Checksum([]byte(m.Name)) w := d.workers[uint16(hash%uint32(d.numWorkers))] select { case <-ctx.Done(): return ctx.Err() case w.metricsQueue <- m: return nil } } // Process concurrently executes provided function in goroutines that own Aggregators. // DispatcherProcessFunc function may be executed zero or up to numWorkers times. It is executed // less than numWorkers times if the context signals "done". func (d *MetricDispatcher) Process(ctx context.Context, f DispatcherProcessFunc) gostatsd.Wait { var wg sync.WaitGroup cmd := &processCommand{ f: f, done: wg.Done, } wg.Add(d.numWorkers) cmdSent := 0 loop: for _, worker := range d.workers { select { case <-ctx.Done(): wg.Add(cmdSent - d.numWorkers) // Not all commands have been sent, should decrement the WG counter. break loop case worker.processChan <- cmd: cmdSent++ } } return wg.Wait }
tiedotguy/gostatsd
pkg/statsd/dispatcher.go
GO
mit
3,174
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('my app', function() { beforeEach(function() { browser().navigateTo('app/index-old.html'); }); it('should automatically redirect to /view1 when location hash/fragment is empty', function() { expect(browser().location().url()).toBe("/view1"); }); describe('view1', function() { beforeEach(function() { browser().navigateTo('#/view1'); }); it('should render view1 when user navigates to /view1', function() { expect(element('[ng-view] p:first').text()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser().navigateTo('#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element('[ng-view] p:first').text()). toMatch(/partial for view 2/); }); }); });
egorps/run-caoch
test/e2e/scenarios.js
JavaScript
mit
936
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace YanZhiwei.DotNet2.Utilities.WebFormExamples { public partial class FileDownHelperDemo { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// Button1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; /// <summary> /// Button2 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button Button2; } }
YanZhiwei/DotNet.Utilities
YanZhiwei.DotNet2.Utilities.WebFormExamples/FileDownHelperDemo.aspx.designer.cs
C#
mit
1,477
export default from './Input';
natac13/Markdown-Previewer-React
app/components/Input/index.js
JavaScript
mit
30
package org.vitanov.container; public class ContainerConstants { public static String CONTAINER_ROOT_PATH = System.getProperty("user.dir"); }
StoyanVitanov/SoftwareUniversity
Java Web/Web Fundamentals/05.Handmade Web Server/servlet-containers/static-container/src/org/vitanov/container/ContainerConstants.java
Java
mit
161
module Cryptoexchange::Exchanges module Bit2c module Services class Pairs < Cryptoexchange::Services::Pairs def fetch output = super market_pairs = [] output.each do |pair| market_pairs << Cryptoexchange::Models::MarketPair.new( base: pair[:base], target: pair[:target], market: Bit2c::Market::NAME ) end market_pairs end end end end end
coingecko/cryptoexchange
lib/cryptoexchange/exchanges/bit2c/services/pairs.rb
Ruby
mit
559
/* Generated code */ interface SyncInfo { syncType?: 'FSync' | 'ISync'; syncToken?: string; syncTime?: string; olderRecordsExist?: boolean; } export default SyncInfo;
zengfenfei/ringcentral-ts
src/definitions/SyncInfo.ts
TypeScript
mit
177
app.router = Backbone.Router.extend({ el : $('main'), routes: { // '': 'home', // '!/': 'home', '!/event-list/': function () { app.preRoute('event-list', this.el); new app.eventListView({ el: this.el }); }, '!/event-detail/:key': function (key) { app.preRoute('event-detail', this.el); new app.eventDetailView({ el: this.el, key: key }); }, '!/event-create/': function () { app.preRoute('event-create', this.el); new app.eventCreateView({ el: this.el }); }, '!/account/': function () { app.preRoute('account', this.el); new app.accountView({ el: this.el }); }, }, initialize: function () { firebase.auth().onAuthStateChanged(function(user) { if (user) { Backbone.history.start(); new app.headerView(); new app.footerView(); // TODO: hook up email verification // if (!user.emailVerified) // firebase.auth().currentUser.sendEmailVerification() var database = firebase.database(); var currentUser = firebase.auth().currentUser; // add user to database of users // TODO: show add photo wizard if no photo database.ref('users/' + currentUser.uid).update({ email: currentUser.email, displayName: currentUser.displayName, }); } else { window.location = '/'; } }, function(error) { console.error(error); }); }, // home: function () { // app.preRoute(this.el); // new app.homeView({ el: this.el }); // }, }); $(function () { app.router = new app.router(); });
nblenke/buzz-proto
public/assets/js/router.js
JavaScript
mit
1,903
"use strict"; const mongoose = require('mongoose'); module.exports = (()=>{ mongoose.connect('mongodb://192.168.56.101:30000/blog'); let db = mongoose.connection; db.on('error', function(err){ console.log(err); }); db.once('open', (err)=> { console.log('connect success'); }) })();
fsy0718/study
node/express/blog/api/db.js
JavaScript
mit
293
<?php /** * @name Upload Module * @author Philipp Maurer * @author Tobias Reich * @copyright 2014 by Philipp Maurer, Tobias Reich */ if (!defined('LYCHEE')) exit('Error: Direct access is not allowed!'); function upload($files, $albumID) { global $database, $settings; switch($albumID) { // s for public (share) case 's': $public = 1; $star = 0; $albumID = 0; break; // f for starred (fav) case 'f': $star = 1; $public = 0; $albumID = 0; break; default: $star = 0; $public = 0; } foreach ($files as $file) { if ($file['type']!=='image/jpeg'&& $file['type']!=='image/png'&& $file['type']!=='image/gif') return false; $id = str_replace('.', '', microtime(true)); while(strlen($id)<14) $id .= 0; $tmp_name = $file['tmp_name']; $extension = array_reverse(explode('.', $file['name'])); $extension = $extension[0]; $photo_name = md5($id) . ".$extension"; // Import if not uploaded via web if (!is_uploaded_file($tmp_name)) { if (copy($tmp_name, '../uploads/big/' . $photo_name)) { @unlink($tmp_name); $import_name = $tmp_name; } } else { move_uploaded_file($tmp_name, '../uploads/big/' . $photo_name); $import_name = ''; } // Read infos $info = getInfo($photo_name); // Use title of file if IPTC title missing if ($info['title']==='') $info['title'] = mysqli_real_escape_string($database, substr(basename($file['name'], ".$extension"), 0, 30)); // Set orientation based on EXIF data if ($file['type']==='image/jpeg'&&isset($info['orientation'])&&isset($info['width'])&&isset($info['height'])) { if ($info['orientation']==3||$info['orientation']==6||$info['orientation']==8) { $newWidth = $info['width']; $newHeight = $info['height']; $sourceImg = imagecreatefromjpeg("../uploads/big/$photo_name"); switch($info['orientation']){ case 2: // mirror // not yet implemented break; case 3: $sourceImg = imagerotate($sourceImg, -180, 0); break; case 4: // rotate 180 and mirror // not yet implemented break; case 5: // rotate 90 and mirror // not yet implemented break; case 6: $sourceImg = imagerotate($sourceImg, -90, 0); $newWidth = $info['height']; $newHeight = $info['width']; break; case 7: // rotate -90 and mirror // not yet implemented break; case 8: $sourceImg = imagerotate($sourceImg, 90, 0); $newWidth = $info['height']; $newHeight = $info['width']; break; } $newSourceImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight); imagejpeg($newSourceImg, "../uploads/big/$photo_name", 100); } } // Create Thumb if (!createThumb($photo_name)) return false; // Save to DB $query = "INSERT INTO lychee_photos (id, title, url, description, type, width, height, size, sysdate, systime, iso, aperture, make, model, shutter, focal, takedate, taketime, thumbUrl, album, public, star, import_name) VALUES ( '" . $id . "', '" . $info['title'] . "', '" . $photo_name . "', '" . $info['description'] . "', '" . $info['type'] . "', '" . $info['width'] . "', '" . $info['height'] . "', '" . $info['size'] . "', '" . $info['date'] . "', '" . $info['time'] . "', '" . $info['iso'] . "', '" . $info['aperture'] . "', '" . $info['make'] . "', '" . $info['model'] . "', '" . $info['shutter'] . "', '" . $info['focal'] . "', '" . $info['takeDate'] . "', '" . $info['takeTime'] . "', '" . md5($id) . ".jpeg', '" . $albumID . "', '" . $public . "', '" . $star . "', '" . $import_name . "');"; $result = $database->query($query); if (!$result) return false; } return true; } function getInfo($filename) { global $database; $url = '../uploads/big/' . $filename; $iptcArray = array(); $info = getimagesize($url, $iptcArray); // General information $return['type'] = $info['mime']; $return['width'] = $info[0]; $return['height'] = $info[1]; $return['date'] = date('d.m.Y', filectime($url)); $return['time'] = date('H:i:s', filectime($url)); // Size $size = filesize($url)/1024; if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB'; else $return['size'] = round($size, 1) . ' KB'; // IPTC Metadata Fallback $return['title'] = ''; $return['description'] = ''; // IPTC Metadata if(isset($iptcArray['APP13'])) { $iptcInfo = iptcparse($iptcArray['APP13']); if (is_array($iptcInfo)) { $temp = @$iptcInfo['2#105'][0]; if (isset($temp)&&strlen($temp)>0) $return['title'] = $temp; $temp = @$iptcInfo['2#120'][0]; if (isset($temp)&&strlen($temp)>0) $return['description'] = $temp; } } // EXIF Metadata Fallback $return['orientation'] = ''; $return['iso'] = ''; $return['aperture'] = ''; $return['make'] = ''; $return['model'] = ''; $return['shutter'] = ''; $return['focal'] = ''; $return['takeDate'] = ''; $return['takeTime'] = ''; // Read EXIF if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', 0); else $exif = false; // EXIF Metadata if ($exif!==false) { $temp = @$exif['Orientation']; if (isset($temp)) $return['orientation'] = $temp; $temp = @$exif['ISOSpeedRatings']; if (isset($temp)) $return['iso'] = $temp; $temp = @$exif['COMPUTED']['ApertureFNumber']; if (isset($temp)) $return['aperture'] = $temp; $temp = @$exif['Make']; if (isset($temp)) $return['make'] = $exif['Make']; $temp = @$exif['Model']; if (isset($temp)) $return['model'] = $temp; $temp = @$exif['ExposureTime']; if (isset($temp)) $return['shutter'] = $exif['ExposureTime'] . ' Sec.'; $temp = @$exif['FocalLength']; if (isset($temp)) $return['focal'] = ($temp/1) . ' mm'; $temp = @$exif['DateTimeOriginal']; if (isset($temp)) { $exifDate = explode(' ', $temp); $date = explode(':', $exifDate[0]); $return['takeDate'] = $date[2].'.'.$date[1].'.'.$date[0]; $return['takeTime'] = $exifDate[1]; } } // Security foreach(array_keys($return) as $key) $return[$key] = mysqli_real_escape_string($database, $return[$key]); return $return; } function createThumb($filename, $width = 200, $height = 200) { global $settings; $url = "../uploads/big/$filename"; $info = getimagesize($url); $photoName = explode(".", $filename); $newUrl = "../uploads/thumb/$photoName[0].jpeg"; $newUrl2x = "../uploads/thumb/$photoName[0]@2x.jpeg"; // Set position and size $thumb = imagecreatetruecolor($width, $height); $thumb2x = imagecreatetruecolor($width*2, $height*2); if ($info[0]<$info[1]) { $newSize = $info[0]; $startWidth = 0; $startHeight = $info[1]/2 - $info[0]/2; } else { $newSize = $info[1]; $startWidth = $info[0]/2 - $info[1]/2; $startHeight = 0; } // Fallback for older version if ($info['mime']==='image/webp'&&floatval(phpversion())<5.5) return false; // Create new image switch($info['mime']) { case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break; case 'image/png': $sourceImg = imagecreatefrompng($url); break; case 'image/gif': $sourceImg = imagecreatefromgif($url); break; case 'image/webp': $sourceImg = imagecreatefromwebp($url); break; default: return false; } imagecopyresampled($thumb,$sourceImg,0,0,$startWidth,$startHeight,$width,$height,$newSize,$newSize); imagecopyresampled($thumb2x,$sourceImg,0,0,$startWidth,$startHeight,$width*2,$height*2,$newSize,$newSize); imagejpeg($thumb,$newUrl,$settings['thumbQuality']); imagejpeg($thumb2x,$newUrl2x,$settings['thumbQuality']); return true; } function importPhoto($path, $albumID = 0) { $info = getimagesize($path); $size = filesize($path); $nameFile = array(array()); $nameFile[0]['name'] = $path; $nameFile[0]['type'] = $info['mime']; $nameFile[0]['tmp_name'] = $path; $nameFile[0]['error'] = 0; $nameFile[0]['size'] = $size; return upload($nameFile, $albumID); } function importUrl($url, $albumID = 0) { if (strpos($url, ',')!==false) { // Multiple photos $url = explode(',', $url); foreach ($url as &$key) { $key = str_replace(' ', '%20', $key); if (@getimagesize($key)) { $pathinfo = pathinfo($key); $filename = $pathinfo['filename'].".".$pathinfo['extension']; $tmp_name = "../uploads/import/$filename"; copy($key, $tmp_name); } } return importServer($albumID); } else { // One photo $url = str_replace(' ', '%20', $url); if (@getimagesize($url)) { $pathinfo = pathinfo($url); $filename = $pathinfo['filename'].".".$pathinfo['extension']; $tmp_name = "../uploads/import/$filename"; copy($url, $tmp_name); return importPhoto($tmp_name, $albumID); } } return false; } function importServer($albumID = 0, $path = '../uploads/import/') { global $database; $files = glob($path . '*'); $contains['photos'] = false; $contains['albums'] = false; foreach ($files as $file) { if (@getimagesize($file)) { // Photo if (!importPhoto($file, $albumID)) return false; $contains['photos'] = true; } else if (is_dir($file)) { $name = mysqli_real_escape_string($database, basename($file)); $newAlbumID = addAlbum('[Import] ' . $name); if ($newAlbumID!==false) importServer($newAlbumID, $file . '/'); $contains['albums'] = true; } } if ($contains['photos']===false&&$contains['albums']===false) return "Warning: Folder empty!"; if ($contains['photos']===false&&$contains['albums']===true) return "Notice: Import only contains albums!"; return true; } ?>
massyas/lychee_ynh
source/php/modules/upload.php
PHP
mit
9,705
<?php namespace Illumine\Framework\Traits; use Illuminate\Bus\Dispatcher; trait DispatchesJobs { /** * Dispatch a job to its appropriate handler. * * @param mixed $job * @return mixed */ protected function dispatch($job) { return $this->plugin->make(Dispatcher::class)->dispatch($job); } /** * Dispatch a command to its appropriate handler in the current process. * * @param mixed $job * @return mixed */ public function dispatchNow($job) { return $this->plugin->make(Dispatcher::class)->dispatchNow($job); } }
bayareawebpro/illumine-framework
Traits/DispatchesJobs.php
PHP
mit
613
import pl.edu.agh.amber.common.AmberClient; import pl.edu.agh.amber.drivetopoint.DriveToPointProxy; import pl.edu.agh.amber.drivetopoint.Location; import pl.edu.agh.amber.drivetopoint.Point; import pl.edu.agh.amber.drivetopoint.Result; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Drive to point proxy example. * * @author Pawel Suder <pawel@suder.info> */ public class DriveToPointExample { public static void main(String[] args) { (new DriveToPointExample()).runDemo(); } public void runDemo() { Scanner keyboard = new Scanner(System.in); System.out.print("IP (default: 127.0.0.1): "); String hostname = keyboard.nextLine(); if ("".equals(hostname)) { hostname = "127.0.0.1"; } AmberClient client; try { client = new AmberClient(hostname, 26233); } catch (IOException e) { System.out.println("Unable to connect to robot: " + e); return; } DriveToPointProxy driveToPointProxy = new DriveToPointProxy(client, 0); try { List<Point> targets = Arrays.asList( new Point(2.44725, 4.22125, 0.25), new Point(1.46706, 4.14285, 0.25), new Point(0.67389, 3.76964, 0.25), new Point(0.47339, 2.96781, 0.25)); driveToPointProxy.setTargets(targets); while (true) { Result<List<Point>> resultNextTargets = driveToPointProxy.getNextTargets(); Result<List<Point>> resultVisitedTargets = driveToPointProxy.getVisitedTargets(); List<Point> nextTargets = resultNextTargets.getResult(); List<Point> visitedTargets = resultVisitedTargets.getResult(); System.out.println(String.format("next targets: %s, visited targets: %s", nextTargets.toString(), visitedTargets.toString())); Thread.sleep(1000); } } catch (IOException e) { System.out.println("Error in sending a command: " + e); } catch (Exception e) { e.printStackTrace(); } finally { client.terminate(); } } }
project-capo/amber-java-clients
amber-java-examples/src/main/java/DriveToPointExample.java
Java
mit
2,273
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using ZyGames.Framework.Game.Service; using ZyGames.Tianjiexing.BLL.Base; using ZyGames.Tianjiexing.Lang; using ZyGames.Tianjiexing.Model; using ZyGames.Tianjiexing.BLL.Combat; namespace ZyGames.Tianjiexing.BLL.Action { /// <summary> /// 4206_加入队伍接口 /// </summary> public class Action4206 : BaseAction { private int teamID = 0; private int ops = 0; private FunctionEnum funEnum; public Action4206(ZyGames.Framework.Game.Contract.HttpGet httpGet) : base(ActionIDDefine.Cst_Action4206, httpGet) { } public override void BuildPacket() { PushIntoStack(teamID); } public override bool GetUrlElement() { if (httpGet.GetInt("Ops", ref ops) && httpGet.GetEnum("FunEnum", ref funEnum)) { httpGet.GetInt("TeamID", ref teamID); return true; } return false; } public override bool TakeAction() { if (!PlotTeamCombat.IsMorePlotDate(ContextUser.UserID, funEnum)) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St4202_OutMorePlotDate; return false; } if (UserHelper.IsBeiBaoFull(ContextUser)) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St1107_GridNumFull; return false; } var plotTeam = new PlotTeamCombat(ContextUser); var team = plotTeam.GetTeam(teamID); if (team != null) { if (team.Status == 2) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St4206_TeamPlotStart; return false; } if (team.Status == 3) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St4206_TeamPlotLead; return false; } } if (ops == 1) { plotTeam.AddTeam(teamID); } else if (ops == 2) { if (funEnum == FunctionEnum.Multiplot) { plotTeam.AddTeam(out teamID); } else { plotTeam.AddMoreTeam(out teamID); } if (teamID == -1) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St4206_NoTeam; return false; } } return true; } } }
wenhulove333/ScutServer
Sample/Koudai/Server/src/ZyGames.Tianjiexing.BLL/Action/Action4206.cs
C#
mit
4,309
package daemon import ( "log" "time" "github.com/Cloakaac/cloak/models" ) type RecordDaemon struct{} func (r *RecordDaemon) tick() { total := models.GetOnlineCount() err := models.AddOnlineRecord(total, time.Now().Unix()) if err != nil { log.Fatal(err) } }
Cloakaac/cloak
daemon/record.go
GO
mit
270
from django.dispatch import Signal user_email_bounced = Signal() # args: ['bounce', 'should_deactivate'] email_bounced = Signal() # args: ['bounce', 'should_deactivate'] email_unsubscribed = Signal() # args: ['email', 'reference']
fin/froide
froide/bounce/signals.py
Python
mit
236
<?php declare(strict_types = 1); namespace PHPStan\Rules\Comparison; use PHPStan\Type\Constant\ConstantBooleanType; class BooleanOrConstantConditionRule implements \PHPStan\Rules\Rule { public function getNodeType(): string { return \PhpParser\Node\Expr\BinaryOp\BooleanOr::class; } /** * @param \PhpParser\Node\Expr\BinaryOp\BooleanOr $node * @param \PHPStan\Analyser\Scope $scope * @return string[] */ public function processNode( \PhpParser\Node $node, \PHPStan\Analyser\Scope $scope ): array { $messages = []; $leftType = ConstantConditionRuleHelper::getBooleanType($scope, $node->left); if ($leftType instanceof ConstantBooleanType) { $messages[] = sprintf( 'Left side of || is always %s.', $leftType->getValue() ? 'true' : 'false' ); } $rightType = ConstantConditionRuleHelper::getBooleanType( $scope->filterByFalseyValue($node->left), $node->right ); if ($rightType instanceof ConstantBooleanType) { $messages[] = sprintf( 'Right side of || is always %s.', $rightType->getValue() ? 'true' : 'false' ); } return $messages; } }
rquadling/phpstan
src/Rules/Comparison/BooleanOrConstantConditionRule.php
PHP
mit
1,115
<html> <head> <title> Keep fighting for justice! </title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <?php include "../../legacy-includes/Script.htmlf" ?> </head> <body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0"> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td> <td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?> </td></tr></table> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="18" bgcolor="FFCC66"></td> <td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td> <td width="18"></td> <td width="480" valign="top"> <?php include "../../legacy-includes/BodyInsert.htmlf" ?> <P><font face="Times New Roman, Times, serif" size="4">Kenny Collins taken off of death row in Maryland</font><br> <font face="Times New Roman, Times, serif" size="5"><b>Keep fighting for justice!</b></font></P> <p><font face="Arial, Helvetica, sans-serif" size="2">February 27, 2004 | Page 4</font></P> <B><P><font face="Times New Roman, Times, serif" size="3">Dear <I>Socialist Worker,</I></B><BR> On February 5, Somerset County Judge Daniel Long removed Maryland inmate Kenny Collins from death row because his original trial lawyer failed to represent him adequately during the sentencing phase of his 1988 trial. This dramatic reversal, in effect an admission that Kenny has spent that last 16 years under an illegal death sentence, is a blow to Maryland's death penalty system and a victory for activists and attorneys who have been fighting to prove Kenny's innocence.</P> <P>Far from having a change of heart, the judge's hand was forced after the U.S. Supreme Court overturned the death sentence of Maryland death row inmate Kevin Wiggins. In both Wiggins' and Collins' cases, their trial attorneys failed to conduct an investigation, prepare arguments or call witnesses on their clients' behalf during the sentencing phase of trial.</P> <P>In the past, Maryland courts have ignored such outrages if the trial attorneys claimed these failures were part of some deliberate strategy. However, in Wiggins' case, the U.S. Supreme Court pointed out that strategic legal decisions only occur when attorneys know the facts&#151;not when they don't bother to investigate them.</P> <P>The fight for justice in Kenny's case is far from over. Kenny has steadfastly maintained his innocence. Convicted without eyewitnesses, physical evidence or a confession, the case against Kenny rests on the testimony of the man originally arrested for the crime, Tony Michie, and his cousin, Andre Thorpe. Two years ago, in the aftermath of the successful effort to take Eugene Colvin-El off death row, Thorpe came forward to admit in a taped interview that he had lied at trial to protect his cousin. </P> <P>Despite this dramatic new evidence, Judge Long denied Kenny's request for a new trial&#151;and instead, after removing the death sentence, re-sentenced Kenny to life in prison. This is an outrage&#151;an attempt to silence an innocent man. Kenny and his supporters have pledged to continue the fight for justice. Free Kenny Collins!<br> <B>Mike Stark</B>, Washington, D.C.</P> <?php include "../../legacy-includes/BottomNavLinks.htmlf" ?> <td width="12"></td> <td width="108" valign="top"> <?php include "../../legacy-includes/RightAdFolder.htmlf" ?> </td> </tr> </table> </body> </html>
ISO-tech/sw-d8
web/2004-1/488/488_04_KennyCollins.php
PHP
mit
3,573
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Batch Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Batch Management APIs.")] [assembly: AssemblyVersion("1.0.0.60")] [assembly: AssemblyFileVersion("1.18.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
hovsepm/azure-libraries-for-net
src/ResourceManagement/Batch/Properties/AssemblyInfo.cs
C#
mit
804
// member.cs // // Copyright 2010 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; namespace Microsoft.Ajax.Utilities { public sealed class Member : Expression { private AstNode m_root; public AstNode Root { get { return m_root; } set { ReplaceNode(ref m_root, value); } } public string Name { get; set; } public Context NameContext { get; set; } public Member(Context context) : base(context) { } public override OperatorPrecedence Precedence { get { return OperatorPrecedence.FieldAccess; } } public override void Accept(IVisitor visitor) { if (visitor != null) { visitor.Visit(this); } } public override bool IsEquivalentTo(AstNode otherNode) { var otherMember = otherNode as Member; return otherMember != null && string.CompareOrdinal(this.Name, otherMember.Name) == 0 && this.Root.IsEquivalentTo(otherMember.Root); } internal override string GetFunctionGuess(AstNode target) { return Root.GetFunctionGuess(this) + '.' + Name; } public override IEnumerable<AstNode> Children { get { return EnumerateNonNullNodes(Root); } } public override bool ReplaceChild(AstNode oldNode, AstNode newNode) { if (Root == oldNode) { Root = newNode; return true; } return false; } public override AstNode LeftHandSide { get { // the root object is on the left return Root.LeftHandSide; } } } }
afisd/jovice
Aphysoft.Share/External/AjaxMin/JavaScript/member.cs
C#
mit
2,558
<?php /** * TableBlock.php * * @since 31/05/15 * @author gseidel */ namespace Enhavo\Bundle\AppBundle\Block\Block; use Enhavo\Bundle\AppBundle\Block\BlockInterface; use Enhavo\Bundle\AppBundle\Type\AbstractType; class TableBlock extends AbstractType implements BlockInterface { public function render($parameters) { $translationDomain = $this->getOption('translationDomain', $parameters, null); $tableRoute = $this->getRequiredOption('table_route', $parameters); if(!isset($parameters['filters'])) { $filters = $this->getFiltersFromRoute($tableRoute, $translationDomain); } else { $filters = $this->getFilters($this->getOption('filters', $parameters, []), $translationDomain); } return $this->renderTemplate('EnhavoAppBundle:Block:table.html.twig', [ 'app' => $this->getOption('app', $parameters, 'app/Block/Table'), 'table_route' => $tableRoute, 'table_route_parameters' => $this->getOption('table_route_parameters', $parameters, null), 'update_route_parameters' => $this->getOption('update_route_parameters', $parameters, null), 'update_route' => $this->getOption('update_route', $parameters, null), 'translationDomain' => $translationDomain, 'filters' => $this->convertToFilterRows($filters), 'filterRowSize' => $this->calcFilterRowSize($filters) ]); } protected function getFiltersFromRoute($route, $translationDomain) { $route = $this->container->get('router')->getRouteCollection()->get($route); $sylius = $route->getDefault('_sylius'); if(is_array($sylius)&& isset($sylius['filters'])) { return $this->getFilters($sylius['filters'], $translationDomain); } return []; } protected function calcFilterRowSize($filters) { $amount = count($filters); if($amount == 1) { return 12; } if($amount == 2) { return 6; } if($amount == 3) { return 4; } return 3; } protected function convertToFilterRows($filters) { $rows = []; $i = 0; $index = 0; foreach($filters as $filter) { if($i === 0) { $rows[$index] = []; } $rows[$index][] = $filter; if($i == 3) { $i = 0; $index++; } else { $i++; } } return $rows; } protected function getFilters(array $filters, $translationDomain = null) { foreach($filters as $name => &$options) { $options['value'] = ''; $options['name'] = $name; } foreach($filters as $name => &$options) { if(!array_key_exists('translationDomain', $options)) { $options['translationDomain'] = $translationDomain; } } return $filters; } public function getType() { return 'table'; } }
kiwibun/enhavo
src/Enhavo/Bundle/AppBundle/Block/Block/TableBlock.php
PHP
mit
3,107
// package main provides an implementation of netcat using the secio package. // This means the channel is encrypted (and MACed). // It is meant to exercise the spipe package. // Usage: // seccat [<local address>] <remote address> // seccat -l <local address> // // Address format is: [host]:port package main import ( "context" "errors" "flag" "fmt" "io" "net" "os" "os/signal" "syscall" pstore "gx/ipfs/QmPgDWmTmuzvP7QE5zwo1TmjbJme9pmZHNujB2453jkCTr/go-libp2p-peerstore" logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log" peer "gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer" ci "gx/ipfs/QmaPbCnUMBohSGo3KnxEa2bHqyJVVeEEcwtqJAYxerieBo/go-libp2p-crypto" secio "gx/ipfs/QmbSkjJvDuxaZYtR46sF9ust7XY1hcg7DrA6Mxu4UiSWqs/go-libp2p-secio" ) var verbose = false // Usage prints out the usage of this module. // Assumes flags use go stdlib flag pacakage. var Usage = func() { text := `seccat - secure netcat in Go Usage: listen: %s [<local address>] <remote address> dial: %s -l <local address> Address format is Go's: [host]:port ` fmt.Fprintf(os.Stderr, text, os.Args[0], os.Args[0]) flag.PrintDefaults() } type args struct { listen bool verbose bool debug bool localAddr string remoteAddr string // keyfile string keybits int } func parseArgs() args { var a args // setup + parse flags flag.BoolVar(&a.listen, "listen", false, "listen for connections") flag.BoolVar(&a.listen, "l", false, "listen for connections (short)") flag.BoolVar(&a.verbose, "v", true, "verbose") flag.BoolVar(&a.debug, "debug", false, "debugging") // flag.StringVar(&a.keyfile, "key", "", "private key file") flag.IntVar(&a.keybits, "keybits", 2048, "num bits for generating private key") flag.Usage = Usage flag.Parse() osArgs := flag.Args() if len(osArgs) < 1 { exit("") } if a.verbose { out("verbose on") } if a.listen { a.localAddr = osArgs[0] } else { if len(osArgs) > 1 { a.localAddr = osArgs[0] a.remoteAddr = osArgs[1] } else { a.remoteAddr = osArgs[0] } } return a } func main() { args := parseArgs() verbose = args.verbose if args.debug { logging.SetDebugLogging() } go func() { // wait until we exit. sigc := make(chan os.Signal, 1) signal.Notify(sigc, syscall.SIGABRT) <-sigc panic("ABORT! ABORT! ABORT!") }() if err := connect(args); err != nil { exit("%s", err) } } func setupPeer(a args) (peer.ID, pstore.Peerstore, error) { if a.keybits < 1024 { return "", nil, errors.New("Bitsize less than 1024 is considered unsafe.") } out("generating key pair...") sk, pk, err := ci.GenerateKeyPair(ci.RSA, a.keybits) if err != nil { return "", nil, err } p, err := peer.IDFromPublicKey(pk) if err != nil { return "", nil, err } ps := pstore.NewPeerstore() ps.AddPrivKey(p, sk) ps.AddPubKey(p, pk) out("local peer id: %s", p) return p, ps, nil } func connect(args args) error { p, ps, err := setupPeer(args) if err != nil { return err } var conn net.Conn if args.listen { conn, err = Listen(args.localAddr) } else { conn, err = Dial(args.localAddr, args.remoteAddr) } if err != nil { return err } // log everything that goes through conn rwc := &logRW{n: "conn", rw: conn} // OK, let's setup the channel. sk := ps.PrivKey(p) sg := secio.SessionGenerator{LocalID: p, PrivateKey: sk} sess, err := sg.NewSession(context.TODO(), rwc) if err != nil { return err } out("remote peer id: %s", sess.RemotePeer()) netcat(sess.ReadWriter().(io.ReadWriteCloser)) return nil } // Listen listens and accepts one incoming UDT connection on a given port, // and pipes all incoming data to os.Stdout. func Listen(localAddr string) (net.Conn, error) { l, err := net.Listen("tcp", localAddr) if err != nil { return nil, err } out("listening at %s", l.Addr()) c, err := l.Accept() if err != nil { return nil, err } out("accepted connection from %s", c.RemoteAddr()) // done with listener l.Close() return c, nil } // Dial connects to a remote address and pipes all os.Stdin to the remote end. // If localAddr is set, uses it to Dial from. func Dial(localAddr, remoteAddr string) (net.Conn, error) { var laddr net.Addr var err error if localAddr != "" { laddr, err = net.ResolveTCPAddr("tcp", localAddr) if err != nil { return nil, fmt.Errorf("failed to resolve address %s", localAddr) } } if laddr != nil { out("dialing %s from %s", remoteAddr, laddr) } else { out("dialing %s", remoteAddr) } d := net.Dialer{LocalAddr: laddr} c, err := d.Dial("tcp", remoteAddr) if err != nil { return nil, err } out("connected to %s", c.RemoteAddr()) return c, nil } func netcat(c io.ReadWriteCloser) { out("piping stdio to connection") done := make(chan struct{}, 2) go func() { n, _ := io.Copy(c, os.Stdin) out("sent %d bytes", n) done <- struct{}{} }() go func() { n, _ := io.Copy(os.Stdout, c) out("received %d bytes", n) done <- struct{}{} }() // wait until we exit. sigc := make(chan os.Signal, 1) signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) select { case <-done: case <-sigc: return } c.Close() }
kyledrake/go-ipfs
cmd/seccat/seccat.go
GO
mit
5,208
// f is not called via a go function, instead the go function is inside the body of f. package main func main() { x := "Hello World" ch := make(chan string) f(ch) // @expectedflow: false sink(x) x = source() ch <- x } func f(ch chan string) { // *ssa.MakeClosure go func() { y := <-ch // @expectedflow: true sink(y) }() } func sink(s string) { } func source() string { return "secret" }
akwick/gotcha
tests/exampleCode/chanPaper2.go
GO
mit
408
a = [int(i) for i in input().split()] print(sum(a))
maisilex/Lets-Begin-Python
list.py
Python
mit
52
<?php /* WebProfilerBundle:Collector:memory.html.twig */ class __TwigTemplate_ccb1a70d7cfd163aa51619d0fc404c67 extends Twig_Template { protected $parent; public function __construct(Twig_Environment $env) { parent::__construct($env); $this->blocks = array( 'toolbar' => array($this, 'block_toolbar'), ); } public function getParent(array $context) { if (null === $this->parent) { $this->parent = $this->env->loadTemplate("WebProfilerBundle:Profiler:layout.html.twig"); } return $this->parent; } protected function doDisplay(array $context, array $blocks = array()) { $context = array_merge($this->env->getGlobals(), $context); $this->getParent($context)->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_toolbar($context, array $blocks = array()) { // line 4 echo " "; ob_start(); // line 5 echo " <img width=\"13\" height=\"28\" alt=\"Memory Usage\" style=\"vertical-align: middle; margin-right: 5px;\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAcCAYAAAC6YTVCAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJBJREFUeNpi/P//PwOpgImBDDAcNbE4ODiAg+/AgQOC586d+4BLoZGRkQBQ7Xt0mxQIWKCAzXkCBDQJDEBAIHOKiooicSkEBtTz0WQ0xFI5Mqevr285HrUOMAajvb09ySULk5+f3w1SNIDUMwKLsAIg256IrAECoEx6EKQJlLkkgJiDCE0/gPgF4+AuLAECDAAolCeEmdURAgAAAABJRU5ErkJggg==\"/> "; $context['icon'] = new Twig_Markup(ob_get_clean()); // line 7 echo " "; ob_start(); // line 8 echo " "; echo twig_escape_filter($this->env, sprintf("%.0f", ($this->getAttribute($this->getContext($context, 'collector'), "memory", array(), "any", false) / 1024)), "html"); echo " KB "; $context['text'] = new Twig_Markup(ob_get_clean()); // line 10 echo " "; $this->env->loadTemplate("WebProfilerBundle:Profiler:toolbar_item.html.twig")->display(array_merge($context, array("link" => false))); } public function getTemplateName() { return "WebProfilerBundle:Collector:memory.html.twig"; } public function isTraitable() { return false; } }
radzikowski/alf
app/cache/dev/twig/cc/b1/a70d7cfd163aa51619d0fc404c67.php
PHP
mit
2,299
<?php /** * CompraingredienteFixture * */ class CompraingredienteFixture extends CakeTestFixture { /** * Fields * * @var array */ public $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false, 'key' => 'primary'), 'resto_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false), 'restosurcusale_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false), 'proveedore_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false), 'compratipopago_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'unsigned' => false), 'fecha_compra' => array('type' => 'date', 'null' => false, 'default' => null), 'fecha_vencimiento' => array('type' => 'date', 'null' => false, 'default' => null), 'num_factura' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'), 'observaciones' => array('type' => 'text', 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'), 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1) ), 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'InnoDB') ); /** * Records * * @var array */ public $records = array( array( 'id' => 1, 'resto_id' => 1, 'restosurcusale_id' => 1, 'proveedore_id' => 1, 'compratipopago_id' => 1, 'fecha_compra' => '2017-01-20', 'fecha_vencimiento' => '2017-01-20', 'num_factura' => 'Lorem ipsum dolor sit amet', 'observaciones' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.', 'created' => '2017-01-20 15:51:45', 'modified' => '2017-01-20 15:51:45' ), ); }
kster007/CUBETECH-SOLTERA
app/Test/Fixture/CompraingredienteFixture.php
PHP
mit
2,307
<?php namespace spec\Prophecy\Exception\Prophecy; use PhpSpec\ObjectBehavior; use Prophecy\Prophecy\ObjectProphecy; class ObjectProphecyExceptionSpec extends ObjectBehavior { function let(ObjectProphecy $objectProphecy) { $this->beConstructedWith('message', $objectProphecy); } function it_should_be_a_prophecy_exception() { $this->shouldBeAnInstanceOf('Prophecy\Exception\Prophecy\ProphecyException'); } function it_holds_double_reference($objectProphecy) { $this->getObjectProphecy()->shouldReturn($objectProphecy); } }
gustavokev/preescolar1
vendor/phpspec/prophecy/spec/Prophecy/Exception/Prophecy/ObjectProphecyExceptionSpec.php
PHP
mit
611
/* * The MIT License (MIT) * * Copyright (c) 2016 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package burstcoin.faucet.data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.io.Serializable; import java.util.Date; @Entity public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String accountId; @Column(nullable = true) private Date lastClaim; protected Account() { } public Account(String accountId, Date lastClaim) { this.accountId = accountId; this.lastClaim = lastClaim; } public Long getId() { return id; } public void setAccountId(String accountId) { this.accountId = accountId; } public void setLastClaim(Date lastClaim) { this.lastClaim = lastClaim; } public String getAccountId() { return accountId; } public Date getLastClaim() { return lastClaim; } }
de-luxe/burstcoin-faucet
src/main/java/burstcoin/faucet/data/Account.java
Java
mit
2,187
"use strict"; const _ = require ('underscore') _.hasTypeMatch = true /* Type matching for arbitrary complex structures (TODO: test) ======================================================================== */ Meta.globalTag ('required') Meta.globalTag ('atom') $global.const ('$any', _.identity) _.deferTest (['type', 'type matching'], function () { $assert (_.omitTypeMismatches ( { '*': $any, foo: $required ('number'), bar: $required ('number') }, { baz: 'x', foo: 42, bar: 'foo' }), { }) $assert (_.omitTypeMismatches ( { foo: { '*': $any } }, { foo: { bar: 42, baz: 'qux' } }), { foo: { bar: 42, baz: 'qux' } }) $assert (_.omitTypeMismatches ( { foo: { bar: $required(42), '*': $any } }, { foo: { bar: 'foo', baz: 'qux' } }), { }) $assert (_.omitTypeMismatches ( [{ foo: $required ('number'), bar: 'number' }], [{ foo: 42, bar: 42 }, { foo: 24, }, { bar: 42 }]), [{ foo: 42, bar: 42 }, { foo: 24 }]) $assert (_.omitTypeMismatches ({ '*': 'number' }, { foo: 42, bar: 42 }), { foo: 42, bar: 42 }) $assert (_.omitTypeMismatches ({ foo: $any }, { foo: 0 }), { foo: 0 }) // there was a bug (any zero value was omitted) $assert (_.decideType ([]), []) $assert (_.decideType (42), 'number') $assert (_.decideType (_.identity), 'function') $assert (_.decideType ([{ foo: 1 }, { foo: 2 }]), [{ foo: 'number' }]) $assert (_.decideType ([{ foo: 1 }, { bar: 2 }]), []) $assert (_.decideType ( { foo: { bar: 1 }, foo: { baz: [] } }), { foo: { bar: 'number' }, foo: { baz: [] } }) $assert (_.decideType ( { foo: { bar: 1 }, foo: { bar: 2 } }), { foo: { bar: 'number' } }) $assert (_.decideType ( { foo: { bar: 1 }, bar: { bar: 2 } }), { '*': { bar: 'number' } }) if (_.hasOOP) { var Type = $prototype () $assert (_.decideType ({ x: new Type () }), { x: Type }) } }, function () { _.isMeta = function (x) { return (x === $any) || $atom.is (x) || $required.is (x) } var zip = function (type, value, pred) { var required = Meta.unwrapAll (_.filter2 (type, $required.is)) var match = _.nonempty (_.zip2 (Meta.unwrapAll (type), value, pred)) if (_.isEmpty (required)) { return match } else { var requiredMatch = _.nonempty (_.zip2 (required, value, pred)) var allSatisfied = _.values2 (required).length === _.values2 (requiredMatch).length return allSatisfied ? match : _.coerceToEmpty (value) } } var hyperMatch = _.hyperOperator (_.binary, function (type_, value, pred) { var type = Meta.unwrap (type_) if (_.isArray (type)) { // matches [ItemType] → [item, item, ..., N] if (_.isArray (value)) { return zip (_.times (value.length, _.constant (type[0])), value, pred) } else { return undefined } } else if (_.isStrictlyObject (type) && type['*']) { // matches { *: .. } → { a: .., b: .., c: .. } if (_.isStrictlyObject (value)) { return zip (_.extend ( _.map2 (value, _.constant (type['*'])), _.omit (type, '*')), value, pred) } else { return undefined } } else { return zip (type_, value, pred) } }) var typeMatchesValue = function (c, v) { var contract = Meta.unwrap (c) return (contract === $any) || ((contract === undefined) && (v === undefined)) || (_.isFunction (contract) && ( _.isPrototypeConstructor (contract) ? _.isTypeOf (contract, v) : // constructor type (contract (v) === true))) || // test predicate (typeof v === contract) || // plain JS type (v === contract) } // constant match _.mismatches = function (op, contract, value) { return hyperMatch (contract, value, function (contract, v) { return op (contract, v) ? undefined : contract }) } _.omitMismatches = function (op, contract, value) { return hyperMatch (contract, value, function (contract, v) { return op (contract, v) ? v : undefined }) } _.typeMismatches = _.partial (_.mismatches, typeMatchesValue) _.omitTypeMismatches = _.partial (_.omitMismatches, typeMatchesValue) _.valueMismatches = _.partial (_.mismatches, function (a, b) { return (a === $any) || (b === $any) || (a === b) }) var unifyType = function (value) { if (_.isArray (value)) { return _.nonempty ([_.reduce (value.slice (1), function (a, b) { return _.undiff (a, b) }, _.first (value) || undefined)]) } else if (_.isStrictlyObject (value)) { var pairs = _.pairs (value) var unite = _.map ( _.reduce (pairs.slice (1), function (a, b) { return _.undiff (a, b) }, _.first (pairs) || [undefined, undefined]), _.nonempty) return (_.isEmpty (unite) || _.isEmpty (unite[1])) ? value : _.fromPairs ([[unite[0] || '*', unite[1]]]) } else { return value } } _.decideType = function (value) { var operator = _.hyperOperator (_.unary, function (value, pred) { if (value && value.constructor && value.constructor.$definition) { return value.constructor } return unifyType (_.map2 (value, pred)) }) return operator (value, function (value) { if (_.isPrototypeInstance (value)) { return value.constructor } else { return _.isEmptyArray (value) ? value : (typeof value) } }) } }) // TODO: fix hyperOperator to remove additional check for []
xpl/useless
base/tier0/typeMatch.js
JavaScript
mit
6,907
<?php return [ 'app' => [ 'name' => 'OctoberCMS', 'tagline' => 'Getting back to basics' ], 'locale' => [ 'be' => 'Беларуская', 'bg' => 'Български', 'cs' => 'Čeština', 'da' => 'Dansk', 'en' => 'English (United States)', 'en-au' => 'English (Australia)', 'en-ca' => 'English (Canada)', 'en-gb' => 'English (United Kingdom)', 'et' => 'Eesti', 'de' => 'Deutsch', 'el' => 'Ελληνικά', 'es' => 'Español', 'es-ar' => 'Español (Argentina)', 'fa' => 'فارسی', 'fr' => 'Français', 'fr-ca' => 'Français (Canada)', 'hu' => 'Magyar', 'id' => 'Bahasa Indonesia', 'it' => 'Italiano', 'ja' => '日本語', 'kr' => '한국어', 'lt' => 'Lietuvių', 'lv' => 'Latviešu', 'nb-no' => 'Norsk (Bokmål)', 'nl' => 'Nederlands', 'pl' => 'Polski', 'pt-br' => 'Português (Brasil)', 'pt-pt' => 'Português (Portugal)', 'ro' => 'Română', 'ru' => 'Русский', 'fi' => 'Suomi', 'sv' => 'Svenska', 'sk' => 'Slovenský', 'tr' => 'Türkçe', 'uk' => 'Українська мова', 'zh-cn' => '简体中文', 'zh-tw' => '繁體中文', 'vn' => 'Tiếng việt' ], 'directory' => [ 'create_fail' => 'Không thể tạo danh mục: :name' ], 'file' => [ 'create_fail' => 'Không thể tạo file: :name' ], 'combiner' => [ 'not_found' => "Không tìm thấy combiner file ':name'." ], 'system' => [ 'name' => 'Hệ thống', 'menu_label' => 'Hệ thống', 'categories' => [ 'cms' => 'CMS', 'misc' => 'Misc', 'logs' => 'Các bản ghi', 'mail' => 'Mail', 'shop' => 'Cửa hàng', 'team' => 'Team', 'users' => 'Người dùng', 'system' => 'Hệ thống', 'social' => 'Mạng xã hội', 'backend' => 'Trang quản trị', 'events' => 'Sự kiện', 'customers' => 'Khách hàng', 'my_settings' => 'Cài đặt của tôi', 'notifications' => 'Thông báo' ] ], 'theme' => [ 'label' => 'Theme', 'unnamed' => 'Theme chưa được đặt tên', 'name' => [ 'label' => 'Tên theme', 'help' => 'Tên của theme không được trùng lặp. Ví dụ RainLab.Vanilla' ], ], 'themes' => [ 'install' => 'Cài đặt themes', 'search' => 'Tìm kiếm theme để cài đặt...', 'installed' => 'Các theme đã cài đặt', 'no_themes' => 'Không có theme nào được cài đặt từ chợ theme.', 'recommended' => 'Được khuyến khích cài đặt', 'remove_confirm' => 'Bạn có chắc chắn muốn xóa theme này?' ], 'plugin' => [ 'label' => 'Plugin', 'unnamed' => 'Plugin chưa được đặt tên', 'name' => [ 'label' => 'Tên plugin', 'help' => 'Tên của plugin không được trùng lặp. For example, RainLab.Blog' ] ], 'plugins' => [ 'manage' => 'Quản lý các plugin', 'enable_or_disable' => 'Bật hoặc tắt', 'enable_or_disable_title' => 'Bật hoặc tắt plugin', 'install' => 'Cài đặt plugin', 'install_products' => 'Các sản phẩm để cài đặt', 'search' => 'Tìm kiếm plugin để cài đặt...', 'installed' => 'Các plugin đã cài đặt', 'no_plugins' => 'Không có plugin nào được cài đặt từ chợ plugin', 'recommended' => 'Được khuyến khích cài đặt', 'remove' => 'Xóa', 'refresh' => 'Làm mới', 'disabled_label' => 'Đã tắt', 'disabled_help' => 'Các plugin đã tắt và không được sử dụng bới ứng dụng', 'frozen_label' => 'Tắt cập nhật', 'frozen_help' => 'Những plugin tắt cập nhật sẽ không được sử lý cập nhật tự động.', 'selected_amount' => 'Số plugin đã được chọn: :amount', 'remove_confirm' => 'Xác nhận xóa plugin này?', 'remove_success' => 'Đã xóa các plugin ra khỏi hệ thống.', 'refresh_confirm' => 'Xác nhận?', 'refresh_success' => 'Đã làm mới các plugin.', 'disable_confirm' => 'Xác nhận tắt?', 'disable_success' => 'Đã tắt các plugin.', 'enable_success' => 'Đã bật các plugin.', 'unknown_plugin' => 'Đã xóa các file của plugin ra khỏi hệ thống.' ], 'project' => [ 'name' => 'Dự án', 'owner_label' => 'Người sở hữu', 'attach' => 'Chèn Dự án', 'detach' => 'Gỡ bỏ Dự án', 'none' => 'Trống', 'id' => [ 'label' => 'ID Dự án', 'help' => 'Cách để xem ID Dự án', 'missing' => 'Điền vào ID Dự án để sử dụng.' ], 'detach_confirm' => 'Xác nhận gỡ Dự án?', 'unbind_success' => 'Dự án đã được gỡ ra.' ], 'settings' => [ 'menu_label' => 'Cài đặt', 'not_found' => 'Không tìm thấy các cấu hình được chỉ định.', 'missing_model' => 'Không có Model cho trang cài đặt.', 'update_success' => 'Cấu hình cho :name thành công', 'return' => 'Trở lại trang cài đặt', 'search' => 'Tìm kiếm' ], 'mail' => [ 'log_file' => 'Log file', 'menu_label' => 'Cấu hình mail', 'menu_description' => 'Quản lý các cấu hình mail.', 'general' => 'Cấu hình chung', 'method' => 'Phương thức gửi mail', 'sender_name' => 'Tên người gửi', 'sender_email' => 'Email người gửi', 'php_mail' => 'PHP mail', 'smtp' => 'SMTP', 'smtp_address' => 'Địa chỉ SMTP', 'smtp_authorization' => 'Yêu cầu cấp quyền', 'smtp_authorization_comment' => 'Chọn mụ này nếu SMTP sever của bạn yêu cầu cấp quyền truy cập(requires authorization).', 'smtp_username' => 'Tên đăng nhập', 'smtp_password' => 'Mật khẩu', 'smtp_port' => 'SMTP port', 'smtp_ssl' => 'Yêu cầu sử dụng SSL', 'smtp_encryption' => 'Giao thức mã hóa SMTP', 'smtp_encryption_none' => 'Không mã hóa', 'smtp_encryption_tls' => 'TLS', 'smtp_encryption_ssl' => 'SSL', 'sendmail' => 'Gửi mail', 'sendmail_path' => 'Đường dẫn gửi mail', 'sendmail_path_comment' => 'Please specify the path of the sendmail program.', 'mailgun' => 'Mailgun', 'mailgun_domain' => 'Tên miền trên Mailgun', 'mailgun_domain_comment' => 'Điền tên miền trên Mailgun', 'mailgun_secret' => 'Mã bí mật trên Mailgun(secret key)', 'mailgun_secret_comment' => 'Điền vào mã Mailgun API của bạn', 'mandrill' => 'Mandrill', 'mandrill_secret' => 'Mã bí mật trên Mandrill (secret key)', 'mandrill_secret_comment' => 'Điền vào mã Mandrill API của bạn.', 'ses' => 'SES', 'ses_key' => 'Mã SES', 'ses_key_comment' => 'Điền vào mã SES API của bạn', 'ses_secret' => 'Mã bí mật trên SES (secret key)', 'ses_secret_comment' => 'Điền vào mã bí mật trên SES API của bạn (secret key)', 'ses_region' => 'Ku vực SES', 'ses_region_comment' => 'Điền vào khu vực SES (ví dụ us-east-1)', 'drivers_hint_header' => 'Trình điều khiển chưa được cài đặt', 'drivers_hint_content' => 'Phương thức gửi mail này cần phải cài ":plugin" plugin, bạn cần phải cài đặt nó trước mới gửi được mail' ], 'mail_templates' => [ 'menu_label' => 'Các mẫu mail', 'menu_description' => 'Quản lý các mẫu mail sẽ được gửi cho user và administrators.', 'new_template' => 'Thêm mẫu mới', 'new_layout' => 'Thêm mẫu mới', 'new_partial' => 'Thêm Partial', 'template' => 'Giao diện mẫu', 'templates' => 'Các giao diện mẫu', 'partial' => 'Partial', 'partials' => 'Partials', 'menu_layouts_label' => 'Giao diện mail mẫu', 'menu_partials_label' => 'Mail Partials', 'layout' => 'Giao diễn mẫu', 'layouts' => 'Các giao diễn mẫu', 'no_layout' => '-- Không sử dụng mẫu --', 'name' => 'Tên', 'name_comment' => 'Tên của giao diễn mẫu không được trùng nhau.', 'code' => 'Code', 'code_comment' => 'Nhập một mã không được trùng với các mẫu giao diện khác', 'subject' => 'Tiêu đề mail', 'subject_comment' => 'Tiêu đề của mail', 'description' => 'Mô tả', 'content_html' => 'HTML', 'content_css' => 'CSS', 'content_text' => 'Văn bản thô', 'test_send' => 'Gửi mail test', 'test_success' => 'Đã gửi mail test.', 'test_confirm' => 'Gửi mail test đến :email. Tiếp tục?', 'creating' => 'Đang tạo mẫu...', 'creating_layout' => 'Đang tạo Layout...', 'saving' => 'Đang lưu mẫu...', 'saving_layout' => 'Đang lưu Layout...', 'delete_confirm' => 'Xác nhận xóa template này?', 'delete_layout_confirm' => 'Xác nhận xóa layout này?', 'deleting' => 'Đang xóa mẫu...', 'deleting_layout' => 'Đang xóa Layout...', 'sending' => 'Đang gửi mail test...', 'return' => 'Quay lại trang danh sách mail mẫu' ], 'mail_brand' => [ 'menu_label' => 'Giao diện Mail', 'menu_description' => 'Chỉnh sửa màu sắc, giao diện của mẫu mail.', 'page_title' => 'Tùy chỉnh giao diện của mẫu mail', 'sample_template' => [ 'heading' => 'Tiêu đề', 'paragraph' => 'Đây là đoạn văn mẫu.... This is a paragraph filled with Lorem Ipsum and a link. Cumque dicta <a>doloremque eaque</a>, enim error laboriosam pariatur possimus tenetur veritatis voluptas.', 'table' => [ 'item' => 'Danh sách các mục', 'description' => 'Mô tả', 'price' => 'Giá', 'centered' => 'Căn giữa', 'right_aligned' => 'Căn phải' ], 'buttons' => [ 'primary' => 'Nút bấm chính', 'positive' => 'Nút nổi bật', 'negative' => 'Nút chú ý', ], 'panel' => 'Mẫu giao diện này thật tuyện vời!', 'more' => 'Mô tả thêm', 'promotion' => 'Mã ưu đãi: OCTOBER', 'subcopy' => 'Thông tin thêm', 'thanks' => 'Lời cám ơn' ], 'fields' => [ '_section_background' => 'Màu nền', 'body_bg' => 'Màu nền chính', 'content_bg' => 'Màu nền nội dung', 'content_inner_bg' => 'Màu nền bên trong nội dung', '_section_buttons' => 'Màu nền của các nút bấm', 'button_text_color' => 'Màu chữ của nút bấm', 'button_primary_bg' => 'Màu của nút bấm chính', 'button_positive_bg' => 'Màu của nút bấm nổi bật', 'button_negative_bg' => 'Màu của nút bấm chú ý', '_section_type' => 'Màu của chữ', 'header_color' => 'Màu của tiêu đề', 'heading_color' => 'Màu của tiêu đề', 'text_color' => 'Màu chữ bình thường', 'link_color' => 'Màu đường dẫn', 'footer_color' => 'Màu chữ chân trang', '_section_borders' => 'Đường viền', 'body_border_color' => 'Màu của đường viền toàn trang', 'subcopy_border_color' => 'Màu đường viền phần mô tả thêm', 'table_border_color' => 'Màu của đường viền bảng', '_section_components' => 'Thành phần khác', 'panel_bg' => 'Nền của bảng điều khiển', 'promotion_bg' => 'Nền mục khuyến mãi', 'promotion_border_color' => 'Viền của mục khuyến mãi', ] ], 'install' => [ 'project_label' => 'Chèn Project', 'plugin_label' => 'Cài đặt Plugin', 'theme_label' => 'Cài đặt Theme', 'missing_plugin_name' => 'Điền vào tên Plugin để cài đặt.', 'missing_theme_name' => 'Điền vào tên Theme để cài đặt.', 'install_completing' => 'Hoàn tất cài đặt', 'install_success' => 'Plugin đã được cài thành công' ], 'updates' => [ 'title' => 'Quản lý các cập nhật', 'name' => 'Cập nhật hệ thống', 'menu_label' => 'Những cập nhật & Plugins', 'menu_description' => 'Cập nhật hệ thống, quản lý và cài đặt plugins, themes.', 'return_link' => 'Quay lại trang cập nhật hệ thống', 'check_label' => 'Kiểm tra cập nhật', 'retry_label' => 'Thử lại', 'plugin_name' => 'Tên Plugin', 'plugin_code' => 'Code', 'plugin_description' => 'Mô tả', 'plugin_version' => 'Phiên bản', 'plugin_author' => 'Tác giả', 'plugin_not_found' => 'Không tìm thấy Plugin', 'core_current_build' => 'Current build', 'core_build' => 'Build :build', 'core_build_help' => 'Phiên bản build gần nhất.', 'core_downloading' => 'Đang tải file ứng dụng', 'core_extracting' => 'Đang giải nén', 'core_set_build' => 'Cài đặt build number', 'plugins' => 'Plugins', 'themes' => 'Themes', 'disabled' => 'Đã tắt', 'plugin_downloading' => 'Đang tải plugin: :name', 'plugin_extracting' => 'Đang giải nén plugin: :name', 'plugin_version_none' => 'Tạo mới plugin', 'plugin_current_version' => 'Phiên bản hiện tại version', 'theme_new_install' => 'Cài đặt theme mới.', 'theme_downloading' => 'Đang tải theme: :name', 'theme_extracting' => 'Đang giải nén theme: :name', 'update_label' => 'cập nhật hệ thống', 'update_completing' => 'Cập nhật hoàn tất', 'update_loading' => 'Đang kiểm tra các cập nhật có sẵn...', 'update_success' => 'Cập nhật hoàn tất', 'update_failed_label' => 'Lỗi cập nhật', 'force_label' => 'Bắt buộc cập nhật', 'found' => [ 'label' => 'Có cập nhật mới!', 'help' => 'Bấm cập nhật hệ thống để bắt đầu cập nhật.' ], 'none' => [ 'label' => 'Không có cập nhật', 'help' => 'Không tìm thấy bản cập nhật nào.' ], 'important_action' => [ 'empty' => 'Chọn hành động', 'confirm' => 'Xác nhận cập nhật', 'skip' => 'Bỏ qua bản cập nhật này (Chỉ lần này)', 'ignore' => 'Bỏ qua bản cập nhật này (luôn luôn bỏ qua)' ], 'important_action_required' => 'Hành động này là bắt buộc', 'important_view_guide' => 'Xem hướng dẫn nâng cấp', 'important_view_release_notes' => 'Xem ghi chú', 'important_alert_text' => 'Một số cập nhật cần phải chú ý.', 'details_title' => 'Chi tiết Plugin', 'details_view_homepage' => 'Đến trang chủ', 'details_readme' => 'Tài liệu hướng dẫn', 'details_readme_missing' => 'Không có tài liệu được cung cấp.', 'details_changelog' => 'Các lần thay đổi', 'details_changelog_missing' => 'Không có bản ghi các lần thay đổi.', 'details_upgrades' => 'Hướng dẫn nâng cấp', 'details_upgrades_missing' => 'Không có hướng dẫn nâng cấp nào được cung cấp.', 'details_licence' => 'Giấy phép', 'details_licence_missing' => 'Không có giấy phép nào được cung cấp.', 'details_current_version' => 'Phiên bản hiện tại', 'details_author' => 'Tác giả' ], 'server' => [ 'connect_error' => 'Lỗi kết nối đến máy chủ.', 'response_not_found' => 'Không tìm thấy máy chủ cập nhật.', 'response_invalid' => 'Phản hồi không hợp lệ từ máy chủ.', 'response_empty' => 'Phản hồi trống từ máy chủ.', 'file_error' => 'Lỗi máy chủ không thể gửi về các package.', 'file_corrupt' => 'File trên máy chủ bị hỏng.' ], 'behavior' => [ 'missing_property' => 'Class :class cần phải khai báo thuộc tính $:property được sử dụng bởi :behavior behavior.' ], 'config' => [ 'not_found' => 'Không tìm thấy tệp tin cấu hình :file được khai báo cho :location.', 'required' => "Cấu hình được sử dụng cho :location cần phải có giá trị ':property'." ], 'zip' => [ 'extract_failed' => "Không thể giải nén tệp tin ':file'." ], 'event_log' => [ 'hint' => 'Bản ghi các lỗi có thể sảy ra trong ứng dụng, ví dụ exceptions và thông tin debug.', 'menu_label' => 'Bản ghi các sự kiện', 'menu_description' => 'Xem nhật ký hệ thống với thông tin thời gian cụ thể.', 'empty_link' => 'Xóa hết các bản ghi', 'empty_loading' => 'Đang xóa các bản ghi...', 'empty_success' => 'Đã xóa các bản ghi sự kiện', 'return_link' => 'Quay lại trang các bản ghi sự kiện', 'id' => 'ID', 'id_label' => 'Event ID', 'created_at' => 'Ngày giờ', 'message' => 'Nội dung', 'level' => 'Cấp độ', 'preview_title' => 'Event' ], 'request_log' => [ 'hint' => 'Bản ghi các request lỗi của trình duyệt. Ví dụ, nếu có khách truy cập vào một trang nội dung mà hệ thống không tìm thấy trang đó, một bản ghi sẽ được tạo ra với mã trạng thái 404.', 'menu_label' => 'Bản ghi các Request', 'menu_description' => 'Xem các request lỗi hoặc bị chuyển hướng, ví dụ như Không tìm thấy trang (404).', 'empty_link' => 'Xóa hết các request log', 'empty_loading' => 'Đang xóa request log...', 'empty_success' => 'Đã xóa hết request log', 'return_link' => 'Quay lại trang request log', 'id' => 'ID', 'id_label' => 'Log ID', 'count' => 'Số lần', 'referer' => 'Người giới thiệu', 'url' => 'URL', 'status_code' => 'Trạng thái', 'preview_title' => 'Request' ], 'permissions' => [ 'name' => 'Hệ thống', 'manage_system_settings' => 'Quản lý các cài đặt của hệ thống', 'manage_software_updates' => 'Quản lý các cập nhật của hệ thống', 'access_logs' => 'Xem các bản ghi hệ thống', 'manage_mail_templates' => 'Quản lý các mẫu mail', 'manage_mail_settings' => 'Quản lý các cài đặt mail', 'manage_other_administrators' => 'Quản lý các administrator khác', 'manage_preferences' => 'Cá nhân hóa trang quản trị', 'manage_editor' => 'Cá nhân hóa trình biên tập(code editor)', 'view_the_dashboard' => 'Xem bảng điều khiển', 'manage_branding' => 'Tùy chỉnh trang quản trị' ], 'log' => [ 'menu_label' => 'Cài đặt log', 'menu_description' => 'Cấu hình những mục sẽ được ghi log.', 'default_tab' => 'Những lần đăng nhập', 'log_events' => 'Ghi các sự kiện của hệ thống', 'log_events_comment' => 'Lưu các sự kiện của hệ thống vào database dựa trên file log', 'log_requests' => 'Bản ghi các lỗi request', 'log_requests_comment' => 'Các lỗi request của trình duyệt, ví dụ lỗi 404.', 'log_theme' => 'Bản ghi các thay đổi của theme', 'log_theme_comment' => 'Khi thay đổi theme thông qua giao diện quản trị.', ], 'media' => [ 'invalid_path' => "Đường dẫn không hợp lệ: ':path'.", 'folder_size_items' => 'item(s)', ], ];
c57fr/c57
modules/system/lang/vn/lang.php
PHP
mit
21,151
/** * Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.darksci.pardot.api.request.form; import com.darksci.pardot.api.request.BaseRequest; /** * For creating new Forms using Pardot's API. */ public class FormCreateRequest extends BaseRequest<FormCreateRequest> { @Override public String getApiEndpoint() { return "form/do/create"; } /** * Define the name of the form. * @param name The name of the form. * @return FormCreateRequest builder. */ public FormCreateRequest withName(final String name) { setParam("name", name); return this; } /** * Associate form with a campaign. * @param campaignId Id of campaign to associate with form. * @return FormCreateRequest builder. */ public FormCreateRequest withCampaignId(final Long campaignId) { setParam("campaign_id", campaignId); return this; } /** * Associate form with a layout template. * @param layoutTemplateId Id of layout template to associate with form. * @return FormCreateRequest builder. */ public FormCreateRequest withLayoutTemplateId(final Long layoutTemplateId) { setParam("layout_template_id", layoutTemplateId); return this; } /** * Associate form with a folder. * @param folderId Id of folder to associate with form. * @return FormCreateRequest builder. */ public FormCreateRequest withFolderId(final Long folderId) { setParam("folder_id", folderId); return this; } }
Crim/pardot-java-client
src/main/java/com/darksci/pardot/api/request/form/FormCreateRequest.java
Java
mit
2,672
import { $, util } from './util-node' import Taglet from './taglet' var lace, version = '1.0.0', defaults = { opts: {} }, warehouse = { singleton: null, compiled_dom: null, laces: { global: null }, taglets: {} } ; class Lace { constructor(name) { this.name = name; } /** * * @param name * @param def * @param global, true when make available only for this lace * @returns {*} */ annotation(name, def, global = false) { /*if (typeof def !== Type.UNDEFINED) { this.definition('annotation', name, def); } return this.instance('annotation', name);*/ } taglet(name, def, global = false) { /*if (typeof def !== Type.UNDEFINED) { this.definition('taglet', name, def); } return this.instance('taglet', name);*/ } compile() { } render(template, data) { var $tmpl = $(template); console.log($tmpl); } definition(type, name, def) { return this.__lace__[type]['definitions'][name] = def || this.__lace__[type]['definitions'][name]; } instance(type, name, inst) { return this.__lace__[type]['instances'][name] = inst || this.__lace__[type]['instances'][name]; } } //TODO: should I declare in prototype? Lace.prototype.__lace__ = { annotation: { definitions: {}, instances: {} }, taglet: { definitions: {}, instances: {} } }; Lace.init = function (name) { return warehouse.laces[name] = warehouse.laces[name] || new Lace(name); }; Lace.parse = function(template) { }; /** * MODULE function for lace * @param name * @returns {Function|*} */ lace = function(name) { name = name || 'global'; return Lace.init(name); }; export default lace;
jRoadie/lace
src/es6/lace.js
JavaScript
mit
1,897
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cinema { class Program { static void Main(string[] args) { var project = Console.ReadLine().ToLower(); var r = double.Parse(Console.ReadLine()); var c = double.Parse(Console.ReadLine()); var result = r * c; var price = -1.0; if (project == "premiere") { price = 12.00; } else if (project == "normal") { price = 7.50; } else if (project == "discount") { price = 5.00; } if (price >= 0) { Console.WriteLine("{0:f2}", price * result); } } } }
vasilchavdarov/SoftUniHomework
Projects/ComplexCondition/Cinema/Program.cs
C#
mit
875
from django.conf import settings from django.conf.urls import static from django.urls import include, path, re_path from django.contrib import admin urlpatterns = [ path(r"admin/", admin.site.urls), path(r"flickr/", include("ditto.flickr.urls")), path(r"lastfm/", include("ditto.lastfm.urls")), path(r"pinboard/", include("ditto.pinboard.urls")), path(r"twitter/", include("ditto.twitter.urls")), path(r"", include("ditto.core.urls")), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ re_path(r"^__debug__/", include(debug_toolbar.urls)), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static.static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )
philgyford/django-ditto
devproject/devproject/urls.py
Python
mit
795
import angular from 'rollup-plugin-angular'; import commonjs from 'rollup-plugin-commonjs'; import nodeResolve from 'rollup-plugin-node-resolve'; import typescript from 'rollup-plugin-typescript'; import uglify from 'rollup-plugin-uglify'; import { minify } from 'uglify-es'; // rollup-plugin-angular addons import sass from 'node-sass'; import CleanCSS from 'clean-css'; import { minify as minifyHtml } from 'html-minifier'; const cssmin = new CleanCSS(); const htmlminOpts = { caseSensitive: true, collapseWhitespace: true, removeComments: true, }; export default { input: 'dist/index.js', output: { // core output options file: 'dist/bundle.umd.js', // required format: 'umd', // required name: 'ngx-form.element', globals: { '@angular/core': 'ng.core', 'rxjs/Subject': 'Subject', '@angular/forms': 'ng.forms', '@ngx-core/common': 'ngx-core.common', '@ngx-form/interface': 'ngx-form.interface', '@angular/common': 'ng.common', '@angular/material': 'ng.material' }, // advanced output options // paths: , // banner: , // footer: , // intro:, // outro: , sourcemap: true, // true | inline // sourcemapFile: , // interop: , // danger zone exports: 'named', // amd: , // indent: , // strict: }, onwarn, plugins: [ angular({ preprocessors: { template: template => minifyHtml(template, htmlminOpts), style: scss => { const css = sass.renderSync({ data: scss }).css; return cssmin.minify(css).styles; }, } }), commonjs(), nodeResolve({ // use "module" field for ES6 module if possible module: true, // Default: true // use "jsnext:main" if possible // – see https://github.com/rollup/rollup/wiki/jsnext:main jsnext: true, // Default: false // use "main" field or index.js, even if it's not an ES6 module // (needs to be converted from CommonJS to ES6 // – see https://github.com/rollup/rollup-plugin-commonjs main: true, // Default: true // some package.json files have a `browser` field which // specifies alternative files to load for people bundling // for the browser. If that's you, use this option, otherwise // pkg.browser will be ignored browser: true, // Default: false // not all files you want to resolve are .js files extensions: [ '.js', '.json' ], // Default: ['.js'] // whether to prefer built-in modules (e.g. `fs`, `path`) or // local ones with the same names preferBuiltins: true, // Default: true // Lock the module search in this path (like a chroot). Module defined // outside this path will be mark has external jail: '/src', // Default: '/' // If true, inspect resolved files to check that they are // ES2015 modules modulesOnly: false, // Default: false // Any additional options that should be passed through // to node-resolve customResolveOptions: {} }), typescript({ typescript: require('./node_modules/typescript') }), uglify({}, minify) ] }; function onwarn(message) { const suppressed = [ 'UNRESOLVED_IMPORT', 'THIS_IS_UNDEFINED' ]; if (!suppressed.find(code => message.code === code)) { return console.warn(message.message); } }
ngx-form/element
rollup.config.js
JavaScript
mit
3,420
using System; namespace Problem_04_Float_or_Integer { class Program_04_Float_or_Integer { static void Main() { decimal number = decimal.Parse(Console.ReadLine()); number = Math.Round(number); Console.WriteLine(number); } } }
ReapeR-MaxPayne/SU-TM-PF-Ext-0517-Excersises-CSharp
03-DataTypesAndVariables-Exercises/Problem_04_Float or Integer/Program_04_Float_or_Integer.cs
C#
mit
302
using System; using System.Collections; using UnityEngine; namespace Doubility3D.Resource.Downloader { public class WWWDownloader : IDownloader { private string home; internal WWWDownloader (string _home) { home = _home; if (home [home.Length - 1] != '/') { home += "/"; } } public IEnumerator ResourceTask (string path, Action<Byte[],string> actOnComplate) { Byte[] _bytes = null; WWW www = new WWW (home + path); while (!www.isDone) { yield return www; } if (string.IsNullOrEmpty (www.error)) { _bytes = www.bytes; } actOnComplate (_bytes, www.error); } public string Home { get { return home;} } public void Dispose(){ } } }
lighter-cd/Doubility3D
DoubilityUnity/Runtime/Doubility3D/Resource/Downloader/WWWDownloader.cs
C#
mit
704
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented")
spirit01/SAXS
test_caxs.py
Python
mit
6,842
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for LRORetrysOperations. /// </summary> public static partial class LRORetrysOperationsExtensions { /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static ProductInner Put201CreatingSucceeded200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.Put201CreatingSucceeded200Async(product).GetAwaiter().GetResult(); } /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> Put201CreatingSucceeded200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Put201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static ProductInner PutAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.PutAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult(); } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> PutAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ProductInner DeleteProvisioning202Accepted200Succeeded(this ILRORetrysOperations operations) { return operations.DeleteProvisioning202Accepted200SucceededAsync().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> DeleteProvisioning202Accepted200SucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LRORetrysDelete202Retry200HeadersInner Delete202Retry200(this ILRORetrysOperations operations) { return operations.Delete202Retry200Async().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysDelete202Retry200HeadersInner> Delete202Retry200Async(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Delete202Retry200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner DeleteAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations) { return operations.DeleteAsyncRelativeRetrySucceededAsync().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> DeleteAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LRORetrysPost202Retry200HeadersInner Post202Retry200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.Post202Retry200Async(product).GetAwaiter().GetResult(); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysPost202Retry200HeadersInner> Post202Retry200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Post202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LRORetrysPostAsyncRelativeRetrySucceededHeadersInner PostAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.PostAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult(); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> PostAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static ProductInner BeginPut201CreatingSucceeded200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.BeginPut201CreatingSucceeded200Async(product).GetAwaiter().GetResult(); } /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> BeginPut201CreatingSucceeded200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginPut201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static ProductInner BeginPutAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.BeginPutAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult(); } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> BeginPutAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ProductInner BeginDeleteProvisioning202Accepted200Succeeded(this ILRORetrysOperations operations) { return operations.BeginDeleteProvisioning202Accepted200SucceededAsync().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProductInner> BeginDeleteProvisioning202Accepted200SucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LRORetrysDelete202Retry200HeadersInner BeginDelete202Retry200(this ILRORetrysOperations operations) { return operations.BeginDelete202Retry200Async().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysDelete202Retry200HeadersInner> BeginDelete202Retry200Async(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDelete202Retry200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner BeginDeleteAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations) { return operations.BeginDeleteAsyncRelativeRetrySucceededAsync().GetAwaiter().GetResult(); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> BeginDeleteAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LRORetrysPost202Retry200HeadersInner BeginPost202Retry200(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.BeginPost202Retry200Async(product).GetAwaiter().GetResult(); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysPost202Retry200HeadersInner> BeginPost202Retry200Async(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginPost202Retry200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> public static LRORetrysPostAsyncRelativeRetrySucceededHeadersInner BeginPostAsyncRelativeRetrySucceeded(this ILRORetrysOperations operations, ProductInner product = default(ProductInner)) { return operations.BeginPostAsyncRelativeRetrySucceededAsync(product).GetAwaiter().GetResult(); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='product'> /// Product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> BeginPostAsyncRelativeRetrySucceededAsync(this ILRORetrysOperations operations, ProductInner product = default(ProductInner), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } } }
matthchr/autorest
src/generator/AutoRest.CSharp.Azure.Fluent.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperationsExtensions.cs
C#
mit
27,615