text:
<!DOCTYPE html>

<title>集市宝</title>
<?php $this->load->view('common/cmdsource');?>

				<form action="<?php echo site_url('home/search')?>" method="post">
					<input type="text" name="name" id="name" class="search-input" placeholder="输入商品名称">

					<input type="submit" class="search-button" value="" />
				</form>

			<a class="button-left" href="<?php echo site_url('home/index')?>" style="padding:7px 6px 0 6px;">
			<a class="button-right button-right-title" href="<?php echo site_url('user/index')?>">个人中心

			<?php $this->load->view('common/menu'); ?>

				<?php foreach ($products as $item):?>

							<img id="img_product"
					src="http://7xj0kd.com2.z0.glb.qiniucdn.com/<?php echo $item['image'];?>?imageView2/2/w/60/interlace/1" />

<?php echo $item['name'];?>

							 <?php echo $item['price'];?> 元/<?php echo $item['unit'];?>

							<?php echo $item['description'];?>

							仅剩 <?php echo $item['stock'];?> <?php echo $item['unit'];?>

							<button class="sub"></button><input type="tel" value="<?php echo $item['amount'];?>" class="num<?php echo $item['id'];?>" onclick="this.select()"><button class="plus"></button>

							<button class="button button-blank-warm button-sm add" data-id='<?php echo $item['id'];?>'> 购买</button>

				<?php endforeach;?>

				<input type="hidden" name="sale" id="sale" value="1">

				总计 <?php echo $total;?>  元

				<a href="<?php echo site_url('shoppingcart/index')?>" class="button button-warm button-md">去购物车结算

	<?php //$this->load->view('common/sidebar'); ?>


text:
#pragma once

struct KeyEvent
{
    bool isPressed;
    char c;
};

class IPhone
{
public: // constructor / destructor
    virtual ~IPhone() {}

public: // methods
    virtual void init() = 0;

    /* TODO: startListening is not a good name:
       are we listening to events? keys? ... */

    virtual void startListening() = 0;
    virtual void stopListening() = 0;

    virtual KeyEvent readKey() = 0;
};

redpajama_set_name: RedPajamaGithub


text:
package com.socialthingy.plusf.z80.operations;

import com.socialthingy.plusf.z80.*;

public class OpAndAHlIndirect extends AndOperation {
    private final Register hlReg;
    private final Memory memory;

    public OpAndAHlIndirect(final Processor processor, final Memory memory) {
        super(processor);
        this.hlReg = processor.register("hl");
        this.memory = memory;
    }

    @Override
    public void execute(ContentionModel contentionModel, int initialPcValue, int irValue) {
        final int address = hlReg.get();
        contentionModel.applyContention(initialPcValue, 4);
        contentionModel.applyContention(address, 3);
        and(memory.get(address));
    }

    @Override
    public String toString() {
        return "and (hl)";
    }
}


text:
@interface YFShowPictureViewController ()
@property (weak, nonatomic) IBOutlet YFProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIScrollView *ScrollView;

@end

@implementation YFShowPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc]init];

    [self.ScrollView addSubview:imageView];

    [imageView sd_setImageWithURL:[NSURL URLWithString:self.topic.image2] placeholderImage:nil options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        CGFloat progress = receivedSize *1.0 / expectedSize;

        [self.progressView setProgress:progress animated:NO];

    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        self.progressView.hidden = YES;

        CGFloat w = YFScreenW;

        CGFloat h = YFScreenW * image.size.height / image.size.width;
        imageView.size = CGSizeMake(w, h);
        if(h <= YFScreenH){

            imageView.center = CGPointMake(YFScreenW * 0.5, YFScreenH * 0.5);
            self.ScrollView.contentSize = CGSizeZero;
        }else
        {
            imageView.frame = CGRectMake(0, 0, w, h);
            self.ScrollView.contentSize = CGSizeMake(0, h);
        }

    }];

    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back:)]];

}
- (IBAction)back:(id)sender {

    [self dismissViewControllerAnimated:NO completion:nil];
}
- (IBAction)save:(id)sender {
    YFLogFunc;
}
- (IBAction)repost:(id)sender {

    YFLogFunc;
}

@end


text:
package ro.pub.cs.aipi.lab08.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.pub.cs.aipi.lab08.dataaccess.DataBaseException;
import ro.pub.cs.aipi.lab08.dataaccess.DataBaseWrapper;
import ro.pub.cs.aipi.lab08.dataaccess.DataBaseWrapperImplementation;
import ro.pub.cs.aipi.lab08.entities.Record;
import ro.pub.cs.aipi.lab08.general.Constants;
import ro.pub.cs.aipi.lab08.general.Utilities;

public class ClientServlet extends HttpServlet {

    final public static long serialVersionUID = 10021002L;

    private DataBaseWrapper dataBaseWrapper;

    private String selectedTable, selectedCollection, selectedDomain;
    private String userDisplayName;

    private ArrayList<Record> shoppingCart;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        dataBaseWrapper = DataBaseWrapperImplementation.getInstance();
        selectedTable = Constants.BOOKS_TABLE;
        selectedCollection = Constants.ALL;
        selectedDomain = Constants.ALL;
    }

    @Override
    public void destroy() {
        dataBaseWrapper.releaseResources();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
		if (session == null || session.getAttribute(Constants.IDENTIFIER) == null)
			return;
		userDisplayName = session.getAttribute(Constants.IDENTIFIER).toString();
		shoppingCart = (ArrayList<Record>) session.getAttribute(Utilities.removeSpaces(Constants.SHOPPING_CART.toLowerCase()));
		if (shoppingCart == null)
			shoppingCart = new ArrayList<>();
		RequestDispatcher requestDispatcher = null;
		String errorMessage = "";
		Enumeration<String> parameters = request.getParameterNames();
		while (parameters.hasMoreElements()) {
			String parameter = (String) parameters.nextElement();
			if (parameter.equals(Constants.SELECTED_COLLECTION))
				selectedCollection = request.getParameter(parameter);
			if (parameter.equals(Constants.SELECTED_DOMAIN))
                selectedDomain = request.getParameter(parameter);

			// TO DO (exercitiul 8): stabileste continut cos de cumparaturi
            if (parameter.contains(Constants.COPIES.toLowerCase()) && request.getParameter(parameter) != null && !request.getParameter(parameter).isEmpty()) {
                String book_id = parameter.substring(parameter.indexOf("_") + 1);
                String quantity = request.getParameter(parameter);
                ArrayList<String> attributes = new ArrayList<>();
                attributes.add(Constants.STOCK);
                int stock = 0;
                try {
                    stock = Integer.parseInt(dataBaseWrapper.getTableContent(selectedTable, attributes, dataBaseWrapper.getTablePrimaryKey(selectedTable) + "=\'" + book_id + "\'", null, null).get(0).get(0));
                } catch (SQLException sqlException) {
                    System.out.println("An exception has occurred: " + sqlException.getMessage());
                    if (Constants.DEBUG) {
                        sqlException.printStackTrace();
                    }
                }
                boolean found = false;
                for (Record shoppingCartContent : shoppingCart) {
                    if (shoppingCartContent.getAttribute().equals(book_id)) {
                        if (Integer.parseInt(quantity) != 0) {
                            if (Integer.parseInt(quantity) <= stock) {
                                shoppingCartContent.setValue(quantity);
                            } else {
                                errorMessage += "" + Constants.INVALID_COMMAND_ERROR1 + book_id + Constants.INVALID_COMMAND_ERROR2 + "";
                            }
                        } else {
                            shoppingCart.remove(shoppingCartContent);
                        }
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    if (Integer.parseInt(quantity) <= stock) {
                        shoppingCart.add(new Record(book_id, quantity));
                    } else {
                        errorMessage += "" + Constants.INVALID_COMMAND_ERROR1 + book_id + Constants.INVALID_COMMAND_ERROR2 + "";
                    }
                }
            }
            // TO DO (exercitiul 10): finalizare comanda -> continut cos de cumparaturi = {}, inregistrare comanda in baza de date, actualizare stocuri
            if (parameter.equals(Utilities.removeSpaces(Constants.CANCEL_COMMAND.toLowerCase()) + ".x")) {
                shoppingCart = new ArrayList<>();
            }
            if (parameter.equals(Utilities.removeSpaces(Constants.COMPLETE_COMMAND.toLowerCase()) + ".x")) {
                ArrayList<String> attributes;
                try {
                    ArrayList<String> insertValues = new ArrayList<>();
                    int invoice_id = dataBaseWrapper.getTablePrimaryKeyMaximumValue(Constants.INVOICE_TABLE) + 1;
                    insertValues.add(invoice_id + "");
                    insertValues.add(Utilities.generateInvoiceNumber());
                    insertValues.add("CURDATE()");
                    insertValues.add(Constants.STATE_ISSUED);
                    attributes = new ArrayList<>();
                    attributes.add(Constants.USER_PERSONAL_IDENTIFIER);
                    insertValues.add(dataBaseWrapper.getTableContent(Constants.USERS_TABLE, attributes, "CONCAT(first_name, ' ', last_name)=\'" + userDisplayName + "\'", null, null).get(0).get(0));
                    dataBaseWrapper.insertValuesIntoTable(Constants.INVOICE_TABLE, null, insertValues, false);
                    for (Record shoppingCartContent : shoppingCart) {
                        String book_id = shoppingCartContent.getAttribute();
                        String quantity = shoppingCartContent.getValue();
                        attributes = new ArrayList<>();
                        attributes.add(Constants.STOCK);
                        int stock = 0;
                        try {
                            stock = Integer.parseInt(dataBaseWrapper.getTableContent(selectedTable, attributes, dataBaseWrapper.getTablePrimaryKey(selectedTable) + "=\'" + book_id + "\'", null, null).get(0).get(0));
                        } catch (SQLException sqlException) {
                            System.out.println("An exception has occurred: " + sqlException.getMessage());
                            if (Constants.DEBUG) {
                                sqlException.printStackTrace();
                            }
                        }
                        if (Integer.parseInt(quantity) <= stock) {
                            ArrayList<String> updateAttributes = new ArrayList<>();
                            updateAttributes.add(Constants.STOCK);
                            ArrayList<String> updateValues = new ArrayList<>();
                            updateValues.add(stock - Integer.parseInt(quantity) + "");
                            dataBaseWrapper.updateRecordsIntoTable(selectedTable, updateAttributes, updateValues, dataBaseWrapper.getTablePrimaryKey(selectedTable) + "=\'" + book_id + "\'");
                            insertValues = new ArrayList<>();
                            insertValues.add(invoice_id + "");
                            insertValues.add(book_id);
                            insertValues.add(quantity);
                            dataBaseWrapper.insertValuesIntoTable(Constants.INVOICE_DETAIL_TABLE, null, insertValues, true);
                        } else {
                            errorMessage += "" + Constants.INVALID_COMMAND_ERROR1 + book_id + Constants.INVALID_COMMAND_ERROR2 + "
";
                        }
                    }
                } catch (SQLException | DataBaseException exception) {
                    System.out.println("An exception has occurred: " + exception.getMessage());
                    if (Constants.DEBUG) {
                        exception.printStackTrace();
                    }
                }
                shoppingCart = new ArrayList<>();
            }
            session.setAttribute(Utilities.removeSpaces(Constants.SHOPPING_CART.toLowerCase()), shoppingCart);
            if (parameter.equals(Constants.SIGNOUT.toLowerCase() + ".x")) {
                Enumeration<String> requestParameters = request.getParameterNames();
                while (requestParameters.hasMoreElements()) {
                    request.removeAttribute(requestParameters.nextElement());
                }
                requestDispatcher = getServletContext().getRequestDispatcher("/login.jsp");
                if (requestDispatcher != null) {
                    requestDispatcher.forward(request, response);
                }
                session.invalidate();
                selectedTable = Constants.BOOKS_TABLE;
                selectedCollection = Constants.ALL;
                selectedDomain = Constants.ALL;
                return;
            }
        }
        response.setContentType("text/html");
        requestDispatcher = getServletContext().getRequestDispatcher("/client.jsp");
        if (requestDispatcher != null) {
            request.setAttribute("userDisplayName", userDisplayName);
            request.setAttribute("errorMessage", errorMessage);
            request.setAttribute("currentTableName", selectedTable);
			if (selectedCollection == null || selectedCollection.isEmpty())
				selectedCollection = Constants.ALL;
			request.setAttribute("currentCollection", selectedCollection);
			if (selectedDomain == null || selectedDomain.isEmpty())
				selectedDomain = Constants.ALL;
            request.setAttribute("currentDomain", selectedDomain);
            request.setAttribute("shoppingCart", shoppingCart);
            try {
                ArrayList<String> attributes = dataBaseWrapper.getTableColumns(selectedTable);
                request.setAttribute("attributes", attributes);
                String collectionPrimaryKey = dataBaseWrapper.getTablePrimaryKey(Constants.COLLECTIONS_TABLE);
                String primaryKey = dataBaseWrapper.getTablePrimaryKey(selectedTable);
                request.setAttribute("primaryKey", primaryKey);
                request.setAttribute("collectionPrimaryKey", collectionPrimaryKey);
                String domainPrimaryKey = dataBaseWrapper.getTablePrimaryKey(Constants.DOMAINS_TABLE);
                request.setAttribute("domainPrimaryKey", domainPrimaryKey);
            } catch (SQLException sqlException) {
                System.out.println("An exception has occurred: " + sqlException.getMessage());
				if (Constants.DEBUG)
					sqlException.printStackTrace();
			}
            requestDispatcher.forward(request, response);
        }
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}


text:
var _data = new Object();
%DebugAsyncTaskEvent(_data);


text:
import * as vscode from 'vscode';
import { extensionName } from '../appGlobals';
import { escapeRegExp } from '../helpers';
import { basename } from 'path';
import { DebugCodeLens } from './DebugCodeLens';
import { TestReconciliationState } from '../TestResults';
import { TestState, TestStateByTestReconciliationState } from './TestState';
import { GetJestExtByURI } from '../extensionManager';

export class DebugCodeLensProvider implements vscode.CodeLensProvider {
  onDidChange: vscode.EventEmitter<void>;
  private _showWhenTestStateIn: TestState[];
  private getJestExt: GetJestExtByURI;

  constructor(getJestExt: GetJestExtByURI, showWhenTestStateIn: TestState[] = []) {
    this.getJestExt = getJestExt;
    this._showWhenTestStateIn = showWhenTestStateIn;
    this.onDidChange = new vscode.EventEmitter();
  }

  get showWhenTestStateIn() {
    return this._showWhenTestStateIn;
  }

  set showWhenTestStateIn(value: TestState[]) {
    this._showWhenTestStateIn = value;
    this.onDidChange.fire();
  }

  get onDidChangeCodeLenses(): vscode.Event<void> {
    return this.onDidChange.event;
  }

  provideCodeLenses(document: vscode.TextDocument, _: vscode.CancellationToken): vscode.CodeLens[] {
    const result = [];
    const ext = this.getJestExt(document.uri);
    if (!ext || this._showWhenTestStateIn.length === 0 || document.isUntitled) {
      return result;
    }

    const filePath = document.fileName;
    const testResults = ext.testResultProvider.getResults(filePath);
    const fileName = basename(document.fileName);

    for (const test of testResults) {
      if (!this.showCodeLensAboveTest(test)) {
        continue;
      }

      const start = new vscode.Position(test.start.line, test.start.column);
      const end = new vscode.Position(test.end.line, test.start.column + 5);
      const range = new vscode.Range(start, end);
      result.push(new DebugCodeLens(document, range, fileName, test.name));
    }

    return result;
  }

  showCodeLensAboveTest(test: { status: TestReconciliationState }) {
    const state = TestStateByTestReconciliationState[test.status];
    return this._showWhenTestStateIn.includes(state);
  }

  resolveCodeLens(
    codeLens: vscode.CodeLens,
    _: vscode.CancellationToken
  ): vscode.ProviderResult<vscode.CodeLens> {
    if (codeLens instanceof DebugCodeLens) {
      codeLens.command = {
        arguments: [codeLens.document, codeLens.fileName, escapeRegExp(codeLens.testName)],
        command: `${extensionName}.run-test`,
        title: 'Debug',
      };
    }

    return codeLens;
  }

  didChange() {
    this.onDidChange.fire();
  }
}


text:
module.exports = function (grunt) {
  grunt.initConfig({
    coveralls: {
      options: {
        debug: true,
        coverageDir: 'coverage',
        dryRun: false,
        force: true,
        recursive: true
      }
    }
  })
  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-karma-coveralls')
  // Default task(s).
  grunt.registerTask('default', ['coveralls'])
}


text:
toc: true
next: /using/objects-reference/library-objects
prev: /using/objects-reference/store-object
icon: "- "
title: logger Object
weight: 244
---

Allows to add a trace message to the log output via the `Log` method.

## Log method

It works like `Console.WriteLine`, accepting a format string followed by optional arguments.
If you do not specify the importance, the message will be logged at `Verbose` level.

### Examples

```
logger.Log("Hello, World from {1} #{0}!", self.Id, self.TypeName);

logger.Log(LogLevel.Warning, "Unexpected work item state!");
```

Possible `LogLevel` values are:

 * Critical
 * Error
 * Warning
 * Information
 * Verbose
 * Diagnostic

Each message goes to

* Debug output (visible using DebugView).
* Windows _Application_ EventLog using `TFS Aggregator` source, when level is **Warning** or **Critical**.
* .Net Trace listeners.

The .Net Trace Source for user messages is `TfsAggregator.User`; TFS Aggregator own messages have `TfsAggregator.ServerPlugin` Trace Source.

## RuleName property (**v2.1**)

Returns the name of current executing Rule.

```
logger.Log("Hello from Rule {0} processing {1} #{2}.", logger.RuleName, self.TypeName, self.Id);
```


text:
package com.ftfl.icare;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ftfl.icare.adapter.CustomDrawerAdapter;
import com.ftfl.icare.adapter.CustomProfileAdapter;
import com.ftfl.icare.helper.ICareProfileDataSource;
import com.ftfl.icare.model.ICareProfile;
import com.ftfl.icare.util.DrawerItem;
import com.ftfl.icare.util.FragmentAbout;
import com.ftfl.icare.util.FragmentAddAppointmentInfo;
import com.ftfl.icare.util.FragmentAddCareCenter;
import com.ftfl.icare.util.FragmentAddDiet;
import com.ftfl.icare.util.FragmentAddDoctor;
import com.ftfl.icare.util.FragmentAddMadication;
import com.ftfl.icare.util.FragmentAddMedicalHistory;
import com.ftfl.icare.util.FragmentAddNote;
import com.ftfl.icare.util.FragmentAddVaccination;
import com.ftfl.icare.util.FragmentHome;
import com.ftfl.icare.util.FragmentViewGeneralDiet;
import com.ftfl.icare.util.FragmentViewGeneralGrowth;
import com.ftfl.icare.util.FragmentViewGeneralVaccination;
import com.ftfl.icare.util.ICareConstants;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class HomeScreenActivity extends Activity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	FragmentManager frgManager;
	Fragment fragment;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	CustomDrawerAdapter adapter;
	Bundle args = new Bundle();
	List<DrawerItem> dataList;

	TextView mId_tv = null;
	ICareProfileDataSource ProfileDataSource;
	ICareProfile IProfile;

	ListView lvProfileList;
	List<ICareProfile> iCareProfilesList;
	String mId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_screen);
		centerActionBarTitle();
		getOverflowMenu();

		ProfileDataSource = new ICareProfileDataSource(this);
		iCareProfilesList = ProfileDataSource.iCareProfilesList();

		if(iCareProfilesList.size() == 1){

			share(iCareProfilesList.get(0).getID());

		}

		// Initializing
		dataList = new ArrayList<DrawerItem>();
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		dataList.add(new DrawerItem("Home", R.drawable.home));
		dataList.add(new DrawerItem("View Profile ", R.drawable.myprofile));
		dataList.add(new DrawerItem("Profile List", R.drawable.userlist));
		dataList.add(new DrawerItem("Add Profile", R.drawable.adduser));

		dataList.add(new DrawerItem("________________________________"));

		dataList.add(new DrawerItem("Add Diet", R.drawable.plus));
		dataList.add(new DrawerItem("Add Doctor", R.drawable.plus));
		dataList.add(new DrawerItem("Add Appointment", R.drawable.plus));
		dataList.add(new DrawerItem("Add Madication", R.drawable.plus));
		dataList.add(new DrawerItem("Add Madical History", R.drawable.plus));
		dataList.add(new DrawerItem("Add Care Centre", R.drawable.plus));
		dataList.add(new DrawerItem("Add Vaccination", R.drawable.plus));
		dataList.add(new DrawerItem("Add Notes", R.drawable.plus));

		dataList.add(new DrawerItem("________________________________"));

		dataList.add(new DrawerItem("Growth", R.drawable.drawergrowth));
		dataList.add(new DrawerItem("Vaccination", R.drawable.drawerinjection));
		dataList.add(new DrawerItem("Diet/Nutrition", R.drawable.drawerdiet));

		dataList.add(new DrawerItem("_________________________________"));

		dataList.add(new DrawerItem("About", R.drawable.drawerabout));

		adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
				dataList);

		mDrawerList.setAdapter(adapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menu, R.string.drawer_open, R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {

			ProfileDataSource = new ICareProfileDataSource(this);
			iCareProfilesList = ProfileDataSource.iCareProfilesList();

			if(iCareProfilesList.size() == 0){
				SelectItem(3);
				SharedPreferences settings = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
				settings.edit().clear().commit();

			}
			else if(iCareProfilesList.size() == 1){

				SelectItem(0);
				share(iCareProfilesList.get(0).getID());

			}else{

				SelectItem(0);
				dialogOnStart();
			}

		}

	}

	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// // Handle the back button
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// // Ask the user if they want to quit
	// new AlertDialog.Builder(this)
	// .setIcon(android.R.drawable.ic_dialog_alert)
	// .setTitle(R.string.quit)
	// .setMessage(R.string.really_quit)
	// .setPositiveButton(R.string.yes,
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	//
	// // Stop the activity
	// HomeScreenActivity.this.finish();
	// }
	//
	// }).setNegativeButton(R.string.no, null).show();
	//
	// return true;
	// } else {
	// return super.onKeyDown(keyCode, event);
	// }
	//
	// }

	private void centerActionBarTitle() {

		int titleId = 0;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			titleId = getResources().getIdentifier("action_bar_title", "id",
					"android");
		} else {
			// This is the id is from your app's generated R class when
			// ActionBarActivity is used
			// for SupportActionBar
			titleId = R.id.action_bar_title;
		}

		// Final check for non-zero invalid id
		if (titleId > 0) {
			TextView titleTextView = (TextView) findViewById(titleId);

			DisplayMetrics metrics = getResources().getDisplayMetrics();

			// Fetch layout parameters of titleTextView
			// (LinearLayout.LayoutParams : Info from HierarchyViewer)
			LinearLayout.LayoutParams txvPars = (android.widget.LinearLayout.LayoutParams) titleTextView
					.getLayoutParams();
			txvPars.gravity = Gravity.CENTER_HORIZONTAL;
			txvPars.width = metrics.widthPixels;
			titleTextView.setLayoutParams(txvPars);

			titleTextView.setGravity(Gravity.CENTER);
		}
	}

	public void SelectItem(int possition) {

		switch (possition) {

		case 0:
			fragment = new FragmentHome();

			break;

		case 1:
			fragment = new FragmentViewProfile();
			break;

		case 2:
			fragment = new FragmentViewProfileList();
			break;
		case 3:
			fragment = new FragmentAddProfile();
			break;

		case 5:
			fragment = new FragmentAddDiet();

			break;

		case 6:
			fragment = new FragmentAddDoctor();
			break;
		case 7:
			fragment = new FragmentAddAppointmentInfo();
			break;
		case 8:
			fragment = new FragmentAddMadication();
			break;
		case 9:
			fragment = new FragmentAddMedicalHistory();
			break;
		case 10:
			fragment = new FragmentAddCareCenter();
			break;
		case 11:
			fragment = new FragmentAddVaccination();
			break;
		case 12:
			fragment = new FragmentAddNote();
			break;
		case 14:
			fragment = new FragmentViewGeneralGrowth();
			break;

		case 15:
			fragment = new FragmentViewGeneralVaccination();
			break;
		case 16:
			fragment = new FragmentViewGeneralDiet();
			break;

		case 18:
			fragment = new FragmentAbout();
			break;

		default:
			break;
		}

		fragment.setArguments(args);
		frgManager = getFragmentManager();
		frgManager.beginTransaction().replace(R.id.content_frame, fragment)
				.addToBackStack(null).commit();

		mDrawerList.setItemChecked(possition, true);
		setTitle(dataList.get(possition).getItemName());
		mDrawerLayout.closeDrawer(mDrawerList);

	}

	public void dialogOnStart() {

		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.fragment_layout_view_profile_list);
		dialog.setTitle("Select Profile");

		// Create global configuration and initialize ImageLoader with this
		// config
		// Create default options which will be used for every
		// displayImage(...) call if no options will be passed to this method
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisk(true).build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).defaultDisplayImageOptions(defaultOptions).build();
		ImageLoader.getInstance().init(config);

		ProfileDataSource = new ICareProfileDataSource(this);
		iCareProfilesList = ProfileDataSource.iCareProfilesList();
		CustomProfileAdapter arrayAdapter = new CustomProfileAdapter(this,
				iCareProfilesList);
		lvProfileList = (ListView) dialog.findViewById(R.id.lvProfileList);
		lvProfileList.setAdapter(arrayAdapter);

		lvProfileList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						mId_tv = (TextView) view.findViewById(R.id.tvID);
						mId = mId_tv.getText().toString();

						share(iCareProfilesList.get(position).getID());

						dialog.dismiss();
					}
				});

		dialog.show();
	}

	public void share(String position) {

		SharedPreferences preferences = getSharedPreferences(
				"AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("profile_id", position);
		editor.apply();

		ICareConstants.SELECTED_PROFILE_ID = Integer.parseInt(position);

	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggles
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (dataList.get(position).getTitle() == null) {
				SelectItem(position);
			}

		}
	}

	private void getOverflowMenu() {

		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// // Inflate the menu; this adds items to the action bar if it is present.
	// getMenuInflater().inflate(R.menu.main, menu);
	// return true;
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		return false;
	}

}


text:
'use strict';

/* Controllers */

angular.module('myApp.controllers', [])

  .controller('LandingPageController', [function() {

  }])

  .controller('WaitlistController', ['$scope', 'partyService', 'textMessageService', 'authService', function($scope, partyService, textMessageService, authService) {

      authService.getCurrentUser().then(function(user) {
        if (user) {
          $scope.parties = partyService.getPartiesByUserId(user.id);
        }
      });

  		$scope.newParty = { name: '', phone: '', size: '', done: false, notified: 'No' };

      // Save a new party
  		$scope.saveParty = function() {
        partyService.saveParty($scope.newParty, $scope.currentUser.id);
        $scope.newParty = { name: '', phone: '', size: '', done: false, notified: 'No' };
  		}

      // Send a text message
      $scope.sendTextMessage = function(party) {
        textMessageService.sendTextMessage(party, $scope.currentUser.id);
      };

  }])

  .controller('AuthController', ['$scope', 'authService', function($scope, authService) {

    $scope.user = {email: '', password: ''};

    $scope.register = function() {
      authService.register($scope.user);
    }

    $scope.login = function() {
      authService.login($scope.user);
    }

    $scope.logout = function() {
      authService.logout();
    }

  }]);


text:
package com.cloudera.cdk.data.filesystem;

import com.cloudera.cdk.data.FieldPartitioner;
import com.cloudera.cdk.data.partition.DayOfMonthFieldPartitioner;
import com.cloudera.cdk.data.partition.HourFieldPartitioner;
import com.cloudera.cdk.data.partition.MinuteFieldPartitioner;
import com.cloudera.cdk.data.partition.MonthFieldPartitioner;
import com.cloudera.cdk.data.spi.Conversions;
import com.cloudera.cdk.data.spi.StorageKey;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.hadoop.fs.Path;

import java.util.List;
import java.util.Map;

class PathConversion {

  public StorageKey toKey(Path fromPath, StorageKey storage) {
    final List<FieldPartitioner> partitioners =
        storage.getPartitionStrategy().getFieldPartitioners();
    final List<Object> values = Lists.newArrayList(
        new Object[partitioners.size()]);

    Path currentPath = fromPath;
    int index = partitioners.size() - 1;
    while (currentPath != null && index >= 0) {
      values.set(index, valueForDirname(
          (FieldPartitioner<?, ?>) partitioners.get(index),
          currentPath.getName()));

      // update
      currentPath = currentPath.getParent();
      index -= 1;
    }

    storage.replaceValues(values);
    return storage;
  }

  public Path fromKey(StorageKey key) {
    final StringBuilder pathBuilder = new StringBuilder();
    final List<FieldPartitioner> partitioners =
        key.getPartitionStrategy().getFieldPartitioners();

    for (int i = 0; i < partitioners.size(); i++) {
      final FieldPartitioner fp = partitioners.get(i);
      if (i != 0) {
        pathBuilder.append(Path.SEPARATOR_CHAR);
      }
      @SuppressWarnings("unchecked")
      String dirname = dirnameForValue(fp, key.get(i));
      pathBuilder.append(dirname);
    }

    return new Path(pathBuilder.toString());
  }

  private static final Splitter PART_SEP = Splitter.on('=');
  private static final Joiner PART_JOIN = Joiner.on('=');
  private static final Map<Class<?>, Integer> WIDTHS =
      ImmutableMap.<Class<?>, Integer>builder()
          .put(MinuteFieldPartitioner.class, 2)
          .put(HourFieldPartitioner.class, 2)
          .put(DayOfMonthFieldPartitioner.class, 2)
          .put(MonthFieldPartitioner.class, 2)
          .build();

  public <T> String dirnameForValue(FieldPartitioner<?, T> field, T value) {
    return PART_JOIN.join(field.getName(),
        Conversions.makeString(value, WIDTHS.get(field.getClass())));
  }

  public <T> T valueForDirname(FieldPartitioner<?, T> field, String name) {
    // this could check that the field name matches the directory name
    return Conversions.convert(valueStringForDirname(name), field.getType());
  }

  public String valueStringForDirname(String name) {
    return Iterables.getLast(PART_SEP.split(name));
  }
}


text:
// init_ui.js
// 2011-10-19

// This is the web browser companion to fulljslint.js. It is an ADsafe
// lib file that implements a web ui by adding behavior to the widget's
// html tags.

// It stores a function in lib.init_ui. Calling that function will
// start up the JSLint widget ui.

// option = {adsafe: true, fragment: false}

/*properties check, cookie, each, edition, get, getCheck, getTitle, getValue,
    has, indent, isArray, join, jslint, length, lib, maxerr, maxlen, on,
    predef, push, q, select, set, split, stringify, style, target, tree, value
*/

ADSAFE.lib("init_ui", function (lib) {
    "use strict";

    return function (dom) {
        var table = dom.q('#JSLINT_TABLE'),
            boxes = table.q('span'),
            indent = dom.q('#JSLINT_INDENT'),
            input = dom.q('#JSLINT_INPUT'),
            jslintstring = dom.q('#JSLINT_JSLINTSTRING'),
            maxerr = dom.q('#JSLINT_MAXERR'),
            maxlen = dom.q('#JSLINT_MAXLEN'),
            option = lib.cookie.get(),
            output = dom.q('#JSLINT_OUTPUT'),
            tree = dom.q('#JSLINT_TREE'),
            predefined = dom.q('#JSLINT_PREDEF');

        function show_jslint_control() {

// Build and display a /*jslint*/ control comment.
// The comment can be copied into a .js file.

            var a = [];

            boxes.each(function (bunch) {
                var name = bunch.getTitle(),
                    value = ADSAFE.get(option, name);
                if (typeof value === 'boolean') {
                    a.push(name + ': ' + value);
                    bunch.style('backgroundColor', value ? 'black' : 'white');
                } else {
                    bunch.style('backgroundColor', 'gainsboro');
                }
            });
            if (typeof option.maxerr === 'number' && option.maxerr >= 0) {
                a.push('maxerr: ' + String(option.maxerr));
            }
            if (typeof option.maxlen === 'number' && option.maxlen >= 0) {
                a.push('maxlen: ' + String(option.maxlen));
            }
            if (typeof option.indent === 'number' && option.indent >= 0) {
                a.push('indent: ' + String(option.indent));
            }
            jslintstring.value('/*jslint ' + a.join(', ') + ' */');

// Make a JSON cookie of the option object.

            lib.cookie.set(option);
        }

        function show_options() {
            indent.value(String(option.indent));
            maxlen.value(String(option.maxlen || ''));
            maxerr.value(String(option.maxerr));
            predefined.value(ADSAFE.isArray(option.predef) ? option.predef.join(',') : '');
            show_jslint_control();
        }

        function update_box(event) {

//  Boxes are tristate, cycling true, false, undefined.

            var title = event.target.getTitle();
            if (title) {
                ADSAFE.set(option, title,
                    ADSAFE.get(option, title) === true
                        ? false
                        : ADSAFE.get(option, title) === false
                            ? undefined
                            : true);
            }
            show_jslint_control();
        }

        function update_number(event) {
            var value = event.target.getValue();
            if (value.length === 0 || +value < 0 || !isFinite(value)) {
                value = '';
                ADSAFE.set(option, event.target.getTitle(), undefined);
            } else {
                ADSAFE.set(option, event.target.getTitle(), +value);
            }
            event.target.value(String(value));
            show_jslint_control();
        }

        function update_list(event) {
            var value = event.target.getValue().split(/\s*,\s*/);
            ADSAFE.set(option, event.target.getTitle(), value);
            event.target.value(value.join(', '));
            show_jslint_control();
        }

// Restore the options from a JSON cookie.

        if (!option || typeof option !== 'object') {
            option = {
                indent: 4,
                maxerr: 50
            };
        } else {
            option.indent = typeof option.indent === 'number' && option.indent >= 0
                ? option.indent
                : 4;
            option.maxerr = typeof option.maxerr === 'number' && option.maxerr >= 0
                ? option.maxerr
                : 50;
        }
        show_options();

// Display the edition.

        dom.q('#JSLINT_EDITION').value('Edition ' + lib.edition());

// Add click event handlers to the [JSLint] and [clear] buttons.

        dom.q('input&jslint').on('click', function () {
            tree.value('');

// Call JSLint and display the report.

            tree.value(String(lib.jslint(input.getValue(), option, output) / 1000) + ' seconds.');
            input.select();
            return false;
        });

        dom.q('input&tree').on('click', function () {
            output.value('Tree:');
            tree.value(JSON.stringify(lib.tree(), [
                'label', 'id', 'string', 'number', 'arity', 'name', 'first',
                'second', 'third', 'block', 'else', 'quote', 'flag', 'type'
            ], 4));
            input.select();
        });

        dom.q('input&clear').on('click', function () {
            output.value('');
            tree.value('');
            input.value('').select();
        });

        dom.q('#JSLINT_CLEARALL').on('click', function () {
            option = {
                indent: 4,
                maxerr: 50
            };
            show_options();
        });

        table.on('click', update_box);
        indent.on('change', update_number);
        maxerr.on('change', update_number);
        maxlen.on('change', update_number);
        predefined.on('change', update_list);
        input
            .on('change', function () {
                output.value('');
            })
            .select();
    };
});


text:
import { OTHER_ERROR, SUCCESS } from 'nagu-validates';
import fetch from '../core/fetch';
import { fetchFailed, fetching, fetchDone } from './common';
import { SET_LIST_PARAMS } from '../constants';

export const findResources = ({ catagory, state, before }) => async dispatch => {
  dispatch(fetching());
  try {
    const res = await fetch(
      `/api/res-track?catagory=${catagory || ''}&state=${state || ''}&before=${before || ''}`, {
        credentials: 'same-origin',
      });
    const result = await res.json();
    if (result.ret === SUCCESS) {
      dispatch(fetchDone(result.data));
      return Promise.resolve(result.data);
    }
    dispatch(fetchFailed(result));
    return Promise.reject(result);
  } catch (msg) {
    const result = {
      ret: OTHER_ERROR,
      msg,
    };
    dispatch(fetchFailed(result));
    return Promise.reject(result);
  }
};

export const setParams = params => ({
  type: SET_LIST_PARAMS,
  params,
});


text:
from collections import OrderedDict

from bokeh.sampledata.unemployment1948 import data
from bokeh.charts import HeatMap

# pandas magic
df = data[data.columns[:-2]]
df2 = df.set_index(df[df.columns[0]].astype(str))
df2.drop(df.columns[0], axis=1, inplace=True)
df3 = df2.transpose()

cols = df3.columns.tolist()
index = df3.index.tolist()

#prepare some inputs
to_odict = lambda v: OrderedDict((kk, v[kk]) for kk in index)

# Create an ordered dict (or ordered dicts) with the data from the DataFrame
datadict = df3.to_dict()
data = OrderedDict(sorted((k, to_odict(v)) for k, v in datadict.items()))

# any of the following commented line is a valid HeatMap input
#data = df3
#data = df3.values.T
#data = list(df3.values.T)

hm = HeatMap(data, title="categorical heatmap", filename="cat_heatmap.html")
hm.width(1000).height(400).show()


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\TwiML\Voice;

use Twilio\TwiML\TwiML;

class SsmlPhoneme extends TwiML {
    /**
     * SsmlPhoneme constructor.
     *
     * @param string $words Words to speak
     * @param array $attributes Optional attributes
     */
    public function __construct($words, $attributes = array()) {
        parent::__construct('phoneme', $words, $attributes);
    }

    /**
     * Add Alphabet attribute.
     *
     * @param string $alphabet Specify the phonetic alphabet
     * @return static $this.
     */
    public function setAlphabet($alphabet) {
        return $this->setAttribute('alphabet', $alphabet);
    }

    /**
     * Add Ph attribute.
     *
     * @param string $ph Specifiy the phonetic symbols for pronunciation
     * @return static $this.
     */
    public function setPh($ph) {
        return $this->setAttribute('ph', $ph);
    }
}


text:
package com.springapp.mvc.model;

import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DocParser {

    public String parseDocument(String docPath) throws FileNotFoundException,
            IOException,
            XmlException,
            InvalidFormatException,
            OpenXML4JException,
            ParserConfigurationException,
            SAXException
    {
        File file = new File(docPath);
        FileInputStream fs = new FileInputStream(file);

        if (file.getName().endsWith(".docx")) {
            return this.parseDocx(OPCPackage.open(fs));
        } else if (file.getName().endsWith(".xlsx")) {
            return this.parseXlsx(OPCPackage.open(fs));
        } else if (file.getName().endsWith(".pptx")) {
            return this.parsePptx(OPCPackage.open(fs));
        } else if (file.getName().endsWith(".doc")) {
            return this.parseDoc(new POIFSFileSystem(fs));
        } else if (file.getName().endsWith(".xls")) {
            return this.parseXls(new POIFSFileSystem(fs));
        } else if (file.getName().endsWith(".ppt")) {
            return this.parsePpt(new POIFSFileSystem(fs));
        } else if (file.getName().endsWith(".pdf")) {
            return this.parsePdf(fs);
        } else if (file.getName().endsWith(".txt")) {
            return this.parseTxt(fs);
        }

        //better to handle in different way if document is not recognized
        return "";
    }

    private String parseDocx(OPCPackage docx) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        XWPFWordExtractor xw = new XWPFWordExtractor(docx);
        return xw.getText();
    }

    private String parsePptx(OPCPackage pptx) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        XSLFPowerPointExtractor xw = new XSLFPowerPointExtractor(pptx);
        return xw.getText();
    }

    private String parseXlsx(OPCPackage xlsx) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        XSSFExcelExtractor xe = new XSSFExcelExtractor(xlsx);
        return xe.getText();
    }

    private String parseDoc(POIFSFileSystem doc) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        WordExtractor xw = new WordExtractor(doc);
        return xw.getText();
    }

    private String parsePpt(POIFSFileSystem ppt) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        PowerPointExtractor xw = new PowerPointExtractor(ppt);
        return xw.getText();
    }

    private String parseXls(POIFSFileSystem xls) throws FileNotFoundException,
            IOException,
            InvalidFormatException,
            XmlException,
            OpenXML4JException
    {
        ExcelExtractor xe = new ExcelExtractor(xls);
        return xe.getText();
    }

    private String parsePdf(FileInputStream fileInputStream) throws IOException {
        PDFParser pdfParser = new PDFParser(fileInputStream);
        pdfParser.parse();
        COSDocument cd = pdfParser.getDocument();
        PDFTextStripper stripper = new PDFTextStripper();
        String pdfContent = stripper.getText(new PDDocument(cd));
        cd.close();
        return pdfContent;
    }

    private String parseTxt(FileInputStream fileInputStream) throws IOException {
        try {
            String content = IOUtils.toString(fileInputStream);
            return content;
        } finally {
            fileInputStream.close();
        }
    }
}


text:
layout: news
title: UDK2014 Preview
---
{% include site-links.md %}

Upcoming soon UDK2014 See a sneak preview:
[UDK2014 Features]({{wiki}}/RoadMap2014)


text:
cask 'atom' do
  version '1.23.1'
  sha256 '575d7e4311475eae69a4456cd7bd5a038f679e953193c76638dde0602c2b0131'

  # github.com/atom/atom was verified as official when first introduced to the cask
  url "https://github.com/atom/atom/releases/download/v#{version}/atom-mac.zip"
  appcast 'https://github.com/atom/atom/releases.atom',
          checkpoint: 'ff39504028ff760b856cfb1ce91d7adb7fe1aee97205a2380c2d82f4cc52cad2'
  name 'Github Atom'
  homepage 'https://atom.io/'

  auto_updates true
  depends_on macos: '>= :mavericks'

  app 'Atom.app'
  binary "#{appdir}/Atom.app/Contents/Resources/app/apm/bin/apm"
  binary "#{appdir}/Atom.app/Contents/Resources/app/atom.sh", target: 'atom'

  zap trash: [
               '~/.atom',
               '~/Library/Application Support/Atom',
               '~/Library/Application Support/ShipIt_stderr.log',
               '~/Library/Application Support/ShipIt_stdout.log',
               '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.github.atom.sfl*',
               '~/Library/Application Support/com.github.atom.ShipIt',
               '~/Library/Caches/com.github.atom',
               '~/Library/Caches/com.github.atom.ShipIt',
               '~/Library/Preferences/com.github.atom.helper.plist',
               '~/Library/Preferences/com.github.atom.plist',
               '~/Library/Saved Application State/com.github.atom.savedState',
             ]
end


text:
package org.broadleafcommerce.cms.page.domain;

import org.broadleafcommerce.common.admin.domain.AdminMainEntity;
import org.broadleafcommerce.common.copy.CreateResponse;
import org.broadleafcommerce.common.copy.MultiTenantCopyContext;
import org.broadleafcommerce.common.extensibility.jpa.clone.ClonePolicyArchive;
import org.broadleafcommerce.common.extensibility.jpa.clone.ClonePolicyMapOverride;
import org.broadleafcommerce.common.extensibility.jpa.clone.IgnoreEnterpriseBehavior;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes;
import org.broadleafcommerce.common.extensibility.jpa.copy.ProfileEntity;
import org.broadleafcommerce.common.presentation.AdminPresentation;
import org.broadleafcommerce.common.presentation.AdminPresentationClass;
import org.broadleafcommerce.common.presentation.AdminPresentationMap;
import org.broadleafcommerce.common.presentation.AdminPresentationToOneLookup;
import org.broadleafcommerce.common.presentation.PopulateToOneFieldsEnum;
import org.broadleafcommerce.common.presentation.RequiredOverride;
import org.broadleafcommerce.common.presentation.ValidationConfiguration;
import org.broadleafcommerce.common.presentation.client.VisibilityEnum;
import org.broadleafcommerce.common.presentation.override.AdminPresentationOverride;
import org.broadleafcommerce.common.presentation.override.AdminPresentationOverrides;
import org.broadleafcommerce.common.web.Locatable;
import org.broadleafcommerce.openadmin.audit.AdminAuditable;
import org.broadleafcommerce.openadmin.audit.AdminAuditableListener;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.Parameter;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Created by bpolster.
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PAGE")
@EntityListeners(value = { AdminAuditableListener.class })
@AdminPresentationOverrides(
    {
        @AdminPresentationOverride(name="auditable.createdBy.id", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="auditable.updatedBy.id", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="auditable.createdBy.name", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="auditable.updatedBy.name", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="auditable.dateCreated", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="auditable.dateUpdated", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
        @AdminPresentationOverride(name="pageTemplate.templateDescription", value=@AdminPresentation(excluded = true)),
        @AdminPresentationOverride(name="pageTemplate.templateName", value=@AdminPresentation(excluded = true)),
        @AdminPresentationOverride(name="pageTemplate.locale", value=@AdminPresentation(excluded = true))
    }
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "PageImpl_basePage")
@DirectCopyTransform({
        @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true),
        @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_SITE)
})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blCMSElements")
public class PageImpl implements Page, AdminMainEntity, Locatable, ProfileEntity {

    private static final long serialVersionUID = 1L;

    private static final Integer ZERO = new Integer(0);

    @Id
    @GeneratedValue(generator = "PageId")
    @GenericGenerator(
            name="PageId",
            strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
            parameters = {
                @Parameter(name="segment_value", value="PageImpl"),
                @Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageImpl")
            }
        )
    @Column(name = "PAGE_ID")
    protected Long id;

    @ManyToOne(targetEntity = PageTemplateImpl.class)
    @JoinColumn(name = "PAGE_TMPLT_ID")
    @AdminPresentation(friendlyName = "PageImpl_Page_Template", order = 4000,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic, prominent = true,
        requiredOverride = RequiredOverride.REQUIRED)
    @AdminPresentationToOneLookup(lookupDisplayProperty = "templateName")
    protected PageTemplate pageTemplate;

    @Column (name = "DESCRIPTION")
    @AdminPresentation(friendlyName = "PageImpl_Description", order = 1000,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
            requiredOverride = RequiredOverride.REQUIRED,
        prominent = true, gridOrder = 1)
    protected String description;

    @Column (name = "FULL_URL")
    @Index(name="PAGE_FULL_URL_INDEX", columnNames={"FULL_URL"})
    @AdminPresentation(friendlyName = "PageImpl_Full_Url", order = 3000,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
        prominent = true, gridOrder = 2,
        validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") })
    protected String fullUrl;

    @OneToMany(mappedBy = "page", targetEntity = PageFieldImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @MapKey(name = "fieldKey")
    @BatchSize(size = 20)
    @ClonePolicyMapOverride
    @ClonePolicyArchive
    protected Map<String,PageField> pageFields = new HashMap<String,PageField>();

    @Column(name = "PRIORITY")
    @Deprecated
    protected Integer priority;

    @Column(name = "OFFLINE_FLAG")
    @AdminPresentation(friendlyName = "PageImpl_Offline", order = 3500,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic, defaultValue = "false")
    protected Boolean offlineFlag = false;

    /*
     * This will not work with Enterprise workflows.  Do not use.
     */
    @ManyToMany(targetEntity = PageRuleImpl.class, cascade = {CascadeType.ALL})
    @JoinTable(name = "BLC_PAGE_RULE_MAP",
        inverseJoinColumns = @JoinColumn(name = "PAGE_RULE_ID", referencedColumnName = "PAGE_RULE_ID"))
    @Cascade(value = { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
    @MapKeyColumn(name = "MAP_KEY", nullable = false)
    @Deprecated
    protected Map<String, PageRule> pageMatchRules = new HashMap<String, PageRule>();

    /*
     * This will not work with Enterprise workflows. Do not use.
     */
    @OneToMany(fetch = FetchType.LAZY, targetEntity = PageItemCriteriaImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @JoinTable(name = "BLC_QUAL_CRIT_PAGE_XREF",
        joinColumns = @JoinColumn(name = "PAGE_ID"),
        inverseJoinColumns = @JoinColumn(name = "PAGE_ITEM_CRITERIA_ID"))
    @Deprecated
    @IgnoreEnterpriseBehavior
    protected Set<PageItemCriteria> qualifyingItemCriteria = new HashSet<PageItemCriteria>();

    @Column(name = "EXCLUDE_FROM_SITE_MAP")
    @AdminPresentation(friendlyName = "PageImpl_Exclude_From_Site_Map", order = 1000,
        tab = Presentation.Tab.Name.Seo, tabOrder = Presentation.Tab.Order.Seo,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic)
    protected Boolean excludeFromSiteMap;

    @OneToMany(mappedBy = "page", targetEntity = PageAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @MapKey(name = "name")
    @BatchSize(size = 50)
    @AdminPresentationMap(friendlyName = "PageImpl_Page_Attributes_Title",
        deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "PageAttributeImpl_Name"
    )
    protected Map<String, PageAttribute> additionalAttributes = new HashMap<String, PageAttribute>();

    @Column(name = "ACTIVE_START_DATE")
    @AdminPresentation(friendlyName = "PageImpl_activeStartDate", order = 5000,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
        excluded = true)
    protected Date activeStartDate;

    @Column(name = "ACTIVE_END_DATE")
    @AdminPresentation(friendlyName = "PageImpl_activeEndDate", order = 6000,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
        excluded = true)
    protected Date activeEndDate;

    @Column (name = "META_TITLE")
    @AdminPresentation(friendlyName = "PageImpl_metaTitle", order = 2000,
        tab = Presentation.Tab.Name.Seo, tabOrder = Presentation.Tab.Order.Seo,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic)
    protected String metaTitle;

    @Column (name = "META_DESCRIPTION")
    @AdminPresentation(friendlyName = "PageImpl_metaDescription", order = 3000,
        tab = Presentation.Tab.Name.Seo, tabOrder = Presentation.Tab.Order.Seo,
        group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic)
    protected String metaDescription;

    @Embedded
    @AdminPresentation(excluded = true)
    protected AdminAuditable auditable = new AdminAuditable();

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public PageTemplate getPageTemplate() {
        return pageTemplate;
    }

    @Override
    public void setPageTemplate(PageTemplate pageTemplate) {
        this.pageTemplate = pageTemplate;
    }

    @Override
    public Map<String, PageField> getPageFields() {
        return pageFields;
    }

    @Override
    public void setPageFields(Map<String, PageField> pageFields) {
        this.pageFields = pageFields;
    }

    @Override
    public String getFullUrl() {
        return fullUrl;
    }

    @Override
    public void setFullUrl(String fullUrl) {
        this.fullUrl = fullUrl;
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public AdminAuditable getAuditable() {
        return auditable;
    }

    @Override
    public void setAuditable(AdminAuditable auditable) {
        this.auditable = auditable;
    }

    @Override
    public Boolean getOfflineFlag() {
        return offlineFlag == null ? false : offlineFlag;
    }

    @Override
    public void setOfflineFlag(Boolean offlineFlag) {
        this.offlineFlag = offlineFlag == null ? false : offlineFlag;
    }

    @Override
    public Integer getPriority() {
        if (priority == null) {
            return ZERO;
        }
        return priority;
    }

    @Override
    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    @Override
    public Map<String, PageRule> getPageMatchRules() {
        return pageMatchRules;
    }

    @Override
    public void setPageMatchRules(Map<String, PageRule> pageMatchRules) {
        this.pageMatchRules = pageMatchRules;
    }

    @Override
    public Set<PageItemCriteria> getQualifyingItemCriteria() {
        return qualifyingItemCriteria;
    }

    @Override
    public void setQualifyingItemCriteria(Set<PageItemCriteria> qualifyingItemCriteria) {
        this.qualifyingItemCriteria = qualifyingItemCriteria;
    }

    @Override
    public boolean getExcludeFromSiteMap() {
        if (this.excludeFromSiteMap == null) {
            return false;
        }
        return excludeFromSiteMap;
    }

    @Override
    public void setExcludeFromSiteMap(boolean excludeFromSiteMap) {
        this.excludeFromSiteMap = excludeFromSiteMap;
    }

    @Override
    public <G extends Page> CreateResponse<G> createOrRetrieveCopyInstance(MultiTenantCopyContext context) throws CloneNotSupportedException {
        CreateResponse<G> createResponse = context.createOrRetrieveCopyInstance(this);
        if (createResponse.isAlreadyPopulated()) {
            return createResponse;
        }

        Page cloned = createResponse.getClone();
        cloned.setPriority(priority);
        cloned.setActiveEndDate(activeEndDate);
        cloned.setActiveStartDate(activeStartDate);
        cloned.setDescription(description);
        cloned.setExcludeFromSiteMap(getExcludeFromSiteMap());
        cloned.setFullUrl(fullUrl);
        cloned.setMetaDescription(metaDescription);
        cloned.setOfflineFlag(offlineFlag);
        cloned.setMetaTitle(metaTitle);
        for(Map.Entry<String, PageField> entry : pageFields.entrySet()){
            CreateResponse<PageField> clonedPageField = entry.getValue().createOrRetrieveCopyInstance(context);
            PageField pageField = clonedPageField.getClone();
            cloned.getPageFields().put(entry.getKey(),pageField);
        }
        for(Map.Entry<String,PageRule> entry : pageMatchRules.entrySet()){
            CreateResponse<PageRule> clonedRsp = entry.getValue().createOrRetrieveCopyInstance(context);
            PageRule clonedRule = clonedRsp.getClone();
            cloned.getPageMatchRules().put(entry.getKey(),clonedRule);
        }
        if (pageTemplate != null){
            CreateResponse<PageTemplate> clonedTemplateRsp = pageTemplate.createOrRetrieveCopyInstance(context);
            cloned.setPageTemplate(clonedTemplateRsp.getClone());
        }
        return createResponse;
    }

    public static class Presentation {
        public static class Tab {
            public static class Name {
                public static final String Rules = "PageImpl_Rules_Tab";
                public static final String Seo = "PageImpl_Seo_Tab";
            }

            public static class Order {
                public static final int Rules = 1000;
                public static final int Seo = 2000;
            }
        }

        public static class Group {
            public static class Name {
                public static final String Basic = "PageImpl_Basic";
                public static final String Page = "PageImpl_Page";
                public static final String Rules = "PageImpl_Rules";
            }

            public static class Order {
                public static final int Basic = 1000;
                public static final int Page = 2000;
                public static final int Rules = 1000;
            }
        }
    }

    @Override
    public String getMainEntityName() {
        return getDescription();
    }

    @Override
    public String getLocation() {
        return getFullUrl();
    }

    @Override
    public Map<String, PageAttribute> getAdditionalAttributes() {
        return additionalAttributes;
    }

    @Override
    public void setAdditionalAttributes(Map<String, PageAttribute> additionalAttributes) {
        this.additionalAttributes = additionalAttributes;
    }

    @Override
    public Date getActiveStartDate() {
        return activeStartDate;
    }

    @Override
    public void setActiveStartDate(Date activeStartDate) {
        this.activeStartDate = activeStartDate;
    }

    @Override
    public Date getActiveEndDate() {
        return activeEndDate;
    }

    @Override
    public void setActiveEndDate(Date activeEndDate) {
        this.activeEndDate = activeEndDate;
    }

    @Override
    public String getMetaTitle() {
        return metaTitle;
    }

    @Override
    public void setMetaTitle(String metaTitle) {
        this.metaTitle = metaTitle;
    }

    @Override
    public String getMetaDescription() {
        return metaDescription;
    }

    @Override
    public void setMetaDescription(String metaDescription) {
        this.metaDescription = metaDescription;
    }

}


text:
package com.alibaba.rocketmq.example.transaction;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.client.producer.TransactionCheckListener;
import com.alibaba.rocketmq.client.producer.TransactionMQProducer;
import com.alibaba.rocketmq.common.message.Message;

/**
 * 发送事务消息例子
 *
 */
public class TransactionProducer {
    public static void main(String[] args) throws MQClientException, InterruptedException {

        TransactionCheckListener transactionCheckListener = new TransactionCheckListenerImpl();
        TransactionMQProducer producer = new TransactionMQProducer("please_rename_unique_group_name");
        // 事务回查最小并发数
        producer.setCheckThreadPoolMinSize(2);
        // 事务回查最大并发数
        producer.setCheckThreadPoolMaxSize(2);
        // 队列数
        producer.setCheckRequestHoldMax(2000);
        producer.setTransactionCheckListener(transactionCheckListener);
        producer.start();

        String[] tags = new String[] { "TagA", "TagB", "TagC", "TagD", "TagE" };
        TransactionExecuterImpl tranExecuter = new TransactionExecuterImpl();
        for (int i = 0; i < 100; i++) {
            try {
                Message msg =
                        new Message("TopicTest", tags[i % tags.length], "KEY" + i,
                            ("Hello RocketMQ " + i).getBytes());
                SendResult sendResult = producer.sendMessageInTransaction(msg, tranExecuter, null);
                System.out.println(sendResult);

                Thread.sleep(10);
            }
            catch (MQClientException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < 100000; i++) {
            Thread.sleep(1000);
        }

        producer.shutdown();

    }
}


text:
require 'spec_helper'
require 'rainbow/ext/string'

describe 'String mixin' do

  before do
    Rainbow.enabled = true
  end

  it 'proxies foreground to Rainbow().foreground' do
    expect('hello'.foreground(:red)).to eq(Rainbow('hello').foreground(:red))
  end

  it 'proxies color to Rainbow().color' do
    expect('hello'.color(:red)).to eq(Rainbow('hello').color(:red))
  end

  it 'proxies x11 color to Rainbow().color' do
    expect('hello'.color(:midnightblue)).to eq(Rainbow('hello').color(:midnightblue))
  end

  it 'proxies colour to Rainbow().colour' do
    expect('hello'.colour(:red)).to eq(Rainbow('hello').colour(:red))
  end

  it 'proxies background to Rainbow().background' do
    expect('hello'.background(:red)).to eq(Rainbow('hello').background(:red))
  end

  it 'proxies bright to Rainbow().bright' do
    expect('hello'.bright).to eq(Rainbow('hello').bright)
  end

  it 'proxies italic to Rainbow().italic' do
    expect('hello'.italic).to eq(Rainbow('hello').italic)
  end

  it 'proxies underline to Rainbow().underline' do
    expect('hello'.underline).to eq(Rainbow('hello').underline)
  end

  it 'proxies blink to Rainbow().blink' do
    expect('hello'.blink).to eq(Rainbow('hello').blink)
  end

  it 'proxies inverse to Rainbow().inverse' do
    expect('hello'.inverse).to eq(Rainbow('hello').inverse)
  end

  it 'proxies hide to Rainbow().hide' do
    expect('hello'.hide).to eq(Rainbow('hello').hide)
  end

  it 'proxies reset to Rainbow().reset' do
    expect('hello'.reset).to eq(Rainbow('hello').reset)
  end

  context "when Rainbow is disabled" do

    before do
      Rainbow.enabled = false
    end

    it "allows chaining but doesn't wrap with escape codes" do
      result = 'hello'.
        foreground(:red).
        bright.
        italic.
        background('#ff8040').
        underline.
        color(:blue).
        blink.
        inverse.
        hide

      expect(result).to eq('hello')
    end
  end

end


text:
<?php

declare(strict_types=1);

namespace Blackprism\Serializer\Configuration\Type;

use Blackprism\Serializer\Configuration\TypeInterface;

/**
 * Handler
 *
 * @property HandlerDeserializerInterface $deserializer
 * @property HandlerSerializerInterface $serializer
 */
final class Handler implements TypeInterface
{
    /**
     * @var HandlerDeserializerInterface
     */
    private $deserializer;

    /**
     * @var HandlerSerializerInterface
     */
    private $serializer;

    /**
     * @param HandlerDeserializerInterface $deserializer
     * @param HandlerSerializerInterface $serializer
     */
    public function __construct(HandlerDeserializerInterface $deserializer, HandlerSerializerInterface $serializer)
    {
        $this->deserializer = $deserializer;
        $this->serializer = $serializer;
    }

    /**
     * @return HandlerDeserializerInterface
     */
    public function deserializer(): HandlerDeserializerInterface
    {
        return $this->deserializer;
    }

    /**
     * @return HandlerSerializerInterface
     */
    public function serializer(): HandlerSerializerInterface
    {
        return $this->serializer;
    }
}


text:
<?php

namespace App\Notifications;

use App\Comment;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class NewCommentNotification extends Notification
{
    use Queueable;

    private $comment;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Comment $comment)
    {
        $this->comment = $comment;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'name' => $this->comment->username,
            'id' => $this->comment->commentable->question_id,
         ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}


text:
package com.hortonworks.streamline.common.exception.service.exception.request;

import com.hortonworks.streamline.common.exception.service.exception.WebServiceException;

import javax.ws.rs.core.Response;

public class EntityNotFoundException extends WebServiceException {
  private static final String BY_ID_MESSAGE = "Entity with id [%s] not found.";
  private static final String BY_NAME_MESSAGE = "Entity with name [%s] not found.";
  private static final String BY_FILTER_MESSAGE = "Entity not found for query params [%s].";
  private static final String BY_VERSION_MESSAGE = "Entity with id [%s] and version [%s] not found.";
  private static final String BY_PARSER_SCHEMA_MESSAGE = "Parser schema not found for entity with id [%s].";

  private EntityNotFoundException(String message) {
    super(Response.Status.NOT_FOUND, message);
  }

  private EntityNotFoundException(String message, Throwable cause) {
    super(Response.Status.NOT_FOUND, message, cause);
  }

  public static EntityNotFoundException byId(String id) {
    return new EntityNotFoundException(buildMessageByID(id));
  }

  public static EntityNotFoundException byId(String id, Throwable cause) {
    return new EntityNotFoundException(buildMessageByID(id), cause);
  }

  public static EntityNotFoundException byMessage(String msg) {
    return new EntityNotFoundException(msg);
  }

  public static EntityNotFoundException byName(String name) {
    return new EntityNotFoundException(buildMessageByName(name));
  }

  public static EntityNotFoundException byName(String name, Throwable cause) {
    return new EntityNotFoundException(buildMessageByName(name), cause);
  }

  public static EntityNotFoundException byFilter(String parameter) {
    return new EntityNotFoundException(buildMessageByFilter(parameter));
  }

  public static EntityNotFoundException byFilter(String parameter, Throwable cause) {
    return new EntityNotFoundException(buildMessageByFilter(parameter), cause);
  }

  public static EntityNotFoundException byVersion(String id, String version) {
    return new EntityNotFoundException(buildMessageByVersion(id, version));
  }

  public static EntityNotFoundException byVersion(String id, String version, Throwable cause) {
    return new EntityNotFoundException(buildMessageByVersion(id, version), cause);
  }

  public static EntityNotFoundException byParserSchema(String id) {
    return new EntityNotFoundException(buildMessageByParserSchema(id));
  }

  public static EntityNotFoundException byParserSchema(String id, Throwable cause) {
    return new EntityNotFoundException(buildMessageByParserSchema(id), cause);
  }

  private static String buildMessageByID(String id) {
    return String.format(BY_ID_MESSAGE, id);
  }

  private static String buildMessageByName(String name) {
    return String.format(BY_NAME_MESSAGE, name);
  }

  private static String buildMessageByFilter(String parameter) {
    return String.format(BY_FILTER_MESSAGE, parameter);
  }

  private static String buildMessageByVersion(String id, String version) {
    return String.format(BY_VERSION_MESSAGE, id, version);
  }

  private static String buildMessageByParserSchema(String id) {
    return String.format(BY_PARSER_SCHEMA_MESSAGE, id);
  }
}


text:
describe("Int pointer mapper", function(){
  var IntMapper = require("../../../../../lib/node-blas/native_type_mappers/int_pointer");

  it("writes the int value to a buffer", function(){
    spy = spyOn(Buffer.prototype, "writeInt32LE");
    var pointer = IntMapper.toNative(13);

    expect(spy).toHaveBeenCalledWith(13, 0);
  });

  it("returns a buffer (pointer) instance for an integer", function(){
    var pointer = IntMapper.toNative(13);

    expect(pointer).toEqual(jasmine.any(Buffer));
    expect(pointer.length).toEqual(4);
  });

});


text:
from commands import is_command

if __name__ == "__main__":
    sentences = [
        "tomorrow remind me to do something",
        "tomorrow remnd me to do something",
        "show me the weather",
        "remind me to do something tomorrow",
    ]

    for s in sentences[:]:
        matches = is_command(s)
        print("'{}' is {}a match".format(s, "" if matches else "not "))
        print("> {}".format(matches))
        print()


text:
package main

import (
	"archive/tar"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"path"
	"regexp"
	"strings"
	"time"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-docopt"
	"github.com/flynn/flynn/controller/client"
	ct "github.com/flynn/flynn/controller/types"
	"github.com/flynn/flynn/host/types"
	"github.com/flynn/flynn/pkg/cluster"
	"github.com/flynn/flynn/pkg/exec"
	"github.com/flynn/flynn/pkg/random"
	"github.com/flynn/flynn/pkg/version"
)

var clusterc = cluster.NewClient()

func init() {
	log.SetFlags(0)
}

var typesPattern = regexp.MustCompile("types.* -> (.+)\n")

const blobstoreURL = "http://blobstore.discoverd"
const scaleTimeout = 20 * time.Second

func parsePairs(args *docopt.Args, str string) (map[string]string, error) {
	pairs := args.All[str].([]string)
	item := make(map[string]string, len(pairs))
	for _, s := range pairs {
		v := strings.SplitN(s, "=", 2)
		if len(v) != 2 {
			return nil, fmt.Errorf("invalid var format: %q", s)
		}
		item[v[0]] = v[1]
	}
	return item, nil
}

func main() {
	client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
	if err != nil {
		log.Fatalln("Unable to connect to controller:", err)
	}

	usage := `
Usage: flynn-receiver <app> <rev> [-e <var>=<val>]... [-m <key>=<val>]...

Options:
	-e,--env <var>=<val>
	-m,--meta <key>=<val>
`[1:]
	args, _ := docopt.Parse(usage, nil, true, version.String(), false)

	appName := args.String["<app>"]
	env, err := parsePairs(args, "--env")
	if err != nil {
		log.Fatal(err)
	}
	meta, err := parsePairs(args, "--meta")
	if err != nil {
		log.Fatal(err)
	}

	app, err := client.GetApp(appName)
	if err == controller.ErrNotFound {
		log.Fatalf("Unknown app %q", appName)
	} else if err != nil {
		log.Fatalln("Error retrieving app:", err)
	}
	prevRelease, err := client.GetAppRelease(app.Name)
	if err == controller.ErrNotFound {
		prevRelease = &ct.Release{}
	} else if err != nil {
		log.Fatalln("Error getting current app release:", err)
	}

	fmt.Printf("-----> Building %s...\n", app.Name)

	var output bytes.Buffer
	slugURL := fmt.Sprintf("%s/%s.tgz", blobstoreURL, random.UUID())
	cmd := exec.Command(exec.DockerImage(os.Getenv("SLUGBUILDER_IMAGE_URI")), slugURL)
	cmd.Stdout = io.MultiWriter(os.Stdout, &output)
	cmd.Stderr = os.Stderr
	cmd.Meta = map[string]string{
		"flynn-controller.app":      app.ID,
		"flynn-controller.app_name": app.Name,
		"flynn-controller.release":  prevRelease.ID,
	}
	if len(prevRelease.Env) > 0 {
		stdin, err := cmd.StdinPipe()
		if err != nil {
			log.Fatalln(err)
		}
		go appendEnvDir(os.Stdin, stdin, prevRelease.Env)
	} else {
		cmd.Stdin = os.Stdin
	}
	cmd.Env = make(map[string]string)
	cmd.Env["BUILD_CACHE_URL"] = fmt.Sprintf("%s/%s-cache.tgz", blobstoreURL, app.ID)
	if buildpackURL, ok := prevRelease.Env["BUILDPACK_URL"]; ok {
		cmd.Env["BUILDPACK_URL"] = buildpackURL
	}
	for _, k := range []string{"SSH_CLIENT_KEY", "SSH_CLIENT_HOSTS"} {
		if v := os.Getenv(k); v != "" {
			cmd.Env[k] = v
		}
	}

	if err := cmd.Run(); err != nil {
		log.Fatalln("Build failed:", err)
	}

	var types []string
	if match := typesPattern.FindSubmatch(output.Bytes()); match != nil {
		types = strings.Split(string(match[1]), ", ")
	}

	fmt.Printf("-----> Creating release...\n")

	artifact := &ct.Artifact{Type: "docker", URI: os.Getenv("SLUGRUNNER_IMAGE_URI")}
	if err := client.CreateArtifact(artifact); err != nil {
		log.Fatalln("Error creating artifact:", err)
	}

	release := &ct.Release{
		ArtifactID: artifact.ID,
		Env:        prevRelease.Env,
		Meta:       prevRelease.Meta,
	}
	if release.Meta == nil {
		release.Meta = make(map[string]string, len(meta))
	}
	if release.Env == nil {
		release.Env = make(map[string]string, len(env))
	}
	for k, v := range env {
		release.Env[k] = v
	}
	for k, v := range meta {
		release.Meta[k] = v
	}
	procs := make(map[string]ct.ProcessType)
	for _, t := range types {
		proc := prevRelease.Processes[t]
		proc.Cmd = []string{"start", t}
		if t == "web" || strings.HasSuffix(t, "-web") {
			proc.Ports = []ct.Port{{
				Port:  8080,
				Proto: "tcp",
				Service: &host.Service{
					Name:   app.Name + "-" + t,
					Create: true,
					Check:  &host.HealthCheck{Type: "tcp"},
				},
			}}
		}
		procs[t] = proc
	}
	release.Processes = procs
	if release.Env == nil {
		release.Env = make(map[string]string)
	}
	release.Env["SLUG_URL"] = slugURL

	if err := client.CreateRelease(release); err != nil {
		log.Fatalln("Error creating release:", err)
	}
	if err := client.DeployAppRelease(app.Name, release.ID); err != nil {
		log.Fatalln("Error deploying app release:", err)
	}

	fmt.Println("=====> Application deployed")

	if needsDefaultScale(app.ID, prevRelease.ID, procs, client) {
		formation := &ct.Formation{
			AppID:     app.ID,
			ReleaseID: release.ID,
			Processes: map[string]int{"web": 1},
		}

		watcher, err := client.WatchJobEvents(app.ID, release.ID)
		if err != nil {
			log.Fatalln("Error streaming job events", err)
			return
		}
		defer watcher.Close()

		if err := client.PutFormation(formation); err != nil {
			log.Fatalln("Error putting formation:", err)
		}
		fmt.Println("=====> Waiting for web job to start...")

		err = watcher.WaitFor(ct.JobEvents{"web": {"up": 1}}, scaleTimeout, func(e *ct.Job) error {
			switch e.State {
			case "up":
				fmt.Println("=====> Default web formation scaled to 1")
			case "down", "crashed":
				return fmt.Errorf("Failed to scale web process type")
			}
			return nil
		})
		if err != nil {
			log.Fatalln(err.Error())
		}
	}
}

// needsDefaultScale indicates whether a release needs a default scale based on
// whether it has a web process type and either has no previous release or no
// previous scale.
func needsDefaultScale(appID, prevReleaseID string, procs map[string]ct.ProcessType, client *controller.Client) bool {
	if _, ok := procs["web"]; !ok {
		return false
	}
	if prevReleaseID == "" {
		return true
	}
	_, err := client.GetFormation(appID, prevReleaseID)
	return err == controller.ErrNotFound
}

func appendEnvDir(stdin io.Reader, pipe io.WriteCloser, env map[string]string) {
	defer pipe.Close()
	tr := tar.NewReader(stdin)
	tw := tar.NewWriter(pipe)
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		if err != nil {
			log.Fatalln(err)
		}
		hdr.Name = path.Join("app", hdr.Name)
		if err := tw.WriteHeader(hdr); err != nil {
			log.Fatalln(err)
		}
		if _, err := io.Copy(tw, tr); err != nil {
			log.Fatalln(err)
		}
	}
	// append env dir
	for key, value := range env {
		hdr := &tar.Header{
			Name:    path.Join("env", key),
			Mode:    0644,
			ModTime: time.Now(),
			Size:    int64(len(value)),
		}

		if err := tw.WriteHeader(hdr); err != nil {
			log.Fatalln(err)
		}
		if _, err := tw.Write([]byte(value)); err != nil {
			log.Fatalln(err)
		}
	}
	hdr := &tar.Header{
		Name:    ".ENV_DIR_bdca46b87df0537eaefe79bb632d37709ff1df18",
		Mode:    0400,
		ModTime: time.Now(),
		Size:    0,
	}
	if err := tw.WriteHeader(hdr); err != nil {
		log.Fatalln(err)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace Xunit
{

	public static class ForEachAsyncExtensions
	{

		public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
		{
			return Task.WhenAll(
				from partition in Partitioner.Create(source).GetPartitions(dop)
				select Task.Run(async delegate
				{
					using (partition)
						while (partition.MoveNext())
							await body(partition.Current);
				}));
		}

	}
}


text:
.. _sockets-dumb-http-server-mt-sample:

Socket Multithreaded Dumb HTTP Server
#####################################

Overview
********

The ``sockets/dumb_http_server_mt`` sample application for Zephyr implements a
skeleton HTTP server using a BSD Sockets compatible API.
This sample has similar functionality as :ref:`sockets-dumb-http-server-sample`
except it has support for multiple simultaneous connections, TLS and
IPv6. Also this sample application has no compatibility with POSIX.
This HTTP server example is very minimal and does not really parse an incoming
HTTP request, just reads and discards it, and always serves a single static
page.

The source code for this sample application can be found at:
:zephyr_file:`samples/net/sockets/dumb_http_server_mt`.

Requirements
************

- :ref:`networking_with_host`
- or, a board with hardware networking

Building and Running
********************

Build the Zephyr version of the sockets/dumb_http_server_mt application like
this:

.. zephyr-app-commands::
   :zephyr-app: samples/net/sockets/dumb_http_server_mt
   :board: <board_to_use>
   :goals: build
   :compact:

After the sample starts, it expects connections at 192.0.2.1 or 2001:db8::1,
port 8080. The easiest way to connect is by opening a following URL in a web
browser: http://192.0.2.1:8080/ or http://[2001:db8::1]:8080/
You should see a page with a sample content about Zephyr (captured at a
particular time from Zephyr's web site, note that it may differ from the
content on the live Zephyr site).
Alternatively, a tool like ``curl`` can be used:

.. code-block:: console

    $ curl http://192.0.2.1:8080/

Finally, you can run an HTTP profiling/load tool like Apache Bench
(``ab``) against the server::

    $ ab -n10 http://192.0.2.1:8080/

``-n`` parameter specifies the number of HTTP requests to issue against
a server.


text:
<?php

namespace FileStorage;

class FileStorage{

	private static $_instance;

	private $filesd;

	private $buffer = [];

	private function __construct(FileStorageDriver $filesd){

		$this->filesd = $filesd;
	}

	private function __clone(){}

	public static function getInstance(FileStorageDriver $filesd){

		if (is_null(self::$_instance) || !self::$_instance instanceof self) {

			self::$_instance = new self($filesd);
		}

		return self::$_instance;
	}

	public function set($key , $value , $expire = -1){

		if (!is_int($expire))
			throw new FileStorageException('expire必须为int');

		$this->filesd->set($key , $value , $expire);

		$expire = 0 > $expire ? time() + $expire : $expire;

		$this->buffer[$key] = [$value , $expire];
	}

	public function get($key , $default = null){

		$value = null;

		if (isset($this->buffer[$key][0])) {

			if (!isset($this->buffer[$key][1]) || $this->buffer[$key][1] <= 0 || (time() > $this->buffer[$key][1])) {

				$value = $this->buffer[$key][0];

			}
		} else {

			$value = $this->filesd->get($key , $default);
		}

		return null !== $value ? $value : $default;
	}

	public function delete($key){

		unset($this->buffer[$key]);
		$this->filesd->delete($key);
	}
}
?>


text:
<?php
namespace common\widget\avatar;

use Yii;
use yii\base\Action;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;

class CropAction extends Action
{
    public $config = [];

    public function init()
    {
        //默认配置
        $config = [
            'bigImageWidth' => '200',   //大图宽度
            'bigImageHeight' => '200',  //大图高度
            'middleImageWidth'=> '100', //中图宽度
            'middleImageHeight'=> '100',//中图高度
            'smallImageWidth' => '50',  //小图宽度
            'smallImageHeight' => '50', //小图高度

            'uploadPath' => 'storage/uploads/avatar',//头像上传目录
            'successCallback' => null, //上传成功后的回调
        ];
        $this->config = ArrayHelper::merge($config, $this->config);
        parent::init();
    }

    public function run()
    {
        if (\Yii::$app->getUser()->getIsGuest()) {
            return $this->controller->goHome();
        }

        $model = new UploadForm();

        if (Yii::$app->getRequest()->getIsPost()) {
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            $post = Yii::$app->getRequest()->post();
            $model->avatarData = $post['UploadForm']['avatarData'];
            $model->config = $this->config;
            if ($model->upload()) {
                // 文件上传成功
                if ($this->config['successCallback']) {
                    call_user_func_array($this->config['successCallback'], [
                        'avatar' => $model->imageUrl,
                    ]);
                }
                return json_encode(['state'=>200,'message'=>'上传成功!','result'=>$model->imageUrl]);
            }
        }
        return true;
    }
}


text:
"use strict";

const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const impl = utils.implSymbol;

function DOMParser() {
  const args = [];
  for (let i = 0; i < arguments.length && i < 0; ++i) {
    args[i] = utils.tryImplForWrapper(arguments[i]);
  }

  iface.setup(this, args);
}

DOMParser.prototype.parseFromString = function parseFromString(str, type) {
  if (!this || !module.exports.is(this)) {
    throw new TypeError("Illegal invocation");
  }
  if (arguments.length < 2) {
    throw new TypeError("Failed to execute 'parseFromString' on 'DOMParser': 2 arguments required, but only " + arguments.length + " present.");
  }
  const args = [];
  for (let i = 0; i < arguments.length && i < 2; ++i) {
    args[i] = utils.tryImplForWrapper(arguments[i]);
  }
  args[0] = conversions["DOMString"](args[0]);
  return utils.tryWrapperForImpl(this[impl].parseFromString.apply(this[impl], args));
};

DOMParser.prototype.toString = function () {
  if (this === DOMParser.prototype) {
    return "[object DOMParserPrototype]";
  }
  return this[impl].toString();
};

const iface = {
  mixedInto: [],
  is(obj) {
    if (obj) {
      if (obj[impl] instanceof Impl.implementation) {
        return true;
      }
      for (let i = 0; i < module.exports.mixedInto.length; ++i) {
        if (obj instanceof module.exports.mixedInto[i]) {
          return true;
        }
      }
    }
    return false;
  },
  isImpl(obj) {
    if (obj) {
      if (obj instanceof Impl.implementation) {
        return true;
      }

      const wrapper = utils.wrapperForImpl(obj);
      for (let i = 0; i < module.exports.mixedInto.length; ++i) {
        if (wrapper instanceof module.exports.mixedInto[i]) {
          return true;
        }
      }
    }
    return false;
  },
  create(constructorArgs, privateData) {
    let obj = Object.create(DOMParser.prototype);
    this.setup(obj, constructorArgs, privateData);
    return obj;
  },
  createImpl(constructorArgs, privateData) {
    let obj = Object.create(DOMParser.prototype);
    this.setup(obj, constructorArgs, privateData);
    return utils.implForWrapper(obj);
  },
  _internalSetup(obj) {
  },
  setup(obj, constructorArgs, privateData) {
    if (!privateData) privateData = {};
    privateData.wrapper = obj;

    this._internalSetup(obj);

    obj[impl] = new Impl.implementation(constructorArgs, privateData);
    obj[impl][utils.wrapperSymbol] = obj;
  },
  interface: DOMParser,
  expose: {
    Window: { DOMParser: DOMParser }
  }
};
module.exports = iface;

const Impl = require("../domparsing/DOMParser-impl.js");


text:
export enum StructureGrade {
  Weak,
  Moderate,
  Strong
}