<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright (C) 2019 The Android Open Source Project

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="24dp"
    android:tint="?android:attr/colorControlNormal"
    android:viewportHeight="24"
    android:viewportWidth="24"
    android:width="24dp" >
    <path
        android:fillColor="@android:color/white"
        android:pathData="M9,8H6L4,4H2v5v8c0,1.66,1.34,3,3,3h14c1.66,0,3-1.34,3-3V9V4h-5l2,4h-3l-2-4h-2l2,4h-3L9,4H7L9,8z M20.5,9v8 c0,0.83-0.67,1.5-1.5,1.5H5c-0.83,0-1.5-0.67-1.5-1.5V9H20.5z" />
</vector>

{'repo_name': 'aosp-mirror/platform_frameworks_base', 'stars': '9245', 'repo_language': 'Java', 'file_name': 'DatabaseCursorTest.java', 'mime_type': 'text/x-java', 'hash': 9012423340602046406, 'source_dataset': 'data'}


<?php
/*
 * This file is a part of GraphQL project.
 *
 * @author Alexandr Viniychuk <a@viniychuk.com>
 * created: 11:54 AM 5/5/16
 */

namespace Youshido\GraphQL\Type\Union;

final class UnionType extends AbstractUnionType
{

    protected $isFinal = true;

    public function resolveType($object)
    {
        $callable = $this->getConfigValue('resolveType');

        return $callable($object);
    }

    public function getTypes()
    {
        return $this->getConfig()->get('types', []);
    }

}

{'repo_name': 'youshido-php/GraphQL', 'stars': '715', 'repo_language': 'PHP', 'file_name': 'TestExtendedType.php', 'mime_type': 'text/x-php', 'hash': 366461635484434573, 'source_dataset': 'data'}


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <istream>

// int sync();

#include <istream>
#include <cassert>

int sync_called = 0;

template <class CharT>
struct testbuf
    : public std::basic_streambuf<CharT>
{
    typedef std::basic_string<CharT> string_type;
    typedef std::basic_streambuf<CharT> base;
private:
    string_type str_;
public:

    testbuf() {}
    testbuf(const string_type& str)
        : str_(str)
    {
        base::setg(const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data()) + str_.size());
    }

    CharT* eback() const {return base::eback();}
    CharT* gptr() const {return base::gptr();}
    CharT* egptr() const {return base::egptr();}

protected:
    int sync()
    {
        ++sync_called;
        return 5;
    }
};

int main()
{
    {
        testbuf<char> sb(" 123456789");
        std::istream is(&sb);
        assert(is.sync() == 0);
        assert(sync_called = 1);
    }
    {
        testbuf<wchar_t> sb(L" 123456789");
        std::wistream is(&sb);
        assert(is.sync() == 0);
        assert(sync_called = 2);
    }
}

{'repo_name': 'google/libcxx', 'stars': '154', 'repo_language': 'C++', 'file_name': 'GetTriple.cmake', 'mime_type': 'text/plain', 'hash': 469991756785044643, 'source_dataset': 'data'}


/*
 * Copyright (c) 2019-2020 Adubbz, Atmosphère-NX
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once
#include <vapours.hpp>

namespace ams::ncm {

    enum class ContentType : u8 {
        Meta                = 0,
        Program             = 1,
        Data                = 2,
        Control             = 3,
        HtmlDocument        = 4,
        LegalInformation    = 5,
        DeltaFragment       = 6,
    };

}

{'repo_name': 'Atmosphere-NX/Atmosphere', 'stars': '4637', 'repo_language': 'C', 'file_name': 'ini.c', 'mime_type': 'text/x-c', 'hash': -8712955987776967233, 'source_dataset': 'data'}


// -*- Mode: vala; indent-tabs-mode: nil; tab-width: 4 -*-
/*-
 * Copyright (c) 2014–2018 elementary, Inc. (https://elementary.io)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Corentin Noël <corentin@elementary.io>
 */

public errordomain PackageLaunchError {
    DESKTOP_ID_NOT_FOUND,
    APP_INFO_NOT_FOUND
}

public errordomain PackageUninstallError {
    APP_STATE_NOT_INSTALLED
}

public class AppCenterCore.PackageDetails : Object {
    public string? name { get; set; }
    public string? description { get; set; }
    public string? summary { get; set; }
    public string? version { get; set; }
}

public class AppCenterCore.Package : Object {
    public const string APPCENTER_PACKAGE_ORIGIN = "appcenter-bionic-main";
    // We stopped using this origin in elementary OS 5.1, references to this can be removed
    // after everyone has had chance to update their appstream-data-pantheon package
    private const string DEPRECATED_ELEMENTARY_STABLE_PACKAGE_ORIGIN = "stable-bionic-main";
    private const string ELEMENTARY_STABLE_PACKAGE_ORIGIN = "elementary-stable-bionic-main";

    /* Note: These are just a stopgap, and are not a replacement for a more
     * fleshed out parental control system. We assume any of these "moderate"
     * or above is considered explicit for our naive warning.
     *
     * See https://hughsie.github.io/oars/generate.html for ratings.
     */
    private const string[] EXPLICIT_TAGS = {
        "violence-realistic",
        "violence-bloodshed",
        "violence-sexual",
        "drugs-narcotics",
        "sex-nudity",
        "sex-themes",
        "sex-prostitution",
        "language-profanity",
        "language-humor",
        "language-discrimination"
    };

    public signal void changing (bool is_changing);
    /**
     * This signal is likely to be fired from a non-main thread. Ensure any UI
     * logic driven from this runs on the GTK thread
     */
    public signal void info_changed (ChangeInformation.Status status);

    public enum State {
        NOT_INSTALLED,
        INSTALLED,
        INSTALLING,
        UPDATE_AVAILABLE,
        UPDATING,
        REMOVING
    }

    public const string OS_UPDATES_ID = "xxx-os-updates";
    public const string LOCAL_ID_SUFFIX = ".appcenter-local";
    public const string DEFAULT_PRICE_DOLLARS = "1";

    public AppStream.Component component { get; protected set; }
    public ChangeInformation change_information { public get; private set; }
    public GLib.Cancellable action_cancellable { public get; private set; }
    public State state { public get; private set; default = State.NOT_INSTALLED; }

    public Backend backend { public get; construct; }

    public double progress {
        get {
            return change_information.progress;
        }
    }

    private bool _installed = false;
    public bool installed {
        get {
            if (component.get_id () == OS_UPDATES_ID) {
                return true;
            }

            return _installed;
        }
    }

    public void mark_installed () {
        _installed = true;
        update_state ();
    }

    public void clear_installed () {
        _installed = false;
        update_state ();
    }

    public bool update_available {
        get {
            return state == State.UPDATE_AVAILABLE;
        }
    }

    /**
     * The component ID of the package with the .desktop suffix removed if it exists.
     * This is used for comparing two packages to see if they have a matching ID
     */
    private string? _component_id = null;
    public string normalized_component_id {
        get {
            if (_component_id != null) {
                return _component_id;
            }

            _component_id = component.id;
            if (_component_id.has_suffix (".desktop")) {
                // ".desktop" is always 8 bytes in UTF-8 so we can just chop 8 bytes off the end
                _component_id = _component_id.substring (0, _component_id.length - 8);
            }

            return _component_id;
        }
    }

    public bool should_pay {
        get {
            if (!is_native || is_os_updates) {
                return false;
            }

            if (get_payments_key () == null || get_suggested_amount () == "0") {
                return false;
            }

            if (component.get_id () in AppCenter.App.settings.get_strv ("paid-apps")) {
                return false;
            }

            var newest_release = get_newest_release ();
            if (newest_release != null && newest_release.get_urgency () == AppStream.UrgencyKind.CRITICAL) {
                return false;
            }

            return true;
        }
    }

    public bool should_nag_update {
        get {
            return update_available && should_pay;
        }
    }

    public bool is_updating {
        get {
            return state == State.UPDATING;
        }
    }

    public bool changes_finished {
        get {
            return change_information.status == ChangeInformation.Status.FINISHED;
        }
    }

    public bool is_os_updates {
        get {
            return component.id == OS_UPDATES_ID;
        }
    }

    public bool is_driver {
       get {
           return component.get_kind () == AppStream.ComponentKind.DRIVER;
       }
    }

    public bool is_font {
        get {
            return component.get_kind () == AppStream.ComponentKind.FONT;
        }
    }

    public bool is_local {
        get {
            return component.get_id ().has_suffix (LOCAL_ID_SUFFIX);
        }
    }

    public bool is_shareable {
        get {
            return is_native && !is_driver && !is_os_updates;
        }
    }

    public bool is_native {
        get {
            switch (component.get_origin ()) {
                case APPCENTER_PACKAGE_ORIGIN:
                case DEPRECATED_ELEMENTARY_STABLE_PACKAGE_ORIGIN:
                case ELEMENTARY_STABLE_PACKAGE_ORIGIN:
                    return true;
                default:
                    return false;
            }
        }
    }

    public bool is_compulsory {
        get {
            unowned string? _current = Environment.get_variable ("XDG_SESSION_DESKTOP");
            if (_current == null) {
                return false;
            }

            string current = _current.down ();
            unowned GenericArray<string> compulsory = component.get_compulsory_for_desktops ();
            for (int i = 0; i < compulsory.length; i++) {
                if (current == compulsory[i].down ()) {
                    return true;
                }
            }

            return false;
        }
    }

    private bool _explicit = false;
    private bool _check_explicit = true;
    public bool is_explicit {
        get {
            if (_check_explicit) {
                _check_explicit = false;
                var ratings = component.get_content_ratings ();
                for (int i = 0; i < ratings.length; i++) {
                    var rating = ratings[i];

                    foreach (string tag in EXPLICIT_TAGS) {
                        var rating_value = rating.get_value (tag);
                        if (rating_value > AppStream.ContentRatingValue.MILD) {
                            _explicit = true;
                            return _explicit;
                        }
                    }
                }
            }

            return _explicit;
        }
    }

    public bool is_flatpak {
        get {
            return (backend is FlatpakBackend)
                || change_information.updatable_packages.contains (FlatpakBackend.get_default ());
        }
    }

    private string? _author = null;
    public string author {
        get {
            if (_author != null) {
                return _author;
            }

            _author = component.developer_name;

            if (_author == null) {
                var project_group = component.project_group;

                if (project_group != null) {
                    _author = project_group;
                }
            }

            return _author;
        }
    }

    private string? _author_title = null;
    public string author_title {
        get {
            if (_author_title != null) {
                return _author_title;
            }

            _author_title = author;
            if (_author_title == null) {
                _author_title = _("%s Developers").printf (get_name ());
            }

            return _author_title;
        }
    }

    public bool is_plugin {
        get {
            return component.get_kind () == AppStream.ComponentKind.ADDON;
        }
    }

    public Gee.Collection<Package> origin_packages {
        owned get {
            return BackendAggregator.get_default ().get_packages_for_component_id (component.get_id ());
        }
    }

    public bool has_multiple_origins {
        get {
            return origin_packages.size > 1;
        }
    }

    public string origin_description {
        owned get {
            unowned string origin = component.get_origin ();
            if (backend is PackageKitBackend) {
                if (origin == APPCENTER_PACKAGE_ORIGIN) {
                    return _("AppCenter");
                } else if (origin == DEPRECATED_ELEMENTARY_STABLE_PACKAGE_ORIGIN || origin == ELEMENTARY_STABLE_PACKAGE_ORIGIN) {
                    return _("elementary Updates");
                } else if (origin.has_prefix ("ubuntu-")) {
                    return _("Ubuntu (non-curated)");
                }
            } else if (backend is FlatpakBackend) {
                var fp_package = this as FlatpakPackage;
                if (fp_package != null && fp_package.installation == FlatpakBackend.system_installation) {
                    return _("%s (system-wide)").printf (origin);
                }

                return origin;
            } else if (backend is UbuntuDriversBackend) {
                return _("Ubuntu Drivers");
            }

            return _("Unknown Origin (non-curated)");
        }
    }

    public int origin_score {
        get {
            int score = 0;

            if (installed) {
                score += 10;
            }

            if (is_native) {
                score += 5;
            }

            if (is_flatpak) {
                score++;

                var fp_package = this as FlatpakPackage;
                if (fp_package != null && fp_package.installation == FlatpakBackend.user_installation) {
                    score++;
                }
            }

            return score;
        }
    }

    public string hash {
        owned get {
            string key = "";
            if (backend is FlatpakBackend) {
                var fp_package = this as FlatpakPackage;
                if (fp_package.installation != null && fp_package.installation == FlatpakBackend.system_installation) {
                    key += "system/";
                } else {
                    key += "user/";
                }
            }

            key += component.get_origin () + "/";
            key += component.get_id ();

            return key;
        }
    }

    private string? name = null;
    public string? description = null;
    private string? summary = null;
    private string? color_primary = null;
    private string? color_primary_text = null;
    private string? payments_key = null;
    private string? suggested_amount = null;
    private string? _latest_version = null;
    public string? latest_version {
        private get { return _latest_version; }
        internal set { _latest_version = convert_version (value); }
    }

    private PackageDetails? backend_details = null;
    private AppInfo? app_info;
    private bool app_info_retrieved = false;

    construct {
        change_information = new ChangeInformation ();
        change_information.status_changed.connect (() => info_changed (change_information.status));

        action_cancellable = new GLib.Cancellable ();
    }

    public Package (Backend backend, AppStream.Component component) {
        Object (backend: backend, component: component);
    }

    public void replace_component (AppStream.Component component) {
        name = null;
        description = null;
        summary = null;
        color_primary = null;
        color_primary_text = null;
        payments_key = null;
        suggested_amount = null;
        _author = null;
        _author_title = null;
        backend_details = null;

        // The version on a PackageKit package comes from the package not AppStream, so only reset the version
        // on other backends
        if (!(backend is PackageKitBackend)) {
            _latest_version = null;
        }

        this.component = component;
    }

    public void update_state () {
        State new_state;

        if (installed) {
            if (change_information.has_changes ()) {
                new_state = State.UPDATE_AVAILABLE;
            } else {
                new_state = State.INSTALLED;
            }
        } else {
            new_state = State.NOT_INSTALLED;
        }

        // Only trigger a notify if the state has changed, quite a lot of things listen to this
        if (state != new_state) {
            state = new_state;
        }
    }

    /**
     * Instructs the backend to update this package
     *
     * @refresh_updates_after: Whether to run the check for updates (and update the badges etc...) after
     * this method succeeds. This is fine after updating a single package, but for efficiency, it's better to
     * do this only once at the end of updating a batch of packages, so this should be set to false if updating
     * multiple packages in a loop.
     *
     */
    public async bool update (bool refresh_updates_after = true) {
        if (state != State.UPDATE_AVAILABLE) {
            return false;
        }

        try {
            var success = yield perform_operation (State.UPDATING, State.INSTALLED, State.UPDATE_AVAILABLE);
            if (success && refresh_updates_after) {
                unowned Client client = Client.get_default ();
                yield client.refresh_updates ();
            }

            return success;
        } catch (Error e) {
            return false;
        }
    }

    public async bool install () {
        if (state != State.NOT_INSTALLED) {
            return false;
        }

        try {
            bool success = yield perform_operation (State.INSTALLING, State.INSTALLED, State.NOT_INSTALLED);
            if (success) {
                var client = AppCenterCore.Client.get_default ();
                client.operation_finished (this, State.INSTALLING, null);
            }

            return success;
        } catch (Error e) {
            var client = AppCenterCore.Client.get_default ();
            client.operation_finished (this, State.INSTALLING, e);
            return false;
        }
    }

    public async bool uninstall () throws Error {
        // We possibly don't know if this package is installed or not yet, so trigger that check first
        _installed = yield backend.is_package_installed (this);

        update_state ();

        if (state == State.INSTALLED || state == State.UPDATE_AVAILABLE) {
            try {
                return yield perform_operation (State.REMOVING, State.NOT_INSTALLED, state);
            } catch (Error e) {
                throw e;
            }
        }

        throw new PackageUninstallError.APP_STATE_NOT_INSTALLED (_("Application state not set as installed in AppCenter for package: %s".printf (get_name ())));
    }

    public void launch () throws Error {
        if (app_info == null) {
            throw new PackageLaunchError.APP_INFO_NOT_FOUND ("AppInfo not found for package: %s".printf (get_name ()));
        }

        try {
            app_info.launch (null, null);
        } catch (Error e) {
            throw e;
        }
    }

    private async bool perform_operation (State performing, State after_success, State after_fail) throws GLib.Error {
        bool success = false;
        prepare_package_operation (performing);
        try {
            success = yield perform_package_operation ();
        } catch (GLib.Error e) {
            warning ("Operation failed for package %s - %s", get_name (), e.message);
            throw e;
        } finally {
            clean_up_package_operation (success, after_success, after_fail);
        }

        return success;
    }

    private void prepare_package_operation (State initial_state) {
        changing (true);

        action_cancellable.reset ();
        change_information.start ();
        state = initial_state;
    }

    private async bool perform_package_operation () throws GLib.Error {
        ChangeInformation.ProgressCallback cb = change_information.callback;
        var client = AppCenterCore.Client.get_default ();

        switch (state) {
            case State.UPDATING:
                var success = yield backend.update_package (this, (owned)cb, action_cancellable);
                if (success) {
                    change_information.clear_update_info ();
                    update_state ();
                }

                return success;
            case State.INSTALLING:
                var success = yield backend.install_package (this, (owned)cb, action_cancellable);
                _installed = success;
                update_state ();
                return success;
            case State.REMOVING:
                var success = yield backend.remove_package (this, (owned)cb, action_cancellable);
                _installed = !success;
                update_state ();
                yield client.refresh_updates ();
                return success;
            default:
                return false;
        }
    }

    private void clean_up_package_operation (bool success, State success_state, State fail_state) {
        changing (false);

        if (success) {
            change_information.complete ();
            state = success_state;
        } else {
            state = fail_state;
            change_information.cancel ();
        }
    }

    public string? get_name () {
        if (name != null) {
            return name;
        }

        name = component.get_name ();
        if (name == null) {
            if (backend_details == null) {
                populate_backend_details_sync ();
            }

            name = backend_details.name;
        }

        return name;
    }

    public void set_name (string? new_name) {
        name = new_name;
    }

    public string? get_description () {
        if (description == null) {
            description = component.get_description ();
            if (description == null) {
                if (backend_details == null) {
                    populate_backend_details_sync ();
                }

                description = backend_details.description;
            }
        }

        return description;
    }

    public string? get_summary () {
        if (summary != null) {
            return summary;
        }

        summary = component.get_summary ();
        if (summary == null) {
            if (backend_details == null) {
                populate_backend_details_sync ();
            }

            summary = backend_details.summary;
        }

        return summary;
    }

    public void set_summary (string? new_summary) {
        summary = new_summary;
    }

    public string get_progress_description () {
        return change_information.status_description;
    }

    public GLib.Icon get_icon (uint size, uint scale_factor) {
        GLib.Icon? icon = null;
        uint current_size = 0;
        uint current_scale = 0;
        uint pixel_size = size * scale_factor;

        weak GenericArray<AppStream.Icon> icons = component.get_icons ();
        for (int i = 0; i < icons.length; i++) {
            weak AppStream.Icon _icon = icons[i];
            switch (_icon.get_kind ()) {
                case AppStream.IconKind.STOCK:
                    unowned string icon_name = _icon.get_name ();
                    if (Gtk.IconTheme.get_default ().has_icon (icon_name)) {
                        return new ThemedIcon (icon_name);
                    }

                    break;
                case AppStream.IconKind.CACHED:
                case AppStream.IconKind.LOCAL:
                    var icon_scale = _icon.get_scale ();
                    var icon_width = _icon.get_width () * icon_scale;
                    bool is_bigger = (icon_width > current_size && current_size < pixel_size);
                    bool has_better_dpi = (icon_width == current_size && current_scale < icon_scale && scale_factor <= icon_scale);
                    if (is_bigger || has_better_dpi) {
                        var file = File.new_for_path (_icon.get_filename ());
                        icon = new FileIcon (file);
                        current_size = icon_width;
                        current_scale = icon_scale;
                    }

                    break;
                case AppStream.IconKind.REMOTE:
                    var icon_scale = _icon.get_scale ();
                    var icon_width = _icon.get_width () * icon_scale;
                    bool is_bigger = (icon_width > current_size && current_size < pixel_size);
                    bool has_better_dpi = (icon_width == current_size && current_scale < icon_scale && scale_factor <= icon_scale);
                    if (is_bigger || has_better_dpi) {
                        var file = File.new_for_uri (_icon.get_url ());
                        icon = new FileIcon (file);
                        current_size = icon_width;
                        current_scale = icon_scale;
                    }

                    break;
            }
        }

        if (icon == null) {
            if (component.get_kind () == AppStream.ComponentKind.ADDON) {
                icon = new ThemedIcon ("extension");
            } else {
                icon = new ThemedIcon ("application-default-icon");
            }
        }

        return icon;
    }

    public Package? get_plugin_host_package () {
        var extends = component.get_extends ();

        if (extends == null || extends.length < 1) {
            return null;
        }

        for (int i = 0; i < extends.length; i++) {
            var package = backend.get_package_for_component_id (extends[i]);
            if (package != null) {
                return package;
            }
        }

        return null;
    }

    public string? get_version () {
        if (latest_version != null) {
            return latest_version;
        }

        if (backend_details == null) {
            populate_backend_details_sync ();
        }

        if (backend_details.version != null) {
            latest_version = backend_details.version;
        }

        return latest_version;
    }

    public string? get_color_primary () {
        if (color_primary != null) {
            return color_primary;
        } else {
            color_primary = component.get_custom_value ("x-appcenter-color-primary");
            return color_primary;
        }
    }

    public string? get_color_primary_text () {
        if (color_primary_text != null) {
            return color_primary_text;
        } else {
            color_primary_text = component.get_custom_value ("x-appcenter-color-primary-text");
            return color_primary_text;
        }
    }

    public string? get_payments_key () {
        if (payments_key != null) {
            return payments_key;
        } else {
            payments_key = component.get_custom_value ("x-appcenter-stripe");
            return payments_key;
        }
    }

    public string get_suggested_amount () {
        if (suggested_amount != null) {
            return suggested_amount;
        } else {
            suggested_amount = component.get_custom_value ("x-appcenter-suggested-price");
            return suggested_amount == null ? DEFAULT_PRICE_DOLLARS : suggested_amount;
        }
    }

    private string convert_version (string version) {
        if (is_os_updates) {
            return version;
        }

        string returned = version;
        returned = returned.split ("+", 2)[0];
        returned = returned.split ("-", 2)[0];
        returned = returned.split ("~", 2)[0];
        if (":" in returned) {
            returned = returned.split (":", 2)[1];
        }

        return returned;
    }

    public bool get_can_launch () {
        if (app_info_retrieved) {
            return app_info != null;
        }

        if (is_compulsory) {
            return false;
        }

        var launchable = component.get_launchable (AppStream.LaunchableKind.DESKTOP_ID);
        if (launchable != null) {
            var launchables = launchable.get_entries ();
            for (int i = 0; i < launchables.length; i++) {
                app_info = new DesktopAppInfo (launchables[i]);
                // A bit strange in Vala, but the DesktopAppInfo constructor does indeed return null if the desktop
                // file isn't found: https://valadoc.org/gio-unix-2.0/GLib.DesktopAppInfo.DesktopAppInfo.html
                if (app_info != null) {
                    break;
                }
            }
        }

        if (app_info != null) {
            app_info_retrieved = true;
            return true;
        }

        // Fallback to trying Appstream ID as desktop ID for applications that haven't updated to the newest spec yet
        string? desktop_id = component.id;
        if (desktop_id != null) {
            app_info = new DesktopAppInfo (desktop_id);
        }

        app_info_retrieved = true;
        return app_info != null;
    }

    public Gee.ArrayList<AppStream.Release> get_newest_releases (int min_releases, int max_releases) {
        var list = new Gee.ArrayList<AppStream.Release> ();

        var releases = component.get_releases ();
        uint index = 0;
        while (index < releases.length) {
            if (releases[index].get_version () == null) {
                releases.remove_index (index);
                if (index >= releases.length) {
                    break;
                }

                continue;
            }

            index++;
        }

        if (releases.length < min_releases) {
            return list;
        }

        releases.sort_with_data ((a, b) => {
            return b.vercmp (a);
        });

        string installed_version = get_version ();

        int start_index = 0;
        int end_index = min_releases;

        if (installed) {
            for (int i = 0; i < releases.length; i++) {
                var release = releases.@get (i);
                unowned string release_version = release.get_version ();
                if (release_version == null) {
                    continue;
                }

                if (AppStream.utils_compare_versions (release_version, installed_version) == 0) {
                    end_index = i.clamp (min_releases, max_releases);
                    break;
                }
            }
        }

        for (int j = start_index; j < end_index; j++) {
            list.add (releases.get (j));
        }

        return list;
    }

    public AppStream.Release? get_newest_release () {
        var releases = component.get_releases ();
        releases.sort_with_data ((a, b) => {
            if (a.get_version () == null || b.get_version () == null) {
                if (a.get_version () != null) {
                    return -1;
                } else if (b.get_version () != null) {
                    return 1;
                } else {
                    return 0;
                }
            }

            return b.vercmp (a);
        });

        if (releases.length > 0) {
            return releases[0];
        }

        return null;
    }

    public async uint64 get_download_size_including_deps () {
        uint64 size = 0;
        try {
            size = yield backend.get_download_size (this, null);
        } catch (Error e) {
            warning ("Error getting download size: %s", e.message);
        }

        return size;
    }

    private void populate_backend_details_sync () {
        if (component.id == OS_UPDATES_ID || is_local) {
            backend_details = new PackageDetails ();
            return;
        }

        var loop = new MainLoop ();
        PackageDetails? result = null;
        backend.get_package_details.begin (this, (obj, res) => {
            try {
                result = backend.get_package_details.end (res);
            } catch (Error e) {
                warning (e.message);
            } finally {
                loop.quit ();
            }
        });

        loop.run ();
        backend_details = result;
        if (backend_details == null) {
            backend_details = new PackageDetails ();
        }
    }
}

{'repo_name': 'elementary/appcenter', 'stars': '307', 'repo_language': 'Vala', 'file_name': 'categories.gresource.xml', 'mime_type': 'text/xml', 'hash': 5958569162093697948, 'source_dataset': 'data'}


# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for the snippet management service."""
from mobly.controllers.android_device_lib import errors
from mobly.controllers.android_device_lib import snippet_client
from mobly.controllers.android_device_lib.services import base_service

MISSING_SNIPPET_CLIENT_MSG = 'No snippet client is registered with name "%s".'

class Error(errors.ServiceError):
    """Root error type for snippet management service."""
    SERVICE_TYPE = 'SnippetManagementService'

class SnippetManagementService(base_service.BaseService):
    """Management service of snippet clients.

    This service manages all the snippet clients associated with an Android
    device.
    """

    def __init__(self, device, configs=None):
        del configs  # Unused param.
        self._device = device
        self._is_alive = False
        self._snippet_clients = {}
        super(SnippetManagementService, self).__init__(device)

    @property
    def is_alive(self):
        """True if any client is running, False otherwise."""
        return any(
            [client.is_alive for client in self._snippet_clients.values()])

    def get_snippet_client(self, name):
        """Gets the snippet client managed under a given name.

        Args:
            name: string, the name of the snippet client under management.

        Returns:
            SnippetClient.
        """
        if name in self._snippet_clients:
            return self._snippet_clients[name]

    def add_snippet_client(self, name, package):
        """Adds a snippet client to the management.

        Args:
            name: string, the attribute name to which to attach the snippet
                client. E.g. `name='maps'` attaches the snippet client to
                `ad.maps`.
            package: string, the package name of the snippet apk to connect to.

        Raises:
            Error, if a duplicated name or package is passed in.
        """
        # Should not load snippet with the same name more than once.
        if name in self._snippet_clients:
            raise Error(
                self,
                'Name "%s" is already registered with package "%s", it cannot '
                'be used again.' %
                (name, self._snippet_clients[name].client.package))
        # Should not load the same snippet package more than once.
        for snippet_name, client in self._snippet_clients.items():
            if package == client.package:
                raise Error(
                    self,
                    'Snippet package "%s" has already been loaded under name'
                    ' "%s".' % (package, snippet_name))
        client = snippet_client.SnippetClient(package=package, ad=self._device)
        client.start_app_and_connect()
        self._snippet_clients[name] = client

    def remove_snippet_client(self, name):
        """Removes a snippet client from management.

        Args:
            name: string, the name of the snippet client to remove.

        Raises:
            Error: if no snippet client is managed under the specified name.
        """
        if name not in self._snippet_clients:
            raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)
        client = self._snippet_clients.pop(name)
        client.stop_app()

    def start(self):
        """Starts all the snippet clients under management."""
        for client in self._snippet_clients.values():
            if not client.is_alive:
                self._device.log.debug('Starting SnippetClient<%s>.',
                                       client.package)
                client.start_app_and_connect()
            else:
                self._device.log.debug(
                    'Not startng SnippetClient<%s> because it is already alive.',
                    client.package)

    def stop(self):
        """Stops all the snippet clients under management."""
        for client in self._snippet_clients.values():
            if client.is_alive:
                self._device.log.debug('Stopping SnippetClient<%s>.',
                                       client.package)
                client.stop_app()
            else:
                self._device.log.debug(
                    'Not stopping SnippetClient<%s> because it is not alive.',
                    client.package)

    def pause(self):
        """Pauses all the snippet clients under management.

        This clears the host port of a client because a new port will be
        allocated in `resume`.
        """
        for client in self._snippet_clients.values():
            self._device.log.debug(
                'Clearing host port %d of SnippetClient<%s>.',
                client.host_port, client.package)
            client.clear_host_port()

    def resume(self):
        """Resumes all paused snippet clients."""
        for client in self._snippet_clients.values():
            # Resume is only applicable if a client is alive and does not have
            # a host port.
            if client.is_alive and client.host_port is None:
                self._device.log.debug('Resuming SnippetClient<%s>.',
                                       client.package)
                client.restore_app_connection()
            else:
                self._device.log.debug('Not resuming SnippetClient<%s>.',
                                       client.package)

    def __getattr__(self, name):
        client = self.get_snippet_client(name)
        if client:
            return client
        return self.__getattribute__(name)

{'repo_name': 'google/mobly', 'stars': '376', 'repo_language': 'Python', 'file_name': 'logcat_test.py', 'mime_type': 'text/x-python', 'hash': -8202392973933282573, 'source_dataset': 'data'}


/*
 * Copyright (C) 2010 Google Inc. 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 name of Google Inc. 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.
 */

WebInspector.DebuggerModel = function()
{
    this._debuggerPausedDetails = {};
    this._scripts = {};

    InspectorBackend.registerDomainDispatcher("Debugger", new WebInspector.DebuggerDispatcher(this));
}

WebInspector.DebuggerModel.Events = {
    DebuggerWasEnabled: "debugger-was-enabled",
    DebuggerWasDisabled: "debugger-was-disabled",
    DebuggerPaused: "debugger-paused",
    DebuggerResumed: "debugger-resumed",
    ParsedScriptSource: "parsed-script-source",
    FailedToParseScriptSource: "failed-to-parse-script-source",
    BreakpointResolved: "breakpoint-resolved",
    Reset: "reset"
}

WebInspector.DebuggerModel.prototype = {
    enableDebugger: function()
    {
        DebuggerAgent.enable();
    },

    disableDebugger: function()
    {
        DebuggerAgent.disable();
    },

    _debuggerWasEnabled: function()
    {
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasEnabled);
    },

    _debuggerWasDisabled: function()
    {
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasDisabled);
    },

    continueToLocation: function(location)
    {
        DebuggerAgent.continueToLocation(location);
    },

    setBreakpoint: function(url, lineNumber, columnNumber, condition, callback)
    {
        // Adjust column if needed.
        var minColumnNumber = 0;
        for (var id in this._scripts) {
            var script = this._scripts[id];
            if (url === script.sourceURL && lineNumber === script.lineOffset)
                minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset;
        }
        columnNumber = Math.max(columnNumber, minColumnNumber);

        function didSetBreakpoint(error, breakpointId, locations)
        {
            if (callback)
                callback(error ? null : breakpointId, locations);
        }
        DebuggerAgent.setBreakpointByUrl(url, lineNumber, columnNumber, condition, didSetBreakpoint.bind(this));
    },

    setBreakpointBySourceId: function(location, condition, callback)
    {
        function didSetBreakpoint(error, breakpointId, actualLocation)
        {
            if (callback)
                callback(error ? null : breakpointId, [actualLocation]);
        }
        DebuggerAgent.setBreakpoint(location, condition, didSetBreakpoint.bind(this));
    },

    removeBreakpoint: function(breakpointId, callback)
    {
        DebuggerAgent.removeBreakpoint(breakpointId, callback);
    },

    _breakpointResolved: function(breakpointId, location)
    {
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BreakpointResolved, {breakpointId: breakpointId, location: location});
    },

    reset: function()
    {
        this._debuggerPausedDetails = {};
        this._scripts = {};
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.Reset);
    },

    get scripts()
    {
        return this._scripts;
    },

    scriptForSourceID: function(sourceID)
    {
        return this._scripts[sourceID];
    },

    scriptsForURL: function(url)
    {
        return this.queryScripts(function(s) { return s.sourceURL === url; });
    },

    queryScripts: function(filter)
    {
        var scripts = [];
        for (var sourceID in this._scripts) {
            var script = this._scripts[sourceID];
            if (filter(script))
                scripts.push(script);
        }
        return scripts;
    },

    editScriptSource: function(sourceID, newSource, callback)
    {
        this._scripts[sourceID].editSource(newSource, this._didEditScriptSource.bind(this, sourceID, newSource, callback));
    },

    _didEditScriptSource: function(sourceID, newSource, callback, error, callFrames)
    {
        if (!error && callFrames && callFrames.length)
            this._debuggerPausedDetails.callFrames = callFrames;
        callback(error);
    },

    get callFrames()
    {
        return this._debuggerPausedDetails.callFrames;
    },

    get debuggerPausedDetails()
    {
        return this._debuggerPausedDetails;
    },

    _pausedScript: function(details)
    {
        this._debuggerPausedDetails = details;
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerPaused, details);
    },

    _resumedScript: function()
    {
        this._debuggerPausedDetails = {};
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerResumed);
    },

    _parsedScriptSource: function(sourceID, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript)
    {
        var script = new WebInspector.Script(sourceID, sourceURL, startLine, startColumn, endLine, endColumn, undefined, undefined, isContentScript);
        this._scripts[sourceID] = script;
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ParsedScriptSource, script);
    },

    _failedToParseScriptSource: function(sourceURL, source, startingLine, errorLine, errorMessage)
    {
        var script = new WebInspector.Script(null, sourceURL, startingLine, 0, 0, 0, errorLine, errorMessage, undefined);
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, script);
    }
}

WebInspector.DebuggerModel.prototype.__proto__ = WebInspector.Object.prototype;

WebInspector.DebuggerEventTypes = {
    JavaScriptPause: 0,
    JavaScriptBreakpoint: 1,
    NativeBreakpoint: 2
};

WebInspector.DebuggerDispatcher = function(debuggerModel)
{
    this._debuggerModel = debuggerModel;
}

WebInspector.DebuggerDispatcher.prototype = {
    paused: function(details)
    {
        this._debuggerModel._pausedScript(details);
    },

    resumed: function()
    {
        this._debuggerModel._resumedScript();
    },

    debuggerWasEnabled: function()
    {
        this._debuggerModel._debuggerWasEnabled();
    },

    debuggerWasDisabled: function()
    {
        this._debuggerModel._debuggerWasDisabled();
    },

    scriptParsed: function(sourceID, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript)
    {
        this._debuggerModel._parsedScriptSource(sourceID, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript);
    },

    scriptFailedToParse: function(sourceURL, source, startingLine, errorLine, errorMessage)
    {
        this._debuggerModel._failedToParseScriptSource(sourceURL, source, startingLine, errorLine, errorMessage);
    },

    breakpointResolved: function(breakpointId, sourceID, lineNumber, columnNumber)
    {
        this._debuggerModel._breakpointResolved(breakpointId, sourceID, lineNumber, columnNumber);
    }
}

{'repo_name': 'AlloyTeam/webtop', 'stars': '287', 'repo_language': 'C++', 'file_name': 'nphostapi.h', 'mime_type': 'text/x-c', 'hash': -5768066514307074313, 'source_dataset': 'data'}


<?php
// Heading
$_['heading_title']     = 'Latest Orders';

// Text
$_['text_extension']    = 'Extensions';
$_['text_success']      = 'Success: You have modified dashboard recent orders!';
$_['text_edit']         = 'Edit Dashboard Recent Orders';

// Column
$_['column_order_id']   = 'Order ID';
$_['column_customer']   = 'Customer';
$_['column_status']     = 'Status';
$_['column_total']      = 'Total';
$_['column_date_added'] = 'Date Added';
$_['column_action']     = 'Action';

// Entry
$_['entry_status']      = 'Status';
$_['entry_sort_order']  = 'Sort Order';
$_['entry_width']       = 'Width';

// Error
$_['error_permission']  = 'Warning: You do not have permission to modify dashboard recent orders!';

{'repo_name': 'myopencart/ocStore', 'stars': '107', 'repo_language': 'PHP', 'file_name': 'SetupTest.php', 'mime_type': 'text/x-php', 'hash': -3024627510401121196, 'source_dataset': 'data'}


// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials  : https://learngoprogramming.com
// In-person training  : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"
)

const data = `
[
        {
                "id": 1,
                "name": "god of war",
                "genre": "action adventure",
                "price": 50
        },
        {
                "id": 2,
                "name": "x-com 2",
                "genre": "strategy",
                "price": 40
        },
        {
                "id": 3,
                "name": "minecraft",
                "genre": "sandbox",
                "price": 20
        }
]`

func main() {
	type item struct {
		id    int
		name  string
		price int
	}

	type game struct {
		item
		genre string
	}

	// ----------------------------------------------------------
	// DECODING SOLUTION:

	// encodable and decodable game type
	type jsonGame struct {
		ID    int    `json:"id"`
		Name  string `json:"name"`
		Genre string `json:"genre"`
		Price int    `json:"price"`
	}

	// load the initial data from json
	var decoded []jsonGame
	if err := json.Unmarshal([]byte(data), &decoded); err != nil {
		fmt.Println("Sorry, there is a problem:", err)
		return
	}

	// load the data into usual game values
	var games []game
	for _, dg := range decoded {
		games = append(games, game{item{dg.ID, dg.Name, dg.Price}, dg.Genre})
	}
	// ----------------------------------------------------------

	// index the games by id
	byID := make(map[int]game)
	for _, g := range games {
		byID[g.id] = g
	}

	fmt.Printf("Inanc's game store has %d games.\n", len(games))

	in := bufio.NewScanner(os.Stdin)
	for {
		fmt.Printf(`
  > list   : lists all the games
  > id N   : queries a game by id
  > save   : exports the data to json and quits
  > quit   : quits

`)

		if !in.Scan() {
			break
		}

		fmt.Println()

		cmd := strings.Fields(in.Text())
		if len(cmd) == 0 {
			continue
		}

		switch cmd[0] {
		case "quit":
			fmt.Println("bye!")
			return

		case "list":
			for _, g := range games {
				fmt.Printf("#%d: %-15q %-20s $%d\n",
					g.id, g.name, "("+g.genre+")", g.price)
			}

		case "id":
			if len(cmd) != 2 {
				fmt.Println("wrong id")
				continue
			}

			id, err := strconv.Atoi(cmd[1])
			if err != nil {
				fmt.Println("wrong id")
				continue
			}

			g, ok := byID[id]
			if !ok {
				fmt.Println("sorry. i don't have the game")
				continue
			}

			fmt.Printf("#%d: %-15q %-20s $%d\n",
				g.id, g.name, "("+g.genre+")", g.price)

		case "save":
			// load the data into the encodable game values
			var encodable []jsonGame
			for _, g := range games {
				encodable = append(encodable,
					jsonGame{g.id, g.name, g.genre, g.price})
			}

			out, err := json.MarshalIndent(encodable, "", "\t")
			if err != nil {
				fmt.Println("Sorry:", err)
				continue
			}

			fmt.Println(string(out))
			return
		}
	}
}

{'repo_name': 'inancgumus/learngo', 'stars': '5544', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 8172941236772246660, 'source_dataset': 'data'}


/*
   Copyright (C) 2009 - 2010

   Artem Makhutov <artem@makhutov.org>
   http://www.makhutov.org

   Dmitry Vagin <dmitry2004@yandex.ru>

   bg <bg_one@mail.ru>
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */

#include "memmem.h"

#include <stdio.h>			/* NULL */
#include <errno.h>			/* errno */
#include <stdlib.h>			/* strtol */

#include "at_parse.h"
#include "mutils.h"			/* ITEMS_OF() */
#include "chan_dongle.h"
#include "pdu.h"			/* pdu_parse() */

#/* */
static unsigned mark_line(char * line, const char * delimiters, char * pointers[])
{
	unsigned found = 0;

	for(; line[0] && delimiters[found]; line++)
	{
		if(line[0] == delimiters[found])
		{
			pointers[found] = line;
			found++;
		}
	}
	return found;
}

/*!
 * \brief Parse a CNUM response
 * \param str -- string to parse (null terminated)
 * @note str will be modified when the CNUM message is parsed
 * \return NULL on error (parse error) or a pointer to the subscriber number
 */

EXPORT_DEF char * at_parse_cnum (char* str)
{
	/*
	 * parse CNUM response in the following format:
	 * +CNUM: <name>,<number>,<type>
	 *   example
	 *   +CNUM: "Subscriber Number","+79139131234",145
	 *   +CNUM: "Subscriber Number","",145
	 *   +CNUM: "Subscriber Number",,145
	 */

	char delimiters[] = ":,,";
	char * marks[STRLEN(delimiters)];

	/* parse URC only here */
	if(mark_line(str, delimiters, marks) == ITEMS_OF(marks))
	{
		marks[1]++;
		if(marks[1][0] == '"')
			marks[1]++;
		if(marks[2][-1] == '"')
			marks[2]--;
		marks[2][0] = 0;
		return marks[1];
	}

	return NULL;
}

/*!
 * \brief Parse a COPS response
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * @note str will be modified when the COPS message is parsed
 * \return NULL on error (parse error) or a pointer to the provider name
 */

EXPORT_DEF char* at_parse_cops (char* str)
{
	/*
	 * parse COPS response in the following format:
	 * +COPS: <mode>[,<format>,<oper>,<?>]
	 *
	 * example
	 *  +COPS: 0,0,"TELE2",0
	 */

	char delimiters[] = ":,,,";
	char * marks[STRLEN(delimiters)];

	/* parse URC only here */
	if(mark_line(str, delimiters, marks) == ITEMS_OF(marks))
	{
		marks[2]++;
		if(marks[2][0] == '"')
			marks[2]++;
		if(marks[3][-1] == '"')
			marks[3]--;
		marks[3][0] = 0;
		return marks[2];
	}

	return NULL;
}

/*!
 * \brief Parse a CREG response
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * \param gsm_reg -- a pointer to a int
 * \param gsm_reg_status -- a pointer to a int
 * \param lac -- a pointer to a char pointer which will store the location area code in hex format
 * \param ci  -- a pointer to a char pointer which will store the cell id in hex format
 * @note str will be modified when the CREG message is parsed
 * \retval  0 success
 * \retval -1 parse error
 */

EXPORT_DEF int at_parse_creg (char* str, unsigned len, int* gsm_reg, int* gsm_reg_status, char** lac, char** ci)
{
	unsigned	i;
	int	state;
	char*	p1 = NULL;
	char*	p2 = NULL;
	char*	p3 = NULL;
	char*	p4 = NULL;

	*gsm_reg = 0;
	*gsm_reg_status = -1;
	*lac = NULL;
	*ci  = NULL;

	/*
	 * parse CREG response in the following format:
	 * +CREG: [<p1>,]<p2>[,<p3>,<p4>]
	 */

	for (i = 0, state = 0; i < len && state < 8; i++)
	{
		switch (state)
		{
			case 0:
				if (str[i] == ':')
				{
					state++;
				}
				break;

			case 1:
				if (str[i] != ' ')
				{
					p1 = &str[i];
					state++;
				}
				/* fall through */

			case 2:
				if (str[i] == ',')
				{
					str[i] = '\0';
					state++;
				}
				break;

			case 3:
				if (str[i] != ' ')
				{
					p2 = &str[i];
					state++;
				}
				/* fall through */
			case 4:
				if (str[i] == ',')
				{
					str[i] = '\0';
					state++;
				}
				break;

			case 5:
				if (str[i] != ' ')
				{
					p3 = &str[i];
					state++;
				}
				/* fall through */

			case 6:
				if (str[i] == ',')
				{
					str[i] = '\0';
					state++;
				}
				break;

			case 7:
				if (str[i] != ' ')
				{
					p4 = &str[i];
					state++;
				}
				break;
		}
	}

	if (state < 2)
	{
		return -1;
	}

	if ((p2 && !p3 && !p4) || (p2 && p3 && p4))
	{
		p1 = p2;
	}

	if (p1)
	{
		errno = 0;
		*gsm_reg_status = (int) strtol (p1, (char**) NULL, 10);
		if (*gsm_reg_status == 0 && errno == EINVAL)
		{
			*gsm_reg_status = -1;
			return -1;
		}

		if (*gsm_reg_status == 1 || *gsm_reg_status == 5)
		{
			*gsm_reg = 1;
		}
	}

	if (p2 && p3 && !p4)
	{
		*lac = p2;
		*ci  = p3;
	}
	else if (p3 && p4)
	{
		*lac = p3;
		*ci  = p4;
	}

	return 0;
}

/*!
 * \brief Parse a CMTI notification
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * @note str will be modified when the CMTI message is parsed
 * \return -1 on error (parse error) or the index of the new sms message
 */

EXPORT_DEF int at_parse_cmti (const char* str)
{
	int index;

	/*
	 * parse cmti info in the following format:
	 * +CMTI: <mem>,<index>
	 */

	return sscanf (str, "+CMTI: %*[^,],%u", &index) == 1 ? index : -1;
}

static const char * parse_cmgr_text(char ** str, size_t len, char * oa, size_t oa_len, str_encoding_t * oa_enc, char ** msg, str_encoding_t * msg_enc)
{
	/*
	 * parse cmgr info in the following TEXT format:
	 * +CMGR: "<msg status>","+123456789",,timestamp<CR><LF>
	 * <message text><CR><LF><CR><LF>
	 * OK<CR><LF>
	 *	or
	 * +CMGR: "<msg status>","002B....",,timestamp<CR><LF>
	 * <message text><CR><LF><CR><LF>
	 * OK<CR><LF>
	 */

	char delimiters[] = ",,,\n";
	char * marks[STRLEN(delimiters)];
	size_t length;

	unsigned count = mark_line(*str, delimiters, marks);
	if(count == ITEMS_OF(marks))
	{
		/* unquote number */
		marks[0]++;
		if(marks[0][0] == '"')
			marks[0]++;
		if(marks[1][-1] == '"')
			marks[1]--;
		length = marks[1] - marks[0] + 1;
		if(oa_len < length)
			return "Not enought space for store number";
		*oa_enc = get_encoding(RECODE_DECODE, marks[0], length  - 1);
		marks[1][0] = 0;
		memcpy(oa, marks[0], length);

		*msg = marks[3] + 1;
		length = len - (*msg - *str);
		*msg_enc = get_encoding(RECODE_DECODE, *msg, length);
		return NULL;
	}
	else if(count > 0)
		*str = marks[count - 1];

	return "Can't parse +CMGR response text";
}

static const char* parse_cmgr_pdu(char** str, attribute_unused size_t len, char* oa, size_t oa_len, str_encoding_t* oa_enc, char** msg, str_encoding_t* msg_enc)
{
	/*
	 * parse cmgr info in the following PDU format
	 * +CMGR: message_status,[address_text],TPDU_length<CR><LF>
	 * SMSC_number_and_TPDU<CR><LF><CR><LF>
	 * OK<CR><LF>
	 *
	 *	sample
	 * +CMGR: 1,,31
	 * 07911234567890F3040B911234556780F20008012150220040210C041F04400438043204350442<CR><LF><CR><LF>
	 * OK<CR><LF>
	 */

	char delimiters[] = ",,\n";
	char * marks[STRLEN(delimiters)];
	char * end;
	size_t tpdu_length;

	if(mark_line(*str, delimiters, marks) == ITEMS_OF(marks))
	{
		tpdu_length = strtol(marks[1] + 1, &end, 10);
		if(tpdu_length <= 0 || end[0] != '\r')
			return "Invalid TPDU length in CMGR PDU status line";
		*str = marks[2] + 1;
		return pdu_parse(str, tpdu_length, oa, oa_len, oa_enc, msg, msg_enc);
	}

	return "Can't parse +CMGR response";
}

/*!
 * \brief Parse a CMGR message
 * \param str -- pointer to pointer of string to parse (null terminated)
 * \param len -- string lenght
 * \param number -- a pointer to a char pointer which will store the from number
 * \param text -- a pointer to a char pointer which will store the message text
 * @note str will be modified when the CMGR message is parsed
 * \retval  0 success
 * \retval -1 parse error
 */

EXPORT_DEF const char * at_parse_cmgr(char ** str, size_t len, char * oa, size_t oa_len, str_encoding_t * oa_enc, char ** msg, str_encoding_t * msg_enc)
{
	const char* rv = "Can't parse +CMGR response line";

	/* skip "+CMGR:" */
	*str += 6;
	len -= 6;

	/* skip leading spaces */
	while(len > 0 && str[0][0] == ' ')
	{
		(*str)++;
		len--;
	}

	if(len > 0)
	{
		/* check PDU or TEXT mode */
		const char* (*fptr)(char** str, size_t len, char* num, size_t num_len, str_encoding_t * oa_enc, char** msg, str_encoding_t * msg_enc);
		fptr = str[0][0] == '"' ? parse_cmgr_text : parse_cmgr_pdu;

		rv = (*fptr)(str, len, oa, oa_len, oa_enc, msg, msg_enc);
	}

	return rv;
}

 /*!
 * \brief Parse a CUSD answer
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * @note str will be modified when the CUSD string is parsed
 * \retval  0 success
 * \retval -1 parse error
 */

EXPORT_DEF int at_parse_cusd (char* str, int * type, char** cusd, int * dcs)
{
	/*
	 * parse cusd message in the following format:
	 * +CUSD: <m>,[<str>,<dcs>]
	 *
	 * examples
	 *   +CUSD: 5
	 *   +CUSD: 0,"100,00 EURO, valid till 01.01.2010, you are using tariff "Mega Tariff". More informations *111#.",15
	 */

	char delimiters[] = ":,,";
	char * marks[STRLEN(delimiters)];
	unsigned count;

	*type = -1;
	*cusd = "";
	*dcs = -1;

	count = mark_line(str, delimiters, marks);
// 0, 1, 2, 3
	if(count > 0)
	{
		if(sscanf(marks[0] + 1, "%u", type) == 1)
		{
			if(count > 1)
			{
				marks[1]++;
				if(marks[1][0] == '"')
					marks[1]++;
				*cusd = marks[1];

				if(count > 2) {
					sscanf(marks[2] + 1, "%u", dcs);
					if(marks[2][-1] == '"')
						marks[2]--;
					marks[2][0] = 0;
				} else {
					int len = strlen(*cusd);
					if(len > 0 && (*cusd)[len - 1] == '"')
						(*cusd)[len-1] = 0;
				}
			}
			return 0;
		}
	}
	return -1;
}

/*!
 * \brief Parse a CPIN notification
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * \return  2 if PUK required
 * \return  1 if PIN required
 * \return  0 if no PIN required
 * \return -1 on error (parse error) or card lock
 */

EXPORT_DEF int at_parse_cpin (char* str, size_t len)
{
	static const struct {
		const char	* value;
		unsigned	length;
	} resp[] = {
		{ "READY", 5 },
		{ "SIM PIN", 7 },
		{ "SIM PUK", 7 },
	};

	unsigned idx;
	for(idx = 0; idx < ITEMS_OF(resp); idx++)
	{
		if(memmem (str, len, resp[idx].value, resp[idx].length) != NULL)
			return idx;
	}
	return -1;
}

/*!
 * \brief Parse +CSQ response
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * \retval  0 success
 * \retval -1 error
 */

EXPORT_DEF int at_parse_csq (const char* str, int* rssi)
{
	/*
	 * parse +CSQ response in the following format:
	 * +CSQ: <RSSI>,<BER>
	 */

	return sscanf (str, "+CSQ:%2d,", rssi) == 1 ? 0 : -1;
}

/*!
 * \brief Parse a ^RSSI notification
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * \return -1 on error (parse error) or the rssi value
 */

EXPORT_DEF int at_parse_rssi (const char* str)
{
	int rssi = -1;

	/*
	 * parse RSSI info in the following format:
	 * ^RSSI:<rssi>
	 */

	sscanf (str, "^RSSI:%d", &rssi);
	return rssi;
}

/*!
 * \brief Parse a ^MODE notification (link mode)
 * \param str -- string to parse (null terminated)
 * \param len -- string lenght
 * \return -1 on error (parse error) or the the link mode value
 */

EXPORT_DEF int at_parse_mode (char * str, int * mode, int * submode)
{
	/*
	 * parse RSSI info in the following format:
	 * ^MODE:<mode>,<submode>
	 */

	return sscanf (str, "^MODE:%d,%d", mode, submode) == 2 ? 0 : -1;
}

#/* */
EXPORT_DEF int at_parse_csca(char* str, char ** csca)
{
	/*
	 * parse CSCA info in the following format:
	 * +CSCA: <SCA>,<TOSCA>
	 *  +CSCA: "+79139131234",145
	 *  +CSCA: "",145
	 */
	char delimiters[] = "\"\"";
	char * marks[STRLEN(delimiters)];

	if(mark_line(str, delimiters, marks) == ITEMS_OF(marks))
	{
		*csca = marks[0] + 1;
		marks[1][0] = 0;
		return 0;
	}

	return -1;
}

#/* */
EXPORT_DEF int at_parse_clcc(char* str, unsigned * call_idx, unsigned * dir, unsigned * state, unsigned * mode, unsigned * mpty, char ** number, unsigned * toa)
{
	/*
	 * +CLCC:<id1>,<dir>,<stat>,<mode>,<mpty>[,<number>,<type>[,<alpha>[,<priority>]]]\r\n
	 *  ...
	 * +CLCC:<id1>,<dir>,<stat>,<mode>,<mpty>[,<number>,<type>[,<alpha>[,<priority>]]]\r\n
	 *  examples
	 *   +CLCC: 1,1,4,0,0,"",145
	 *   +CLCC: 1,1,4,0,0,"+79139131234",145
	 *   +CLCC: 1,1,4,0,0,"0079139131234",145
	 *   +CLCC: 1,1,4,0,0,"+7913913ABCA",145
	 */
	char delimiters[] = ":,,,,,,";
	char * marks[STRLEN(delimiters)];

	*call_idx = 0;
	*dir = 0;
	*state = 0;
	*mode = 0;
	*mpty = 0;
	*number = "";
	*toa = 0;

	if(mark_line(str, delimiters, marks) == ITEMS_OF(marks))
	{
		if( sscanf(marks[0] + 1, "%u", call_idx) == 1
			&&
		    sscanf(marks[1] + 1, "%u", dir) == 1
			&&
		    sscanf(marks[2] + 1, "%u", state) == 1
			&&
		    sscanf(marks[3] + 1, "%u", mode) == 1
			&&
		    sscanf(marks[4] + 1, "%u", mpty) == 1
			&&
		    sscanf(marks[6] + 1, "%u", toa) == 1)
		{
			marks[5]++;
			if(marks[5][0] == '"')
				marks[5]++;
			if(marks[6][-1] == '"')
				marks[6]--;
			*number = marks[5];
			marks[6][0] = 0;

			return 0;
		}
	}

	return -1;
}

#/* */
EXPORT_DEF int at_parse_ccwa(char* str, unsigned * class)
{
	/*
	 * CCWA may be in form:
	 *	in response of AT+CCWA=?
	 *		+CCWA: (0,1)
	 *	in response of AT+CCWA=?
	 *		+CCWA: <n>
	 *	in response of "AT+CCWA=[<n>[,<mode>[,<class>]]]"
	 *		+CCWA: <status>,<class1>
	 *
	 *	unsolicited result code
	 *		+CCWA: <number>,<type>,<class>,[<alpha>][,<CLI validity>[,<subaddr>,<satype>[,<priority>]]]
	 */
	char delimiters[] = ":,,";
	char * marks[STRLEN(delimiters)];

	/* parse URC only here */
	if(mark_line(str, delimiters, marks) == ITEMS_OF(marks))
	{
		if(sscanf(marks[2] + 1, "%u", class) == 1)
			return 0;
	}

	return -1;
}

{'repo_name': 'bg111/asterisk-chan-dongle', 'stars': '239', 'repo_language': 'C', 'file_name': 'dongle.conf', 'mime_type': 'text/plain', 'hash': 9192235250604172812, 'source_dataset': 'data'}


<?php

declare(strict_types=1);

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Extbase\Tests\Unit\Reflection\Fixture;

use TYPO3\CMS\Extbase\Annotation\IgnoreValidation;

/**
 * Dummy controller with @TYPO3\CMS\Extbase\Annotation\IgnoreValidation annotation
 */
class DummyControllerWithIgnoreValidationDoctrineAnnotation
{
    /**
     * @param $foo
     * @param $bar
     * @IgnoreValidation("foo")
     * @IgnoreValidation("bar")
     */
    public function someAction($foo, $bar)
    {
    }
}

{'repo_name': 'TYPO3/TYPO3.CMS', 'stars': '710', 'repo_language': 'PHP', 'file_name': 'Deprecation-77405-PageRepository-getPathFromRootline.rst', 'mime_type': 'text/plain', 'hash': -3165430687570918275, 'source_dataset': 'data'}


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

/*
 * @desc : 队列的链式存储实现方案,两个指针：头指针指向头节点,头节点指向队列第一个节点；尾巴指针
           指向最后队列最后一个节点

           PS:头节点不是队列的第一个节点！

            --------    ---------     ---------     ---------
  头指针--->|头节点|--->|第一节点|--->|第二节点|--->|尾巴节点| <---尾巴指针
            --------    ---------     ---------     ---------

            当队列为空的时候,头指针和尾巴指针都指向 头节点 ～～

 */

typedef struct queue_node {
  int                 element;
  struct queue_node * next;
} queue_node;
typedef queue_node * queue_node_p;

typedef struct queue {
  queue_node_p head;
  queue_node_p tail;
} queue;
typedef queue * queue_p;

void add( queue_p, int );
int  del( queue_p );

int main( int argc, char * argv[] ) {
  // 初始化一个空队列
  queue_p q = ( queue_p )malloc( sizeof( queue ) );
  // 初始化一个头节点
  queue_node_p head_node = ( queue_node_p )malloc( sizeof( queue_node ) );
  head_node->element     = 0;
  head_node->next        = NULL;
  q->head = head_node;
  q->tail = head_node;
  //
  add( q, 1 );
  add( q, 2 );
  add( q, 3 );
  add( q, 4 );
  //
  int temp = del( q );
  printf( "%d\n", temp );
  temp = del( q );
  printf( "%d\n", temp );
  temp = del( q );
  printf( "%d\n", temp );
  temp = del( q );
  printf( "%d\n", temp );
  temp = del( q );
  printf( "%d\n", temp );
  return 0;
}

void add( queue_p q, int element ) {
  // 开辟新节点
  queue_node_p node = ( queue_node_p )malloc( sizeof( queue_node ) );
  node->element = element;
  node->next    = NULL;
  q->tail->next = node;
  q->tail       = node;
}

int del( queue_p q ) {
  if ( q->head == q->tail ) {
    printf( "队列是空的\n" );
    exit( -1 );
  }
  int temp;
  temp = ( *( q->head->next ) ).element;
  q->head = q->head->next;
  free( q->head );
  return temp;
}

{'repo_name': 'elarity/data-structure-php-clanguage', 'stars': '290', 'repo_language': 'C', 'file_name': 'clang.hash-table.c', 'mime_type': 'text/x-c', 'hash': 528804486281319409, 'source_dataset': 'data'}


/*
 * Path handling for intermediate proxies.
 *
 * Copyright (C) 2006 Inode GmbH (Andreas Granig <andreas.granig@inode.info>)
 *
 * This file is part of opensips, a free SIP server.
 *
 * opensips is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version
 *
 * opensips is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 */

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

#include "../../mem/mem.h"
#include "../../lib/path.h"
#include "../../strcommon.h"
#include "../../ut.h"

#include "path_mod.h"

/*
 * Prepend own uri to Path header and take care of given
 * user.
 */
int add_path(struct sip_msg* _msg, str* _usr)
{
	str user = {0,0};
	int rc;

	if (_usr)
		user = *_usr;

	rc = prepend_path(_msg, &user, 0, enable_double_path);
	return rc == 0 ? 1 : rc;
}

/*
 * Prepend own uri to Path header and append received address as
 * "received"-param to that uri.
 */
int add_path_received(struct sip_msg* _msg, str* _usr)
{
	str user = {0,0};
	int rc;

	if (_usr)
		user = *_usr;

	rc = prepend_path(_msg, &user, 1, enable_double_path);
	return rc == 0 ? 1 : rc;
}

/*
 * rr callback
 */
void path_rr_callback(struct sip_msg *_m, str *r_param, void *cb_param)
{
	static str unescape_buf;

	param_hooks_t hooks;
	param_t *params;
	param_t *first_param;
	str received = {0, 0};
	str transport = {0, 0};
	str dst_uri = {0, 0};
	char *p;

	if (parse_params(r_param, CLASS_ANY, &hooks, &params) != 0) {
		LM_ERR("failed to parse route parameters\n");
		return;
	}

	first_param = params;

	while(params)
	{
		if (params->name.len == 8 &&
		    !strncasecmp(params->name.s, "received", params->name.len)) {

			received = params->body;
			if (pkg_str_extend(&unescape_buf, received.len + 1) != 0) {
				LM_ERR("oom\n");
				goto out1;
			}

			if (unescape_param(&received, &unescape_buf) != 0) {
				LM_ERR("failed to unescape received=%.*s\n",
				       received.len, received.s);
				goto out1;
			}

			/* if there's a param here, it has to be ;transport= */
			if ((p = q_memchr(unescape_buf.s, ';', unescape_buf.len))) {
				received.len = p - unescape_buf.s;

				if ((p = q_memchr(p, '=', unescape_buf.len))) {
					transport.s = p + 1;
					transport.len = unescape_buf.s + unescape_buf.len - transport.s;
				}
			}

			break;
		}

		params = params->next;
	}

	LM_DBG("extracted received=%.*s, transport=%.*s\n",
	       received.len, received.s, transport.len, transport.s);

	if (received.len > 0) {
		if (transport.len > 0) {
			dst_uri.len = received.len + PATH_TRANS_PARAM_LEN + 1 + transport.len;
			dst_uri.s = pkg_malloc(dst_uri.len);
			if(!dst_uri.s) {
				LM_ERR("no pkg memory left for receive-address\n");
				goto out1;
			}
			dst_uri.len = snprintf(dst_uri.s, dst_uri.len,
				"%.*s" PATH_TRANS_PARAM "%.*s", received.len, received.s, transport.len, transport.s);
		}
		else
		{
			dst_uri = received;
		}

		if (set_dst_uri(_m, &dst_uri) != 0)
			LM_ERR("failed to set dst-uri\n");

		if (transport.len > 0)
			pkg_free(dst_uri.s);
	}

out1:
	free_params(first_param);
	return;
}

{'repo_name': 'OpenSIPS/opensips', 'stars': '741', 'repo_language': 'C', 'file_name': 'opensips_trunking_def.m4', 'mime_type': 'text/plain', 'hash': 7361418778654378105, 'source_dataset': 'data'}


var _   = require('lodash');

/**
 * formats variables for handlebars in multi-post contexts.
 * If extraValues are available, they are merged in the final value
 * @return {Object} containing page variables
 */
function formatPageResponse(result) {
    var response = {
        posts: result.posts,
        pagination: result.meta.pagination
    };

    _.each(result.data, function (data, name) {
        if (data.meta) {
            // Move pagination to be a top level key
            response[name] = data;
            response[name].pagination = data.meta.pagination;
            delete response[name].meta;
        } else {
            // This is a single object, don't wrap it in an array
            response[name] = data[0];
        }
    });

    return response;
}

/**
 * similar to formatPageResponse, but for single post pages
 * @return {Object} containing page variables
 */
function formatResponse(post) {
    return {
        post: post
    };
}

module.exports = {
    channel: formatPageResponse,
    single: formatResponse
};

{'repo_name': 'felixrieseberg/Ghost-Azure', 'stars': '122', 'repo_language': 'JavaScript', 'file_name': 'index.js', 'mime_type': 'text/plain', 'hash': 1930297143632387568, 'source_dataset': 'data'}


/*
Description: Syslog is called with a user supplied format string.
Keywords: Unix C Size0 Complex0 Taint FormatString
ValidArg: "'NormalString\n'"
InvalidArg: "%s"*100

Copyright 2005 Fortify Software.

Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.

IN NO EVENT SHALL FORTIFY SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF FORTIFY SOFTWARE HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.

FORTIFY SOFTWARE SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.

THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND FORTIFY SOFTWARE HAS NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
*/

#include <syslog.h>

void
test(char *str)
{
	syslog(LOG_CRIT, str);			/* BAD */
}

int
main(int argc, char **argv)
{
	char *userstr;

	if(argc > 1) {
		userstr = argv[1];
		test(userstr);
	}
	return 0;
}

{'repo_name': 'CGCL-codes/VulDeePecker', 'stars': '105', 'repo_language': 'C', 'file_name': 'CWE124_Buffer_Underwrite__char_alloca_ncpy_54a.c', 'mime_type': 'text/x-c', 'hash': -2721367420697665925, 'source_dataset': 'data'}


/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'cs', {
	border: 'Ohraničení',
	caption: 'Popis',
	cell: {
		menu: 'Buňka',
		insertBefore: 'Vložit buňku před',
		insertAfter: 'Vložit buňku za',
		deleteCell: 'Smazat buňky',
		merge: 'Sloučit buňky',
		mergeRight: 'Sloučit doprava',
		mergeDown: 'Sloučit dolů',
		splitHorizontal: 'Rozdělit buňky vodorovně',
		splitVertical: 'Rozdělit buňky svisle',
		title: 'Vlastnosti buňky',
		cellType: 'Typ buňky',
		rowSpan: 'Spojit řádky',
		colSpan: 'Spojit sloupce',
		wordWrap: 'Zalamování',
		hAlign: 'Vodorovné zarovnání',
		vAlign: 'Svislé zarovnání',
		alignBaseline: 'Na účaří',
		bgColor: 'Barva pozadí',
		borderColor: 'Barva okraje',
		data: 'Data',
		header: 'Hlavička',
		yes: 'Ano',
		no: 'Ne',
		invalidWidth: 'Šířka buňky musí být číslo.',
		invalidHeight: 'Zadaná výška buňky musí být číslená.',
		invalidRowSpan: 'Zadaný počet sloučených řádků musí být celé číslo.',
		invalidColSpan: 'Zadaný počet sloučených sloupců musí být celé číslo.',
		chooseColor: 'Výběr'
	},
	cellPad: 'Odsazení obsahu v buňce',
	cellSpace: 'Vzdálenost buněk',
	column: {
		menu: 'Sloupec',
		insertBefore: 'Vložit sloupec před',
		insertAfter: 'Vložit sloupec za',
		deleteColumn: 'Smazat sloupec'
	},
	columns: 'Sloupce',
	deleteTable: 'Smazat tabulku',
	headers: 'Záhlaví',
	headersBoth: 'Obojí',
	headersColumn: 'První sloupec',
	headersNone: 'Žádné',
	headersRow: 'První řádek',
	invalidBorder: 'Zdaná velikost okraje musí být číselná.',
	invalidCellPadding: 'Zadané odsazení obsahu v buňce musí být číselné.',
	invalidCellSpacing: 'Zadaná vzdálenost buněk musí být číselná.',
	invalidCols: 'Počet sloupců musí být číslo větší než 0.',
	invalidHeight: 'Zadaná výška tabulky musí být číselná.',
	invalidRows: 'Počet řádků musí být číslo větší než 0.',
	invalidWidth: 'Šířka tabulky musí být číslo.',
	menu: 'Vlastnosti tabulky',
	row: {
		menu: 'Řádek',
		insertBefore: 'Vložit řádek před',
		insertAfter: 'Vložit řádek za',
		deleteRow: 'Smazat řádky'
	},
	rows: 'Řádky',
	summary: 'Souhrn',
	title: 'Vlastnosti tabulky',
	toolbar: 'Tabulka',
	widthPc: 'procent',
	widthPx: 'bodů',
	widthUnit: 'jednotka šířky'
} );

{'repo_name': 'forcedotcom/aura', 'stars': '678', 'repo_language': 'JavaScript', 'file_name': 'org.eclipse.jdt.core.prefs', 'mime_type': 'text/plain', 'hash': 5196596749078061038, 'source_dataset': 'data'}


//
//  RMStoreTransactionReceiptVerificator.m
//  RMStore
//
//  Created by Hermes Pique on 7/31/13.
//  Copyright (c) 2013 Robot Media SL (http://www.robotmedia.net)
//
//  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.
//

#import "RMStoreTransactionReceiptVerificator.h"

#ifdef DEBUG
#define RMStoreLog(...) NSLog(@"RMStore: %@", [NSString stringWithFormat:__VA_ARGS__]);
#else
#define RMStoreLog(...)
#endif

@interface NSData(rm_base64)

- (NSString *)rm_stringByBase64Encoding;

@end

@implementation NSData(rm_base64)

static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

- (NSString *)rm_stringByBase64Encoding
{ // From: http://stackoverflow.com/a/4727124/143378
    const unsigned char * objRawData = self.bytes;
    char * objPointer;
    char * strResult;

    // Get the Raw Data length and ensure we actually have data
    NSInteger intLength = self.length;
    if (intLength == 0) return nil;

    // Setup the String-based Result placeholder and pointer within that placeholder
    strResult = (char *)calloc((((intLength + 2) / 3) * 4) + 1, sizeof(char));
    objPointer = strResult;

    // Iterate through everything
    while (intLength > 2) { // keep going until we have less than 24 bits
        *objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
        *objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
        *objPointer++ = _base64EncodingTable[((objRawData[1] & 0x0f) << 2) + (objRawData[2] >> 6)];
        *objPointer++ = _base64EncodingTable[objRawData[2] & 0x3f];

        // we just handled 3 octets (24 bits) of data
        objRawData += 3;
        intLength -= 3;
    }

    // now deal with the tail end of things
    if (intLength != 0) {
        *objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
        if (intLength > 1) {
            *objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
            *objPointer++ = _base64EncodingTable[(objRawData[1] & 0x0f) << 2];
            *objPointer++ = '=';
        } else {
            *objPointer++ = _base64EncodingTable[(objRawData[0] & 0x03) << 4];
            *objPointer++ = '=';
            *objPointer++ = '=';
        }
    }

    // Terminate the string-based result
    *objPointer = '\0';

    // Create result NSString object
    NSString *base64String = @(strResult);

    // Free memory
    free(strResult);

    return base64String;
}

@end

@implementation RMStoreTransactionReceiptVerificator

- (void)verifyTransaction:(SKPaymentTransaction*)transaction
                           success:(void (^)())successBlock
                           failure:(void (^)(NSError *error))failureBlock
{
    NSString *receipt = [transaction.transactionReceipt rm_stringByBase64Encoding];
    if (receipt == nil)
    {
        if (failureBlock != nil)
        {
            NSError *error = [NSError errorWithDomain:RMStoreErrorDomain code:0 userInfo:nil];
            failureBlock(error);
        }
        return;
    }
    static NSString *receiptDataKey = @"receipt-data";
    NSDictionary *jsonReceipt = @{receiptDataKey : receipt};

    NSError *error;
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:jsonReceipt options:0 error:&error];
    if (!requestData)
    {
        RMStoreLog(@"Failed to serialize receipt into JSON");
        if (failureBlock != nil)
        {
            failureBlock(error);
        }
        return;
    }

    static NSString *productionURL = @"https://buy.itunes.apple.com/verifyReceipt";

    [self verifyRequestData:requestData url:productionURL success:successBlock failure:failureBlock];
}

- (void)verifyRequestData:(NSData*)requestData
                      url:(NSString*)urlString
                  success:(void (^)())successBlock
                  failure:(void (^)(NSError *error))failureBlock
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPBody = requestData;
    static NSString *requestMethod = @"POST";
    request.HTTPMethod = requestMethod;

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *error;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!data)
            {
                RMStoreLog(@"Server Connection Failed");
                NSError *wrapperError = [NSError errorWithDomain:RMStoreErrorDomain code:RMStoreErrorCodeUnableToCompleteVerification userInfo:@{NSUnderlyingErrorKey : error, NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"Connection to Apple failed. Check the underlying error for more info.", @"RMStore", @"Error description")}];
                if (failureBlock != nil)
                {
                    failureBlock(wrapperError);
                }
                return;
            }
            NSError *jsonError;
            NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            if (!responseJSON)
            {
                RMStoreLog(@"Failed To Parse Server Response");
                if (failureBlock != nil)
                {
                    failureBlock(jsonError);
                }
            }

            static NSString *statusKey = @"status";
            NSInteger statusCode = [responseJSON[statusKey] integerValue];

            static NSInteger successCode = 0;
            static NSInteger sandboxCode = 21007;
            if (statusCode == successCode)
            {
                if (successBlock != nil)
                {
                    successBlock();
                }
            }
            else if (statusCode == sandboxCode)
            {
                RMStoreLog(@"Verifying Sandbox Receipt");
                // From: https://developer.apple.com/library/ios/#technotes/tn2259/_index.html
                // See also: http://stackoverflow.com/questions/9677193/ios-storekit-can-i-detect-when-im-in-the-sandbox
                // Always verify your receipt first with the production URL; proceed to verify with the sandbox URL if you receive a 21007 status code. Following this approach ensures that you do not have to switch between URLs while your application is being tested or reviewed in the sandbox or is live in the App Store.

                static NSString *sandboxURL = @"https://sandbox.itunes.apple.com/verifyReceipt";
                [self verifyRequestData:requestData url:sandboxURL success:successBlock failure:failureBlock];
            }
            else
            {
                RMStoreLog(@"Verification Failed With Code %ld", (long)statusCode);
                NSError *serverError = [NSError errorWithDomain:RMStoreErrorDomain code:statusCode userInfo:nil];
                if (failureBlock != nil)
                {
                    failureBlock(serverError);
                }
            }
        });
    });
}

@end

{'repo_name': 'altairwei/WizNotePlus', 'stars': '310', 'repo_language': 'C++', 'file_name': 'package.xml', 'mime_type': 'text/xml', 'hash': -5183137372711934388, 'source_dataset': 'data'}


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

#import "NSObject.h"

@class MPMediaEntity, MPMediaItemImageRequest, UIViewController<MPUCoverZoomDetailViewControllerProtocol>;

@protocol MPUCoverZoomViewControllerDelegate <NSObject>
- (UIViewController<MPUCoverZoomDetailViewControllerProtocol> *)detailViewControllerForEntity:(MPMediaEntity *)arg1;
- (MPMediaItemImageRequest *)imageRequestForEntity:(MPMediaEntity *)arg1;

@optional
- (float)imageAspectRatio;
- (unsigned int)maximumNumberOfRows;
- (unsigned int)minimumNumberOfRows;
- (unsigned int)defaultNumberOfRows;
@end

{'repo_name': 'MP0w/iOS-Headers', 'stars': '405', 'repo_language': 'Objective-C', 'file_name': 'IMAVChat-IMAVChatAudioAdditions.h', 'mime_type': 'text/x-objective-c', 'hash': -7719829279450828161, 'source_dataset': 'data'}


// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "amount.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(GetFeeTest)
{
    CFeeRate feeRate;

    feeRate = CFeeRate(0);
    // Must always return 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), 0);

    feeRate = CFeeRate(1000);
    // Must always just return the arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), 1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), 121);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), 999);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 1e3);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 9e3);

    feeRate = CFeeRate(-1000);
    // Must always just return -1 * arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), -1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), -121);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), -999);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), -1e3);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), -9e3);

    feeRate = CFeeRate(123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), 1); // Special case: returns 1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), 1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), 14);
    BOOST_CHECK_EQUAL(feeRate.GetFee(122), 15);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), 122);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 123);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 1107);

    feeRate = CFeeRate(-123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), -1); // Special case: returns -1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), -1);

    // Check full constructor
    // default value
    BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1));
    BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1));
    // lost precision (can only resolve satoshis per kB)
    BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1));
    // some more integer checks
    BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32));
    BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34));
    // Maximum size in bytes, should not crash
    CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();
}

BOOST_AUTO_TEST_SUITE_END()

{'repo_name': 'unitusdev/unitus', 'stars': '176', 'repo_language': 'C++', 'file_name': 'rpc-tests.py', 'mime_type': 'text/x-python', 'hash': -7229376058811871707, 'source_dataset': 'data'}