#ifndef PHP_SHMT_H
	#define PHP_SHMT_H

	#define PHP_SHMT_EXTNAME	"SHMT"
	#define PHP_SHMT_EXTVER		"1.0.1"

	#ifdef HAVE_CONFIG_H
		#include "config.h"
	#endif /* HAVE_CONFIG_H */

	extern zend_module_entry shmt_module_entry;
	#define phpext_shmt_ptr &shmt_module_entry;

#endif /* PHP_SHMT_H */

#ifndef PHP_SHMT_H
	#define PHP_SHMT_H

	#define PHP_SHMT_EXTNAME	"SHMT"
	#define PHP_SHMT_EXTVER		"1.0.2dev"

	#ifdef HAVE_CONFIG_H
		#include "config.h"
	#endif /* HAVE_CONFIG_H */

	extern zend_module_entry shmt_module_entry;
	#define phpext_shmt_ptr &shmt_module_entry;

#endif /* PHP_SHMT_H */

Update the version after tagging

Update the version after tagging


#pragma once

#include <utility>

namespace shk {

template<
    typename T,
    typename Return,
    Return (Free)(T),
    T EmptyValue = nullptr>
class RAIIHelper {
 public:
  RAIIHelper(T obj)
      : _obj(obj) {}

  RAIIHelper(const RAIIHelper &) = delete;
  RAIIHelper &operator=(const RAIIHelper &) = delete;

  RAIIHelper(RAIIHelper &&other)
      : _obj(other._obj) {
    other._obj = EmptyValue;
  }

  ~RAIIHelper() {
    if (_obj != EmptyValue) {
      Free(_obj);
    }
  }

  explicit operator bool() const {
    return _obj != EmptyValue;
  }

  T get() const {
    return _obj;
  }

 private:
  T _obj;
};

}  // namespace shk

#pragma once

#include <utility>

namespace shk {

template<
    typename T,
    typename Return,
    Return (Free)(T),
    T EmptyValue = nullptr>
class RAIIHelper {
 public:
  explicit RAIIHelper(T obj)
      : _obj(obj) {}

  RAIIHelper(const RAIIHelper &) = delete;
  RAIIHelper &operator=(const RAIIHelper &) = delete;

  RAIIHelper(RAIIHelper &&other)
      : _obj(other._obj) {
    other._obj = EmptyValue;
  }

  ~RAIIHelper() {
    if (_obj != EmptyValue) {
      Free(_obj);
    }
  }

  explicit operator bool() const {
    return _obj != EmptyValue;
  }

  T get() const {
    return _obj;
  }

 private:
  T _obj;
};

}  // namespace shk

Make it harder to accidentally steal ownership of a RAIIHelper resource


//
//  VOKMappableModel.h
//  VOKCoreData
//

#import "VOKCoreDataManager.h"

/**
 *  Any models that conform to this protocol will be automatically registered for mapping with the shared instance
 *  of VOKCoreDataManager.
 */
@protocol VOKMappableModel <NSObject>

///@return an array of VOKManagedObjectMap objects mapping foreign keys to local keys.
+ (NSArray *)coreDataMaps;

///@return the key name to use to uniquely compare two instances of a class.
+ (NSString *)uniqueKey;

// If an optional method isn't defined, the default VOKManagedObjectMap behavior/value will be used.
@optional

///@return whether to ignore remote null/nil values are ignored when updating.
+ (BOOL)ignoreNullValueOverwrites;

///@return whether to warn about incorrect class types when receiving null/nil values for optional properties.
+ (BOOL)ignoreOptionalNullValues;

///@return completion block to run after importing each foreign dictionary.
+ (VOKPostImportBlock)importCompletionBlock;

@end

//
//  VOKMappableModel.h
//  VOKCoreData
//

#import "VOKCoreDataManager.h"

/**
 *  Any models that conform to this protocol will be automatically registered for mapping with the shared instance
 *  of VOKCoreDataManager.
 *
 *  Note that runtime protocol-conformance is based on declared conformance (the angle-bracketed protocol name appended
 *  to the interface) and not by checking that the required methods are implemented.  If you ignore the compiler
 *  warnings about failing to implement required methods, your app will crash.
 */
@protocol VOKMappableModel <NSObject>

///@return an array of VOKManagedObjectMap objects mapping foreign keys to local keys.
+ (NSArray *)coreDataMaps;

///@return the key name to use to uniquely compare two instances of a class.
+ (NSString *)uniqueKey;

// If an optional method isn't defined, the default VOKManagedObjectMap behavior/value will be used.
@optional

///@return whether to ignore remote null/nil values are ignored when updating.
+ (BOOL)ignoreNullValueOverwrites;

///@return whether to warn about incorrect class types when receiving null/nil values for optional properties.
+ (BOOL)ignoreOptionalNullValues;

///@return completion block to run after importing each foreign dictionary.
+ (VOKPostImportBlock)importCompletionBlock;

@end

Add note about how protocol conformance checking works.


#include <stdio.h>
#include <stdlib.h>
#include "therm.h"

/* Loads settings from persistent storage, returning the number of
   items read, or -1 on error. */
int persistent_load() {
	FILE *f = fopen(SAVEPATH, "r");
	float pid[6];
	int ret = 0;

	if(!f) {
		return -1;
	}

	ret += fread(&wanted_temperature, sizeof(wanted_temperature), 1, f);
	ret += fread(&wanted_humidity, sizeof(wanted_humidity), 1, f);

	ret += fread(pid, sizeof(float), 6, f);
	pid_setvalues(pid[0], pid[1], pid[2], pid[3], pid[4], pid[5]);

	fclose(f);
	return ret;
}

/* Writes settings to persistent storage, returning the number of
   items written, or -1 on error. */
int persistent_write() {
	FILE *f = fopen(SAVEPATH, "w");
	float pid[6];
	int ret = 0;

	if(!f) {
		fprintf(stderr, "Couldn't open " SAVEPATH " for writing.\n");
		return -1;
	}

	ret += fwrite(&wanted_temperature, sizeof(wanted_temperature), 1, f);
	ret += fwrite(&wanted_humidity, sizeof(wanted_humidity), 1, f);

	pid_getvalues(pid+0, pid+1, pid+2, pid+3, pid+4, pid+5);
	ret += fwrite(pid, sizeof(float), 6, f);

	fclose(f);

	fprintf(stderr, "Done.\n");
	return ret;
}

[hotfix/0.4.2] Add file for reading/writing settings. Oops.


// RUN: not %clang_cc1 %s -cake-is-lie -%0 -%d 2> %t.log
// RUN: FileCheck %s -input-file=%t.log

// CHECK: unknown argument
// CHECK: unknown argument
// CHECK: unknown argument

// RUN: %clang -S %s -o %t.s -funknown-to-clang-option -Wunknown-to-clang-option -munknown-to-clang-optio

// IGNORED: warning: argument unused during compilation: '-funknown-to-clang-option'
// IGNORED: warning: argument unused during compilation: '-munknown-to-clang-option'
// IGNORED: warning: unknown warning option '-Wunknown-to-clang-option'

// RUN: not %clang_cc1 %s -cake-is-lie -%0 -%d 2> %t.log
// RUN: FileCheck %s -input-file=%t.log

// CHECK: unknown argument
// CHECK: unknown argument
// CHECK: unknown argument

// RUN: %clang -S %s -o %t.s -funknown-to-clang-option -Wunknown-to-clang-option -munknown-to-clang-option 2>&1 | FileCheck --check-prefix=IGNORED %s

// IGNORED: warning: argument unused during compilation: '-funknown-to-clang-option'
// IGNORED: warning: argument unused during compilation: '-munknown-to-clang-option'
// IGNORED: warning: unknown warning option '-Wunknown-to-clang-option'

Fix an incomplete copy and paste in my previous patch.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@191245 91177308-0d34-0410-b5e6-96231b3b80d8


// Unwinding stuff missing on some architectures (Mac OS X).

#ifndef RUST_UNWIND_H
#define RUST_UNWIND_H

#ifdef __APPLE__
#include <libunwind.h>

typedef int _Unwind_Action;
typedef void _Unwind_Context;
typedef void _Unwind_Exception;
typedef int _Unwind_Reason_Code;

#else

#include <unwind.h>

#endif

#endif

// Unwinding stuff missing on some architectures (Mac OS X).

#ifndef RUST_UNWIND_H
#define RUST_UNWIND_H

#ifdef __APPLE__
#include <libunwind.h>

typedef void _Unwind_Context;
typedef int _Unwind_Reason_Code;

#else

#include <unwind.h>

#endif

#if (defined __APPLE__) || (defined __clang__)

typedef int _Unwind_Action;
typedef void _Unwind_Exception;

#endif

#endif

Fix build with clang on non-Mac

rt: Fix build with clang on non-Mac


#include "chemfiles.h"

// Force NDEBUG to be undefined
#undef NDEBUG
#include <assert.h>
#include <stdlib.h>

int main() {
    CHFL_TOPOLOGY* topology = chfl_topology();
    CHFL_ATOM* O = chfl_atom("O");
    CHFL_ATOM* H = chfl_atom("H");
    assert(topology != NULL);
    assert(H != NULL);
    assert(O != NULL);

    assert(!chfl_topology_append(topology, H));
    assert(!chfl_topology_append(topology, O));
    assert(!chfl_topology_append(topology, O));
    assert(!chfl_topology_append(topology, H));
    assert(!chfl_atom_free(O));
    assert(!chfl_atom_free(H));

    CHFL_FRAME* frame = chfl_frame(4);
    assert(!chfl_frame_set_topology(frame, topology));
    assert(!chfl_topology_free(topology));

    bool* matched = malloc(4 * sizeof(bool));
    assert(!chfl_frame_selection(frame, "name O", matched, 4));
    assert(matched[0] == false);
    assert(matched[1] == true);
    assert(matched[2] == true);
    assert(matched[3] == false);

    assert(!chfl_frame_selection(frame, "not index <= 2", matched, 4));
    assert(matched[0] == false);
    assert(matched[1] == false);
    assert(matched[2] == false);
    assert(matched[3] == true);

    free(matched);
    assert(!chfl_frame_free(frame));
    return EXIT_SUCCESS;
}

Add test for the C API for selections

Add test for the C API for selections


#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct vector3f
{
    float x, y, z;
}VECTOR3F;

typedef struct triangle
{
    int32_t v1, v2, v3;
}TRIANGLE;

typedef struct trianglemesh
{
    int32_t id;
    TRIANGLE t; // vertices number
    VECTOR3F v[3]; // vertices coordinates
}TRIANGLEMESH;

void usage(char *argv0)
{
    fprintf(stdout, "%s <obj filename>\n", argv0);
    exit(1);
}

int parse_file(const char *filename)
{
    FILE *fp = NULL;
    char buf[1024];
    int vertices_count = 0;
    int faces_count = 0;

    if ((fp = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "Cannot open file %s.\n", filename);
        return -1;
    }

    // Reading file until the end
    while (!feof(fp))
    {
        memset(buf, 0, sizeof(buf));
        char start_line = 0;

        // Read a line and save to a buffer.
        while (fgets(buf, sizeof(buf), fp) != NULL)
        {
            // Read the first character of the line
            sscanf(buf, "%c", &start_line);

            switch(start_line)
            {
                VECTOR3F v;
                TRIANGLE t;
                TRIANGLEMESH tm;

                case 'v':
                    sscanf(buf, "%c %f %f %f", &start_line, &v.x, &v.y, &v.z);
                    vertices_count += 1;

                    fprintf(stdout, "%c %f %f %f\n", start_line, v.x, v.y, v.z);
                    break;
                case 'f':
                    sscanf(buf, "%c %d %d %d", &start_line, &t.v1, &t.v2, &t.v3);
                    faces_count += 1;

                    fprintf(stdout, "%c %d %d %d\n", start_line, t.v1, t.v2, t.v3);
                    break;
                default:
                    fprintf(stdout, "Not known start line %c\n", start_line);
                    break;
            }

        }

    }

    return 0;
}

int main(int argc, char *argv[])
{

    if (argc != 2)
    {
        usage(argv[0]);
    }

    const char* filename = argv[1];

    parse_file(filename);

    return 0;
}

Create a utility to properly parse obj files.


extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) {
    if (!(cond)) {
        ERROR: __VERIFIER_error();
    }
    return;
}

int g = 1;

int main()
{
    __VERIFIER_assert(g == 1);
    return 0;
}

Add global initializer SV-COMP test

Add global initializer SV-COMP test


/*
 * This file is part of Kotaka, a mud library for DGD
 * http://github.com/shentino/kotaka
 *
 * Copyright (C) 2012  Raymond Jennings
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <kotaka/paths.h>
#include <text/paths.h>
#include <status.h>

inherit LIB_RAWVERB;

void main(object actor, string args)
{
	mixed *st;
	int i, sz;
	int tcount;

	if (query_user()->query_class() < 2) {
		send_out("You do not have sufficient access rights to touch all clones.\n");
		return;
	}

	st = status(args);

	if (!st) {
		send_out("No such object.\n");
		return;
	}

	sz = status(ST_OTABSIZE);

	for (i = 0; i < sz; i++) {
		object obj;

		obj = find_object(args + "#" + i);

		if (obj) {
			call_touch(obj);
			tcount++;
		}
	}

	send_out(tcount + " objects touched.\n");
}

Add verb to touch all clones of a given clonable


//
//  BackgroundTaskManager.h
//
//  Created by Puru Shukla on 20/02/13.
//  Copyright (c) 2013 Puru Shukla. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BackgroundTaskManager : NSObject

+(instancetype)sharedBackgroundTaskManager;

-(UIBackgroundTaskIdentifier)beginNewBackgroundTask;

@end

//
//  BackgroundTaskManager.h
//
//  Created by Puru Shukla on 20/02/13.
//  Copyright (c) 2013 Puru Shukla. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BackgroundTaskManager : NSObject

+(instancetype)sharedBackgroundTaskManager;

-(UIBackgroundTaskIdentifier)beginNewBackgroundTask;
-(void)endAllBackgroundTasks;

@end

Add endAllBackgroundTasks to the Public API


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <vespa/vespalib/util/threadstackexecutor.h>
#include <chrono>
#include <mutex>
#include <condition_variable>

namespace search::bmcluster {

class BmCluster;

class BmNodeStatsReporter {
    BmCluster&                    _cluster;
    vespalib::ThreadStackExecutor _executor;
    std::mutex                    _mutex;
    std::condition_variable       _cond;
    uint32_t                      _pending_report;
    bool                          _started;
    bool                          _stop;

    void report();
    void run_report_loop(std::chrono::milliseconds interval);
public:
    BmNodeStatsReporter(BmCluster& cluster);
    ~BmNodeStatsReporter();
    void start(std::chrono::milliseconds interval);
    void stop();
    void report_now();
};

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <vespa/vespalib/util/threadstackexecutor.h>
#include <chrono>
#include <mutex>
#include <condition_variable>

namespace search::bmcluster {

class BmCluster;

/*
 * Class handling background reporting of node stats during feed or
 * document redistribution.
 */
class BmNodeStatsReporter {
    BmCluster&                    _cluster;
    vespalib::ThreadStackExecutor _executor;
    std::mutex                    _mutex;
    std::condition_variable       _cond;
    uint32_t                      _pending_report;
    bool                          _started;
    bool                          _stop;

    void report();
    void run_report_loop(std::chrono::milliseconds interval);
public:
    BmNodeStatsReporter(BmCluster& cluster);
    ~BmNodeStatsReporter();
    void start(std::chrono::milliseconds interval);
    void stop();
    void report_now();
};

}

Add class comment for BmNodeStatsReporter.


#ifndef NEWSBOAT_DIRBROWSERFORMACTION_H
#define NEWSBOAT_DIRBROWSERFORMACTION_H

#include <grp.h>

#include "configcontainer.h"
#include "formaction.h"

namespace newsboat {

	class DirBrowserFormAction : public FormAction {
	public:
		DirBrowserFormAction(View*, std::string formstr, ConfigContainer* cfg);
		~DirBrowserFormAction() override;
		void prepare() override;
		void init() override;
		KeyMapHintEntry* get_keymap_hint() override;

		void set_dir(const std::string& d)
		{
			dir = d;
		}

		std::string id() const override
		{
			return "filebrowser";
		}
		std::string title() override;

	private:
		void process_operation(Operation op,
							   bool automatic = false,
							   std::vector<std::string>* args = nullptr) override;

		std::string add_directory(std::string dirname);
		std::string get_rwx(unsigned short val);

		std::string get_owner(uid_t uid);
		std::string get_group(gid_t gid);
		std::string
		get_formatted_dirname(std::string dirname, char ftype, mode_t mode);

		std::string cwd;
		std::string dir;

	};

} // namespace newsboat

#endif //NEWSBOAT_DIRBROWSERFORMACTION_H

#ifndef NEWSBOAT_DIRBROWSERFORMACTION_H
#define NEWSBOAT_DIRBROWSERFORMACTION_H

#include <sys/stat.h>
#include <grp.h>

#include "configcontainer.h"
#include "formaction.h"

namespace newsboat {

	class DirBrowserFormAction : public FormAction {
	public:
		DirBrowserFormAction(View*, std::string formstr, ConfigContainer* cfg);
		~DirBrowserFormAction() override;
		void prepare() override;
		void init() override;
		KeyMapHintEntry* get_keymap_hint() override;

		void set_dir(const std::string& d)
		{
			dir = d;
		}

		std::string id() const override
		{
			return "filebrowser";
		}
		std::string title() override;

	private:
		void process_operation(Operation op,
							   bool automatic = false,
							   std::vector<std::string>* args = nullptr) override;

		std::string add_directory(std::string dirname);
		std::string get_rwx(unsigned short val);

		std::string get_owner(uid_t uid);
		std::string get_group(gid_t gid);
		std::string
		get_formatted_dirname(std::string dirname, char ftype, mode_t mode);

		std::string cwd;
		std::string dir;

	};

} // namespace newsboat

#endif //NEWSBOAT_DIRBROWSERFORMACTION_H

Fix DirBrowserFormAction build on FreeBSD


#ifndef _TILESET_H_
#define _TILESET_H_

#include <SDL.h>

//#define TILESET_ROW_LENGTH	8

typedef struct tileset
{
	SDL_Surface *image;
	SDL_Rect *clip;
	int length;
} tileset;

int tilesetLoad(tileset *tSet, char *fileName, int width, int height, int rowLen, int length);
void tilesetUnload(tileset *tSet);

#endif /* _TILESET_H_ */

#ifndef _TILESET_H_
#define _TILESET_H_

#include <SDL.h>

typedef struct tileset
{
	SDL_Surface *image;
	SDL_Rect *clip;
	int length;
} tileset;

int tilesetLoad(tileset *tSet, char *fileName, int width, int height, int rowLen, int length);
void tilesetUnload(tileset *tSet);

#endif /* _TILESET_H_ */

Remove redundant commended out code

Remove redundant commended out code


/* Preprocessor defines added by opencl compiler
 * #define CONFIGS_PER_PROC
 */

__kernel void start_trampoline(__global char *match_configs,
				__global char *output)
{

	__private unsigned int i;
	for (i = 0; i < 256; i++) {
		output[i] = CONFIGS_PER_PROC;
	}
	write_mem_fence(CLK_GLOBAL_MEM_FENCE);
	return;

}

/* Preprocessor defines added by opencl compiler
 * #define CONFIGS_PER_PROC
 */

__kernel void start_trampoline(__global char *match_configs,
				__global char *output)
{
	__private unsigned int i, startloc;
	// Per worker match configs.
	__private char local_match_configs[CONFIGS_PER_PROC * sizeof(char) * 4];

	// Read in per worker match configs
	startloc = get_local_id(0) * CONFIGS_PER_PROC * 4;
	for (i = 0; i < CONFIGS_PER_PROC * 4; i++)
		local_match_configs[i] = match_configs[startloc + i];

	for (i = 0; i < 256; i++) {
		output[i] = CONFIGS_PER_PROC;
	}
	write_mem_fence(CLK_GLOBAL_MEM_FENCE);
	return;

}

Load match configs into each local proc.


// Calculates the 45th Fibonacci number with a visual indicator.
#include <stdio.h>
#include <assert.h>
#include <libdill.h>

// Calculates Fibonacci of x.
static int fib(int x)
{
	// Need to yield or spinner will not have any time to spin.
	int rc = yield();
	assert(rc == 0);

	if (x < 2) return x;
	return fib(x - 1) + fib(x - 2);
}

coroutine void spinner(int delay)
{
	const char spinChars[] = {'-', '\\', '|', '/'};
	while (1) {
		for (int i = 0; i < sizeof(spinChars); i++) {
			printf("\r%c", spinChars[i]);
			msleep(now() + delay);
		}
	}
}

int main()
{
	// Turn off buffering on stdout otherwise we won't see the spinner.
	setbuf(stdout, NULL);

	int rc = go(spinner(100));
	assert(rc != -1);

	const int n = 45;
	int fibN = fib(n);
	printf("\rFibonacci(%d) = %d\n", n, fibN);
}

// Calculates the 45th Fibonacci number with a visual indicator.
// Note: using yield() in fib() may allow the spinner to actually spin, but
// fib() takes a lot longer to complete. E.g. Over 2 minutes with yield()
// vs. 10 seconds without it.
#include <stdio.h>
#include <assert.h>
#include <libdill.h>

// Calculates Fibonacci of x.
static int fib(int x)
{
	// Need to yield or spinner will not have any time to spin.
	int rc = yield();
	assert(rc == 0);

	if (x < 2) return x;
	return fib(x - 1) + fib(x - 2);
}

coroutine void spinner(int delay)
{
	const char spinChars[] = {'-', '\\', '|', '/'};
	while (1) {
		for (int i = 0; i < sizeof(spinChars); i++) {
			printf("\r%c", spinChars[i]);
			msleep(now() + delay);
		}
	}
}

int main()
{
	// Turn off buffering on stdout otherwise we won't see the spinner.
	setbuf(stdout, NULL);

	int rc = go(spinner(500));
	assert(rc != -1);

	const int n = 45;
	int fibN = fib(n);
	printf("\rFibonacci(%d) = %d\n", n, fibN);
}

Add note about using yield().

Add note about using yield().


#include <stdlib.h>
#include <stdio.h>
#include types.c
#include <string.h>

/* We can:
   Set something equal to something
   Function calls
   Function definitions
   Returning things -- delimiter '<'
   Printing things
   Iffing */

struct call parseCall(char* statement);
struct function parseFunction(char* statement);

char* fixSpacing(char* code) {
  char* fixedCode = calloc(sizeof(char), strlen(code) + 1);
  fixedCode = strcpy(fixedCode, code);
  char* doubleSpace = strstr(fixedCode, "  ");
  char* movingIndex;
  for( ; doubleSpace; doubleSpace = strstr(fixedCode, "  ")) {
    for(movingIndex = doubleSpace; movingIndex&; movingIndex++) {
      movingIndex[0] = movingIndex[1];
    }
  }
  return fixedCode;
}

struct statement* parse(char* code) {
  char* regCode = fixSpacing(code);
  int n = 0;
  int i;
  for(i = 0; regCode[i]; i++) {
    if(regCode[i] == ' ') {
      n++;
    }
  }
  char** spcTokens = calloc(sizeof(char*), n+1);

#include <stdlib.h>
#include <stdio.h>
#include types.c
#include <string.h>

/* We can:
   Set something equal to something
   Function calls
   Function definitions
   Returning things -- delimiter '<'
   Printing things
   Iffing */

struct call parseCall(char* statement);
struct function parseFunction(char* statement);

char* fixSpacing(char* code) {
  char* fixedCode = malloc(sizeof(char) * (strlen(code) + 1));
  fixedCode = strcpy(fixedCode, code);
  char* doubleSpace = strstr(fixedCode, "  ");
  char* movingIndex;
  for( ; doubleSpace; doubleSpace = strstr(fixedCode, "  ")) {
    for(movingIndex = doubleSpace; movingIndex&; movingIndex++) {
      movingIndex[0] = movingIndex[1];
    }
  }
  return fixedCode;
}

char** spcTokenize(char* regCode) {
  int n = 0;
  int i;
  for(i = 0; regCode[i]; i++) {
    if(regCode[i] == ' ') {
      n++;
    }
  }
  char** spcTokens = malloc(sizeof(char*) * (n+1));
  int k;
  for(i = 0; i < n+1; i++) {
    k = strchr(regCode, ' ') - regCode;
    regCode[k] = NULL;
    spcTokens[i] = regCode + k + 1;
  }
}

Refactor the space tokenizer to be its own function; parse() no longer exists.


// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

// Multiply-included file, no traditional include guard.

#include "atom/common/api/api_messages.h"
#include "chrome/common/print_messages.h"
#include "chrome/common/tts_messages.h"
#include "chrome/common/widevine_cdm_messages.h"
#include "chrome/common/chrome_utility_messages.h"

Fix linking problem with IPC::MessageT

Fix linking problem with IPC::MessageT

IPC::MessageT<ChromeUtilityHostMsg_ProcessStarted_Meta, std::__1::tuple<>, void>::MessageT(IPC::Routing)


/* Boolean object interface */

typedef PyIntObject PyBoolObject;

extern DL_IMPORT(PyTypeObject) PyBool_Type;

#define PyBool_Check(x) ((x)->ob_type == &PyBool_Type)

/* Py_False and Py_True are the only two bools in existence.
Don't forget to apply Py_INCREF() when returning either!!! */

/* Don't use these directly */
extern DL_IMPORT(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct;

/* Use these macros */
#define Py_False ((PyObject *) &_Py_ZeroStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)

/* Function to return a bool from a C long */
PyObject *PyBool_FromLong(long);

/* Boolean object interface */

#ifndef Py_BOOLOBJECT_H
#define Py_BOOLOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif

typedef PyIntObject PyBoolObject;

extern DL_IMPORT(PyTypeObject) PyBool_Type;

#define PyBool_Check(x) ((x)->ob_type == &PyBool_Type)

/* Py_False and Py_True are the only two bools in existence.
Don't forget to apply Py_INCREF() when returning either!!! */

/* Don't use these directly */
extern DL_IMPORT(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct;

/* Use these macros */
#define Py_False ((PyObject *) &_Py_ZeroStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)

/* Function to return a bool from a C long */
PyObject *PyBool_FromLong(long);

#ifdef __cplusplus
}
#endif
#endif /* !Py_BOOLOBJECT_H */

Add standard header preamble and footer, a-la intobject.h. Main purpose is extern "C" for C++ programs.


#include <math.h>
#include <stdio.h>

int main() {
    double r1, x1, y1, r2, x2, y2;
    double distance;

    while (scanf("%lf %lf %lf %lf %lf %lf", &r1, &x1, &y1, &r2, &x2, &y2) != EOF) {
        distance = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));

        if (r1 >= distance + r2) {
            puts("RICO");
        } else {
            puts("MORTO");
        }
    }

    return 0;
}

Solve Fire Flowers in c

Solve Fire Flowers in c


#include <gst/gst.h>
#include "kms-core.h"

static GstElement *pipe = NULL;
static G_LOCK_DEFINE(mutex);
static gboolean init = FALSE;

static gboolean
bus_watch(GstBus *bus, GstMessage *message, gpointer data) {
	KMS_LOG_DEBUG("TODO: implement bus watcher\n");
	return TRUE;
}

void
kms_init(gint *argc, gchar **argv[]) {
	G_LOCK(mutex);
	if (!init) {
		GstBus *bus;

		g_type_init();
		gst_init(argc, argv);
		pipe = gst_pipeline_new(NULL);
		gst_element_set_state(pipe, GST_STATE_PLAYING);

		bus = gst_element_get_bus(pipe);
		gst_bus_add_watch(bus, bus_watch, NULL);
		init = TRUE;
	}
	G_UNLOCK(mutex);
}

GstElement*
kms_get_pipeline() {
	return pipe;
}

#include <gst/gst.h>
#include "kms-core.h"

static GstElement *pipe = NULL;
static G_LOCK_DEFINE(mutex);
static gboolean init = FALSE;

static gpointer
gstreamer_thread(gpointer data) {
	GMainLoop *loop;
	loop = g_main_loop_new(NULL, TRUE);
	g_main_loop_run(loop);
	return NULL;
}

void
kms_init(gint *argc, gchar **argv[]) {
	G_LOCK(mutex);
	if (!init) {
		GstBus *bus;

		g_type_init();
		gst_init(argc, argv);
		pipe = gst_pipeline_new(NULL);
		gst_element_set_state(pipe, GST_STATE_PLAYING);

		bus = gst_element_get_bus(pipe);
		gst_bus_add_watch(bus, gst_bus_async_signal_func, NULL);

		g_thread_create(gstreamer_thread, NULL, TRUE, NULL);

		init = TRUE;
	}
	G_UNLOCK(mutex);
}

GstElement*
kms_get_pipeline() {
	return pipe;
}

Make all bus events to be signals

Make all bus events to be signals


#ifndef _EFFECTLESS
#define EFFECTLESS

/*
Macros without multiple execution of side-effects.
*/

/*
Generic min and max without double execution of side-effects:
  http://stackoverflow.com/questions/3437404/min-and-max-in-c
*/

#define _CHOOSE(boolop, a, b, uid) \
  ({                               \
    decltype(a) _a_ ## uid = (a);  \
    decltype(b) _b_ ## uid = (b);  \
    (a) boolop (b) ? (a) : (b);    \
  })
#undef MIN
#undef MAX
#define MIN(a, b) _CHOOSE(<, a, b, __COUNTER__)
#define MAX(a, b) _CHOOSE(>, a, b, __COUNTER__)

#endif

#ifndef _EFFECTLESS
#define EFFECTLESS

/*
Macros without multiple execution of side-effects.
*/

/*
Generic min and max without double execution of side-effects:
  http://stackoverflow.com/questions/3437404/min-and-max-in-c
*/

#define _CHOOSE(boolop, a, b, uid)                                  \
  ({                                                                \
    decltype(a) _a_ ## uid = (a);                                   \
    decltype(b) _b_ ## uid = (b);                                   \
    (_a_ ## uid) boolop (_b_ ## uid) ? (_a_ ## uid) : (_b_ ## uid); \
  })
#undef MIN
#undef MAX
#define MIN(a, b) _CHOOSE(<, a, b, __COUNTER__)
#define MAX(a, b) _CHOOSE(>, a, b, __COUNTER__)

#endif

Fix `_CHOOSE` to use the copies instead of double execution of side-effects (issue reported by tromp at bitcointalk.org)


/*
 * This file is part of Kotaka, a mud library for DGD
 * http://github.com/shentino/kotaka
 *
 * Copyright (C) 2009, 2012, 2013, 2014  Raymond Jennings
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <kotaka/paths/bigstruct.h>
#include <kotaka/paths/system.h>
#include <kotaka/privilege.h>

inherit LIB_INITD;
inherit UTILITY_COMPILE;

static void create()
{
	KERNELD->set_global_access("Help", 1);

	load_dir("obj", 1);
	load_dir("sys", 1);
}

void do_upgrade()
{
	INITD->shutdown_subsystem("Help");
}

Make gutted help subsystem shut itself down on next upgrade


/* SPDX-License-Identifier: BSD-2-Clause */

#include <tilck/common/basic_defs.h>
#include <tilck/common/string_util.h>
#include <tilck/kernel/kmalloc.h>
#include <tilck/kernel/cmdline.h>

#include "termutil.h"
#include "dp_int.h"

static debug_kmalloc_chunk_stat chunks_arr[1024];

static void dp_show_chunks(void)
{
   debug_kmalloc_stats stats;
   int row = dp_screen_start_row;

   if (!KMALLOC_HEAVY_STATS) {
      dp_writeln("Not available: recompile with KMALLOC_HEAVY_STATS=1");
      return;
   }

   debug_kmalloc_get_stats(&stats);

   if (stats.chunk_sizes_count > ARRAY_SIZE(chunks_arr)) {
      dp_writeln("Not enough space in chunks_arr!");
      return;
   }

   debug_kmalloc_get_chunks_info(chunks_arr);

   for (size_t i = 0; i < stats.chunk_sizes_count; i++) {
      dp_writeln("Size: %8u -> %6u allocs",
                 chunks_arr[i].size, chunks_arr[i].count);
   }
}

static dp_screen dp_chunks_screen =
{
   .index = 5,
   .label = "MemChunks",
   .draw_func = dp_show_chunks,
   .on_keypress_func = NULL,
};

__attribute__((constructor))
static void dp_chunks_init(void)
{
   dp_register_screen(&dp_chunks_screen);
}

[debugpanel] Add the MemChunks screen [for kmalloc heavy stats]


#include "../sccs.h"

#ifdef WIN32

#include <psapi.h>

u64
maxrss(void)
{
	PROCESS_MEMORY_COUNTERS cnt;

	if (GetProcessMemoryInfo(GetCurrentProcess(), &cnt, sizeof(cnt))) {
		return (cnt.PeakWorkingSetSize);
	}
	return (0);
}

#else

#include <sys/resource.h>

u64
maxrss(void)
{
	struct rusage ru;

	if (!getrusage(RUSAGE_SELF, &ru)) return (1024 * ru.ru_maxrss);
	return (0);
}

#endif

#include "../sccs.h"

#ifdef WIN32

#include <psapi.h>

u64
maxrss(void)
{
	PROCESS_MEMORY_COUNTERS cnt;

	if (GetProcessMemoryInfo(GetCurrentProcess(), &cnt, sizeof(cnt))) {
		return (cnt.PeakWorkingSetSize);
	}
	return (0);
}

#else

#include <sys/resource.h>

u64
maxrss(void)
{
	struct rusage	ru;
#if defined(sun)
	int		factor = getpagesize();
#elif defined(__APPLE__)
	int	factor = 1;
#else
	int	factor = 1024;
#endif

	if (getrusage(RUSAGE_SELF, &ru)) return (0);

	return (ru.ru_maxrss * factor);
}

#endif

Adjust for the fact that MacOS X and Solaris report maxrss in
different units.

bk: 5489ebbfQIN1Wbpf9Qa4aY-VK6F8xw


#ifndef __ZERO_FIELD_H__
#define __ZERO_FIELD_H__

#include "Field.h"

namespace cigma {
    class ZeroField;
}

class cigma::ZeroField : public cigma::Field
{
public:
    ZeroField();
    ~ZeroField();
    void set_shape(int dim, int rank);

public:
    int n_dim() { return dim; }
    int n_rank() { return rank; }
    FieldType getType() { return USER_FIELD; }

public:
    bool eval(double *point, double *value);

public:
    int dim;
    int rank;
};

#endif

#ifndef __ZERO_FIELD_H__
#define __ZERO_FIELD_H__

#include "UserField.h"

namespace cigma {
    class ZeroField;
}

class cigma::ZeroField : public cigma::UserField
{
public:
    ZeroField();
    ~ZeroField();
    void set_shape(int dim, int rank);

public:
    int n_dim() { return dim; }
    int n_rank() { return rank; }

public:
    bool eval(double *point, double *value);

public:
    int dim;
    int rank;
};

#endif

Make zero a user field

Make zero a user field


#ifndef PSTOREJNI_H
#define PSTOREJNI_H

#include <inttypes.h>

#ifdef __i386__
  #define LONG_TO_PTR(ptr) (void *) (uint32_t) ptr
#elif __X86_64__
  #define LONG_TO_PTR(ptr) (void *) ptr
#endif

#define PTR_TO_LONG(ptr) (long) ptr

#endif

java: Add 'LONG_TO_PTR' and 'PTR_TO_LONG' macros

Signed-off-by: Karim Osman <94396faf6cc817be76165477038b3cfa832e89a4@reaktor.fi>
Signed-off-by: Pekka Enberg <add4fcd06328a394f0ad91feda7ee057316dc5ed@kernel.org>


//
//  MORK.h
//  MORK
//
//  Created by Nolan Carroll on 4/23/15.
//  Copyright (c) 2015 Medidata Solutions. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "ORKTaskResult+MORK.h"
#import "ORKQuestionResult+MORK.h"

//! Project version number for MORK.
FOUNDATION_EXPORT double MORKVersionNumber;

//! Project version string for MORK.
FOUNDATION_EXPORT const unsigned char MORKVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <MORK/PublicHeader.h>

//
//  MORK.h
//  MORK
//
//  Created by Nolan Carroll on 4/23/15.
//  Copyright (c) 2015 Medidata Solutions. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "ORKCollectionResult+MORK.h"
#import "ORKQuestionResult+MORK.h"

//! Project version number for MORK.
FOUNDATION_EXPORT double MORKVersionNumber;

//! Project version string for MORK.
FOUNDATION_EXPORT const unsigned char MORKVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <MORK/PublicHeader.h>

Update import in main header file

Update import in main header file


Clean up versioning commit hash.

Clean up versioning commit hash.


// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
// Check that no empty blocks are generated for nested ifs.

extern void func();

int f0(int val) {
  if (val == 0) {
    func();
  } else if (val == 1) {
    func();
  }
  return 0;
}

// CHECK-LABEL: define i32 @f0
// CHECK: call void {{.*}} @func
// CHECK: call void {{.*}} @func
// CHECK: br label %[[RETBLOCK1:[^ ]*]]
// CHECK: [[RETBLOCK1]]:
// CHECK-NOT: br label
// CHECK: ret i32

int f1(int val, int g) {
  if (val == 0)
    if (g == 1) {
      func();
    }
  return 0;
}

// CHECK-LABEL: define i32 @f1
// CHECK: call void {{.*}} @func
// CHECK: br label %[[RETBLOCK2:[^ ]*]]
// CHECK: [[RETBLOCK2]]:
// CHECK-NOT: br label
// CHECK: ret i32

// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
// Check that no empty blocks are generated for nested ifs.

extern void func();

int f0(int val) {
  if (val == 0) {
    func();
  } else if (val == 1) {
    func();
  }
  return 0;
}

// CHECK-LABEL: define {{.*}} i32 @f0
// CHECK: call void {{.*}} @func
// CHECK: call void {{.*}} @func
// CHECK: br label %[[RETBLOCK1:[^ ]*]]
// CHECK: [[RETBLOCK1]]:
// CHECK-NOT: br label
// CHECK: ret i32

int f1(int val, int g) {
  if (val == 0)
    if (g == 1) {
      func();
    }
  return 0;
}

// CHECK-LABEL: define {{.*}} i32 @f1
// CHECK: call void {{.*}} @func
// CHECK: br label %[[RETBLOCK2:[^ ]*]]
// CHECK: [[RETBLOCK2]]:
// CHECK-NOT: br label
// CHECK: ret i32

Fix test submitted with r275115 (failed on ppc64 buildbots).

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@275127 91177308-0d34-0410-b5e6-96231b3b80d8


// Taken from: http://stackoverflow.com/a/14537855

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#ifndef M_PI
#define M_PI 3.14159265358979324
#endif

#define N 16

#define kiss_fft_scalar double
#include "kiss_fftr.h"

void TestFftReal(const char *title, const kiss_fft_scalar in[N],
                 kiss_fft_cpx out[N / 2 + 1]) {
  kiss_fftr_cfg cfg;

  printf("%s\n", title);

  if ((cfg = kiss_fftr_alloc(N, 0 /*is_inverse_fft*/, NULL, NULL)) != NULL) {
    size_t i;

    kiss_fftr(cfg, in, out);
    free(cfg);

    for (i = 0; i < N; i++) {
      printf(" in[%2zu] = %+f    ", i, in[i]);
      if (i < N / 2 + 1)
        printf("out[%2zu] = %+f , %+f", i, out[i].r, out[i].i);
      printf("\n");
    }
  } else {
    printf("not enough memory?\n");
    exit(-1);
  }
}

int main(void) {
  kiss_fft_scalar in[N];
  kiss_fft_cpx out[N / 2 + 1];
  size_t i;

  for (i = 0; i < N; i++)
    in[i] = 0;
  TestFftReal("Zeroes (real)", in, out);

  for (i = 0; i < N; i++)
    in[i] = 1;
  TestFftReal("Ones (real)", in, out);

  for (i = 0; i < N; i++)
    in[i] = sin(2 * M_PI * 4 * i / N);
  TestFftReal("SineWave (real)", in, out);

  return 0;
}

Add a program to test Kiss FFT.

Add a program to test Kiss FFT.


/*

Small library to test implementation of option -Z and FPART_PARTERRNO

Inspired from:
https://lists.gnu.org/archive/html/bug-gnulib/2016-06/msg00058.html

$ cc -fPIC -shared -o libfake_readdir.so fake_readdir.c

$ mkdir -p /tmp/test/a/b/c/d/e/f/g/h/i/j
$ LD_PRELOAD=./libfake_readdir.so fpart -L -E -zz -Z -f 2 -vvv /tmp/test

$ mkdir -p /tmp/test/b/{c,d}
$ touch /tmp/test/b/{c,d}/{a..z}
$ LD_PRELOAD=./libfake_readdir.so fpart -L -E -zz -Z -f 2 -vvv /tmp/test/b

*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>

#include <dlfcn.h>

static size_t counter = 0;
#define FAIL_EVERY 7

static struct dirent *(*real_readdir)(DIR *dirp) = NULL;

struct dirent *readdir(DIR *dirp)
{
    /* Keep original pointer */
    if(real_readdir == NULL)
        real_readdir = dlsym(RTLD_NEXT, "readdir");

    counter++;

    if((counter % FAIL_EVERY) == 0) {
        fprintf(stderr, "XXX Failing call to readdir(), counter = %zu\n", counter);
        fflush(stderr);
        errno=EIO;
        return NULL;
    }

    return real_readdir(dirp);
}

Add a small wrapper to simulate readdir() errors

Useful to test recently-patched embedded fts and option -Z


Use ! instead of |, looks nicer also saves two bytes


#include <unistd.h>

int main() {
  char c;
  while (read(STDIN_FILENO, &c, 1) == 1 && c!= 'q');
  return 0;
}

#include <termios.h>
#include <unistd.h>

void enableRawMode() {
  struct termios raw;

  tcgetattr(STDIN_FILENO, &raw);

  raw.c_lflag &= ~(ECHO);

  tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
}

int main() {
  enableRawMode();

  char c;
  while (read(STDIN_FILENO, &c, 1) == 1 && c!= 'q');
  return 0;
}

Enable raw mode in terminal

Enable raw mode in terminal


/* This is not a proper strtod() implementation, but sufficient for Python.
   Python won't detect floating point constant overflow, though. */

extern int strlen();
extern double atof();

double
strtod(p, pp)
	char *p;
	char **pp;
{
	if (pp)
		*pp = p + strlen(p);
	return atof(p);
}

/* This is not a proper strtod() implementation, but sufficient for Python.
   Python won't detect floating point constant overflow, though. */

extern int errno;

extern int strlen();
extern double atof();

double
strtod(p, pp)
	char *p;
	char **pp;
{
	double res;

	if (pp)
		*pp = p + strlen(p);
	res = atof(p);
	errno = 0;
	return res;

}

Clear errno, just to be sure.

Clear errno, just to be sure.


@class NSString;

/**
 * Returns a string appropriate for displaying in test output
 * from the provided value.
 *
 * @param value A value that will show up in a test's output.
 *
 * @return The string that is returned can be
 *     customized per type by conforming a type to the `TestOutputStringConvertible`
 *     protocol. When stringifying a non-`TestOutputStringConvertible` type, this
 *     function will return the value's debug description and then its
 *     normal description if available and in that order. Otherwise it
 *     will return the result of constructing a string from the value.
 *
 * @see `TestOutputStringConvertible`
 */
extern NSString *_Nonnull NMBStringify(id _Nullable anyObject) __attribute__((warn_unused_result));

@class NSString;

/**
 * Returns a string appropriate for displaying in test output
 * from the provided value.
 *
 * @param anyObject A value that will show up in a test's output.
 *
 * @return The string that is returned can be
 *     customized per type by conforming a type to the `TestOutputStringConvertible`
 *     protocol. When stringifying a non-`TestOutputStringConvertible` type, this
 *     function will return the value's debug description and then its
 *     normal description if available and in that order. Otherwise it
 *     will return the result of constructing a string from the value.
 *
 * @see `TestOutputStringConvertible`
 */
extern NSString *_Nonnull NMBStringify(id _Nullable anyObject) __attribute__((warn_unused_result));

Fix documentation parameter name warnings

value is not matching `anyObject`


#pragma once

#include <Windows.h>

#include <string>

class DiskInfo {
public:
    DiskInfo(wchar_t driveLetter);

    static std::wstring DriveFileName(wchar_t &driveLetter);
    static std::wstring DriveFileName(std::wstring &driveLetter);

private:
    HANDLE _devHandle;
};

#pragma once

#include <Windows.h>

#include <string>

class DiskInfo {
public:
    DiskInfo(wchar_t driveLetter);

    static std::wstring DriveFileName(wchar_t &driveLetter);
    static std::wstring DriveFileName(std::wstring &driveLetter);

private:
    HANDLE _devHandle;
    std::wstring _productId;
    std::wstring _vendorId;
};

Add member variables for storing disk info


#include <stdio.h>

int main() {
  char palavrasecreta[20];

  sprintf(palavrasecreta, "MELANCIA");

  printf("%s\n", palavrasecreta);

  /*
  palavrasecreta[0] = 'M';
  palavrasecreta[1] = 'E';
  palavrasecreta[2] = 'L';
  palavrasecreta[3] = 'A';
  palavrasecreta[4] = 'N';
  palavrasecreta[5] = 'C';
  palavrasecreta[6] = 'I';
  palavrasecreta[7] = 'A';

  printf("%c%c%c%c%c%c%c%c\n", palavrasecreta[0], palavrasecreta[1], palavrasecreta[2], palavrasecreta[3], palavrasecreta[4], palavrasecreta[5], palavrasecreta[6], palavrasecreta[7]);
  */
}

#include <stdio.h>

int main() {
  char palavrasecreta[20];

  sprintf(palavrasecreta, "MELANCIA");

  printf("%s\n", palavrasecreta);

  /*
  palavrasecreta[0] = 'M';
  palavrasecreta[1] = 'E';
  palavrasecreta[2] = 'L';
  palavrasecreta[3] = 'A';
  palavrasecreta[4] = 'N';
  palavrasecreta[5] = 'C';
  palavrasecreta[6] = 'I';
  palavrasecreta[7] = 'A';
  palavrasecreta[8] = '\0';

  printf("%c%c%c%c%c%c%c%c\n", palavrasecreta[0], palavrasecreta[1], palavrasecreta[2], palavrasecreta[3], palavrasecreta[4], palavrasecreta[5], palavrasecreta[6], palavrasecreta[7]);
  */
}

Update files, Alura, Introdução a C - Parte 2, Aula 2.2


//
//  BBAAPIErrors.h
//  BBAAPI
//
//  Created by Owen Worley on 11/08/2014.
//  Copyright (c) 2014 Blinkbox Books. All rights reserved.
//

NS_ENUM(NSInteger, BBAAPIError) {
    /**
     *  Used when needed parameter is not supplied to the method
     *  or when object is supplied but it has wrong type or
     *  for example one of it's needed properties is not set
     */
    BBAAPIWrongUsage = 700,
    /**
     *  Error returned when for any reason API call cannot connect to the server
     */
    BBAAPIErrorCouldNotConnect = 701,
    /**
     *  Returned when call cannot be authenticated, or when server returns 401
     */
    BBAAPIErrorUnauthorised = 702,
    /**
     *  Used when server cannot find a resource and returns 404
     */
    BBAAPIErrorNotFound = 703,
    /**
     *  Used when server returns 500
     */
    BBAAPIServerError = 704,
    /**
     *  Used when server returns 403
     */
    BBAAPIErrorForbidden = 705,
    /**
     *  Used when we cannot decode or read data returned from the server
     */
    BBAAPIUnreadableData = 706,
};

//
//  BBAAPIErrors.h
//  BBAAPI
//
//  Created by Owen Worley on 11/08/2014.
//  Copyright (c) 2014 Blinkbox Books. All rights reserved.
//

NS_ENUM(NSInteger, BBAAPIError) {
    /**
     *  Used when needed parameter is not supplied to the method
     *  or when object is supplied but it has wrong type or
     *  for example one of it's needed properties is not set
     */
    BBAAPIWrongUsage = 700,
    /**
     *  Error returned when for any reason API call cannot connect to the server
     */
    BBAAPIErrorCouldNotConnect = 701,
    /**
     *  Returned when call cannot be authenticated, or when server returns 401
     */
    BBAAPIErrorUnauthorised = 702,
    /**
     *  Used when server cannot find a resource and returns 404
     */
    BBAAPIErrorNotFound = 703,
    /**
     *  Used when server returns 500
     */
    BBAAPIServerError = 704,
    /**
     *  Used when server returns 403
     */
    BBAAPIErrorForbidden = 705,
    /**
     *  Used when we cannot decode or read data returned from the server
     */
    BBAAPIUnreadableData = 706,
    /**
     *  Used when the server returns a 400 (Bad Request)
     */
    BBAAPIBadRequest = 707,
};

Add Bad Request error code

Add Bad Request error code


#ifndef SQREDIR_BLOCKLIST_H
#define SQREDIR_BLOCKLIST_H

#include <cstdio>
#include <string>

using namespace std;

// reads the given configuration file
// returns: true/false for success/failure
bool read_config(string filename);

// tries to match the Squid request & writes the response to the output stream
// input: a request line as passed by Squid
// output: response output stream (usually stdout)
void match_and_reply(const char* input, FILE* output);

#endif

#ifndef SQREDIR_BLOCKLIST_H
#define SQREDIR_BLOCKLIST_H

#include <cstdio>
#include <string>

// reads the given configuration file
// returns: true/false for success/failure
bool read_config(std::string filename);

// tries to match the Squid request & writes the response to the output stream
// input: a request line as passed by Squid
// output: response output stream (usually stdout)
void match_and_reply(const char* input, FILE* output);

#endif

Remove 'using' directive from header, explicitly qualify std namespace.


/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetMCDecayTree.h
 */

#ifndef _JPETMCHIT_H_
#define _JPETMCHIT_H_

#include "./JPetHit/JPetHit.h"

/**
 * @brief Data class representing a hit of a photon in the scintillator strip based on Monte Carlo simulation.
 *
 */
class JPetMCDecayTree : public TObject
{

public:
  JPetMCDecayTree();

private:

  UInt_t fMCMCDecayTreeIndex = 0u;
  UInt_t fMCVtxIndex = 0u;

  UInt_t fnVertices = 0u;
  UInt_t fnTracks = 0u;
  // add also track and vertices structures

  ClassDef(JPetMCDecayTree, 1);
};

#endif

/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetMCDecayTree.h
 */

#ifndef _JPETMCDECAYTREE_H_
#define _JPETMCDECAYTREE_H_

#include "./JPetHit/JPetHit.h"

/**
 * @brief Data class representing a hit of a photon in the scintillator strip based on Monte Carlo simulation.
 *
 */
class JPetMCDecayTree : public TObject {

public:
  JPetMCDecayTree();

private:
  UInt_t fMCMCDecayTreeIndex = 0u;
  UInt_t fMCVtxIndex = 0u;

  UInt_t fnVertices = 0u;
  UInt_t fnTracks = 0u;
  // add also track and vertices structures

  ClassDef(JPetMCDecayTree, 1);
};

#endif

Change header guard name to do not colide with JPetMCHit


#pragma once
#include "MileObject.h"

namespace Mile
{
    /**
    * ActorComponent Actor ߰  ִ    ϴ Component ⺻ ŬԴϴ.
    */
    class Actor;
    class MILE_API ActorComponent : public MileObject
    {
        friend Actor;
    public:
        ActorComponent( const MString& NewName ) :
            bIsTick( false ),
            OwnerPrivate( nullptr ),
            TickPriority( 0 ),
            MileObject( NewName )
        {
        }

        ActorComponent( ActorComponent&& MovedObject ) :
            OwnerPrivate( MovedObject.OwnerPrivate ),
            bIsTick( MovedObject.bIsTick ),
            TickPriority( MovedObject.TickPriority ),
            MileObject( std::move( MovedObject ) )
        {
            this->SetOwner( MovedObject.GetOwner( ) );
            MovedObject.SetOwner( nullptr );
            MovedObject.bIsTick = false;
            MovedObject.TickPriority = UINT64_MAX;
        }

        ActorComponent& operator=( ActorComponent&& MovedObject ) = delete;

        void SetOwner( Actor* Owner, bool bIsDetachBeforeSetNewOwner = true );
        virtual void SetOwnerRecursively( Actor* NewOwner, bool bIsDetachBeforeSetNewOwner = true );
        FORCEINLINE Actor* GetOwner( ) const
        {
            return OwnerPrivate;
        }

        virtual void TickComponent( float DeltaTime ) {}

    private:
        Actor* OwnerPrivate;

    public:
        bool    bIsTick;
        uint64  TickPriority;

    };
}

#pragma once
#include "MileObject.h"

namespace Mile
{
    /**
    * ActorComponent Actor ߰  ִ    ϴ Component ⺻ ŬԴϴ.
    */
    class Actor;
    class MILE_API ActorComponent : public MileObject
    {
        friend Actor;
    public:
        ActorComponent( const MString& NewName ) :
            bIsTick( false ),
            OwnerPrivate( nullptr ),
            TickPriority( 0 ),
            MileObject( NewName )
        {
        }

        ActorComponent( ActorComponent&& MovedObject ) :
            OwnerPrivate( MovedObject.OwnerPrivate ),
            bIsTick( MovedObject.bIsTick ),
            TickPriority( MovedObject.TickPriority ),
            MileObject( std::move( MovedObject ) )
        {
            this->SetOwner( MovedObject.GetOwner( ) );
            MovedObject.SetOwner( nullptr );
            MovedObject.bIsTick = false;
            MovedObject.TickPriority = UINT64_MAX;
        }

        ActorComponent& operator=( ActorComponent&& MovedObject ) = delete;

        void SetOwner( Actor* Owner, bool bIsDetachBeforeSetNewOwner = true );
        virtual void SetOwnerRecursively( Actor* NewOwner, bool bIsDetachBeforeSetNewOwner = true );
        FORCEINLINE Actor* GetOwner( ) const
        {
            return OwnerPrivate;
        }

        virtual void Tick( float DeltaTime ) { UNUSED_PARAM( DeltaTime ); }

    private:
        Actor* OwnerPrivate;
        bool    bIsTick;
        uint64  TickPriority;

    };
}

Delete TickComponent ( because of tick manager )


#pragma once
#include "esp32-hal.h"
#ifndef ESP32
#define ESP32
#endif

#define FASTLED_ESP32

#if CONFIG_IDF_TARGET_ARCH_RISCV
#define FASTLED_RISCV
#endif

#if CONFIG_IDF_TARGET_ARCH_XTENSA || CONFIG_XTENSA_IMPL
#define FASTLED_XTENSA
#endif

// Use system millis timer
#define FASTLED_HAS_MILLIS

typedef volatile uint32_t RoReg;
typedef volatile uint32_t RwReg;
typedef unsigned long prog_uint32_t;

// Default to NOT using PROGMEM here
#ifndef FASTLED_USE_PROGMEM
# define FASTLED_USE_PROGMEM 0
#endif

#ifndef FASTLED_ALLOW_INTERRUPTS
# define FASTLED_ALLOW_INTERRUPTS 1
# define INTERRUPT_THRESHOLD 0
#endif

#define NEED_CXX_BITS

// These can be overridden
#   define FASTLED_ESP32_RAW_PIN_ORDER

#pragma once
#include "esp32-hal.h"
#ifndef ESP32
#define ESP32
#endif

#define FASTLED_ESP32

#if CONFIG_IDF_TARGET_ARCH_RISCV
#define FASTLED_RISCV
#else
#define FASTLED_XTENSA
#endif

// Handling for older versions of ESP32 Arduino core
#if !defined(ESP_IDF_VERSION)
// Older versions of ESP_IDF only supported ESP32
#define CONFIG_IDF_TARGET_ESP32 1
// Define missing version macros.  Hard code older version 3.0 since actual version is unknown
#define ESP_IDF_VERSION_VAL(major, minor, patch) ((major << 16) | (minor << 8) | (patch))
#define ESP_IDF_VERSION ESP_IDF_VERSION_VAL(3, 0, 0)
#endif

// Use system millis timer
#define FASTLED_HAS_MILLIS

typedef volatile uint32_t RoReg;
typedef volatile uint32_t RwReg;
typedef unsigned long prog_uint32_t;

// Default to NOT using PROGMEM here
#ifndef FASTLED_USE_PROGMEM
# define FASTLED_USE_PROGMEM 0
#endif

#ifndef FASTLED_ALLOW_INTERRUPTS
# define FASTLED_ALLOW_INTERRUPTS 1
# define INTERRUPT_THRESHOLD 0
#endif

#define NEED_CXX_BITS

// These can be overridden
#   define FASTLED_ESP32_RAW_PIN_ORDER

Improve compatibility with older ESP32 Arduino core versions


/*
 * This file is part of Kotaka, a mud library for DGD
 * http://github.com/shentino/kotaka
 *
 * Copyright (C) 2012  Raymond Jennings
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <kotaka/assert.h>
#include <kotaka/paths.h>
#include <kotaka/privilege.h>
#include <kotaka/log.h>

private object root;

static void create()
{
	root = previous_object();
}

static void destruct()
{
}

static void check_caller()
{
	ACCESS_CHECK(previous_object() == root);
}

nomask object query_root()
{
	return root;
}

/*
 * This file is part of Kotaka, a mud library for DGD
 * http://github.com/shentino/kotaka
 *
 * Copyright (C) 2012  Raymond Jennings
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <kotaka/assert.h>
#include <kotaka/paths.h>
#include <kotaka/privilege.h>
#include <kotaka/log.h>

private object root;

static void create()
{
	root = previous_object();
}

static void destruct()
{
}

static void check_caller()
{
	ASSERT(root);

	ACCESS_CHECK(previous_object() == root);
}

nomask object query_root()
{
	return root;
}

Add another debug check to bigstructs

Add another debug check to bigstructs


#if defined(WIN32) || defined(_WIN32) || \
    defined(__WIN32) && !defined(__CYGWIN__)
#include <BaseTsd.h>
#include <windows.h>
typedef SSIZE_T ssize_t;
#endif
#ifndef _WIN32
#include <unistd.h>
#endif
#include <inttypes.h>

typedef char *String;
typedef char *Pattern;
typedef int64_t Long;

#if defined NDEBUG
#define CHK_INDEX(i, n)
#else

#define CHK_INDEX_FORMAT_STRING ":%u: bad index: %zd < %zd\n"

#define CHK_INDEX(i, n)                                                    \
    do {                                                                   \
        size_t __si = (size_t)i;                                           \
        size_t __ni = (size_t)n;                                           \
        if (!(__si < __ni)) {                                              \
            printf(__FILE__ CHK_INDEX_FORMAT_STRING, __LINE__, (ssize_t)i, \
                   (ssize_t)n);                                            \
            abort();                                                       \
        }                                                                  \
    } while (0)
#endif

// Array
typedef struct {
    size_t len;
    size_t capacity;
    void *data;
} Array;

// Lambdas
typedef struct {
    void *callback;
    void *env;
    void *delete;
    void *copy;
} Lambda;

typedef void *LambdaEnv;

#if defined(WIN32) || defined(_WIN32) || \
    defined(__WIN32) && !defined(__CYGWIN__)
#include <BaseTsd.h>
#include <windows.h>
typedef SSIZE_T ssize_t;
#define SIZE_T_FORMAT_SPECIFIER "%ld"
#endif
#ifndef _WIN32
#include <unistd.h>
#define SIZE_T_FORMAT_SPECIFIER "%zd"
#endif
#include <inttypes.h>

typedef char *String;
typedef char *Pattern;
typedef int64_t Long;

#if defined NDEBUG
#define CHK_INDEX(i, n)
#else

#define CHK_INDEX_FORMAT_STRING ":%u: bad index: " SIZE_T_FORMAT_SPECIFIER " < " SIZE_T_FORMAT_SPECIFIER "\n"

#define CHK_INDEX(i, n)                                                    \
    do {                                                                   \
        size_t __si = (size_t)i;                                           \
        size_t __ni = (size_t)n;                                           \
        if (!(__si < __ni)) {                                              \
            printf(__FILE__ CHK_INDEX_FORMAT_STRING, __LINE__, (ssize_t)i, \
                   (ssize_t)n);                                            \
            abort();                                                       \
        }                                                                  \
    } while (0)
#endif

// Array
typedef struct {
    size_t len;
    size_t capacity;
    void *data;
} Array;

// Lambdas
typedef struct {
    void *callback;
    void *env;
    void *delete;
    void *copy;
} Lambda;

typedef void *LambdaEnv;

Use other format specifers on Windows.

Use other format specifers on Windows.


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBitmap.h"
#include "SkCodec.h"

/**
 *  Abstract subclass of SkBitmap's allocator.
 *  Allows the allocator to indicate if the memory it allocates
 *  is zero initialized.
 */
class SkBRDAllocator : public SkBitmap::Allocator {
public:

    /**
     *  Indicates if the memory allocated by this allocator is
     *  zero initialized.
     */
    virtual SkCodec::ZeroInitialized zeroInit() const = 0;
};

Add an Allocator interface that indicates if memory is zero init

This is the first step in a three part change:
(1) Skia: Add SkBRDAllocator.
(2) Android: Make JavaPixelAllocator and RecyclingClippingPixelAllocator
             implement SkBRDAllocator.
(3) Skia: Change SkBitmapRegionDecoder to use SkBRDAllocator and take
          advantage of zero allocated memory when possible.

BUG=skia:

Review URL: https://codereview.chromium.org/1423253004


/* Copyright 2014 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef __CROS_EC_CONFIG_CORE_H
#define __CROS_EC_CONFIG_CORE_H

/* Linker binary architecture and format */
#define BFD_ARCH arm
#define BFD_FORMAT "elf32-littlearm"

/* Emulate the CLZ/CTZ instructions since the CPU core is lacking support */
#define CONFIG_SOFTWARE_CLZ
#define CONFIG_SOFTWARE_CTZ
#define CONFIG_SOFTWARE_PANIC

#define CONFIG_ASSEMBLY_MULA32

#endif /* __CROS_EC_CONFIG_CORE_H */

/* Copyright 2014 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef __CROS_EC_CONFIG_CORE_H
#define __CROS_EC_CONFIG_CORE_H

/* Linker binary architecture and format */
#define BFD_ARCH arm
#define BFD_FORMAT "elf32-littlearm"

/*
 * Emulate the CLZ/CTZ instructions since the CPU core is lacking support.
 * When building with clang, we rely on compiler_rt to provide this support.
 */
#ifndef __clang__
#define CONFIG_SOFTWARE_CLZ
#define CONFIG_SOFTWARE_CTZ
#endif /* __clang__ */
#define CONFIG_SOFTWARE_PANIC

#define CONFIG_ASSEMBLY_MULA32

#endif /* __CROS_EC_CONFIG_CORE_H */

Use compiler_rt version of clz and ctz

core/cortex-m0: Use compiler_rt version of clz and ctz

Use __clzsi2 and __ctzsi2 from compiler_rt instead of our own version.
Using the compiler_rt versions result in a slightly smaller image.

servo_micro before this change:
RO: 18744 bytes in flash remaining
RW: 23192 bytes in flash remaining

servo_micro after this change:
RO: 18808 bytes in flash remaining
RW: 23256 bytes in flash remaining

BRANCH=none
BUG=b:172020503
TEST=CC=clang make BOARD=servo_micro
TEST=make buildall

Signed-off-by: Tom Hughes <fc5c12f30a5ed2baa0581f44ee14ad1eb7b20d83@chromium.org>
Change-Id: Ibc19a3670127dde211fb20d247c1284d0aec5f61
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/ec/+/3199739
Reviewed-by: Jack Rosenthal <d3f605bef1867f59845d4ce6e4f83b8dc9e4e0ae@chromium.org>


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkStippleMaskFilter_DEFINED
#define SkStippleMaskFilter_DEFINED

#include "SkMaskFilter.h"

/**
 * Simple MaskFilter that creates a screen door stipple pattern
 */
class SkStippleMaskFilter : public SkMaskFilter {
public:
    SkStippleMaskFilter() : INHERITED() {
    }

    virtual bool filterMask(SkMask* dst, const SkMask& src,
                            const SkMatrix& matrix,
                            SkIPoint* margin) SK_OVERRIDE;

    // getFormat is from SkMaskFilter
    virtual SkMask::Format getFormat() SK_OVERRIDE {
        return SkMask::kA8_Format;
    }

    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkStippleMaskFilter);

protected:
    SkStippleMaskFilter::SkStippleMaskFilter(SkFlattenableReadBuffer& buffer)
    : SkMaskFilter(buffer) {
    }

private:
    typedef SkMaskFilter INHERITED;
};

#endif // SkStippleMaskFilter_DEFINED

/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkStippleMaskFilter_DEFINED
#define SkStippleMaskFilter_DEFINED

#include "SkMaskFilter.h"

/**
 * Simple MaskFilter that creates a screen door stipple pattern
 */
class SkStippleMaskFilter : public SkMaskFilter {
public:
    SkStippleMaskFilter() : INHERITED() {
    }

    virtual bool filterMask(SkMask* dst, const SkMask& src,
                            const SkMatrix& matrix,
                            SkIPoint* margin) SK_OVERRIDE;

    // getFormat is from SkMaskFilter
    virtual SkMask::Format getFormat() SK_OVERRIDE {
        return SkMask::kA8_Format;
    }

    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkStippleMaskFilter);

protected:
    SkStippleMaskFilter(SkFlattenableReadBuffer& buffer)
    : SkMaskFilter(buffer) {
    }

private:
    typedef SkMaskFilter INHERITED;
};

#endif // SkStippleMaskFilter_DEFINED

Fix for compiler error in r4154

Fix for compiler error in r4154

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4155 2bbb7eff-a529-9590-31e7-b0007b416f81


#ifndef STRATIFIED_SAMPLER_H
#define STRATIFIED_SAMPLER_H

#include <random>
#include <memory>
#include <array>
#include <vector>
#include "sampler.h"

/*
 * A stratified sampler, generates multipled jittered
 * samples per pixel in its sample region
 */
class StratifiedSampler : public Sampler {
	const int spp;
	std::mt19937 rng;
	std::uniform_real_distribution<float> distrib;

public:
	StratifiedSampler(int x_start, int x_end, int y_start, int y_end, int spp);
	/*
	 * Get some {x, y} positions to sample in the space being sampled
	 * If the sampler has finished sampling samples will be empty
	 */
	void get_samples(std::vector<Sample> &samples) override;
	/*
	 * Get subsamplers that divide the space to be sampled
	 * into count disjoint subsections where each samples a w x h
	 * section of the original sampler
	 */
	std::vector<std::unique_ptr<Sampler>> get_subsamplers(int w, int h) const override;

private:
	/*
	 * Generate a 2d pattern of stratified samples and return them
	 * sample positions will be normalized between [0, 1)
	 */
	void sample2d(std::vector<Sample> &samples);
};

#endif

#ifndef STRATIFIED_SAMPLER_H
#define STRATIFIED_SAMPLER_H

#include <random>
#include <memory>
#include <array>
#include <vector>
#include "sampler.h"

/*
 * A stratified sampler, generates multipled jittered
 * samples per pixel in its sample region
 */
class StratifiedSampler : public Sampler {
	const int spp;
	std::minstd_rand rng;
	std::uniform_real_distribution<float> distrib;

public:
	StratifiedSampler(int x_start, int x_end, int y_start, int y_end, int spp);
	/*
	 * Get some {x, y} positions to sample in the space being sampled
	 * If the sampler has finished sampling samples will be empty
	 */
	void get_samples(std::vector<Sample> &samples) override;
	/*
	 * Get subsamplers that divide the space to be sampled
	 * into count disjoint subsections where each samples a w x h
	 * section of the original sampler
	 */
	std::vector<std::unique_ptr<Sampler>> get_subsamplers(int w, int h) const override;

private:
	/*
	 * Generate a 2d pattern of stratified samples and return them
	 * sample positions will be normalized between [0, 1)
	 */
	void sample2d(std::vector<Sample> &samples);
};

#endif

Fix stratified sampler to use minstd_rand

still unsure why mt19937 suddenly started segfaulting


// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ORBIT_GL_THREAD_STATE_TRACK_H_
#define ORBIT_GL_THREAD_STATE_TRACK_H_

#include "Track.h"

// This is a track dedicated to displaying thread states in different colors
// and with the corresponding tooltips.
// It is a thin sub-track of ThreadTrack, added above the callstack track (EventTrack).
// The colors are determined only by the states, not by the color assigned to the thread.

class ThreadStateTrack final : public Track {
 public:
  ThreadStateTrack(TimeGraph* time_graph, int32_t thread_id);
  Type GetType() const override { return kThreadStateTrack; }

  void Draw(GlCanvas* canvas, PickingMode picking_mode, float z_offset) override;
  void UpdatePrimitives(uint64_t min_tick, uint64_t max_tick, PickingMode picking_mode,
                        float z_offset) override;

  void OnPick(int x, int y) override;
  void OnRelease() override { picked_ = false; };
  float GetHeight() const override { return size_[1]; }

  bool IsEmpty() const;

 private:
  std::string GetThreadStateSliceTooltip(PickingId id) const;
};

#endif  // ORBIT_GL_THREAD_STATE_TRACK_H_

// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ORBIT_GL_THREAD_STATE_TRACK_H_
#define ORBIT_GL_THREAD_STATE_TRACK_H_

#include "Track.h"

// This is a track dedicated to displaying thread states in different colors
// and with the corresponding tooltips.
// It is a thin sub-track of ThreadTrack, added above the callstack track (EventTrack).
// The colors are determined only by the states, not by the color assigned to the thread.

class ThreadStateTrack final : public Track {
 public:
  ThreadStateTrack(TimeGraph* time_graph, int32_t thread_id);
  Type GetType() const override { return kThreadStateTrack; }

  void Draw(GlCanvas* canvas, PickingMode picking_mode, float z_offset) override;
  void UpdatePrimitives(uint64_t min_tick, uint64_t max_tick, PickingMode picking_mode,
                        float z_offset) override;

  void OnPick(int x, int y) override;
  void OnDrag(int, int) override {}
  void OnRelease() override { picked_ = false; };
  float GetHeight() const override { return size_[1]; }

  bool IsEmpty() const;

 private:
  std::string GetThreadStateSliceTooltip(PickingId id) const;
};

#endif  // ORBIT_GL_THREAD_STATE_TRACK_H_

Fix crash when dragging a thread state track

Only when you have enabled track_ordering_feature, this class inherit
OnDrag from Track and crashed.

Related to b/173093860.


/*
 * Copyright 2019 The Project Oak Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef OAK_SERVER_LOGGING_CHANNEL_H
#define OAK_SERVER_LOGGING_CHANNEL_H

#include "oak/server/channel.h"

namespace oak {

// A channel implementation that only has a send half, which logs to stderr the data written to it.
class LoggingChannelHalf final : public ChannelHalf {
 public:
  uint32_t Write(absl::Span<const char> data) override {
    std::string log_message(data.cbegin(), data.cend());
    LOG(INFO) << "LOG: " << log_message;
  };
};

}  // namespace oak

#endif  // OAK_SERVER_LOGGING_CHANNEL_H

/*
 * Copyright 2019 The Project Oak Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef OAK_SERVER_LOGGING_CHANNEL_H
#define OAK_SERVER_LOGGING_CHANNEL_H

#include "oak/server/channel.h"

namespace oak {

// A channel implementation that only has a send half, which logs to stderr the data written to it.
class LoggingChannelHalf final : public ChannelHalf {
 public:
  uint32_t Write(absl::Span<const char> data) override {
    std::string log_message(data.cbegin(), data.cend());
    LOG(INFO) << "LOG: " << log_message;
    return data.size();
  }
};

}  // namespace oak

#endif  // OAK_SERVER_LOGGING_CHANNEL_H

Fix return value for logging channel write


#pragma once

#ifdef _WIN32
#include <SDKDDKVer.h>

//#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#define tstring std::wstring
#define WidenHelper(x)  L##x
#define LITERAL(x) WidenHelper(x)

#else // ifdef _WIN32

#define tstring std::string
#define LITERAL(x) (x)

#endif

/* Don't let Python.h #define (v)snprintf as macro because they are implemented
   properly in Visual Studio since 2015. */
#if defined(_MSC_VER) && _MSC_VER >= 1900
#  define HAVE_SNPRINTF 1
#endif

#include <queue>
#include <random>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include "third_party/spdlog/spdlog.h"

#pragma once

#ifdef _WIN32
#include <SDKDDKVer.h>

//#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#define tstring std::wstring
#define WidenHelper(x)  L##x
#define LITERAL(x) WidenHelper(x)

#else // ifdef _WIN32

#define tstring std::string
#define LITERAL(x) (x)

// Prevents this error: Failed getting file size from fd: Value too large for defined data type
#define _FILE_OFFSET_BITS 64

#endif

/* Don't let Python.h #define (v)snprintf as macro because they are implemented
   properly in Visual Studio since 2015. */
#if defined(_MSC_VER) && _MSC_VER >= 1900
#  define HAVE_SNPRINTF 1
#endif

#include <queue>
#include <random>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include "third_party/spdlog/spdlog.h"

Fix the spdlog issue on 32bit systems: Failed getting file size from fd


// RUN: %llvmgcc %s -S -emit-llvm -o - | llvm-as | llvm-dis | grep llvm.used | grep foo | grep X

int X __attribute__((used));
int Y;

void foo() __attribute__((used));

void foo() {}

// RUN: %llvmgcc %s -S -emit-llvm -o - | llvm-as | llvm-dis | grep llvm.used | grep foo | grep X

int X __attribute__((used));
int Y;

__attribute__((used)) void foo() {}

Adjust this to the wonky syntax that GCC expects.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@30670 91177308-0d34-0410-b5e6-96231b3b80d8


/*-------------------------------------------------------------------------
 *
 * nodes.c
 *	  support code for nodes (now that we get rid of the home-brew
 *	  inheritance system, our support code for nodes get much simpler)
 *
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $PostgreSQL: pgsql/src/backend/nodes/nodes.c,v 1.22 2003/11/29 19:51:49 pgsql Exp $
 *
 * HISTORY
 *	  Andrew Yu			Oct 20, 1994	file creation
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "nodes/nodes.h"

/*
 * Support for newNode() macro
 */

Node	   *newNodeMacroHolder;

/*-------------------------------------------------------------------------
 *
 * nodes.c
 *	  support code for nodes (now that we have removed the home-brew
 *	  inheritance system, our support code for nodes is much simpler)
 *
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $PostgreSQL: pgsql/src/backend/nodes/nodes.c,v 1.23 2004/05/06 06:11:01 neilc Exp $
 *
 * HISTORY
 *	  Andrew Yu			Oct 20, 1994	file creation
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "nodes/nodes.h"

/*
 * Support for newNode() macro
 */

Node	   *newNodeMacroHolder;

Fix grammatical error in comment.

Fix grammatical error in comment.


/*
 * RELIC is an Efficient LIbrary for Cryptography
 * Copyright (C) 2007-2011 RELIC Authors
 *
 * This file is part of RELIC. RELIC is legal property of its developers,
 * whose names are not listed here. Please refer to the COPYRIGHT file
 * for contact information.
 *
 * RELIC is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * RELIC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with RELIC. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file
 *
 * Implementation of AVR-dependent routines.
 *
 * @version $Id$
 * @ingroup arch
 */

/*============================================================================*/
/* Public definitions                                                         */
/*============================================================================*/

void arch_init(void) {
}

void arch_clean(void) {
}

Add missing file for ARCH = AVR.

Add missing file for ARCH = AVR.


//  OCHamcrest by Jon Reid, http://qualitycoding.org/about/
//  Copyright 2015 hamcrest.org. See LICENSE.txt

#import <OCHamcrest/HCDiagnosingMatcher.h>

/*!
 * @abstract Does executing a block throw an exception which satisfies a nested matcher?
 */
@interface HCThrowsException : HCDiagnosingMatcher

- (id)initWithExceptionMatcher:(id)exceptionMatcher;

@end

FOUNDATION_EXPORT id HC_throwsException(id exceptionMatcher);

#ifndef HC_DISABLE_SHORT_SYNTAX
/*!
 * @abstract Creates a matcher that matches when the examined object is a block which, when
 * executed, throws an exception satisfying the specified matcher.
 * @param exceptionMatcher The matcher to satisfy when passed the exception.
 * @discussion
 * Example

 *
assertThat(^{ [obj somethingBad]; }, throwsException(anything())

 *
 * Name Clash

 * In the event of a name clash, #define HC_DISABLE_SHORT_SYNTAX and use the synonym
 * HC_throwsException instead.
 */
static inline id throwsException(id exceptionMatcher)
{
    return HC_throwsException(exceptionMatcher);
}
#endif

//  OCHamcrest by Jon Reid, http://qualitycoding.org/about/
//  Copyright 2015 hamcrest.org. See LICENSE.txt

#import <OCHamcrest/HCDiagnosingMatcher.h>

/*!
 * @abstract Does executing a block throw an exception which satisfies a nested matcher?
 */
@interface HCThrowsException : HCDiagnosingMatcher

- (id)initWithExceptionMatcher:(id)exceptionMatcher;

@end

FOUNDATION_EXPORT id HC_throwsException(id exceptionMatcher);

#ifndef HC_DISABLE_SHORT_SYNTAX
/*!
 * @abstract Creates a matcher that matches when the examined object is a block which, when
 * executed, throws an exception satisfying the specified matcher.
 * @param exceptionMatcher The matcher to satisfy when passed the exception.
 * @discussion
 * Example

 *
assertThat(^{ [obj somethingBad]; }, throwsException(hasProperty(@"reason", @"EXPECTED REASON")))

 *
 * Name Clash

 * In the event of a name clash, #define HC_DISABLE_SHORT_SYNTAX and use the synonym
 * HC_throwsException instead.
 */
static inline id throwsException(id exceptionMatcher)
{
    return HC_throwsException(exceptionMatcher);
}
#endif

Improve throwsException example to use hasProperty


/*
 * Copyright (c) 2012-2016 Israel Jacquez
 * See LICENSE for details.
 *
 * Israel Jacquez <mrkotfw@gmail.com>
 */

#include <stdlib.h>

#include <vdp1.h>
#include <vdp2.h>
#include <vdp2/tvmd.h>
#include <vdp2/vram.h>

#include <cons.h>

void __noreturn
internal_exception_show(const char *buffer)
{
        /* Reset the VDP1 */
        vdp1_init();

        /* Reset the VDP2 */
        vdp2_init();
        vdp2_tvmd_display_res_set(TVMD_INTERLACE_NONE, TVMD_HORZ_NORMAL_A,
            TVMD_VERT_224);
        vdp2_scrn_back_screen_color_set(VRAM_ADDR_4MBIT(0, 0x01FFFE),
            COLOR_RGB555(0, 7, 0));
        vdp2_tvmd_display_set();

        cons_init(CONS_DRIVER_VDP2, 40, 28);
        cons_buffer(buffer);

        vdp2_tvmd_vblank_out_wait();
        vdp2_tvmd_vblank_in_wait();
        vdp2_commit();
        cons_flush();

        abort();
}

/*
 * Copyright (c) 2012-2016 Israel Jacquez
 * See LICENSE for details.
 *
 * Israel Jacquez <mrkotfw@gmail.com>
 */

#include <stdlib.h>

#include <vdp1.h>
#include <vdp2.h>
#include <vdp2/tvmd.h>
#include <vdp2/vram.h>

#include <cons.h>

void __noreturn
internal_exception_show(const char *buffer)
{
        /* Reset the VDP1 */
        vdp1_init();

        /* Reset the VDP2 */
        vdp2_init();
        vdp2_tvmd_display_res_set(TVMD_INTERLACE_NONE, TVMD_HORZ_NORMAL_A,
            TVMD_VERT_224);
        vdp2_scrn_back_screen_color_set(VRAM_ADDR_4MBIT(0, 0x01FFFE),
            COLOR_RGB555(0, 7, 0));

        /* Set sprite to type 0 and set its priority to 0 (invisible) */
        vdp2_sprite_type_set(0);
        vdp2_sprite_priority_set(0, 0);

        vdp2_tvmd_display_set();

        cons_init(CONS_DRIVER_VDP2, 40, 28);
        cons_buffer(buffer);

        vdp2_tvmd_vblank_out_wait();
        vdp2_tvmd_vblank_in_wait();
        vdp2_commit();
        cons_flush();

        abort();
}

Hide VDP1 even if FB hasn't been erased and changed


/** Author : Paul TREHIOU & Victor SENE
 *  Date : November 2014
 **/

/**
 * Declaration Point structure
 * x - real wich is the abscisse of the point
 * y - real wich is the ordinate of the point
 */
 typedef struct
 {
 	float x;
 	float y;
 }Point;

 /**
  * Function wich create a point with a specified abscisse and ordinate
  * abscisse - real
  * ordinate - real
  * return a new point
  */
createPoint(float abscisse, float ordinate);

typedef struct pointelem{

	Point value;
	pointelem* next;
	pointelem* before;

}PointElement;

typedef PointElement* Polygon;

Add some spaces and enters

Add some spaces and enters


// RUN: clang-cc -emit-llvm %s -o - | not grep ptrtoint

// Make sure we generate something sane instead of a ptrtoint
union x {long long b;union x* a;} r = {.a = &r};

// RUN: clang-cc -emit-llvm %s -o - -triple i686-pc-linux-gnu | grep "bitcast (%0\* @r to %union.x\*), \[4 x i8\] zeroinitializer"

// Make sure we generate something sane instead of a ptrtoint
union x {long long b;union x* a;} r = {.a = &r};

Make test a bit more precise.

Make test a bit more precise.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@79073 91177308-0d34-0410-b5e6-96231b3b80d8


#include <stdio.h>
#include <stdlib.h>

/* This is a code for binary search tree basic implementtion */

//Contains code for PreOrder, InOrder and PostOrder Traversals i.e. Depth First

typedef struct node{
	int data;
	struct node* left;
	struct node* right;
} node;

node* head;

node* create(int data){
	node* temp = (node* ) malloc(sizeof(node));
	temp->data = data;
	temp->left = NULL;
	temp->right = NULL;
	return temp;
}

node* insert(node* current, int data){

	if(head == NULL){
		node* temp;
		temp = create(data);
		head = temp;
		return temp;

	}
	else{
		if(current == NULL){
			node* temp;
			temp = create(data);
			return temp;
		}

		if(data <= current->data){

			current->left = insert(current->left,data);
		}
		else if ( data > current->data){

			current->right = insert(current->right,data);
		}

	}
	return current;

}

void print_preorder_all(node* temp){
	if(temp != NULL){

		printf("data %d ",temp->data);

		if(temp->left != NULL){
		printf("left child %d ",temp->left->data);}
		else {
			printf("left child NULL ");
		}
		if(temp->right != NULL){
		printf("right child %d \n",temp->right->data);}
		else {
			printf("right child NULL \n");
		}

		print_preorder_all(temp->left);
		print_preorder_all(temp->right);
	}
	return;
}

/* Size of tree i.e. number of nodes */

int min_tree(node* root){
	node* temp;
	temp =root;
	if(temp == NULL ){
		return 0;
	}
	else{
		while (temp->left!=NULL){
			temp = temp->left;
		}
		return temp->data;
	}

}

int max_tree(node* root){
	node* temp;
	temp =root;
	if(temp == NULL ){
		return 0;
	}
	else{
		while (temp->right!=NULL){
			temp = temp->right;
		}
		return temp->data;
	}
}

int main(){
	head = NULL;
	node* temp;

	int A[7] = {9,4,15,2,6,12,17};
	int i;
	for(i =0 ; i<7 ; i ++){
		temp = insert(head,A[i]);
	}

	printf("all info\n");
	print_preorder_all(head);
	printf("\n");

	printf("The min of tree is %d \n",min_tree(head));
	printf("The max of tree is %d \n",max_tree(head));

	return 0;
}

Add BST find min and max value node

Add BST find min and max value node


//
//  GTDiffFile.h
//  ObjectiveGitFramework
//
//  Created by Danny Greg on 30/11/2012.
//  Copyright (c) 2012 GitHub, Inc. All rights reserved.
//

#import "git2.h"

// Flags which may be set on the file.
//
// See diff.h for individual documentation.
typedef enum : git_diff_file_flag_t {
	GTDiffFileFlagValidOID = GIT_DIFF_FILE_VALID_OID,
	GTDiffFileFlagFreePath = GIT_DIFF_FILE_FREE_PATH,
	GTDiffFileFlagBinary = GIT_DIFF_FILE_BINARY,
	GTDiffFileFlagNotBinary = GIT_DIFF_FILE_NOT_BINARY,
	GTDiffFileFlagFreeData = GIT_DIFF_FILE_FREE_DATA,
	GTDiffFileFlagUnmapData = GIT_DIFF_FILE_UNMAP_DATA,
	GTDiffFileFlagNoData = GIT_DIFF_FILE_NO_DATA,
} GTDiffFileFlag;

// A class representing a file on one side of a diff.
@interface GTDiffFile : NSObject

// The location within the working directory of the file.
@property (nonatomic, readonly, copy) NSString *path;

// The size (in bytes) of the file.
@property (nonatomic, readonly) NSUInteger size;

// Any flags set on the file (see `GTDiffFileFlag` for more info).
@property (nonatomic, readonly) GTDiffFileFlag flags;

// The mode of the file.
@property (nonatomic, readonly) mode_t mode;

// Designated initialiser.
- (instancetype)initWithGitDiffFile:(git_diff_file)file;

@end

//
//  GTDiffFile.h
//  ObjectiveGitFramework
//
//  Created by Danny Greg on 30/11/2012.
//  Copyright (c) 2012 GitHub, Inc. All rights reserved.
//

#import "git2.h"

// Flags which may be set on the file.
//
// See diff.h for individual documentation.
typedef enum : git_diff_flag_t {
	GTDiffFileFlagValidOID = GIT_DIFF_FLAG_VALID_OID,
	GTDiffFileFlagBinary = GIT_DIFF_FLAG_BINARY,
	GTDiffFileFlagNotBinary = GIT_DIFF_FLAG_NOT_BINARY,
} GTDiffFileFlag;

// A class representing a file on one side of a diff.
@interface GTDiffFile : NSObject

// The location within the working directory of the file.
@property (nonatomic, readonly, copy) NSString *path;

// The size (in bytes) of the file.
@property (nonatomic, readonly) NSUInteger size;

// Any flags set on the file (see `GTDiffFileFlag` for more info).
@property (nonatomic, readonly) GTDiffFileFlag flags;

// The mode of the file.
@property (nonatomic, readonly) mode_t mode;

// Designated initialiser.
- (instancetype)initWithGitDiffFile:(git_diff_file)file;

@end

Remove some diff file flags

Remove some diff file flags


#ifndef	EVENT_SYSTEM_H
#define	EVENT_SYSTEM_H

#include <event/event_thread.h>

/*
 * XXX
 * This is kind of an awful shim while we move
 * towards something thread-oriented.
 */

class EventSystem {
	EventThread td_;
private:
	EventSystem(void)
	: td_()
	{ }

	~EventSystem()
	{ }

public:
	Action *poll(const EventPoll::Type& type, int fd, EventCallback *cb)
	{
		return (td_.poll(type, fd, cb));
	}

	Action *register_interest(const EventInterest& interest, Callback *cb)
	{
		return (td_.register_interest(interest, cb));
	}

	Action *schedule(Callback *cb)
	{
		return (td_.schedule(cb));
	}

	Action *timeout(unsigned ms, Callback *cb)
	{
		return (td_.timeout(ms, cb));
	}

	void start(void)
	{
		td_.start();

		td_.join();
	}

	static EventSystem *instance(void)
	{
		static EventSystem *instance;

		if (instance == NULL)
			instance = new EventSystem();
		return (instance);
	}
};

#endif /* !EVENT_SYSTEM_H */

Add EventSystem shim missed in r588.

Add EventSystem shim missed in r588.


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Morwenn
 *
 * 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.
 */
#include <stdexcept>
#include <utility>

////////////////////////////////////////////////////////////
// Move-only type for benchmarks
//
// std::sort and std::stable_sort are supposed to be able to
// sort collections of types that are move-only and that are
// not default-constructible. The class template move_only
// wraps such a type and can be fed to algorithms to check
// whether they still compile.
//
// Additionally, move_only detects attempts to read the value
// after a move has been performed and throws an exceptions
// when it happens.
//

template<typename T>
struct move_only
{
    // Not default-constructible
    move_only() = delete;

    // Move-only
    move_only(const move_only&) = delete;
    move_only& operator=(const move_only&) = delete;

    // Can be constructed from a T for convenience
    move_only(const T& value):
        can_read(true),
        value(value)
    {}

    // Move operators

    move_only(move_only&& other):
        can_read(true),
        value(std::move(other.value))
    {
        if (not std::exchange(other.can_read, false))
        {
            throw std::logic_error("illegal read from a moved-from value");
        }
    }

    auto operator=(move_only&& other)
        -> move_only&
    {
        if (&other != this)
        {
            if (not std::exchange(other.can_read, false))
            {
                throw std::logic_error("illegal read from a moved-from value");
            }
            can_read = true;
            value = std::move(other.value);
        }
        return *this;
    }

    // Whether the value can be read
    bool can_read = false;
    // Actual value
    T value;
};

template<typename T>
auto operator<(const move_only<T>& lhs, const move_only<T>& rhs)
    -> bool
{
    return lhs.value < rhs.value;
}

Add move-only type for testing/benchmarking.


// Copyright (c) 2015 Yandex LLC. All rights reserved.
// Author: Vasily Chekalkin <bacek@yandex-team.ru>

#ifndef SDCH_REQUEST_CONTEXT_H_
#define SDCH_REQUEST_CONTEXT_H_

extern "C" {

#include <ngx_config.h>
#include <nginx.h>
#include <ngx_core.h>
#include <ngx_http.h>

}

namespace sdch {

class Handler;

// Context used inside nginx to keep relevant data.
struct RequestContext {
    ngx_http_request_t  *request;

    ngx_chain_t         *in;
    ngx_chain_t         *free;
    ngx_chain_t         *busy;
    ngx_chain_t         *out;
    ngx_chain_t        **last_out;

    ngx_chain_t         *copied;
    ngx_chain_t         *copy_buf;

    ngx_buf_t           *in_buf;
    ngx_buf_t           *out_buf;
    ngx_int_t            bufs;

    struct sdch_dict    *dict;
    struct sdch_dict     fdict;

    unsigned             started:1;
    unsigned             flush:4;
    unsigned             redo:1;
    unsigned             done:1;
    unsigned             nomem:1;
    unsigned             buffering:1;

    unsigned             store:1;

    size_t               zin;
    size_t               zout;

    z_stream             zstream;

    struct sv            *stuc;
};

 private:
};

}  // namespace sdch

#endif  // SDCH_REQUEST_CONTEXT_H_

Add copy-pasted stub for future RequestContext


#ifndef _ASM_POWERPC_CODE_PATCHING_H
#define _ASM_POWERPC_CODE_PATCHING_H

/*
 * Copyright 2008, Michael Ellerman, IBM Corporation.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 */

/* Flags for create_branch:
 * "b"   == create_branch(addr, target, 0);
 * "ba"  == create_branch(addr, target, BRANCH_ABSOLUTE);
 * "bl"  == create_branch(addr, target, BRANCH_SET_LINK);
 * "bla" == create_branch(addr, target, BRANCH_ABSOLUTE | BRANCH_SET_LINK);
 */
#define BRANCH_SET_LINK	0x1
#define BRANCH_ABSOLUTE	0x2

unsigned int create_branch(const unsigned int *addr,
			   unsigned long target, int flags);
void patch_branch(unsigned int *addr, unsigned long target, int flags);
void patch_instruction(unsigned int *addr, unsigned int instr);

#endif /* _ASM_POWERPC_CODE_PATCHING_H */

#ifndef _ASM_POWERPC_CODE_PATCHING_H
#define _ASM_POWERPC_CODE_PATCHING_H

/*
 * Copyright 2008, Michael Ellerman, IBM Corporation.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 */

#include <asm/types.h>

/* Flags for create_branch:
 * "b"   == create_branch(addr, target, 0);
 * "ba"  == create_branch(addr, target, BRANCH_ABSOLUTE);
 * "bl"  == create_branch(addr, target, BRANCH_SET_LINK);
 * "bla" == create_branch(addr, target, BRANCH_ABSOLUTE | BRANCH_SET_LINK);
 */
#define BRANCH_SET_LINK	0x1
#define BRANCH_ABSOLUTE	0x2

unsigned int create_branch(const unsigned int *addr,
			   unsigned long target, int flags);
void patch_branch(unsigned int *addr, unsigned long target, int flags);
void patch_instruction(unsigned int *addr, unsigned int instr);

static inline unsigned long ppc_function_entry(void *func)
{
#ifdef CONFIG_PPC64
	/*
	 * On PPC64 the function pointer actually points to the function's
	 * descriptor. The first entry in the descriptor is the address
	 * of the function text.
	 */
	return ((func_descr_t *)func)->entry;
#else
	return (unsigned long)func;
#endif
}

#endif /* _ASM_POWERPC_CODE_PATCHING_H */

powerpc: Add ppc_function_entry() which gets the entry point for a function

Because function pointers point to different things on 32-bit vs 64-bit,
add a macro that deals with dereferencing the OPD on 64-bit.  The soon to
be merged ftrace wants this, as well as other code I am working on.

Signed-off-by: Michael Ellerman <17b9e1c64588c7fa6419b4d29dc1f4426279ba01@ellerman.id.au>
Acked-by: Kumar Gala <383ef5577c6e1178b93f59ec8d0936f76d2a98c4@kernel.crashing.org>
Signed-off-by: Paul Mackerras <19a0ba370c443ba08d20b5061586430ab449ee8c@samba.org>


#pragma once

#include <stdexcept>

namespace erebus {

/**
 * This is a exception for the case a stated file doenst exist.
 */
class file_not_found : public std::runtime_error {
public:
	/**
	 * Constructor.
	 */
	explicit file_not_found(const std::string& msg) : std::runtime_error(msg) {

	}
};

}

Add file not found exception

Add file not found exception


/**
* \file socket.c - Windows Socket Abstractions
*
* Copyright (c) 2015 Michael Casadevall
*
* 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.
**/

#define __FTL_INTERNAL
#include "ftl.h"

#include <unistd.h>

void ftl_init_sockets() {
  //BSD sockets are smarter and don't need silly init
}

int ftl_close_socket(int sock) {
  return close(sock);
}

char * ftl_get_socket_error() {
  return strerror(errno);
}

Add POSIX files, yay. Almost fixes compile


#include "ug_thread_safe_counter.h"
#pragma once
// obsolete once intrusive_ref_counter is available everywhere

namespace Moses {

  class reference_counter
  {
  public:
    friend void intrusive_ptr_add_ref(reference_counter* p)
    {
      if (p) ++p->m_refcount;
    }
    friend void intrusive_ptr_release(reference_counter* p)
    {
      if (p && --p->m_refcount == 0)
	delete p;
    }
  protected:
    reference_counter() {}
    virtual ~reference_counter() {};
  private:
    mutable ThreadSafeCounter m_refcount;
  };
}

#include "ug_thread_safe_counter.h"
#pragma once
// obsolete once intrusive_ref_counter is available everywhere

namespace Moses {

  class reference_counter
  {
  public:
    friend void intrusive_ptr_add_ref(reference_counter const* p)
    {
      if (p) ++p->m_refcount;
    }
    friend void intrusive_ptr_release(reference_counter const* p)
    {
      if (p && --p->m_refcount == 0)
	delete p;
    }
  protected:
    reference_counter() {}
    virtual ~reference_counter() {};
  private:
    mutable ThreadSafeCounter m_refcount;
  };
}

Allow intrusive pointers to const objects.


#include "log.h"
#include <stdio.h>
#include <stdarg.h>

void debug(const char* format, ...) {
#ifdef __DEBUG__
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
#endif // __DEBUG__
}

void initializeLogging() { }

#include "log.h"
#include <stdio.h>
#include <stdarg.h>

void debugNoNewline(const char* format, ...) {
#ifdef __DEBUG__
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
#endif // __DEBUG__
}

void initializeLogging() { }

Rename test suite version of debug to match the header.


#ifndef UTIL_H
#define UTIL_H

/*** Utility functions ***/

#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);

#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)

#endif /* UTIL_H */

#ifndef UTIL_H
#define UTIL_H

/*** Utility functions ***/

#define ALLOC(type) ALLOC_N(type, 1)
#define ALLOC_N(type, n) ((type*) xmalloc(sizeof(type) * (n)))
#define MEMCPY(dst, src, type) MEMCPY_N(dst, src, type, 1)
#define MEMCPY_N(dst, src, type, n) (memcpy((dst), (src), sizeof(type) * (n)))
void *xmalloc(size_t);
char *hextoa(const char *, int);

#define STARTS_WITH(x, y) (strncmp((x), (y), strlen(y)) == 0)

#endif /* UTIL_H */

Add MEMCPY and MEMCPY_N macros

Add MEMCPY and MEMCPY_N macros