text:
using Eventual.MessageContracts;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Eventual.EventStore
{
    public class EventStoreConcurrencyException : Exception
    {
        public Guid StreamId { get; }
        public int CurrentSteamSequence { get; }
        public int LoadedStreamSequence { get; }
        public int Difference { get; }
        public IEnumerable<string> ExtraEventTypes { get; }

        public EventStoreConcurrencyException(Guid streamId, int loadedStreamSequence, int currentSteamSequence)
        {
            StreamId = streamId;
            LoadedStreamSequence = loadedStreamSequence;
            CurrentSteamSequence = currentSteamSequence;
            Difference = CurrentSteamSequence - LoadedStreamSequence;
        }

        public EventStoreConcurrencyException(Guid streamId, int loadedStreamSequence, int currentSteamSequence, IEnumerable<Type> extraEvents)
            : this (streamId, loadedStreamSequence, currentSteamSequence)
        {
            ExtraEventTypes = extraEvents.Select(x => x.FullName);
        }

        public override string Message {
            get {
                var extraEvents = " extra event(s)";
                var missingEvents = " missing event(s)";
                var differencePhrase = Difference > 0 ? extraEvents : missingEvents;

                var message = $@"Concurrency exception, stream being saved to has been modified.
StreamId: { StreamId}
Loaded Stream Sequence: {LoadedStreamSequence}
Current Stream Sequence: {CurrentSteamSequence}
Difference: {Difference} {differencePhrase}

When updating a stream all events in that stream are first read, in this case there were {LoadedStreamSequence} _
events in the stream when the stream was loaded. Once the events are loaded work is done using them to _
calculate subsequent events. These new events are then appended to the stream. However, in this case another agent _
changed the stream by {Difference} events. This means the new events created using the origial set _
of events is out of date. The action that casued these events to be created must retry using the new up-to-date _
event stream.

"
+ ((Difference > 0) ? (@"Extra Events:
"
+ string.Join(Environment.NewLine, ExtraEventTypes)) : "")
+ $@"
Suggestions
 1) Check if you've got lots of changes happening to a single aggregate, if you do you might need to perform these changes in serial.
 2) If this happens occasionally let the user rety or add automated retries, remember you'll have to load the aggregate again and completely retry.
 3) If the extra events do not conflict register them as non conflicting and they'll be appended after the extra evens, beware this is dangerious if you get it wrong.
";
                return message.Replace("_" + Environment.NewLine, "");
            }
        }
    }
}


text:
(function() {

  App.List = Backbone.Model.extend({
    initialize: function(dirtyData) {
      this[dirtyData.source](dirtyData);
    },

    rdio: function(dirtyData) {
      if (dirtyData.type == 'playlist') {
        // TODO
      }
    }
  });

})();

redpajama_set_name: RedPajamaGithub


text:
using RestSharp;

namespace Contour.Testing.Plumbing
{
    internal class RabbitJsonSerializerStrategy : PocoJsonSerializerStrategy
    {
        protected override string MapClrMemberNameToJsonFieldName(string clrPropertyName)
        {
            return base.MapClrMemberNameToJsonFieldName(clrPropertyName.ToLowerInvariant());
        }
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe ProfileQuestion do
  before(:each) do
    @valid_attributes = {
      :profile_id => 1,
      :name => "value for name",
      :value => "value for value"
    }
  end

  it "should create a new instance given valid attributes" do
    ProfileQuestion.create!(@valid_attributes)
  end
end


text:
using System.ComponentModel;

namespace System
{
    public static class EnumExtension
    {
        public static string GetDescription(this Enum value)
        {
            var fieldInfo = value.GetType().GetField(value.ToString());
            if (fieldInfo == null)
                return default(string);

            var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
                return attributes[0].Description;

            return value.ToString();
        }
    }
}


text:
module SwellSocial

	class NotificationService

		def self.notify( recipients, content, args = {} )
			# @todo insert more efficiently
			# @todo start a job to process event notifications... they don't need to be synchronous
			# @todo run a cron which batches events together into a notification (Mac Knife and 3 other products have dropped in price)

			title 			= args[:title]
			user_event 	= args[:user_event]
			status 			= args[:status] || 'unread'
			actor 			= args[:actor]

			recipients.each do | recipient |

					user = recipient
					user = recipient.user if recipient.is_a? ObjectSubscription

					Notification.create user: user, actor: actor, content: content, title: title, status: status, user_event: user_event
					# @coulddo push notifications
					# @todo count updates

			end

		end

	end

end


text:
**MaterialPrime** is new JSF project built with [PrimeFaces](http://www.primefaces.org/). It helps you create JSF applications that follows the **Google** [Material Design](http://www.google.com/design/spec/material-design/introduction.html) guidelines. It's based on [MaterializeCSS](http://materializecss.com/) library.

**The work on MaterialPrime is funded by the community. Just check the project page on [Patreon](https://www.patreon.com/material_prime).**

If you want to contribute to the project, just fork our [GitHub repository](https://github.com/MaterialPrime/), or simply contact me at [francesco.strazzullo86@gmail.com](mailto:francesco.strazzullo86@gmail.com)! :D

## Setup
### Stable Version

You can use Jitpack to use MaterialPrime. Just add this repository:

    <repositories>
    	<repository>
    	    <id>jitpack.io</id>
    	    <url>https://jitpack.io</url>
    	</repository>
    </repositories>

Now just add the dependency to the pom.xml file.

    <dependency>
        <groupId>com.github.MaterialPrime</groupId>
        <artifactId>material-prime</artifactId>
        <version>v0.0.2</version>
    </dependency>

To use MaterialPrime in a JSF page, just add the namespace on the top of the page

    <html xmlns="http://www.w3.org/1999/xhtml"
    	xmlns:mp="http://primefaces.org/ui/material"
    	xmlns:p="http://primefaces.org/ui">

If you're using Gradle just follow the guide [here](https://jitpack.io/#MaterialPrime/material-prime).

You can also download the last stable [jar file](https://jitpack.io/com/github/MaterialPrime/material-prime/v0.0.2/material-prime-v0.0.2.jar).

### Bleeding Edge

If you want the last unstable version of MaterialPrime, you need to change the dependency like this:

    <dependency>
        <groupId>com.github.MaterialPrime</groupId>
        <artifactId>material-prime</artifactId>
        <version>develop-SNAPSHOT</version>
    </dependency>

### Custom build

If you want to use a jar file of MaterialPrime you need maven to build it:

    git clone https://github.com/MaterialPrime/material-prime.git
    cd material-prime
    mvn package

Enjoy! :)


text:
@interface BTTradeTVC () <RETableViewManagerDelegate>
@property (nonatomic, strong) RETableViewManager *manager;
@end

@implementation BTTradeTVC

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"交易", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"tab_trade"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.manager = [[RETableViewManager alloc] initWithTableView:self.tableView delegate:self];
    [self addBuySection];
    [self addSellSection];
    [self addOrderSection];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)addBuySection{
    RETableViewSection *section = [RETableViewSection section];
    section.headerTitle = NSLocalizedString(@"买入比特币", @"");
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 8)];
    section.footerView = footerView;
    [_manager addSection:section];

    RETextItem *amountItem = [RETextItem itemWithTitle:NSLocalizedString(@"购买数额 (฿):", @"") value:@"" placeholder:@"0.000"];
    amountItem.keyboardType = UIKeyboardTypeDecimalPad;
    RETextItem *priceItem = [RETextItem itemWithTitle:NSLocalizedString(@"出价 (¥):", @"") value:@"" placeholder:@"0.00"];
    priceItem.keyboardType = UIKeyboardTypeDecimalPad;
    RETableViewItem *buttonItem = [RETableViewItem itemWithTitle:NSLocalizedString(@"下买单", @"") accessoryType:UITableViewCellAccessoryNone selectionHandler:^(RETableViewItem *item) {
        [item deselectRowAnimated:YES];
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        if ([BTDataManager shared].userAccessKey) {
            if ([amountItem.value isEqualToString:@""] || [priceItem.value isEqualToString:@""]) {
                [[DHActionManager shared] showAndHideHUDWithTitle:NSLocalizedString(@"提示", @"") detailText:NSLocalizedString(@"数额和价格不能为空", @"") inView:self.view];
                return;
            }
            [UIAlertView showWithTitle:NSLocalizedString(@"确认买单", @"")
                               message:[NSString stringWithFormat:@"购买数额 (฿):%@\n出价 (¥):%@",amountItem.value,priceItem.value]
                     cancelButtonTitle:NSLocalizedString(@"取消", @"")
                     otherButtonTitles:@[NSLocalizedString(@"提交", @"")]
                              tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                  NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
                                  if ([title isEqualToString:NSLocalizedString(@"提交", @"")]) {

                                      MBProgressHUD *hud = [[DHActionManager shared] showHUDWithTitle:Nil detailText:Nil inView:self.view];
                                      hud.mode = MBProgressHUDModeIndeterminate;
                                      [[BCTradeAPIKit sharedAPIKit] requestBuyOrderWithPrice:priceItem.value amount:amountItem.value success:^(NSDictionary *result) {
                                          hud.mode = MBProgressHUDModeText;
                                          hud.labelText = NSLocalizedString(@"提交买单成功", @"");
                                          double delayInSeconds1 = 1.8;
                                          dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 * NSEC_PER_SEC));
                                          dispatch_after(popTime1, dispatch_get_main_queue(), ^(void){
                                              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                              [self dismissViewControllerAnimated:YES completion:NULL];
                                          });
                                          amountItem.value = nil;
                                          priceItem.value = nil;
                                          [self.tableView reloadData];
                                      } failure:^(NSError *error) {
                                          hud.mode = MBProgressHUDModeText;
                                          hud.labelText = NSLocalizedString(@"提交买单失败", @"");
                                          double delayInSeconds1 = 1.8;
                                          dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 * NSEC_PER_SEC));
                                          dispatch_after(popTime1, dispatch_get_main_queue(), ^(void){
                                              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                              [self dismissViewControllerAnimated:YES completion:NULL];
                                          });
                                      }];

                                  }
                              }];
        }else{
            BTLoginTVC *loginTVC = [[BTLoginTVC alloc] initWithStyle:UITableViewStyleGrouped];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginTVC];
            [self.navigationController presentViewController:nav animated:YES completion:NULL];
        }
    }];
    buttonItem.textAlignment = NSTextAlignmentCenter;

    [section addItem:amountItem];
    [section addItem:priceItem];

    RETableViewSection *btnSection = [RETableViewSection section];
    UIView *btnHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 2)];
    btnSection.headerView = btnHeaderView;
    [_manager addSection:btnSection];
    [btnSection addItem:buttonItem];
}

- (void)addSellSection{
    RETableViewSection *section = [RETableViewSection section];
    section.headerTitle = NSLocalizedString(@"卖出比特币", @"");
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 8)];
    section.footerView = footerView;
    [_manager addSection:section];

    RETextItem *amountItem = [RETextItem itemWithTitle:NSLocalizedString(@"出售数额 (฿):", @"") value:@"" placeholder:@"0.000"];
    amountItem.keyboardType = UIKeyboardTypeDecimalPad;
    RETextItem *priceItem = [RETextItem itemWithTitle:NSLocalizedString(@"售价 (¥):", @"") value:@"" placeholder:@"0.00"];
    priceItem.keyboardType = UIKeyboardTypeDecimalPad;
    RETableViewItem *buttonItem = [RETableViewItem itemWithTitle:NSLocalizedString(@"下卖单", @"") accessoryType:UITableViewCellAccessoryNone selectionHandler:^(RETableViewItem *item) {
        [item deselectRowAnimated:YES];
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        if ([BTDataManager shared].userAccessKey) {
            if (!amountItem.value || [amountItem.value isEqualToString:@""] || !priceItem.value || [priceItem.value isEqualToString:@""]) {
                [[DHActionManager shared] showAndHideHUDWithTitle:NSLocalizedString(@"提示", @"") detailText:NSLocalizedString(@"数额和价格不能为空", @"") inView:self.view];
                return;
            }
            [UIAlertView showWithTitle:NSLocalizedString(@"确认卖单", @"")
                               message:[NSString stringWithFormat:@"出售数额 (฿):%@\n售价 (¥):%@",amountItem.value,priceItem.value]
                     cancelButtonTitle:NSLocalizedString(@"取消", @"")
                     otherButtonTitles:@[NSLocalizedString(@"提交", @"")]
                              tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                  NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
                                  if ([title isEqualToString:NSLocalizedString(@"提交", @"")]) {

                                      MBProgressHUD *hud = [[DHActionManager shared] showHUDWithTitle:Nil detailText:Nil inView:self.view];
                                      hud.mode = MBProgressHUDModeIndeterminate;
                                      [[BCTradeAPIKit sharedAPIKit] requestSellOrderWithPrice:priceItem.value amount:amountItem.value success:^(NSDictionary *result) {
                                          hud.mode = MBProgressHUDModeText;
                                          hud.labelText = NSLocalizedString(@"提交卖单成功", @"");
                                          double delayInSeconds1 = 1.8;
                                          dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 * NSEC_PER_SEC));
                                          dispatch_after(popTime1, dispatch_get_main_queue(), ^(void){
                                              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                              [self dismissViewControllerAnimated:YES completion:NULL];
                                          });
                                          amountItem.value = nil;
                                          priceItem.value = nil;
                                          [self.tableView reloadData];
                                      } failure:^(NSError *error) {
                                          hud.mode = MBProgressHUDModeText;
                                          hud.labelText = NSLocalizedString(@"提交卖单失败", @"");
                                          double delayInSeconds1 = 1.8;
                                          dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 * NSEC_PER_SEC));
                                          dispatch_after(popTime1, dispatch_get_main_queue(), ^(void){
                                              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                              [self dismissViewControllerAnimated:YES completion:NULL];
                                          });
                                      }];

                                  }
                              }];
        }else{
            BTLoginTVC *loginTVC = [[BTLoginTVC alloc] initWithStyle:UITableViewStyleGrouped];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginTVC];
            [self.navigationController presentViewController:nav animated:YES completion:NULL];
        }
    }];
    buttonItem.textAlignment = NSTextAlignmentCenter;

    [section addItem:amountItem];
    [section addItem:priceItem];

    RETableViewSection *btnSection = [RETableViewSection section];
    UIView *btnHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 2)];
    btnSection.headerView = btnHeaderView;
    [_manager addSection:btnSection];
    [btnSection addItem:buttonItem];
}

- (void)addOrderSection{
    RETableViewItem *orderItem = [RETableViewItem itemWithTitle:NSLocalizedString(@"尚未成交的挂单", @"")
                                                  accessoryType:UITableViewCellAccessoryDisclosureIndicator
                                               selectionHandler:^(RETableViewItem *item) {
                                                   if ([BTDataManager shared].userAccessKey) {
                                                       BTNotYetOrdersTVC *vc = [[BTNotYetOrdersTVC alloc] initWithStyle:UITableViewStyleGrouped];
                                                       [self.navigationController pushViewController:vc animated:YES];
                                                   }else{
                                                       BTLoginTVC *loginTVC = [[BTLoginTVC alloc] initWithStyle:UITableViewStyleGrouped];
                                                       UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginTVC];
                                                       [self.navigationController presentViewController:nav animated:YES completion:NULL];
                                                   }

                                               }];
    RETableViewSection *ordersSection = [RETableViewSection section];
    [ordersSection addItem:orderItem];
    [_manager addSection:ordersSection];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
package org.wso2.carbon.databridge.commons.binary.test;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.wso2.carbon.databridge.commons.binary.BinaryMessageConstants;
import org.wso2.carbon.databridge.commons.binary.BinaryMessageConverterUtil;

import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * Binary Message Convert Util Testcase.
 */
public class BinaryMessageConvertUtilTest {
    private static final Logger log = LogManager.getLogger(BinaryMessageConvertUtilTest.class);

    @Test
    public void testEventBufferSize() {
        int stringSize = BinaryMessageConverterUtil.getSize("i♥apim)");
        int intSize = BinaryMessageConverterUtil.getSize(1);
        int longSize = BinaryMessageConverterUtil.getSize(1L);
        int doubleSize = BinaryMessageConverterUtil.getSize(1D);
        int floatSize = BinaryMessageConverterUtil.getSize(1F);
        int booleanSize = BinaryMessageConverterUtil.getSize(true);
        int intArraySize = BinaryMessageConverterUtil.getSize(new int[]{1, 2, 3});

        AssertJUnit.assertEquals("Expected byte length of String is 13", 13, stringSize);
        AssertJUnit.assertEquals("Expected byte length of Int is 4", 4, intSize);
        AssertJUnit.assertEquals("Expected byte length of Float is 4", 4, floatSize);
        AssertJUnit.assertEquals("Expected byte length of Long is 8", 8, longSize);
        AssertJUnit.assertEquals("Expected byte length of Double is 8", 8, doubleSize);
        AssertJUnit.assertEquals("Expected byte length of Boolean is 4", 1, booleanSize);
        AssertJUnit.assertEquals("Expected byte length of Int-Array  is 4", 4, intArraySize);
    }

    @Test
    public void testGetString() {
        byte[] bytes = "iapim)".getBytes(StandardCharsets.UTF_8);
        ByteBuffer eventByteBuffer = ByteBuffer.wrap(bytes);
        String returnString = BinaryMessageConverterUtil.getString(eventByteBuffer, 5);
        AssertJUnit.assertEquals("Expected return string is \'iapim\'", "iapim", returnString);
    }

    @Test
    public void testLoadDataWithValidByteArray() {
        String exampleString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ";
        InputStream stream = null;
        try {
            stream = new ByteArrayInputStream(exampleString.getBytes(BinaryMessageConstants.DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        byte[] dataArray1 = new byte[75];
        try {
            BinaryMessageConverterUtil.loadData(stream, dataArray1);
        } catch (IOException e) {
            Assert.fail(e.getMessage());
        }
    }

    @Test(expectedExceptions = EOFException.class)
    public void testLoadDataWithInValidByteArray() throws IOException {
        String exampleString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ";
        InputStream stream = null;
        try {
            stream = new ByteArrayInputStream(exampleString.getBytes(BinaryMessageConstants.DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        byte[] dataArray1 = new byte[100];
        BinaryMessageConverterUtil.loadData(stream, dataArray1);
    }

    @Test
    public void testAssignData() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        try {
            BinaryMessageConverterUtil.assignData("Lorem Ipsum", byteBuffer);
            BinaryMessageConverterUtil.assignData(123, byteBuffer);
            BinaryMessageConverterUtil.assignData(1L, byteBuffer);
            BinaryMessageConverterUtil.assignData(1F, byteBuffer);
            BinaryMessageConverterUtil.assignData(1D, byteBuffer);
            BinaryMessageConverterUtil.assignData(true, byteBuffer);
            BinaryMessageConverterUtil.assignData(new int[]{1, 2, 3}, byteBuffer);
        } catch (IOException e) {
            Assert.fail(e.getMessage());
        }
    }
}


text:
module WebFont
  module LocalCache
    class << self
      attr_accessor :cache, :cache_path

      def path(filename)
        path = File.join(cache_path, filename)
        File.exist?(path) ? path : nil
      end

      def save(font)
        return nil unless cache_path

        filename = File.basename(font)
        path     = File.join(cache_path, filename)
        FileUtils.copy(font, path) unless font == path

        path
      end

      def enable?
        cache && !!cache_path && Dir.exist?(cache_path)
      end
    end
  end
end


text:
package de.saxsys.mvvmfx.utils.mapping.accessorfunctions;

import java.util.Set;
import java.util.function.BiFunction;

/**
 * A functional interface to define an immutable "setter" method of type {@link Set}. As the model element is immutable this method is not a real
 * "setter". Instead it returns a new immutable copy of the original model element that has the specified field updated to the new value.
 *
 * @param <M> the generic type of the model.
 */
@FunctionalInterface
public interface SetImmutableSetter<M, E> extends BiFunction<M, Set<E>, M> {

	/**
	 * @param model       the model instance
	 * @param newElements the new elements of this set field.
	 * @return a new model instance with the new values
	 */
	@Override
	M apply(M model, Set<E> newElements);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/draw_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/Theme.AppCompat.Light">

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="56dp"
                app:tabGravity="fill"
                app:tabIndicatorHeight="0dp"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/black"
                app:tabTextColor="@color/white"/>
        </android.support.v7.widget.Toolbar>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_margin="16dp"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu"/>

</android.support.v4.widget.DrawerLayout>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ayax.website.persistencia.controladores;

import com.ayax.website.persistencia.controladores.exceptions.NonexistentEntityException;
import com.ayax.website.persistencia.controladores.exceptions.PreexistingEntityException;
import com.ayax.website.persistencia.entidades.Factura;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.ayax.website.persistencia.entidades.Transportador;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author hmcarvajal@ayax.co
 */
public class FacturaJpaController implements Serializable {

    public FacturaJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Factura factura) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Transportador transportador = factura.getTransportador();
            if (transportador != null) {
                transportador = em.getReference(transportador.getClass(), transportador.getId());
                factura.setTransportador(transportador);
            }
            em.persist(factura);
            if (transportador != null) {
                transportador.getFacturaCollection().add(factura);
                transportador = em.merge(transportador);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findFactura(factura.getId()) != null) {
                throw new PreexistingEntityException("Factura " + factura + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Factura factura) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Factura persistentFactura = em.find(Factura.class, factura.getId());
            Transportador transportadorOld = persistentFactura.getTransportador();
            Transportador transportadorNew = factura.getTransportador();
            if (transportadorNew != null) {
                transportadorNew = em.getReference(transportadorNew.getClass(), transportadorNew.getId());
                factura.setTransportador(transportadorNew);
            }
            factura = em.merge(factura);
            if (transportadorOld != null && !transportadorOld.equals(transportadorNew)) {
                transportadorOld.getFacturaCollection().remove(factura);
                transportadorOld = em.merge(transportadorOld);
            }
            if (transportadorNew != null && !transportadorNew.equals(transportadorOld)) {
                transportadorNew.getFacturaCollection().add(factura);
                transportadorNew = em.merge(transportadorNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = factura.getId();
                if (findFactura(id) == null) {
                    throw new NonexistentEntityException("The factura with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Factura factura;
            try {
                factura = em.getReference(Factura.class, id);
                factura.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The factura with id " + id + " no longer exists.", enfe);
            }
            Transportador transportador = factura.getTransportador();
            if (transportador != null) {
                transportador.getFacturaCollection().remove(factura);
                transportador = em.merge(transportador);
            }
            em.remove(factura);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Factura> findFacturaEntities() {
        return findFacturaEntities(true, -1, -1);
    }

    public List<Factura> findFacturaEntities(int maxResults, int firstResult) {
        return findFacturaEntities(false, maxResults, firstResult);
    }

    private List<Factura> findFacturaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Factura.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Factura findFactura(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Factura.class, id);
        } finally {
            em.close();
        }
    }

    public int getFacturaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Factura> rt = cq.from(Factura.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}


text:
from typing import Sequence

def copy_table_multiple_source(dest_table_id: str, table_ids: Sequence[str]) -> None:

    # [START bigquery_copy_table_multiple_source]

    from google.cloud import bigquery

    # Construct a BigQuery client object.
    client = bigquery.Client()

    # TODO(developer): Set dest_table_id to the ID of the destination table.
    # dest_table_id = "your-project.your_dataset.your_table_name"

    # TODO(developer): Set table_ids to the list of the IDs of the original tables.
    # table_ids = ["your-project.your_dataset.your_table_name", ...]

    job = client.copy_table(table_ids, dest_table_id)  # Make an API request.
    job.result()  # Wait for the job to complete.

    print("The tables {} have been appended to {}".format(table_ids, dest_table_id))
    # [END bigquery_copy_table_multiple_source]


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
H. G. A. Engler, Pflanzenr. IV. 129(Heft 53):379, fig. 50B. 1912

#### Original name
null

### Remarks
null


text:
#ifndef DFGAbstractValue_h
#define DFGAbstractValue_h

#include <wtf/Platform.h>

#if ENABLE(DFG_JIT)

#include "ArrayProfile.h"
#include "DFGStructureAbstractValue.h"
#include "JSCell.h"
#include "SpeculatedType.h"
#include "StructureSet.h"

namespace JSC { namespace DFG {

struct AbstractValue {
    AbstractValue()
        : m_type(SpecNone)
        , m_arrayModes(0)
    {
    }

    void clear()
    {
        m_type = SpecNone;
        m_arrayModes = 0;
        m_currentKnownStructure.clear();
        m_futurePossibleStructure.clear();
        m_value = JSValue();
        checkConsistency();
    }

    bool isClear() const
    {
        bool result = m_type == SpecNone && !m_arrayModes && m_currentKnownStructure.isClear() && m_futurePossibleStructure.isClear();
        if (result)
            ASSERT(!m_value);
        return result;
    }

    void makeTop()
    {
        m_type = SpecTop;
        m_arrayModes = ALL_ARRAY_MODES;
        m_currentKnownStructure.makeTop();
        m_futurePossibleStructure.makeTop();
        m_value = JSValue();
        checkConsistency();
    }

    void clobberStructures()
    {
        if (m_type & SpecCell) {
            m_currentKnownStructure.makeTop();
            clobberArrayModes();
        } else {
            ASSERT(m_currentKnownStructure.isClear());
            ASSERT(!m_arrayModes);
        }
        checkConsistency();
    }

    void clobberValue()
    {
        m_value = JSValue();
    }

    bool isTop() const
    {
        return m_type == SpecTop && m_currentKnownStructure.isTop() && m_futurePossibleStructure.isTop();
    }

    bool valueIsTop() const
    {
        return !m_value && m_type;
    }

    JSValue value() const
    {
        return m_value;
    }

    static AbstractValue top()
    {
        AbstractValue result;
        result.makeTop();
        return result;
    }

    void setMostSpecific(JSValue value)
    {
        if (!!value && value.isCell()) {
            Structure* structure = value.asCell()->structure();
            m_currentKnownStructure = structure;
            setFuturePossibleStructure(structure);
            m_arrayModes = asArrayModes(structure->indexingType());
        } else {
            m_currentKnownStructure.clear();
            m_futurePossibleStructure.clear();
            m_arrayModes = 0;
        }

        m_type = speculationFromValue(value);
        m_value = value;

        checkConsistency();
    }

    void set(JSValue value)
    {
        if (!!value && value.isCell()) {
            m_currentKnownStructure.makeTop();
            Structure* structure = value.asCell()->structure();
            setFuturePossibleStructure(structure);
            m_arrayModes = asArrayModes(structure->indexingType());
            clobberArrayModes();
        } else {
            m_currentKnownStructure.clear();
            m_futurePossibleStructure.clear();
            m_arrayModes = 0;
        }

        m_type = speculationFromValue(value);
        m_value = value;

        checkConsistency();
    }

    void set(Structure* structure)
    {
        m_currentKnownStructure = structure;
        setFuturePossibleStructure(structure);
        m_arrayModes = asArrayModes(structure->indexingType());
        m_type = speculationFromStructure(structure);
        m_value = JSValue();

        checkConsistency();
    }

    void set(SpeculatedType type)
    {
        if (type & SpecCell) {
            m_currentKnownStructure.makeTop();
            m_futurePossibleStructure.makeTop();
            m_arrayModes = ALL_ARRAY_MODES;
        } else {
            m_currentKnownStructure.clear();
            m_futurePossibleStructure.clear();
            m_arrayModes = 0;
        }
        m_type = type;
        m_value = JSValue();
        checkConsistency();
    }

    bool operator==(const AbstractValue& other) const
    {
        return m_type == other.m_type
            && m_arrayModes == other.m_arrayModes
            && m_currentKnownStructure == other.m_currentKnownStructure
            && m_futurePossibleStructure == other.m_futurePossibleStructure
            && m_value == other.m_value;
    }
    bool operator!=(const AbstractValue& other) const
    {
        return !(*this == other);
    }

    bool merge(const AbstractValue& other)
    {
#if !ASSERT_DISABLED
        AbstractValue oldMe = *this;
#endif
        bool result = false;
        if (isClear()) {
            *this = other;
            result = !other.isClear();
        } else {
            result |= mergeSpeculation(m_type, other.m_type);
            result |= mergeArrayModes(m_arrayModes, other.m_arrayModes);
            result |= m_currentKnownStructure.addAll(other.m_currentKnownStructure);
            result |= m_futurePossibleStructure.addAll(other.m_futurePossibleStructure);
            if (m_value != other.m_value) {
                result |= !!m_value;
                m_value = JSValue();
            }
        }
        checkConsistency();
        ASSERT(result == (*this != oldMe));
        return result;
    }

    void merge(SpeculatedType type)
    {
        mergeSpeculation(m_type, type);

        if (type & SpecCell) {
            m_currentKnownStructure.makeTop();
            m_futurePossibleStructure.makeTop();
            m_arrayModes = ALL_ARRAY_MODES;
        }
        m_value = JSValue();

        checkConsistency();
    }

    void filter(const StructureSet& other)
    {
        m_type &= other.speculationFromStructures();
        m_arrayModes &= other.arrayModesFromStructures();
        m_currentKnownStructure.filter(other);
        if (m_currentKnownStructure.isClear())
            m_futurePossibleStructure.clear();
        else if (m_currentKnownStructure.hasSingleton())
            filterFuturePossibleStructure(m_currentKnownStructure.singleton());

        // It's possible that prior to the above two statements we had (Foo, TOP), where
        // Foo is a SpeculatedType that is disjoint with the passed StructureSet. In that
        // case, we will now have (None, [someStructure]). In general, we need to make
        // sure that new information gleaned from the SpeculatedType needs to be fed back
        // into the information gleaned from the StructureSet.
        m_currentKnownStructure.filter(m_type);
        m_futurePossibleStructure.filter(m_type);

        filterArrayModesByType();
        filterValueByType();

        checkConsistency();
    }

    void filterArrayModes(ArrayModes arrayModes)
    {
        ASSERT(arrayModes);

        m_type &= SpecCell;
        m_arrayModes &= arrayModes;

        // I could do more fancy filtering here. But it probably won't make any difference.

        checkConsistency();
    }

    void filter(SpeculatedType type)
    {
        if (type == SpecTop)
            return;
        m_type &= type;

        // It's possible that prior to this filter() call we had, say, (Final, TOP), and
        // the passed type is Array. At this point we'll have (None, TOP). The best way
        // to ensure that the structure filtering does the right thing is to filter on
        // the new type (None) rather than the one passed (Array).
        m_currentKnownStructure.filter(m_type);
        m_futurePossibleStructure.filter(m_type);

        filterArrayModesByType();
        filterValueByType();

        checkConsistency();
    }

    bool filterByValue(JSValue value)
    {
        if (!validate(value))
            return false;

        if (!!value && value.isCell())
            filter(StructureSet(value.asCell()->structure()));
        else
            filter(speculationFromValue(value));

        m_value = value;

        return true;
    }

    bool validateType(JSValue value) const
    {
        if (isTop())
            return true;

        if (mergeSpeculations(m_type, speculationFromValue(value)) != m_type)
            return false;

        if (value.isEmpty()) {
            ASSERT(m_type & SpecEmpty);
            return true;
        }

        return true;
    }

    bool validate(JSValue value) const
    {
        if (isTop())
            return true;

        if (!!m_value && m_value != value)
            return false;

        if (mergeSpeculations(m_type, speculationFromValue(value)) != m_type)
            return false;

        if (value.isEmpty()) {
            ASSERT(m_type & SpecEmpty);
            return true;
        }

        if (!!value && value.isCell()) {
            ASSERT(m_type & SpecCell);
            Structure* structure = value.asCell()->structure();
            return m_currentKnownStructure.contains(structure)
                && m_futurePossibleStructure.contains(structure)
                && (m_arrayModes & asArrayModes(structure->indexingType()));
        }

        return true;
    }

    Structure* bestProvenStructure() const
    {
        if (m_currentKnownStructure.hasSingleton())
            return m_currentKnownStructure.singleton();
        if (m_futurePossibleStructure.hasSingleton())
            return m_futurePossibleStructure.singleton();
        return 0;
    }

    void checkConsistency() const
    {
        if (!(m_type & SpecCell)) {
            ASSERT(m_currentKnownStructure.isClear());
            ASSERT(m_futurePossibleStructure.isClear());
            ASSERT(!m_arrayModes);
        }

        if (isClear())
            ASSERT(!m_value);

        if (!!m_value)
            ASSERT(mergeSpeculations(m_type, speculationFromValue(m_value)) == m_type);

        // Note that it's possible for a prediction like (Final, []). This really means that
        // the value is bottom and that any code that uses the value is unreachable. But
        // we don't want to get pedantic about this as it would only increase the computational
        // complexity of the code.
    }

    void dump(FILE* out) const
    {
        fprintf(out, "(%s, %s, ", speculationToString(m_type), arrayModesToString(m_arrayModes));
        m_currentKnownStructure.dump(out);
        dataLogF(", ");
        m_futurePossibleStructure.dump(out);
        if (!!m_value)
            fprintf(out, ", %s", m_value.description());
        fprintf(out, ")");
    }

    // A great way to think about the difference between m_currentKnownStructure and
    // m_futurePossibleStructure is to consider these four examples:
    //
    // 1) x = foo();
    //
    //    In this case x's m_currentKnownStructure and m_futurePossibleStructure will
    //    both be TOP, since we don't know anything about x for sure, yet.
    //
    // 2) x = foo();
    //    y = x.f;
    //
    //    Where x will later have a new property added to it, 'g'. Because of the
    //    known but not-yet-executed property addition, x's currently structure will
    //    not be watchpointable; hence we have no way of statically bounding the set
    //    of possible structures that x may have if a clobbering event happens. So,
    //    x's m_currentKnownStructure will be whatever structure we check to get
    //    property 'f', and m_futurePossibleStructure will be TOP.
    //
    // 3) x = foo();
    //    y = x.f;
    //
    //    Where x has a terminal structure that is still watchpointable. In this case,
    //    x's m_currentKnownStructure and m_futurePossibleStructure will both be
    //    whatever structure we checked for when getting 'f'.
    //
    // 4) x = foo();
    //    y = x.f;
    //    bar();
    //
    //    Where x has a terminal structure that is still watchpointable. In this
    //    case, m_currentKnownStructure will be TOP because bar() may potentially
    //    change x's structure and we have no way of proving otherwise, but
    //    x's m_futurePossibleStructure will be whatever structure we had checked
    //    when getting property 'f'.

    // This is a proven constraint on the structures that this value can have right
    // now. The structure of the current value must belong to this set. The set may
    // be TOP, indicating that it is the set of all possible structures, in which
    // case the current value can have any structure. The set may be BOTTOM (empty)
    // in which case this value cannot be a cell. This is all subject to change
    // anytime a new value is assigned to this one, anytime there is a control flow
    // merge, or most crucially, anytime a side-effect or structure check happens.
    // In case of a side-effect, we typically must assume that any value may have
    // had its structure changed, hence contravening our proof. We make the proof
    // valid again by switching this to TOP (i.e. claiming that we have proved that
    // this value may have any structure). Of note is that the proof represented by
    // this field is not subject to structure transition watchpoints - even if one
    // fires, we can be sure that this proof is still valid.
    StructureAbstractValue m_currentKnownStructure;

    // This is a proven constraint on the structures that this value can have now
    // or any time in the future subject to the structure transition watchpoints of
    // all members of this set not having fired. This set is impervious to side-
    // effects; even if one happens the side-effect can only cause the value to
    // change to at worst another structure that is also a member of this set. But,
    // the theorem being proved by this field is predicated upon there not being
    // any new structure transitions introduced into any members of this set. In
    // cases where there is no way for us to guard this happening, the set must be
    // TOP. But in cases where we can guard new structure transitions (all members
    // of the set have still-valid structure transition watchpoints) then this set
    // will be finite. Anytime that we make use of the finite nature of this set,
    // we must first issue a structure transition watchpoint, which will effectively
    // result in m_currentKnownStructure being filtered according to
    // m_futurePossibleStructure.
    StructureAbstractValue m_futurePossibleStructure;

    // This is a proven constraint on the possible types that this value can have
    // now or any time in the future, unless it is reassigned. This field is
    // impervious to side-effects unless the side-effect can reassign the value
    // (for example if we're talking about a captured variable). The relationship
    // between this field, and the structure fields above, is as follows. The
    // fields above constraint the structures that a cell may have, but they say
    // nothing about whether or not the value is known to be a cell. More formally,
    // the m_currentKnownStructure is itself an abstract value that consists of the
    // union of the set of all non-cell values and the set of cell values that have
    // the given structure. This abstract value is then the intersection of the
    // m_currentKnownStructure and the set of values whose type is m_type. So, for
    // example if m_type is SpecFinal|SpecInt32 and m_currentKnownStructure is
    // [0x12345] then this abstract value corresponds to the set of all integers
    // unified with the set of all objects with structure 0x12345.
    SpeculatedType m_type;

    // This is a proven constraint on the possible indexing types that this value
    // can have right now. It also implicitly constraints the set of structures
    // that the value may have right now, since a structure has an immutable
    // indexing type. This is subject to change upon reassignment, or any side
    // effect that makes non-obvious changes to the heap.
    ArrayModes m_arrayModes;

    // This is a proven constraint on the possible values that this value can
    // have now or any time in the future, unless it is reassigned. Note that this
    // implies nothing about the structure. Oddly, JSValue() (i.e. the empty value)
    // means either BOTTOM or TOP depending on the state of m_type: if m_type is
    // BOTTOM then JSValue() means BOTTOM; if m_type is not BOTTOM then JSValue()
    // means TOP.
    JSValue m_value;

private:
    void clobberArrayModes()
    {
        // FIXME: We could make this try to predict the set of array modes that this object
        // could have in the future. For now, just do the simple thing.
        m_arrayModes = ALL_ARRAY_MODES;
    }

    void setFuturePossibleStructure(Structure* structure)
    {
        if (structure->transitionWatchpointSetIsStillValid())
            m_futurePossibleStructure = structure;
        else
            m_futurePossibleStructure.makeTop();
    }

    void filterFuturePossibleStructure(Structure* structure)
    {
        if (structure->transitionWatchpointSetIsStillValid())
            m_futurePossibleStructure.filter(StructureAbstractValue(structure));
    }

    // We could go further, and ensure that if the futurePossibleStructure contravenes
    // the value, then we could clear both of those things. But that's unlikely to help
    // in any realistic scenario, so we don't do it. Simpler is better.
    void filterValueByType()
    {
        if (!!m_type) {
            // The type is still non-empty. This implies that regardless of what filtering
            // was done, we either didn't have a value to begin with, or that value is still
            // valid.
            ASSERT(!m_value || validateType(m_value));
            return;
        }

        // The type has been rendered empty. That means that the value must now be invalid,
        // as well.
        ASSERT(!m_value || !validateType(m_value));
        m_value = JSValue();
    }

    void filterArrayModesByType()
    {
        if (!(m_type & SpecCell))
            m_arrayModes = 0;
        else if (!(m_type & ~SpecArray))
            m_arrayModes &= ALL_ARRAY_ARRAY_MODES;
        else if (!(m_type & SpecArray))
            m_arrayModes &= ALL_NON_ARRAY_ARRAY_MODES;
    }
};

} } // namespace JSC::DFG

#endif // ENABLE(DFG_JIT)

#endif // DFGAbstractValue_h


text:
import ast
from unittest import TestCase
from bricklayer.doctor.ast_visitors import *

class AstVisitorsTest(TestCase):

    def test_it_gets_all_user_defined_functions(self):
        code = """
def my_function():
    print 'hello'
        """
        v = UserDefinedFunctionVisitor()
        v.visit(ast.parse(code))
        self.assertEqual(v.functions, ['my_function'])

    def test_it_gets_all_imports(self):
        code = """
from bricklayer.levels import level_1
import bricklayer.levels.level_2
        """
        v = ImportedModuleVisitor()
        v.visit(ast.parse(code))
        self.assertEqual(v.imports, [('level_1', 'bricklayer.levels'), ('bricklayer.levels.level_2', None)])

    def test_it_gets_all_called_functions(self):
        code = """
f('hello')
x(123)
        """
        v = CalledFunctionVisitor()
        v.visit(ast.parse(code))
        self.assertEqual(v.functions, ['f', 'x'])


text:
using System;
using System.ComponentModel;
using EnumsNET;
using SJP.Schematic.Core.Extensions;

namespace SJP.Schematic.Dot;

internal sealed class EdgeAttribute : IEquatable<EdgeAttribute>
{
    public EdgeAttribute(string attrName, string attrValue)
    {
        if (attrName.IsNullOrWhiteSpace())
            throw new ArgumentNullException(nameof(attrName));
        if (attrValue.IsNullOrWhiteSpace())
            throw new ArgumentNullException(nameof(attrValue));

        _attr = attrName.ToLowerInvariant() + "=" + attrValue.ToLowerInvariant();
        _hashCode = _attr.GetHashCode(StringComparison.Ordinal);
    }

    public override string ToString() => _attr;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public override int GetHashCode() => _hashCode;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public override bool Equals(object? obj)
    {
        if (obj == null)
            return false;
        if (ReferenceEquals(this, obj))
            return true;

        return obj is EdgeAttribute attr && Equals(attr);
    }

    public bool Equals(EdgeAttribute? other)
    {
        if (other == null)
            return false;
        if (ReferenceEquals(this, other))
            return true;

        return string.Equals(_attr, other.ToString(), StringComparison.Ordinal);
    }

    public static EdgeAttribute ArrowHead(ArrowStyleName arrowStyle)
    {
        if (!arrowStyle.IsValid())
            throw new ArgumentException($"The {nameof(ArrowStyleName)} provided must be a valid enum.", nameof(arrowStyle));

        var arrowStyleStr = arrowStyle.AsString().ToLowerInvariant();
        return new EdgeAttribute("arrowhead", arrowStyleStr);
    }

    public static EdgeAttribute ArrowTail(ArrowStyleName arrowStyle)
    {
        if (!arrowStyle.IsValid())
            throw new ArgumentException($"The {nameof(ArrowStyleName)} provided must be a valid enum.", nameof(arrowStyle));

        var arrowStyleStr = arrowStyle.AsString().ToLowerInvariant();
        return new EdgeAttribute("arrowtail", arrowStyleStr);
    }

    public static EdgeAttribute Direction(EdgeDirection direction)
    {
        if (!direction.IsValid())
            throw new ArgumentException($"The {nameof(EdgeDirection)} provided must be a valid enum.", nameof(direction));

        var directionStr = direction.AsString().ToLowerInvariant();
        return new EdgeAttribute("dir", directionStr);
    }

    private readonly string _attr;
    private readonly int _hashCode;
}


text:
package kikaha.urouting.unit.samples;

import kikaha.urouting.api.ContextProducer;
import io.undertow.server.HttpServerExchange;

import javax.enterprise.inject.Typed;
import javax.inject.Singleton;

@Singleton
@Typed( ContextProducer.class )
public class StringProducer implements ContextProducer<String> {

	public static final String HELLO_WORLD = "Hello World";

	@Override
	public String produce( HttpServerExchange exchange ) {
		return HELLO_WORLD;
	}
}


text:
module Cdx
  class User < ApplicationRecord
    include Cdx::Resourceable

    AVAILABLE_ROLES = Cdx.user_available_roles.freeze

    # Devise
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable

    # Assets
    has_one_attached :avatar, 'Asset::User::Avatar'

    # Settings
    store_accessor :settings, :theme

    # Validators
    validates :email, presence: true

    # Methods
    def content_header_title
      email_was
    end

    def avatar_url(style = :thumb)
      avatar&.attachment_file_name ? avatar.attachment.url(style) : gravatar_url
    end

    def gravatar_url
      "https://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(email.downcase)}"
    end

    def full_name
      "#{first_name} #{last_name}".strip
    end

    def has_role?(role)
      roles.include? role.to_s
    end

    Cdx.user_available_roles.each do |role|
      define_method("is_#{role}?") do
        has_role?(role)
      end
    end
  end
end


text:
cliconfig
=========

Urfave Cli flags setup from config struct fields

[![Build Status](https://travis-ci.org/miolini/cliconfig.svg?branch=master)](https://travis-ci.org/miolini/cliconfig)
[![GoDoc](https://godoc.org/github.com/miolini/cliconfig?status.svg)](https://godoc.org/github.com/miolini/cliconfig)
[![Go Report Card](https://goreportcard.com/badge/miolini/cliconfig)](https://goreportcard.com/report/miolini/cliconfig)

## Example

```go
package main

import (
  "log"
  "os"

  "github.com/miolini/cliconfig"
  "github.com/urfave/cli"
)

type Config struct {
  ListenAddr string `flag:"listen_addr_flag" env:"LISTEN_ADDR_ENV" default:"localhost:8080"`
}

func main() {
  config := Config{}
  app := cli.NewApp()
  app.Name = "example-app"
  app.Flags = cliconfig.Fill(&config, "EXAMPLE_APP_")
  app.Action = func(ctx *cli.Context) error {
    log.Printf("config: %#v", config)
    return nil
  }
  app.Run(os.Args)
}
```

Usage

```shell
$ ./simple  --help
command-line-arguments
NAME:
   example-app - A new cli application

USAGE:
   simple [global options] command [command options] [arguments...]

VERSION:
   0.0.0

COMMANDS:
     help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --listen_addr_flag value  (default: "localhost:8080") [$EXAMPLE_APP_LISTEN_ADDR_ENV]
   --help, -h                show help
   --version, -v             print the version
```


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

  <title>Index of /wp-content/themes/blocksy/static/js/frontend/lazy</title>

Index of /wp-content/themes/blocksy/static/js/frontend/lazy

 Parent Directory

 overlay.js

 overlay/


text:
<Record>
<Term>Penile Vascular Disorder</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Vascular Disorder</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Reproductive System Disorder/Male Reproductive System Disorder/Penile Disorder/Penile Vascular Disorder,/NCIThesaurus/Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Cardiovascular Disorder/Vascular Disorder/Penile Vascular Disorder</ClassificationPath>
<BroaderTerm>Male Reproductive System Disorder</BroaderTerm>
<BroaderTerm>Penile Vascular Disorder</BroaderTerm>
<BroaderTerm>Vascular Disorder</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Penile Disorder</BroaderTerm>
<BroaderTerm>Penile Vascular Disorder,</BroaderTerm>
<BroaderTerm>Reproductive System Disorder</BroaderTerm>
<BroaderTerm>Cardiovascular Disorder</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<Synonym>Penile Vascular Disorder</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
Experimenting with a react, redux, and typescript app wrapped by electron. Simple image editor.

## P1 Features
 - File or open button to launch explorer/finder
 - Filters:
    - scatter
    - edge detection
    - green screen effect
 - Ability to save filtered image through the ui or `CTRL+S` for windows and `CMD+s` for mac
 - Debug tool to compare the pixels between two images

 ## P2 Features
 - Edit
    - Undo UI plus: `CTRL+Z` for windows and `CMD+Z` for mac
    - Redo UI plus: `CTRL+R` for windows and `CMD+R` for mac
- Drag and drop image loader
- Sticker effect

## Up and running:
* Install deps: `npm install`
* Run hot-server: `npm run dev`
* Test: `npm run test`
* Test-e2e: `npm run test-e2e`
* Test-watcher: `npm run test-watch`


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>net.taejo</groupId>
        <artifactId>taejo</artifactId>
        <version>${revision}</version>
    </parent>

    <artifactId>taejo-core</artifactId>
    <packaging>jar</packaging>

    <name>Taejo - Core</name>
    <description>Main code for the bot.</description>

    <dependencies>
        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-integration</artifactId>
        </dependency>

        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-version</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-hearthstone</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-password</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-random</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>net.taejo</groupId>
            <artifactId>taejo-info</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-servicebus</artifactId>
            <version>0.9.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>prepare-dockerfile</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>docker</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>


text:
package editor;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JPanel;

import NodoImagen.NodoImg;
import NodoObjects.NodoObj;

public class Editor extends JPanel implements KeyListener, MouseListener, MouseMotionListener{

	private Graphics dbg;
	private Image dbImage = null;
	public int tiles[][]=new int[20][13];
	int w,h,tS;
	boolean bigChunk;
	int currentTileX, currentTileY;
	int anchorX, anchorY;
	int imgIndex;
	boolean playerSpawn, itemSpawn, orbSpawn;
	ArrayList<NodoImg> imagenes;
    ArrayList<NodoObj>  jugadores;
    ArrayList<NodoObj>  items;
                 NodoObj orb;
	String path;

	private static final long serialVersionUID = 1L;

	public Editor(int width, int height, int tileSize, File file){
		path = file.getAbsolutePath();
		this.h = height;
		this.w = width;
		this.tS = tileSize;
		tiles=new int[w][h];
		currentTileX = 0;
		currentTileY = 0;
		imgIndex = 0;
		imagenes = new ImagesLoader().getImagesFromDir(file);
		jugadores = new ArrayList<NodoObj>(4);
        items = new ArrayList<NodoObj>();

		for(int x=0;x<tiles.length;x++){
			for(int y=0;y<tiles[0].length;y++){
				tiles[x][y]=-1;
			}
		}

	}

	public void paint(Graphics g) {
  		update(g);
 	}

 	public void update (Graphics g){

 		dbImage = createImage(getWidth(), getHeight());
		 dbg=dbImage.getGraphics();
		 dbg.setColor(Color.black);
		 dbg.fillRect(0, 0, getWidth(), getHeight());
		 dbg.setColor(Color.GREEN);

			for(int x=0;x<tiles.length;x++){
				for(int y=0;y<tiles[0].length;y++){
					if(tiles[x][y]!=-1)
						 dbg.drawImage(imagenes.get(tiles[x][y]).getImage(),x*tS,y*tS,tS,tS, null);
				}
			}

		 for(int x=0;x<tiles.length;x++){
				for(int y=0;y<tiles[0].length+1;y++){
					dbg.drawLine(x*tS, y*tS, w*tS, y*tS);
					dbg.drawLine(x*tS, y*tS, x*tS, h*tS);
				}
		}

         dbg.setColor(Color.cyan);
         for(NodoObj nob : jugadores)                        {
             dbg.drawRect(nob.x*tS, nob.y*tS, tS, tS);
             dbg.drawLine(nob.x*tS, nob.y*tS, nob.x*tS+tS,nob.y*tS+ tS);
         }

        dbg.setColor(Color.yellow);
        for(NodoObj nob : items)                        {
            dbg.drawRect(nob.x*tS, nob.y*tS, tS, tS);
            dbg.drawLine(nob.x*tS, nob.y*tS, nob.x*tS+tS,nob.y*tS+ tS);
        }
        dbg.setColor(Color.magenta);
        if(orb!= null)                        {
            dbg.drawRect(orb.x*tS, orb.y*tS, tS, tS);
            dbg.drawLine(orb.x*tS, orb.y*tS, orb.x*tS+tS,orb.y*tS+ tS);
        }

		 dbg.setColor(Color.RED);
		 if(!bigChunk){
			dbg.drawRect(currentTileX*tS, currentTileY*tS, tS, tS);
		 }else{
			dbg.drawRect(anchorX*tS,anchorY*tS,currentTileX*tS, currentTileY*tS);
		 }

		 if(imagenes.size()>0){
			 for (int x =0; x < imagenes.size(); x++)
				 dbg.drawImage(imagenes.get(x).getImage(),x*tS, (tiles[0].length+1)*tS,tS,tS, null);
		 }

			dbg.drawRect(imgIndex*tS,  (tiles[0].length+1)*tS, tS, tS);

            dbg.setColor(Color.cyan);

        if(playerSpawn)
		    dbg.drawString("PlayerSpawn Mode", tS,(tiles[0].length+1)*tS+tS*2);

        if(itemSpawn)
            dbg.drawString("ItemSpawn Mode", tS,(tiles[0].length+1)*tS+tS*2);

        if(orbSpawn)
            dbg.drawString("OrbSpawn Mode", tS,(tiles[0].length+1)*tS+tS*2);

		 g.drawImage(dbImage, 0, 0, null);
		 repaint();

 	}

	@Override
	public void keyPressed(KeyEvent arg0) {

		if(arg0.getKeyChar()=='w'){
			if(currentTileY>0)
				currentTileY -=1;
		}

		if(arg0.getKeyChar()=='a'){
			if(currentTileX>0)
				currentTileX -=1;
		}

		if(arg0.getKeyChar()=='s'){
			if(currentTileY<tiles[0].length-1)
				currentTileY +=1;
		}

		if(arg0.getKeyChar()=='d'){
			if(currentTileX<tiles.length-1)
				currentTileX +=1;
		}

		if(arg0.getKeyChar()==' '){
			bigChunk = true;
			anchorX = currentTileX;
			anchorY = currentTileY;
		}

        //spawn locations
        if(arg0.getKeyCode()==KeyEvent.VK_I){
            itemSpawn = itemSpawn ? false : true;
            orbSpawn = playerSpawn = false;
        }

        if(arg0.getKeyCode()==KeyEvent.VK_O){
            orbSpawn = orbSpawn ? false : true;
            itemSpawn = playerSpawn = false;
        }

        if(arg0.getKeyCode()==KeyEvent.VK_P){
            playerSpawn = playerSpawn ? false : true;
            itemSpawn = orbSpawn = false;
        }

		if(arg0.getKeyCode()==40){
            setItem(currentTileX, currentTileY,imgIndex );
        }

		if(arg0.getKeyCode()==38){
            removeItem(currentTileX,currentTileY);
		}

		if(arg0.getKeyCode()==KeyEvent.VK_LEFT){
			if(imgIndex>0)
				imgIndex--;
		}

		if(arg0.getKeyCode()==KeyEvent.VK_RIGHT){
			if(imgIndex<imagenes.size()-1)
				imgIndex++;
		}

		if(arg0.getKeyCode()==KeyEvent.VK_ENTER){
            if(orb!=null&& jugadores.size()>0&&items.size()>0)
		    	new JsonExport().writeFile(tiles, imagenes,jugadores,items,orb, path);
            else
                System.out.println("you must place items, players and the orb.");
		}

	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		if(arg0.getKeyChar()==' '){
			bigChunk = false;
			anchorX = currentTileX;
			anchorY = currentTileY;
		}
	}

	@Override
	public void keyTyped(KeyEvent arg0) {

	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
       if (arg0.getButton()== MouseEvent.BUTTON1){
           setItem(currentTileX, currentTileY,imgIndex );
       }

        if (arg0.getButton()== MouseEvent.BUTTON3||arg0.getButton()== MouseEvent.BUTTON2){
            removeItem(currentTileX,currentTileY);
        }
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {

	}

	@Override
	public void mouseExited(MouseEvent arg0) {

	}

	@Override
	public void mousePressed(MouseEvent arg0) {

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {

	}

    @Override
    public void mouseDragged(MouseEvent e) {
    }

    @Override
    public void mouseMoved(MouseEvent e) {

        currentTileX = e.getX()/tS;
        currentTileY = (e.getY()-tS)/tS;

        if(currentTileX<0)
            currentTileX = 0;

        if(currentTileY<0)
            currentTileX = 0;

        if(currentTileY>tiles[0].length-1)
            currentTileY = tiles[0].length-1;

        if(currentTileX>tiles.length-1)
            currentTileX  = tiles.length-1;

    }

    void setItem(int currentTileX, int currentTileY, int imgIndex){
        if(playerSpawn)  {
            boolean exist =false;
            for(NodoObj nob : jugadores) {
                    if(nob.x==currentTileX&&nob.y==currentTileY)
                        exist = true;
            }
            if(!exist){
                if(jugadores.size()<4)
                  jugadores.add(new NodoObj(currentTileX,currentTileY));
            }
            return;
        }
        if(itemSpawn){
            boolean exist =false;
            for(NodoObj nob : items) {
                if(nob.x==currentTileX&&nob.y==currentTileY)
                    exist = true;
            }
            if(!exist){
                items.add(new NodoObj(currentTileX,currentTileY));
            }
            return;
        }
        if(orbSpawn){
            orb = new NodoObj(currentTileX,currentTileY);
              return;
        }
        tiles[currentTileX][currentTileY]=imgIndex;
    }

    void removeItem(int currentTileX, int currentTileY)
    {
        if(playerSpawn)  {
            for(NodoObj nob : jugadores) {
                if(nob.x==currentTileX&&nob.y==currentTileY)       {
                   jugadores.remove(nob);
                    break;                                          }
            }

            return;
        }
        if(itemSpawn){
            for(NodoObj nob : items) {
                if(nob.x==currentTileX&&nob.y==currentTileY)    {
                   items.remove(nob);
                    break;
                }
            }

            return;
        }
        if(orbSpawn){
                 orb = null;
            return;
        }
             tiles[currentTileX][currentTileY]=-1;
    }
}


text:
<?php

/* @var $this yii\web\View */

use yii\materialicons\MD;

$this->title = 'My Yii Application';
?>

The Tip App

What do you wish someone told you when you were learning to code???

Leave a tip!


text:
package gzip

import (
	"compress/gzip"
	"io"
)

const (
	NoCompression      = gzip.NoCompression
	BestSpeed          = gzip.BestSpeed
	BestCompression    = gzip.BestCompression
	DefaultCompression = gzip.DefaultCompression
)

type Writer gzip.Writer

func NewWriterLevel(w io.Writer, level int) (*Writer, error) {
	z, err := gzip.NewWriterLevel(w, level)
	return (*Writer)(z), err
}

func (z *Writer) Reset(w io.Writer) {
	(*gzip.Writer)(z).Reset(w)
}

func (z *Writer) Write(p []byte) (int, error) {
	return (*gzip.Writer)(z).Write(p)
}

func (z *Writer) Close() error {
	return (*gzip.Writer)(z).Close()
}


text:
package testsuite.regression;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;

import com.mysql.jdbc.PacketTooBigException;
import com.mysql.jdbc.jdbc2.optional.ConnectionWrapper;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;

import testsuite.BaseTestCase;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * Tests a PooledConnection implementation provided by a JDBC driver. Test case provided by Johnny Macchione from bug database record BUG#884. According to
 * the JDBC 2.0 specification:
 *
 *

 * "Each call to PooledConnection.getConnection() must return a newly constructed Connection object that exhibits the default Connection behavior. Only the most
 * recent Connection object produced from a particular PooledConnection is open. An existing Connection object is automatically closed, if the getConnection()
 * method of its associated Pooled-Connection is called again, before it has been explicitly closed by the application. This gives the application server a way
 * to �take away� a Connection from the application if it wishes, and give it out to someone else. This capability will not likely be used frequently in
 * practice."
 *

 *
 *

 * "When the application calls Connection.close(), an event is triggered that tells the connection pool it can recycle the physical database connection. In
 * other words, the event signals the connection pool that the PooledConnection object which originally produced the Connection object generating the event can
 * be put back in the connection pool."
 *

 *
 *

 * "A Connection-EventListener will also be notified when a fatal error occurs, so that it can make a note not to put a bad PooledConnection object back in the
 * cache when the application finishes using it. When an error occurs, the ConnectionEventListener is notified by the JDBC driver, just before the driver throws
 * an SQLException to the application to notify it of the same error. Note that automatic closing of a Connection object as discussed in the previous section
 * does not generate a connection close event."
 *

 * The JDBC 3.0 specification states the same in other words:
 *
 *

 * "The Connection.close method closes the logical handle, but the physical connection is maintained. The connection pool manager is notified that the
 * underlying PooledConnection object is now available for reuse. If the application attempts to reuse the logical handle, the Connection implementation throws
 * an SQLException."
 *

 *
 *

 * "For a given PooledConnection object, only the most recently produced logical Connection object will be valid. Any previously existing Connection object is
 * automatically closed when the associated PooledConnection.getConnection method is called. Listeners (connection pool managers) are not notified in this case.
 * This gives the application server a way to take a connection away from a client. This is an unlikely scenario but may be useful if the application server is
 * trying to force an orderly shutdown."
 *

 *
 *

 * "A connection pool manager shuts down a physical connection by calling the method PooledConnection.close. This method is typically called only in certain
 * circumstances: when the application server is undergoing an orderly shutdown, when the connection cache is being reinitialized, or when the application
 * server receives an event indicating that an unrecoverable error has occurred on the connection."
 *

 * Even though the specification isn't clear about it, I think it is no use
 * generating a close event when calling the method PooledConnection.close(),
 * even if a logical Connection is open for this PooledConnection, bc the
 * PooledConnection will obviously not be returned to the pool.
 */
public final class PooledConnectionRegressionTest extends BaseTestCase {
    private ConnectionPoolDataSource cpds;

    // Count nb of closeEvent.
    protected int closeEventCount;

    // Count nb of connectionErrorEvent
    protected int connectionErrorEventCount;

    /**
     * Creates a new instance of ProgressPooledConnectionTest
     *
     * @param testname
     */
    public PooledConnectionRegressionTest(String testname) {
        super(testname);
    }

    /**
     * Set up test case before a test is run.
     *
     * @throws Exception
     */
    @Override
    public void setUp() throws Exception {
        super.setUp();

        // Reset event count.
        this.closeEventCount = 0;
        this.connectionErrorEventCount = 0;

        MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();

        ds.setURL(BaseTestCase.dbUrl);

        this.cpds = ds;
    }

    /**
     * Runs all test cases in this test suite
     *
     * @param args
     */
    public static void main(String[] args) {
        junit.textui.TestRunner.run(PooledConnectionRegressionTest.class);
    }

    /**
     * @return a test suite composed of this test case.
     */
    public static Test suite() {
        TestSuite suite = new TestSuite(PooledConnectionRegressionTest.class);

        return suite;
    }

    /**
     * After the test is run.
     */
    @Override
    public void tearDown() throws Exception {
        this.cpds = null;
        super.tearDown();
    }

    /**
     * Tests fix for BUG#7136 ... Statement.getConnection() returning physical
     * connection instead of logical connection.
     */
    public void testBug7136() {
        final ConnectionEventListener conListener = new ConnectionListener();
        PooledConnection pc = null;
        this.closeEventCount = 0;

        try {
            pc = this.cpds.getPooledConnection();

            pc.addConnectionEventListener(conListener);

            Connection _conn = pc.getConnection();

            Connection connFromStatement = _conn.createStatement().getConnection();

            // This should generate a close event.

            connFromStatement.close();

            assertEquals("One close event should've been registered", 1, this.closeEventCount);

            this.closeEventCount = 0;

            _conn = pc.getConnection();

            Connection connFromPreparedStatement = _conn.prepareStatement("SELECT 1").getConnection();

            // This should generate a close event.

            connFromPreparedStatement.close();

            assertEquals("One close event should've been registered", 1, this.closeEventCount);

        } catch (SQLException ex) {
            fail(ex.toString());
        } finally {
            if (pc != null) {
                try {
                    pc.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * Test the nb of closeEvents generated when a Connection is reclaimed. No
     * event should be generated in that case.
     */
    public void testConnectionReclaim() {
        final ConnectionEventListener conListener = new ConnectionListener();
        PooledConnection pc = null;
        final int NB_TESTS = 5;

        try {
            pc = this.cpds.getPooledConnection();

            pc.addConnectionEventListener(conListener);

            for (int i = 0; i < NB_TESTS; i++) {
                Connection _conn = pc.getConnection();

                try {
                    // Try to reclaim connection.
                    System.out.println("Before connection reclaim.");

                    _conn = pc.getConnection();

                    System.out.println("After connection reclaim.");
                } finally {
                    if (_conn != null) {
                        System.out.println("Before connection.close().");

                        // This should generate a close event.
                        _conn.close();

                        System.out.println("After connection.close().");
                    }
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            fail(ex.toString());
        } finally {
            if (pc != null) {
                try {
                    System.out.println("Before pooledConnection.close().");

                    // This should not generate a close event.
                    pc.close();

                    System.out.println("After pooledConnection.close().");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    fail(ex.toString());
                }
            }
        }

        assertEquals("Wrong nb of CloseEvents: ", NB_TESTS, this.closeEventCount);
    }

    /**
     * Tests that PacketTooLargeException doesn't clober the connection.
     *
     * @throws Exception
     *             if the test fails.
     */
    public void testPacketTooLargeException() throws Exception {
        final ConnectionEventListener conListener = new ConnectionListener();
        PooledConnection pc = null;

        pc = this.cpds.getPooledConnection();

        pc.addConnectionEventListener(conListener);

        createTable("testPacketTooLarge", "(field1 LONGBLOB)");

        Connection connFromPool = pc.getConnection();
        PreparedStatement pstmtFromPool = ((ConnectionWrapper) connFromPool).clientPrepare("INSERT INTO testPacketTooLarge VALUES (?)");

        this.rs = this.stmt.executeQuery("SHOW VARIABLES LIKE 'max_allowed_packet'");
        this.rs.next();

        int maxAllowedPacket = this.rs.getInt(2);

        int numChars = (int) (maxAllowedPacket * 1.2);

        pstmtFromPool.setBinaryStream(1, new BufferedInputStream(new FileInputStream(newTempBinaryFile("testPacketTooLargeException", numChars))), numChars);

        try {
            pstmtFromPool.executeUpdate();
            fail("Expecting PacketTooLargeException");
        } catch (PacketTooBigException ptbe) {
            // We're expecting this one...
        }

        // This should still work okay, even though the last query on the same connection didn't...
        this.rs = connFromPool.createStatement().executeQuery("SELECT 1");

        assertTrue(this.connectionErrorEventCount == 0);
        assertTrue(this.closeEventCount == 0);
    }

    /**
     * Test the nb of closeEvents generated by a PooledConnection. A
     * JDBC-compliant driver should only generate 1 closeEvent each time
     * connection.close() is called.
     */
    public void testCloseEvent() {
        final ConnectionEventListener conListener = new ConnectionListener();
        PooledConnection pc = null;
        final int NB_TESTS = 5;

        try {
            pc = this.cpds.getPooledConnection();

            pc.addConnectionEventListener(conListener);

            for (int i = 0; i < NB_TESTS; i++) {
                Connection pConn = pc.getConnection();

                System.out.println("Before connection.close().");

                // This should generate a close event.
                pConn.close();

                System.out.println("After connection.close().");
            }
        } catch (SQLException ex) {
            fail(ex.toString());
        } finally {
            if (pc != null) {
                try {
                    System.out.println("Before pooledConnection.close().");

                    // This should not generate a close event.
                    pc.close();

                    System.out.println("After pooledConnection.close().");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        assertEquals("Wrong nb of CloseEvents: ", NB_TESTS, this.closeEventCount);
    }

    /**
     * Listener for PooledConnection events.
     */
    protected final class ConnectionListener implements ConnectionEventListener {
        /** */
        public void connectionClosed(ConnectionEvent event) {
            PooledConnectionRegressionTest.this.closeEventCount++;
            System.out.println(PooledConnectionRegressionTest.this.closeEventCount + " - Connection closed.");
        }

        /** */
        public void connectionErrorOccurred(ConnectionEvent event) {
            PooledConnectionRegressionTest.this.connectionErrorEventCount++;
            System.out.println("Connection error: " + event.getSQLException());
        }
    }

    /**
     * Tests fix for BUG#35489 - Prepared statements from pooled connections
     * cause NPE when closed() under JDBC4
     *
     * @throws Exception
     *             if the test fails
     */
    public void testBug35489() throws Exception {
        MysqlConnectionPoolDataSource pds = new MysqlConnectionPoolDataSource();
        pds.setUrl(dbUrl);
        this.pstmt = pds.getPooledConnection().getConnection().prepareStatement("SELECT 1");
        this.pstmt.execute();
        this.pstmt.close();

        MysqlXADataSource xads = new MysqlXADataSource();
        xads.setUrl(dbUrl);
        this.pstmt = xads.getXAConnection().getConnection().prepareStatement("SELECT 1");
        this.pstmt.execute();
        this.pstmt.close();

        xads = new MysqlXADataSource();
        xads.setUrl(dbUrl);
        xads.setPinGlobalTxToPhysicalConnection(true);
        this.pstmt = xads.getXAConnection().getConnection().prepareStatement("SELECT 1");
        this.pstmt.execute();
        this.pstmt.close();
    }
}


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="8dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/messageUserAvatar"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"/>

    <!--this view is needed for custom holder-->

    <ImageView
        android:id="@+id/onlineIndicator"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_alignEnd="@+id/messageUserAvatar"
        android:layout_alignRight="@+id/messageUserAvatar"
        android:layout_alignTop="@+id/messageUserAvatar"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"/>

    <com.github.siyamed.shapeimageview.mask.PorterShapeImageView
        android:id="@+id/image"
        android:layout_width="280dp"
        android:layout_height="280dp"
        android:layout_marginEnd="@dimen/message_incoming_bubble_margin_right"
        android:layout_marginRight="@dimen/message_incoming_bubble_margin_right"
        android:layout_toEndOf="@+id/messageUserAvatar"
        android:layout_toRightOf="@+id/messageUserAvatar"
        android:adjustViewBounds="true"
        app:siShape="@drawable/bg_custom_incoming_message"
        app:siSquare="false"/>

    <TextView
        android:id="@+id/messageTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/image"
        android:layout_alignRight="@+id/image"
        android:layout_below="@+id/image"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"/>

</RelativeLayout>