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.
 */

package tk.timtim3001.bettercalendarview;

import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

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

/**
 * This class is a calendar widget that supports events. You can use it for selecting and displaying
 * dates and making and display calendar events
 * <p>
 * The calendar can be customized and follows the material design guidelines. You can
 * select a date by tapping on it and can scroll either by using the buttons on the top
 * or swipe left and right.
 */
public class BetterCalendarView extends LinearLayout {

    private static final String TAG = "BetterCalendarView";

    private final String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    //#region Attributes for all layout elements
    private LinearLayout daysLayout;
    private ImageButton prevButton;
    private ImageButton nextButton;
    private TextView monthView;
    private TextView mondayView;
    private TextView tuesdayView;
    private TextView wednesdayView;
    private TextView thursdayView;
    private TextView fridayView;
    private TextView saturdayView;
    private TextView sundayView;
    private List<DateView> dayList = new ArrayList<>();
    //#endregion

    //#region Attributs for basic functionality
    private Calendar calendar;
    private boolean dayIsColored = false;
    private ClickHandler clickHandler = new ClickHandler();
    private Date selectedDate = null;
    private int totalMonthDifference = 0;
    private Context context;
    private AttributeSet attrs;
    private List<CalendarEvent> calendarEvents;
    private List<CalendarEvent> eventsToDisplay;
    private CalendarEventDAO calendarEventDAO;
    private DateView lastSelectedView = null;
    //#endregion

    //#region Attributes for listeners
    private OnDateSelectedListener dateChangedListener = null;
    private OnEventSelectedListener eventSelectedListener = null;
    //#endregion

    //#region Attributes for xml-attributes
    private boolean hasToColorCurrentDay;
    private int currentDayColor;
    private int eventColor;
    private int selectedColor;
    //#endregion

    //#region Attributes for theme-ing
    private final int DARK = 0;
    private final int LIGHT = 1;
    private int dayColor;
    //#endregion

    /**
     * Constructor to initialize an BetterCalendarView
     *
     * @param context The context
     */
    public BetterCalendarView(@NonNull Context context) {
        this(context, null);
    }

    /**
     * Constructor to initialize an BetterCalendarView
     *
     * @param context The context
     * @param attrs The xml-attributes
     */
    public BetterCalendarView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        Log.d(TAG, "BetterCalendarView");

        this.context = context;
        this.attrs = attrs;

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BetterCalendarView, 0, 0);
        TypedArray themeArray = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.colorBackground});
        try{
            hasToColorCurrentDay = typedArray.getBoolean(R.styleable.BetterCalendarView_hasToColorCurrentDay, true);
            currentDayColor = typedArray.getColor(R.styleable.BetterCalendarView_colorCurrentDay, Color.RED);
            eventColor = typedArray.getColor(R.styleable.BetterCalendarView_colorEvent, Color.MAGENTA);
            selectedColor = typedArray.getColor(R.styleable.BetterCalendarView_colorSelectedDay, Color.rgb(51,181,229));

            changeColorScheme(checkThemeColor(themeArray.getColor(0, Color.WHITE)));
        }finally {
            typedArray.recycle();
        }

        calendarEventDAO = new CalendarEventDAO(context);

        init(context);
        populateGrid();
        setCurrentMonth();

    }

    private void getAllEvents(){
        Cursor cursor = calendarEventDAO.getCalendarEvents();
        while(cursor.moveToNext()) {
            long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents._ID));
            int day = cursor.getInt(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents.COLUMN_NAME_DAY));
            int month = cursor.getInt(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents.COLUMN_NAME_MONTH));
            int year = cursor.getInt(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents.COLUMN_NAME_YEAR));
            String smallDescription = cursor.getString(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents.COLUMN_NAME_SMALL_DESCRIPTION));
            String description = cursor.getString(cursor.getColumnIndexOrThrow(MySQLContracts.CalendarEvents.COLUMN_NAME_DESCRIPTION));
            calendarEvents.add(new CalendarEvent(itemId, description, smallDescription, new Date(day, month, year)));
        }
        cursor.close();
    }

    private int checkThemeColor(int color){

        if((Color.red(color) + Color.green(color) + Color.blue(color)) / 3 > 175)
            return LIGHT;

        return DARK;

    }

    private void changeColorScheme(int colorScheme){

        if(colorScheme == LIGHT){
            dayColor = Color.DKGRAY;
        }else if(colorScheme == DARK){
            dayColor = Color.WHITE;
        }

    }

    private void init(Context context){
        Log.d(TAG, "init");
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.calendar_layout, this);

        daysLayout = (LinearLayout) findViewById(R.id.days_layout);
        prevButton = (ImageButton) findViewById(R.id.calendar_prev_button);
        nextButton = (ImageButton) findViewById(R.id.calendar_next_button);
        monthView = (TextView) findViewById(R.id.calendar_date_display);

        mondayView  = (TextView) findViewById(R.id.mondayView);
        tuesdayView = (TextView) findViewById(R.id.tuesdayView);
        wednesdayView = (TextView) findViewById(R.id.wednesdayView);
        thursdayView = (TextView) findViewById(R.id.thursdayView);
        fridayView = (TextView) findViewById(R.id.fridayView);
        saturdayView = (TextView) findViewById(R.id.saturdayView);
        sundayView = (TextView) findViewById(R.id.sundayView);

        mondayView.setTextColor(dayColor);
        tuesdayView.setTextColor(dayColor);
        wednesdayView.setTextColor(dayColor);
        thursdayView.setTextColor(dayColor);
        fridayView.setTextColor(dayColor);
        saturdayView.setTextColor(dayColor);
        sundayView.setTextColor(dayColor);
        monthView.setTextColor(dayColor);

        DrawableCompat.setTint(nextButton.getDrawable(), dayColor);
        DrawableCompat.setTint(prevButton.getDrawable(), dayColor);

        prevButton.setOnClickListener(clickHandler);
        nextButton.setOnClickListener(clickHandler);

        calendar = Calendar.getInstance();
        monthView.setText(months[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.YEAR));

        calendarEvents = new ArrayList<>();
        getAllEvents();
    }

    private void setCurrentMonth(){
        Log.d(TAG, "setCurrentMonth");
        changeMonth(0);
    }

    private int changeMonth(int difference){
        Log.d(TAG, "changeMonth");
        totalMonthDifference += difference;
        calendar.add(Calendar.MONTH, difference);

        monthView.setText(months[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.YEAR));
        eventsToDisplay = getAllCalendarEventsCurrentMonth(calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));

        int daysInMonth, daysInLastMonth, firstDayOfMonth;

        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        firstDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
        calendar.set(Calendar.DAY_OF_MONTH, currentDay);

        daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        calendar.add(Calendar.MONTH, -1);
        daysInLastMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.MONTH, 1);

        switch (firstDayOfMonth){
            case Calendar.MONDAY:
                changeDays(0, daysInMonth, daysInLastMonth);
                break;
            case Calendar.TUESDAY:
                changeDays(1, daysInMonth, daysInLastMonth);
                break;
            case Calendar.WEDNESDAY:
                changeDays(2, daysInMonth, daysInLastMonth);
                break;
            case Calendar.THURSDAY:
                changeDays(3, daysInMonth, daysInLastMonth);
                break;
            case Calendar.FRIDAY:
                changeDays(4, daysInMonth, daysInLastMonth);
                break;
            case Calendar.SATURDAY:
                changeDays(5, daysInMonth, daysInLastMonth);
                break;
            case Calendar.SUNDAY:
                changeDays(6, daysInMonth, daysInLastMonth);
                break;
        }

        drawEvents();

        if(hasToColorCurrentDay) {
            colorCurrentDay();
        }

        return calendar.get(Calendar.MONTH);
    }

    private void colorCurrentDay(){
        if (Calendar.getInstance().get(Calendar.MONTH) == calendar.get(Calendar.MONTH)) {
            for (int i = 0; i < dayList.size(); i++) {
                if (dayList.get(i).getAlpha() == 1f)
                    if (dayList.get(i).getText().equals(Integer.toString(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)))) {
                        dayList.get(i).setTextColor(currentDayColor);
                        dayIsColored = true;
                    }
            }
        } else {
            if (dayIsColored) {
                resetColorCurrentDay();
            }
        }
    }

    private void resetColorCurrentDay(){
        for (int i = 0; i < dayList.size(); i++) {
            dayList.get(i).setTextColor(dayColor);
        }
        dayIsColored = false;
    }

    private void setColorOfView(DateView view, int color){
        view.setBackgroundColor(color);
    }

    private void drawEvents(){
        for(DateView view : dayList){
            setColorOfView(view, Color.TRANSPARENT);
        }

        for(CalendarEvent event : eventsToDisplay){
            for (int i = 0; i < dayList.size(); i++) {
                if (dayList.get(i).getAlpha() == 1f) {
                    if (dayList.get(i).getText().equals(Integer.toString(event.getDate().getDay()))) {
                        setColorOfView(dayList.get(i), eventColor);
                    }
                }
            }
        }
        if(lastSelectedView != null){
            setColorOfView(lastSelectedView, selectedColor);
        }
    }

    private void changeDays(int startDay, int maxDays, int maxDaysLastMonth){
        Log.d(TAG, "changeDays");
        int dayOfMonth = 1;

        for(int i = startDay-1;i>=0;i--){
            dayList.get(i).setText(String.format("%s", maxDaysLastMonth - (startDay-1-i)));
            dayList.get(i).setAlpha(0.25f);
            dayList.get(i).setClickable(false);
        }
        for(int i = startDay; dayOfMonth <= maxDays; dayOfMonth++, i++){
            dayList.get(i).setText(String.format("%s", dayOfMonth));
            dayList.get(i).setAlpha(1f);
            dayList.get(i).setClickable(true);
        }
        for(int i = startDay + maxDays;i<dayList.size();i++){
            dayList.get(i).setText(String.format("%s", i - maxDays - startDay + 1));
            dayList.get(i).setAlpha(0.25f);
            dayList.get(i).setClickable(false);
        }
    }

    private void populateGrid(){
        Log.d(TAG, "populateGrid");

        LinearLayout.LayoutParams dateViewParams = new LinearLayout.LayoutParams(context, attrs);
        dateViewParams.width = LayoutParams.MATCH_PARENT;
        dateViewParams.height = LayoutParams.MATCH_PARENT;
        dateViewParams.weight = 1;

        LayoutParams llParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        llParams.weight = 1;

        for(int y = 0;y<6;y++){
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(HORIZONTAL);
            linearLayout.setLayoutParams(llParams);
            for(int x = 0;x<7;x++){
                DateView dateView = new DateView(context);
                dateView.setGravity(Gravity.CENTER);
                dateView.setText("1");
                dateView.setOnClickListener(clickHandler);
                dateView.setTextColor(dayColor);
                //dateView.setBackgroundResource(R.drawable.rouned_corners);
                dayList.add(dateView);
                linearLayout.addView(dateView, dateViewParams);
            }
            daysLayout.addView(linearLayout);
        }
    }

    private List<CalendarEvent> getAllCalendarEventsCurrentMonth(int month, int year){
        List<CalendarEvent> eventList = new ArrayList<>();
        for(CalendarEvent event : calendarEvents){
            if(event.getDate().getMonth() == month && event.getDate().getYear() == year){
                eventList.add(event);
            }
        }
        return eventList;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        changeMonth(totalMonthDifference);
        for(View view : dayList){
            GradientDrawable gradientDrawable = (GradientDrawable) view.getBackground();
            //gradientDrawable.setSize(10,10);
            view.setBackgroundDrawable(gradientDrawable);
//            BitmapDrawable drawable = (BitmapDrawable) view.getBackground();
//            Bitmap b = drawable.getBitmap();
//            view.setBackgroundDrawable(new BitmapDrawable(Bitmap.createScaledBitmap(b, b.getHeight(), b.getHeight(), false)));
        }
    }

    //#region getters and setters
    /**
     * Gets the currently shown month
     * @return The currently shown month
     */
    public int getMonth(){
        return calendar.get(Calendar.MONTH);
    }

    /**
     * Gets the currently shown year
     * @return The currently shown year
     */
    public  int getYear(){
        return calendar.get(Calendar.YEAR);
    }

    //#region getters and setters for customizability
    /**
     * Gets whether the current day has to be colored a different color.
     * @return Whether current day is colored differently
     */
    public boolean getHasToColorCurrentDay() {
        return hasToColorCurrentDay;
    }

    /**
     * Sets whether the current day has to be colored a different color.
     * @param hasToColorCurrentDay boolean - Whether current day is colored differently
     */
    public void hasToColorCurrentDay(boolean hasToColorCurrentDay) {
        this.hasToColorCurrentDay = hasToColorCurrentDay;
        if(!hasToColorCurrentDay){
            for (int i = 0; i < dayList.size(); i++) {
                dayList.get(i).setTextColor(dayColor);
            }
            dayIsColored = false;
        }
    }
    //#endregion
    //#endregion

    //#region methods for listeners
    /**
     * Sets the OnEventSelectedListener. If you want to remove the listener you can pass null
     *
     * @see OnEventSelectedListener
     * @param eventSelectedListener The listener that has to be set
     */
    public void setOnEventSelectedListener(@Nullable OnEventSelectedListener eventSelectedListener){
        this.eventSelectedListener = eventSelectedListener;
    }

    /**
     * Checks whether the view has an OnEventSelectedListener
     *
     * @see OnEventSelectedListener
     * @return Whether the view has an OnEventSelectedListener
     */
    public boolean hasOnEventSelectedListener(){
        return eventSelectedListener != null;
    }

    /**
     * Sets the OnDateSelectedListener. If you want to remove the listener you can pass null
     *
     * @see OnDateSelectedListener
     * @param dateChangedListener The listener that has to be set
     */
    public void setDateChangedListener(@Nullable OnDateSelectedListener dateChangedListener) {
        this.dateChangedListener = dateChangedListener;
    }

    /**
     * Checks whether the view has an OnDateSelectedListener.
     *
     * @see OnDateSelectedListener
     * @return Whether the view has an OnDateSelectedListener
     */
    public boolean hasOnDateChangedListener(){
        return dateChangedListener != null;
    }
    //#endregion

    //#region Methods for events
    /**
     * Method that add an {@link CalendarEvent} to the calender view
     * @param event The event that has to be added
     * @return  Whether the event was added successfully
     */
    public boolean addCalendarEvent(CalendarEvent event) {
        long id = calendarEventDAO.addCalendarEvent(event);
        if (id > 0){
            event.setId(id);
            calendarEvents.add(event);
            if(event.getDate().getMonth() == calendar.get(Calendar.MONTH) && event.getDate().getYear() == calendar.get(Calendar.YEAR)){
                eventsToDisplay.add(event);
            }
            drawEvents();
            return true;
        }
        return false;
    }

    /**
     * Returns all the {@link CalendarEvent}s as an array
     * @return all the {@link CalendarEvent}s
     */
    public CalendarEvent[] getAllCalendarEvents(){
        CalendarEvent[] array = new CalendarEvent[calendarEvents.size()];
        return calendarEvents.toArray(array);
    }

    /**
     * Removes all the events from the calendar
     */
    public void deleteAllEvents(){

        for(CalendarEvent event : calendarEvents){
            calendarEventDAO.deleteById(event.getId());
        }
        calendarEvents.clear();
        eventsToDisplay.clear();
        drawEvents();
    }

    /**
     * Removes an event from the calendar
     * @param event The event that has to be deleted
     * @return whether the event was deleted successfully
     */
    public boolean deleteEvent(CalendarEvent event){
        if(calendarEventDAO.deleteById(event.getId())){
            if(calendarEvents.contains(event)){
                calendarEvents.remove(event);
            }
            if(eventsToDisplay.contains(event)){
                eventsToDisplay.remove(event);
            }
            drawEvents();
            return true;
        }
        return false;
    }
    //#endregion

    private class ClickHandler implements OnClickListener{

        @Override
        public void onClick(View v) {

            int difference = 0;
            if(v instanceof DateView){
                DateView dateView = (DateView) v;

                if(lastSelectedView != null){
                    setColorOfView(lastSelectedView, Color.TRANSPARENT);
                }

                lastSelectedView = (DateView) v;
                setColorOfView((DateView) v, selectedColor);
                selectedDate = new Date(Integer.parseInt(dateView.getText().toString()), getMonth(), getYear());

                List<CalendarEvent> eventsList = new ArrayList<>();
                for(CalendarEvent event : eventsToDisplay){
                    if(event.getDate().equals(selectedDate))
                        eventsList.add(event);
                }

                if(dateChangedListener != null){
                    dateChangedListener.onDateChanged(selectedDate);
                }

                if(eventSelectedListener != null && eventsList.size() > 0){
                    CalendarEvent[] events = new CalendarEvent[eventsList.size()];
                    eventSelectedListener.onEventSelected(eventsList.toArray(events));
                }

            }else if(v instanceof ImageButton){
                if(v.getId() == nextButton.getId())
                    difference = 1;
                if(v.getId() == prevButton.getId())
                    difference = -1;
            }

            changeMonth(difference);
            if(selectedDate != null) {
                if (getMonth() == selectedDate.getMonth() && getYear() == selectedDate.getYear())
                    setColorOfView(lastSelectedView, selectedColor);
                else
                    setColorOfView(lastSelectedView, Color.TRANSPARENT);
            }
        }
    }

    //#region interface definitions
    /**
     * Interface definition for a callback to be invoked when a date is selected
     */
    public interface OnDateSelectedListener {
        /**
         * called when a date is clicked
         *
         * @param selectedDate The newly selected day
         */
        void onDateChanged(Date selectedDate);
    }

    /**
     * Interface definition for a callback to be invoked when a event is selected
     */
    public interface OnEventSelectedListener{
        /**
         * Called when a event is clicked
         * @param events An array containing all of the events on the selected day
         */
        void onEventSelected(CalendarEvent[] events);
    }
    //#endregion
}


text:
import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';

const { Component, RSVP, inject, computed } = Ember;
const { Promise } = RSVP;
const { service } = inject;

export default Component.extend({
  store: service(),
  currentUser: service(),

  init(){
    this._super(...arguments);
    this.set('togglePermissions', []);
  },

  classNameBindings: [':user-profile-schools', ':small-component', ':last', 'hasSavedRecently:has-saved:has-not-saved'],

  user: null,
  isManaging: false,
  isManagable: false,

  togglePermissions: null,
  hasSavedRecently: false,

  save: task(function * (){
    yield timeout(10);
    const store = this.get('store');
    const user = this.get('user');

    const readSchools = yield this.get('readSchools');
    const writeSchools = yield this.get('writeSchools');
    const readOnlySchools = readSchools.filter(school => !writeSchools.includes(school));

    const userPermissions = yield user.get('permissions');
    yield userPermissions.invoke('destroyRecord');
    userPermissions.clear();

    let newPermissions = [];
    const writePermissions = writeSchools.map(school => {
      return store.createRecord('permission', {
        canRead: true,
        canWrite: true,
        user,
        tableName: 'school',
        tableRowId: school.get('id')
      });

    });
    newPermissions.pushObjects(writePermissions);

    const readOnlyPermissions = readOnlySchools.map(school => {
      return store.createRecord('permission', {
        canRead: true,
        canWrite: false,
        user,
        tableName: 'school',
        tableRowId: school.get('id')
      });
    });
    newPermissions.pushObjects(readOnlyPermissions);

    yield newPermissions.invoke('save');
    this.get('cancel').perform();
    this.set('hasSavedRecently', true);
    yield timeout(500);
    this.set('hasSavedRecently', false);

  }).drop(),

  cancel: task(function * (){
    yield timeout(1);
    this.set('hasSavedRecently', false);
    this.set('togglePermissions', []);
    this.get('setIsManaging')(false);

  }).drop(),

  displaySchools: computed('editableSchools.[]', 'secondarySchools.[]', 'isManaging', function(){
    const isManaging = this.get('isManaging');
    if (isManaging) {
      return this.get('editableSchools');
    } else {
      return this.get('secondarySchools');
    }
  }),

  editableSchools: computed('user.school', 'currentUser.model.schools', 'currentUser.model.school', function(){
    const currentUser = this.get('currentUser');
    const user = this.get('user');
    return new Promise(resolve => {
      currentUser.get('model').then(authUser => {
        authUser.get('schools').then(schools => {
          user.get('school').then(userPrimarySchool => {
            let editableSchools = schools.filter(school => school.get('id') !== userPrimarySchool.get('id'));
            resolve(editableSchools);
          });
        });
      });
    });
  }),

  secondarySchools: computed('user.school', 'currentUser.model.school', async function(){
    const store = this.get('store');
    const user = this.get('user');
    const schools = await store.findAll('school');
    const primarySchool = await user.get('school');
    const secondarySchools = schools.filter(school => school.get('id') !== primarySchool.get('id'));

    return secondarySchools;
  }),

  readSchools: computed('user.permissions.[]', 'secondarySchools.[]', 'togglePermissions.[]', async function(){
    const togglePermissions = this.get('togglePermissions');
    const user = this.get('user');

    const schools = await this.get('secondarySchools');
    const overriddenIds = schools.filter(school => {
      const permission = school.get('id') + 'read';
      return togglePermissions.includes(permission);
    }).mapBy('id');
    const permissions = await user.get('permissions');
    const existingIds = permissions.filter(permission => {
      return permission.get('tableName') === 'school' && permission.get('canRead');
    }).mapBy('tableRowId');
    const readSchools = schools.filter(school => {
      let id = school.get('id');
      return (existingIds.includes(id) && !overriddenIds.includes(id)) ||
             (!existingIds.includes(id) && overriddenIds.includes(id));
    });

    return readSchools;
  }),

  writeSchools: computed('user.permissions.[]', 'secondarySchools.[]', 'togglePermissions.[]', async function(){
    const togglePermissions = this.get('togglePermissions');
    const user = this.get('user');

    const schools = await this.get('secondarySchools');
    const overriddenIds = schools.filter(school => {
      const permission = school.get('id') + 'write';
      return togglePermissions.includes(permission);
    }).mapBy('id');
    const permissions = await user.get('permissions');
    const existingIds = permissions.filter(permission => {
      return permission.get('tableName') === 'school' && permission.get('canWrite');
    }).mapBy('tableRowId');
    const writeSchools = schools.filter(school => {
      let id = school.get('id');
      return (existingIds.includes(id) && !overriddenIds.includes(id)) ||
             (!existingIds.includes(id) && overriddenIds.includes(id));
    });

    return [].concat(writeSchools);
  }),

  readAndWriteSchoolIds: computed('readSchools.[]', 'writeSchools.[]', async function(){
    const readSchools = await this.get('readSchools');
    const writeSchools = await this.get('writeSchools');

    const all = [].concat(readSchools, writeSchools);

    return all.mapBy('id');
  }),

  writeSchoolIds: computed('writeSchools.[]', async function(){
    const writeSchools = await this.get('writeSchools');
    return writeSchools.mapBy('id');
  }),

  actions: {
    toggleReadSchool(school){
      const permission = school.get('id') + 'read';
      if (this.get('togglePermissions').includes(permission)) {
        this.get('togglePermissions').removeObject(permission);
      } else {
        this.get('togglePermissions').pushObject(permission);
      }
    },
    toggleWriteSchool(school){
      const permission = school.get('id') + 'write';
      if (this.get('togglePermissions').includes(permission)) {
        this.get('togglePermissions').removeObject(permission);
      } else {
        this.get('togglePermissions').pushObject(permission);
      }
    }
  }
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>XLabs: F:/Projects/Xamarin-Forms-Labs/src/Serialization/XLabs.Serialization Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

XLabs

Cross-platform reusable C# libraries

Main Page

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

XLabs.Serialization Directory Reference

Directories

directory  	Properties

Files

file  	IByteSerializer.cs

file  	IJsonConvert.cs

file  	IJsonSerializer.cs

file  	IProtoBufSerializer.cs

file  	ISerializer.cs

file  	IStreamSerializer.cs

file  	IStringSerializer.cs

file  	IXmlSerializer.cs

file  	JsonDelegate.cs

file  	SerializationFormat.cs

file  	StreamSerializer.cs

file  	StreamSerializerExtensions.cs

file  	StringSerializer.cs

file  	StringSerializerExtensions.cs

file  	SystemJsonSerializer.cs

file  	SystemXmlSerializer.cs

Xamarin-Forms-Labs

src

Serialization

XLabs.Serialization

Generated by

     1.8.10


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>gameplay: Main Page</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>

overview
wiki
api reference
forums
download

- s -

samplerArrayValue : gameplay::MaterialParameter

samplerValue : gameplay::MaterialParameter

script : gameplay::PhysicsCollisionObject::ScriptListener, gameplay::ScriptTarget::CallbackFunction, gameplay::ScriptTarget::ScriptEntry

size : gameplay::VertexFormat::Element

sphere : gameplay::PhysicsCollisionShape::Definition

STATE_ALL : gameplay::Control

SWIPE_DIRECTION_DOWN : gameplay::Gesture

SWIPE_DIRECTION_LEFT : gameplay::Gesture

SWIPE_DIRECTION_RIGHT : gameplay::Gesture

SWIPE_DIRECTION_UP : gameplay::Gesture

<address class="footer">
Generated on Wed May 18 2022 18:44:29 for gameplay by  1.9.4
</address>


text:
package ds.tree;

/**
 * The visitor interface that is used by {@link RadixTreeImpl} for perfroming
 * task on a searched node.
 *
 * @author Tahseen Ur Rehman (tahseen.ur.rehman {at.spam.me.not} gmail.com)
 * @author Javid Jamae
 * @author Dennis Heidsiek
 * @param <T>
 * @param <R>
 */
public interface Visitor<T, R> {
    /**
     * This method gets called by {@link RadixTreeImpl#visit(String, Visitor) visit}
     * when it finds a node matching the key given to it.
     *
     * @param key The key that matched the node
     * @param parent The parent of the node being visited
     * @param node The node that is being visited
     */
    public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node);

    /**
     * The visitor can store any type of result object, depending on the context of
     * what it is being used for.
     *
     * @return The result captured by the visitor.
     */
    public R getResult();
}


text:
module INSPECTOR {
    /**
     * A tab bar will contains each view the inspector can have : Canvas2D, Meshes...
     * The default active tab is the first one of the list.
     */
    export class TabBar extends BasicElement {

        // The list of available tabs
        private _tabs: Array<Tab> = [];
        private _inspector: Inspector;
        /** The tab displaying all meshes */
        private _meshTab: MeshTab;
        /** The toolbar */
        private _toolBar: Toolbar;
        /** The icon displayed at the end of the toolbar displaying a combo box of tabs not displayed */
        private _moreTabsIcon: HTMLElement;
        /** The panel displayed when the 'more-tab' icon is selected */
        private _moreTabsPanel: HTMLElement;
        /** The list of tab displayed by clicking on the remainingIcon */
        private _invisibleTabs: Array<Tab> = [];
        /** The list of tabs visible, displayed in the tab bar */
        private _visibleTabs: Array<Tab> = [];

        constructor(inspector: Inspector, initialTab?: number) {
            super();
            this._inspector = inspector;
            this._tabs.push(new SceneTab(this, this._inspector));
            this._tabs.push(new ConsoleTab(this, this._inspector));
            this._tabs.push(new StatsTab(this, this._inspector));
            this._meshTab = new MeshTab(this, this._inspector);
            this._tabs.push(new TextureTab(this, this._inspector));
            this._tabs.push(this._meshTab);
            this._tabs.push(new LightTab(this, this._inspector));
            this._tabs.push(new MaterialTab(this, this._inspector));
            if (BABYLON.GUI) {
                this._tabs.push(new GUITab(this, this._inspector));
            }
            this._tabs.push(new PhysicsTab(this, this._inspector));
            this._tabs.push(new CameraTab(this, this._inspector));
            this._tabs.push(new SoundTab(this, this._inspector));

            this._toolBar = new Toolbar(this._inspector);

            this._build();

            //Check initialTab is defined and between tabs bounds
            if (!initialTab || initialTab < 0 || initialTab >= this._tabs.length) {
                initialTab = 0;
            }

            this._tabs[initialTab].active(true);

            // set all tab as visible
            for (let tab of this._tabs) {
                this._visibleTabs.push(tab);
            }
        }

        // No update
        public update() { }

        protected _build() {
            this._div.className = 'tabbar';

            this._div.appendChild(this._toolBar.toHtml());
            for (let tab of this._tabs) {
                this._div.appendChild(tab.toHtml());
            }

            this._moreTabsIcon = Helpers.CreateElement('i', 'fa fa-angle-double-right more-tabs');

            this._moreTabsPanel = Helpers.CreateDiv('more-tabs-panel');

            this._moreTabsIcon.addEventListener('click', () => {
                // Hide the 'more-tabs-panel' if already displayed
                if (this._moreTabsPanel.style.display == 'flex') {
                    this._moreTabsPanel.style.display = 'none';
                } else {
                    // Attach more-tabs-panel if not attached yet
                    let topPanel = this._div.parentNode as HTMLElement;
                    if (!topPanel.contains(this._moreTabsPanel)) {
                        topPanel.appendChild(this._moreTabsPanel);
                    }
                    // Clean the 'more-tabs-panel'
                    Helpers.CleanDiv(this._moreTabsPanel);
                    // Add each invisible tabs to this panel
                    for (let tab of this._invisibleTabs) {
                        this._addInvisibleTabToPanel(tab);
                    }
                    // And display it
                    this._moreTabsPanel.style.display = 'flex';
                }
            });
        }

        /**
         * Add a tab to the 'more-tabs' panel, displayed by clicking on the
         * 'more-tabs' icon
         */
        private _addInvisibleTabToPanel(tab: Tab) {
            let div = Helpers.CreateDiv('invisible-tab', this._moreTabsPanel);
            div.textContent = tab.name;
            div.addEventListener('click', () => {
                this._moreTabsPanel.style.display = 'none';
                this.switchTab(tab);
            });
        }

        /** Dispose the current tab, set the given tab as active, and refresh the treeview */
        public switchTab(tab: Tab) {
            // Dispose the active tab
            let activeTab = this.getActiveTab();

            if (activeTab) {
                activeTab.dispose();
            }

            // Deactivate all tabs
            for (let t of this._tabs) {
                t.active(false);
            }
            // activate the given tab
            tab.active(true);

            // Refresh the inspector
            this._inspector.refresh();
        }

        /** Display the mesh tab.
         * If a parameter is given, the given mesh details are displayed
         */
        public switchMeshTab(mesh?: BABYLON.AbstractMesh) {
            this.switchTab(this._meshTab);
            if (mesh) {
                let item = this._meshTab.getItemFor(mesh);
                if (item) {
                    this._meshTab.select(item);
                }
            }
        }

        /** Returns the active tab */
        public getActiveTab(): BABYLON.Nullable<Tab> {
            for (let tab of this._tabs) {
                if (tab.isActive()) {
                    return tab;
                }
            }

            return null;
        }

        public getActiveTabIndex(): number {
            for (let i = 0; i < this._tabs.length; i++) {
                if (this._tabs[i].isActive()) {
                    return i;
                }
            }
            return 0;
        }

        public get inspector(): Inspector {
            return this._inspector;
        }

        /**
         * Returns the total width in pixel of the tabbar,
         * that corresponds to the sum of the width of each visible tab + toolbar width
        */
        public getPixelWidth(): number {
            let sum = 0;
            for (let tab of this._visibleTabs) {
                sum += tab.getPixelWidth();
            }
            sum += this._toolBar.getPixelWidth();
            if (this._div.contains(this._moreTabsIcon)) {
                sum += 30; // $tabbarheight
            }
            return sum;
        }

        /** Display the remaining icon or not depending on the tabbar width.
         * This function should be called each time the inspector width is updated
         */
        public updateWidth(): void {
            if (!this._div.parentElement) {
                return;
            }
            let parentSize = this._div.parentElement.clientWidth;
            let lastTabWidth = 75;
            let currentSize = this.getPixelWidth();

            // Check if a tab should be removed : if the tab bar width is greater than
            // its parent width
            while (this._visibleTabs.length > 0 && currentSize > parentSize) {
                // Start by the last element
                let tab = this._visibleTabs.pop();

                if (!tab) {
                    break;
                }

                // set it invisible
                this._invisibleTabs.push(tab);
                // and removes it from the DOM
                this._div.removeChild(tab.toHtml());
                currentSize = this.getPixelWidth() + lastTabWidth;
            }

            // Check if a tab can be added to the tab bar : if the tab bar width
            // + 100 (at least 100px is needed to add a tab) is less than its parent width
            if (this._invisibleTabs.length > 0) {
                if (currentSize + lastTabWidth < parentSize) {
                    let lastTab = this._invisibleTabs.pop();

                    if (lastTab) {
                        this._div.appendChild(lastTab.toHtml());
                        this._visibleTabs.push(lastTab);
                    }
                    // Update more-tab icon in last position if needed
                    if (this._div.contains(this._moreTabsIcon)) {
                        this._div.removeChild(this._moreTabsIcon);
                    }
                }
            }
            if (this._invisibleTabs.length > 0 && !this._div.contains(this._moreTabsIcon)) {
                this._div.appendChild(this._moreTabsIcon);
            }
        }

    }
}


text:
export function isJsOrResponseType(data: any): boolean {
    const jsType =
        data.type === 'undefined' ||
        data.type === 'object' ||
        data.type === 'boolean' ||
        data.type === 'number' ||
        data.type === 'bigint' ||
        data.type === 'string' ||
        data.type === 'symbol' ||
        data.type === 'function';

    const responseType = data.type === 'response';

    return responseType || jsType;
}


text:
package com.google.appengine.samples;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Partial1Servlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      resp.setContentType("text/html");
      resp.getWriter().println("
This is the partial for view 1.
");
  }
}


text:
package org.elasticsearch.action.admin.indices.validate.query;

import org.elasticsearch.action.support.broadcast.BroadcastShardOperationRequest;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.index.shard.ShardId;

import java.io.IOException;

/**
 * Internal validate request executed directly against a specific index shard.
 */
class ShardValidateQueryRequest extends BroadcastShardOperationRequest {

    private BytesReference source;
    private String[] types = Strings.EMPTY_ARRAY;
    private boolean explain;
    private boolean rewrite;
    private long nowInMillis;

    @Nullable
    private String[] filteringAliases;

    ShardValidateQueryRequest() {

    }

    ShardValidateQueryRequest(ShardId shardId, @Nullable String[] filteringAliases, ValidateQueryRequest request) {
        super(shardId, request);
        this.source = request.source();
        this.types = request.types();
        this.explain = request.explain();
        this.rewrite = request.rewrite();
        this.filteringAliases = filteringAliases;
        this.nowInMillis = request.nowInMillis;
    }

    public BytesReference source() {
        return source;
    }

    public String[] types() {
        return this.types;
    }

    public boolean explain() {
        return this.explain;
    }

    public boolean rewrite() {
        return this.rewrite;
    }

    public String[] filteringAliases() {
        return filteringAliases;
    }

    public long nowInMillis() {
        return this.nowInMillis;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        source = in.readBytesReference();

        int typesSize = in.readVInt();
        if (typesSize > 0) {
            types = new String[typesSize];
            for (int i = 0; i < typesSize; i++) {
                types[i] = in.readString();
            }
        }
        int aliasesSize = in.readVInt();
        if (aliasesSize > 0) {
            filteringAliases = new String[aliasesSize];
            for (int i = 0; i < aliasesSize; i++) {
                filteringAliases[i] = in.readString();
            }
        }

        explain = in.readBoolean();
        rewrite = in.readBoolean();
        nowInMillis = in.readVLong();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeBytesReference(source);

        out.writeVInt(types.length);
        for (String type : types) {
            out.writeString(type);
        }
        if (filteringAliases != null) {
            out.writeVInt(filteringAliases.length);
            for (String alias : filteringAliases) {
                out.writeString(alias);
            }
        } else {
            out.writeVInt(0);
        }

        out.writeBoolean(explain);
        out.writeBoolean(rewrite);
        out.writeVLong(nowInMillis);
    }
}


text: This is restaurants list page


text:
window.varDumpListenerTools = (cascade, specialClass) => {
    function toggleCollapse() {
        const $collapser = $(this);

        if ($collapser.hasClass('closed')) { // if it is closed
            $collapser.siblings('ul').children('li').removeClass('hide');
            $collapser.removeClass('closed');
        } else { // if it is open
            collapse($collapser) // collapse this element

            if (cascade === 'true') { // if we want to cascade down, collapse the other elements as well
                collapseAllChildren($collapser.siblings('ul'))
            }
        }
    }

    function collapse($element) {
        $element.siblings('ul').children('li').addClass('hide');
        $element.addClass('closed');
    }

    function collapseAllChildren($start) {
        const all = $start.find('.openClose .openCloseIcon'); // get all collapsers ...
        for (let i = 0; i < all.length; i++) { // ... and close them
            collapse($(all[i]));
        }
    }

    function openAll() {
        const $varDumpChildren = $('#var_dump').find('*')
        $varDumpChildren.removeClass('hide'); // remove the hide class from everything
        $varDumpChildren.removeClass('closed'); // <-- could be way more efficient
    }

    function closeAll() {
        collapseAllChildren($('#var_dump'))
    }

    function toggleFullScreen() {
        $('.var_dump_modal').toggleClass('fullScreen')
    }

    function openOptions() {
        chrome.extension.sendRequest({action: 'openOptionsPage'})
    }

    function addListeners() {
        $('.openClose .openCloseIcon').bind('click', toggleCollapse);
        $('#expandAll').bind('click', openAll);
        $('#collapseAll').bind('click', closeAll);
        $('.fullScreen').bind('click', toggleFullScreen);
        $('.settings').bind('click', openOptions)
        addCloseListener();
    }

    function addCloseListener() {
        $('.closeModal').bind('click', () => {
            $(`.${specialClass}`).remove();
        });
    }

    return {
        addListeners: addListeners,
        addCloseListener: addCloseListener
    }
}


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.
 */

package org.brixcms.jcr.base.wrapper;

import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;

class ValueFactoryWrapper extends BaseWrapper<ValueFactory> implements ValueFactory {
// -------------------------- STATIC METHODS --------------------------

    public static ValueFactory wrap(ValueFactory delegate, SessionWrapper session) {
        if (delegate == null) {
            return null;
        } else {
            return new ValueFactoryWrapper(delegate, session);
        }
    }

// --------------------------- CONSTRUCTORS ---------------------------

    private ValueFactoryWrapper(ValueFactory delegate, SessionWrapper session) {
        super(delegate, session);
    }

// ------------------------ INTERFACE METHODS ------------------------

// --------------------- Interface ValueFactory ---------------------

    public Value createValue(String value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(String value, int type) throws ValueFormatException {
        return getDelegate().createValue(value);
    }

    public Value createValue(long value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(double value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(BigDecimal value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(boolean value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(Calendar value) {
        return getDelegate().createValue(value);
    }

    /**
     * @deprecated
     */
    @Deprecated
    public Value createValue(InputStream value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(Binary value) {
        return getDelegate().createValue(value);
    }

    public Value createValue(Node value) throws RepositoryException {
        return getDelegate().createValue(unwrap(value));
    }

    public Value createValue(Node value, boolean weak) throws RepositoryException {
        return getDelegate().createValue(value, weak);
    }

    public Binary createBinary(InputStream stream) throws RepositoryException {
        return getDelegate().createBinary(stream);
    }
}


text:
This package supports native net3.5+ and netstandard1.0+ and only includes the abstractions.

To use DotNetStarter, please use the DotNetStarter or other implementation package.

The goal of this package to create a startup framework for any dotnet project where everything is swappable via Inversion Of Control (IoC) or object factories (AssemblyFactoryBaseAttribute).

[Website](https://bmcdavid.github.io/DotNetStarter/)


text:
<?php

class Onxshop_Controller_Bo_Component_News_Add extends Onxshop_Controller {

	/**
	 * main action
	 */

	public function mainAction() {

		require_once('models/common/common_node.php');
		$Node = new common_node();

		$news_list_detail = $Node->getDetail($this->GET['blog_node_id']);
		$this->tpl->assign("NEWS_LIST", $news_list_detail);

		$node_data = $_POST['node'];

		if ($_POST['save']) {

			/**
			 * pre-populate content
			 */

			$node_data['description'] = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
			$node_data['content'] = '

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

velit esse cillum dolore

consectetur adipisicing elit

occaecat cupidatat non proident

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			';

			/**
			 * insert a new node
			 */

			if($id = $Node->nodeInsert($node_data)) {

				msg(ucfirst($node_data['node_group']) ." has been added.");

				//quick pages builder
				//$Page_builder = new Onxshop_Request("bo/page_builder@blank&parent=$id&node_group={$node_data['node_group']}&node_controller={$node_data['node_controller']}");
			}
		}

		$this->tpl->assign('NODE', $node_data);

		return true;
	}
}


text:
<?php
/**
 * This is a Deus pagecontroller.
 *
 */
// Include the essential config-file which also creates the $deus variable with its defaults.
include(__DIR__.'/config.php');

// Do it and store it all in variables in the Deus container.
$deus['title'] = "404";
$deus['header'] = "";
$deus['main'] = "This is a Anax 404. Document is not here.";
$deus['footer'] = "";

// Send the 404 header
header("HTTP/1.0 404 Not Found");

// Finally, leave it all to the rendering phase of Deus.
include(DEUS_THEME_PATH);


text:
{% extends 'django_openstack/dash/base.html' %}
{%load i18n%}

{% block sidebar %}
  {% with current_sidebar="security_groups" %}
    {{block.super}}
  {% endwith %}
{% endblock %}

{% block page_header %}
  {% url dash_security_groups request.user.tenant_id as refresh_link %}
  {# to make searchable false, just remove it from the include statement #}
  {% include "django_openstack/common/_page_header.html" with title=_("Security Groups") refresh_link=refresh_link searchable="true" %}
{% endblock page_header %}

{% block dash_main %}
  {% if security_groups %}
    {% include 'django_openstack/dash/security_groups/_list.html' %}
    {% url dash_security_groups_create request.user.tenant_id as create_sec_url %}
    {% trans "Create Security Group"%}
  {% else %}

      {% url dash_security_groups_create request.user.tenant_id as dash_sec_url %}

{% trans "Info"%}

{% blocktrans %}There are currently no security groups. Create A Security Group >>{% endblocktrans %}

  {% endif %}
{% endblock %}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="inventoryService"
	      class="ajia.service.impl.InventoryServiceStubImpl" />
</beans>

	<!-- Listing 9.2 application-context.xml: application context file -->


text:
<?php

namespace Symfony\Bridge\PhpUnit\Tests\FailTests;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;

/**
 * This class is deliberately suffixed with *TestRisky.php so that it is ignored
 * by PHPUnit. This test is designed to fail. See ../expectnotrisky.phpt.
 */
final class NoAssertionsTestNotRisky extends TestCase
{
    use ExpectDeprecationTrait;

    /**
     * Do not remove this test in the next major version.
     */
    public function testOne()
    {
        $this->expectNotToPerformAssertions();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using WinLess.Helpers;

namespace WinLess.Models
{
    public class File
    {
        #region Constructor

        private File()
        {
            this.ParentFiles = new List<File>();
        }

        public File(Models.Directory directory, string fullPath)
        {
            this.FullPath = fullPath;
            this.ProjectDirectoryPath = directory.FullPath;
            this.Minify = Program.Settings.DefaultMinify;
            this.Enabled = true;
            this.OutputPath = GetInitialOutputPath();
            this.ParentFiles = new List<File>();
            CheckForImports();
        }

        #endregion

        #region Properties

        public string FullPath
        {
            get;
            set;
        }

        public string DirectoryPath
        {
            get
            {
                return Path.GetDirectoryName(this.FullPath);
            }
        }

        public string ProjectDirectoryPath
        {
            get;
            set;
        }

        public string RelativePath
        {
            get
            {
                return FullPath.Replace(ProjectDirectoryPath, "").Substring(1); ;
            }
        }

        public string OutputPath
        {
            get;
            set;
        }

        public string RelativeOutputPath
        {
            get
            {
                Uri outputPathUri = new Uri(OutputPath);
                Uri projectDirPathUri = new Uri(string.Format("{0}\\", ProjectDirectoryPath));
                return Uri.UnescapeDataString(projectDirPathUri.MakeRelativeUri(outputPathUri).ToString()).Replace("/", "\\");
            }
        }

        public bool Minify
        {
            get;
            set;
        }

        public bool Enabled
        {
            get;
            set;
        }

        [XmlIgnore]
        public List<File> ParentFiles
        {
            get; set;
        }

        #endregion

        #region Public Methods

        public void CheckForImports()
        {
            List<string> importPaths = this.GetLessImportPaths();
            foreach (string importPath in importPaths)
            {
                File importFile = Program.Settings.DirectoryList.GetFile(importPath);
                if(importFile != null && importFile.ParentFiles.Find(f => string.Compare(f.FullPath, this.FullPath, StringComparison.InvariantCultureIgnoreCase) == 0) == null)
                {
                    importFile.ParentFiles.Add(this);
                }
            }
        }

        public void Compile(bool compileParentFiles = true)
        {
            if (this.Enabled)
            {
                LessCompiler.Compile(this.FullPath, this.OutputPath, this.Minify);
            }
            if (compileParentFiles)
            {
                foreach (File parentFile in this.ParentFiles)
                {
                    parentFile.Compile();
                }
            }

            //Recheck the imports of the current file
            CheckForImports();
        }

        #endregion

        #region Private Methods

        private string GetInitialOutputPath()
        {
            return string.Format("{0}{1}", GetInitialOuputDir(), GetInitialOuputFileName());
        }

        private string GetInitialOuputDir()
        {
            FileInfo fileInfo = new FileInfo(this.FullPath);
            string directoryName = string.Format("{0}\\", fileInfo.DirectoryName);

            if (directoryName.Contains("\\less\\")){
                if (System.IO.Directory.Exists(directoryName.Replace("\\less\\", "\\css\\"))){
                    return directoryName.Replace("\\less\\", "\\css\\");
                }
                else if (System.IO.Directory.Exists(directoryName.Replace("\\less\\", "\\..\\css\\"))){
                    return directoryName.Replace("\\less\\", "\\..\\css\\");
                }
                else if (System.IO.Directory.Exists(directoryName.Replace("\\less\\", "\\less\\css\\"))){
                    return directoryName.Replace("\\less\\", "\\less\\css\\");
                }
            }

            //no matches, use same dir as the less file is in
            return directoryName;
        }

        private string GetInitialOuputFileName()
        {
            FileInfo fileInfo = new FileInfo(this.FullPath);
            string fileName = fileInfo.Name.Replace(fileInfo.Extension, ".css");
            if (fileName.Contains(".less"))
            {
                fileName = fileName.Replace(".less", "");
            }
            return fileName;
        }

        private List<string> GetLessImportPaths()
        {
            List<string> lessImportPaths = new List<string>();
            string fileText = this.GetFileText();
            if (!string.IsNullOrEmpty(fileText))
            {
                // find the @imports using regex
                MatchCollection matches = Regex.Matches(fileText, "@import\\s*(?:url\\()?\\s*[\"\\']?([^\"\\'\\);]+)[\"\\']?\\s*\\)?\\s*;");

                foreach (Match match in matches)
                {
                    if (match.Groups.Count > 1)
                    {
                        string cssImportValue = match.Groups[1].Value;

                        // if the import is a .less import
                        if (!cssImportValue.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase) ||
                            cssImportValue.EndsWith(".less.css", StringComparison.InvariantCultureIgnoreCase))
                        {
                            string relativeImportPath = cssImportValue.Replace("/", "\\");

                            // if the import doesn't include the .less extension
                            if (!cssImportValue.EndsWith(".less.css", StringComparison.InvariantCultureIgnoreCase) &&
                                !cssImportValue.EndsWith(".less", StringComparison.InvariantCultureIgnoreCase))
                            {
                                relativeImportPath = string.Format("{0}.less", relativeImportPath);
                            }

                            try
                            {
                                string fullImportPath = Path.GetFullPath(string.Format("{0}\\{1}", this.DirectoryPath, relativeImportPath));
                                lessImportPaths.Add(fullImportPath);
                            }
                            catch {
                                //invalid path, ignore this here
                            }
                        }
                    }
                }
            }

            return lessImportPaths;
        }

        private string GetFileText()
        {
            string fileText = null;
            try
            {
                StreamReader streamReader = new StreamReader(this.FullPath);
                fileText = streamReader.ReadToEnd();
                streamReader.Close();
            }
            catch (Exception e)
            {
                ExceptionHandler.LogException(e);
            }

            return fileText;
        }

        #endregion
    }
}


text:
package org.socraticgrid.hl7.ucs.nifi.common.serialization;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socraticgrid.hl7.ucs.nifi.common.model.ExceptionWrapper;

/**
 * Utility class used to de/serialize ExceptionWrapper objects.
 * @author esteban
 */
public class ExceptionWrapperSerializer {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionWrapperSerializer.class);

    public static String serializeExceptionWrapper(ExceptionWrapper exceptionWrapper) throws MessageSerializationException {
        try {
            logger.debug("Serializing ExceptionWrapper {}", exceptionWrapper);
            JAXBContext context = JAXBContext.newInstance(ExceptionWrapper.class);
            Marshaller m = context.createMarshaller();

            StringWriter result = new StringWriter();
            m.marshal(exceptionWrapper, result);

            return result.toString();

        } catch (Exception e) {
            throw new MessageSerializationException("Exception in ExceptionWrapper serialization.", e);
        }
    }

    public static ExceptionWrapper deserializeExceptionWrapper(InputStream exceptionWrapper) throws MessageSerializationException {
        try {
            logger.debug("Deserializing ExceptionWrapper");
            JAXBContext context = JAXBContext.newInstance(ExceptionWrapper.class);
            Unmarshaller u = context.createUnmarshaller();

            return (ExceptionWrapper)u.unmarshal(exceptionWrapper);
        } catch (Exception e) {
            throw new MessageSerializationException("Exception in ExceptionWrapper deserialization.", e);
        }
    }

    public static ExceptionWrapper deserializeExceptionWrapper(String exceptionWrapper) throws MessageSerializationException {
        return deserializeExceptionWrapper(new ByteArrayInputStream(exceptionWrapper.getBytes()));
    }
}


text:
###Description

A small userscript to help avoid clutter on the sidebar of any Stack Exchange chat room.

- The chat room will load without showing the chat room's info or the present users in the chat room

- There will be buttons that say "Show Info" or "Show Users", and when they are clicked on, the chat room's info or the present users will be shown

- When the chat room's info or present users are visible, there will be buttons saying "Hide Info" and "Hide Users", and those will hide the chat room's info or present users

------------------

This userscript supports Chrome and should support all other browsers.


text:
<TITLE>
cef_string_list.h
</TITLE>

// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef _CEF_STRING_LIST_H
#define _CEF_STRING_LIST_H

#include "cef_export.h"
#include "cef_string.h"

#ifdef __cplusplus
extern "C" {
#endif

///
// CEF string maps are a set of key/value string pairs.
///
typedef void* cef_string_list_t;

///
// Allocate a new string map.
///
CEF_EXPORT cef_string_list_t cef_string_list_alloc();

///
// Return the number of elements in the string list.
///
CEF_EXPORT int cef_string_list_size(cef_string_list_t list);

///
// Retrieve the value at the specified zero-based string list index. Returns
// true (1) if the value was successfully retrieved.
///
CEF_EXPORT int cef_string_list_value(cef_string_list_t list,
                                     int index, cef_string_t* value);

///
// Append a new value at the end of the string list.
///
CEF_EXPORT void cef_string_list_append(cef_string_list_t list,
                                       const cef_string_t* value);

///
// Clear the string list.
///
CEF_EXPORT void cef_string_list_clear(cef_string_list_t list);

///
// Free the string list.
///
CEF_EXPORT void cef_string_list_free(cef_string_list_t list);

///
// Creates a copy of an existing string list.
///
CEF_EXPORT cef_string_list_t cef_string_list_copy(cef_string_list_t list);

#ifdef __cplusplus
}
#endif

#endif // _CEF_STRING_LIST_H


text:
<?php

namespace Kunstmaan\AdminListBundle\AdminList\Configurator;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Kunstmaan\AdminBundle\Helper\Security\Acl\AclHelper;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition;
use Kunstmaan\AdminListBundle\AdminList\Filter;
use Kunstmaan\AdminListBundle\AdminList\FilterType\ORM\AbstractORMFilterType;
use Kunstmaan\AdminListBundle\AdminList\SortableInterface;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use Traversable;

/**
 * An abstract admin list configurator that can be used with the orm query builder
 */
abstract class AbstractDoctrineORMAdminListConfigurator extends AbstractAdminListConfigurator
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

    /**
     * @var Query
     */
    private $query;

    /**
     * @var Pagerfanta
     */
    private $pagerfanta;

    /**
     * @var PermissionDefinition
     */
    private $permissionDef;

    /**
     * @var AclHelper
     */
    protected $aclHelper;

    /**
     * AbstractDoctrineORMAdminListConfigurator constructor.
     *
     * @param EntityManagerInterface $em
     * @param AclHelper|null         $aclHelper
     */
    public function __construct(EntityManagerInterface $em, AclHelper $aclHelper = null)
    {
        $this->em = $em;
        $this->aclHelper = $aclHelper;
    }

    /**
     * Return the url to edit the given $item
     *
     * @param object $item
     *
     * @return array
     */
    public function getEditUrlFor($item)
    {
        $params = array('id' => $item->getId());
        $params = array_merge($params, $this->getExtraParameters());

        return array(
            'path' => $this->getPathByConvention($this::SUFFIX_EDIT),
            'params' => $params,
        );
    }

    /**
     * Get the delete url for the given $item
     *
     * @param object $item
     *
     * @return array
     */
    public function getDeleteUrlFor($item)
    {
        $params = array('id' => $item->getId());
        $params = array_merge($params, $this->getExtraParameters());

        return array(
            'path' => $this->getPathByConvention($this::SUFFIX_DELETE),
            'params' => $params,
        );
    }

    /**
     * @return Pagerfanta
     */
    public function getPagerfanta()
    {
        if (\is_null($this->pagerfanta)) {
            $adapter = new DoctrineORMAdapter($this->getQuery());
            $this->pagerfanta = new Pagerfanta($adapter);
            $this->pagerfanta->setNormalizeOutOfRangePages(true);
            $this->pagerfanta->setMaxPerPage($this->getLimit());
            $this->pagerfanta->setCurrentPage($this->getPage());
        }

        return $this->pagerfanta;
    }

    /**
     * @param QueryBuilder $queryBuilder
     */
    public function adaptQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilder->where('1=1');
    }

    /**
     * @return int
     */
    public function getCount()
    {
        return $this->getPagerfanta()->getNbResults();
    }

    /**
     * @return array|Traversable
     */
    public function getItems()
    {
        return $this->getPagerfanta()->getCurrentPageResults();
    }

    /**
     * Return an iterator for all items that matches the current filtering
     *
     * @return \Iterator
     */
    public function getIterator()
    {
        return $this->getQuery()->iterate();
    }

    /**
     * @return Query|null
     */
    public function getQuery()
    {
        if (\is_null($this->query)) {
            $queryBuilder = $this->getQueryBuilder();
            $this->adaptQueryBuilder($queryBuilder);

            // Apply filters
            $filters = $this->getFilterBuilder()->getCurrentFilters();
            /* @var Filter $filter */
            foreach ($filters as $filter) {
                /* @var AbstractORMFilterType $type */
                $type = $filter->getType();
                $type->setQueryBuilder($queryBuilder);
                $filter->apply();
            }

            // Apply sorting
            if (!empty($this->orderBy)) {
                $orderBy = $this->orderBy;
                if ($this->getEntityManager()->getClassMetadata($this->getRepositoryName())->hasAssociation($this->orderBy)) {
                    $queryBuilder->leftJoin('b.' . $orderBy, 'A' . $orderBy);
                    $orderBy = 'A' . $orderBy . '.id';
                } elseif (!strpos($orderBy, '.')) {
                    $orderBy = 'b.' . $orderBy;
                }
                $queryBuilder->orderBy($orderBy, ($this->orderDirection == 'DESC' ? 'DESC' : 'ASC'));
            }

            // Apply other changes
            $this->finishQueryBuilder($queryBuilder);

            // Apply ACL restrictions (if applicable)
            if (!\is_null($this->permissionDef) && !\is_null($this->aclHelper)) {
                $this->query = $this->aclHelper->apply($queryBuilder, $this->permissionDef);
            } else {
                $this->query = $queryBuilder->getQuery();
            }
        }

        return $this->query;
    }

    /**
     * @param QueryBuilder $queryBuilder
     */
    protected function finishQueryBuilder(QueryBuilder $queryBuilder)
    {
        if ($this instanceof SortableInterface) {
            $queryBuilder->addOrderBy('b.' . $this->getSortableField());
        }
    }

    /**
     * @return QueryBuilder
     */
    protected function getQueryBuilder()
    {
        $queryBuilder = $this->em
            ->getRepository($this->getRepositoryName())
            ->createQueryBuilder('b');

        return $queryBuilder;
    }

    /**
     * Get current permission definition.
     *
     * @return PermissionDefinition|null
     */
    public function getPermissionDefinition()
    {
        return $this->permissionDef;
    }

    /**
     * Set permission definition.
     *
     * @param PermissionDefinition $permissionDef
     *
     * @return AbstractDoctrineORMAdminListConfigurator
     */
    public function setPermissionDefinition(PermissionDefinition $permissionDef)
    {
        $this->permissionDef = $permissionDef;

        return $this;
    }

    /**
     * @param EntityManagerInterface $em
     *
     * @return AbstractDoctrineORMAdminListConfigurator
     */
    public function setEntityManager(EntityManagerInterface $em)
    {
        $this->em = $em;

        return $this;
    }

    /**
     * @return EntityManagerInterface
     */
    public function getEntityManager()
    {
        return $this->em;
    }
}


text:
var express = require('express');
var app = express();
//var port = process.env.PORT || 3000;

app.set('port', (process.env.PORT || 3000));

app.use(express.static(__dirname + '/dist'));

app.get('/feature', function (req, res) {
    res.sendfile( __dirname + '/dist/features.html');
})

//app.listen(port, function () {
app.listen(app.get('port'), function() {
    console.log('Example app listening on port 3000!')
})


text:
class FlowField
  attr_reader :cols, :field, :resolution, :rows

  def initialize(resolution:, width:, height:)
    @resolution = resolution
    @cols = width / resolution
    @rows = height / resolution
    reset!
  end

  def display
    field.each_with_index do |row, i|
      row.each_with_index do |v, j|
        draw_vector(v, i * resolution, j * resolution, resolution - 1)
      end
    end
  end

  def draw_vector(v, x, y, scayl)
    push_matrix
    translate(x, y)
    stroke(0, 100)
    rotate(v.heading)
    len = v.mag * scayl
    line(0, 0, len, 0)
    pop_matrix
  end

  def lookup(vector)
    column = constrain(vector.x / resolution, 0, cols - 1).to_i
    row = constrain(vector.y / resolution, 0, rows - 1).to_i
    field[column][row].copy
  end

  def reset!
    @field = create_field(cols, rows)
  end

  private

  def create_field(cols, rows)
    noise_seed(rand(10_000))
    xoff = -1
    Array.new(cols) do
      yoff = 0
      xoff += 1
      Array.new(rows) do
        theta = map1d(noise(xoff, yoff), (-1..1.0), (0..TWO_PI))
        yoff += 1
        Vec2D.new(cos(theta), sin(theta))
      end
    end
    # need to return field 2D Array
  end
end

class Vehicle
  attr_reader :acceleration, :location, :velocity, :width, :height

  def initialize(location:, maxspeed:, maxforce:, max_x:, max_y:)
    @acceleration = Vec2D.new
    @velocity = Vec2D.new(0, -2)
    @location = location
    @r = 6
    @maxspeed = maxspeed
    @maxforce = maxforce
    @width = max_x
    @height = max_y
  end

  def run
    update
    borders # ensure we don't lose those vehicles
    display
  end

  def apply_force(force:)
    @acceleration += force
  end

  def update
    @velocity += acceleration
    @velocity.set_mag(@maxspeed) { velocity.mag > @maxspeed }
    @location += velocity
    @acceleration *= 0
  end

  def follow(field: flowfield)
    # What is the vector at that spot in the flow field?
    desired = flowfield.lookup(location)
    # Scale it up by maxspeed
    desired *= @maxspeed
    # Steering is desired minus velocity
    steer = desired - velocity
    steer.set_mag(@maxforce) { steer.mag > @maxforce }
    apply_force(force: steer)
  end

  def display
    theta = velocity.heading + PI / 2
    fill(127)
    stroke(0)
    stroke_weight(1)
    push_matrix
    translate(location.x, location.y)
    rotate(theta)
    begin_shape
    vertex(0, -@r * 2)
    vertex(-@r, @r * 2)
    vertex(@r, @r * 2)
    end_shape(CLOSE)
    pop_matrix
  end

  def borders
    location.x = width - @r if location.x < -@r
    location.y = height - @r if location.y < -@r
    location.x = -@r if location.x > width + @r
    location.y = -@r if location.y > height + @r
  end
end

attr_reader :flowfield, :vehicles

def setup
  sketch_title 'Flow Field'
  @flowfield = FlowField.new(
    resolution: 20,
    width: width,
    height: height
  )
  @vehicles = Array.new(120) do
    Vehicle.new(
      location: Vec2D.new(rand(width), rand(height)),
      maxspeed: rand(2.0..5),
      maxforce: rand(0.1..0.5),
      max_x: width,
      max_y: height
    )
  end
end

def draw
  background(255)
  vehicles.each do |v|
    v.follow(field: flowfield)
    v.run
  end
  flowfield.display
end

def settings
  size(640, 340)
end

def mouse_pressed
  flowfield.reset!
end


text:
<?PHP

// class for interacting with order_items table
class odr_itms_tbl {
	public $id;
	public $order_id;
	public $item_id;
	public $certificate_value_id;
	public $item_type;
	public $item_value;
	public $item_quantity;
	public $item_start_date;
	public $item_expiration_date;
	// table name used throughout queries within page
	private $tbl_nme = "order_items";

	public function __construct() {
		$this->reset_vars();
	}

	public function reset_vars() {
		$this->id = NULL;
		$this->order_id = NULL;
		$this->item_id = NULL;
		$this->certificate_value_id = NULL;
		$this->item_type = NULL;
		$this->item_value = NULL;
		$this->item_quantity = NULL;
		$this->item_start_date = NULL;
		$this->item_expiration_date = NULL;
	}

	// insert new order_items amount
	public function insert() {
			global $dbh;

		$sql_query = "INSERT INTO
						".$this->tbl_nme."
					 (
						order_id,
						item_id,
						certificate_value_id,
						item_type,
						item_value,
						item_quantity,
						item_start_date,
						item_expiration_date
					 )
					 VALUES
					 (
						?,
						?,
						?,
						?,
						?,
						?,
						?,
						?
					 );";

		$update_vals = array(
							$this->order_id,
							$this->item_id,
							$this->certificate_value_id,
							$this->item_type,
							$this->item_value,
							$this->item_quantity,
							$this->item_start_date,
							$this->item_expiration_date
							);

		$stmt = $dbh->prepare($sql_query);
		$stmt->execute($update_vals);

	}

	// update existing order_items
	public function update() {
			global $dbh;

		$sql_query = "UPDATE
						".$this->tbl_nme."
					 SET
						order_id = ?,
						item_id = ?,
						certificate_value_id = ?,
						item_type = ?,
						item_value = ?,
						item_quantity =?,
						item_start_date = ?,
						item_expiration_date = ?
					 WHERE
						id = ?
					 ;";

		$update_vals = array(
							$this->order_id,
							$this->item_id,
							$this->certificate_value_id,
							$this->item_type,
							$this->item_value,
							$this->item_quantity,
							$this->item_start_date,
							$this->item_expiration_date,
							$this->id
							);

		$stmt = $dbh->prepare($sql_query);
		$stmt->execute($update_vals);

	}

	// write post vars to class variables
	public function get_post_vars() {

		$this->id = (isset($_POST['id']) ? $_POST['id'] : '');
		$this->order_id = (isset($_POST['order_id']) ? $_POST['order_id'] : '');
		$this->item_id = (isset($_POST['item_id']) ? $_POST['item_id'] : '');
		$this->certificate_value_id = (isset($_POST['certificate_value_id']) ? $_POST['certificate_value_id'] : '');
		$this->item_type = (isset($_POST['item_type']) ? $_POST['item_type'] : '');
		$this->item_value = (isset($_POST['item_value']) ? $_POST['item_value'] : '');
		$this->item_quantity = (isset($_POST['item_quantity']) ? $_POST['item_quantity'] : '');
		$this->item_start_date = (isset($_POST['item_start_date']) ? $_POST['item_start_date'] : '');
		$this->item_expiration_date = (isset($_POST['item_expiration_date']) ? $_POST['item_expiration_date'] : '');

	}

	// get vars from database
	public function get_db_vars($id) {
			global $dbh;

		$sql_query = "SELECT
						id,
						order_id,
						item_id,
						certificate_value_id,
						item_type,
						item_value,
						item_quantity,
						item_start_date,
						item_expiration_date
					 FROM
						".$this->tbl_nme."
					 WHERE
						id = ?
					  LIMIT 1;";

		$values = array(
						$id
						);

		$stmt = $dbh->prepare($sql_query);
		$result = $stmt->execute($values);

		$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);

		$this->id = $row['id'];
		$this->order_id = $row['order_id'];
		$this->item_id = $row['item_id'];
		$this->certificate_value_id = $row['certificate_value_id'];
		$this->item_type = $row['item_type'];
		$this->item_value = $row['item_value'];
		$this->item_quantity = $row['item_quantity'];
		$this->item_start_date = $row['item_start_date'];
		$this->item_expiration_date = $row['item_expiration_date'];

		// clear result set
		$result->free();

		// reset DB conn
		db_check_conn();
	}
}

?>


text:
/**
 *  Dependent types
 *  ===============
 *
 *  Yup it's more like a joke, 'cause where is the kind?
 *
 *  Note: Compile with -std=c++17.
 */

#include <iostream>
#include <vector>

template <typename N>
constexpr void
ensure_positive(N n)
{
	static_assert(n > 0);
}

int
main()
{
	auto three_t = std::integral_constant<int, 3>();
	std::vector<int> vec(three_t);
	std::cout << vec.size() << std::endl; // 3
	ensure_positive(three_t);
	return 0;
}


text:
<?=$title;?>

            <img src='<?=Url::templatePath();?>images/logo.png'  class="img-responsive" alt='<?=SITETITLE;?>'>

                <div class="<?=$_SESSION['yolo_message_type'];?>">

<?=$_SESSION['yolo_message'];?>

                <?php unset($_SESSION['yolo_message']); ?>

<?=$welcomeMessage;?>

                <input type="text" class="form-control" placeholder="Search...">

                <button class="btn btn-default" type="button">

                </button>

            <a class="btn btn-md btn-success" href="<?=DIR;?>subpage">
                <?php echo Language::show('openSubPage', 'Home'); ?>


text:
import hickle as hkl
import numpy as np
from keras import backend as K
from keras.preprocessing.image import Iterator

# Data generator that creates sequences for input into PredNet.
class SequenceGenerator(Iterator):
    def __init__(self, data_file, source_file, nt,
                 batch_size=8, shuffle=False, seed=None,
                 output_mode='error', sequence_start_mode='all', N_seq=None,
                 data_format=K.image_data_format()):
        self.X = hkl.load(data_file)  # X will be like (n_images, nb_cols, nb_rows, nb_channels)
        self.sources = hkl.load(source_file) # source for each image so when creating sequences can assure that consecutive frames are from same video
        self.nt = nt
        self.batch_size = batch_size
        self.data_format = data_format
        assert sequence_start_mode in {'all', 'unique'}, 'sequence_start_mode must be in {all, unique}'
        self.sequence_start_mode = sequence_start_mode
        assert output_mode in {'error', 'prediction'}, 'output_mode must be in {error, prediction}'
        self.output_mode = output_mode

        if self.data_format == 'channels_first':
            self.X = np.transpose(self.X, (0, 3, 1, 2))
        self.im_shape = self.X[0].shape

        if self.sequence_start_mode == 'all':  # allow for any possible sequence, starting from any frame
            self.possible_starts = np.array([i for i in range(self.X.shape[0] - self.nt) if self.sources[i] == self.sources[i + self.nt - 1]])
        elif self.sequence_start_mode == 'unique':  #create sequences where each unique frame is in at most one sequence
            curr_location = 0
            possible_starts = []
            while curr_location < self.X.shape[0] - self.nt + 1:
                if self.sources[curr_location] == self.sources[curr_location + self.nt - 1]:
                    possible_starts.append(curr_location)
                    curr_location += self.nt
                else:
                    curr_location += 1
            self.possible_starts = possible_starts

        if shuffle:
            self.possible_starts = np.random.permutation(self.possible_starts)
        if N_seq is not None and len(self.possible_starts) > N_seq:  # select a subset of sequences if want to
            self.possible_starts = self.possible_starts[:N_seq]
        self.N_sequences = len(self.possible_starts)
        super(SequenceGenerator, self).__init__(len(self.possible_starts), batch_size, shuffle, seed)

    def next(self):
        with self.lock:
            index_array, current_index, current_batch_size = next(self.index_generator)
        batch_x = np.zeros((current_batch_size, self.nt) + self.im_shape, np.float32)
        for i, idx in enumerate(index_array):
            idx = self.possible_starts[idx]
            batch_x[i] = self.preprocess(self.X[idx:idx+self.nt])
        if self.output_mode == 'error':  # model outputs errors, so y should be zeros
            batch_y = np.zeros(current_batch_size, np.float32)
        elif self.output_mode == 'prediction':  # output actual pixels
            batch_y = batch_x
        return batch_x, batch_y

    def preprocess(self, X):
        return X.astype(np.float32) / 255

    def create_all(self):
        X_all = np.zeros((self.N_sequences, self.nt) + self.im_shape, np.float32)
        for i, idx in enumerate(self.possible_starts):
            X_all[i] = self.preprocess(self.X[idx:idx+self.nt])
        return X_all


text:
""" Implement the patzer_greetings function """

import unittest

def patzer_greetings(list_of_greetings):
    """Create a function that returns True if the input list of strings
    contains the word "Greetings". Otherwise, the function returns False.
    """
    pass # TODO remove this line and implement the function

# Tests below
# You can look, but don't touch!

class PatzerGreetingsUnitTests(unittest.TestCase):
    """Test the patzer_greetings function"""

    def test_returns_true_for_greeting(self):
        inputs = ["Hey", "Hello", "Greetings", "Hola"]
        self.assertTrue(patzer_greetings(inputs))

    def test_returns_false_for_no_greetings(self):
        inputs = ["Hey", "Hello", "Hola"]
        self.assertFalse(patzer_greetings(inputs))

    def test_returns_false_for_empty_list(self):
        self.assertFalse(patzer_greetings([]))

    def test_logic_is_lower_case_insensitive(self):
        inputs = ["Hey", "Hello", "Greetings", "Hola"]
        lower_inputs = list(map(lambda x: x.lower(), inputs))
        self.assertTrue(patzer_greetings(lower_inputs))

    def test_logic_is_upper_case_insensitive(self):
        inputs = ["Hey", "Hello", "Greetings", "Hola"]
        upper_inputs = list(map(lambda x: x.upper(), inputs))
        self.assertTrue(patzer_greetings(upper_inputs))

if __name__ == '__main__':
    unittest.main()


text:
package spark.streaming.dstream

import spark.streaming.{Duration, DStream, Time}
import spark.RDD

private[streaming]
class FilteredDStream[T: ClassManifest](
    parent: DStream[T],
    filterFunc: T => Boolean
  ) extends DStream[T](parent.ssc) {

  override def dependencies = List(parent)

  override def slideDuration: Duration = parent.slideDuration

  override def compute(validTime: Time): Option[RDD[T]] = {
    parent.getOrCompute(validTime).map(_.filter(filterFunc))
  }
}


text:
package quasar.api

import java.lang.String

package object table {
  type TableColumn = Column[ColumnType.Scalar]

  object TableColumn {
    def apply(name: String, tpe: ColumnType.Scalar): TableColumn =
      Column(name, tpe)
  }
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Leadership Summit" />
<meta name="twitter:title" content="Leadership Summit"/>
<meta itemprop="name" content="Leadership Summit"><meta property="og:description" content="Interested in nominating an executive of your company to attend the Leadership Summit at DevOpsDays Dallas 2017? We greatly value leaders and want your executives to support you in this DevOps cultural movement from top down." />
  <meta name="twitter:description" content="Interested in nominating an executive of your company to attend the Leadership Summit at DevOpsDays Dallas 2017? We greatly value leaders and want your executives to support you in this DevOps cultural movement from top down." />
  <meta itemprop="description" content="Interested in nominating an executive of your company to attend the Leadership Summit at DevOpsDays Dallas 2017? We greatly value leaders and want your executives to support you in this DevOps cultural movement from top down."><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="event" />
<meta property="og:url" content="/events/2017-dallas/leadership/" /><meta name="twitter:creator" content="@devopsdaysdfw" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Dallas 2017" /><meta name="twitter:label2" value="Dates" />
    <meta name="twitter:data2" value="August 28 - 30, 2017" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="263">
<title>Leadership Summit
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Dallas
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  propose

                  location

                  program

                  registration

                  speakers

                  sponsor

                  contact

                  conduct

devopsdays Dallas - Leadership Summit

DevOps Leadership Summit in Dallas

by: Michael Hedgpeth

Last year when we organized the first DevOps Days DFW, many attendees told us that they thought the content was fantastic, but that they wished they could have something that they could invite their leadership team to. Since alignment is so critical to changing anything in a large organization, the DevOps Days DFW Organizers agree and are pleased to announce a DevOps Leadership Summit on Monday, August 28, 2017 from 8:00 to 1:30 at the Capital One Plano Conference Center.

We're pleased to have Nicole Forsgren of DORA, Adam Jacob from Chef Software, and John Willis from SJ Technologies join us for the event. We will have a couple of talks, a workshop, and an interactive networking lunch where attendees can interact directly with our speakers.

Attendance to the event is limited to 50 people and is by invitation only through nominations. The ideal attendee is a Director, VP, or C-level executive who is or is interested in facilitating a DevOps transformation in his or her company. To nominate yourself or someone else, let us know how this person fits that criteria via email: organizers-dallas-2017@devopsdays.org.

The cost of the event is covered by a ticket to DevOps Days DFW 2017, which can be purchased here. We don't expect everyone attending the Leadership event to attend the entire DevOps Days. In fact, it would be just fine if they came to the keynotes in the morning and that's it.

If you know anyone who would benefit from coming to our Leadership Summit, please let us know!

Location & Platinum Sponsors

Platinum Sponsors

Gold Sponsors

Silver Sponsors
Join as Silver Sponsor!

Workshop Sponsors
Join as Workshop Sponsor!

Media Sponsors
Join as Media Sponsor!

Community Sponsors

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct