text:
<?php

namespace Acme\BlogBundle\Tests\Controller;

use Acme\BlogBundle\Test\WebTestCase;

class PostControllerTest extends WebTestCase
{
    public function testIndexAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
        $this->setCrawler($crawler);

        $this->assertContains('Blog Posts', $crawler->filter('title')->text());
        $this->assertCrawlerHasNode('h2 a:contains("Unit testing")');
        $this->assertCrawlerHasNode('h2 a:contains("Functional testing")');
    }

    public function testPostsByTagAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/tag/unit testing');
        $this->setCrawler($crawler);

        $this->assertContains('Posts By Tag: unit testing', $crawler->filter('title')->text());
        $this->assertCrawlerHasNode('h2 a:contains("Unit testing")');
        $this->assertCrawlerNotHasNode('h2 a:contains("Functional testing")');
    }

    public function testCreateAction()
    {
        $client = static::createClient(
            array(),
            array(
                'PHP_AUTH_USER' => 'user',
                'PHP_AUTH_PW'   => 'userpass',
            )
        );

        $crawler = $client->request('GET', '/posts/create');
        $this->setCrawler($crawler);

        $this->assertContains('Create a new post', $crawler->filter('title')->text());
        $this->assertCrawlerHasNode('form input[type="text"][required="required"][name="post[title]"]');
        $this->assertCrawlerHasNode('form textarea[required="required"][name="post[body]"]');
        $this->assertCrawlerHasNode('form select[required="required"][name="post[publicationDate][date][month]"]');
        $this->assertCrawlerHasNode('form select[required="required"][name="post[publicationDate][date][day]"]');
        $this->assertCrawlerHasNode('form select[required="required"][name="post[publicationDate][date][year]"]');
        $this->assertCrawlerHasNode(
            'form select[required="required"][name="post[publicationDate][time][hour]"]'
        );
        $this->assertCrawlerHasNode(
            'form select[required="required"][name="post[publicationDate][time][minute]"]'
        );
    }

    public function testCreateActionSubmitSuccessful()
    {
        $client = static::createClient(
            array(),
            array(
                'PHP_AUTH_USER' => 'user',
                'PHP_AUTH_PW'   => 'userpass',
            )
        );

        $crawler = $client->request('GET', '/posts/create');

        $form = $crawler->selectButton('Submit')->form(
            array(
                'post[title]' => 'Test post',
                'post[body]' => 'This post created by automated test.',
            )
        );

        $client->submit($form);

        $crawler = $client->followRedirect();
        $this->setCrawler($crawler);

        $this->assertCrawlerHasNode('.content:contains("Test post")');
        $this->assertCrawlerHasNode('.content:contains("This post created by automated test.")');
    }

    /**
     * @dataProvider createActionSubmitErrorsDataProvider
     * @param array $postData
     * @param array|string $errorMessages
     * @return void
     */
    public function testCreateActionSubmitErrors(array $postData, $errorMessages)
    {
        $postData = array_merge(
            array(
                'post[title]' => 'Test post',
                'post[body]' => 'This post created by automated test.',
            ),
            $postData
        );

        $client = static::createClient(
            array(),
            array(
                'PHP_AUTH_USER' => 'user',
                'PHP_AUTH_PW'   => 'userpass',
            )
        );

        $crawler = $client->request('GET', '/posts/create');

        $form = $crawler->selectButton('Submit')->form($postData);

        $crawler = $client->submit($form);
        $this->assertFalse($client->getResponse()->isRedirection());
        $this->setCrawler($crawler);
        foreach ((array)$errorMessages as $errorMessage) {
            $this->assertCrawlerHasNode("span:contains(\"$errorMessage\")");
        }
    }

    public function createActionSubmitErrorsDataProvider()
    {
        return array(
            'title is required' => array(
                array('post[title]' => ''),
                'This value should not be blank.'
            ),
            'body is required' => array(
                array('post[body]' => ''),
                'This value should not be blank.'
            )
        );
    }

    public function testCreateActionDeniedForAnonymousUser()
    {
        $client = static::createClient();

        $client->request('GET', '/posts/create');

        $this->assertTrue($client->getResponse()->isRedirection());
        $this->assertContains('/login', $client->getResponse()->getTargetUrl());
    }

    public function testShowAction()
    {
        $client = $this->createClient();

        $crawler = $client->request('GET', '/posts/unit_testing');
        $this->setCrawler($crawler);

        $this->assertCrawlerHasNode('.content:contains("Unit testing")');
        $this->assertCrawlerHasNode(
            '.content:contains("The goal of unit testing is to isolate each part '
            . 'of the program and show that the individual parts are correct.")'
        );
    }

    public function testShowActionPostNotFound()
    {
        $client = $this->createClient();

        $crawler = $client->request('GET', '/posts/unknown_post');
        $this->setCrawler($crawler);

        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }

    public function testAddCommentAction()
    {
        $client = $this->createClient();

        $crawler = $client->request('GET', '/posts/unit_testing');
        $this->setCrawler($crawler);

        $this->assertCrawlerHasNode('form input[type="text"][required="required"][name="comment[author]"]');
        $this->assertCrawlerHasNode('form input[type="email"][required="required"][name="comment[email]"]');
        $this->assertCrawlerHasNode('form textarea[required="required"][name="comment[body]"]');
    }

    public function testAddCommentActionSubmitSuccessful()
    {
        $client = $this->createClient();

        $crawler = $client->request('GET', '/posts/unit_testing');

        $form = $crawler->selectButton('Add Comment')->form(
            array(
                'comment[author]' => 'John Doe',
                'comment[email]' => 'john.doe@example.com',
                'comment[body]' => 'This comment created by automated test.',
            )
        );

        $client->submit($form);

        $crawler = $client->followRedirect();
        $this->setCrawler($crawler);

        $this->assertCrawlerHasNode('.content:contains("Unit testing")');
        $this->assertCrawlerHasNode(
            '.content:contains("The goal of unit testing is to isolate each part '
            . 'of the program and show that the individual parts are correct.")'
        );
        $this->assertCrawlerHasNode('.content:contains("Your comment was added.")');
        $this->assertCrawlerHasNode('.content a[href="email:john.doe@example.com"]:contains("John Doe")');
        $this->assertCrawlerHasNode('.content:contains("This comment created by automated test.")');
    }

    /**
     * @dataProvider addCommentSubmitErrorsDataProvider
     * @param array $commentData
     * @param array|string $errorMessages
     * @return void
     */
    public function testAddCommentActionSubmitErrors(array $commentData, $errorMessages)
    {
        $commentData = array_merge(
            array(
                'comment[author]' => 'John Doe',
                'comment[email]' => 'john.doe@example.com',
                'comment[body]' => 'This comment created by automated test.',
            ),
            $commentData
        );

        $client = static::createClient();

        $crawler = $client->request('GET', '/posts/unit_testing');

        $form = $crawler->selectButton('Add Comment')->form($commentData);

        $crawler = $client->submit($form);
        $this->assertFalse($client->getResponse()->isRedirection());
        $this->setCrawler($crawler);
        foreach ((array)$errorMessages as $errorMessage) {
            $this->assertCrawlerHasNode("span:contains(\"$errorMessage\")");
        }
    }

    public function addCommentSubmitErrorsDataProvider()
    {
        return array(
            'author is required' => array(
                array('comment[author]' => ''),
                'This value should not be blank.'
            ),
            'email is required' => array(
                array('comment[email]' => ''),
                'This value should not be blank.'
            ),
            'email is invalid' => array(
                array('comment[email]' => 'john'),
                'This value is not a valid email address'
            ),
            'body is required' => array(
                array('comment[body]' => ''),
                'This value should not be blank.'
            )
        );
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18408
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;
using Duomo.Common.Lib.Dates;

//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//

namespace Duomo.Common.Gunther.Lib
{
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:ScheduleSpecificationTypes")]
    public partial class HourlyScheduleSpecification
    {

        private System.DateTime startTimeField;

        private System.DateTime endTimeField;

        private string daysOfWeekField;

        private HolidayCalendarEnumeration holidayCalendarField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute(DataType = "time")]
        public System.DateTime StartTime
        {
            get
            {
                return this.startTimeField;
            }
            set
            {
                this.startTimeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute(DataType = "time")]
        public System.DateTime EndTime
        {
            get
            {
                return this.endTimeField;
            }
            set
            {
                this.endTimeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string DaysOfWeek
        {
            get
            {
                return this.daysOfWeekField;
            }
            set
            {
                this.daysOfWeekField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public HolidayCalendarEnumeration HolidayCalendar
        {
            get
            {
                return this.holidayCalendarField;
            }
            set
            {
                this.holidayCalendarField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    //[System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:ScheduleSpecificationTypes")]
    public partial class DailyScheduleSpecification
    {

        private System.DateTime timeField;

        private string daysOfWeekField;

        private HolidayCalendarEnumeration holidayCalendarField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute(DataType = "time")]
        public System.DateTime Time
        {
            get
            {
                return this.timeField;
            }
            set
            {
                this.timeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string DaysOfWeek
        {
            get
            {
                return this.daysOfWeekField;
            }
            set
            {
                this.daysOfWeekField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public HolidayCalendarEnumeration HolidayCalendar
        {
            get
            {
                return this.holidayCalendarField;
            }
            set
            {
                this.holidayCalendarField = value;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
in_tifdir=$1
epsg=$2
nodata=$3

# making data.asc
# convert tif to asc with user supplied EPSG code and nodata value
cd $in_tifdir
for i in *.tif
do
	gdal_translate -of AAIGrid -a_srs EPSG:$epsg -a_nodata $nodata -ot Float32 $i /tmp/asc/$( basename $i .tif ).asc
done
# make a single BSQ ascii, with bands separated by newline
# need to remove headers
cd tmp/asc/
ls *.asc | parallel 'asc=$( cat {} | sed "1,6d" ); echo -e "\n$asc"' | sed '1d' > data.asc

# making counter.asc
# make a single BSQ ascii, with bands separated by newline - for boolean nodata mask
cat data.asc | sed "s:\b0\b:1:g;s:\b${nodata}\b:|:g;s:[0-9]\+:1:g;s:|:0:g" > counter.asc


text:
from typing import Callable, Dict, Type

from pandas_profiling.report.presentation.core import Root
from pandas_profiling.report.presentation.core.renderable import Renderable

def apply_renderable_mapping(
    mapping: Dict[Type[Renderable], Type[Renderable]],
    structure: Renderable,
    flavour: Callable,
) -> None:
    mapping[type(structure)].convert_to_class(structure, flavour)

def get_html_renderable_mapping() -> Dict[Type[Renderable], Type[Renderable]]:
    """Workaround variable type annotations not being supported in Python 3.5

    Returns:
        type annotated mapping dict
    """
    from pandas_profiling.report.presentation.core import (
        HTML,
        Alerts,
        Collapse,
        Container,
        Duplicate,
        FrequencyTable,
        FrequencyTableSmall,
        Image,
        Root,
        Sample,
        Table,
        ToggleButton,
        Variable,
        VariableInfo,
    )
    from pandas_profiling.report.presentation.flavours.html import (
        HTMLHTML,
        HTMLAlerts,
        HTMLCollapse,
        HTMLContainer,
        HTMLDuplicate,
        HTMLFrequencyTable,
        HTMLFrequencyTableSmall,
        HTMLImage,
        HTMLRoot,
        HTMLSample,
        HTMLTable,
        HTMLToggleButton,
        HTMLVariable,
        HTMLVariableInfo,
    )

    return {
        Container: HTMLContainer,
        Variable: HTMLVariable,
        VariableInfo: HTMLVariableInfo,
        Table: HTMLTable,
        HTML: HTMLHTML,
        Root: HTMLRoot,
        Image: HTMLImage,
        FrequencyTable: HTMLFrequencyTable,
        FrequencyTableSmall: HTMLFrequencyTableSmall,
        Alerts: HTMLAlerts,
        Duplicate: HTMLDuplicate,
        Sample: HTMLSample,
        ToggleButton: HTMLToggleButton,
        Collapse: HTMLCollapse,
    }

def HTMLReport(structure: Root) -> Root:
    """Adds HTML flavour to Renderable

    Args:
        structure:

    Returns:

    """
    mapping = get_html_renderable_mapping()
    apply_renderable_mapping(mapping, structure, flavour=HTMLReport)
    return structure

def get_widget_renderable_mapping() -> Dict[Type[Renderable], Type[Renderable]]:
    from pandas_profiling.report.presentation.core import (
        HTML,
        Alerts,
        Collapse,
        Container,
        Duplicate,
        FrequencyTable,
        FrequencyTableSmall,
        Image,
        Root,
        Sample,
        Table,
        ToggleButton,
        Variable,
        VariableInfo,
    )
    from pandas_profiling.report.presentation.flavours.widget import (
        WidgetAlerts,
        WidgetCollapse,
        WidgetContainer,
        WidgetDuplicate,
        WidgetFrequencyTable,
        WidgetFrequencyTableSmall,
        WidgetHTML,
        WidgetImage,
        WidgetRoot,
        WidgetSample,
        WidgetTable,
        WidgetToggleButton,
        WidgetVariable,
        WidgetVariableInfo,
    )

    return {
        Container: WidgetContainer,
        Variable: WidgetVariable,
        VariableInfo: WidgetVariableInfo,
        Table: WidgetTable,
        HTML: WidgetHTML,
        Root: WidgetRoot,
        Image: WidgetImage,
        FrequencyTable: WidgetFrequencyTable,
        FrequencyTableSmall: WidgetFrequencyTableSmall,
        Alerts: WidgetAlerts,
        Duplicate: WidgetDuplicate,
        Sample: WidgetSample,
        ToggleButton: WidgetToggleButton,
        Collapse: WidgetCollapse,
    }

def WidgetReport(structure: Root) -> Root:
    mapping = get_widget_renderable_mapping()
    apply_renderable_mapping(mapping, structure, flavour=WidgetReport)
    return structure


text:
class AutoBox {
    static int m(Integer v) {
        return v; //auto-unbox to int
    }

    public static void main(String args[]) {
        Integer iOb = m(100);
        System.out.println(iOb);
    }
}


text:
package org.n52.supervisor.resources;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.n52.supervisor.CheckerResolver;
import org.n52.supervisor.api.Check;
import org.n52.supervisor.api.CheckRunner;
import org.n52.supervisor.db.CheckDatabase;
import org.n52.supervisor.db.ResultDatabase;
import org.n52.supervisor.tasks.ManualChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.SessionScoped;

/**
 *
 * @author Daniel Nüst
 *
 */
@Path("/api/v1/checks")
@SessionScoped
public class Checks {

    private static Logger log = LoggerFactory.getLogger(Checks.class);

    private final ExecutorService manualExecutor;

    private final CheckDatabase checkDatabase;

    private final ResultDatabase resultDatabase;

    private final CheckerResolver checkResolver;

    @Inject
    public Checks(final CheckDatabase cd, final ResultDatabase rd, final CheckerResolver cr) {
        checkDatabase = cd;
        resultDatabase = rd;
        checkResolver = cr;

        // create thread pool for manually started checks
        manualExecutor = Executors.newSingleThreadExecutor();

        log.info("NEW {}", this);
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getCheck(@PathParam("id") final String id) {
        log.debug("Requesting checker with id {}", id);

        final Check check = checkDatabase.getCheck(id);

        if (check != null) {
			return Response.ok().entity(check).build();
		}

        return Response.status(Status.NOT_FOUND).entity("{\"error\": \"entitiy for id not found:" + id + "\" } ").build();
    }

    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getChecks(@Context final UriInfo uriInfo) throws JSONException {
        final List<Check> checks = checkDatabase.getAllChecks();

        // GenericEntity<List<Check>> entity = new GenericEntity<List<Check>>(Lists.newArrayList(checks)) {};
        final JSONObject result = new JSONObject();
        final JSONArray jsonChecks = new JSONArray();
        result.put("checks", jsonChecks);
        for (final Check check : checks) {
        	final JSONObject jsonCheck = new JSONObject();
        	jsonCheck.put("id", check.getIdentifier());
        	URI path = uriInfo.getBaseUriBuilder().path(Checks.class).path(check.getIdentifier()).build();
        	jsonCheck.put("uri", path);
        	path = uriInfo.getBaseUriBuilder().path(Checks.class).path(check.getIdentifier() + "/results").build();
        	jsonCheck.put("results",path);
            jsonChecks.put(jsonCheck);
        }
        return Response.ok(result).build();

        // return Response.ok(entity).build();
    }

    @GET
    @Path("/{id}/results")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getChecksResults(
    		@Context 			final UriInfo uriInfo,
    		@PathParam("id") 	final String id) {
        final UriBuilder redirect = uriInfo.getBaseUriBuilder().path(Results.class).queryParam("checkId", id);
        return Response.seeOther(redirect.build()).build();
    }

    @PUT
    @Path("/run")
    @Produces(MediaType.TEXT_PLAIN)
    public Response runChecksNow(
    		@QueryParam("notify") @DefaultValue("true")		final boolean notify,
    		@QueryParam("all")    @DefaultValue("false")	final boolean runAll,
    		@QueryParam("ids")								final String ids,
    		@Context										final UriInfo uri) {
        log.debug("Running processes: notify = {}, all = {}, ids = {}", notify, runAll, ids);
        log.debug(uri.toString());

        if (runAll && ids != null) {
			log.warn("Both ids and 'all' specified.");
		}

        ManualChecker manualChecker = null;
        if (runAll) {
            final Collection<CheckRunner> checkers = new ArrayList<>();
            final List<Check> allChecks = checkDatabase.getAllChecks();
            for (final Check check : allChecks) {
                final CheckRunner runner = checkResolver.getRunner(check);
                runner.setResultDatabase(resultDatabase);

                if (runner != null) {
					checkers.add(runner);
				}
            }

            manualChecker = new ManualChecker(checkers, notify);
            manualExecutor.submit(manualChecker);

            return Response.ok(Response.Status.CREATED).entity("running all processes").build();
        }

        return Response.serverError().entity("not implemented yet").build();
    }

}


text:
void missing() {}
// NO-OVERRIDE: define void @missing() #[[#NONE:]]
// OVERRIDE: define void @missing() #[[#STD:]]

__attribute__ ((target("branch-protection=none")))
void none() {}
// NO-OVERRIDE: define void @none() #[[#NONE]]
// OVERRIDE: define void @none() #[[#NONE:]]

  __attribute__ ((target("branch-protection=standard")))
void std() {}
// NO-OVERRIDE: define void @std() #[[#STD:]]
// OVERRIDE: define void @std() #[[#STD]]

__attribute__ ((target("branch-protection=bti")))
void btionly() {}
// NO-OVERRIDE: define void @btionly() #[[#BTI:]]
// OVERRIDE: define void @btionly() #[[#BTI:]]

__attribute__ ((target("branch-protection=pac-ret")))
void paconly() {}
// NO-OVERRIDE: define void @paconly() #[[#PAC:]]
// OVERRIDE: define void @paconly() #[[#PAC:]]

__attribute__ ((target("branch-protection=pac-ret+bti")))
void pacbti0() {}
// NO-OVERRIDE: define void @pacbti0() #[[#PACBTI:]]
// OVERRIDE: define void @pacbti0() #[[#PACBTI:]]

__attribute__ ((target("branch-protection=bti+pac-ret")))
void pacbti1() {}
// NO-OVERRIDE: define void @pacbti1() #[[#PACBTI]]
// OVERRIDE: define void @pacbti1() #[[#PACBTI]]

__attribute__ ((target("branch-protection=pac-ret+leaf")))
void leaf() {}
// NO-OVERRIDE: define void @leaf() #[[#PACLEAF:]]
// OVERRIDE: define void @leaf() #[[#PACLEAF:]]

__attribute__ ((target("branch-protection=pac-ret+b-key")))
void bkey() {}
// NO-OVERRIDE: define void @bkey() #[[#PACBKEY:]]
// OVERRIDE: define void @bkey() #[[#PACBKEY:]]

__attribute__ ((target("branch-protection=pac-ret+b-key+leaf")))
void bkeyleaf0() {}
// NO-OVERRIDE: define void @bkeyleaf0()  #[[#PACBKEYLEAF:]]
// OVERRIDE: define void @bkeyleaf0()  #[[#PACBKEYLEAF:]]

__attribute__ ((target("branch-protection=pac-ret+leaf+b-key")))
void bkeyleaf1() {}
// NO-OVERRIDE: define void @bkeyleaf1()  #[[#PACBKEYLEAF]]
// OVERRIDE: define void @bkeyleaf1()  #[[#PACBKEYLEAF]]

__attribute__ ((target("branch-protection=pac-ret+leaf+bti")))
void btileaf() {}
// NO-OVERRIDE: define void @btileaf() #[[#BTIPACLEAF:]]
// OVERRIDE: define void @btileaf() #[[#BTIPACLEAF:]]

// CHECK-DAG: attributes #[[#NONE]]

// CHECK-DAG: attributes #[[#STD]] = { {{.*}} "branch-target-enforcement" {{.*}} "sign-return-address"="non-leaf" "sign-return-address-key"="a_key"

// CHECK-DAG: attributes #[[#BTI]] = { {{.*}}"branch-target-enforcement"

// CHECK-DAG: attributes #[[#PAC]] = { {{.*}} "sign-return-address"="non-leaf" "sign-return-address-key"="a_key"

// CHECK-DAG: attributes #[[#PACLEAF]] = { {{.*}} "sign-return-address"="all" "sign-return-address-key"="a_key"

// CHECK-DAG: attributes #[[#PACBKEY]] = { {{.*}} "sign-return-address"="non-leaf" "sign-return-address-key"="b_key"

// CHECK-DAG: attributes #[[#PACBKEYLEAF]] = { {{.*}} "sign-return-address"="all" "sign-return-address-key"="b_key"

// CHECK-DAG: attributes #[[#BTIPACLEAF]] = { {{.*}}"branch-target-enforcement" {{.*}} "sign-return-address"="all" "sign-return-address-key"="a_key"


text:
package fr.free.nrw.commons.settings;

import android.Manifest;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.MultiSelectListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.google.android.material.snackbar.Snackbar;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.single.BasePermissionListener;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.TelemetryDefinition;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils;
import fr.free.nrw.commons.di.ApplicationlessInjection;
import fr.free.nrw.commons.kvstore.JsonKvStore;
import fr.free.nrw.commons.logging.CommonsLogSender;
import fr.free.nrw.commons.upload.Language;
import fr.free.nrw.commons.utils.PermissionUtils;
import fr.free.nrw.commons.utils.ViewUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Named;

public class SettingsFragment extends PreferenceFragmentCompat {

    @Inject
    @Named("default_preferences")
    JsonKvStore defaultKvStore;

    @Inject
    CommonsLogSender commonsLogSender;

    private ListPreference themeListPreference;
    private ListPreference langListPreference;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        ApplicationlessInjection
            .getInstance(getActivity().getApplicationContext())
            .getCommonsApplicationComponent()
            .inject(this);

        // Set the preferences from an XML resource
        setPreferencesFromResource(R.xml.preferences, rootKey);

        themeListPreference = findPreference(Prefs.KEY_THEME_VALUE);
        prepareTheme();

        MultiSelectListPreference multiSelectListPref = findPreference(Prefs.MANAGED_EXIF_TAGS);
        if (multiSelectListPref != null) {
            multiSelectListPref.setOnPreferenceChangeListener((preference, newValue) -> {
                if (newValue instanceof HashSet && !((HashSet) newValue).contains(getString(R.string.exif_tag_location))) {
                    defaultKvStore.putBoolean("has_user_manually_removed_location", true);
                }
                return true;
            });
        }

        langListPreference = findPreference("descriptionDefaultLanguagePref");
        prepareLanguages();
        Preference betaTesterPreference = findPreference("becomeBetaTester");
        betaTesterPreference.setOnPreferenceClickListener(preference -> {
            Utils.handleWebUrl(getActivity(), Uri.parse(getResources().getString(R.string.beta_opt_in_link)));
            return true;
        });
        Preference sendLogsPreference = findPreference("sendLogFile");
        sendLogsPreference.setOnPreferenceClickListener(preference -> {
            checkPermissionsAndSendLogs();
            return true;
        });
        // Disable some settings when not logged in.
        if (defaultKvStore.getBoolean("login_skipped", false)) {
            findPreference("useExternalStorage").setEnabled(false);
            findPreference("useAuthorName").setEnabled(false);
            findPreference("displayNearbyCardView").setEnabled(false);
            findPreference("displayLocationPermissionForCardView").setEnabled(false);
            findPreference("displayCampaignsCardView").setEnabled(false);
        }

        findPreference("telemetryOptOut").setOnPreferenceChangeListener(
            (preference, newValue) -> {
                telemetryOptInOut((boolean)newValue);
                defaultKvStore.putBoolean(Prefs.TELEMETRY_PREFERENCE,(boolean)newValue);
                return false;
            });
    }

    /**
     * Opt in or out of MapBox telemetry
     * @param shouldOptIn
     */
    private void telemetryOptInOut(boolean shouldOptIn){
        TelemetryDefinition telemetry = Mapbox.getTelemetry();
        if (telemetry != null) {
            telemetry.setUserTelemetryRequestState(shouldOptIn);
        }
    }

    /**
     * Sets the theme pref
     */
    private void prepareTheme() {
        themeListPreference.setOnPreferenceChangeListener((preference, newValue) -> {
            getActivity().recreate();
            return true;
        });
    }

    /**
     * Prepares language summary and language codes list and adds them to list preference as pairs.
     * Uses previously saved language if there is any, if not uses phone local as initial language.
     * Adds preference changed listener and saves value chosen by user to shared preferences
     * to remember later
     */
    private void prepareLanguages() {
        List<String> languageNamesList = new ArrayList<>();
        List<String> languageCodesList = new ArrayList<>();
        List<Language> languages = getLanguagesSupportedByDevice();

        for(Language language: languages) {
            // Go through all languages and add them to lists
            if(!languageCodesList.contains(language.getLocale().getLanguage())) {
                // This if prevents us from adding same language twice
                languageNamesList.add(language.getLocale().getDisplayName());
                languageCodesList.add(language.getLocale().getLanguage());
            }
        }

        CharSequence[] languageNames = languageNamesList.toArray(new CharSequence[0]);
        CharSequence[] languageCodes = languageCodesList.toArray(new CharSequence[0]);
        // Add all languages and languages codes to lists preference as pair
        langListPreference.setEntries(languageNames);
        langListPreference.setEntryValues(languageCodes);

        // Gets current language code from shared preferences
        String languageCode = getCurrentLanguageCode();
        if (languageCode.equals("")){
            // If current language code is empty, means none selected by user yet so use phone local
            langListPreference.setValue(Locale.getDefault().getLanguage());
        } else {
            // If any language is selected by user previously, use it
            langListPreference.setValue(languageCode);
        }

        langListPreference.setOnPreferenceChangeListener((preference, newValue) -> {
            String userSelectedValue = (String) newValue;
            saveLanguageValue(userSelectedValue);
            return true;
        });
    }

    private void saveLanguageValue(String userSelectedValue) {
        defaultKvStore.putString(Prefs.KEY_LANGUAGE_VALUE, userSelectedValue);
    }

    private String getCurrentLanguageCode() {
        return defaultKvStore.getString(Prefs.KEY_LANGUAGE_VALUE, "");
    }

    private List<Language> getLanguagesSupportedByDevice() {
        List<Language> languages = new ArrayList<>();
        Locale[] localesArray = Locale.getAvailableLocales();
        for (Locale locale : localesArray) {
            languages.add(new Language(locale));
        }

        Collections.sort(languages, (language, t1) -> language.getLocale().getDisplayName()
                .compareTo(t1.getLocale().getDisplayName()));
        return languages;
    }

    /**
     * First checks for external storage permissions and then sends logs via email
     */
    private void checkPermissionsAndSendLogs() {
        if (PermissionUtils.hasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            commonsLogSender.send(getActivity(), null);
        } else {
            requestExternalStoragePermissions();
        }
    }

    /**
     * Requests external storage permissions and shows a toast stating that log collection has started
     */
    private void requestExternalStoragePermissions() {
        Dexter.withActivity(getActivity())
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new BasePermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        ViewUtil.showLongToast(getActivity(), getResources().getString(R.string.log_collection_started));
                    }
                }).check();
    }
}


text:
FROM alpine:latest

LABEL maintainer="Nikolaos Dimopoulos <nikos@niden.net>"

RUN apk add --no-cache --update \
    nmap

ENTRYPOINT ["nmap"]


text:
package mo_usage

import (
	"encoding/json"
	"github.com/watermint/toolbox/domain/dropbox/model/mo_member"
	"github.com/watermint/toolbox/essentials/api/api_parser"
	"github.com/watermint/toolbox/essentials/log/esl"
)

type Usage struct {
	Raw                               json.RawMessage
	Used                              uint64 `path:"used" json:"used"`
	Allocation                        string `path:"allocation.\\.tag" json:"allocation"`
	Allocated                         uint64 `path:"allocation.allocated" json:"allocated"`
	TeamUsed                          uint64 `path:"allocation.used" json:"team_used"`
	TeamUserWithinTeamSpaceAllocated  uint64 `path:"allocation.user_within_team_space_allocated" json:"team_user_within_team_space_allocated"`
	TeamUserWithinTeamSpaceLimitType  string `path:"allocation.user_within_team_space_limit_type.\\.tag" json:"team_user_within_team_space_limit_type"`
	TeamUserWithinTeamSpaceUsedCached uint64 `path:"allocation.user_within_team_space_used_cached" json:"team_user_within_team_space_used_cached"`
}

type MemberUsage struct {
	Raw        json.RawMessage
	Email      string  `path:"member.profile.email" json:"email"`
	UsedGB     float64 `path:"usage.used" json:"used_gb"`
	UsedBytes  uint64  `path:"usage.used" json:"used_bytes"`
	Allocation string  `path:"usage.allocation.\\.tag" json:"allocation"`
	Allocated  uint64  `path:"usage.allocation.allocated" json:"allocated"`
	//TeamUsed                          uint64  `path:"usage.allocation.used" json:"team_used"`
	//TeamUserWithinTeamSpaceAllocated  uint64  `path:"usage.allocation.user_within_team_space_allocated" json:"team_user_within_team_space_allocated"`
	//TeamUserWithinTeamSpaceLimitType  string  `path:"usage.allocation.user_within_team_space_limit_type.\\.tag" json:"team_user_within_team_space_limit_type"`
	//TeamUserWithinTeamSpaceUsedCached uint64  `path:"usage.allocation.user_within_team_space_used_cached" json:"team_user_within_team_space_used_cached"`
}

func NewMemberUsage(member *mo_member.Member, usage *Usage) (mu *MemberUsage) {
	raws := make(map[string]json.RawMessage)
	raws["member"] = member.Raw
	raws["usage"] = usage.Raw
	raw := api_parser.CombineRaw(raws)

	mu = &MemberUsage{}
	if err := api_parser.ParseModelRaw(mu, raw); err != nil {
		esl.Default().Warn("unexpected data format", esl.Error(err))
		// return empty
		return mu
	}
	mu.UsedGB = float64(mu.UsedBytes) / 1_073_741_824.0
	return mu
}


text:
package com.semmle.ts.ast;

import java.util.ArrayList;
import java.util.List;

import com.semmle.js.ast.Expression;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.SourceLocation;
import com.semmle.js.ast.TemplateElement;
import com.semmle.js.ast.TemplateLiteral;
import com.semmle.js.ast.Visitor;

/**
 * A template literal used in a type, such as in <code>type T = `Hello, ${name}!`</code>.
 */
public class TemplateLiteralTypeExpr extends TypeExpression {
  private final List<ITypeExpression> expressions;
  private final List<TemplateElement> quasis;
  private final List<Node> children;

  public TemplateLiteralTypeExpr(
      SourceLocation loc, List<ITypeExpression> expressions, List<TemplateElement> quasis) {
    super("TemplateLiteralTypeExpr", loc);
    this.expressions = expressions;
    this.quasis = quasis;
    this.children = TemplateLiteral.<Node>mergeChildren(expressions, quasis);
  }

  @Override
  public <Q, A> A accept(Visitor<Q, A> v, Q q) {
    return v.visit(this, q);
  }

  /** The type expressions in this template. */
  public List<ITypeExpression> getExpressions() {
    return expressions;
  }

  /** The template elements in this template. */
  public List<TemplateElement> getQuasis() {
    return quasis;
  }

  /** All type expressions and template elements in this template, in lexical order. */
  public List<Node> getChildren() {
    return children;
  }
}


text:
function jump_after_first_word() {
    local words
    words=(${(z)BUFFER})

    if (( ${#words} <= 1 )) ; then
        CURSOR=${#BUFFER}
    else
        CURSOR=${#${words[1]}}
    fi
}
zle -N jump_after_first_word

# jump to after first word (for adding options)
bindkey '^x1' jump_after_first_word


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/studentinfo.iml" filepath="$PROJECT_DIR$/.idea/studentinfo.iml" />
    </modules>
  </component>
</project>


text:
Originally published: 2013-07-08 04:22:49
Last updated: 2013-07-08 04:33:58
Author: AJay Kumar

This script will allow you to send Messages to people who have a username on facebook from an email id you specify in the script.Although message will not be sent to their inbox,if you're not a friend but it will be sent to other category.


text:
/*
 * Intel common I2C header
 */

#ifndef COMMON_I2C_H_
#define COMMON_I2C_H_

#include <stdint.h>

/**
 * @defgroup common_driver_i2c Common I2C
 * Inter Integrated Communication bus drivers API.
 * @ingroup common_drivers
 * @{
 */

/**
 * API types.
 */
typedef enum {
    I2C_OK = 0,             /*!< I2C BUS OK */
    I2C_BUSY,               /*!< I2C BUS BUSY */
    I2C_TX_ABORT,           /*!< I2C BUS TX ABORT */
    I2C_TX_OVER,            /*!< I2C BUS TX OVER */
    I2C_RX_OVER,            /*!< I2C BUS RX OVER */
    I2C_RX_UNDER,           /*!< I2C BUS RX UNDER */
}DRIVER_I2C_STATUS_CODE;

/**
 * I2C speeds.
 */
typedef enum {
    I2C_SLOW = 1,            /*!< (1) 0-100 Khz - note: Starts at 1 to remove need to translate before hardware write */
    I2C_FAST = 2,            /*!< (2) 400 Khz */
    I2C_HS = 3               /*!< (3) 3400 kbit/s mode added support for HS mode available only in SoC block */
} I2C_SPEED;

/**
 * I2C addressing modes.
 */
typedef enum {
    I2C_7_Bit = 0,           /*!< (0) 7 bit  */
    I2C_10_Bit,              /*!< (1) 10 bit */
} I2C_ADDR_MODE;

/**
 * I2C mode types.
 */
typedef enum {
    I2C_MASTER = 0,         /*!< MASTER WRITE MODE */
    I2C_SLAVE               /*!< MASTER READ MODE */
} I2C_MODE_TYPE;

/**
*  callback function signature.
*/
typedef void (*i2c_callback)( uint32_t );     /*!< callback function signature */

/**
*  I2C controller configuration.
*  Driver instantiates one of these with given parameters for each I2C
*  controller configured using the "ss_i2c_set_config" function
*/
typedef struct i2c_cfg_data{
    I2C_SPEED           speed;
    I2C_ADDR_MODE       addressing_mode;    /*!< 7 bit / 10 bit addressing */
    I2C_MODE_TYPE       mode_type;          /*!< Master or Slave */
    uint32_t            slave_adr;          /*!< I2C address if configured as a Slave */
    i2c_callback        cb_rx;              /*!< callback function for notification of data received and available to application, NULL if callback not required by application code */
    uint32_t            cb_rx_data;         /*!< this will be passed back by the callback routine - can be used as an controller identifier */
    i2c_callback        cb_tx               /*!< callback function for notification of transmit completion by the I2C controller,  NULL if callback not required by application code */;
    uint32_t            cb_tx_data;         /*!< this will be passed back by the callback routine - can be used as an controller identifier */
    i2c_callback        cb_err;             /*!< callback function on transaction error, NULL if callback not required by application code */
    uint32_t            cb_err_data;        /*!< this will be passed back by the callback routine - can be used as an controller identifier */
}i2c_cfg_data_t;

/** @} */

#endif /* COMMON_I2C_H_ */


text:
<?php

/**
 * This is the model class for table "t_ComprasItems".
 *
 * The followings are the available columns in table 't_ComprasItems':
 * @property integer $idCompraItem
 * @property integer $idCompra
 * @property string $codigoProducto
 * @property string $descripcion
 * @property string $presentacion
 * @property integer $precioBaseUnidad
 * @property integer $precioBaseFraccion
 * @property integer $descuentoUnidad
 * @property integer $descuentoFraccion
 * @property integer $precioTotalUnidad
 * @property integer $precioTotalFraccion
 * @property integer $idOperador
 * @property integer $terceros
 * @property integer $unidades
 * @property integer $fracciones
 * @property integer $unidadesCedi
 * @property integer $codigoImpuesto
 * @property integer $idEstadoItem
 * @property integer $flete
 * @property integer $disponible
 * @property integer $idCombo
 * @property string $descripcionCombo
 *
 * The followings are the available model relations:
 * @property EstadoItem $objEstadoItem
 * @property Compras $objCompra
 */
class ComprasItems extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 't_ComprasItems';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('idCompra, precioBaseUnidad, precioBaseFraccion, descuentoUnidad, descuentoFraccion, precioTotalUnidad, precioTotalFraccion, idOperador, terceros, unidades, fracciones, unidadesCedi, codigoImpuesto, idEstadoItem, flete, disponible, idCombo', 'numerical', 'integerOnly' => true),
            array('codigoProducto', 'length', 'max' => 10),
            array('descripcion', 'length', 'max' => 200),
            array('presentacion, descripcionCombo', 'length', 'max' => 100),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('idCompraItem, idCompra, codigoProducto, descripcion, descripcionCombo, presentacion, precioBaseUnidad, precioBaseFraccion, descuentoUnidad, descuentoFraccion, precioTotalUnidad, precioTotalFraccion, idOperador, terceros, unidades, fracciones, unidadesCedi, codigoImpuesto, idEstadoItem, flete, disponible, idCombo', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'objProducto' => array(self::BELONGS_TO, 'Producto', 'codigoProducto'),
            'objCombo' => array(self::BELONGS_TO, 'Combo', 'idCombo'),
            'objImpuesto' => array(self::BELONGS_TO, 'Impuesto', 'codigoImpuesto'),
            'objCompra' => array(self::BELONGS_TO, 'Compras', 'idCompra'),
            'objOperador' => array(self::BELONGS_TO, 'Operador', 'idOperador'),
            'objEstadoItem' => array(self::BELONGS_TO, 'EstadoItem', 'idEstadoItem'),
            'listBeneficios' => array(self::HAS_MANY, 'BeneficiosComprasItems', 'idCompraItem'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'idCompraItem' => 'Id Compra Item',
            'idCompra' => 'Id Compra',
            'codigoProducto' => 'Codigo Producto',
            'descripcion' => 'Descripcion',
            'presentacion' => 'Presentacion',
            'precioBaseUnidad' => 'Precio Base Unidad',
            'precioBaseFraccion' => 'Precio Base Fraccion',
            'descuentoUnidad' => 'Descuento Unidad',
            'descuentoFraccion' => 'Descuento Fraccion',
            'precioTotalUnidad' => 'Precio Total Unidad',
            'precioTotalFraccion' => 'Precio Total Fraccion',
            'idOperador' => 'Codigo Operador',
            'terceros' => 'Terceros',
            'unidades' => 'Unidades',
            'fracciones' => 'Fracciones',
            'unidadesCedi' => 'Unidades Cedi',
            'codigoImpuesto' => 'Impuesto',
            'idEstadoItem' => 'Id Estado Item',
            'flete' => 'Flete',
            'disponible' => 'Disponible',
            'idCombo' => 'Id Combo',
            'descripcionCombo' => 'Sescripcion Combo'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('idCompraItem', $this->idCompraItem);
        $criteria->compare('idCompra', $this->idCompra);
        $criteria->compare('codigoProducto', $this->codigoProducto, true);
        $criteria->compare('descripcion', $this->descripcion, true);
        $criteria->compare('presentacion', $this->presentacion, true);
        $criteria->compare('precioBaseUnidad', $this->precioBaseUnidad);
        $criteria->compare('precioBaseFraccion', $this->precioBaseFraccion);
        $criteria->compare('descuentoUnidad', $this->descuentoUnidad);
        $criteria->compare('descuentoFraccion', $this->descuentoFraccion);
        $criteria->compare('precioTotalUnidad', $this->precioTotalUnidad);
        $criteria->compare('precioTotalFraccion', $this->precioTotalFraccion);
        $criteria->compare('idOperador', $this->idOperador);
        $criteria->compare('terceros', $this->terceros);
        $criteria->compare('unidades', $this->unidades);
        $criteria->compare('fracciones', $this->fracciones);
        $criteria->compare('unidadesCedi', $this->unidadesCedi);
        $criteria->compare('codigoImpuesto', $this->codigoImpuesto);
        $criteria->compare('idEstadoItem', $this->idEstadoItem);
        $criteria->compare('flete', $this->flete);
        $criteria->compare('disponible', $this->disponible);
        $criteria->compare('idCombo', $this->idCombo);
        $criteria->compare('descripcionCombo', $this->descripcionCombo, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return ComprasItems the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * Metodo que hereda comportamiento de ValidateModelBehavior
     * @return void
     */
    public function behaviors() {
        return array(
            'ValidateModelBehavior' => array(
                'class' => 'application.components.behaviors.ValidateModelBehavior',
                'model' => $this
            ),
        );
    }

    public function getTotalUnidades(){
        $unidades = $this->unidades+$this->unidadesCedi;
        $fracciones = 0;

        if($this->fracciones>0){
            $fracciones = round($this->objProducto->unidadFraccionamiento/$this->objProducto->numeroFracciones,4);
            $fracciones = $fracciones*$this->fracciones;
        }

        return $unidades+$fracciones;
    }

    public function actualizarUnidades($cantidad) {
        $cantDiff = $cantidad - $this->unidades;
        //igual
        if ($cantDiff == 0) {
            echo CJSON::encode(array('result' => 'error', 'response' => 'Actualización exitosa.'));
            Yii::app()->end();
        }

        //aumentar --> verificar saldo
        if ($cantDiff > 0) {
            $objProducto = Producto::model()->find(array(
                'with' => array(
                    'listSaldos' => array('condition' => '(listSaldos.saldoUnidad>:saldo AND listSaldos.codigoCiudad=:ciudad AND listSaldos.codigoSector=:sector) OR (listSaldos.saldoUnidad IS NULL AND listSaldos.codigoCiudad IS NULL AND listSaldos.codigoSector IS NULL)'),
                    'listPrecios' => array('condition' => '(listPrecios.codigoCiudad=:ciudad AND listPrecios.codigoSector=:sector) OR (listPrecios.codigoCiudad IS NULL AND listPrecios.codigoSector IS NULL)'),
                    'listSaldosTerceros' => array('condition' => '(listSaldosTerceros.codigoCiudad=:ciudad AND listSaldosTerceros.codigoSector=:sector) OR (listSaldosTerceros.codigoCiudad IS NULL AND listSaldosTerceros.codigoSector IS NULL)')
                ),
                'condition' => 't.activo=:activo AND t.codigoProducto=:codigo AND ( (listSaldos.saldoUnidad IS NOT NULL AND listPrecios.codigoCiudad IS NOT NULL) OR listSaldosTerceros.codigoCiudad IS NOT NULL)',
                'params' => array(
                    ':activo' => 1,
                    ':codigo' => $this->codigoProducto,
                    ':saldo' => 0,
                    ':ciudad' => $this->objCompra->codigoCiudad,
                    ':sector' => $this->objCompra->codigoSector,
                ),
            ));

            if ($objProducto === null) {
                throw new Exception('Producto no disponible.');
            }

            $objSaldo = $objProducto->getSaldo($this->objCompra->codigoCiudad, $this->objCompra->codigoSector);

            if ($objSaldo === null) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. No hay unidades disponibles");
            }

            if ($cantDiff > $objSaldo->saldoUnidad) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. Saldos disponibles: $objSaldo->saldoUnidad unidades");
            }
        }

        $precioTotal = $this->precioBaseUnidad - $this->descuentoUnidad;
        $precioDiff = $precioTotal * $cantDiff;
        $this->unidades += $cantDiff;
        $this->precioTotalUnidad += $precioDiff;
        $this->idEstadoItem = Yii::app()->params->callcenter['estadoItem']['estado']['modificado'];
        $this->idOperador = Yii::app()->controller->module->user->id;

        $objCompra = $this->objCompra;
        $objCompra->subtotalCompra += $precioDiff;
        $objCompra->impuestosCompra += round(Precio::calcularImpuesto($precioDiff, $this->objImpuesto->porcentaje));
        $objCompra->baseImpuestosCompra += round(Precio::calcularBaseImpuesto($precioDiff,$this->objImpuesto->porcentaje));
        $objCompra->totalCompra += $precioDiff;

        if ($this->unidades + $this->fracciones == 0) {
            $objCompra->flete -= $this->flete;
        }

        $transaction = Yii::app()->db->beginTransaction();

        if (!$this->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización item: ' . $this->validateErrorsResponse());
        }

        if($objCompra->totalCompra<0){
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Total compra no puede ser negativo');
        }

        if (!$objCompra->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización compra: ' . $objCompra->validateErrorsResponse());
        }
        $transaction->commit();
    }

    public function actualizarFracciones($cantidad) {
        $cantDiff = $cantidad - $this->fracciones;
        //igual
        if ($cantDiff == 0) {
            echo CJSON::encode(array('result' => 'error', 'response' => 'Actualización exitosa.'));
            Yii::app()->end();
        }

        //aumentar
        if ($cantDiff > 0) {
            $objProducto = Producto::model()->find(array(
                'with' => array(
                    'listSaldos' => array('condition' => '(listSaldos.saldoFraccion>:saldo AND listSaldos.codigoCiudad=:ciudad AND listSaldos.codigoSector=:sector) OR (listSaldos.saldoFraccion IS NULL AND listSaldos.codigoCiudad IS NULL AND listSaldos.codigoSector IS NULL)'),
                    'listPrecios' => array('condition' => '(listPrecios.codigoCiudad=:ciudad AND listPrecios.codigoSector=:sector) OR (listPrecios.codigoCiudad IS NULL AND listPrecios.codigoSector IS NULL)'),
                    'listSaldosTerceros' => array('condition' => '(listSaldosTerceros.codigoCiudad=:ciudad AND listSaldosTerceros.codigoSector=:sector) OR (listSaldosTerceros.codigoCiudad IS NULL AND listSaldosTerceros.codigoSector IS NULL)')
                ),
                'condition' => 't.activo=:activo AND t.codigoProducto=:codigo AND ( (listSaldos.saldoUnidad IS NOT NULL AND listPrecios.codigoCiudad IS NOT NULL) OR listSaldosTerceros.codigoCiudad IS NOT NULL)',
                'params' => array(
                    ':activo' => 1,
                    ':codigo' => $this->codigoProducto,
                    ':saldo' => 0,
                    ':ciudad' => $this->objCompra->codigoCiudad,
                    ':sector' => $this->objCompra->codigoSector,
                ),
            ));

            if ($objProducto === null) {
                throw new Exception('Producto no disponible.');
            }

            $objSaldo = $objProducto->getSaldo($this->objCompra->codigoCiudad, $this->objCompra->codigoSector);

            if ($objSaldo === null) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. No hay unidades disponibles");
            }

            if ($cantDiff > $objSaldo->saldoFraccion) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. Saldos disponibles: $objSaldo->saldoFraccion fracciones");
            }
        }

        $precioTotal = $this->precioBaseFraccion - $this->descuentoFraccion;
        $precioDiff = $precioTotal * $cantDiff;
        $this->fracciones += $cantDiff;
        $this->precioTotalFraccion += $precioDiff;
        $this->idEstadoItem = Yii::app()->params->callcenter['estadoItem']['estado']['modificado'];
        $this->idOperador = Yii::app()->controller->module->user->id;

        $objCompra = $this->objCompra;
        $objCompra->subtotalCompra += $precioDiff;
        $objCompra->impuestosCompra += round(Precio::calcularImpuesto($precioDiff, $this->objImpuesto->porcentaje));
        $objCompra->baseImpuestosCompra += round(Precio::calcularBaseImpuesto($precioDiff,$this->objImpuesto->porcentaje));
        $objCompra->totalCompra += $precioDiff;

        if ($this->unidades + $this->fracciones == 0) {
            $objCompra->flete -= $this->flete;
        }

        $transaction = Yii::app()->db->beginTransaction();

        if (!$this->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización item: ' . $this->validateErrorsResponse());
        }

        if($objCompra->totalCompra<0){
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Total compra no puede ser negativo');
        }
        if (!$objCompra->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización compra: ' . $objCompra->validateErrorsResponse());
        }
        $transaction->commit();
    }

    public function actualizarBodega($cantidad) {
        $cantDiff = $cantidad - $this->unidadesCedi;
        //igual
        if ($cantDiff == 0) {
            echo CJSON::encode(array('result' => 'error', 'response' => 'Actualización exitosa.'));
            Yii::app()->end();
        }

        //aumentar
        if ($cantDiff > 0) {
            $objSaldo = ProductosSaldosCedi::model()->find(array(
                'condition' => 'codigoProducto=:codigo AND codigoCedi=:cedi',
                'params' => array(
                    ':codigo' => $this->codigoProducto,
                    ':cedi' => $this->objCompra->objCiudad->codigoSucursal
                )
            ));

            if ($objSaldo === null) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. No hay unidades disponibles");
            }

            if ($cantDiff > $objSaldo->saldoUnidad) {
                throw new Exception("La cantidad solicitada no está disponible en este momento. Saldos disponibles: $objSaldo->saldoUnidad unidades");
            }
        }

        $precioTotal = $this->precioBaseUnidad - $this->descuentoUnidad;
        $precioDiff = $precioTotal * $cantDiff;
        $this->unidadesCedi += $cantDiff;
        $this->precioTotalUnidad += $precioDiff;
        $this->idEstadoItem = Yii::app()->params->callcenter['estadoItem']['estado']['modificado'];
        $this->idOperador = Yii::app()->controller->module->user->id;

        $objCompra = $this->objCompra;
        $objCompra->subtotalCompra += $precioDiff;
        $objCompra->impuestosCompra += round(Precio::calcularImpuesto($precioDiff, $this->objImpuesto->porcentaje));
        $objCompra->baseImpuestosCompra += round(Precio::calcularBaseImpuesto($precioDiff,$this->objImpuesto->porcentaje));
        $objCompra->totalCompra += $precioDiff;

        if ($this->unidades + $this->fracciones == 0) {
            $objCompra->flete -= $this->flete;
        }

        $transaction = Yii::app()->db->beginTransaction();

        if (!$this->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización item: ' . $this->validateErrorsResponse());
        }
        if($objCompra->totalCompra<0){
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Total compra no puede ser negativo');
        }
        if (!$objCompra->save()) {
            try {
                $transaction->rollBack();
            } catch (Exception $txexc) {
                Yii::log($txexc->getMessage() . "\n" . $txexc->getTraceAsString(), CLogger::LEVEL_ERROR, 'application');
            }
            throw new Exception('Error de actualización compra: ' . $objCompra->validateErrorsResponse());
        }
        $transaction->commit();
    }

}


text:
/**
 * Write a description of class Fight here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public interface Fight
{
   public boolean fight();
}


text:
package chapter1

// Using map of runes for duplicate detection.
func IsUnique(input string) bool {
	seen := make(map[rune]struct{})
	for _, r := range input {
		if _, ok := seen[r]; ok {
			return false
		} else {
			seen[r] = struct{}{}
		}
	}
	return true
}


text:
====================
Testing Instructions
====================

----------------------
Running the test suite
----------------------

To run all of the Packaginator tests::

    python manage.py test --settings.base

To run tests for a particular Packaginator app, for example the feeds app::

    python manage.py test feeds --settings.base


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
	<meta content="2013-12-25 10:18:47 -0700" http-equiv="change-date" />
	<title>1CR 10</title>

	<link rel="stylesheet" href='../css/bpi.css' >

1º Crônicas 10

1Ora, os filisteus pelejaram contra Israel; e os homens de Israel, fugindo de diante dos filisteus, caíram mortos no monte Gilboa.

2Os filisteus perseguiram a Saul e seus filhos, e mataram Jônatas, Abinadabe e Malquisua, filhos de Saul.

3A peleja se agravou contra Saul, e os flecheiros o alcançaram, e ele foi ferido pelos flecheiros.

4Então disse Saul: Arranca a tua espada, e atravessa-me com ela, para que não venham estes incircuncisos e escarneçam de mim. Mas o seu escudeiro não quis, porque temia muito; então tomou Saul a sua espada, e se lançou sobre ela.

5Vendo, pois, o seu escudeiro que Saul estava morto, lançou-se também sobre sua espada, e morreu.

6Assim morreram Saul e seus três filhos; morreu toda a sua casa juntamente.

7Quando todos os homens de Israel que estavam no vale viram que Israel havia fugido, e que Saul eram mortos, abandonaram as suas cidades e fugiram, e vindo os filisteus, habitaram nelas.

8No dia seguinte, quando os filisteus vieram para despojar os mortos acharam Saul e seus filhos estirados no monte Gilboa.

9Então o despojaram, tomaram a sua cabeça e as suas armas, e enviaram mensageiros pela terra dos filisteus em redor, para levarem a boa nova a seus ídolos e ao povo.

10Puseram as armas dele na casa de seus deuses, e pregaram-lhe a cabeça na casa de Dagom.

11Quando, pois, toda a Jabes-Gileade ouviu tudo quanto os filisteus haviam feito a Saul,

12todos os homens valentes se levantaram e, tomando o corpo de Saul e os corpos de seus filhos, trouxeram-nos: a Jabes; e sepultaram os seus ossos debaixo o terebinto em Jabes, e jejuaram sete dias.

13Assim morreu Saul por causa da sua infidelidade para com o Senhor, porque não havia guardado a palavra do Senhor; e também porque buscou a adivinhadora para a consultar,

14e não buscou ao Senhor; pelo que ele o matou, e transferiu o reino a Davi, filho de Jessé.

Almeida Revista e Atualizada© Copyright © 1993 Sociedade Bíblica do Brasil. Todos os direitos reservados. Texto bíblico utilizado com autorização. Saiba mais sobre a Sociedade Bíblica do Brasil. A Sociedade Bíblica do Brasil trabalha para que a Bíblia esteja, efetivamente, ao alcance de todos e seja lida por todos. A SBB é uma entidade sem fins lucrativos, dedicada a promover o desenvolvimento integral do ser humano.


text:
package com.spotify.scio.redis.syntax

import com.spotify.scio.io.ClosedTap
import com.spotify.scio.redis.{RedisConnectionOptions, RedisMutator, RedisWrite}
import com.spotify.scio.redis.RedisWrite.WriteParam
import com.spotify.scio.redis.types._
import com.spotify.scio.values.SCollection

final class SCollectionRedisOps[T <: RedisMutation: RedisMutator](
  private val self: SCollection[T]
) {

  def saveAsRedis(
    connectionOptions: RedisConnectionOptions,
    batchSize: Int = RedisWrite.WriteParam.DefaultBatchSize
  ): ClosedTap[Nothing] = {
    val params = WriteParam(batchSize)
    self.write(RedisWrite[T](connectionOptions))(params)
  }

}

trait SCollectionSyntax {
  implicit def redisSCollectionOps[T <: RedisMutation: RedisMutator](
    coll: SCollection[T]
  ): SCollectionRedisOps[T] = new SCollectionRedisOps[T](coll)
}


text:
package dad.practica.pesemu.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import dad.practica.pesemu.model.Usuario;

public interface UsuarioRepository extends JpaRepository<Usuario, Long> {

	Usuario findByCorreo(String correo);

}


text:
package roomtime

import (
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"fmt"
)

// Time is an abstract time value
type Time struct {
	N uint64
}

// New allocates and returns a new Time.
func New(n uint64) *Time {
	return &Time{n}
}

// Parse interprets raw as a Time value in the wire format.
func Parse(raw []byte) *Time {
	if len(raw) != 8 {
		return nil
	}

	n := binary.BigEndian.Uint64(raw)
	t := &Time{N: n}
	return t
}

// Bytes returns the wire format representation of t.
func (t *Time) Bytes() []byte {
	var b [8]byte
	binary.BigEndian.PutUint64(b[:], t.N)
	return b[:]
}

// MarshalJSON implements json.Marshaller.
func (t *Time) MarshalJSON() ([]byte, error) {
	var x [18]byte
	x[0] = '"'
	hex.Encode(x[1:17], t.Bytes())
	x[17] = '"'
	return x[:], nil
}

// UnmarshalJSON implements json.Unmarshaller.
func (t *Time) UnmarshalJSON(b []byte) error {
	var s string
	err := json.Unmarshal(b, &s)
	if err != nil {
		return err
	}
	raw, err := hex.DecodeString(s)
	if err != nil {
		return err
	}
	_t := Parse(raw)
	if _t == nil {
		return fmt.Errorf("invalid time")
	}
	*t = *_t
	return nil
}


text:
from setuptools import setup

setup(
    name = "django-redis-cache",
    url = "http://github.com/sebleier/django-redis-cache/",
    author = "Sean Bleier",
    author_email = "sebleier@gmail.com",
    version = "0.9.2",
    packages = ["redis_cache"],
    description = "Redis Cache Backend for Django",
    install_requires=['redis>=2.4.5',],
    classifiers = [
        "Programming Language :: Python",
        "Operating System :: OS Independent",
        "Topic :: Software Development :: Libraries",
        "Topic :: Utilities",
        "Environment :: Web Environment",
        "Framework :: Django",
    ],
)


text:
<?php

// Specify character set in HTTP headers for better load time
header('Content-type: application/json; charset=utf-8');

include('keys.php');

$tomatoJSON = file_get_contents("http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=10&page=1&country=us&apikey=" . RT_KEY);
print $tomatoJSON;
// $jsonDecoded = json_decode($tomatoJSON);

?>


text:
;@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
;@                                                                            @
;@                 S Y M B O S   S Y S T E M   L I B R A R Y                  @
;@                        - NETWORK DAEMON FUNCTIONS -                        @
;@                                                                            @
;@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

;Author     Prodatron / SymbiosiS
;Date       11.07.2015

;This library supports you in using all network daemon functions.

;The existance of
;- "App_PrcID" (a byte, where the ID of the applications process is stored)
;- "App_MsgBuf" (the message buffer, 14 bytes, which are placed in the transfer
;  ram area)
;- "App_BnkNum" (a byte, where the number of the applications' ram bank (0-15)
;  is stored)
;is required.

;### SUMMARY ##################################################################

;;   SyNet_NETINI                ;...
;use_SyNet_NETEVT        equ 0   ;check for network events
;use_SyNet_CFGGET        equ 0   ;Config get data
;use_SyNet_CFGSET        equ 0   ;Config set data
;use_SyNet_CFGSCK        equ 0   ;Config socket status
;use_SyNet_TCPOPN        equ 0   ;TCP open connection
;use_SyNet_TCPCLO        equ 0   ;TCP close connecton
;use_SyNet_TCPSTA        equ 0   ;TCP status of connection
;use_SyNet_TCPRCV        equ 0   ;TCP receive from connection
;use_SyNet_TCPSND        equ 0   ;TCP send to connection
;use_SyNet_TCPSKP        equ 0   ;TCP skip received data
;use_SyNet_TCPFLS        equ 0   ;TCP flush send buffer
;use_SyNet_TCPDIS        equ 0   ;TCP disconnect connection
;use_SyNet_TCPRLN        equ 0   ;TCP receive textline from connection
;use_SyNet_UDPOPN        equ 0   ;UDP open
;use_SyNet_UDPCLO        equ 0   ;UDP close
;use_SyNet_UDPSTA        equ 0   ;UDP status
;use_SyNet_UDPRCV        equ 0   ;UDP receive
;use_SyNet_UDPSND        equ 0   ;UDP send
;use_SyNet_UDPSKP        equ 0   ;UDP skip received data
;use_SyNet_DNSRSV        equ 0   ;DNS resolve
;use_SyNet_DNSVFY        equ 0   ;DNS verify

;### GLOBAL VARIABLES #########################################################

SyNet_PrcID db 0    ;network daemon process ID

;### GENERAL FUNCTIONS ########################################################

SyNet_NETINI
;******************************************************************************
;*** Name           Network_Init
;*** Input          -
;*** Output         CF   = Error state (0 = ok, 1 = Network daemon not running)
;***                - if CF is 0:
;***                (SyNet_PrcID) = Network daemon process ID
;*** Destroyed      AF,BC,DE,HL,IX,IY
;*** Description    ...
;******************************************************************************
        ld e,0
        ld hl,snwdmnt
        ld a,(App_BnkNum)
        call SySystem_PRGSRV
        or a
        scf
        ret nz
        ld a,h
        ld (SyNet_PrcID),a
        or a
        ret
snwdmnt db "Network Daem"

if use_SyNet_NETEVT=1
SyNet_NETEVT
;******************************************************************************
;*** Name           Network_Event
;*** Input          -
;*** Output         CF   = Flag, if network event occured (1=no)
;***                - if CF is 0:
;***                A    = Handle
;***                L    = Status (1=TCP opening, 2=TCP established, 3=TCP
;***                       close waiting, 4=TCP close,
;***                       16=UDP sending,
;***                       128=data received)
;***                IX,IY= Remote IP
;***                DE   = Remote port
;***                BC   = Received bytes
;*** Destroyed      F,HL
;*** Description    ...
;******************************************************************************
        ld a,(App_PrcID)
        db #dd:ld l,a
        ld a,(SyNet_PrcID)
        db #dd:ld h,a
        ld iy,App_MsgBuf
        rst #18                 ;check for message
        db #dd:dec l
        scf
        ret nz                  ;no message available
        ld a,(App_MsgBuf)
        cp MSR_NET_TCPEVT
        jp z,snwmsgo_afbcdehlixiy
        cp MSR_NET_UDPEVT
        jp z,snwmsgo_afbcdehlixiy
        scf                     ;senseless message
        ret
endif

;### CONFIG FUNCTIONS #########################################################

if use_SyNet_CFGSET=1
SyNet_CFGGET
;******************************************************************************
;*** ID             001 (CFGGET)
;*** Name           Config_GetData
;*** Input          A    = Type
;***                HL   = Config data buffer
;*** Output         CF   = status (CF=1 invalid type)
;*** Destroyed      AF,BC,DE,HL,IX,IY
;*** Description    ...
;******************************************************************************
        ld de,(App_BnkNum)
        call snwmsgi_afdehl
        db FNC_NET_CFGGET
        jp snwmsgo_afhl
endif

if use_SyNet_CFGGET=1
SyNet_CFGSET
;******************************************************************************
;*** ID             002 (CFGSET)
;*** Name           Config_SetData
;*** Input          A    = Type
;***                HL   = New config data
;*** Output         CF   = status (CF=1 invalid type)
;*** Destroyed      AF,BC,DE,HL,IX,IY
;*** Description    ...
;******************************************************************************
        ld de,(App_BnkNum)
        call snwmsgi_afdehl
        db FNC_NET_CFGSET
        jp snwmsgo_afhl
endif

if use_SyNet_CFGSCK=1
SyNet_CFGSCK
;******************************************************************************
;*** ID             003 (CFGSCK)
;*** Name           Config_SocketStatus
;*** Input          A    = first socket
;***                C    = number of sockets
;***                HL   = data buffer
;*** Output         CF   = status (CF=1 invalid range)
;*** Destroyed      AF,BC,DE,HL,IX,IY
;*** Description    ...
;******************************************************************************
        ld de,(App_BnkNum)
        call snwmsgi_afbcdehl
        db FNC_NET_CFGSCK
        jp snwmsgo_afhl
endif

;### TCP FUNCTIONS ############################################################

if use_SyNet_TCPOPN=1
;******************************************************************************
;*** ID             016 (TCPOPN)
;*** Name           TCP_Open
;*** Input          A    = Type (0=active/client, 1=passive/server)
;***                HL   = Local port (-1=dynamic client port)
;***                - if A is 0:
;***                IX,IY= Remote IP
;***                DE   = Remote port
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Opens a TCP connection as a client (active) or as a server
;***                (passive). If it's an active connection you have to specify
;***                the remote IP address and port number as well.
;***                The local port number always has to be set. For client
;***                network applications you should set HL to -1 (65535) to get
;***                a dynamic port number. This will automaticaly generated by
;***                the network daemon in the range of 49152-65535 (official
;***                range for dynamic ports).
;***                This function will fail, if there is no free socket left.
;***                It returns the connection handle if it was successful.
;******************************************************************************
SyNet_TCPOPN
        call snwmsgi_afbcdehlixiy
        db FNC_NET_TCPOPN
        jp snwmsgo_afhl
endif

if use_SyNet_TCPCLO=1
;******************************************************************************
;*** ID             017 (TCPCLO)
;*** Name           TCP_Close
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Closes a TCP connection and releases the used socket. It
;***                will not send a disconnect signal to the remote host (see
;***                TCPDIS). Use this, after the remote host already
;***                closed the connection.
;******************************************************************************
SyNet_TCPCLO
        call snwmsgi_af
        db FNC_NET_TCPCLO
        jp snwmsgo_afhl
endif

if use_SyNet_TCPSTA=1
;******************************************************************************
;*** ID             018 (TCPSTA)
;*** Name           TCP_Status
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;***                L    = Status (1=TCP opening, 2=TCP established, 3=TCP
;***                       close waiting, 4=TCP close; +128=data received)
;***                - if L is >1:
;***                IX,IY= Remote IP
;***                DE   = Remote port
;***                - if L is >=128:
;***                BC   = Received bytes (which are available in the RX
;***                       buffer)
;*** Destroyed      F,H
;*** Description    Returns the actual status of the TCP connection. Usually
;***                this is exactly the same as received in the last event
;***                message (see TCPEVT). The number of received bytes in BC
;***                may have been increased during the last event, if it was
;***                already larger than 0.
;******************************************************************************
SyNet_TCPSTA
        call snwmsgi_af
        db FNC_NET_TCPSTA
        jp snwmsgo_afbcdehlixiy
endif

if use_SyNet_TCPRCV=1
;******************************************************************************
;*** ID             019 (TCPRCV)
;*** Name           TCP_Receive
;*** Input          A    = Handle
;***                E    = Destination bank
;***                HL   = Destination address
;***                BC   = Length (has to be >0)
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;***                BC   = Number of transfered bytes (which have been copied
;***                       to the destination)
;***                HL   = Number of remaining bytes (which are still left in
;***                       the RX buffer)
;***                ZF   = 1 -> no remaining bytes (RX buffer is empty)
;*** Destroyed      F,DE,HL,IX,IY
;*** Description    Copies data, which has been received from the remote host,
;***                to a specified destination in memory. The length of the
;***                requested data is not limited, but this function will only
;***                receive the available one.
;***                Please note, that a new TCPEVT event only occurs on new
;***                incoming bytes, if this function returned HL=0 (no
;***                remaining bytes). It may happen, that during the last
;***                TCPEVT/TCPSTA status the number of remaining bytes has been
;***                increased, so you always have to check HL, even if you
;***                requested all incoming bytes known from the last status.
;******************************************************************************
SyNet_TCPRCV
        call snwmsgi_afbcdehl
        db FNC_NET_TCPRCV
        jp snwmsgo_afbchl
endif

if use_SyNet_TCPSND=1
;******************************************************************************
;*** ID             020 (TCPSND)
;*** Name           TCP_Send
;*** Input          A    = Handle
;***                E    = Source bank
;***                HL   = Source address
;***                BC   = Length
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;***                BC   = Number of transfered bytes
;***                HL   = Number of remaining bytes (which couldn't be
;***                       transfered, as the TX buffer is full at the moment)
;***                ZF   = 1 -> no remaining bytes
;*** Destroyed      F,DE,IX,IY
;*** Description    Sends data to the remote host. The length of the data is
;***                not limited, but this function may send only a part of it.
;***                In case that not all data have been send, the application
;***                should idle for a short time and send the remaining part
;***                at another attempt.
;******************************************************************************
SyNet_TCPSND
        call snwmsgi_afbcdehl
        db FNC_NET_TCPSND
        jp snwmsgo_afbchl
endif

if use_SyNet_TCPSKP=1
;******************************************************************************
;*** ID             021 (TCPSKP)
;*** Name           TCP_Skip
;*** Input          A    = Handle
;***                BC   = Length
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Skips data, which has been received from the remote host.
;***                This can be used if the application is sure, that the
;***                following bytes are not needed and the data transfer can be
;***                skipped to save resources. The amount of bytes must be
;***                equal or smaller than the total amount of received data.
;******************************************************************************
SyNet_TCPSKP
        call snwmsgi_afbcdehl
        db FNC_NET_TCPSKP
        jp snwmsgo_afhl
endif

if use_SyNet_TCPFLS=1
;******************************************************************************
;*** ID             022 (TCPFLS)
;*** Name           TCP_Flush
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Flushes the send buffer. This maybe used to send data
;***                immediately, as some network hardware or software
;***                implementations may store it first in the send buffer for a
;***                while until it is full or a special amount of time has
;***                passed.
;******************************************************************************
SyNet_TCPFLS
        call snwmsgi_af
        db FNC_NET_TCPFLS
        jp snwmsgo_afhl
endif

if use_SyNet_TCPDIS=1
;******************************************************************************
;*** ID             023 (TCPDIS)
;*** Name           TCP_Disconnect
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Sends a disconnect signal to the remote host, closes the
;***                TCP connection and releases the used socket. Use this, if
;***                you want to close the connection by yourself.
;******************************************************************************
SyNet_TCPDIS
        call snwmsgi_af
        db FNC_NET_TCPDIS
        jp snwmsgo_afhl
endif

if use_SyNet_TCPRLN=1
;******************************************************************************
;*** ID             024 (TCPRLN)
;*** Name           TCP_ReceiveLine
;*** Input          A    = Handle
;***                E    = Destination bank
;***                HL   = Destination address
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;***                D    = Line length (-1=no complete line received, ZF=1)
;***                ZF   = 1 -> no complete line received
;*** Destroyed      AF,E,HL,IX,IY
;*** Description    ...
;******************************************************************************
SyNet_TCPRLN_Buffer ds 256      ;buffer
SyNet_TCPRLN_Length db 0        ;length (always <255)
SyNet_TCPRLN
        ld (snwrln3+1),a
        ld a,e
        add a:add a:add a:add a
        ld (snwrlnb+1),a
        ld (snwrlna+1),hl
        call snwrln0
        ld a,d
        inc a
        jr z,snwrln8
snwrln9 ld a,d
        inc a
        or a
snwrlnc ld a,(snwrln3+1)
        ret
snwrln8 ld a,(SyNet_TCPRLN_Length)
        ld c,a
        ld b,0
        cpl                     ;A=255-buflen
        ld hl,SyNet_TCPRLN_Buffer
        add hl,bc
        ld c,a
snwrln3 ld a,0
        ld de,(App_BnkNum)
        call snwmsgi_afbcdehl   ;receive data
        db FNC_NET_TCPRCV
        call snwmsgo_afbchl
        ret c
        ld hl,SyNet_TCPRLN_Length
        ld a,(hl)
        add c
        ld (hl),a               ;update buffer length
        call snwrln0
        jr snwrln9

snwrln0 ld a,(SyNet_TCPRLN_Length)
        cp 255
        ccf
        sbc 0
        ld d,-1
        ret z
        ld e,a                  ;e,bc=search length (max 254)
        ld c,a
        ld b,0
        ld hl,SyNet_TCPRLN_Buffer
        ld a,13
        cpir
        jr z,snwrln5
        ld a,e
        cp 254
        ret c                   ;** not found and <254 chars -> no complete line received
        inc d
snwrln4 call snwrln7            ;** not found and =254 chars -> send line anyway
        ld d,254
        ret
snwrln5 ld a,c                  ;** found -> HL=behind 13-char, BC=remaining length
        or b
        ld d,-1
        ret z                   ;found at the last position -> no complete line received
        ld d,1
        ld a,10
        cp (hl)
        jr nz,snwrln6
        inc d
snwrln6 ld bc,SyNet_TCPRLN_Buffer+1
        or a
        sbc hl,bc
        ld e,l
        push de
        call snwrln7
        pop de
        ld d,e
        ret

;e=line length, d=bytes to skip -> copy line to destination and remove it from the buffer
snwrln7 push de
        ld d,0
        ld hl,SyNet_TCPRLN_Buffer
        push hl
        add hl,de
        ld (hl),0
        pop hl
        ld c,e
        inc c
        ld b,0
        ld a,(App_BnkNum)
snwrlnb add 0
snwrlna ld de,0
        rst #20:dw jmp_bnkcop
        pop de
        ld hl,SyNet_TCPRLN_Length
        ld a,(hl)
        sub e
        sub d
        ld (hl),a
        ret z
        ld c,a
        ld b,0
        ld a,e
        add d
        ld e,a
        ld d,0
        ld hl,SyNet_TCPRLN_Buffer
        add hl,de
        ld de,SyNet_TCPRLN_Buffer
        ldir
        ret
endif

;### UDP FUNCTIONS ############################################################

if use_SyNet_UDPOPN=1
;******************************************************************************
;*** ID             032 (UDPOPN)
;*** Name           UDP_Open
;*** Input          A    = Type
;***                HL   = Local port
;***                E    = Source/destination bank for receive/send
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Opens an UDP session. Already with this functions you have
;***                to specify the ram bank number of the source and
;***                destination memory areas for upcoming data transfer.
;***                This function will fail, if there is no free socket left.
;***                It returns the session handle if it was successful.
;******************************************************************************
SyNet_UDPOPN
        call snwmsgi_afdehl
        db FNC_NET_UDPOPN
        jp snwmsgo_afhl
endif

if use_SyNet_UDPCLO=1
;******************************************************************************
;*** ID             033 (UDPCLO)
;*** Name           UDP_Close
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Closes an UDP session and releases the used socket.
;******************************************************************************
SyNet_UDPCLO
        call snwmsgi_af
        db FNC_NET_UDPCLO
        jp snwmsgo_afhl
endif

if use_SyNet_UDPSTA=1
;******************************************************************************
;*** ID             034 (UDPSTA)
;*** Name           UDP_Status
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;***                L    = Status
;***                - if L is ???:
;***                BC   = Received bytes
;***                IX,IY= Remote IP
;***                DE   = Remote port
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Returns the actual status of the UDP session. This is
;***                always exactly the same as received in the last event
;***                message (see UDPEVT).
;******************************************************************************
SyNet_UDPSTA
        call snwmsgi_af
        db FNC_NET_UDPSTA
        jp snwmsgo_afbcdehlixiy
endif

if use_SyNet_UDPRCV=1
;******************************************************************************
;*** ID             035 (UDPRCV)
;*** Name           UDP_Receive
;*** Input          A    = Handle
;***                HL   = Destination address
;***                       (bank has been specified by the UDPOPN function)
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Copies the package data, which has been received from a
;***                remote host, to a specified destination in memory. Please
;***                note, that this function will always transfer the whole
;***                data at once, so there should be enough place at the
;***                destination address. The destination ram bank number has
;***                already been specified with the UDPOPN function.
;******************************************************************************
SyNet_UDPRCV
        call snwmsgi_afhl
        db FNC_NET_UDPRCV
        jp snwmsgo_afhl
endif

if use_SyNet_UDPSND=1
;******************************************************************************
;*** ID             036 (UDPSND)
;*** Name           UDP_Send
;*** Input          A    = Handle
;***                HL   = Source address
;***                       (bank has been specified by the UDPOPN function)
;***                BC   = Length
;***                IX,IY= Remote IP
;***                DE   = Remote port
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Sends a data package to a remote host. It may happen, that
;***                the send buffer is currently full, and this function will
;***                the return the appropriate error code. In this case the
;***                application should idle for a short time and try to send
;***                the package again at another attempt.
;******************************************************************************
SyNet_UDPSND
        call snwmsgi_afbcdehlixiy
        db FNC_NET_UDPSND
        jp snwmsgo_afhl
endif

if use_SyNet_UDPSKP=1
;******************************************************************************
;*** ID             037 (UDPSKP)
;*** Name           UDP_Skip
;*** Input          A    = Handle
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                A    = Handle
;*** Destroyed      F,BC,DE,HL,IX,IY
;*** Description    Skips a received data package. This can be used if the
;***                application is sure, that the data is not needed or has
;***                sent from the wrong remote host, so the data transfer can
;***                be skipped to save resources.
;******************************************************************************
SyNet_UDPSKP
        call snwmsgi_af
        db FNC_NET_UDPSKP
        jp snwmsgo_afhl
endif

;### DNS FUNCTIONS ############################################################

if use_SyNet_DNSRSV=1
;******************************************************************************
;*** ID             112 (DNSRSV)
;*** Name           DNS_Resolve
;*** Input          HL = string address (0-terminated)
;*** Output         CF   = Error state (0 = ok, 1 = error; A = error code)
;***                - if CF is 0:
;***                IX,IY= IP
;*** Destroyed      AF,BC,DE,HL
;*** Description    ...
;******************************************************************************
SyNet_DNSRSV
        ld de,(App_BnkNum)
        call snwmsgi_afdehl
        db FNC_NET_DNSRSV
        jp snwmsgo_afbcdehlixiy
endif

if use_SyNet_DNSVFY=1
;******************************************************************************
;*** ID             113 (DNSVFY)
;*** Name           DNS_Verify
;*** Input          HL = string address (0-terminated)
;*** Output         L    = type of address (0=no valid address, 1=IP address,
;***                                        2=domain address)
;***                - if L is 1:
;***                IX,IY= IP
;*** Destroyed      F,BC,DE,HL
;*** Description    ...
;******************************************************************************
SyNet_DNSVFY
        ld de,(App_BnkNum)
        call snwmsgi_afdehl
        db FNC_NET_DNSVFY
        jp snwmsgo_afbcdehlixiy
endif

;### SUB ROUTINES #############################################################

snwmsgi_afbcdehlixiy
        ld (App_MsgBuf+10),ix   ;store registers to message buffer
        ld (App_MsgBuf+12),iy
snwmsgi_afbcdehl
        ld (App_MsgBuf+04),bc
snwmsgi_afdehl
        ld (App_MsgBuf+06),de
snwmsgi_afhl
        ld (App_MsgBuf+08),hl
snwmsgi_af
        push af:pop hl
        ld (App_MsgBuf+02),hl
        pop hl
        ld a,(hl)               ;set command
        inc hl
        push hl
        ld (App_MsgBuf+0),a
        ld (snwmsg2+1),a
        ld iy,App_MsgBuf
        ld a,(App_PrcID)
        db #dd:ld l,a
        ld a,(SyNet_PrcID)
        db #dd:ld h,a
        ld (snwmsg1+2),ix
        rst #10                 ;send message
snwmsg1 ld ix,0                 ;wait for response
        rst #08
        db #dd:dec l
        jr nz,snwmsg1
        ld a,(App_MsgBuf)
        sub 128
snwmsg2 cp 0
        ret z
        ld a,(App_PrcID)        ;wrong response code -> re-send and wait for correct one
        db #dd:ld h,a
        ld a,(SyNet_PrcID)
        db #dd:ld l,a
        rst #10
        rst #30
        jr snwmsg1
snwmsgo_afbcdehlixiy
        ld ix,(App_MsgBuf+10)   ;get registers from the message buffer
        ld iy,(App_MsgBuf+12)
        ld de,(App_MsgBuf+06)
snwmsgo_afbchl
        ld bc,(App_MsgBuf+04)
snwmsgo_afhl
        ld hl,(App_MsgBuf+02)
        push hl
        pop af
        ld hl,(App_MsgBuf+08)
        ret


text:
<?php

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Helper for mod_syndicate
 *
 * @package     Joomla.Site
 * @subpackage  mod_syndicate
 * @since       1.5
 */
class ModSyndicateHelper
{
	/**
	 * Gets the link
	 *
	 * @param   \Joomla\Registry\Registry  &$params  module parameters
	 *
	 * @return  array  The link as a string
	 *
	 * @since   1.5
	 */
	public static function getLink(&$params)
	{
		$document = JFactory::getDocument();

		foreach ($document->_links as $link => $value)
		{
			$value = ArrayHelper::toString($value);

			if (strpos($value, 'application/' . $params->get('format') . '+xml'))
			{
				return $link;
			}
		}
	}
}


text:
Template.signUp.events({

  'submit form': function(e,t){
    e.preventDefault();
    toggleSpinner("2rem", "show");
    var email = $('[name=email]').val();
    var password = $('[name=password]').val();
    var username = $('[name=username]').val();
    /** validations */
    if (isNotEmpty(email) &&
    isEmail(email) &&
    isNotEmpty(username) &&
    isNotEmpty(password) &&
    isValidPassword(password)) {
      Accounts.createUser({
        email: email,
        password: password,
        username: username
      }, function (error) {
        if (error) {
          toggleSpinner("2rem","hide");
          NProgress.stop();
          sAlert.error(error.reason);
        } else {
          sAlert.success("Your account has been created!");
          sAlert.info("An email has been sent to your inbox. Verify your email address to continue.", {timeout: 'none'});
          FlowRouter.go("/dashboard/profile/edit");
        }
      });
    } else {
      toggleSpinner("2rem","hide");
    }

    return false;
  }

});


text:
using System;
using System.Runtime.Serialization;
using Tweetsharp;
using Newtonsoft.Json;

namespace TweetSharp
{
    [JsonObject(MemberSerialization.OptIn)]
    public class TwitterRelationship : PropertyChangedBase, ITwitterModel
    {
        private TwitterFriend _source;
        private TwitterFriend _target;

#if !Smartphone && !NET20
        /// <summary>
        /// Gets or sets the relative source of the relationship.
        /// </summary>
        /// <value>The source.</value>
        [DataMember]
#endif
        [JsonProperty("source")]
        public virtual TwitterFriend Source
        {
            get { return _source; }
            set
            {
                if (_source == value)
                {
                    return;
                }

                _source = value;
                OnPropertyChanged("Source");
            }
        }

#if !Smartphone && !NET20
        /// <summary>
        /// Gets or sets the relative target of the relationship.
        /// </summary>
        /// <value>The target.</value>
        [DataMember]
#endif
        [JsonProperty("target")]
        public virtual TwitterFriend Target
        {
            get { return _target; }
            set
            {
                if (_target == value)
                {
                    return;
                }

                _target = value;
                OnPropertyChanged("Target");
            }
        }

#if !Smartphone && !NET20
        [DataMember]
#endif
        public virtual string RawSource { get; set; }
    }
}