text:
package tomdrever.timetable.android.controllers;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tomdrever.timetable.R;
import tomdrever.timetable.android.controllers.base.BaseController;
import tomdrever.timetable.data.Timetable;

public class TimetableListController extends BaseController {

    private ArrayList<Timetable> timetables;

    private TimetableListAdapter adapter;

    @BindView(R.id.timetables_list_recyclerview) RecyclerView recyclerView;
    @BindView(R.id.no_timetables) TextView noTimetablesTextView;

    @Override
    protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
        return inflater.inflate(R.layout.controller_timetable_list, container, false);
    }

    @Override
    protected void onViewBound(@NonNull View view) {
        super.onViewBound(view);

        timetables = getFileManager().loadAll();

        updateNoTimetablesTextView();

        adapter = new TimetableListAdapter(LayoutInflater.from(view.getContext()));

        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        recyclerView.setAdapter(adapter);

        // region Swiping
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.UP | ItemTouchHelper.DOWN,
                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            @Override
            public boolean isItemViewSwipeEnabled() { return true; }

            @Override
            public boolean isLongPressDragEnabled() { return false; }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                // Store timetable data temporarily, so it can be restored
                final Timetable tempTimetable = timetables.get(viewHolder.getAdapterPosition());
                final int tempPosition = viewHolder.getAdapterPosition();
                removeTimetableAt(tempPosition);
                Snackbar.make(viewHolder.itemView, tempTimetable.getName() + " deleted", Snackbar.LENGTH_SHORT).setAction("Undo", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Restore
                        addTimetableAt(tempTimetable, tempPosition);
                    }
                }).show();
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();

                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        swapTimetablesAt(i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        swapTimetablesAt(i, i - 1);
                    }
                }

                adapter.notifyItemMoved(fromPosition, toPosition);

                return true;
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
        // endregion
    }

    private void addTimetableAt(Timetable timetable, int position) {
        getFileManager().save(timetable);
        timetables.add(position, timetable);
        adapter.notifyItemInserted(position);

        updateNoTimetablesTextView();
    }

    private void removeTimetableAt(int position) {
        getFileManager().delete(timetables.get(position).getId());
        timetables.remove(position);
        adapter.notifyItemRemoved(position);

        updateNoTimetablesTextView();
    }

    private void swapTimetablesAt(int position1, int position2) {
        Timetable timetable1 = timetables.get(position1);
        timetable1.setIndex(position2);
        getFileManager().save(timetable1);

        Timetable timetable2 = timetables.get(position2);
        timetable2.setIndex(position1);
        getFileManager().save(timetable2);

        timetables.set(position1, timetable2);
        timetables.set(position2, timetable1);
    }

    private void updateNoTimetablesTextView() {
        if (timetables.isEmpty())
            noTimetablesTextView.setVisibility(View.VISIBLE);
        else
            noTimetablesTextView.setVisibility(View.INVISIBLE);
    }

    @Override
    protected String getTitle() {
        return "Timetables";
    }

    @Override
    public boolean handleBack() {
        getActivity().finish();

        return true;
    }

    @Override
    protected void onSave(Bundle outState) {
        outState.putParcelableArrayList("timetables", timetables);
    }

    @Override
    protected void onRestore(Bundle inState) {
        timetables = inState.getParcelableArrayList("timetables");
    }

    @OnClick(R.id.new_timetable_fab)
    void onFabClick() {
        getRouter().pushController(RouterTransaction.with(new EditTimetableController(timetables.size()))
                .popChangeHandler(new FadeChangeHandler())
                .pushChangeHandler(new FadeChangeHandler()));
    }

    public class TimetableListAdapter extends RecyclerView.Adapter<TimetableListAdapter.TimetableViewHolder> {
        private final LayoutInflater inflater;

        public TimetableListAdapter(LayoutInflater inflater) {
            this.inflater = inflater;
        }

        @Override
        public TimetableViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new TimetableViewHolder(inflater.inflate(R.layout.view_card_view_timetable, parent, false));
        }

        @Override
        public void onBindViewHolder(TimetableViewHolder holder, int position) {
            holder.bind(timetables.get(position));
        }

        @Override
        public int getItemCount() {
            return timetables.size();
        }

        public class TimetableViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.timetable_card_name) TextView nameTextView;
            @BindView(R.id.timetable_card_description) TextView descriptionTextView;

            Timetable timetable;

            public TimetableViewHolder(View itemView) {
                super(itemView);

                ButterKnife.bind(this, itemView);
            }

            public void bind(Timetable item) {
                this.timetable = item;

                nameTextView.setText(timetable.getName());
                descriptionTextView.setText(timetable.getDescription());

                if (timetable.getDescription().trim().isEmpty()) {
                    // TODO - change timetable card height?
                    descriptionTextView.setVisibility(View.GONE);
                } else {
                    descriptionTextView.setVisibility(View.VISIBLE);
                }
            }

            @OnClick(R.id.timetable_card_base_view)
            void onCardClicked() {
                getRouter().pushController(RouterTransaction.with(new ViewTimetableController(timetable))
                        .popChangeHandler(new FadeChangeHandler())
                        .pushChangeHandler(new FadeChangeHandler()));
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Amazonas</logradouro><bairro>Caravelas</bairro><cidade>Ipatinga</cidade><uf>MG</uf><cep>35164286</cep></feed>

redpajama_set_name: RedPajamaGithub


text:
using DebuggerApi;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using System;
using System.Threading;
using System.Threading.Tasks;
using YetiCommon;
using YetiCommon.CastleAspects;
using YetiVSI.DebugEngine.AsyncOperations;
using YetiVSI.DebugEngine.Interfaces;

namespace YetiVSI.DebugEngine
{
    public interface IDebugExpression : IDebugExpression2, IDebugExpression157
    {
    }

    public interface IDebugExpressionFactory
    {
        IDebugExpression Create(RemoteFrame frame, string text,
                                IDebugEngineHandler debugEngineHandler,
                                IGgpDebugProgram debugProgram, IDebugThread2 thread);
    }

    public class DebugAsyncExpression : SimpleDecoratorSelf<IDebugExpression>, IDebugExpression
    {
        public class Factory : IDebugExpressionFactory
        {
            readonly AsyncExpressionEvaluator.Factory _asyncEvaluatorFactory;
            readonly ITaskExecutor _taskExecutor;

            [Obsolete("This constructor only exists to support mocking libraries.", error: true)]
            protected Factory()
            {
            }

            public Factory(AsyncExpressionEvaluator.Factory asyncEvaluatorFactory,
                           ITaskExecutor taskExecutor)
            {
                _asyncEvaluatorFactory = asyncEvaluatorFactory;
                _taskExecutor = taskExecutor;
            }

            public virtual IDebugExpression Create(RemoteFrame frame, string text,
                                                   IDebugEngineHandler debugEngineHandler,
                                                   IGgpDebugProgram debugProgram,
                                                   IDebugThread2 thread)
            {
                var evaluator = _asyncEvaluatorFactory.Create(debugProgram.Target, frame, text);
                return new DebugAsyncExpression(debugEngineHandler, evaluator, _taskExecutor,
                                                debugProgram, thread);
            }
        }

        readonly IGgpDebugProgram _program;
        readonly IDebugThread2 _thread;

        readonly IDebugEngineHandler _debugEngineHandler;
        readonly IAsyncExpressionEvaluator _asyncEvaluator;
        readonly ITaskExecutor _taskExecutor;

        DebugAsyncExpression(IDebugEngineHandler debugEngineHandler,
                             IAsyncExpressionEvaluator asyncEvaluator, ITaskExecutor taskExecutor,
                             IGgpDebugProgram program, IDebugThread2 thread)
        {
            _debugEngineHandler = debugEngineHandler;
            _asyncEvaluator = asyncEvaluator;
            _taskExecutor = taskExecutor;
            _program = program;
            _thread = thread;
        }

        public int Abort() => VSConstants.E_NOTIMPL;

        public int EvaluateAsync(enum_EVALFLAGS flags, IDebugEventCallback2 callback)
        {
            Task Evaluate() =>
                _taskExecutor.SubmitAsync(async () =>
                {
                    EvaluationResult evalResult = await _asyncEvaluator.EvaluateExpressionAsync();
                    _debugEngineHandler.OnEvaluationComplete(
                        Self, evalResult.Result, _program, _thread);
                }, CancellationToken.None, nameof(EvaluateAsync), typeof(DebugAsyncExpression));

            SafeErrorUtil.SafelyLogErrorAndForget(Evaluate,
                                                  "EvaluateAsync: error evaluating " +
                                                  "expression asynchronously");

            return VSConstants.S_OK;
        }

        public int EvaluateSync(enum_EVALFLAGS flags, uint timeout, IDebugEventCallback2 callback,
                                out IDebugProperty2 result)
        {
            EvaluationResult evalResult =
                _taskExecutor.Run(async () => await _asyncEvaluator.EvaluateExpressionAsync());
            result = evalResult.Result;
            return evalResult.Status;
        }

        public int GetEvaluateAsyncOp(uint dwFields, uint dwRadix, uint dwFlags, uint dwTimeout,
                                      IAsyncDebugEvaluateCompletionHandler pCompletionHandler,
                                      out IAsyncDebugEngineOperation ppDebugOperation)
        {
            ppDebugOperation = new AsyncEvaluateExpressionOperation(pCompletionHandler,
                                                                    _asyncEvaluator, _taskExecutor);
            return VSConstants.S_OK;
        }
    }
}


text:
<?php

namespace Lego\Foundation\Exceptions;

class NotSupportedException extends LegoException
{
    protected $message = 'Feature not support yet.';
}


text:
using System;

namespace Nucleo.EventsManagement.Listeners
{
	/// <summary>
	/// Represents a listener critera for text identifiers.
	/// </summary>
	public class NameIdentifierListenerCriteria : IListenerCriteria
	{
		private string _identifier = null;

		#region " Properties "

		/// <summary>
		/// Gets the identifier.
		/// </summary>
		public string Identifier
		{
			get { return _identifier; }
		}

		#endregion

		#region " Constructors "

		/// <summary>
		/// Creates the identifier.
		/// </summary>
		/// <param name="identifier">The identifying string.</param>
		/// <exception cref="ArgumentNullException">Thrown when the identifier is empty or null.</exception>
		public NameIdentifierListenerCriteria(string identifier)
		{
			if (string.IsNullOrEmpty(identifier))
				throw new ArgumentNullException("identifier");

			_identifier = identifier;
		}

		#endregion

		#region " Methods "

		public virtual bool IsMatch(IListenerCriteria criteria)
		{
			if (criteria is NameIdentifierListenerCriteria)
				return (string.Compare(this.Identifier, ((NameIdentifierListenerCriteria)criteria).Identifier, StringComparison.OrdinalIgnoreCase) == 0);
			else if (criteria is EventListenerCriteria)
				return (string.Compare(this.Identifier, ((EventListenerCriteria)criteria).Event.Name, StringComparison.OrdinalIgnoreCase) == 0);
			else if (criteria is AnyListenerCriteria)
				return true;

			return false;
		}

		public override string ToString()
		{
			return "Identifier set to " + Identifier;
		}

		#endregion
	}
}


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

<title>WithWriteLock (Groovy 2.1.7)</title>
<meta name="date" content="2013-09-05">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element

groovy.transform

Annotation Type WithWriteLock

@Documented
@Retention(value=SOURCE)
@Target(value=METHOD)
public @interface WithWriteLock

This annotation is used in conjunction with WithReadLock to support read and write synchronization on a method.

 To use this annotation, declare @WithWriteLock on your method. The method may be either an instance method or
 a static method. The resulting method will allow only one thread access to the method at a time, and will wait to access
 the method until any other read locks have been released.

 This annotation is a declarative wrapper around the JDK's java.util.concurrent.locks.ReentrantReadWriteLock.
 Objects containing this annotation will have a ReentrantReadWriteLock field named $reentrantLock added to the class,
 and method access is protected by the lock. If the method is static then the field is static and named $REENTRANTLOCK.

 The annotation takes an optional parameter for the name of the field. This field must exist on the class and must be
 of type ReentrantReadWriteLock.

 To understand how this annotation works, it is convenient to think in terms of the source code it replaces. The following
 is a typical usage of this annotation from Groovy:

 import groovy.transform.*;

 public class ResourceProvider {

     private final Map<String, String> data = new HashMap<String, String>();

    @WithReadLock
     public String getResource(String key) throws Exception {
             return data.get(key);
     }

    @WithWriteLock
     public void refresh() throws Exception {
             //reload the resources into memory
     }
 }

 As part of the Groovy compiler, code resembling this is produced:

 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import java.util.concurrent.locks.ReadWriteLock;

 public class ResourceProvider {

     private final ReadWriteLock $reentrantlock = new ReentrantReadWriteLock();
     private final Map<String, String> data = new HashMap<String, String>();

     public String getResource(String key) throws Exception {
         $reentrantlock.readLock().lock();
         try {
             return data.get(key);
         } finally {
             $reentrantlock.readLock().unlock();
         }
     }

     public void refresh() throws Exception {
         $reentrantlock.writeLock().lock();
         try {
             //reload the resources into memory
         } finally {
             $reentrantlock.writeLock().unlock();
         }
     }
 }

Since:

1.8.0

Author:

Hamlet D'Arcy

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

String
value

Element Detail

value

public abstract String value

Returns:

if a user specified lock object with the given name should be used
      the lock object must exist. If the annotated method is static then the
      lock object must be static. If the annotated method is not static then
      the lock object must not be static.

Default:

""

Overview

Package

Class

Tree

Deprecated

Index

Help

Copyright &copy; 2003-2013 The Codehaus. All rights reserved.

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element


text:
from django.contrib.sites.models import Site

def site(request):
    return {
        'site': Site.objects.get_current()
    }


text:
import {Component, View} from 'angular2/core';

import {AccordionGroup} from './accordion-group.component';

@Component({
  selector: 'accordion, [accordion]',
  host: {
    'class': 'panel-group'
  }
})
@View({
  template: '<ng-content></ng-content>'
})
export class Accordion {
  private groups: Array<AccordionGroup> = [];

  addGroup(group: AccordionGroup): void {
    this.groups.push(group);
  }

  closeOthers(openGroup: AccordionGroup): void {
    this.groups.forEach((group: AccordionGroup) => {
      if (group !== openGroup) {
        group.isOpen = false;
      }
    });
  }

  removeGroup(group: AccordionGroup): void {
    const index = this.groups.indexOf(group);
    if (index !== -1) {
      this.groups.splice(index, 1);
    }
  }
}


text:
package net.herit.business.api;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import net.herit.business.api.service.ApiHdmDAO;
import net.herit.business.api.service.ApiHdpDAO;
import net.herit.business.api.service.DatabaseService;
import net.herit.business.api.service.FileUploadVO;
import net.herit.business.api.service.LWM2MApiService;
import net.herit.business.api.service.OneM2MApiService;
import net.herit.business.api.service.OpenApiService;
import net.herit.business.api.service.TR069ApiService;
import net.herit.business.device.service.DeviceModelVO;
import net.herit.business.device.service.DeviceVO;
import net.herit.business.device.service.ExtMoProfileVO;
import net.herit.business.device.service.MoProfileVO;
import net.herit.business.device.service.ParameterVO;
import net.herit.business.firmware.service.FirmwareDAO;
import net.herit.business.firmware.service.FirmwareService;
import net.herit.business.protocol.HttpConnector;
import net.herit.business.protocol.Util;
import net.herit.business.protocol.tr069.CurlOperation;
import net.herit.common.conf.HeritProperties;
import net.herit.common.exception.UserSysException;
import net.herit.common.model.ErrorVO;
import net.herit.common.model.HeritFormBasedFileVO;
import net.herit.common.util.HeritFileUploadUtil;
import net.herit.common.util.PagingUtil;
import net.herit.security.dto.GroupAuthorization;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.poi.util.IOUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;

import com.oreilly.servlet.MultipartRequest;

@Controller
@RequestMapping(value = "/api")
public class ApiController {

	@Resource(name = "DatabaseService")
	private DatabaseService databaseService;
	@Resource(name = "OpenApiService")
	private OpenApiService openApiService;
	@Resource(name = "LWM2MApiService")
	private LWM2MApiService lwm2mApiService;
	@Resource(name = "TR069ApiService")
	private TR069ApiService tr069ApiService;
	@Resource(name = "ApiHdmDAO")
	private ApiHdmDAO hdmDAO;
	@Resource(name="ApiHdpDAO")
	private ApiHdpDAO hdpDAO;
	@Resource(name = "FirmwareService")
	private FirmwareService firmwareService;
	@Resource(name = "FirmwareDAO")
	private FirmwareDAO fdao;

	/** 이미지경로를 위한 URL */
	private final String hostUrl = HeritProperties
			.getProperty("Globals.hostUrl");
	/** 톰캣 위치 지정 */
	private final String tomcatDir = HeritProperties
			.getProperty("Globals.tomcatDir");
	/** 첨부파일 위치 지정 */
	private final String uploadDir = HeritProperties
			.getProperty("Globals.uploadDir");

	private final String firmwareDir = HeritProperties
			.getProperty("Globals.firmwareDir");

	private final long maxFileSize = 1024 * 1024 * 100;

	public final static String INVALID_PARAM = "101";
	public final static String DUPLICATED_DEVICE_ID = "102";

	@ResponseBody
	@RequestMapping(value = "/{system}/{domain}/{data}/{operation}")
	public Map<String, Object> get(@PathVariable("system") String system,
			@PathVariable("domain") String domain,
			@PathVariable("data") String data,
			@PathVariable("operation") String operation,
			HttpServletRequest request) throws Exception {

		//System.out.println("##### get in! "+system+"/"+domain+"/"+data+"/"+operation);
		Map<String, Object> response = new HashMap<String, Object>();

		HashMap<String, Object> param = new HashMap<String, Object>();

		// URL Sample: /hdp/deviceModel/info/get
		// URL Sample: /hdm/device/info/list
		/*
		 * HttpSession session = request.getSession(false); if(session != null){
		 * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization)
		 * session.getAttribute("requestAuth");
		 * if(!requestAuth.getAuthorizationDBRead().equals("1")){
		 *
		 * response.put("result", 505); response.put("errorCode", 505);
		 * response.put("content", "Permission denied");
		 * response.put("parameter", param); return response; } }
		 */
		Enumeration names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			param.put(name, value);
		}
		//System.out.println(param);

		try {

			Map<String, Object> content = databaseService.execute(system,
					domain, data, operation, param);
			//System.out.println(content);

			response.put("result", 0);
			response.put("errorCode", 0);
			response.put("content", content);
			response.put("parameter", param);

		} catch (UserSysException ex) {
			ex.printStackTrace();
			ErrorVO err = ex.getErrorVO();
			response.put("result", 1);
			response.put("errorCode", err.getErrorCode());
			response.put("content", err.getErrorMessage());
			response.put("parameter", param);

		} catch (Exception ex) {
			ex.printStackTrace();
			response.put("result", 1);
			response.put("errorCode", -1);
			response.put("content", ex.toString());
			response.put("exception", ex);
			response.put("parameter", param);
		}

		return response;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value = "/{system}/{domain}/{operation}")
	public Map<String, Object> execute(
			@RequestBody String bodyString,
			@PathVariable("system") String system,
			@PathVariable("domain") String domain,
			@PathVariable("operation") String operation,
			HttpServletRequest request) throws Exception {

		//System.out.println("##### get in222! "+system+"/"+domain+"/"+operation);

		Map<String, Object> response = new HashMap<String, Object>();
		HashMap<String, String> param = new HashMap<String, String>();
		/*
		 * HttpSession session = request.getSession(false); if(session != null){
		 * //페이지 권한 확인 GroupAuthorization requestAuth = (GroupAuthorization)
		 * session.getAttribute("requestAuth");
		 * if(!requestAuth.getAuthorizationDBRead().equals("1")){
		 *
		 * response.put("result", 505); response.put("errorCode", 505);
		 * response.put("content", "Permission denied");
		 * response.put("parameter", param); return response; } }
		 */

		Enumeration names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			param.put(name, value);
		}

		//TODO:body 안에 있는 정보를 가져와야 햄.
		HashMap<String, Object> contentMap = new ObjectMapper().readValue(bodyString, HashMap.class);

		String deviceId = contentMap.containsKey("d") ? (String) contentMap.get("d") : null;
		if (deviceId == null || "".equals(deviceId)) {
			/** oneM2M 서버에서 검색 */
			if (operation.equals("discovery")) {
				String sn = (String) contentMap.get("sn");

				OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance();
				HashMap<String, Object> content = oneM2MSvc.discovery(operation, sn);

				ArrayList<HashMap<String, String>> eList = new ArrayList<HashMap<String,String>>();
				LinkedHashMap<String, Object> snContent = new LinkedHashMap<String, Object>();

				snContent.put("o", "d");
				snContent.put("r", "200");//XXX
				snContent.put("devId", content);

				response.put("result", 0);
				response.put("content", snContent);
				//System.out.println("response (discovery) : " + response.toString());
				return response;
			}
		}

		//System.out.println("deviceId:" + deviceId);
		//System.out.println("WHY");
		DeviceVO deviceInfo = hdmDAO.getDeviceInfo(deviceId);

		//System.out.println("deviceInfo is null? : " + deviceInfo == null);

		int dmType = deviceInfo.getDmType();
		String extDeviceId = deviceInfo.getExtDeviceId();
		String modelName = deviceInfo.getModelName();
		DeviceModelVO deviceModelInfo = hdpDAO.getDeviceModelId(modelName);
		String deviceModelId = deviceModelInfo.getId();
		//System.out.println("dmType : " + dmType);
		//System.out.println("extDeviceId : " + extDeviceId);
		//System.out.println("modelName : " + modelName);
		//System.out.println("deviceModelId : " + deviceModelId);

		//System.err.println("#########################################");
		//System.err.println("   TEST :: dmType :: "+dmType);
		//System.err.println("#########################################");

		String body = null;
		if (dmType == 0) {
			try {

				// body = getBody(request);
				HashMap<String, Object> content = openApiService.execute(operation, bodyString);

				//System.err.println(content.toString());
				if (content.get("exception") == null
						&& (Integer) content.get("status") == 200) {
					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
				} else if (content.get("exception") == null
						&& (Integer) content.get("status") != 200) {
					response.put("result", 1);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
				} else {
					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("exception").toString());
					// response.put("exception", content.get("exception"));
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
					// response.put("json", content.get("json"));
				}

			} catch (UserSysException ex) {
				ErrorVO err = ex.getErrorVO();
				response.put("result", 1);
				response.put("errorCode", err.getErrorCode());
				response.put("content", err.getErrorMessage());
				response.put("parameter", param);

			} catch (Exception ex) {
				response.put("result", 1);
				response.put("errorCode", -1);
				response.put("content", ex.toString());
				response.put("exception", ex);
				response.put("requestBody", body);
			}
		} else if (dmType == 1) {//oneM2M서버
			try {
				//body data
				ArrayList<HashMap<String, String>> resourceList = contentMap.containsKey("e") ? (ArrayList<HashMap<String,String>>) contentMap.get("e") : null;
				if (resourceList == null || resourceList.isEmpty()) {
					// 예외처리
				}
				//System.out.println("e:" + resourceList.toString());

				ArrayList<String> resUris = new ArrayList<String>();
				String executeCont = null;
				for (int i=0; i < resourceList.size(); i++) {
					//System.out.println("contentList:" + resourceList.get(i));

					HashMap<String, String> resUri = resourceList.get(i);
					String resource = resUri.get("n");
					//System.out.println("resource:" + resource);

					//execute 명령에 대한 웹 제어 데이터
					executeCont = resUri.get("sv");
					//System.out.println("executeCont:" + executeCont);

					MoProfileVO moProfileInfo = hdpDAO.getMoProfileId(deviceModelId, resource);
					String moProfileId = moProfileInfo.getId();
					//System.out.println("moProfileId : " + moProfileId);

					ExtMoProfileVO extInfo = hdpDAO.getResUriNameInfo(moProfileId);
					//System.out.println("extInfo:" + extInfo.getExtResourceUri());

					String resourceUri = extDeviceId +"/"+ extInfo.getExtResourceUri();
					//System.out.println("resourceUri:" + resourceUri);

					resUris.add(resourceUri);
				}

				//System.out.println("resUris:" + resUris.toString());

				//oneM2M 서버
				OneM2MApiService oneM2MSvc = OneM2MApiService.getInstance();
				HashMap<String, Object> content = oneM2MSvc.execute(operation, resUris, extDeviceId, executeCont);

				//dm서버와 같은 데이터 형식으로 만들어서 구현
				ArrayList<String> to = new ArrayList<String>();
				ArrayList<String> ct = new ArrayList<String>();
 				for(int j=0; j < resUris.size(); j++) {
					to.add((String) content.get(resUris.get(j)));
					ct.add((String) content.get(resUris.get(j)+"_"+j));
					//System.out.println(resUris.get(j) + content.get(resUris.get(j)));
					//System.out.println(resUris.get(j)+"_"+j + content.get(resUris.get(j)+"_"+j));
				}

				ArrayList<HashMap<String, String>> eList = new ArrayList<HashMap<String,String>>();

				LinkedHashMap<String, Object> resContent = new LinkedHashMap<String, Object>();
				HashMap<String, String> resDatas = new HashMap<String, String>();

				resContent.put("o", (String)content.get("o"));
				resContent.put("r", "200");//XXX
				for(int k=0; k < resourceList.size(); k++) {
					resDatas = resourceList.get(k);
					String resData = resDatas.get("n");
					HashMap<String, String> dataMap = new HashMap<String, String>();
					dataMap.put("n", resData);
					dataMap.put("sv", to.get(k));
					dataMap.put("ti", ct.get(k));
					eList.add(dataMap);
				}
				resContent.put("e", eList);
				/*ObjectMapper mapper = new ObjectMapper();
				Object json = mapper.writeValueAsString(resContent);*/
				response.put("result", 0);
				response.put("errorCode", "200");
				response.put("content", resContent);

				////System.out.println("=================" + response.toString());

			} catch (Exception ex) {
				//System.out.println("ex :" + ex);
			}
		} else if (dmType == 2) { // LWM2M Server
			try {

				String op = "r";
				if(operation.equals("write")){
					op = "e";
				} else if(operation.equals("reboot")) {
					op = "rb";
				}
				contentMap.put("o", op);
				HashMap<String, Object> content = lwm2mApiService.execute(operation, contentMap, deviceInfo.getAuthId());

				//*
				if (content.get("exception") == null
						&& (Integer) content.get("status") == 200) {
					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
				} else if (content.get("exception") == null
						&& (Integer) content.get("status") != 200) {
					response.put("result", 1);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
				} else {
					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("exception").toString());
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
				}//*/

				//System.out.println("CONTENT : " + content.toString());
				//System.out.println("RESPONSE : " + response);

			} catch (UserSysException ex) {
				ex.printStackTrace();

				ErrorVO err = ex.getErrorVO();
				response.put("result", 1);
				response.put("errorCode", err.getErrorCode());
				response.put("content", err.getErrorMessage());
				response.put("parameter", param);

			} catch (Exception ex) {
				ex.printStackTrace();

				response.put("result", 1);
				response.put("errorCode", -1);
				response.put("content", ex.toString());
				response.put("exception", ex);
				response.put("requestBody", body);
			}

		} else if (dmType == 3) { // TR-069 Server

			//System.out.println("##### operation : "+operation);
			//System.out.println("##### bodyString : "+bodyString);
			//System.out.println("##### contentMap : "+contentMap);

			HashMap<String, Object> content = null;

			try{
				content = tr069ApiService.execute(operation, new JSONObject(bodyString));
				//System.out.println("::::::::::::::::::::::::::::::::::");
				//System.out.println(content);
				if (content.get("exception") == null && (Integer) content.get("status") == 200) {

					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
				} else if (content.get("exception") == null && (Integer) content.get("status") != 200) {
					response.put("result", 1);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("json"));
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
				} else {
					response.put("result", 0);
					response.put("errorCode", content.get("status"));
					response.put("content", content.get("exception").toString());
					response.put("requestBody", body);
					response.put("responseBody", content.get("body"));
				}
			} /*catch (UserSysException ex) {
				ex.printStackTrace();
				//System.out.println(ex);
				ErrorVO err = ex.getErrorVO();
				response.put("result", 1);
				response.put("errorCode", err.getErrorCode());
				response.put("content", err.getErrorMessage());
				response.put("parameter", param);

			}*/ catch (Exception ex) {
				ex.printStackTrace();
				//System.out.println(ex);
				response.put("result", 1);
				response.put("errorCode", -1);
				response.put("content", ex.toString());
				response.put("exception", ex);
				response.put("requestBody", body);
			}

			//System.out.println("[ CONTENT_OUT ] : "+content);
			//System.out.println("[ RESPONSE_OUT ] : "+response);

		}

		return response;
	}

	// HERE FIRMWARE VERSION INSERT, UPDATE
	@ResponseBody
	@RequestMapping(value = "/{system}/{domain}/upload")
	public String uploadFirmware(
		@PathVariable("system") String system,
		@PathVariable("domain") String domain,
		HttpServletRequest request) {
		//throws Exception {

		String returnMsg = "success";
		Map<String, Object> response = new HashMap<String, Object>();

		try{
			//System.out.println("##### get in444! "+system+"/"+domain);

			String savePath = "";
			//System.out.println(firmwareDir);
			//System.out.println(tomcatDir+uploadDir);
			//System.out.println("ddddddddd3333");

			MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
			String originalFileName = mptRequest.getFile("packageName").getOriginalFilename();
			//System.out.println(originalFileName);
			File dir = new File(originalFileName);

			if (!dir.exists()) {
				dir.mkdir();
			}

			String directory = null;
			int fileType = Integer.parseInt(mptRequest.getParameter("fileType").substring(0, mptRequest.getParameter("fileType").indexOf(" ")));
			if( fileType == 1 ){
				directory = firmwareDir;
			} else {
				directory = tomcatDir+uploadDir;
			}

			//System.out.println("middle test : " +dir);
			List<HeritFormBasedFileVO> result = HeritFileUploadUtil.filesUpload(request, directory, maxFileSize);
			//System.out.println(result.size());

			String res = null;
			HttpConnector hc = new HttpConnector();
			res = hc.sendFile(mptRequest);
			//System.out.println("---- res : "+res);
			/*
			hc.sendFileWithCurl();

			if( result.size() > 0 ){

				CurlOperation co = new CurlOperation();
				co.setHeader("fileType", mptRequest.getParameter("fileType"));
				co.setHeader("oui", mptRequest.getParameter("oui"));
				co.setHeader("productClass", mptRequest.getParameter("productClass"));
				co.setHeader("version", mptRequest.getParameter("version"));

				Object[] params = new Object[3];
				params[0] = "http://"+HeritProperties.getProperty("Globals.tr069ServerHost")+":"+HeritProperties.getProperty("Globals.tr069ServerPort");
				params[1] = co.getHeader();
				params[2] = firmwareDir+dir.getName();

				res = co.send("file upload", params);
				//System.out.println(res);
			}*/

			if(res != null && res.indexOf("201") > -1){
				int deviceModelId = Integer.parseInt(mptRequest.getParameter("deviceModel"));
				//long fileSize = dir.length();
				long fileSize = result.get(0).getSize();
				//System.out.println("######################## file size ");
				//System.out.println(fileSize);
				int fwId = 0;
				String fileName = originalFileName;
				String version = mptRequest.getParameter("version");
				String description = mptRequest.getParameter("description");

				fwId = fdao.getFirmwareId(deviceModelId, fileType);
				int fvCount = 0;
				if(fwId == 0){
					fwId = fdao.addFirmwareInfo(deviceModelId, fileName, fileType, description);
					fdao.addFirmwareVersion(fwId, version, fileSize);
				} else {
					fvCount = fdao.getFirmwareVersionCount(fwId, mptRequest.getParameter("version"));
					if(fvCount == 0){
						fdao.addFirmwareVersion(fwId, version, fileSize);
					}
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			returnMsg = ex.getMessage();
		}

		return returnMsg;
	}

	// HERE FIRMWARE VERSION INSERT, UPDATE
	@ResponseBody
	@RequestMapping(value = "/{system}/{domain}/{data}/upload")
	public Map<String, Object> upload(
			@PathVariable("system") String system,
			@PathVariable("domain") String domain,
			@PathVariable("data") String data, HttpServletRequest request)
			throws Exception {

		//System.out.println("##### get in333! "+system+"/"+domain+"/"+data);

		Map<String, Object> response = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();

		Enumeration names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			//System.out.println("name value : " + name + " , " + value);
			param.put(name, value);
		}

		FileUploadVO fileUploadVO = new FileUploadVO();

		List<FileUploadVO> fileUploadList = new ArrayList();

		// List<HeritFormBasedFileVO> list =
		// HeritFileUploadUtil.filesUpload(request, fileDir, maxFileSize);
		String fileUploadDir = "";

		List<HeritFormBasedFileVO> list = null;
		if (domain.equalsIgnoreCase("firmware")) {

			String dirPackageName = (String) param.get("packageName");
			//System.out.println("dirPackageName : " + dirPackageName);
			File dir = new File(dirPackageName);

			if (!dir.exists()) {
				dir.mkdir();
			}

			String fileDir = firmwareDir + dir;
			//System.out.println("fileDir " + fileDir);

			fileUploadDir = firmwareDir;
			list = HeritFileUploadUtil.filesUpload(request, fileDir,
					maxFileSize);
		} else {
			fileUploadDir = tomcatDir + uploadDir;
			list = HeritFileUploadUtil.uploadFiles(request, fileUploadDir,
					maxFileSize);
		}

		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HeritFormBasedFileVO vo = list.get(i);

				fileUploadVO.setFileRealName(vo.getFileName());
				fileUploadVO.setFilePhysName(vo.getPhysicalName());
				fileUploadVO.setFileSize(String.valueOf(vo.getSize()));
				fileUploadList.add(fileUploadVO);
			}
		}
		// js에 보내질 url 경로
		// param.put("fileUploadDir", fileUploadDir);
		param.put("hostUrl", hostUrl);
		param.put("uploadDir", uploadDir);

		try {

			Map<String, Object> content = databaseService.upload(system,
					domain, data, param, fileUploadList);

			response.put("result", 0);
			response.put("errorCode", 0);
			response.put("content", content);
			response.put("parameter", param);

		} catch (UserSysException ex) {
			ErrorVO err = ex.getErrorVO();
			response.put("result", 1);
			response.put("errorCode", err.getErrorCode());
			response.put("content", err.getErrorMessage());
			response.put("parameter", param);

		} catch (Exception ex) {
			response.put("result", 1);
			response.put("errorCode", -1);
			response.put("content", ex.toString());
			response.put("exception", ex);
			response.put("parameter", param);
		}
		return response;
	}

	@ResponseBody
	@RequestMapping(value = "/{system}/{domain}/{data}/{operation}/json")
	public Map<String, Object> getJson(
			@RequestBody Map<String, Object> paramMap,
			@PathVariable("system") String system,
			@PathVariable("domain") String domain,
			@PathVariable("data") String data,
			@PathVariable("operation") String operation,
			HttpServletRequest request) throws Exception {

		Map<String, Object> response = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();

		try {

			Map<String, Object> content = databaseService.execute(system,
					domain, data, operation, paramMap);

			response.put("result", 0);
			response.put("errorCode", 0);
			response.put("content", content);
			response.put("parameter", paramMap);

		} catch (UserSysException ex) {
			ErrorVO err = ex.getErrorVO();
			response.put("result", 1);
			response.put("errorCode", err.getErrorCode());
			response.put("content", err.getErrorMessage());
			response.put("parameter", paramMap);

		} catch (Exception ex) {
			response.put("result", 1);
			response.put("errorCode", -1);
			response.put("content", ex.toString());
			response.put("exception", ex);
			response.put("parameter", paramMap);
		}

		return response;
	}

	/*public static void main(String[] a) throws JsonGenerationException, JsonMappingException, IOException {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("a", "aaa");
		map.put("b", "bbb");

		ObjectMapper mapper = new ObjectMapper();
		Object json = mapper.writeValueAsString(map);

		//System.out.println("json: " + json.toString());
	}*/

	/*
	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value = "/{system}/{domain}/{operation}/json")
	public Map<String, Object> dbHandler(
			@RequestBody String bodyString,
			@PathVariable("system") String system,
			@PathVariable("domain") String domain,
			@PathVariable("operation") String operation,
			HttpServletRequest request) throws Exception {

		HashMap<String, Object> param = new HashMap<String, Object>();

		Enumeration names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			param.put(name, value);
		}

		return null;
	}
	*/

	@ResponseBody
	@RequestMapping(value = "/firmware/list.do")
	//public Map<String, Object> getFirmwareList(ParameterVO po, HttpServletRequest request) throws Exception {
	public Map<String, Object> getFirmwareList(@RequestBody String bodyString, HttpServletRequest request) throws Exception {
		//System.out.println("값 체크");
		Map<String, Object> response = new HashMap<String, Object>();

		//*
		JSONObject param = new JSONObject(bodyString);
		//System.out.println(bodyString);
		//System.out.println(param);
		//System.out.println("@@@@@@@@@@@@@@@@@@@");
		ParameterVO po = new ParameterVO();
		try{
			po.setSn(param.getString("sn"));
			po.setDeviceModel(String.valueOf(param.getInt("deviceModel")));
			po.setOui(param.getString("oui"));
			po.setModelName(param.getString("modelName"));//*/

			Method[] methods = po.getClass().getMethods();
			for(int i=0; i<methods.length; i++){
				if( methods[i].getName().startsWith("get") && methods[i].invoke(po) != null ){
					//System.out.println("[PO - "+methods[i].getName()+"] : "+methods[i].invoke(po));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		PagingUtil pagingUtil = null;
		try {
			pagingUtil = firmwareService.getFirmwareListPaging(1, 10, po);

			response.put("result", 0);
			response.put("errorCode", 0);
			response.put("pagingUtil", pagingUtil);

		} catch (Exception ex) {
			ex.printStackTrace();
			response.put("result", 1);
			response.put("errorCode", -1);
			response.put("content", ex.toString());
			response.put("exception", ex);
		}

		return response;
	}

	// MSH-START
	/**
	 * store "con" value to database when server is received notification
	 *
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/onem2m/noti")
	public String getConFromNotification(HttpServletRequest request, ModelMap model) {

		// map
		HashMap<String, String> headers = new HashMap<String, String>();
		HashMap<String, String> notification = new HashMap<String, String>();

		// headers
		Enumeration headerName = request.getHeaderNames();
		while( headerName.hasMoreElements() ){
			String name = (String)headerName.nextElement();
			String value = request.getHeader(name);
			headers.put(name, value);
		}
		Util.getInstance().printMap(headers);

		//
		String contentType = "json";
		String cnf = "text/plain:0";
		try(InputStream is = request.getInputStream()){
			byte[] buffer = IOUtils.toByteArray(is);
			String body = new String(buffer);
			//System.out.println(body);

			if( (headers.containsKey("Accept") && headers.get("Accept").indexOf("xml") > -1) || body.startsWith("<?xml") ){
				contentType = "xml";
			}

			switch( contentType ){
			case "json" :
				JSONObject jbody = new JSONObject(body);
				notification.put("sur", jbody.getJSONObject("m2m:sgn").getString("sur"));
				notification.put("con", jbody.getJSONObject("m2m:sgn").getJSONObject("nev").getJSONObject("rep").getJSONObject("m2m:cin").getString("con"));
				if( jbody.getJSONObject("m2m:sgn").getJSONObject("nev").getJSONObject("rep").getJSONObject("m2m:cin").has("cnf") ){
					cnf = jbody.getJSONObject("m2m:sgn").getJSONObject("nev").getJSONObject("rep").getJSONObject("m2m:cin").getString("cnf");
				}
				break;
			case "xml" :
				notification.put("sur", Util.getValueFromXml(body, "sur"));
				notification.put("con", Util.getValueFromXml(body, "con"));
				if( Util.getValueFromXml(body, "cnf") != null ){
					cnf = Util.getValueFromXml(body, "cnf");
				}
				break;
			default :
				//System.out.println("type exception");
				return null;
			}

			notification.put("cnf", cnf);
			Util.getInstance().printMap(notification);
			boolean isSuccess = hdmDAO.insertNotificationResource(notification);
			if( isSuccess ){
				//System.out.println(contentType+" - saved");
			} else {
				//System.out.println(contentType+" - fail to save");
			}

		} catch(Exception e) {
			e.printStackTrace();
		}

		String result = null;

		/*
		try(InputStream is = request.getInputStream()){
			byte[] buffer = IOUtils.toByteArray(is);
			String xml = new String(buffer);
			//System.out.println(xml);
			HashMap<String, String> notification = new HashMap<String, String>();
			notification.put("con", Util.getValueFromXml(xml, "con"));
			notification.put("cnf", Util.getValueFromXml(xml, "cnf"));
			notification.put("sur", Util.getValueFromXml(xml, "sur"));
			Util.getInstance().printMap(notification);

			boolean isSuccess = hdmDAO.insertNotificationResource(notification);
			if( isSuccess ){

			} else {

			}

		} catch(Exception e) {
			e.printStackTrace();
		} finally {

		}
		*/

		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/device/type")
	public int getDeviceType(HttpServletRequest request, ModelMap model) {

		int dmType = 0;

		try(InputStream is = request.getInputStream()){
			byte[] buffer = IOUtils.toByteArray(is);
			//System.out.println(new String(buffer));
			JSONObject body = new JSONObject(new String(buffer));
			//System.out.println(body);

			String deviceId = body.getString("deviceId");
			dmType = hdmDAO.getDeviceType(deviceId);

			//System.out.println(dmType);

		} catch(Exception e) {
			e.printStackTrace();
		}

		return dmType;
	}

	@ResponseBody
	@RequestMapping(value = "/device/model")
	public int getDeviceModel(HttpServletRequest request, ModelMap model) {

		int dmModelId = 0;

		try(InputStream is = request.getInputStream()){
			byte[] buffer = IOUtils.toByteArray(is);
			//System.out.println(new String(buffer));
			JSONObject body = new JSONObject(new String(buffer));
			//System.out.println(body);

			//
			String deviceId = body.getString("deviceId");
			dmModelId = hdpDAO.getDeviceModel(deviceId);

			//System.out.println(dmModelId);

		} catch(Exception e) {
			e.printStackTrace();
		}

		return dmModelId;
	}

	// MSH-END

}


text:
![CoreDataQueryInterface](CoreDataQueryInterface.png)

<!-- [![Build Status](https://travis-ci.org/Prosumma/CoreDataQueryInterface.svg)](https://travis-ci.org/Prosumma/CoreDataQueryInterface) -->
[![CocoaPods compatible](https://img.shields.io/cocoapods/v/CoreDataQueryInterface.svg)](https://cocoapods.org)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Core Data Query Interface (CDQI) is a type-safe, fluent, intuitive library for working with Core Data in Swift. CDQI tremendously reduces the amount of code needed to do Core Data, and dramatically improves readability. If you've worked with LINQ in the C# world, CDQI is a bit like LINQ.

## Swift 2.0

Due to the recent announcement of Swift 2.0, all work on this version of CDQI is suspended. If you want to see my progress on the new CDQI, check out the `swift2.0` branch.

Progress has been very uh…swift, and the new version is very nearly complete, barring changes required by the evolution of Swift 2.0. The interface of CDQI 2.0 is very similar to this version, but the implementation makes heavy use of some of the new language features in Swift 2.0, such as default protocol implementations and the new error handling paradigm.

## Advantages

The best way to understand the advantages of CDQI is to see an example. (Be sure to scroll right to see the entire example).

```swift
// Iteration causes the query to execute, though there are other ways
for employee in managedObjectContext.from(Employee).filter({$0.salary > 70000 && $0.department.name == "Engineering"}).order(descending: {$0.lastName}, {$0.firstName}) {
  debugPrintln("\(employee.lastName), \(employee.firstName)")
}
```

Now compare this to vanilla Core Data:

```swift
let fetchRequest = NSFetchRequest(entityName: "Employee")
fetchRequest.predicate = NSPredicate(format: "salary > %ld && department.name == %@", 70000, "Engineering")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastName", ascending: false), NSSortDescriptor(key: "firstName", ascending: false)]
for employee in managedObjectContext.executeFetchRequest(fetchRequest, error: nil)! as! [Employee] {
  debugPrintln("\(employee.lastName), \(employee.firstName)")
}
```

Compare the quantity and readability of the code in the two examples. Which would you rather write?

## Features

- [x] [Fluent interface](http://en.wikipedia.org/wiki/Fluent_interface)
- [x] Large number of overloads
- [x] Type-safety
- [x] Lazy execution
- [x] Three main query types: Entity, ManagedObjectID, and Dictionary (called "Expression" in CDQI)
- [x] Grouping, sorting, counts, etc.
- [x] Optionally eliminates the use of magic strings so common in Core Data
- [x] Query reuse, i.e., no side-effects from chaining
- [x] Support for iOS and OS X

## Requirements

- iOS 8.1+ / Mac OS X 10.9+
- Xcode 6.3+

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects.

CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:

```bash
$ gem install cocoapods
```

To integrate CoreDataQueryInterface into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'CoreDataQueryInterface', '~> 1.2'
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate CoreDataQueryInterface into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "Prosumma/CoreDataQueryInterface" >= 1.2
```

### Manually

CoreDataQueryInterface is a perfectly ordinary Xcode framework project with support for both iOS and OS X. Integrate as you normally would any other framework.

## Usage

### Integration

In order to use CoreDataQueryInterface with your models, they must implement the `ManagedObjectType` protocol:

```swift
class Department : NSManagedObject, ManagedObjectType {
  @NSManaged var name: String
}

class Employee : NSManagedObject, ManagedObjectType {
  @NSManaged var department: Department
  @NSManaged var firstName: String
  @NSManaged var lastName: String
  @NSManaged var salary: Int
}
```

#### Attributes

In order to use CoreDataQueryInterface's support for sorting, filtering, and the like without magic strings, you have to do a little more work. _This is completely optional but highly recommended._

```swift
class Department : NSManagedObject, ManagedObjectType {
  typealias ManagedObjectAttributeType = DepartmentAttribute
  @NSManaged var name: String
}

class DepartmentAttribute : Attribute {
  var name: Attribute { return Attribute("name", parent: self) }
}

class Employee : NSManagedObject, ManagedObjectType {
  typealias ManagedObjectAttributeType = EmployeeAttribute
  @NSManaged var department: Department
  @NSManaged var firstName: String
  @NSManaged var lastName: String
  @NSManaged var salary: Int
}

class EmployeeAttribute : Attribute {
  var department: DepartmentAttribute { return DepartmentAttribute("department", parent: self) }
  var firstName: Attribute { return Attribute("firstName", parent: self) }
  var lastName: Attribute { return Attribute("lastName", parent: self) }
  var salary: Attribute { return Attribute("salary", parent: self) }
}
```

### Starting a Query

There are three query types.

- `EntityQuery` This query requests entities, i.e., `NSManagedObject` subclasses, as the result.
- `ExpressionQuery` This query requests dictionaries as a result. It's called `ExpressionQuery` because typically this query is used when you want to perform some kind of calculation.
- `ManagedObjectIDQuery` This query requests an array of `NSManagedObjectID` as the result.

You can start a query using the static `from` method, either from one of the query types or from `NSManagedObjectContext`. If you start with a context, it's automatically an `EntityQuery`.

```swift
managedObjectContext.from(Employee) // Starts an EntityQuery
EntityQuery.from(Employee)
ExpressionQuery.from(Employee)
ManagedObjectIDQuery.from(Employee)
```

The first way, starting from a context, is the most common. If you start from `EntityQuery`, `ExpressionQuery`, or `ManagedObjectIDQuery`, no context is associated, so you will have to specify one later in the chain. If you start with an `EntityQuery`, there are very simple ways to turn the query into one of the other types.

### Specifying a Managed Object Context

If you start with a context and use `from`, a context has already been specified. If you start with `EntityQuery` and the like, you must specify a context. One way to do this is with the `context` method:

```swift
let query = EntityQuery.from(Employee).filter() { $0.department.name == "Sales" }
query.context(managedObjectContext)
```

There are other ways, as will be discussed below.

### Filtering

Filtering uses the `filter` method. There are a large number of overloads to support such things as `NSPredicate`, string-based queries, `Attribute`-based queries, etc. In general, the `Attribute`-based queries are recommended.

```swift
let employees = managedObjectContext.from(Employee)
employees.filter() { $0.department.name == "Sales" } // Attribute query. Recommended.
employees.filter(NSPredicate(format: "department.name == %@", "Sales"))
employees.filter("department.name == %@", "Sales"))
```

When filters are chained, the result is as if they were joined with `&&`. The following two filters are equivalent:

```swift
let employees = managedObjectContext.from(Employee)
employees.filter({ $0.department.name == "Sales" }).filter({ $0.lastName = "Smith" })
employees.filter({ $0.department.name == "Sales" && $0.lastName == "Smith" })
```

#### Filtering With Nil

When using `nil`, it's necessary to cast `nil` so that Swift knows which of the many operator overloads to call, e.g.,

```swift
employees.filter({ $0.department.name == nil as String? })
```

### Sorting

Sorting uses the `order` method. Its overloads are very similar to those of `filter`, except that each overload has a `descending:` variant.

```swift
let employees = managedObjectContext.from(Employee)
employees.order(descending: {$0.lastName}).order({$0.firstName})
employees.order({$0.lastName},{$0.firstName})
employees.order({e in [e.lastName, e.firstName]})
employees.order("lastName", "firstName")
```

When subsequent `order` methods are chained, the result is cumulative.

### Executing Queries

An ordinary query chain does not actually execute anything.

```swift
// A query to get all the Sales people
let query = EntityQuery.from(Employee).filter() { employee in employee.department.name == "Sales" }
let sortedQuery: EntityQuery<Employee> = query.order(descending: {$0.lastName}).order({$0.firstName})
```

The variables `query` and `sortedQuery` are not the executed results of these expressions. In other words, they're not arrays of `Employee` entities. They are the queries themselves. This is illustrated by the fact that `sortedQuery` is constructed from `query` and the (completely optional) type annotation added to `sortedQuery`. _This action is free of side-effects._ The `query` variable is unaffected by the creation of `sortedQuery`. (Note also that neither of these queries has an assigned managed object context.)

The simplest way to execute a query is to iterate over it.

```swift
let query = EntityQuery.from(Employee).filter() { employee in employee.department.name == "Sales" }
for employee in query.context(moc) {
  debugPrintln(employee)
}
```

Iteration swallows errors and simply does not iterate if an error occurs. A more sophisticated way is to use one of the _query execution methods_, such as `all`.

```swift
let query = EntityQuery.from(Employee).filter() { employee in employee.department.name == "Sales" }
var error: NSError?
let salesPeople = query.context(moc).all()!
let salesPeople = query.all(managedObjectContext: moc)!
let salesPeople = query.context(moc).all(error: &error)!
```

Here you can see the many possible variants. The `all` method returns `nil` if an error occurs. What exactly `all` returns depends on the type of query. For `EntityQuery`, it's an array of `NSManagedObject`s. For `ExpressionQuery`, it's `[[String: AnyObject]]`. For `ManagedObjectIDQuery` it's obviously `[NSManagedObjectID]`.

There are four other query execution methods: `first` and `count`, which are available on all query types, and `value` and `pluck`, which are not available on `ManagedObjectIDQuery`. `value` and `pluck` will be discussed in the as-yet-unwritten Advanced Usage section.

Examples of `first` and `count`:

```swift
var error: NSError?
let topPaidSalesPerson = moc.from(Employee).filter({ e in e.department.name == "Sales" }).order(descending: {$0.salary}).first(error: &error)!
let numberOfEngineers = moc.from(Employee).filter({ $0.department.name == "Engineering" }).count()!
```


text:
package algorithms.GraphAlgorithms

/**
  * problem description: http://rosalind.info/problems/bf/
  */

object BellmanFord {

  object SampleData {
    val sample: List[String] =
      List(
        "9 13",
        "1 2 10",
        "3 2 1",
        "3 4 1",
        "4 5 3",
        "5 6 -1",
        "7 6 -1",
        "8 7 1",
        "1 8 8",
        "7 2 -4",
        "2 6 2",
        "6 3 -2",
        "9 5 -10",
        "9 4 7"
      )
  }

  import SampleData.sample
  import utils.GraphUtilityFunctions.{costToString, readWeightedEdgeList}
  import utils.UtilityFunctions.{convertStringToIntList, readInputData, writeListAsStringToFile}
  import algorithms.Datastructures.WeightedGraph.shortestPathFord
  import algorithms.Datastructures.{WeightedEdge, WeightedGraph}

  val inputFileName: String = "/algorithms/datasets/rosalind_bf.txt"

  def getData(isPractice: Boolean): WeightedGraph = {
    val data: List[String] = if (isPractice) sample else readInputData(inputFileName)
    val List(numberOfNodes, _): List[Int] = convertStringToIntList(data.head)
    val edges: List[WeightedEdge] = readWeightedEdgeList(data.tail)
    WeightedGraph(numberOfNodes, edges, isDirected = true)
  }

  def main(args: Array[String]): Unit = {
    val graph: WeightedGraph = getData(isPractice = false)
    val result: List[String] = shortestPathFord(graph, baseNode = 1).map(costToString)
    writeListAsStringToFile(result)
  }

}


text:
<!DOCTYPE html>

		<title>pc3sq.github.io</title>
		<link rel="stylesheet" type="text/css" href="../css/main.css">

Stereotype Threat

What is Stereotype Threat?

					Stereotype threat is the threat being seen as a negative stereotype or the threat of confirming or fulfilling the stereotype. When you perceive stereotype threat, your cognition is impaired by the constant vigilance you feel necessary to guard against the threat. You are intimidated by the stereotypes against you. Furthermore, you can be in a protracted state of mistrust and anxiety. These impairments may be one reason why negatively stereotyped students receive lower marks than their stereotypically positive or neutral peers.

When Does Stereotype Threat Arise?

					Stereotype threat arises when what is salient to you appears to apply in the context. For example, in a study conducted by Claude M. Steele, blacks students performed significantly worse than their white counterparts on a exam made up of questions from a verbal section of the GREs when the exam was presented as a cognitive test. When the same exam was presented as a puzzle, the black students performed virtually at the same level as the white students.

					When the exam was presented as a cognitive test, the black students became aware of the stereotypes that blacks don't perform well on these types of exams. As a result, the saliency of these stereotypes allocated their cognitive resources to defending against the negative stereotypes leaving them with lesser ability and concentration for the exam itself. The students who saw the exam as game never saw their negative stereotypes come into play and so they did not feel stereotype threats that would impair their ability to perform on the exam.

What Can We Do About Stereotype Threat?

					Having strong emotionaly intelligence (EQ) is one key way to heighten your ability to detect and combat stereotype threat. To have strong EQ, you must practice awareness of yourself and others. One way to practice awareness is to find analogous experiences in your own life that may apply to someone who is experiencing stereotype threat.

					Another way to practice awareness is to practice communicating with others about how you are feeling. Often times when you share your thoughts, feelings, and stories, you'll find that all of us experiencing the same things despite how differently we identify ourselves. In other words, sharing our thoughts, feelings, and stories can dispel the belief that negative experiences are due to some fulfilment of a negative stereotype and instead may just be because of improper instructions, unjust laws, having an off day, etc.


text:
package com.trovebox.android.common.util;

import java.util.concurrent.atomic.AtomicInteger;

import android.view.View;

/**
 * Simple loading control which shows/hides view on start/stop loading
 *
 * @author Eugene Popovich
 */
public class SimpleViewLoadingControl implements LoadingControl {

    static final String TAG = SimpleViewLoadingControl.class.getSimpleName();

    private AtomicInteger mLoaders = new AtomicInteger(0);
    private View mView;

    public SimpleViewLoadingControl(View view) {
        this.mView = view;
    }

    @Override
    public void startLoading() {
        if (mLoaders.getAndIncrement() == 0) {
            setViewVisibile(true);
        }
    }

    @Override
    public void stopLoading() {
        if (mLoaders.decrementAndGet() == 0) {
            setViewVisibile(false);
        }
    }

    void setViewVisibile(boolean visible) {
        try {
            mView.setVisibility(visible ? View.VISIBLE : View.GONE);
        } catch (Exception ex) {
            GuiUtils.noAlertError(TAG, ex);
        }
    }

    @Override
    public boolean isLoading() {
        return mLoaders.get() > 0;
    }
}


text:
import Ember from "ember";
const {
  Route,
  RSVP
} = Ember;

export default Route.extend({

  model() {
    const promises = {
      departments: Ember.$.getJSON('/departments'),
      materials: Ember.$.getJSON('/materials')
    };
    return RSVP.hash(promises);
  }

});


text:
title: OnClientMouseOut
page_title: OnClientMouseOut | RadTabStrip for ASP.NET AJAX Documentation
description: OnClientMouseOut
slug: tabstrip/client-side-programming/onclientmouseout
tags: onclientmouseout
published: True
position: 11
---

# OnClientMouseOut

##

The **OnClientMouseOut** client-side event occurs when the mouse moves off a tab in the tab strip.

The event handler receives two parameters:

1. The instance of the tab strip firing the event.

1. An eventArgs parameter containing the following methods:

* **get_tab** returns a reference to the **RadTab** that the mouse just left.

* **get_domEvent** returns a reference to the DOM event object for the mouse movement.

You can use this event to respond when the mouse moves off a tab:

````ASPNET
<script type="text/javascript">
function markTab(sender, args)
{
	var attributes = args.get_tab().get_attributes();
	attributes.setAttribute("visited", "true");
}
</script>
<telerik:RadTabStrip
  ID="RadTabStrip1" runat="server" OnClientMouseOut="markTab">
<Tabs>
  <telerik:RadTab runat="server" Text="Item 1" visited="false" />
  <telerik:RadTab runat="server" Text="Item 2" visited="false" />
  <telerik:RadTab runat="server" Text="Item 3" visited="false" />
</Tabs>
</telerik:RadTabStrip>
````


text:
#import <UIKit/UIKit.h>
#import <ABI44_0_0React/ABI44_0_0RCTComponent.h>

@interface ABI44_0_0RNCSegmentedControl : UISegmentedControl
@property(nonatomic, assign) NSInteger selectedIndex;
@property(nonatomic, copy) ABI44_0_0RCTBubblingEventBlock onChange;

@end


text:
Storage utility
===============

Patterns include a simple storage utility which you can use to store
data for a pattern. The implementation is similar to the `Web storage
<http://www.whatwg.org/specs/web-apps/current-work/multipage/webstorage.html>`_
mechanism introduces in HTML5 (and in fact uses that as the underlying
storage), but offers multiple named storages and a few extensions that make
it easier to use in patterns.

Store API
-----------

.. js:attribute:: store.supported

   A boolean flag indicating if the browser supports web storage.

.. js:function:: store.local(name)

   :param string name: identifier for the storage section. This should
     almost always be the name of the pattern.
   :returns: storage instance

   Return a local storage instance. Local storage is persistant accross
   multiple browser sessions and tabs, and will survive a browser restart.

.. js:function:: store.session(name)

   :param string name: identifier for the storage section. This should
     almost always be the name of the pattern.
   :returns: storage instance

   Return a session storage instance. Session storage is tied to a single
   browser session. If a browser has multiple tabs open on the same website
   each tab will be seen as a different session. Session storage is not
   guaranteed to survive a browser restart.

Storage instance
----------------

The API for a storage instance mimicks the `HTML5 Storage interface
<http://www.whatwg.org/specs/web-apps/current-work/multipage/webstorage.html#the-storage-interface>`_.
It differs in that it adds a method to remove all data for a pattern, can
return all data as a single javascript object and can store all values that can
be JSON serialized instead of only strings.

.. js:function:: storage.get(name)

   :param string name: name of the stored variable to retrieve
   :returns: stored variable

   Retrieve (a copy of) a stored value from the storage. If no value for the
   given name was stored, `null` will be returned.

.. js:function:: storage.set(name, value)

   :param string name: name of the variable to store
   :param object value: value to store. Can be any type that is JSON serializable.
   :throws QuoteExceededError: This exception is thrown if the browser can
      not store this value.

   Store a variable. This will replace an existing value if already present.

.. js:function:: storage.remove(name)

   :param string name: name of the variable to remove

   Remove a variable from the storage. Unknown names are silently ignored.

.. js:function:: storage.clear()

   This method removes all variables stored for the pattern.

.. js:function:: storage.all()

   :returns: object with all stored data

   This method returns an object containing a copy of all stored data. Please
   note that this is only a copy: modifications made to the returned object
   will *not* be stored.

Example
-------

.. code-block:: javascript
   :linenos:

   var store = require("../core/store");

   if (store.supported)
       alert("Your browser does not support storage.");
   else {
       var storage = store.local("mypattern");
       storage.set("key", true);
       alert("The stored value is: " + storage.get("key"));
   }


text:
package com.example.android.sunshine.app.sync;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;

import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.data.WeatherContract;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallbacks;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.wearable.CapabilityInfo;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;

public class SunshineWearService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    static final String TAG = SunshineWearService.class.getSimpleName();

    public static final String WEATHER_CAPABILITY_NAME="weather";
    public static final String WEATHER_PATH = "/weather";

    GoogleApiClient client;

    public String nodeId;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "Create Service");
        if(client == null) {
            client = new GoogleApiClient.Builder(getApplicationContext())
                    .addApi(Wearable.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            client.connect();
        }
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        if(messageEvent.getPath().equals(WEATHER_PATH)) {
            notifyWear();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Wearable.CapabilityApi.addCapabilityListener(client, this, WEATHER_CAPABILITY_NAME);
    }

    @Override
    public void onConnectionSuspended(int i) {
        switch(i) {
            case CAUSE_NETWORK_LOST:
                Log.i(TAG, "Google client suspended: Network lost");
                break;
            case CAUSE_SERVICE_DISCONNECTED:
                Log.i(TAG, "Google client suspended: Service has been killed");
                break;
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e(TAG, "Client connection error: " + connectionResult.getErrorMessage());
    }

    @Override
    public void onCapabilityChanged(CapabilityInfo capabilityInfo) {
        Log.i(TAG, "Capability changed");
        for(Node node : capabilityInfo.getNodes()) {
            Log.i(TAG, "Node ID: " + node.getId());
            nodeId = node.getId();
        }
    }

    private static final int FORECAST_LOADER = 0;
    // For the forecast view we're showing only a small subset of the stored data.
    // Specify the columns we need.
    private static final String[] FORECAST_COLUMNS = {
            // In this case the id needs to be fully qualified with a table name, since
            // the content provider joins the location & weather tables in the background
            // (both have an _id column)
            // On the one hand, that's annoying.  On the other, you can search the weather table
            // using the location set by the user, which is only in the Location table.
            // So the convenience is worth it.
            WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
            WeatherContract.WeatherEntry.COLUMN_DATE,
            WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
            WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
            WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
            WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
            WeatherContract.LocationEntry.COLUMN_COORD_LAT,
            WeatherContract.LocationEntry.COLUMN_COORD_LONG
    };

    // These indices are tied to FORECAST_COLUMNS.  If FORECAST_COLUMNS changes, these
    // must change.
    static final int COL_WEATHER_ID = 0;
    static final int COL_WEATHER_DATE = 1;
    static final int COL_WEATHER_DESC = 2;
    static final int COL_WEATHER_MAX_TEMP = 3;
    static final int COL_WEATHER_MIN_TEMP = 4;
    static final int COL_LOCATION_SETTING = 5;
    static final int COL_WEATHER_CONDITION_ID = 6;
    static final int COL_COORD_LAT = 7;
    static final int COL_COORD_LONG = 8;

    private void notifyWear() {
        Log.i(TAG, "Notify Wear");
        // This is called when a new Loader needs to be created.  This
        // fragment only uses one loader, so we don't care about checking the id.

        // To only show current and future dates, filter the query to return weather only for
        // dates after or including today.

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";

        String locationSetting = Utility.getPreferredLocation(getApplicationContext());
        Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
                locationSetting, System.currentTimeMillis());

        // TODO figure out why this is needed
        //Looper.prepare();

        CursorLoader loader = new CursorLoader(getApplicationContext(),
                weatherForLocationUri,
                FORECAST_COLUMNS,
                null,
                null,
                sortOrder);

        loader.registerListener(FORECAST_LOADER, new Loader.OnLoadCompleteListener<Cursor>() {
            @Override
            public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
                data.moveToFirst();
                int low = data.getInt(COL_WEATHER_MIN_TEMP);
                int high = data.getInt(COL_WEATHER_MAX_TEMP);
                int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
                // String weather = Utility.getArtUrlForWeatherCondition(getApplicationContext(), weatherId);
                data.close();
                Log.i(TAG, "Temp low: "
                        + Integer.toString(low)
                        + ", high: "
                        + Integer.toString(high)
                        + ", "
                        //+ weather
                        //+ " "
                        + Integer.toString(weatherId));
                PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/weather");
                putDataMapRequest.getDataMap().putInt("temp-low", low);
                putDataMapRequest.getDataMap().putInt("temp-high", high);
                putDataMapRequest.getDataMap().putInt("weather", weatherId);
                //putDataMapRequest.getDataMap().putString("weather", weather);
                Wearable.DataApi.putDataItem(client, putDataMapRequest.asPutDataRequest()).setResultCallback(new ResultCallbacks<DataApi.DataItemResult>() {
                    @Override
                    public void onSuccess(@NonNull DataApi.DataItemResult dataItemResult) {
                        if (dataItemResult.getStatus().isSuccess()) {
                            Log.d(TAG, "Sent weather to wear");
                        } else {
                            Log.e(TAG, "Failed to send weather to wear");
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Status status) {
                        Log.e(TAG, status.getStatusMessage());
                    }
                });
            }
        });

        loader.startLoading();
    }
}


text:
using System;
using DNX.Helpers.Maths;
using DNX.Helpers.Maths.BuiltInTypes;
using NUnit.Framework;
using Test.DNX.Helpers.Maths.BuiltInTypes.TestsDataSource;

namespace Test.DNX.Helpers.Maths.BuiltInTypes
{
    [TestFixture]
    public class MathsFloatExtensionsTests
    {
        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "IsBetween_Default")]
        public bool IsBetween_Default(float value, float min, float max)
        {
            return value.IsBetween(min, max);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "IsBetween_BoundsType")]
        public bool IsBetween_BoundsType(float value, float min, float max, IsBetweenBoundsType boundsType)
        {
            return value.IsBetween(min, max, boundsType);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "IsBetweenEither_Default")]
        public bool IsBetweenEither_Default(float value, float min, float max)
        {
            return value.IsBetweenEither(min, max);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "IsBetweenEither_BoundsType")]
        public bool IsBetweenEither_BoundsType(float value, float min, float max, IsBetweenBoundsType boundsType)
        {
            return value.IsBetweenEither(min, max, boundsType);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "IsBetween")]
        public bool IsBetween(float value, float min, float max, bool allowEitherOrder, IsBetweenBoundsType boundsType)
        {
            return value.IsBetween(min, max, allowEitherOrder, boundsType);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "GetLowerBound")]
        public float GetLowerBound(float min, float max, bool allowEitherOrder)
        {
            return MathsFloatExtensions.GetLowerBound(min, max, allowEitherOrder);
        }

        [TestCaseSource(typeof(MathsFloatExtensionsTestsSource), "GetUpperBound")]
        public float GetUpperBound(float min, float max, bool allowEitherOrder)
        {
            return MathsFloatExtensions.GetUpperBound(min, max, allowEitherOrder);
        }
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Monitor;

namespace Azure.ResourceManager.Monitor.Models
{
    internal partial class DiagnosticSettingsCategoryResourceCollection
    {
        internal static DiagnosticSettingsCategoryResourceCollection DeserializeDiagnosticSettingsCategoryResourceCollection(JsonElement element)
        {
            Optional<IReadOnlyList<DiagnosticSettingsCategoryData>> value = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<DiagnosticSettingsCategoryData> array = new List<DiagnosticSettingsCategoryData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(DiagnosticSettingsCategoryData.DeserializeDiagnosticSettingsCategoryData(item));
                    }
                    value = array;
                    continue;
                }
            }
            return new DiagnosticSettingsCategoryResourceCollection(Optional.ToList(value));
        }
    }
}


text:
#ifndef _DILITHIUM_DXIL_SEMANTIC_HPP
#define _DILITHIUM_DXIL_SEMANTIC_HPP

#pragma once

#include <Dilithium/CXX17/string_view.hpp>

#include <Dilithium/dxc/HLSL/DxilConstants.hpp>
#include <Dilithium/dxc/HLSL/DxilShaderModel.hpp>

namespace Dilithium
{
	class DxilSemantic
	{
		friend class DxilShaderModel;
		friend class DxilSignatureElement;

	public:
		static int constexpr UNDEFINED_ROW = -1;
		static int constexpr UNDEFINED_COL = -1;

	public:
		DxilSemantic(SemanticKind kind, char const * name);

		static DxilSemantic const * GetByName(std::string_view name);
		static DxilSemantic const * GetByName(std::string_view name, SigPointKind sig_point_kind,
			uint32_t major_version = DxilShaderModel::HIGHEST_MAJOR, uint32_t minor_version = DxilShaderModel::HIGHEST_MINOR);
		static DxilSemantic const * Get(SemanticKind kind);
		static DxilSemantic const * Get(SemanticKind kind, SigPointKind sig_point_kind,
			uint32_t major_version = DxilShaderModel::HIGHEST_MAJOR, uint32_t minor_version = DxilShaderModel::HIGHEST_MINOR);
		static DxilSemantic const * GetInvalid();
		static DxilSemantic const * GetArbitrary();
		static bool HasSVPrefix(std::string_view name);
		static void DecomposeNameAndIndex(std::string_view full_name, std::string_view* name, uint32_t* index);

		SemanticKind GetKind() const;
		char const * GetName() const;
		bool IsArbitrary() const;
		bool IsInvalid() const;

	private:
		DxilSemantic() = delete;

	private:
		SemanticKind kind_;
		char const * name_;
	};
}

#endif		// _DILITHIUM_DXIL_SEMANTIC_HPP


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Set of SalientCountry for a document.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class QualitySalientCountriesSalientCountrySet extends com.google.api.client.json.GenericJson {

  /**
   * Packed Country and salience optimized for index storage
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.Integer> packedCountry;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.Integer> packedSalience;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<QualitySalientCountriesSalientCountry> salientCountry;

  static {
    // hack to force ProGuard to consider QualitySalientCountriesSalientCountry used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(QualitySalientCountriesSalientCountry.class);
  }

  /**
   * Packed Country and salience optimized for index storage
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.Integer> getPackedCountry() {
    return packedCountry;
  }

  /**
   * Packed Country and salience optimized for index storage
   * @param packedCountry packedCountry or {@code null} for none
   */
  public QualitySalientCountriesSalientCountrySet setPackedCountry(java.util.List<java.lang.Integer> packedCountry) {
    this.packedCountry = packedCountry;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.Integer> getPackedSalience() {
    return packedSalience;
  }

  /**
   * @param packedSalience packedSalience or {@code null} for none
   */
  public QualitySalientCountriesSalientCountrySet setPackedSalience(java.util.List<java.lang.Integer> packedSalience) {
    this.packedSalience = packedSalience;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.util.List<QualitySalientCountriesSalientCountry> getSalientCountry() {
    return salientCountry;
  }

  /**
   * @param salientCountry salientCountry or {@code null} for none
   */
  public QualitySalientCountriesSalientCountrySet setSalientCountry(java.util.List<QualitySalientCountriesSalientCountry> salientCountry) {
    this.salientCountry = salientCountry;
    return this;
  }

  @Override
  public QualitySalientCountriesSalientCountrySet set(String fieldName, Object value) {
    return (QualitySalientCountriesSalientCountrySet) super.set(fieldName, value);
  }

  @Override
  public QualitySalientCountriesSalientCountrySet clone() {
    return (QualitySalientCountriesSalientCountrySet) super.clone();
  }

}


text:
(function(){
    'use strict';

    angular.module('motech-server')
        .directive('motechServerInfo', directive);

    controller.$inject = ['$scope', 'ServerInfoService'];
    function controller($scope, ServerInfoService){
        $scope.$watch(function(){
            return ServerInfoService.information;
        }, function(information){
            $scope.information = information;
            $scope.serverRunning = ServerInfoService.running;
        });
    }

    function directive(){
        return {
            restrict: 'A',
            controller: controller
        };
    }

})();


text:
<?php

namespace Bermone\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * CompetenceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CompetenceRepository extends EntityRepository
{
	/* Methode permettant de récupérer l'ensemble des articles avec leur image */
		public function getCompetences($nombreArticles, $page){
			if($page<1){
				return null;
			}

			// on définit la requetes de selection avec querybuilder
			$qb = $this->createQueryBuilder("c")
					   ->orderBy("c.competenceDatePost", "DESC")
					   ->getQuery();

			//On défini l'article duquel commence la liste
			$qb->setFirstResult(($page-1)*$nombreArticles)
				//Ainsi que le nombre d'article a afficher
				->setMaxResults($nombreArticles);

			//On fini par retourner l'objet paginator correspondant à la requete construite
			return new Paginator($qb);
		}
}


text:
package edu.gatech.grits.pancakes.service;

public enum ControlOption {

	STOP(0),
	RESTART(1),
	RESCHEDULE(2),
	START(3);

	private int type;
	private ControlOption(int i){
		type = i;
	}

}


text:
package com.cocoahero.android.geojson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * An intermediate, abstract class that acts as a common base for all GeoJSON
 * geometry types.
 *
 */
public abstract class Geometry extends GeoJSONObject {

    // ------------------------------------------------------------------------
    // Public Constants
    // ------------------------------------------------------------------------

    public static final String JSON_COORDINATES = "coordinates";

    // ------------------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------------------

    public Geometry() {
        // Default Constructor
    }

    public Geometry(JSONObject json) {
        super(json);
    }

    // ------------------------------------------------------------------------
    // Public Methods
    // ------------------------------------------------------------------------

    @Override
    public JSONObject toJSON() throws JSONException {
        JSONObject json = super.toJSON();

        json.put(JSON_COORDINATES, new JSONArray());

        return json;
    }

}


text:
module.exports = {
    name: 'externalOperation',
    operation: function (db) {
        const collection = db.collection('posts');
        return collection.insertOne({title: 'Welcome', content: 'This is the test post'});
    }
};


text:
package org.apache.jackrabbit.jcr2spi;

import javax.jcr.Session;

/**
 * The SessionListener interface allows an implementing
 * object to be informed about changes on a Session.
 *
 * @see SessionImpl#addListener
 */
public interface SessionListener {

    /**
     * Called when a Session is about to be 'closed' by
     * calling {@link javax.jcr.Session#logout()}. At this
     * moment the session is still valid.
     *
     * @param session the Session that is about to be 'closed'
     */
    void loggingOut(Session session);

    /**
     * Called when a Session has been 'closed' by
     * calling {@link javax.jcr.Session#logout()}.
     *
     * @param session the Session that has been 'closed'
     */
    void loggedOut(Session session);
}


text:
using System;
using System.IO;
using MidiLoader.Parser;

namespace MidiLoader.Events.Meta {

	public class EndOfTrackMetaEvent : MetaEvent {

		static byte[] identifyingMask = new byte[] {
			0x2f, 0x00
		};

		protected override byte[] identifyingBytesMask {
			get {
				return identifyingMask;
			}
		}

		protected override MetaEvent Construct( Stream stream ) {
			return new EndOfTrackMetaEvent();
		}

	}

}


text:
<% if (ticketPrices.length > 0) { %>
<form class="form-horizontal">
    <% _.each(ticketPrices, function(ticketPrice) { %>
    <div class="form-group" id="ticket-category-fieldset-<%=ticketPrice.id%>">
        <%=ticketPrice.ticketCategory.description%>

                <input class="form-control col-md-6" rel="tooltip" title="Enter value"
                       data-tm-id="<%=ticketPrice.id%>"
                       placeholder="Number of tickets"
                       name="tickets-<%=ticketPrice.ticketCategory.id%>"/>
                @ $<%=ticketPrice.price%>

                <p class="help-block" id="error-input-<%=ticketPrice.id%>">

    <% }) %>

        <input type="button" class="btn btn-primary" disabled="true" name="add" value="Add tickets"/>

</form>
<% } %>


text:
const {
  assertSame,
  assertFalse,
  assertThrows,
} = Assert;

// eval issues with new declaration forms
// https://bugs.ecmascript.org/show_bug.cgi?id=1111

function nonStrictEvalLet() {
  assertFalse(eval("let x1; delete x1;"));
  assertSame("undefined", typeof x1);

  assertFalse(eval("let x2 = 0; delete x2;"));
  assertSame("undefined", typeof x2);

  assertFalse(eval("let {x3} = {}; delete x3;"));
  assertSame("undefined", typeof x3);

  assertFalse(eval("let {x4 = 0} = {}; delete x4;"));
  assertSame("undefined", typeof x4);

  assertFalse(eval("let [x5] = []; delete x5;"));
  assertSame("undefined", typeof x5);

  assertFalse(eval("let [x6 = 0] = []; delete x6;"));
  assertSame("undefined", typeof x6);
}
nonStrictEvalLet();

function nonStrictEvalConst() {
  assertFalse(eval("const x2 = 0; delete x2;"));
  assertSame("undefined", typeof x2);

  assertFalse(eval("const {x3} = {}; delete x3;"));
  assertSame("undefined", typeof x3);

  assertFalse(eval("const {x4 = 0} = {}; delete x4;"));
  assertSame("undefined", typeof x4);

  assertFalse(eval("const [x5] = []; delete x5;"));
  assertSame("undefined", typeof x5);

  assertFalse(eval("const [x6 = 0] = []; delete x6;"));
  assertSame("undefined", typeof x6);
}
nonStrictEvalConst();

function nonStrictEvalClass() {
  assertFalse(eval("class x1 {}; delete x1;"));
  assertSame("undefined", typeof x1);
}
nonStrictEvalConst();