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

/*
   To run: ./lwm2m-sample-client <client name> [-b] [-s SEC_MODE]
   If [-b] argument is not given:
   This LWM2M client sample will try to connect to a LWM2M server @ locahost:5683
   (or @ localhost:5684 if -s is given).
   If a location object is created by the LWM2M server, it will report its location
   every one second.

   If [-b] argument is given:
   This LWM2M client sample expect a server-initiated bootstrap.
   If it doesn't happen in 5s, it will try to connect to a LWM2M bootstrap server
   @ localhost:5783 and perform client-initiated bootstrap.
   If the bootstrap is successful, it will try to connect and register with the
   server(s) received in the bootstrap information.
 */

#include "sol-lwm2m-client.h"
#include "sol-mainloop.h"
#include "sol-vector.h"
#include "sol-util.h"

#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>

#define LOCATION_OBJ_ID (6)
#define LOCATION_OBJ_LATITUDE_RES_ID (0)
#define LOCATION_OBJ_LONGITUDE_RES_ID (1)
#define LOCATION_OBJ_TIMESTAMP_RES_ID (5)

#define ONE_SECOND (1000)
#define LIFETIME (60)

#define SERVER_OBJ_ID (1)
#define SERVER_OBJ_SHORT_RES_ID (0)
#define SERVER_OBJ_LIFETIME_RES_ID (1)
#define SERVER_OBJ_BINDING_RES_ID (7)
#define SERVER_OBJ_REGISTRATION_UPDATE_RES_ID (8)

#define ACCESS_CONTROL_OBJ_ID (2)
#define ACCESS_CONTROL_OBJ_OBJECT_RES_ID (0)
#define ACCESS_CONTROL_OBJ_INSTANCE_RES_ID (1)
#define ACCESS_CONTROL_OBJ_ACL_RES_ID (2)
#define ACCESS_CONTROL_OBJ_OWNER_RES_ID (3)

#define SECURITY_OBJ_ID (0)
#define SECURITY_SERVER_URI_RES_ID (0)
#define SECURITY_IS_BOOTSTRAP_RES_ID (1)
#define SECURITY_SECURITY_MODE_RES_ID (2)
#define SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID (3)
#define SECURITY_SERVER_PUBLIC_KEY_RES_ID (4)
#define SECURITY_SECRET_KEY_RES_ID (5)
#define SECURITY_SERVER_ID_RES_ID (10)
#define SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID (11)
#define SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID (12)

#define PSK_KEY_LEN 16
#define RPK_PRIVATE_KEY_LEN 32
#define RPK_PUBLIC_KEY_LEN (2 * RPK_PRIVATE_KEY_LEN)

//FIXME: UNSEC: Hardcoded Crypto Keys
#define CLIENT_BS_PSK_ID ("cli1-bs")
#define CLIENT_BS_PSK_KEY ("FEDCBA9876543210")
#define CLIENT_SERVER_PSK_ID ("cli1")
#define CLIENT_SERVER_PSK_KEY ("0123456789ABCDEF")

#define CLIENT_PRIVATE_KEY ("D9E2707A72DA6A0504995C86EDDBE3EFC7F1CD74838F7570C8072D0A76261BD4")
#define CLIENT_PUBLIC_KEY ("D055EE14084D6E0615599DB583913E4A3E4526A2704D61F27A4CCFBA9758EF9A" \
    "B418B64AFE8030DA1DDCF4F42E2F2631D043B1FB03E22F4D17DE43F9F9ADEE70")
#define BS_SERVER_PUBLIC_KEY ("cd4110e97bbd6e7e5a800028079d02915c70b915ea4596402098deea585eb7ad" \
    "f3e080487327f70758b13bc0583f4293d13288a0164a8e324779aa4f7ada26c1")
#define SERVER_PUBLIC_KEY ("3b88c213ca5ccfd9c5a7f73715760d7d9a5220768f2992d2628ae1389cbca4c6" \
    "d1b73cc6d61ae58783135749fb03eaaa64a7a1adab8062ed5fc0d7b86ba2d5ca")

struct client_data_ctx {
    bool has_location_instance;
    bool is_bootstrap;
};

struct security_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    struct sol_blob *server_uri;
    bool is_bootstrap;
    int64_t security_mode;
    struct sol_blob *public_key_or_id;
    struct sol_blob *server_public_key;
    struct sol_blob *secret_key;
    int64_t server_id;
    int64_t client_hold_off_time;
    int64_t bootstrap_server_account_timeout;
};

struct server_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    struct sol_blob *binding;
    int64_t server_id;
    int64_t lifetime;
};

struct acl_instance {
    uint16_t key;
    int64_t value;
};

struct access_control_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    int64_t owner_id;
    int64_t object_id;
    int64_t instance_id;
    struct sol_vector acl;
};

struct location_obj_instance_ctx {
    struct sol_timeout *timeout;
    struct sol_lwm2m_client *client;
    double latitude;
    double longitude;
    int64_t timestamp;
};

static struct sol_blob bootstrap_server_addr = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coaps://localhost:5783",
    .size = sizeof("coaps://localhost:5783") - 1,
    .refcnt = 1
};

static struct sol_blob server_addr_coap = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coap://localhost:5683",
    .size = sizeof("coap://localhost:5683") - 1,
    .refcnt = 1
};

static struct sol_blob server_addr_dtls = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coaps://localhost:5684",
    .size = sizeof("coaps://localhost:5684") - 1,
    .refcnt = 1
};

static struct sol_blob binding = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"U",
    .size = sizeof("U") - 1,
    .refcnt = 1
};

static struct sol_blob *
coord_to_str(double d)
{
    int r;
    char *str;
    struct sol_blob *blob;

    r = asprintf(&str, "%g", d);
    if (r < 0) {
        fprintf(stderr, "Could not convert the latitude/longitude to string\n");
        return NULL;
    }

    blob = sol_blob_new(&SOL_BLOB_TYPE_DEFAULT, NULL, str, strlen(str));

    if (!blob) {
        fprintf(stderr, "Could not create a blob to store the latitude/longitude\n");
        free(str);
        return NULL;
    }
    return blob;
}

static bool
change_location(void *data)
{
    struct location_obj_instance_ctx *instance_ctx = data;
    int r = 0;
    static const char *paths[] = { "/6/0/0",
                                   "/6/0/1", "/6/0/5", NULL };

    instance_ctx->latitude = ((double)rand() / (double)RAND_MAX);
    instance_ctx->longitude = ((double)rand() / (double)RAND_MAX);

    instance_ctx->timestamp = (int64_t)time(NULL);

    printf("New latitude: %g - New longitude: %g\n", instance_ctx->latitude,
        instance_ctx->longitude);

    r = sol_lwm2m_client_notify(instance_ctx->client, paths);

    if (r < 0) {
        fprintf(stderr, "Could not notify the observers\n");
    } else
        printf("Sending new location coordinates to the observers\n");

    return true;
}

static int
create_location_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data, struct sol_lwm2m_payload payload)
{
    struct location_obj_instance_ctx *instance_ctx;
    struct client_data_ctx *data_ctx = user_data;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    //Only one location object is allowed
    if (data_ctx->has_location_instance) {
        fprintf(stderr, "Only one location object instance is allowed\n");
        return -EINVAL;
    }

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct location_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for location object context\n");
        return -ENOMEM;
    }

    instance_ctx->timeout = sol_timeout_add(ONE_SECOND, change_location,
        instance_ctx);
    if (!instance_ctx->timeout) {
        fprintf(stderr, "Could not create the client timer\n");
        r = -ENOMEM;
        goto err_free_instance;
    }

    if (payload.payload.tlv_content.len != 3) {
        r = -EINVAL;
        fprintf(stderr, "Missing mandatory fields.\n");
        goto err_free_timeout;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 32);
        double *prop = NULL;

        if (tlv->id == LOCATION_OBJ_LATITUDE_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            prop = &instance_ctx->latitude;
        } else if (tlv->id == LOCATION_OBJ_LONGITUDE_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            prop = &instance_ctx->longitude;
        } else
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->timestamp);

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_timeout;
        }

        if (buf.used) {
            char *endptr = NULL;

            *prop = sol_util_strtod_n(buf.data, &endptr, buf.used, false);

            if (errno != 0 || endptr == buf.data) {
                r = -EINVAL;
                fprintf(stderr, "Could not copy the longitude/latitude"
                    " property\n");
                goto err_free_timeout;
            }
        }
        sol_buffer_fini(&buf);
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    data_ctx->has_location_instance = true;
    printf("Location object created\n");

    return 0;

err_free_timeout:
    sol_timeout_del(instance_ctx->timeout);
err_free_instance:
    free(instance_ctx);
    return r;
}

static int
read_location_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id,
    uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct sol_blob *blob;
    struct location_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case LOCATION_OBJ_LATITUDE_RES_ID:
        blob = coord_to_str(ctx->latitude);
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, blob);
        sol_blob_unref(blob);
        break;
    case LOCATION_OBJ_LONGITUDE_RES_ID:
        blob = coord_to_str(ctx->longitude);
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, blob);
        sol_blob_unref(blob);
        break;
    case LOCATION_OBJ_TIMESTAMP_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_TIME, ctx->timestamp);
        break;
    default:
        if (res_id >= 2 && res_id <= 4)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
read_security_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct security_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case SECURITY_SERVER_URI_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->server_uri);
        break;
    case SECURITY_IS_BOOTSTRAP_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_BOOL, ctx->is_bootstrap);
        break;
    case SECURITY_SECURITY_MODE_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->security_mode);
        break;
    case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
        if (!ctx->public_key_or_id)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->public_key_or_id);
        break;
    case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
        if (!ctx->server_public_key)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->server_public_key);
        break;
    case SECURITY_SECRET_KEY_RES_ID:
        if (!ctx->secret_key)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->secret_key);
        break;
    case SECURITY_SERVER_ID_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->server_id);
        break;
    case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->client_hold_off_time);
        break;
    case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->bootstrap_server_account_timeout);
        break;
    default:
        if (res_id >= 6 && res_id <= 9)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
write_security_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct security_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;

    switch (res->id) {
    case SECURITY_SERVER_URI_RES_ID:
        sol_blob_unref(instance_ctx->server_uri);
        instance_ctx->server_uri = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_IS_BOOTSTRAP_RES_ID:
        instance_ctx->is_bootstrap = res->data->content.b;
        break;
    case SECURITY_SECURITY_MODE_RES_ID:
        instance_ctx->security_mode = res->data->content.integer;
        break;
    case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
        sol_blob_unref(instance_ctx->public_key_or_id);
        instance_ctx->public_key_or_id = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
        sol_blob_unref(instance_ctx->server_public_key);
        instance_ctx->server_public_key = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SECRET_KEY_RES_ID:
        sol_blob_unref(instance_ctx->secret_key);
        instance_ctx->secret_key = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SERVER_ID_RES_ID:
        instance_ctx->server_id = res->data->content.integer;
        break;
    case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
        instance_ctx->client_hold_off_time = res->data->content.integer;
        break;
    case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
        instance_ctx->bootstrap_server_account_timeout = res->data->content.integer;
        break;
    default:
        if (res->id >= 6 && res->id <= 9)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Security object at /0/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);
    return r;
}

static int
write_security_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = 0;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct security_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        switch (tlv->id) {
        case SECURITY_SERVER_URI_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->server_uri);
            instance_ctx->server_uri = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_uri)
                return -EINVAL;
            break;
        case SECURITY_IS_BOOTSTRAP_RES_ID:
            r = sol_lwm2m_tlv_get_bool(tlv, &instance_ctx->is_bootstrap);
            if (r < 0)
                return r;
            break;
        case SECURITY_SECURITY_MODE_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->security_mode);
            if (r < 0)
                return r;
            break;
        case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->public_key_or_id);
            instance_ctx->public_key_or_id = sol_buffer_to_blob(&buf);
            if (!instance_ctx->public_key_or_id)
                return -EINVAL;
            break;
        case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->server_public_key);
            instance_ctx->server_public_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_public_key)
                return -EINVAL;
            break;
        case SECURITY_SECRET_KEY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->secret_key);
            instance_ctx->secret_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->secret_key)
                return -EINVAL;
            break;
        case SECURITY_SERVER_ID_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
            if (r < 0)
                return r;
            break;
        case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->client_hold_off_time);
            if (r < 0)
                return r;
            break;
        case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->bootstrap_server_account_timeout);
            if (r < 0)
                return r;
            break;
        default:
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Security Server Object at /0/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Security object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Security object at /1/%" PRIu16 "\n", instance_id);

    return r;
}

static int
create_security_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct security_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct security_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for security object context\n");
        return -ENOMEM;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        if (tlv->id == SECURITY_SERVER_URI_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->server_uri = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_uri) {
                fprintf(stderr, "Could not set server_uri resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_IS_BOOTSTRAP_RES_ID) {
            r = sol_lwm2m_tlv_get_bool(tlv, &instance_ctx->is_bootstrap);
        } else if (tlv->id == SECURITY_SECURITY_MODE_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->security_mode);
        } else if (tlv->id == SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->public_key_or_id = sol_buffer_to_blob(&buf);
            if (!instance_ctx->public_key_or_id) {
                fprintf(stderr, "Could not set public_key_or_id resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SERVER_PUBLIC_KEY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->server_public_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_public_key) {
                fprintf(stderr, "Could not set server_public_key resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SECRET_KEY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->secret_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->secret_key) {
                fprintf(stderr, "Could not set secret_key resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SERVER_ID_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
        } else if (tlv->id == SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->client_hold_off_time);
        } else if (tlv->id == SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->bootstrap_server_account_timeout);
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_instance;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Security object created at /0/%" PRIu16 "\n", instance_id);

    return 0;

err_free_instance:
    sol_blob_unref(instance_ctx->server_uri);
    if (instance_ctx->public_key_or_id)
        sol_blob_unref(instance_ctx->public_key_or_id);
    if (instance_ctx->server_public_key)
        sol_blob_unref(instance_ctx->server_public_key);
    if (instance_ctx->secret_key)
        sol_blob_unref(instance_ctx->secret_key);
    free(instance_ctx);
    return r;
}

static int
del_security_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct security_obj_instance_ctx *instance_ctx = instance_data;

    sol_blob_unref(instance_ctx->server_uri);
    if (instance_ctx->public_key_or_id)
        sol_blob_unref(instance_ctx->public_key_or_id);
    if (instance_ctx->server_public_key)
        sol_blob_unref(instance_ctx->server_public_key);
    if (instance_ctx->secret_key)
        sol_blob_unref(instance_ctx->secret_key);
    free(instance_ctx);
    return 0;
}

static int
read_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct server_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case SERVER_OBJ_SHORT_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->server_id);
        break;
    case SERVER_OBJ_LIFETIME_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->lifetime);
        break;
    case SERVER_OBJ_BINDING_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->binding);
        break;
    default:
        if (res_id >= 2 && res_id <= 6)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
write_server_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct server_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;

    switch (res->id) {
    case SERVER_OBJ_SHORT_RES_ID:
        instance_ctx->server_id = res->data->content.integer;
        break;
    case SERVER_OBJ_LIFETIME_RES_ID:
        instance_ctx->lifetime = res->data->content.integer;
        break;
    case SERVER_OBJ_BINDING_RES_ID:
        sol_blob_unref(instance_ctx->binding);
        instance_ctx->binding = sol_blob_ref(res->data->content.blob);
        break;
    default:
        if (res->id >= 2 && res->id <= 6)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Server object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);
    return r;
}

static int
write_server_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = 0;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct server_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        switch (tlv->id) {
        case SERVER_OBJ_SHORT_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
            if (r < 0)
                return r;
            break;
        case SERVER_OBJ_LIFETIME_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->lifetime);
            if (r < 0)
                return r;
            break;
        case SERVER_OBJ_BINDING_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->binding);
            instance_ctx->binding = sol_buffer_to_blob(&buf);
            if (!instance_ctx->binding)
                return -EINVAL;
            break;
        default:
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Server Object at /1/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Server object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Server object at /1/%" PRIu16 "\n", instance_id);

    return r;
}

static int
create_server_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct server_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct server_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for server object context\n");
        return -ENOMEM;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        if (tlv->id == SERVER_OBJ_SHORT_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
        } else if (tlv->id == SERVER_OBJ_LIFETIME_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->lifetime);
        } else if (tlv->id == SERVER_OBJ_BINDING_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->binding = sol_buffer_to_blob(&buf);
            if (!instance_ctx->binding) {
                fprintf(stderr, "Could not set binding resource\n");
                goto err_free_instance;
            }
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_instance;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Server object created at /1/%" PRIu16 "\n", instance_id);

    return 0;

err_free_instance:
    free(instance_ctx);
    return r;
}

static int
execute_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id,
    uint16_t res_id, const struct sol_str_slice args)
{
    if (res_id != SERVER_OBJ_REGISTRATION_UPDATE_RES_ID)
        return -EINVAL;

    return sol_lwm2m_client_send_update(client);
}

static int
del_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct server_obj_instance_ctx *instance_ctx = instance_data;

    sol_blob_unref(instance_ctx->binding);
    free(instance_ctx);
    return 0;
}

static int
del_location_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct location_obj_instance_ctx *instance_ctx = instance_data;
    struct client_data_ctx *data_ctx = user_data;

    if (instance_ctx->timeout)
        sol_timeout_del(instance_ctx->timeout);
    free(instance_ctx);
    data_ctx->has_location_instance = false;
    return 0;
}

static int
read_access_control_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct access_control_obj_instance_ctx *ctx = instance_data;
    int r;

    if (res_id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->object_id);
    } else if (res_id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->instance_id);
    } else if (res_id == ACCESS_CONTROL_OBJ_ACL_RES_ID) {
        struct acl_instance *acl_item;
        uint16_t i;
        struct sol_vector acl_instances;
        struct sol_lwm2m_resource_data *res_data;

        if (ctx->acl.len == 0)
            return -ENOENT;

        sol_vector_init(&acl_instances, sizeof(struct sol_lwm2m_resource_data));

        SOL_VECTOR_FOREACH_IDX (&ctx->acl, acl_item, i) {
            res_data = sol_vector_append(&acl_instances);
            res_data->id = acl_item->key;
            res_data->content.integer = acl_item->value;
        }

        SOL_SET_API_VERSION(res->api_version = SOL_LWM2M_RESOURCE_API_VERSION; )
        r = sol_lwm2m_resource_init_vector(res, ACCESS_CONTROL_OBJ_ACL_RES_ID,
            SOL_LWM2M_RESOURCE_DATA_TYPE_INT, &acl_instances);

        sol_vector_clear(&acl_instances);
    } else if (res_id == ACCESS_CONTROL_OBJ_OWNER_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->owner_id);
    } else {
        r = -EINVAL;
    }

    return r;
}

static int
write_access_control_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;
    struct acl_instance *acl_item;
    uint16_t i;

    switch (res->id) {
    case ACCESS_CONTROL_OBJ_OBJECT_RES_ID:
        instance_ctx->object_id = res->data->content.integer;
        break;
    case ACCESS_CONTROL_OBJ_INSTANCE_RES_ID:
        instance_ctx->instance_id = res->data->content.integer;
        break;
    case ACCESS_CONTROL_OBJ_ACL_RES_ID:
        if (res->type == SOL_LWM2M_RESOURCE_TYPE_MULTIPLE) {
            sol_vector_clear(&instance_ctx->acl);

            for (i = 0; i < res->data_len; i++) {
                acl_item = sol_vector_append(&instance_ctx->acl);
                if (!acl_item) {
                    fprintf(stderr, "Could not alloc memory for access control list Resource Instance\n");
                    r = -ENOMEM;
                    goto err_free_acl;
                }

                acl_item->key = res->data[i].id;
                acl_item->value = res->data[i].content.integer;
                printf("<<[WRITE_RES]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
            }
        } else {
            r = -EINVAL;
        }
        break;
    case ACCESS_CONTROL_OBJ_OWNER_RES_ID:
        instance_ctx->owner_id = res->data->content.integer;
        break;
    default:
        r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Access Control object at /2/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);

    return r;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    return r;
}

static int
write_or_create_acl(struct sol_vector *acl,
    struct sol_vector *tlvs, uint16_t *j, bool is_create)
{
    struct acl_instance *acl_item;
    struct sol_lwm2m_tlv *res_tlv;
    int64_t res_val;
    int r;

    while ((res_tlv = sol_vector_get(tlvs, *j)) &&
        res_tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_INSTANCE) {
        r = sol_lwm2m_tlv_get_int(res_tlv, &res_val);
        if (r < 0)
            return r;

        acl_item = sol_vector_append(acl);
        if (!acl_item) {
            fprintf(stderr, "Could not alloc memory for access control list Resource Instance\n");
            return -ENOMEM;
        }

        acl_item->key = res_tlv->id;
        acl_item->value = res_val;
        if (is_create)
            printf("<<[CREATE]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
        else
            printf("<<[WRITE_TLV]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
        (*j)++;
    }

    return 0;
}

static int
write_access_control_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = -EINVAL;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        if (tlv->id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->object_id);
            if (r < 0)
                return r;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->instance_id);
            if (r < 0)
                return r;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_ACL_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_MULTIPLE_RESOURCES) {
            uint16_t j = i + 1;

            sol_vector_clear(&instance_ctx->acl);

            r = write_or_create_acl(&instance_ctx->acl, tlvs, &j, false);
            if (r < 0)
                goto err_free_acl;

            i = j - 1;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_OWNER_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->owner_id);
            if (r < 0)
                return r;
        } else {
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Access Control Object at /2/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Access Control object at /2/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Access Control object at /2/%" PRIu16 "\n", instance_id);

    return r;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    return r;
}

static int
create_access_control_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct access_control_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct access_control_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for access control object context\n");
        return -ENOMEM;
    }

    sol_vector_init(&instance_ctx->acl, sizeof(struct acl_instance));

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        if (tlv->id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->object_id);
        } else if (tlv->id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->instance_id);
        } else if (tlv->id == ACCESS_CONTROL_OBJ_ACL_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_MULTIPLE_RESOURCES) {
            uint16_t j = i + 1;

            sol_vector_clear(&instance_ctx->acl);

            r = write_or_create_acl(&instance_ctx->acl, &payload.payload.tlv_content, &j, true);
            if (r < 0)
                goto err_free_acl;

            i = j - 1;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_OWNER_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->owner_id);
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_acl;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Access Control object created at /2/%" PRIu16 "\n\n", instance_id);

    return 0;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    free(instance_ctx);
    return r;
}

static int
del_access_control_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;

    sol_vector_clear(&instance_ctx->acl);
    free(instance_ctx);
    return 0;
}

static void
bootstrap_cb(void *data,
    struct sol_lwm2m_client *client,
    enum sol_lwm2m_bootstrap_event event)
{
    if (event == SOL_LWM2M_BOOTSTRAP_EVENT_FINISHED) {
        printf("...<Call local Bootstrap clean-up operations>...\n"
            "...<Now that it should have a Server, try to register again>\n");
        sol_lwm2m_client_start(client);
    } else if (event == SOL_LWM2M_BOOTSTRAP_EVENT_ERROR) {
        fprintf(stderr, "Bootstrap Request or Bootstrap Finish Failed!\n");
    }
}

static const struct sol_lwm2m_object location_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = LOCATION_OBJ_ID,
    .create = create_location_obj,
    .read = read_location_obj,
    .del = del_location_obj,
    .resources_count = 6
};

static const struct sol_lwm2m_object security_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = SECURITY_OBJ_ID,
    .resources_count = 12,
    .read = read_security_obj,
    .create = create_security_obj,
    .del = del_security_obj,
    .write_resource = write_security_res,
    .write_tlv = write_security_tlv
};

static const struct sol_lwm2m_object server_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = SERVER_OBJ_ID,
    .resources_count = 9,
    .read = read_server_obj,
    .create = create_server_obj,
    .del = del_server_obj,
    .write_resource = write_server_res,
    .write_tlv = write_server_tlv,
    .execute = execute_server_obj
};

static const struct sol_lwm2m_object access_control_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = ACCESS_CONTROL_OBJ_ID,
    .resources_count = 4,
    .read = read_access_control_obj,
    .create = create_access_control_obj,
    .del = del_access_control_obj,
    .write_resource = write_access_control_res,
    .write_tlv = write_access_control_tlv,
};

int
main(int argc, char *argv[])
{
    struct sol_lwm2m_client *client;
    static const struct sol_lwm2m_object *objects[] =
    { &security_object, &server_object, &access_control_object, &location_object, NULL };
    struct client_data_ctx data_ctx = { 0 };
    struct security_obj_instance_ctx *security_data = NULL;
    struct server_obj_instance_ctx *server_data = NULL;
    int r;
    enum sol_lwm2m_security_mode sec_mode = SOL_LWM2M_SECURITY_MODE_NO_SEC;
    unsigned char buf_aux[RPK_PUBLIC_KEY_LEN];
    struct sol_blob *public_key_or_id, *server_public_key, *secret_key;
    char *cli_name = NULL;
    char usage[256];

    srand(time(NULL));

    snprintf(usage, sizeof(usage), "Usage: ./lwm2m-sample-client <client-name> [-b] [-s SEC_MODE]\n"
        "Where Factory Bootstrap is default and SEC_MODE is an integer as per:\n"
        "\tPRE_SHARED_KEY=%d\n"
        "\tRAW_PUBLIC_KEY=%d\n"
        "\tCERTIFICATE=%d\n"
        "\tNO_SEC=%d (default)\n",
        SOL_LWM2M_SECURITY_MODE_PRE_SHARED_KEY,
        SOL_LWM2M_SECURITY_MODE_RAW_PUBLIC_KEY,
        SOL_LWM2M_SECURITY_MODE_CERTIFICATE,
        SOL_LWM2M_SECURITY_MODE_NO_SEC);

    while ((r = getopt(argc, argv, "bs:")) != -1) {
        switch (r) {
        case 'b':
            data_ctx.is_bootstrap = true;
            break;
        case 's':
            sec_mode = atoi(optarg);
            if (sec_mode < 0 || sec_mode > 3) {
                fprintf(stderr, "%s", usage);
                return -1;
            }
            break;
        default:
            fprintf(stderr, "%s", usage);
            return -1;
        }
    }

    cli_name = argv[optind];
    if (!cli_name) {
        fprintf(stderr, "%s", usage);
        return -1;
    }

    if (data_ctx.is_bootstrap && (sec_mode == SOL_LWM2M_SECURITY_MODE_NO_SEC)) {
        fprintf(stderr, "Non-Factory Bootstrap Mode needs DTLS security enabled\n");
        return -1;
    }

    switch (sec_mode) {
    case SOL_LWM2M_SECURITY_MODE_PRE_SHARED_KEY:
        if (data_ctx.is_bootstrap) {
            public_key_or_id = sol_blob_new_dup(CLIENT_BS_PSK_ID,
                sizeof(CLIENT_BS_PSK_ID) - 1);
            secret_key = sol_blob_new_dup(CLIENT_BS_PSK_KEY, PSK_KEY_LEN);
        } else {
            public_key_or_id = sol_blob_new_dup(CLIENT_SERVER_PSK_ID,
                sizeof(CLIENT_SERVER_PSK_ID) - 1);
            secret_key = sol_blob_new_dup(CLIENT_SERVER_PSK_KEY, PSK_KEY_LEN);
        }
        server_public_key = NULL;
        break;
    case SOL_LWM2M_SECURITY_MODE_RAW_PUBLIC_KEY:
        r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
            sol_str_slice_from_str(CLIENT_PRIVATE_KEY), SOL_DECODE_BOTH);
        secret_key = sol_blob_new_dup(buf_aux, RPK_PRIVATE_KEY_LEN);
        r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
            sol_str_slice_from_str(CLIENT_PUBLIC_KEY), SOL_DECODE_BOTH);
        public_key_or_id = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);

        if (data_ctx.is_bootstrap) {
            r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
                sol_str_slice_from_str(BS_SERVER_PUBLIC_KEY), SOL_DECODE_BOTH);
            server_public_key = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);
        } else {
            r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
                sol_str_slice_from_str(SERVER_PUBLIC_KEY), SOL_DECODE_BOTH);
            server_public_key = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);
        }
        break;
    case SOL_LWM2M_SECURITY_MODE_CERTIFICATE:
        fprintf(stderr, "Certificate security mode is not supported yet.\n");
        return -1;
    case SOL_LWM2M_SECURITY_MODE_NO_SEC:
    default:
        public_key_or_id = NULL;
        server_public_key = NULL;
        secret_key = NULL;
        break;
    }

    sol_init();

    client = sol_lwm2m_client_new(cli_name, NULL, NULL, objects, &data_ctx);

    if (!client) {
        r = -1;
        fprintf(stderr, "Could not the create the LWM2M client\n");
        goto exit;
    }

    security_data = calloc(1, sizeof(struct security_obj_instance_ctx));
    if (!security_data) {
        fprintf(stderr, "Could not alloc memory for security object context\n");
        r = -ENOMEM;
        goto exit_del;
    }

    security_data->client = client;
    security_data->security_mode = sec_mode;
    security_data->public_key_or_id = public_key_or_id;
    security_data->server_public_key = server_public_key;
    security_data->secret_key = secret_key;

    if (!data_ctx.is_bootstrap) {
        server_data = calloc(1, sizeof(struct server_obj_instance_ctx));
        if (!server_data) {
            fprintf(stderr, "Could not alloc memory for server object context\n");
            r = -ENOMEM;
            goto exit_del;
        }

        server_data->client = client;
        server_data->binding = &binding;
        server_data->server_id = 101;
        server_data->lifetime = LIFETIME;

        r = sol_lwm2m_client_add_object_instance(client, &server_object, server_data);

        if (r < 0) {
            fprintf(stderr, "Could not add a server object instance\n");
            goto exit_del;
        }

        security_data->server_uri = (sec_mode == SOL_LWM2M_SECURITY_MODE_NO_SEC) ?
            &server_addr_coap : &server_addr_dtls;
        security_data->is_bootstrap = false;
        security_data->server_id = 101;
    } else {
        r = sol_lwm2m_client_add_bootstrap_finish_monitor(client, bootstrap_cb,
            NULL);

        if (r < 0) {
            fprintf(stderr, "Could not add a bootstrap monitor\n");
            goto exit_del;
        }

        security_data->server_uri = &bootstrap_server_addr;
        security_data->is_bootstrap = true;
        security_data->client_hold_off_time = 0;
        security_data->bootstrap_server_account_timeout = 0;
    }

    r = sol_lwm2m_client_add_object_instance(client, &security_object, security_data);

    if (r < 0) {
        fprintf(stderr, "Could not add a security object instance\n");
        goto exit_del;
    }

    sol_lwm2m_client_start(client);

    sol_run();
    r = 0;

    sol_lwm2m_client_stop(client);

exit_del:
    sol_lwm2m_client_del(client);
    free(security_data);
    free(server_data);
exit:
    sol_shutdown();
    return r;
}

{'repo_name': 'solettaproject/soletta', 'stars': '217', 'repo_language': 'C', 'file_name': 'initial-services.in', 'mime_type': 'text/plain', 'hash': -6004168856003143015, 'source_dataset': 'data'}


---
title: Using Multiple Schemas
---

In MySQL and PostgreSQL is is possible to define your entities in multiple schemas. In MySQL
terminology, it is called database, but from implementation point of view, it is a schema.

> To use multiple schemas, your connection needs to have access to all of them (multiple
> connections are not supported).

All you need to do is simply define the table name including schema name in `collection` option:

```typescript
@Entity({ tableName: 'first_schema.foo' })
export class Foo { ... }

@Entity({ tableName: 'second_schema.bar' })
export class Bar { ... }
```

Then use those entities as usual. Resulting SQL queries will use this `tableName` value as a
table name so as long as your connection has access to given schema, everything should work
as expected.

{'repo_name': 'mikro-orm/mikro-orm', 'stars': '1149', 'repo_language': 'TypeScript', 'file_name': 'multi-decorator.model.ts', 'mime_type': 'text/x-java', 'hash': -5551252907523176209, 'source_dataset': 'data'}


##! Keep a random sample of values.

@load base/frameworks/sumstats/main

module SumStats;

export {
	redef enum Calculation += {
		## Get uniquely distributed random samples from the observation
		## stream.
		SAMPLE
	};

	redef record Reducer += {
		## The number of sample Observations to collect.
		num_samples: count &default=0;
	};

	redef record ResultVal += {
		## This is the vector in which the samples are maintained.
		samples: vector of Observation &default=vector();

		## Number of total observed elements.
		sample_elements: count &default=0;
	};
}

redef record ResultVal += {
	# Internal use only.  This is not meant to be publically available
	# and just a copy of num_samples from the Reducer. Needed for
	# availability in the compose hook.
	num_samples: count &default=0;
};

hook init_resultval_hook(r: Reducer, rv: ResultVal)
	{
	if ( SAMPLE in r$apply )
		rv$num_samples = r$num_samples;
	}

function sample_add_sample(obs:Observation, rv: ResultVal)
	{
	++rv$sample_elements;

	if ( |rv$samples| < rv$num_samples )
		rv$samples += obs;
	else
		{
		local ra = rand(rv$sample_elements);
		if ( ra < rv$num_samples )
			rv$samples[ra] = obs;
		}
	}

hook register_observe_plugins()
	{
	register_observe_plugin(SAMPLE, function(r: Reducer, val: double, obs: Observation, rv: ResultVal)
		{
		sample_add_sample(obs, rv);
		});
	}

hook compose_resultvals_hook(result: ResultVal, rv1: ResultVal, rv2: ResultVal)
	{
	if ( rv1$num_samples != rv2$num_samples )
		{
		Reporter::error("Merging sample sets with differing sizes is not supported");
		return;
		}

	local num_samples = rv1$num_samples;
	result$num_samples = num_samples;

	if ( |rv1$samples| > num_samples || |rv2$samples| > num_samples )
		{
		Reporter::error("Sample vector with too many elements. Aborting.");
		return;
		}

	if ( |rv1$samples| != num_samples && |rv2$samples| < num_samples )
		{
		if ( |rv1$samples| != rv1$sample_elements || |rv2$samples| < rv2$sample_elements )
			{
			Reporter::error("Mismatch in sample element size and tracking. Aborting merge");
			return;
			}

		for ( i in rv1$samples )
			sample_add_sample(rv1$samples[i], result);

		for ( i in rv2$samples)
			sample_add_sample(rv2$samples[i], result);
		}
	else
		{
		local other_vector: vector of Observation;
		local othercount: count;

		if ( rv1$sample_elements > rv2$sample_elements )
			{
			result$samples = copy(rv1$samples);
			other_vector = rv2$samples;
			othercount = rv2$sample_elements;
			}
		else
			{
			result$samples = copy(rv2$samples);
			other_vector = rv1$samples;
			othercount = rv1$sample_elements;
			}

		local totalcount = rv1$sample_elements + rv2$sample_elements;
		result$sample_elements = totalcount;

		for ( i in other_vector )
			{
			if ( rand(totalcount) <= othercount )
				result$samples[i] = other_vector[i];
			}
		}
	}

{'repo_name': 'zeek/zeek', 'stars': '3326', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -2222789360916712628, 'source_dataset': 'data'}


/* pages/components/layout/pages/sticky/index.wxss */

.num {
  color: #fc6517;
  font-size: 42rpx;
  font-style: italic;
}

.text {
  height: 30rpx;
  font-size: 22rpx;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
  line-height: 30rpx;
  margin-top: 9rpx;
}

.grid-item {
  height: 200rpx;
}

page {
  padding-bottom: 1000rpx;
}

.container {
  max-width: 100vw;
  overflow: visible;
}

.text {
  height: 30rpx;
  font-size: 22rpx;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
  line-height: 30rpx;
  margin-top: 9rpx;
}

.grid-item {
  height: 200rpx;
}

.l-header-sticky-class {
  right: 0 !important;
  box-sizing: border-box !important;
  padding: 0 20rpx !important;
  background-color: white !important;
  z-index: 1 !important;
}

.l-container-class {
  background-color: white !important;
}

/* 指定吸顶位置 */
.container-search-bar {
  height: 40px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  background-color: white;
}

/* 卡片样式 */
.card {
  margin: 10rpx auto !important;
}

.right-card {
  height: 180rpx !important;
  width: 220rpx !important;
  border-radius: 12rpx !important;
}

.content {
  margin-top: 10rpx;
  color: #666;
  font-size: 26rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
}

.dynamic-card-header{
  height: 40rpx;
  line-height: 30rpx;
  font-weight: bold;
  background-color: white;
  margin: 30rpx 0;

}

.dynamic-card-body{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

{'repo_name': 'TaleLin/lin-ui', 'stars': '1861', 'repo_language': 'JavaScript', 'file_name': 'index.wxml', 'mime_type': 'text/plain', 'hash': -7887480767999721488, 'source_dataset': 'data'}


package com.haxademic.sketch.test;

import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.context.PG;
import com.haxademic.core.file.FileUtil;

public class ScoreDrawTest
extends PAppletHax {
	public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

//	protected CustomFontText2D _scoreFontRenderer;

	protected void firstFrame() {

		String fontFile = FileUtil.haxademicDataPath() + "haxademic/fonts/Raleway-Regular.ttf";
//		_scoreFontRenderer = new CustomFontText2D( p, fontFile, 36, ColorUtil.colorFromHex("#ff00ff"), CustomFontText2D.ALIGN_CENTER, 80, 80 );

	}

	protected void drawApp() {
		p.background(255);
		PG.setDrawCenter( p );
		p.pushMatrix();

		if( p.frameCount % 5 == 0 ) {
//			_scoreFontRenderer.updateText(""+p.frameCount);
		}

		p.translate( 71f, 50 );
		p.noStroke();

		// draw shadow
		p.fill(0, 25);
		p.ellipse( -6f, 11f, 80f, 80f );

		// draw large bg
		p.fill( p.color(55,100,200) );
		p.ellipse( 0, 0, 80f, 80f );

		// draw small shadow
		p.fill(0, 25);
		p.ellipse( 0, 3f, 60f, 60f );

		// draw small shadow
		p.fill(255);
		p.ellipse( 0, 0, 60f, 60f );

		// draw text
//		p.image(_scoreFontRenderer.getTextPImage(), 0, 0); // , _scoreFontRenderer.getTextPImage().width, _scoreFontRenderer.getTextPImage().height

		p.popMatrix();

	}
}

{'repo_name': 'cacheflowe/haxademic', 'stars': '120', 'repo_language': 'Java', 'file_name': 'Heart.mtl', 'mime_type': 'text/plain', 'hash': 6245022568077351717, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>BenchmarkTest00975</title>

<form action="/benchmark/weakrand-02/BenchmarkTest00975"  method="POST" id="FormBenchmarkTest00975" >

Here is the image you are looking for:

The server automatically generated the cookie "BenchmarkTest00975" for this test case. Press the "Test it!" button to send this cookie back to the server.

<input type="submit" value="Test it!" />

</form>

{'repo_name': 'OWASP/Benchmark', 'stars': '268', 'repo_language': 'Java', 'file_name': 'extensions.xml', 'mime_type': 'text/xml', 'hash': 141961139488029481, 'source_dataset': 'data'}


{'repo_name': 'talentlessguy/tinyhttp', 'stars': '113', 'repo_language': 'TypeScript', 'file_name': 'public', 'mime_type': 'text/plain', 'hash': 487890133852186155, 'source_dataset': 'data'}


/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule ReactNativeViewAttributes
 * @flow
 */
'use strict';

const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');

const ReactNativeViewAttributes = {};

ReactNativeViewAttributes.UIView = {
  pointerEvents: true,
  accessible: true,
  accessibilityLabel: true,
  accessibilityComponentType: true,
  accessibilityLiveRegion: true,
  accessibilityTraits: true,
  importantForAccessibility: true,
  testID: true,
  renderToHardwareTextureAndroid: true,
  shouldRasterizeIOS: true,
  onLayout: true,
  onAccessibilityTap: true,
  onMagicTap: true,
  onEnter: true,
  onExit: true,
  onInput: true,
  onGazeEnter: true,
  onGazeExit: true,
  onMouseEnter: true,
  onMouseExit: true,
  onChange: true,
  onHeadPose: true,
  onGazeInput: true,
  onGazeHeadPose: true,
  onMouseInput: true,
  onMouseHeadPose: true,
  onChangeCaptured: true,
  onInputCaptured: true,
  onHeadPoseCaptured: true,
  onGazeInputCaptured: true,
  onGazeHeadPoseCaptured: true,
  onMouseInputCaptured: true,
  onMouseHeadPoseCaptured: true,
  collapsable: true,
  needsOffscreenAlphaCompositing: true,
  style: ReactNativeStyleAttributes,
};

ReactNativeViewAttributes.RCTView = {
  ...ReactNativeViewAttributes.UIView,

  // This is a special performance property exposed by RCTView and useful for
  // scrolling content when there are many subviews, most of which are offscreen.
  // For this property to be effective, it must be applied to a view that contains
  // many subviews that extend outside its bound. The subviews must also have
  // overflow: hidden, as should the containing view (or one of its superviews).
  removeClippedSubviews: true,
};

module.exports = ReactNativeViewAttributes;

{'repo_name': 'facebook/react-360', 'stars': '8159', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -648839576268532939, 'source_dataset': 'data'}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>GNU Classpath - javax.naming.spi</title>

{'repo_name': 'jcmvbkbc/gcc-xtensa', 'stars': '121', 'repo_language': 'C', 'file_name': 'api.html', 'mime_type': 'text/xml', 'hash': 2359267313624040994, 'source_dataset': 'data'}


package libp2p

import (
	config "github.com/ipfs/go-ipfs-config"
	"github.com/libp2p/go-libp2p"
	noise "github.com/libp2p/go-libp2p-noise"
	secio "github.com/libp2p/go-libp2p-secio"
	tls "github.com/libp2p/go-libp2p-tls"
)

func Security(enabled bool, tptConfig config.Transports) interface{} {
	if !enabled {
		return func() (opts Libp2pOpts) {
			log.Errorf(`Your IPFS node has been configured to run WITHOUT ENCRYPTED CONNECTIONS.
		You will not be able to connect to any nodes configured to use encrypted connections`)
			opts.Opts = append(opts.Opts, libp2p.NoSecurity)
			return opts
		}
	}

	// Using the new config options.
	return func() (opts Libp2pOpts) {
		opts.Opts = append(opts.Opts, prioritizeOptions([]priorityOption{{
			priority:        tptConfig.Security.TLS,
			defaultPriority: 100,
			opt:             libp2p.Security(tls.ID, tls.New),
		}, {
			priority:        tptConfig.Security.SECIO,
			defaultPriority: config.Disabled,
			opt:             libp2p.Security(secio.ID, secio.New),
		}, {
			priority:        tptConfig.Security.Noise,
			defaultPriority: 300,
			opt:             libp2p.Security(noise.ID, noise.New),
		}}))
		return opts
	}
}

{'repo_name': 'ipfs/go-ipfs', 'stars': '9936', 'repo_language': 'Go', 'file_name': 'repub.go', 'mime_type': 'text/plain', 'hash': -4939156110536742759, 'source_dataset': 'data'}


<%def name="doubleindent(code)">${ '\n        '.join(str(code).splitlines()) }</%def>\
/********************
GNU Radio C++ Flow Graph Source File

Title: ${title}
% if flow_graph.get_option('author'):
Author: ${flow_graph.get_option('author')}
% endif
% if flow_graph.get_option('description'):
Description: ${flow_graph.get_option('description')}
% endif
GNU Radio version: ${version}
********************/

#include "${flow_graph.get_option('id')}.hpp"
% if flow_graph.get_option('realtime_scheduling'):
#include <gnuradio/realtime.h>
% endif

% if parameters:

namespace po = boost::program_options;

% endif
using namespace gr;

<%
class_name = flow_graph.get_option('id') + ('_' if flow_graph.get_option('id') == 'top_block' else '')

param_str = ", ".join((param.vtype + " " + param.name) for param in parameters)
param_str_without_types = ", ".join(param.name for param in parameters)
initializer_str = ",\n  ".join((param.name + "(" + param.name + ")") for param in parameters)

if generate_options == 'qt_gui':
  initializer_str = 'QWidget()' + (',\n  ' if len(parameters) > 0 else '') + initializer_str

if len(initializer_str) > 0:
  initializer_str = '\n: ' + initializer_str
%>\

${class_name}::${class_name} (${param_str}) ${initializer_str} {

% if generate_options == 'qt_gui':
    this->setWindowTitle("${title}");
    // check_set_qss
    // set icon
    this->top_scroll_layout = new QVBoxLayout();
    this->setLayout(this->top_scroll_layout);
    this->top_scroll = new QScrollArea();
    this->top_scroll->setFrameStyle(QFrame::NoFrame);
    this->top_scroll_layout->addWidget(this->top_scroll);
    this->top_scroll->setWidgetResizable(true);
    this->top_widget = new QWidget();
    this->top_scroll->setWidget(this->top_widget);
    this->top_layout = new QVBoxLayout(this->top_widget);
    this->top_grid_layout = new QGridLayout();
    this->top_layout->addLayout(this->top_grid_layout);

    this->settings = new QSettings("GNU Radio", "${class_name}");
% endif

% if flow_graph.get_option('thread_safe_setters'):
## self._lock = threading.RLock()
% endif
    this->tb = gr::make_top_block("${title}");

% if blocks:
// Blocks:
% for blk, blk_make, declarations in blocks:
    {
        ${doubleindent(blk_make)}
##      % if 'alias' in blk.params and blk.params['alias'].get_evaluated():
##      ${blk.name}.set_block_alias("${blk.params['alias'].get_evaluated()}")
##      % endif
##      % if 'affinity' in blk.params and blk.params['affinity'].get_evaluated():
##      ${blk.name}.set_processor_affinity("${blk.params['affinity'].get_evaluated()}")
##      % endif
##      % if len(blk.sources) > 0 and 'minoutbuf' in blk.params and int(blk.params['minoutbuf'].get_evaluated()) > 0:
##      ${blk.name}.set_min_output_buffer(${blk.params['minoutbuf'].get_evaluated()})
##      % endif
##      % if len(blk.sources) > 0 and 'maxoutbuf' in blk.params and int(blk.params['maxoutbuf'].get_evaluated()) > 0:
##      ${blk.name}.set_max_output_buffer(${blk.params['maxoutbuf'].get_evaluated()})
##      % endif
    }
% endfor
% endif

% if connections:
// Connections:
% for connection in connections:
    ${connection.rstrip()};
% endfor
% endif
}

${class_name}::~${class_name} () {
}

// Callbacks:
% for var in parameters + variables:
${var.vtype} ${class_name}::get_${var.name} () const {
    return this->${var.name};
}

void ${class_name}::set_${var.name} (${var.vtype} ${var.name}) {
% if flow_graph.get_option('thread_safe_setters'):
    ## with self._lock:
    return;
% else:
    this->${var.name} = ${var.name};
    % for callback in callbacks[var.name]:
    ${callback};
    % endfor
% endif
}

% endfor

int main (int argc, char **argv) {
    % if parameters:
    % for parameter in parameters:
    ${parameter.vtype} ${parameter.name} = ${parameter.cpp_templates.render('make')};
    % endfor

    po::options_description desc("Options");
    desc.add_options()
    ("help", "display help")
    % for parameter in parameters:
    ("${parameter.name}", po::value<${parameter.vtype}>(&${parameter.name}), "${parameter.label}")
    % endfor
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }
    % endif
    % if flow_graph.get_option('realtime_scheduling'):
    if (enable_realtime_scheduling() != RT_OK) {
        std::cout << "Error: failed to enable real-time scheduling." << std::endl;
    }
    % endif

    % if generate_options == 'no_gui':
    ${class_name}* top_block = new ${class_name}(${param_str_without_types});
    ## TODO: params
    % if flow_graph.get_option('run_options') == 'prompt':
    top_block->tb->start();
    % for m in monitors:
    (top_block->${m.name}).start();
    % endfor
    std::cout << "Press Enter to quit: ";
    std::cin.ignore();
    top_block->tb->stop();
    % elif flow_graph.get_option('run_options') == 'run':
    top_block->tb->start();
    % endif
    % for m in monitors:
    (top_block->${m.name}).start();
    % endfor
    top_block->tb->wait();
    % elif generate_options == 'qt_gui':
    QApplication app(argc, argv);

    ${class_name}* top_block = new ${class_name}(${param_str_without_types});

    top_block->tb->start();
    top_block->show();
    app.exec();

    % endif

    return 0;
}
% if generate_options == 'qt_gui':
#include "moc_${class_name}.cpp"
% endif

{'repo_name': 'gnuradio/gnuradio', 'stars': '2291', 'repo_language': 'C++', 'file_name': 'qtgui_tab_widget.block.yml', 'mime_type': 'text/plain', 'hash': 6930801975095756026, 'source_dataset': 'data'}


let packagesAPI = require("../src/constants/packages").default;
let guidesAPI = require("../src/constants/guides").default;
let examplesAPI = require("../src/constants/examples").default;
let tutorialsAPI = require("../src/constants/tutorials").default;

let packageParams = packagesAPI.all().reduce((acc, pkg) => {
  let pkgs = Object.keys(pkg.versions).map(version => ({
    package: pkg.name,
    version
  }));
  return acc.concat(pkgs);
}, []);
let guideParams = guidesAPI.all().map(p => ({ slug: p.slug }));
let exampleParams = examplesAPI.all().map(e => ({ slug: e.slug }));
let tutorialParams = tutorialsAPI.all().map(t => ({ slug: t.slug }));

module.exports = [
  { name: "Home" },

  { name: "Packages", params: { version: "v1" } },
  { name: "Packages", params: { version: "v2" } },
  ...packageParams.map(params => ({ name: "Package", params })),

  { name: "Guides" },
  ...guideParams.map(params => ({ name: "Guide", params })),

  { name: "Examples" },
  ...exampleParams.map(params => ({ name: "Example", params })),

  { name: "Tutorials" },
  ...tutorialParams.map(params => ({ name: "Tutorial", params }))
];

{'repo_name': 'pshrmn/curi', 'stars': '254', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 4721340048195258310, 'source_dataset': 'data'}


/*
 * SonarQube
 * Copyright (C) 2009-2020 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program 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 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
@ParametersAreNonnullByDefault
package org.sonar.server.util;

import javax.annotation.ParametersAreNonnullByDefault;

{'repo_name': 'SonarSource/sonarqube', 'stars': '4904', 'repo_language': 'Java', 'file_name': 'WebServiceTest.java', 'mime_type': 'text/x-java', 'hash': -1014711538231135164, 'source_dataset': 'data'}


# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))

from nodebox.graphics import *

# Render a radial gradient image.
# Without additional parameters, the gradient will be grayscale.
g = gradient(350, 350, type=RADIAL)

# The mask() filter covers one image with another (grayscale) image.
# You can use the grayscale() filter to make image black & white.
# The mask will hide the source image where the mask is black.
# We use the radial gradient as a mask.
# The radial gradient is white at the edges and black at the center.
# We invert it so we get black edges.
# The result is that the source image will gradually fade away at the edges.
img = Image("dendrite.png")
img = mask(img, invert(g))

# Crop the source image to the size of the mask.
# Our mask is smaller than the source image, so beyond it is still pixel data
# but we no longer need it.
img = crop(img, x=0, y=0, width=350, height=350)

def draw(canvas):

    #canvas.clear()

    # Each frame, paint a new image to the canvas.
    # Since its edges are transparent, all images blend into each other.
    # This is a useful technique if you want to create random,
    # procedural textures (e.g. tree back, rust & dirt, clouded sky, ...)
    translate(random(450), random(450))
    rotate(random(360))
    translate(-img.width/2, -img.height/2) # Rotate from image center.
    image(img)

# Start the application:
canvas.fps  = 5 # Slow framerate so we can observe what is happening.
canvas.size = 500, 500 # This is a bad idea since keyboard events
canvas.run(draw)       # are now logged very slowly.

{'repo_name': 'nodebox/nodebox-opengl', 'stars': '155', 'repo_language': 'OpenEdge ABL', 'file_name': 'physics.py', 'mime_type': 'text/x-python', 'hash': -7096291324234891122, 'source_dataset': 'data'}


// uaparser by lindsey simon,
// ported to node by tobie
// https://github.com/tobie/ua-parser/

// browserized by paul irish

(function(exports){

  exports.uaparse = parse;

  function parse(ua) {
    for (var i=0; i < parsers.length; i++) {
      var result = parsers[i](ua);
      if (result) { return result; }
    }
    return new UserAgent();
  }

  function UserAgent(family) {
    this.family = family || 'Other';
  }

  UserAgent.prototype.toVersionString = function() {
    var output = '';
    if (this.major != null) {
      output += this.major;
      if (this.minor != null) {
        output += '.' + this.minor;
        if (this.patch != null) {
          output += '.' + this.patch;
        }
      }
    }
    return output;
  };

  UserAgent.prototype.toString = function() {
    var suffix = this.toVersionString();
    if (suffix) { suffix = ' ' + suffix; }
    return this.family + suffix;
  };

  var regexes = [
      {"pattern":"^(Opera)/(\\d+)\\.(\\d+) \\(Nintendo Wii",
       "v1_replacement":null,
       "family_replacement":"Wii"},
      {"pattern":"(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre)?)",
       "v1_replacement":null,
       "family_replacement":"Firefox ($1)"},
      {"pattern":"(Namoroka|Shiretoko|Minefield)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*)?",
       "v1_replacement":null,
       "family_replacement":"Firefox ($1)"},
      {"pattern":"(SeaMonkey|Fennec|Camino)/(\\d+)\\.(\\d+)([ab]?\\d+[a-z]*)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Flock)/(\\d+)\\.(\\d+)(b\\d+?)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Fennec)/(\\d+)\\.(\\d+)(pre)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Navigator)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Netscape"},
      {"pattern":"(Navigator)/(\\d+)\\.(\\d+)([ab]\\d+)",
       "v1_replacement":null,
       "family_replacement":"Netscape"},
      {"pattern":"(Netscape6)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Netscape"},
      {"pattern":"(MyIBrow)/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"My Internet Browser"},
      {"pattern":"(Firefox).*Tablet browser (\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"MicroB"},
      {"pattern":"(Opera)/9.80.*Version\\/(\\d+)\\.(\\d+)(?:\\.(\\d+))?",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+(?:pre)?) \\(Swiftfox\\)",
       "v1_replacement":null,
       "family_replacement":"Swiftfox"},
      {"pattern":"(Firefox)/(\\d+)\\.(\\d+)([ab]\\d+[a-z]*)? \\(Swiftfox\\)",
       "v1_replacement":null,
       "family_replacement":"Swiftfox"},
      {"pattern":"(konqueror)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Konqueror"},
      {"pattern":"(Jasmine|ANTGalio|Midori|Fresco|Lobo|Maxthon|Lynx|OmniWeb|Dillo|Camino|Demeter|Fluid|Fennec|Shiira|Sunrise|Chrome|Flock|Netscape|Lunascape|Epiphany|WebPilot|Vodafone|NetFront|Konqueror|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|Opera Mini|iCab|NetNewsWire|Iron|Iris)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Bolt|Jasmine|Maxthon|Lynx|Arora|IBrowse|Dillo|Camino|Shiira|Fennec|Phoenix|Chrome|Flock|Netscape|Lunascape|Epiphany|WebPilot|Opera Mini|Opera|Vodafone|NetFront|Konqueror|SeaMonkey|Kazehakase|Vienna|Iceape|Iceweasel|IceWeasel|Iron|K-Meleon|Sleipnir|Galeon|GranParadiso|iCab|NetNewsWire|Iron|Space Bison|Stainless|Orca)/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(iRider|Crazy Browser|SkipStone|iCab|Lunascape|Sleipnir|Maemo Browser) (\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(iCab|Lunascape|Opera|Android) (\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(IEMobile) (\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"IE Mobile"},
      {"pattern":"(Firefox)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Firefox)/(\\d+)\\.(\\d+)(pre|[ab]\\d+[a-z]*)?",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Obigo|OBIGO)[^\\d]*(\\d+)(?:.(\\d+))?",
       "v1_replacement":null,
       "family_replacement":"Obigo"},
      {"pattern":"(MAXTHON|Maxthon) (\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Maxthon"},
      {"pattern":"(Maxthon|MyIE2|Uzbl|Shiira)",
       "v1_replacement":"0",
       "family_replacement":null},
      {"pattern":"(PLAYSTATION) (\\d+)",
       "v1_replacement":null,
       "family_replacement":"PlayStation"},
      {"pattern":"(PlayStation Portable)[^\\d]+(\\d+).(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(BrowseX) \\((\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Opera)/(\\d+)\\.(\\d+).*Opera Mobi",
       "v1_replacement":null,
       "family_replacement":"Opera Mobile"},
      {"pattern":"(POLARIS)/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Polaris"},
      {"pattern":"(BonEcho)/(\\d+)\\.(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Bon Echo"},
      {"pattern":"(iPhone) OS (\\d+)_(\\d+)(?:_(\\d+))?",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Avant)",
       "v1_replacement":"1",
       "family_replacement":null},
      {"pattern":"(Nokia)[EN]?(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Black[bB]erry)(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Blackberry"},
      {"pattern":"(OmniWeb)/v(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Blazer)/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Palm Blazer"},
      {"pattern":"(Pre)/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"Palm Pre"},
      {"pattern":"(Links) \\((\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(QtWeb) Internet Browser/(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(Version)/(\\d+)\\.(\\d+)(?:\\.(\\d+))?.*Safari/",
       "v1_replacement":null,
       "family_replacement":"Safari"},
      {"pattern":"(OLPC)/Update(\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(OLPC)/Update()\\.(\\d+)",
       "v1_replacement":"0",
       "family_replacement":null},
      {"pattern":"(SamsungSGHi560)",
       "v1_replacement":null,
       "family_replacement":"Samsung SGHi560"},
      {"pattern":"^(SonyEricssonK800i)",
       "v1_replacement":null,
       "family_replacement":"Sony Ericsson K800i"},
      {"pattern":"(Teleca Q7)",
       "v1_replacement":null,
       "family_replacement":null},
      {"pattern":"(MSIE) (\\d+)\\.(\\d+)",
       "v1_replacement":null,
       "family_replacement":"IE"}

  ];

  var parsers = regexes.map(function(obj) {
    var regexp = new RegExp(obj.pattern),
        famRep = obj.family_replacement,
        v1Rep = obj.v1_replacement;

    function parser(ua) {
      var m = ua.match(regexp);

      if (!m) { return null; }

      var familly = famRep ? famRep.replace('$1', m[1]) : m[1];

      var obj = new UserAgent(familly);
      obj.major = parseInt(v1Rep ? v1Rep : m[2]);
      obj.minor = m[3] ? parseInt(m[3]) : null;
      obj.patch = m[4] ? parseInt(m[4]) : null;

      return obj;
    }

    return parser;
  });

})(window);

{'repo_name': 'microsoft/WhatTheHack', 'stars': '508', 'repo_language': 'HTML', 'file_name': 'stream_2.txt', 'mime_type': 'text/plain', 'hash': -6373245097852315733, 'source_dataset': 'data'}


using System.Web;
using System.Web.Mvc;

namespace Csharp_xxe
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

{'repo_name': 'c0ny1/xxe-lab', 'stars': '427', 'repo_language': 'Python', 'file_name': 'jquery.bootstrap.js', 'mime_type': 'text/plain', 'hash': 200304400028138414, 'source_dataset': 'data'}


RESOURCE global:initial=1.0:deme=false
RESOURCE deme_ResA:initial=1.0:deme=true
RESOURCE deme_ResB:geometry=grid:initial=1000:inflow=1000:outflow=0.1\
  :deme=true:\
  inflowx1=0:inflowx2=9:inflowy1=1:inflowy2=1:\
  outflowx1=0:outflowx2=9:outflowy1=5:outflowy2=5:\
  xdiffuse=0:ydiffuse=0:xgravity=0:ygravity=0

REACTION  ECHO echo  process:resource=global:value=1000.0:type=energy:frac=1.0:product=global:conversion=2.0 requisite:max_count=10
REACTION  NAND nand  process:resource=deme_ResA:value=1500.0:type=energy:frac=1.0:product=deme_ResA:conversion=1.5 requisite:max_count=10

{'repo_name': 'devosoft/avida', 'stars': '510', 'repo_language': 'C++', 'file_name': 'project.pbxproj', 'mime_type': 'text/plain', 'hash': -1035254436000540327, 'source_dataset': 'data'}


/*******************************************************************************
 * Copyright (c) 2000, 2016 IBM Corp. and others
 *
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License 2.0 which accompanies this
 * distribution and is available at https://www.eclipse.org/legal/epl-2.0/
 * or the Apache License, Version 2.0 which accompanies this distribution and
 * is available at https://www.apache.org/licenses/LICENSE-2.0.
 *
 * This Source Code may also be made available under the following
 * Secondary Licenses when the conditions for such availability set
 * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
 * General Public License, version 2 with the GNU Classpath
 * Exception [1] and GNU General Public License, version 2 with the
 * OpenJDK Assembly Exception [2].
 *
 * [1] https://www.gnu.org/software/classpath/license.html
 * [2] http://openjdk.java.net/legal/assembly-exception.html
 *
 * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
 *******************************************************************************/

#ifndef TR_INSTRUCTION_INCL
#define TR_INSTRUCTION_INCL

#include "codegen/J9Instruction.hpp"

namespace TR
{
class Instruction;

class OMR_EXTENSIBLE Instruction : public J9::InstructionConnector
   {
   public:

   /*
    * Generic constructors
    */
   Instruction(TR::InstOpCode::Mnemonic    op,
            TR::Node          *n,
            TR::CodeGenerator *cg) :
            J9::InstructionConnector(cg, op, n) {}

   Instruction(TR::InstOpCode::Mnemonic    op,
               TR::Node          *n,
               TR::Instruction   *precedingInstruction,
               TR::CodeGenerator *cg):
               J9::InstructionConnector(cg, precedingInstruction, op, n) {}

   /*
    * Z specific constructors, need to call initializer to perform proper construction
    */
   inline Instruction(TR::Instruction *precedingInstruction,
                      TR::InstOpCode::Mnemonic op,
                      TR::RegisterDependencyConditions *cond,
                      TR::CodeGenerator *cg);

   inline Instruction(TR::InstOpCode::Mnemonic    op,
                      TR::Node          *n,
                      TR::RegisterDependencyConditions *cond,
                      TR::CodeGenerator *cg);

   inline Instruction(TR::InstOpCode::Mnemonic    op,
                      TR::Node          *n,
                      TR::RegisterDependencyConditions * cond,
                      TR::Instruction   *precedingInstruction,
                      TR::CodeGenerator *cg);

   };

}

#include "codegen/J9Instruction_inlines.hpp"

TR::Instruction::Instruction(TR::Instruction *precedingInstruction,
                             TR::InstOpCode::Mnemonic op,
                             TR::RegisterDependencyConditions *cond,
                             TR::CodeGenerator                    *cg) :
                             J9::InstructionConnector(cg, precedingInstruction, op) { self()->initialize(precedingInstruction, true, cond, false); }

TR::Instruction::Instruction(TR::InstOpCode::Mnemonic    op,
                             TR::Node          *n,
                             TR::RegisterDependencyConditions *cond,
                             TR::CodeGenerator *cg) :
                             J9::InstructionConnector(cg, op, n) { self()->initialize(NULL, false, cond, true); }

TR::Instruction::Instruction(TR::InstOpCode::Mnemonic    op,
                             TR::Node          *n,
                             TR::RegisterDependencyConditions * cond,
                             TR::Instruction   *precedingInstruction,
                             TR::CodeGenerator *cg) :
                             J9::InstructionConnector(cg, precedingInstruction, op, n) { self()->initialize(precedingInstruction, true, cond, true); }

#endif /* TR_INSTRUCTION_INCL */

{'repo_name': 'eclipse/openj9', 'stars': '2360', 'repo_language': 'Java', 'file_name': 'Build.md', 'mime_type': 'text/plain', 'hash': 4047623461638808994, 'source_dataset': 'data'}


<?php
    require_once('../libs/pgsql.inc.php');

    $query = "SELECT * FROM users ORDER BY " . $_GET['id'];
    dbQuery($query);
?>

{'repo_name': 'sqlmapproject/testenv', 'stars': '272', 'repo_language': 'PHP', 'file_name': 'get_int_3.php', 'mime_type': 'text/x-php', 'hash': 795122872340626822, 'source_dataset': 'data'}


DebugInformationFormat

C7 compatible

Program Database

Program Database for Edit And Continue

CompileAsManaged

No Common Language RunTime Support

Common Language RunTime Support

Pure MSIL Common Language RunTime Support

Safe MSIL Common Language RunTime Support

WarningLevel

Turn Off All Warnings

EnableAllWarnings

DiagnosticsFormat

Caret

Column Info

Classic

Optimization

Custom

Disabled

Maximum Optimization (Favor Size)

Maximum Optimization (Favor Speed)

Optimizations (Favor Speed)

InlineFunctionExpansion

Default

Disabled

Only __inline

Any Suitable

FavorSizeOrSpeed

Favor small code

Favor fast code

Neither

ExceptionHandling

Yes with SEH Exceptions

Yes

Yes with Extern C functions

No

BasicRuntimeChecks

Stack Frames

Uninitialized variables

Both (/RTC1, equiv. to /RTCsu)

Default

RuntimeLibrary

Multi-threaded

Multi-threaded Debug

Multi-threaded DLL

Multi-threaded Debug DLL

StructMemberAlignment

1 Byte

2 Bytes

4 Byte

8 Bytes

16 Bytes

Default

BufferSecurityCheck

Disable Security Check

Enable Security Check

ControlFlowGuard

Yes

No

EnableEnhancedInstructionSet

Streaming SIMD Extensions

Streaming SIMD Extensions 2

Advanced Vector Extensions

Advanced Vector Extensions 2

No Enhanced Instructions

Not Set

FloatingPointModel

Precise

Strict

Fast

SpectreMitigation

Spectre mitigations disabled

Spectre mitigations enabled

LanguageStandard

ISO C++14 Standard

ISO C++17 Standard

Preview - Features from the Latest C++ Working Draft

PrecompiledHeader

Create

Use

Not Using Precompiled Headers

AssemblerOutput

No Listing

Assembly-Only Listing

Assembly With Machine Code

Assembly With Source Code

Assembly, Machine Code and Source

CompileAs

Default

Compile as C Code

Compile as C++ Code

ErrorReporting

Do Not Send Report

Prompt Immediately

Queue For Next Login

Send Automatically

SupportJustMyCode

Support Just My Code Debugging

Support Just My Code Debugging

CompileAsWinRT

Consume Windows Runtime Extension

WinRTNoStdLib

No Standard WinRT Libraries

SuppressStartupBanner

Suppress Startup Banner

TreatWarningAsError

Treat Warnings As Errors

Treat Warnings As Errors

SDLCheck

SDL checks

SDL checks

MultiProcessorCompilation

Multi-processor Compilation

IntrinsicFunctions

Enable Intrinsic Functions

OmitFramePointers

Omit Frame Pointers

Omit Frame Pointers

EnableFiberSafeOptimizations

Enable Fiber-Safe Optimizations

WholeProgramOptimization

Whole Program Optimization

UndefineAllPreprocessorDefinitions

Undefine All Preprocessor Definitions

IgnoreStandardIncludePath

Ignore Standard Include Paths

PreprocessToFile

Preprocess to a File

PreprocessSuppressLineNumbers

Preprocess Suppress Line Numbers

PreprocessKeepComments

Keep Comments

StringPooling

Enable String Pooling

Enable String Pooling

MinimalRebuild

Enable Minimal Rebuild

Enable Minimal Rebuild

SmallerTypeCheck

Smaller Type Check

FunctionLevelLinking

Enable Function-Level Linking

Enable Function-Level Linking

EnableParallelCodeGeneration

Enable Parallel Code Generation

Enable Parallel Code Generation

FloatingPointExceptions

Enable Floating Point Exceptions

Enable Floating Point Exceptions

CreateHotpatchableImage

Create Hotpatchable Image

DisableLanguageExtensions

Disable Language Extensions

ConformanceMode

Conformance mode enabled

Conformance mode disabled

Treat WChar_t As Built in Type

Treat WChar_t As Built in Type

ForceConformanceInForLoopScope

Force Conformance in For Loop Scope

Force Conformance in For Loop Scope

RemoveUnreferencedCodeData

Remove unreferenced code and data

Remove unreferenced code and data

EnforceTypeConversionRules

Enforce type conversion rules

Enforce type conversion rules

RuntimeTypeInfo

Enable Run-Time Type Information

Enable Run-Time Type Information

OpenMPSupport

Open MP Support

Open MP Support

EnableModules

Enable C++ Modules (experimental)

ExpandAttributedSource

Expand Attributed Source

UseUnicodeForAssemblerListing

Use Unicode For Assembler Listing

GenerateXMLDocumentationFiles

Generate XML Documentation Files

BrowseInformation

Enable Browse Information

ShowIncludes

Show Includes

EnablePREfast

Enable Code Analysis

Enable Code Analysis

UseFullPaths

Use Full Paths

OmitDefaultLibName

Omit Default Library Name

AdditionalIncludeDirectories

Additional Include Directories

AdditionalUsingDirectories

Additional #using Directories

PreprocessorDefinitions

Preprocessor Definitions

UndefinePreprocessorDefinitions

Undefine Preprocessor Definitions

DisableSpecificWarnings

Disable Specific Warnings

ForcedIncludeFiles

Forced Include File

ForcedUsingFiles

Forced #using File

PREfastLog

Code Analysis Log

PREfastAdditionalPlugins

Additional Code Analysis Native plugins

TreatSpecificWarningsAsErrors

Treat Specific Warnings As Errors

WarningVersion

Warning Version

PreprocessOutputPath

Preprocess Output Path

PrecompiledHeaderFile

Precompiled Header File

Precompiled Header File

PrecompiledHeaderOutputFile

Precompiled Header Output File

AssemblerListingLocation

ASM List Location

ObjectFileName

Object File Name

ProgramDataBaseFileName

Program Database File Name

XMLDocumentationFileName

XML Documentation File Name

BrowseInformationFile

Browse Information File

ProcessorNumber

Number of processors

{'repo_name': 'jpvanoosten/LearningDirectX12', 'stars': '172', 'repo_language': 'C++', 'file_name': 'DebSourcePPA.cmake', 'mime_type': 'text/plain', 'hash': 5214323932114023732, 'source_dataset': 'data'}


/************************************************************************
 * Copyright (C) 2002-2009, Xiph.org Foundation
 * Copyright (C) 2010, Robin Watts for Pinknoise Productions Ltd
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the names of the Xiph.org Foundation nor Pinknoise
 * Productions Ltd nor the names of its contributors may be used to
 * endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ************************************************************************

 function: arm7 and later wide math functions

 ************************************************************************/

#ifdef _ARM_ASSEM_

#if !defined(_V_WIDE_MATH) && !defined(_LOW_ACCURACY_)
#define _V_WIDE_MATH

static inline ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) {
  int lo,hi;
  asm volatile("smull\t%0, %1, %2, %3"
               : "=&r"(lo),"=&r"(hi)
               : "%r"(x),"r"(y)
	       : "cc");
  return(hi);
}

static inline ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) {
  return MULT32(x,y)<<1;
}

static inline ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) {
  int lo,hi;
  asm volatile("smull	%0, %1, %2, %3\n\t"
	       "movs	%0, %0, lsr #15\n\t"
	       "adc	%1, %0, %1, lsl #17\n\t"
               : "=&r"(lo),"=&r"(hi)
               : "%r"(x),"r"(y)
	       : "cc");
  return(hi);
}

#define MB() asm volatile ("" : : : "memory")

static inline void XPROD32(ogg_int32_t  a, ogg_int32_t  b,
			   ogg_int32_t  t, ogg_int32_t  v,
			   ogg_int32_t *x, ogg_int32_t *y)
{
  int x1, y1, l;
  asm(	"smull	%0, %1, %4, %6\n\t"
	"smlal	%0, %1, %5, %7\n\t"
	"rsb	%3, %4, #0\n\t"
	"smull	%0, %2, %5, %6\n\t"
	"smlal	%0, %2, %3, %7"
	: "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a)
	: "3" (a), "r" (b), "r" (t), "r" (v)
	: "cc" );
  *x = x1;
  MB();
  *y = y1;
}

/* x = (a*t + b*v)>>31,    y = (b*t - a*v)>>31 */
static inline void XPROD31(ogg_int32_t  a, ogg_int32_t  b,
			   ogg_int32_t  t, ogg_int32_t  v,
			   ogg_int32_t *x, ogg_int32_t *y)
{
  int x1, y1, l;
  asm(	"smull	%0, %1, %4, %6\n\t"
	"smlal	%0, %1, %5, %7\n\t"
	"rsb	%3, %4, #0\n\t"
	"smull	%0, %2, %5, %6\n\t"
	"smlal	%0, %2, %3, %7"
	: "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a)
	: "3" (a), "r" (b), "r" (t), "r" (v)
	: "cc" );
  *x = x1 << 1;
  MB();
  *y = y1 << 1;
}

/* x = (a*t - b*v)>>31,     y = (b*t + a*v)>>31 */
static inline void XNPROD31(ogg_int32_t  a, ogg_int32_t  b,
			    ogg_int32_t  t, ogg_int32_t  v,
			    ogg_int32_t *x, ogg_int32_t *y)
{
  int x1, y1, l;
  asm(	"rsb	%2, %4, #0\n\t"
	"smull	%0, %1, %3, %5\n\t"
	"smlal	%0, %1, %2, %6\n\t"
	"smull	%0, %2, %4, %5\n\t"
	"smlal	%0, %2, %3, %6"
	: "=&r" (l), "=&r" (x1), "=&r" (y1)
	: "r" (a), "r" (b), "r" (t), "r" (v)
	: "cc" );
  *x = x1 << 1;
  MB();
  *y = y1 << 1;
}

#endif

#ifndef _V_CLIP_MATH
#define _V_CLIP_MATH

static inline ogg_int32_t CLIP_TO_15(ogg_int32_t x) {
  int tmp;
  asm volatile("subs	%1, %0, #32768\n\t"
	       "movpl	%0, #0x7f00\n\t"
	       "orrpl	%0, %0, #0xff\n"
	       "adds	%1, %0, #32768\n\t"
	       "movmi	%0, #0x8000"
	       : "+r"(x),"=r"(tmp)
	       :
	       : "cc");
  return(x);
}

#endif

#ifndef _V_LSP_MATH_ASM
#define _V_LSP_MATH_ASM

static inline void lsp_loop_asm(ogg_uint32_t *qip,ogg_uint32_t *pip,
				ogg_int32_t *qexpp,
				ogg_int32_t *ilsp,ogg_int32_t wi,
				ogg_int32_t m){

  ogg_uint32_t qi=*qip,pi=*pip;
  ogg_int32_t qexp=*qexpp;

  asm("mov     r0,%3;"
      "mov     r1,%5,asr#1;"
      "add     r0,r0,r1,lsl#3;"
      "1:"

      "ldmdb   r0!,{r1,r3};"
      "subs    r1,r1,%4;"          //ilsp[j]-wi
      "rsbmi   r1,r1,#0;"          //labs(ilsp[j]-wi)
      "umull   %0,r2,r1,%0;"       //qi*=labs(ilsp[j]-wi)

      "subs    r1,r3,%4;"          //ilsp[j+1]-wi
      "rsbmi   r1,r1,#0;"          //labs(ilsp[j+1]-wi)
      "umull   %1,r3,r1,%1;"       //pi*=labs(ilsp[j+1]-wi)

      "cmn     r2,r3;"             // shift down 16?
      "beq     0f;"
      "add     %2,%2,#16;"
      "mov     %0,%0,lsr #16;"
      "orr     %0,%0,r2,lsl #16;"
      "mov     %1,%1,lsr #16;"
      "orr     %1,%1,r3,lsl #16;"
      "0:"
      "cmp     r0,%3;\n"
      "bhi     1b;\n"

      // odd filter assymetry
      "ands    r0,%5,#1;\n"
      "beq     2f;\n"
      "add     r0,%3,%5,lsl#2;\n"

      "ldr     r1,[r0,#-4];\n"
      "mov     r0,#0x4000;\n"

      "subs    r1,r1,%4;\n"          //ilsp[j]-wi
      "rsbmi   r1,r1,#0;\n"          //labs(ilsp[j]-wi)
      "umull   %0,r2,r1,%0;\n"       //qi*=labs(ilsp[j]-wi)
      "umull   %1,r3,r0,%1;\n"       //pi*=labs(ilsp[j+1]-wi)

      "cmn     r2,r3;\n"             // shift down 16?
      "beq     2f;\n"
      "add     %2,%2,#16;\n"
      "mov     %0,%0,lsr #16;\n"
      "orr     %0,%0,r2,lsl #16;\n"
      "mov     %1,%1,lsr #16;\n"
      "orr     %1,%1,r3,lsl #16;\n"

      //qi=(pi>>shift)*labs(ilsp[j]-wi);
      //pi=(qi>>shift)*labs(ilsp[j+1]-wi);
      //qexp+=shift;

      //}

      /* normalize to max 16 sig figs */
      "2:"
      "mov     r2,#0;"
      "orr     r1,%0,%1;"
      "tst     r1,#0xff000000;"
      "addne   r2,r2,#8;"
      "movne   r1,r1,lsr #8;"
      "tst     r1,#0x00f00000;"
      "addne   r2,r2,#4;"
      "movne   r1,r1,lsr #4;"
      "tst     r1,#0x000c0000;"
      "addne   r2,r2,#2;"
      "movne   r1,r1,lsr #2;"
      "tst     r1,#0x00020000;"
      "addne   r2,r2,#1;"
      "movne   r1,r1,lsr #1;"
      "tst     r1,#0x00010000;"
      "addne   r2,r2,#1;"
      "mov     %0,%0,lsr r2;"
      "mov     %1,%1,lsr r2;"
      "add     %2,%2,r2;"

      : "+r"(qi),"+r"(pi),"+r"(qexp)
      : "r"(ilsp),"r"(wi),"r"(m)
      : "r0","r1","r2","r3","cc");

  *qip=qi;
  *pip=pi;
  *qexpp=qexp;
}

static inline void lsp_norm_asm(ogg_uint32_t *qip,ogg_int32_t *qexpp){

  ogg_uint32_t qi=*qip;
  ogg_int32_t qexp=*qexpp;

  asm("tst     %0,#0x0000ff00;"
      "moveq   %0,%0,lsl #8;"
      "subeq   %1,%1,#8;"
      "tst     %0,#0x0000f000;"
      "moveq   %0,%0,lsl #4;"
      "subeq   %1,%1,#4;"
      "tst     %0,#0x0000c000;"
      "moveq   %0,%0,lsl #2;"
      "subeq   %1,%1,#2;"
      "tst     %0,#0x00008000;"
      "moveq   %0,%0,lsl #1;"
      "subeq   %1,%1,#1;"
      : "+r"(qi),"+r"(qexp)
      :
      : "cc");
  *qip=qi;
  *qexpp=qexp;
}

#endif
#endif

{'repo_name': 'ErLinErYi/PlantsVsZombies', 'stars': '293', 'repo_language': 'C++', 'file_name': 'org.eclipse.ltk.core.refactoring.prefs', 'mime_type': 'text/plain', 'hash': -4931054299269889302, 'source_dataset': 'data'}


# LaunchAtLoginController

A very simple to implement Controller for use in Cocoa Mac Apps to register/deregister itself for Launch at Login using LSSharedFileList.

It uses LSSharedFileList which means your Users will be able to check System Preferences > Accounts > Login Items.

I'm currently using it on 10.6 (32/64) successfully. I've not investigated being able to flag the "Hide" flag which is possible from System Preferences.

## IMPLEMENTATION (Code):

### Will app launch at login?

    LaunchAtLoginController *launchController = [[LaunchAtLoginController alloc] init];
	BOOL launch = [launchController launchAtLogin];
	[launchController release];

### Set launch at login state.

	LaunchAtLoginController *launchController = [[LaunchAtLoginController alloc] init];
	[launchController setLaunchAtLogin:YES];
	[launchController release];

## IMPLEMENTATION (Interface builder):

* Open Interface Builder
* Place a NSObject (the blue box) into the nib window
* From the Inspector - Identity Tab (Cmd+6) set the Class to LaunchAtLoginController
* Place a Checkbox on your Window/View
* From the Inspector - Bindings Tab (Cmd+4) unroll the > Value item
  * Bind to Launch at Login Controller
  * Model Key Path: launchAtLogin

## IS IT WORKING:

After implementing either through code or through IB, setLaunchAtLogin:YES and then check System Preferences > Accounts > Login Items. You should see your app in the list of apps that will start when the user logs in.

## CAVEATS (HelperApp Bundles):

If you're trying to set a different bundle (perhaps a HelperApp as a resource to your main bundle) you will simply want to change
    - (NSURL *)appURL
to return the path to this other bundle.

## REQUIREMENTS:

Works on 10.6/10.5

## ORIGINAL CODE IDEAS:

* Growl.
* User: invariant Link: (http://stackoverflow.com/questions/815063/how-do-you-make-your-app-open-at-login/2318004#2318004)

## LICENSE:

(The MIT License)

Copyright (c) 2010 Ben Clark-Robinson, ben.clarkrobinson@gmail.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

{'repo_name': 'mithril-global/GoAgentX', 'stars': '203', 'repo_language': 'Python', 'file_name': 'ServicesMenu.strings', 'mime_type': 'text/plain', 'hash': 6133342188336952997, 'source_dataset': 'data'}


/*
 *     Generated by class-dump 3.3.4 (64 bit).
 *
 *     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
 */

#import "NSObject.h"

#import "GQZArchiveInputStream-Protocol.h"

@class NSData;

@interface GQZArchiveMemoryInputStream : NSObject <GQZArchiveInputStream>
{
    NSData *mData;
    const char *mBytes;
    long long mSize;
}

- (long long)size;
- (void)readFromOffset:(long long)arg1 size:(unsigned long)arg2 buffer:(char *)arg3;
- (const char *)dataAtOffset:(long long)arg1 size:(unsigned long)arg2 end:(long long)arg3 readSize:(unsigned int *)arg4;
- (void)dealloc;
- (id)initWithData:(id)arg1;

@end

{'repo_name': 'mattlawer/iOS6-Private-Frameworks', 'stars': '107', 'repo_language': 'Objective-C', 'file_name': 'Parser.h', 'mime_type': 'text/x-objective-c', 'hash': 5573832877262113616, 'source_dataset': 'data'}