text:
struct TermMatch {
  TermMatch() : term_num(0), offset(0), length(0) {}
  TermMatch(int term_num, size_t offset, size_t length)
      : term_num(term_num),
        offset(offset),
        length(length) {}

  int term_num;  // The index of the term in the original search string.
  size_t offset;  // The starting offset of the substring match.
  size_t length;  // The length of the substring match.
};
typedef std::vector<TermMatch> TermMatches;

// Returns a TermMatches which has an entry for each occurrence of the
// string |term| found in the string |cleaned_string|. Use
// CleanUpUrlForMatching() or CleanUpUrlTitleMatching() before passing
// |cleaned_string| to this function. The function marks each match
// with |term_num| so that the resulting TermMatches can be merged
// with other TermMatches for other terms. Note that only the first
// 2,048 characters of |string| are considered during the match
// operation.
TermMatches MatchTermInString(const base::string16& term,
                              const base::string16& cleaned_string,
                              int term_num);

// Sorts and removes overlapping substring matches from |matches| and
// returns the cleaned up matches.
TermMatches SortAndDeoverlapMatches(const TermMatches& matches);

// Extracts and returns the offsets from |matches|.  This includes both
// the offsets corresponding to the beginning of a match and the offsets
// corresponding to the end of a match (i.e., offset+length for that match).
std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches);

// Replaces the offsets and lengths in |matches| with those given in |offsets|.
// |offsets| gives beginning and ending offsets for each match; this function
// translates (beginning, ending) offset into (beginning offset, length of
// match).  It deletes any matches for which an endpoint is npos and returns
// the updated list of matches.
TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches,
                                        const std::vector<size_t>& offsets);

// Convenience Types -----------------------------------------------------------

typedef std::vector<base::string16> String16Vector;
typedef std::set<base::string16> String16Set;
typedef std::set<base::char16> Char16Set;
typedef std::vector<base::char16> Char16Vector;

// A vector that contains the offsets at which each word starts within a string.
typedef std::vector<size_t> WordStarts;

// Utility Functions -----------------------------------------------------------

// Breaks the string |cleaned_uni_string| down into individual words.
// Use CleanUpUrlForMatching() or CleanUpUrlTitleMatching() before
// passing |cleaned_uni_string| to this function. If |word_starts| is
// not NULL then clears and pushes the offsets within
// |cleaned_uni_string| at which each word starts onto
// |word_starts|. These offsets are collected only up to the first
// kMaxSignificantChars of |cleaned_uni_string|.
String16Set String16SetFromString16(const base::string16& cleaned_uni_string,
                                    WordStarts* word_starts);

// Breaks the |cleaned_uni_string| string down into individual words
// and return a vector with the individual words in their original
// order.  Use CleanUpUrlForMatching() or CleanUpUrlTitleMatching()
// before passing |cleaned_uni_string| to this function.  If
// |break_on_space| is false then the resulting list will contain only
// words containing alpha-numeric characters. If |break_on_space| is
// true then the resulting list will contain strings broken at
// whitespace. (|break_on_space| indicates that the
// BreakIterator::BREAK_SPACE (equivalent to BREAK_LINE) approach is
// to be used. For a complete description of this algorithm refer to
// the comments in base/i18n/break_iterator.h.) If |word_starts| is
// not NULL then clears and pushes the word starts onto |word_starts|.
//
// Example:
//   Given: |cleaned_uni_string|: "http://www.google.com/ harry the rabbit."
//   With |break_on_space| false the returned list will contain:
//    "http", "www", "google", "com", "harry", "the", "rabbit"
//   With |break_on_space| true the returned list will contain:
//    "http://", "www.google.com/", "harry", "the", "rabbit."
String16Vector String16VectorFromString16(
    const base::string16& cleaned_uni_string,
    bool break_on_space,
    WordStarts* word_starts);

// Breaks the |uni_word| string down into its individual characters.
// Note that this is temporarily intended to work on a single word, but
// _will_ work on a string of words, perhaps with unexpected results.
// TODO(mrossetti): Lots of optimizations possible here for not restarting
// a search if the user is just typing along. Also, change this to uniString
// and properly handle substring matches, scoring and sorting the results
// by score. Also, provide the metrics for where the matches occur so that
// the UI can highlight the matched sections.
Char16Set Char16SetFromString16(const base::string16& uni_word);

// Support for InMemoryURLIndex Private Data -----------------------------------

// An index into a list of all of the words we have indexed.
typedef size_t WordID;

// A map allowing a WordID to be determined given a word.
typedef std::map<base::string16, WordID> WordMap;

// A map from character to the word_ids of words containing that character.
typedef std::set<WordID> WordIDSet;  // An index into the WordList.
typedef std::map<base::char16, WordIDSet> CharWordIDMap;

// A map from word (by word_id) to history items containing that word.
typedef history::URLID HistoryID;
typedef std::set<HistoryID> HistoryIDSet;
typedef std::vector<HistoryID> HistoryIDVector;
typedef std::map<WordID, HistoryIDSet> WordIDHistoryMap;
typedef std::map<HistoryID, WordIDSet> HistoryIDWordMap;

// Information used in scoring a particular URL.
typedef std::vector<history::VisitInfo> VisitInfoVector;
struct HistoryInfoMapValue {
  HistoryInfoMapValue();
  ~HistoryInfoMapValue();

  // This field is always populated.
  history::URLRow url_row;

  // This field gets filled in asynchronously after a visit.  As such,
  // it's almost always correct.  If it's wrong, it's likely to either
  // be empty (if this URL was recently added to the index) or
  // slightly out-of-date (one visit behind).
  VisitInfoVector visits;
};

// A map from history_id to the history's URL and title.
typedef std::map<HistoryID, HistoryInfoMapValue> HistoryInfoMap;

// A map from history_id to URL and page title word start metrics.
struct RowWordStarts {
  RowWordStarts();
  ~RowWordStarts();

  // Clears both url_word_starts_ and title_word_starts_.
  void Clear();

  WordStarts url_word_starts_;
  WordStarts title_word_starts_;
};
typedef std::map<HistoryID, RowWordStarts> WordStartsMap;

#endif  // COMPONENTS_OMNIBOX_IN_MEMORY_URL_INDEX_TYPES_H_


text:
package query;

import java.util.List;

import query.domain.Wrapper;
import query.model.OrderParameter;
import query.model.Sort;

public class Order<T> {

	private final Wrapper wrapper;
	private OrderParameter orderParameter;
	private final String[] fields;

	public Order(Wrapper wrapper, String...fields) {
		orderParameter = new OrderParameter(Sort.ASCENDING, fields);
		wrapper.addOrderParameter(orderParameter);
		this.fields = fields;
		this.wrapper = wrapper;
	}

	public Order(Wrapper wrapper, String[] fields, Sort sort) {
		if (fields != null) {
			orderParameter = new OrderParameter(sort, fields);
			wrapper.addOrderParameter(orderParameter);
		}
		this.fields = fields;
		this.wrapper = wrapper;
	}

	public Order<T> descending() {
		int index = wrapper.getOrderParameters().indexOf(orderParameter);
		wrapper.getOrderParameters().set(index, new OrderParameter(Sort.DESCENDING, fields));
		return this;
	}

	public Order<T> and(String... fields){
		return new Order<T>(wrapper, fields);
	}

	public Group<T> groupBy(String... fields){
		return new Group<>(wrapper, fields);
	}

	public Offset<T> offset(int offset){
		return new Offset<>(wrapper, offset);
	}

	public Limit<T> limit(int limit){
		return new Limit<>(wrapper, limit);
	}

	public List<T> find() {
		return new Executer<T>(wrapper).find();
	}

	public Object findSingle() {
		return new Executer<T>(wrapper).findSingle();
	}

	public boolean exists() {
		return new Executer<>(wrapper).exists();
	}

	public String getQueryString() {
		return new Executer<>(wrapper).getQueryString();
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using log4net;
using MyStik.TimeTable.Data;
using MyStik.TimeTable.DataServices.IO.Cie.Data;

namespace MyStik.TimeTable.DataServices.IO.Cie
{
    public class SemesterImport
    {
        private ImportContext _import;

        private Guid _semId;

        private Stopwatch sw = new Stopwatch();

        private readonly ILog _Logger = LogManager.GetLogger("Import");

        private Semester _semester;

        private bool _isValid = true;

        private StringBuilder _report = new StringBuilder();

        ///
        ///
        ///
        /// <param name="import"></param>
        /// <param name="semId">Für dieses Semester werden die Semestergruppen gesucht</param>
        public SemesterImport(ImportContext import, Guid semId)
        {
            _import = import;
            _semId = semId;

            _report.AppendLine("");
            _report.AppendLine("");
        }

        ///
        /// Suche nach unbekannten Fakultäten
        ///
        public void CheckFaculty()
        {
            var db = new TimeTableDbContext();

            _semester = db.Semesters.SingleOrDefault(s => s.Id == _semId);
            if (_semester == null)
            {
                _import.AddErrorMessage("Import", $"Semester {_semId} existiert nicht", true);
                _isValid = false;
            }

            // Jede Fakultät suchen
            foreach (var course in _import.Model.Courses)
            {
                var org = db.Organisers.SingleOrDefault(x => x.ShortName.Equals(course.department));

                if (org != null)
                {
                    // Studiengang suchen => mache ich erst beim Import

                    _import.ValidCourses.Add(course);
                }
                else
                {
                    if (string.IsNullOrEmpty(course.department))
                    {
                        _import.AddErrorMessage("Import", $"Für Kurs {course.name} wurde kein Veranstalter angegeben", true);
                    }
                    else
                    {
                        _import.AddErrorMessage("Import", $"Für Kurs {course.name} gibt es den Veranstalter {course.department} nicht", true);
                    }
                    _isValid = false;
                }
            }
        }

        public void CheckRooms()
        {
            if (!_isValid)
                return;
        }

        public void CheckLecturers()
        {
            if (!_isValid)
                return;
        }

        public string GetReport()
        {
            _report.AppendLine("");
            _report.AppendLine("");

            return _report.ToString();
        }

        public string ImportCourse(CieCourse scheduleCourse)
        {
            string msg;

            _Logger.DebugFormat("Importiere Fach: {0}", scheduleCourse.name);
            _report.AppendFormat("
Erzeuge LV \"{0}\" - [{1}]
", scheduleCourse.name,
                scheduleCourse.id);
            _report.AppendLine();

            var db = new TimeTableDbContext();

            var organiser = db.Organisers.SingleOrDefault(s => s.ShortName.Equals(scheduleCourse.department));
            var sem = db.Semesters.SingleOrDefault(s => s.Id == _semId);

            var cieSemGroup = db.SemesterGroups.SingleOrDefault(x =>
                x.Semester.Id == sem.Id &&
                x.CapacityGroup.CurriculumGroup.Curriculum.ShortName.Equals("CIE") &&
                x.CapacityGroup.CurriculumGroup.Curriculum.ShortName.Equals("CIE") &&
                x.CapacityGroup.CurriculumGroup.Name.Equals("CIE"));

            long msStart = sw.ElapsedMilliseconds;
            // suche den Kurs im bisherigen Angebot auf Grundlage des Namens
            var course = GetCourse(db, sem, organiser, scheduleCourse);

            if (course == null)
            {
                course = new Course
                {
                    ExternalSource = "CIE",
                    ExternalId = scheduleCourse.id,
                    Organiser = organiser,
                    ShortName = "",
                    Name = scheduleCourse.name,
                    Description = scheduleCourse.description,
                    Occurrence = CreateDefaultOccurrence(scheduleCourse.availableSlots),
                    IsInternal = true,
                };
                // Kurs sofort speichern, damit die ID gesichert ist
                db.Activities.Add(course);
                db.SaveChanges();
            }
            long msEnd = sw.ElapsedMilliseconds;
            _Logger.DebugFormat("Dauer: {0}ms", msEnd - msStart);
            msStart = msEnd;

            _report.AppendLine("
Bezeichnungen
");
            _report.AppendLine("
");
            _report.AppendFormat("
Name	{0}
", course.Name);
            _report.AppendFormat("
Kurzname	{0}
", course.ShortName);
            _report.AppendFormat("
Beschreibung	{0}
", course.Description);
            _report.AppendLine("
");

            // jetzt die Gruppen
            // Studiengänge ermitteln
            // Den Kurs gibt es nur einmal
            // Zuordnungen pro Studiengang
            // Modul => d.h. duplizieren von ECTS, SWS
            var curricula= GetCurricula(db, sem, scheduleCourse.department, scheduleCourse.level);

            // Semestergruppe => auch hier eine "intelligente" Zuordnung
            // nur machen, wenn Kurs keine Gruppen hat
            if (!course.SemesterGroups.Any())
            {
                foreach (var curriculum in curricula)
                {
                    // Annahme: ein CIE sind immer WPM
                    var wpmCurrciculumGroup = curriculum.CurriculumGroups.SingleOrDefault(x => x.Name.Equals("WPM"));

                    var wpmCapacityGroup = wpmCurrciculumGroup.CapacityGroups.FirstOrDefault();

                    var wpmSemesterGroup = db.SemesterGroups.FirstOrDefault(x =>
                        x.CapacityGroup.Id == wpmCapacityGroup.Id && x.Semester.Id == sem.Id);

                    course.SemesterGroups.Add(wpmSemesterGroup);

                    // zu jeder Semestergruppe gibt es dann noch eine
                    // Gruppe für Platzverlosung
                    var occGroup =
                        course.Occurrence.Groups.SingleOrDefault(
                            gg => gg.SemesterGroups.Any(s => s.Id == wpmSemesterGroup.Id));

                    if (occGroup == null)
                    {
                        occGroup = new OccurrenceGroup
                        {
                            Capacity = 0,
                            FitToCurriculumOnly = true,
                            Occurrence = course.Occurrence
                        };
                        occGroup.SemesterGroups.Add(wpmSemesterGroup);
                        wpmSemesterGroup.OccurrenceGroups.Add(occGroup);
                        course.Occurrence.Groups.Add(occGroup);
                        db.OccurrenceGroups.Add(occGroup);
                    }

                }
            }

            // Die Semestergruppe FK 13 / CIE / CIE muss immer dran
            if (!course.SemesterGroups.Contains(cieSemGroup))
            {
                course.SemesterGroups.Add(cieSemGroup);
            }
            db.SaveChanges();

            if (!course.SemesterGroups.Any())
            {
                _Logger.ErrorFormat("Kurs {0} ohne Gruppe", scheduleCourse.id);
            }

            // jetzt die Module
            // wieder pro Studiengang
            /*
            foreach (var curriculum in curricula)
            {
                //var module = GetModule(db, curriculum, scheduleCourse);

                var nexus = new CourseModuleNexus();
                //nexus.Requirement = module;
                nexus.Course = course;
                // nexus.ModuleCourse = // fehlt noch

                course.Nexus.Add(nexus);

                db.CourseNexus.Add(nexus);
            }
            */
            db.SaveChanges();

            // Das Ampelsystem
            if (scheduleCourse.courseStatus.Equals("RED"))
            {
                course.Occurrence.IsCoterie = true;
                course.Occurrence.HasHomeBias = true; // Bedeutungslos
            }
            else if (scheduleCourse.courseStatus.Equals("YELLOW"))
            {
                course.Occurrence.IsCoterie = false;
                course.Occurrence.HasHomeBias = true;

            }
            else //(scheduleCourse.courseStatus.Equals("GREEN"))
            {
                course.Occurrence.IsCoterie = false;
                course.Occurrence.HasHomeBias = false;
            }

            db.SaveChanges();

            // zum Schluss die Termine
            // Dummy Termin mit Dozent
            _report.AppendLine("
Neue Termine
");
            _report.AppendLine("
");

            // Der Dummy Termin ist Vorlesungsbeginn 08:00-10:00
            var occDate = sem.StartCourses.Date;

            var occ = new ActivityDate
            {
                Begin = occDate.AddHours(8),
                End = occDate.AddHours(10),
                Activity = course,
                Occurrence = CreateDefaultOccurrence(),
            };
            _report.AppendLine("
");
                _report.AppendFormat("{0}	{1}	{2}	", occ.Begin.ToShortDateString(), occ.Begin.ToShortTimeString(), occ.End.ToShortTimeString());

                // Kein Raum
                _report.AppendFormat("");
                _report.AppendFormat("	");

                // Dozent => der angegebene
                var lec = scheduleCourse.lecturer.Split(',');
                _report.AppendFormat("");

            foreach (var s in lec)
            {
                var scheduleDateLecturer = s.Trim();
                _report.AppendFormat("
{0} ({1})", scheduleDateLecturer, scheduleDateLecturer);

                var lecturer = organiser.Members.SingleOrDefault(l => l.ShortName.Equals(scheduleDateLecturer) || l.Name.Equals(scheduleDateLecturer));
                if (lecturer == null)
                {
                    lecturer = new OrganiserMember
                    {
                        ShortName = scheduleDateLecturer,
                        Name = scheduleDateLecturer,
                        Role = String.Empty,
                        Description = String.Empty
                    };
                    organiser.Members.Add(lecturer);
                    db.Members.Add(lecturer);
                    db.SaveChanges();
                    _report.AppendFormat(" !!!NEUER DOZENT!!!");
                }

                occ.Hosts.Add(lecturer);
                _report.AppendFormat("
");

            }
            _report.AppendFormat("	");

                db.ActivityDates.Add(occ);

                _report.AppendLine();
            _report.AppendLine("
");

            _report.AppendLine("
");
            db.SaveChanges();

            msEnd = sw.ElapsedMilliseconds;
            _Logger.DebugFormat("Dauer {0}ms", msEnd - msStart);

            msg = $"Kurs {course.ShortName} mit Terminen importiert";

            return msg;
        }

        public string UpdateCourse(Course c, CieCourse scheduleCourse)
        {
            string msg;

            _Logger.DebugFormat("Aktualisiere Fach: {0}", scheduleCourse.name);

            _report.AppendFormat("
Aktualisiere LV \"{0} ({1})\" - [{2}]
", scheduleCourse.name, scheduleCourse.name,
                scheduleCourse.id);
            _report.AppendLine();

            /*
            var db = new TimeTableDbContext();

            var organiser = db.Organisers.SingleOrDefault(s => s.Id == _orgId);
            var sem = db.Semesters.SingleOrDefault(s => s.Id == _semId);
            long msStart = sw.ElapsedMilliseconds;

            var course = db.Activities.OfType<Course>().SingleOrDefault(x => x.Id == c.Id);

            // Ober sticht Unter => zuerst alle termine raus!
            _report.AppendLine("
Gelöschte Termine
");
            _report.AppendLine("
");
            foreach (var date in course.Dates.ToList())
            {
                _report.AppendLine("
");
                _report.AppendFormat("{0}	{1}	{2}	", date.Begin.ToShortDateString(), date.Begin.ToShortTimeString(), date.End.ToShortTimeString());

                _report.AppendLine("");
                foreach (var room in date.Rooms)
                {
                    _report.AppendFormat("
{0}
", room.Number);
                }
                _report.AppendLine("	");

                _report.AppendLine("");
                foreach (var host in date.Hosts)
                {
                    _report.AppendFormat("
{0} ({1})
", host.Name, host.ShortName);
                }
                _report.AppendLine("	");

                _report.AppendFormat("{0}	", date.Title);
                _report.AppendFormat("{0}	", date.Description);
                _report.AppendFormat("{0}	", date.Occurrence.Information);

                _report.AppendLine();
                _report.AppendLine("
");

                db.Occurrences.Remove(date.Occurrence);

                foreach (var change in date.Changes.ToList())
                {
                    foreach (var notificationState in change.NotificationStates.ToList())
                    {
                        db.NotificationStates.Remove(notificationState);
                        change.NotificationStates.Remove(notificationState);
                    }
                    date.Changes.Remove(change);
                    db.DateChanges.Remove(change);
                }

                course.Dates.Remove(date);

                db.ActivityDates.Remove(date);
            }
            db.SaveChanges();

            _report.AppendLine("
");

            // Die Bezeichnung
            _report.AppendLine("
Bezeichnungen
");
            _report.AppendLine("
Alt
");
            _report.AppendLine("
");
            _report.AppendFormat("
Name	{0}
", course.Name);
            _report.AppendFormat("
Kurzname	{0}
", course.ShortName);
            _report.AppendFormat("
Beschreibung	{0}
", course.Description);
            _report.AppendLine("
");

            course.Name = scheduleCourse.Name;
            course.ShortName = scheduleCourse.ShortName;
            course.Description = scheduleCourse.Description;

            _report.AppendLine("
Neu
");
            _report.AppendLine("
");
            _report.AppendFormat("
Name	{0}
", course.Name);
            _report.AppendFormat("
Kurzname	{0}
", course.ShortName);
            _report.AppendFormat("
Beschreibung	{0}
", course.Description);
            _report.AppendLine("
");

            // Platzkontingent
            course.Occurrence.Capacity = scheduleCourse.SeatRestriction;

            // Termine einfügen
            // zum Schluss die Termine
            _report.AppendLine("
Neue Termine
");
            _report.AppendLine("
");

            foreach (var scheduleDate in scheduleCourse.Dates)
            {
                // Der Tag
                var occDate = scheduleDate.Begin.Date;

                bool isVorlesung = true;
                foreach (var sd in _semester.Dates)
                {
                    // Wenn der Termin in eine vorlesungsfreie Zeit fällt, dann nicht importieren
                    if (sd.From.Date <= occDate.Date &&
                        occDate.Date <= sd.To.Date &&
                        sd.HasCourses == false)
                    {
                        isVorlesung = false;
                    }
                }

                // Es muss Vorlesung sein und das Datum darf nicht existieren
                if (isVorlesung)
                {
                    var occ = new ActivityDate
                    {
                        Begin = scheduleDate.Begin,
                        End = scheduleDate.End,
                        Activity = course,
                        Occurrence = CreateDefaultOccurrence(),
                    };

                    _report.AppendLine("
");
                    _report.AppendFormat("{0}	{1}	{2}	", occ.Begin.ToShortDateString(), occ.Begin.ToShortTimeString(), occ.End.ToShortTimeString());

                    _report.AppendFormat("");
                    foreach (var scheduleDateRoom in scheduleDate.Rooms)
                    {
                        _report.AppendFormat("
{0}", scheduleDateRoom.RoomNumber);
                        if (!string.IsNullOrEmpty(scheduleDateRoom.RoomNumber))
                        {
                            var room = db.Rooms.SingleOrDefault(r => r.Number.Equals(scheduleDateRoom.RoomNumber));
                            if (room == null)
                            {
                                room = new Room
                                {
                                    Number = scheduleDateRoom.RoomNumber,
                                    Capacity = 0,
                                    Description = string.Empty,
                                    Owner = string.Empty,
                                };
                                db.Rooms.Add(room);
                                db.SaveChanges();

                                _numRooms++;

                                _report.AppendFormat(" !!!NEUER RAUM!!!");
                            }

                            var assignment = db.RoomAssignments.SingleOrDefault(x =>
                                x.Room.Id == room.Id &&
                                x.Organiser.Id == organiser.Id);
                            if (assignment == null)
                            {
                                assignment = new RoomAssignment
                                {
                                    Organiser = organiser,
                                    InternalNeedConfirmation = false, // offen für interne
                                    ExternalNeedConfirmation = true // geschlossen für externe
                                };

                                room.Assignments.Add(assignment);
                                db.RoomAssignments.Add(assignment);
                                db.SaveChanges();
                            }

                            occ.Rooms.Add(room);

                            _report.AppendFormat("
");
                        }
                    }
                    _report.AppendFormat("	");

                    _report.AppendFormat("");
                    foreach (var scheduleDateLecturer in scheduleDate.Lecturers)
                    {
                        _report.AppendFormat("
{0} ({1})", scheduleDateLecturer.Name, scheduleDateLecturer.ShortName);
                        var lecturer = organiser.Members.SingleOrDefault(l => l.ShortName.Equals(scheduleDateLecturer.ShortName));
                        if (lecturer == null)
                        {
                            lecturer = new OrganiserMember
                            {
                                ShortName = scheduleDateLecturer.ShortName,
                                Name = scheduleDateLecturer.Name,
                                Role = String.Empty,
                                Description = String.Empty
                            };
                            organiser.Members.Add(lecturer);
                            db.Members.Add(lecturer);
                            db.SaveChanges();
                            _numLecturers++;

                            _report.AppendFormat(" !!!NEUER DOZENT!!!");
                        }

                        occ.Hosts.Add(lecturer);

                        _report.AppendFormat("
");

                    }
                    _report.AppendFormat("	");

                    db.ActivityDates.Add(occ);

                    _report.AppendLine();
                    _report.AppendLine("
");

                }
            }
            _report.AppendLine("
");

            db.SaveChanges();

            long msEnd = sw.ElapsedMilliseconds;
            _Logger.DebugFormat("Dauer {0}ms", msEnd - msStart);
            */

            msg = $"Kurs {scheduleCourse.name} mit Terminen aktualisiert";

            return msg;
        }

        private static Occurrence CreateDefaultOccurrence(int c=-1)
        {
            return new Occurrence
            {
                Capacity = c,
                IsAvailable = true,
                IsCanceled = false,
                IsMoved = false,
                FromIsRestricted = false,
                UntilIsRestricted = false,
                UseGroups = false,
            };
        }

        private List<TimeTable.Data.Curriculum> GetCurricula(TimeTableDbContext db, Semester semester, string orgName, string level)
        {
            var list = new List<TimeTable.Data.Curriculum>();

            if (orgName.Equals("FK 01") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAAR"));
            }
            if (orgName.Equals("FK 01") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAAR"));
            }

            if (orgName.Equals("FK 02") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BIB"));
            }
            if (orgName.Equals("FK 02") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BIM"));
            }

            if (orgName.Equals("FK 03") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAMB"));
            }
            if (orgName.Equals("FK 03") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAMB"));
            }

            if (orgName.Equals("FK 04") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAET"));
            }
            if (orgName.Equals("FK 04") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAET"));
            }

            if (orgName.Equals("FK 05") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BADMT"));
            }
            if (orgName.Equals("FK 05") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MADMT"));
            }

            if (orgName.Equals("FK 06") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAMT"));
            }
            if (orgName.Equals("FK 06") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAMT"));
            }

            if (orgName.Equals("FK 07") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAINF"));
            }
            if (orgName.Equals("FK 07") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAINF"));
            }

            if (orgName.Equals("FK 08") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BAGEO"));
            }
            if (orgName.Equals("FK 08") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MAGEO"));
            }

            if (orgName.Equals("FK 09") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "WI"));
            }
            if (orgName.Equals("FK 09") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "WIM"));
            }

            if (orgName.Equals("FK 10") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BABW"));
            }
            if (orgName.Equals("FK 10") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MD"));
            }

            if (orgName.Equals("FK 11") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BASA Präsenz"));
            }
            if (orgName.Equals("FK 11") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "AFSA"));
            }

            if (orgName.Equals("FK 12") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "DES"));
            }
            if (orgName.Equals("FK 12") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "DES-M"));
            }

            if (orgName.Equals("FK 13") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "IPM"));
            }
            if (orgName.Equals("FK 13") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "IKK"));
            }

            if (orgName.Equals("FK 14") && (level.Equals("BACHELOR") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "BATM"));
            }
            if (orgName.Equals("FK 14") && (level.Equals("MASTER") || level.Equals("ANY")))
            {
                list.Add(GetCurriculum(db, semester,orgName, "MATM"));
            }

            return list;
        }

        private TimeTable.Data.Curriculum GetCurriculum(TimeTableDbContext db, Semester semester, string orgName, string currName)
        {
            var org = db.Organisers.SingleOrDefault(x => x.ShortName.Equals(orgName));
            var curr = org.Curricula.SingleOrDefault(x => x.ShortName.Equals(currName));

            if (curr == null)
            {
                curr = new TimeTable.Data.Curriculum
                {
                    ShortName = currName,
                    Name = currName,
                    Organiser = org
                };
                db.Curricula.Add(curr);
                db.SaveChanges();
            }

            // Gleich alles notwendige anlegen
            var wpmCurrciculumGroup = curr.CurriculumGroups.SingleOrDefault(x => x.Name.Equals("WPM"));
            if (wpmCurrciculumGroup == null)
            {
                wpmCurrciculumGroup = new CurriculumGroup
                {
                    Curriculum = curr,
                    Name = "WPM",
                    IsSubscribable = true,
                };
                db.CurriculumGroups.Add(wpmCurrciculumGroup);
                db.SaveChanges();

            }

            var wpmCapacityGroup = wpmCurrciculumGroup.CapacityGroups.FirstOrDefault();
            if (wpmCapacityGroup == null)
            {
                wpmCapacityGroup = new CapacityGroup
                {
                    CurriculumGroup = wpmCurrciculumGroup,
                    Name = string.Empty,
                    InSS = true,
                    InWS = true
                };
                db.CapacityGroups.Add(wpmCapacityGroup);
                db.SaveChanges();
            }

            var wpmSemesterGroup = db.SemesterGroups.FirstOrDefault(x =>
                x.CapacityGroup.Id == wpmCapacityGroup.Id && x.Semester.Id == semester.Id);

            if (wpmSemesterGroup == null)
            {
                wpmSemesterGroup = new SemesterGroup
                {
                    Semester = semester,
                    CapacityGroup = wpmCapacityGroup,
                    IsAvailable = false // zu Beginn nicht freigegeben
                };
                db.SemesterGroups.Add(wpmSemesterGroup);

                db.SaveChanges();

            }

            return curr;
        }

        private Course GetCourse(TimeTableDbContext db, Semester sem, ActivityOrganiser org, CieCourse course)
        {
            // alle Kurse im Semester des Organisers nach dem Namen durchsuchen

            return null;
        }

        /*
        private CurriculumRequirement GetModule(TimeTableDbContext db, TimeTable.Data.Curriculum curriculum, CieCourse scheduleCourse)
        {
            var pck = curriculum.Packages.FirstOrDefault();
            if (curriculum.ShortName.Equals("WI") && pck != null)
            {
                pck = curriculum.Packages.SingleOrDefault(x => x.Name.Equals("Wahlpflicht"));
            }

            if (pck == null)
            {
                pck = new CurriculumPackage();
                pck.Name = "Studium";
                curriculum.Packages.Add(pck);
                db.CurriculumPackages.Add(pck);
            }

            var option = pck.Options.FirstOrDefault();

            if (option == null)
            {
                option = new PackageOption();
                option.Name = "Gesamt";
                option.Package = pck;
                db.PackageOptions.Add(option);
            }

            var module =
                option.Requirements.FirstOrDefault(x => x.Name.ToLower().Equals(scheduleCourse.name.ToLower()));

            if (module == null)
            {
                module = new CurriculumRequirement();
                module.Name = scheduleCourse.name;
                module.ECTS = scheduleCourse.ects;
                module.USCredits = scheduleCourse.usCredits;
                module.SWS = scheduleCourse.semesterWeekHours;

                option.Requirements.Add(module);
            }

            db.SaveChanges();

            return module;
        }
        */
    }
}


text:
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root."
   exit 1
fi

if [ ! -f /usr/bin/python3 ]; then
	echo "Could not find /usr/bin/python3, make sure Python 3.x is installed."
	exit 1
fi

echo "This script will copy Healthstone files, set permissions, add crontab and Apache configuration options. Press CTRL-C to cancel."
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Get default values
read -p "Software folder [/usr/share]: " installdir
installdir=${installdir:-/usr/share}
read -p "Apache document root [/var/www/html]: " wwwroot
wwwroot=${wwwroot:-/var/www/html}
read -p "Apache user [apache]: " wwwuser
wwwuser=${wwwuser:-apache}
read -p "Apache configuration file [/etc/httpd/conf/httpd.conf]: " conf
conf=${conf:-/etc/httpd/conf/httpd.conf}

# Copy files
echo "* Copying files..."
mkdir -p $installdir
cp -r $DIR $installdir

# Fix permissions
echo "* Setting permissions..."
chown -R $wwwuser.$wwwuser $installdir/healthstone/db
chmod g+s $installdir/healthstone/db
chmod 755 $installdir/healthstone/www/dashboard.py

# Add crontab for probes
echo "* Adding automation schedule for probes..."
crontab -l > /tmp/mycron
if ! grep -q dashboard /tmp/mycron; then
	echo "*/1 * * * * $installdir/healthstone/www/dashboard.py > /dev/null" >> /tmp/mycron
	crontab /tmp/mycron
fi
rm -f /tmp/mycron

# Add Apache config
echo "* Adding Apache config..."
ln -s $installdir/healthstone/www $wwwroot/healthstone
sed -i.bak '/AllowOverride None/d' $conf
echo "<Directory />" >> $conf
echo " AllowOverride All" >> $conf
echo " Options FollowSymLinks" >> $conf
echo " Require all granted" >> $conf
echo "</Directory>" >> $conf
a2enmod cgi > /dev/null 2>&1
if ! systemctl restart httpd 2> /dev/null ; then
	systemctl restart apache2
fi

# Done
echo "Done. If no error occurred, Healthstone should be available from http://localhost/healthstone"
echo "Please consult the README for troubleshooting."


text:
using System.Linq;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Localisation;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osuTK;

namespace osu.Game.Graphics.UserInterface
{
    public class OsuDropdown<T> : Dropdown<T>, IHasAccentColour
    {
        private const float corner_radius = 4;

        private Color4 accentColour;

        public Color4 AccentColour
        {
            get => accentColour;
            set
            {
                accentColour = value;
                updateAccentColour();
            }
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            if (accentColour == default)
                accentColour = colours.PinkDarker;
            updateAccentColour();
        }

        private void updateAccentColour()
        {
            if (Header is IHasAccentColour header) header.AccentColour = accentColour;

            if (Menu is IHasAccentColour menu) menu.AccentColour = accentColour;
        }

        protected override DropdownHeader CreateHeader() => new OsuDropdownHeader();

        protected override DropdownMenu CreateMenu() => new OsuDropdownMenu();

        #region OsuDropdownMenu

        protected class OsuDropdownMenu : DropdownMenu, IHasAccentColour
        {
            public override bool HandleNonPositionalInput => State == MenuState.Open;

            private Sample sampleOpen;
            private Sample sampleClose;

            // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
            public OsuDropdownMenu()
            {
                CornerRadius = corner_radius;
                BackgroundColour = Color4.Black.Opacity(0.5f);

                MaskingContainer.CornerRadius = corner_radius;

                // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
                ItemsContainer.Padding = new MarginPadding(5);
            }

            [BackgroundDependencyLoader]
            private void load(AudioManager audio)
            {
                sampleOpen = audio.Samples.Get(@"UI/dropdown-open");
                sampleClose = audio.Samples.Get(@"UI/dropdown-close");
            }

            // todo: this shouldn't be required after https://github.com/ppy/osu-framework/issues/4519 is fixed.
            private bool wasOpened;

            // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
            protected override void AnimateOpen()
            {
                wasOpened = true;
                this.FadeIn(300, Easing.OutQuint);
                sampleOpen?.Play();
            }

            protected override void AnimateClose()
            {
                this.FadeOut(300, Easing.OutQuint);
                if (wasOpened)
                    sampleClose?.Play();
            }

            // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
            protected override void UpdateSize(Vector2 newSize)
            {
                if (Direction == Direction.Vertical)
                {
                    Width = newSize.X;
                    this.ResizeHeightTo(newSize.Y, 300, Easing.OutQuint);
                }
                else
                {
                    Height = newSize.Y;
                    this.ResizeWidthTo(newSize.X, 300, Easing.OutQuint);
                }
            }

            private Color4 accentColour;

            public Color4 AccentColour
            {
                get => accentColour;
                set
                {
                    accentColour = value;
                    foreach (var c in Children.OfType<IHasAccentColour>())
                        c.AccentColour = value;
                }
            }

            protected override Menu CreateSubMenu() => new OsuMenu(Direction.Vertical);

            protected override DrawableDropdownMenuItem CreateDrawableDropdownMenuItem(MenuItem item) => new DrawableOsuDropdownMenuItem(item) { AccentColour = accentColour };

            protected override ScrollContainer<Drawable> CreateScrollContainer(Direction direction) => new OsuScrollContainer(direction);

            #region DrawableOsuDropdownMenuItem

            public class DrawableOsuDropdownMenuItem : DrawableDropdownMenuItem, IHasAccentColour
            {
                // IsHovered is used
                public override bool HandlePositionalInput => true;

                private Color4? accentColour;

                public Color4 AccentColour
                {
                    get => accentColour ?? nonAccentSelectedColour;
                    set
                    {
                        accentColour = value;
                        updateColours();
                    }
                }

                private void updateColours()
                {
                    BackgroundColourHover = accentColour ?? nonAccentHoverColour;
                    BackgroundColourSelected = accentColour ?? nonAccentSelectedColour;
                    UpdateBackgroundColour();
                    UpdateForegroundColour();
                }

                private Color4 nonAccentHoverColour;
                private Color4 nonAccentSelectedColour;

                public DrawableOsuDropdownMenuItem(MenuItem item)
                    : base(item)
                {
                    Foreground.Padding = new MarginPadding(2);

                    Masking = true;
                    CornerRadius = corner_radius;
                }

                [BackgroundDependencyLoader]
                private void load(OsuColour colours)
                {
                    BackgroundColour = Color4.Transparent;

                    nonAccentHoverColour = colours.PinkDarker;
                    nonAccentSelectedColour = Color4.Black.Opacity(0.5f);
                    updateColours();

                    AddInternal(new HoverSounds());
                }

                protected override void UpdateForegroundColour()
                {
                    base.UpdateForegroundColour();

                    if (Foreground.Children.FirstOrDefault() is Content content) content.Chevron.Alpha = IsHovered ? 1 : 0;
                }

                protected override Drawable CreateContent() => new Content();

                protected new class Content : FillFlowContainer, IHasText
                {
                    public LocalisableString Text
                    {
                        get => Label.Text;
                        set => Label.Text = value;
                    }

                    public readonly OsuSpriteText Label;
                    public readonly SpriteIcon Chevron;

                    public Content()
                    {
                        RelativeSizeAxes = Axes.X;
                        AutoSizeAxes = Axes.Y;
                        Direction = FillDirection.Horizontal;

                        Children = new Drawable[]
                        {
                            Chevron = new SpriteIcon
                            {
                                AlwaysPresent = true,
                                Icon = FontAwesome.Solid.ChevronRight,
                                Colour = Color4.Black,
                                Alpha = 0.5f,
                                Size = new Vector2(8),
                                Margin = new MarginPadding { Left = 3, Right = 3 },
                                Origin = Anchor.CentreLeft,
                                Anchor = Anchor.CentreLeft,
                            },
                            Label = new OsuSpriteText
                            {
                                Origin = Anchor.CentreLeft,
                                Anchor = Anchor.CentreLeft,
                            },
                        };
                    }
                }
            }

            #endregion
        }

        #endregion

        public class OsuDropdownHeader : DropdownHeader, IHasAccentColour
        {
            protected readonly SpriteText Text;

            protected override LocalisableString Label
            {
                get => Text.Text;
                set => Text.Text = value;
            }

            protected readonly SpriteIcon Icon;

            private Color4 accentColour;

            public virtual Color4 AccentColour
            {
                get => accentColour;
                set
                {
                    accentColour = value;
                    BackgroundColourHover = accentColour;
                }
            }

            public OsuDropdownHeader()
            {
                Foreground.Padding = new MarginPadding(4);

                AutoSizeAxes = Axes.None;
                Margin = new MarginPadding { Bottom = 4 };
                CornerRadius = corner_radius;
                Height = 40;

                Foreground.Children = new Drawable[]
                {
                    Text = new OsuSpriteText
                    {
                        Anchor = Anchor.CentreLeft,
                        Origin = Anchor.CentreLeft,
                    },
                    Icon = new SpriteIcon
                    {
                        Icon = FontAwesome.Solid.ChevronDown,
                        Anchor = Anchor.CentreRight,
                        Origin = Anchor.CentreRight,
                        Margin = new MarginPadding { Right = 5 },
                        Size = new Vector2(12),
                    },
                };

                AddInternal(new HoverClickSounds());
            }

            [BackgroundDependencyLoader]
            private void load(OsuColour colours)
            {
                BackgroundColour = Color4.Black.Opacity(0.5f);
                BackgroundColourHover = colours.PinkDarker;
            }
        }
    }
}


text:
package v1

import (
	"testing"
	"time"

	"github.com/gophercloud/gophercloud/openstack/blockstorage/v1/volumetypes"
	"github.com/gophercloud/gophercloud/pagination"
	th "github.com/gophercloud/gophercloud/testhelper"
)

func TestVolumeTypes(t *testing.T) {
	client, err := newClient(t)
	th.AssertNoErr(t, err)

	vt, err := volumetypes.Create(client, &volumetypes.CreateOpts{
		ExtraSpecs: map[string]interface{}{
			"capabilities": "gpu",
			"priority":     3,
		},
		Name: "gophercloud-test-volumeType",
	}).Extract()
	th.AssertNoErr(t, err)
	defer func() {
		time.Sleep(10000 * time.Millisecond)
		err = volumetypes.Delete(client, vt.ID).ExtractErr()
		if err != nil {
			t.Error(err)
			return
		}
	}()
	t.Logf("Created volume type: %+v\n", vt)

	vt, err = volumetypes.Get(client, vt.ID).Extract()
	th.AssertNoErr(t, err)
	t.Logf("Got volume type: %+v\n", vt)

	err = volumetypes.List(client).EachPage(func(page pagination.Page) (bool, error) {
		volTypes, err := volumetypes.ExtractVolumeTypes(page)
		if len(volTypes) != 1 {
			t.Errorf("Expected 1 volume type, got %d", len(volTypes))
		}
		t.Logf("Listing volume types: %+v\n", volTypes)
		return true, err
	})
	th.AssertNoErr(t, err)
}


text:
vagrant-wp
==========

WP test with Vagrant


text:
namespace HiddenSound.API.Areas.Application.Models.Requests
{
    public class LoginRequest
    {
        public string Email { get; set; }

        public string Password { get; set; }
    }
}


text:
id: expo_usage
title: Expo Usage
sidebar_label: Expo Usage
---

RNCamera of react-native-camera is heavily based on Expo camera module. Thanks @aalices and Expo for the great work.

So you don't need to use **react-native-camera** if you have the following config:

- If you are using [Expo](https://expo.io)
- If you are using [create-react-native-app](https://github.com/react-community/create-react-native-app)
- If you eject a [create-react-native-app](https://github.com/react-community/create-react-native-app) app and are using [ExpoKit](https://docs.expo.io/versions/latest/expokit/expokit)

## How to migrate from Expo to react-native-camera

If you decide to eject without using ExpoKit, you can follow react-native-camera installation instructions and just change the usage of your Camera component to RNCamera:

```diff
- import { Camera } from 'expo';
+ import { RNCamera } from 'react-native-camera';

- <Camera
+ <RNCamera
```

## How to migrate from react-native-camera to Expo Camera Module

```diff
- import { RNCamera } from 'react-native-camera';
+ import { Camera } from 'expo';

- <RNCamera
+ <Camera
```


text:
/**
 * @file server.h
 * Header File for Server Class
 * @date April 2014
 * @author Sai Koppula, Vikram Jayashankar
 */

#ifndef _SERVER_H
#define _SERVER_H

#include <sys/socket.h>
#include <unordered_map>
#include <map>
#include <string>
#include <algorithm>
#include <thread>
#include "mmap_allocator.h"
#include "elements.h"
#include "kvstore.pb.h"

class Server {
 public:
  bool Run(int port);

 private:
  void HandleMessage(const kvstore::Request& request, kvstore::Response* response);

  void ProcessClient(int sock);

  // Parse Message
  void parse(char* message, int fdClient);

  // Handle Set
  char* set(const char* key, String* value);

  // Handle Get
  char* get(const char* key);

  // Handle Del
  char* del(const char* key);

  // Send to TCP Socket
  void sendResponse(char* response, int fdClient);

  // TCP Socket
  int sock_;
  mm::unordered_map<std::string, std::unique_ptr<Element>> map_;
  std::vector<std::thread> threads_;
};

#endif


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('service:dialog', 'Unit | Service | dialog', {
  // Specify the other units that are required for this test.
  // needs: ['service:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let service = this.subject();
  assert.ok(service);
});


text:
 #include "ModuleTextures.h"
#include "ModuleAssimp.h"

#include "Application.h"

#include "glew-2.1.0\include\GL\glew.h"

#include "HelperFoos.h"

#include "Devil\include\il.h"
#include "Devil\include\ilu.h"
#include "Devil\include\ilut.h"

#pragma comment (lib, "Devil/libx86/DevIL.lib")
#pragma comment (lib, "Devil/libx86/ILU.lib")
#pragma comment (lib, "Devil/libx86/ILUT.lib")

ModuleTextures::ModuleTextures(bool start_enabled) : Module(start_enabled)
{
	name = "Texture";
}

ModuleTextures::~ModuleTextures()
{
	ilShutDown();
}

bool ModuleTextures::Init()
{
	// DeviL Initialization
	ilutRenderer(ILUT_OPENGL);
	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	clamping_str = "Clamp to Edge\0Repeat\0Mirrored Repeat\0";
	interpolate_str = "Nearest\0Linear\0";

	return true;
}

bool ModuleTextures::Start() {
	LoadConfig();
	return true;
}

update_status ModuleTextures::Update(float dt)
{

	return UPDATE_CONTINUE;
}

bool ModuleTextures::CleanUp()
{

	return true;
}

void ModuleTextures::LoadConfig() {
	clamp_type = App->parson->config->GetNumber("configuration.textures.clamping");
	interpolation_type = App->parson->config->GetNumber("configuration.textures.interpolation");
}

Texture* ModuleTextures::LoadRawTexture(const char * path)
{
	uint textureID = 0;
	ILuint imageID;

	Texture* new_tex = nullptr;

	ILenum error;

	ilGenImages(1, &imageID);
	ilBindImage(imageID);

	if (ilLoadImage(path)) {
		ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);
		//Flip the image if it is upside-down
		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT) {
			iluFlipImage();
		}
		if (!ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE)) {
			error = ilGetError();
			LOG("Texture Image conversion Failed: %d %s", error, iluErrorString(error));
		}
		else {

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

			new_tex = new Texture();

			glGenTextures(1, &textureID);
			glBindTexture(GL_TEXTURE_2D, textureID);

			new_tex->id = textureID;
			new_tex->w = ilGetInteger(IL_IMAGE_WIDTH);
			new_tex->h = ilGetInteger(IL_IMAGE_HEIGHT);
			new_tex->format = ilGetInteger(IL_IMAGE_FORMAT);
			new_tex->path = path;
			new_tex->name = GetFileFromPath(path).c_str();

			//Clamping Method
			GLint clampParam;
			switch (clamp_type) {
			case clampingTexType_ClampToEdge:
				clampParam = GL_CLAMP_TO_EDGE;
				break;
			case clampingTexType_ClampRepeat:
				clampParam = GL_REPEAT;
				break;
			case clampingTexType_ClampMirroredRepeat:
				clampParam = GL_MIRRORED_REPEAT;
				break;
			default:
				clampParam = GL_REPEAT;
				break;
			}
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clampParam);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clampParam);
			// Interpolation Method
			GLint interParam;
			switch (interpolation_type) {
			case interpolationTexType_Nearest:
				interParam = GL_NEAREST;
				break;
			case interpolationTexType_Linear:
				interParam = GL_LINEAR;
				break;
			default:
				interParam = GL_LINEAR;
				break;
			}
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, interParam);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, interParam);

			//Texture Specifications
			glTexImage2D(GL_TEXTURE_2D, 0, new_tex->format, new_tex->w, new_tex->h, 0, new_tex->format, GL_UNSIGNED_BYTE, ilGetData());

			App->res->textures.push_back(new_tex);

			glBindTexture(GL_TEXTURE_2D, 0);
		}
	}
	else {
		error = ilGetError();
		LOG("Image Load Error %d %s", error, iluErrorString(error));
	}

	//glBindTexture(GL_TEXTURE_2D, 0);

	ilDeleteImages(1, &imageID);

	LOG("Texture Load End:\n\t%s", path);

	return new_tex;
}

int ModuleTextures::ImportTexture(const char * path, std::string& output_file)
{
	bool ret = false;

	std::string checkPath = LIBRARY_TEXTURES;
	checkPath += GetFileFromPath(path);
	checkPath += ".dds";
	if (!App->fs->exists(checkPath))
		ret = Import(path, output_file);
	else {
		LOG("Texture already imported");
		output_file = checkPath;
		ret = -1;
	}

	if (ret == false)
		LOG("ERROR importing texture %s", path);

	return ret;
}

Texture * ModuleTextures::LoadDDSTexture(const char * path)
{
	Texture* tex = nullptr;

	tex = Load(path, tex);

	return tex;
}

Texture * ModuleTextures::LoadToDDS(const char * path, std::string& output_file)
{
	Texture* tex = nullptr;
	curr_tex_state = ImportTexture(path, output_file);
	switch (curr_tex_state) {
	case -1:	// Repeated Tex
		for (int i = 0; i < App->res->textures.size(); i++) {
			if (App->res->textures[i]->path == output_file) {
				tex = App->res->textures[i];
				break;
			}
		}
		break;
	case true:	// Success Import
		tex = LoadDDSTexture(output_file.c_str());
		break;
	default:   // Failed Import
		LOG("ERROR Importing texture %s", GetFileFromPath(path).c_str());
		break;
	}

	return tex;
}

Texture * ModuleTextures::LoadToDDS(const char * path)
{
	Texture* tex = nullptr;

	std::string output_file;

	if (ImportTexture(path, output_file)) {
		tex = LoadDDSTexture(output_file.c_str());
	}
	else {
		LOG("ERROR Importing texture %s", GetFileFromPath(path).c_str());
	}

	return tex;
}

void ModuleTextures::DrawConfigPanel()
{
	if (ImGui::CollapsingHeader("Textures"))
	{
		if(clamping_str != nullptr)
			if (ImGui::Combo("Clamping Method", &clamp_type, clamping_str)) {
				App->parson->config->SetNumber("configuration.textures.clamping", clamp_type);
				App->parson->config->Save();
			}
		if(interpolate_str != nullptr)
			if (ImGui::Combo("Interpolation Method", &interpolation_type, interpolate_str)) {
				App->parson->config->SetNumber("configuration.textures.interpolation", interpolation_type);
				App->parson->config->Save();
			}
	}
}

bool ModuleTextures::Import(const char * path, std::string & output_file)
{
	bool ret = false;

	char* buffer = nullptr;
	uint size = App->fs->Load(path, &buffer);

	if (buffer != NULL) {
		ret = Import(buffer, size, output_file, GetFileFromPath(path).c_str());
	}

	if (buffer != nullptr) {
		mdelete[] buffer;
	}

	return ret;
}

bool ModuleTextures::Import(const void * buffer, uint size, std::string & output_file, const char * file_name = DEFAULT_TEXTURE_NAME)
{
	bool ret = false;

	if (buffer != NULL) {
		ILuint imageID;
		ilGenImages(1, &imageID);
		ilBindImage(imageID);

		if (ilLoadL(IL_TYPE_UNKNOWN, (const void*)buffer, size)) { // loads the buffer
			ilEnable(IL_FILE_OVERWRITE); // Enables File Overwriting (self-explanatory :s)

			ILuint ilsize;
			ILubyte* data;
			ilSetInteger(IL_DXTC_FORMAT, IL_DXT5); // Compression mode [DXT]
			ilsize = ilSaveL(IL_DDS, NULL, 0); // Just setting new buffer size
			if (ilsize > 0) {
				data = new ILubyte[ilsize];
				if (ilSaveL(IL_DDS, data, ilsize) > 0) {
					ret = App->fs->SaveUnique(LIBRARY_TEXTURES, (char*)data, file_name, "dds", ilsize, output_file, (file_name == DEFAULT_TEXTURE_NAME));
				}

				if (data != nullptr) {
					mdelete[] data;
				}

			}
			ilDeleteImages(1, &imageID);
		}
	}

	if (ret == false)
		LOG("ERROR importing texture from buffer");

	return ret;
}

Texture* ModuleTextures::Load(const char * exported_file)
{
	uint textureID = 0;
	ILuint imageID;

	Texture* new_tex = nullptr;

	ILenum error;

	ilGenImages(1, &imageID);
	ilBindImage(imageID);

	if (ilLoadImage(exported_file)) {
		ILinfo ImageInfo;
		iluGetImageInfo(&ImageInfo);
		//Flip the image if it is upside-down
		if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT) {
			iluFlipImage();
		}
		if (!ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE)) {
			error = ilGetError();
			LOG("Texture Image conversion Failed: %d %s", error, iluErrorString(error));
		}
		else {

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

			new_tex = new Texture();

			glGenTextures(1, &textureID);
			glBindTexture(GL_TEXTURE_2D, textureID);

			new_tex->id = textureID;
			new_tex->w = ilGetInteger(IL_IMAGE_WIDTH);
			new_tex->h = ilGetInteger(IL_IMAGE_HEIGHT);
			new_tex->format = ilGetInteger(IL_IMAGE_FORMAT);
			new_tex->path = exported_file;
			new_tex->name = GetFileFromPath(exported_file).c_str();

			//Clamping Method
			GLint clampParam;
			switch (clamp_type) {
			case clampingTexType_ClampToEdge:
				clampParam = GL_CLAMP_TO_EDGE;
				break;
			case clampingTexType_ClampRepeat:
				clampParam = GL_REPEAT;
				break;
			case clampingTexType_ClampMirroredRepeat:
				clampParam = GL_MIRRORED_REPEAT;
				break;
			default:
				clampParam = GL_REPEAT;
				break;
			}
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clampParam);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clampParam);
			// Interpolation Method
			GLint interParam;
			switch (interpolation_type) {
			case interpolationTexType_Nearest:
				interParam = GL_NEAREST;
				break;
			case interpolationTexType_Linear:
				interParam = GL_LINEAR;
				break;
			default:
				interParam = GL_LINEAR;
				break;
			}
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, interParam);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, interParam);

			//Texture Specifications
			glTexImage2D(GL_TEXTURE_2D, 0, new_tex->format, new_tex->w, new_tex->h, 0, new_tex->format, GL_UNSIGNED_BYTE, ilGetData());

			App->res->textures.push_back(new_tex);

			glBindTexture(GL_TEXTURE_2D, 0);
		}
	}
	else {
		error = ilGetError();
		LOG("Image Load Error %d %s", error, iluErrorString(error));
	}

	//glBindTexture(GL_TEXTURE_2D, 0);

	ilDeleteImages(1, &imageID);

	LOG("Texture Load End:\n\t%s", exported_file);

	return new_tex;
}

Texture* ModuleTextures::Load(const char * exported_file, Texture * tex)
{
	char* buffer = nullptr;
	std::string file = exported_file;
	uint size = App->fs->Load(file.c_str(), &buffer);

	Texture* new_tex = nullptr;

	if (buffer != nullptr) {
		if (size > 0) {
			uint textureID = 0;
			ILuint imageID;
			ILenum error;

			ilGenImages(1, &imageID);
			ilBindImage(imageID);

			if (ilLoadL(IL_DDS, buffer, size)) {
				ILinfo ImageInfo;
				iluGetImageInfo(&ImageInfo);
				//Flip the image if it is upside-down
				if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT) {
					iluFlipImage();
				}
				if (!ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE)) {
					error = ilGetError();
					LOG("Texture Image conversion Failed: %d %s", error, iluErrorString(error));
				}
				else {

					glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

					new_tex = new Texture();

					glGenTextures(1, &textureID);
					glBindTexture(GL_TEXTURE_2D, textureID);

					new_tex->id = textureID;
					new_tex->w = ilGetInteger(IL_IMAGE_WIDTH);
					new_tex->h = ilGetInteger(IL_IMAGE_HEIGHT);
					new_tex->format = ilGetInteger(IL_IMAGE_FORMAT);
					new_tex->path = exported_file;
					new_tex->name = GetFileFromPath(exported_file).c_str();

					//Clamping Method
					GLint clampParam;
					switch (clamp_type) {
					case clampingTexType_ClampToEdge:
						clampParam = GL_CLAMP_TO_EDGE;
						break;
					case clampingTexType_ClampRepeat:
						clampParam = GL_REPEAT;
						break;
					case clampingTexType_ClampMirroredRepeat:
						clampParam = GL_MIRRORED_REPEAT;
						break;
					default:
						clampParam = GL_REPEAT;
						break;
					}
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clampParam);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clampParam);
					// Interpolation Method
					GLint interParam;
					switch (interpolation_type) {
					case interpolationTexType_Nearest:
						interParam = GL_NEAREST;
						break;
					case interpolationTexType_Linear:
						interParam = GL_LINEAR;
						break;
					default:
						interParam = GL_LINEAR;
						break;
					}
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, interParam);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, interParam);

					//Texture Specifications
					glTexImage2D(GL_TEXTURE_2D, 0, new_tex->format, new_tex->w, new_tex->h, 0, new_tex->format, GL_UNSIGNED_BYTE, ilGetData());

					App->res->textures.push_back(new_tex);

					glBindTexture(GL_TEXTURE_2D, 0);
				}
			}
			else {
				error = ilGetError();
				LOG("Image Load Error %d %s", error, iluErrorString(error));
			}
			ilDeleteImages(1, &imageID);
		}
	}

	if (buffer != nullptr)
		mdelete[] buffer;

	LOG("Texture Load End:\n\t%s", exported_file);

	return new_tex;
}


text:
//
// Novell.Directory.Ldap.Asn1.LBEREncoder.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using System;

namespace Novell.Directory.Ldap.Asn1
{

	///  This class provides LBER encoding routines for ASN.1 Types. LBER is a
	/// subset of BER as described in the following taken from 5.1 of RFC 2251:
	///
	/// 5.1. Mapping Onto BER-based Transport Services
	///
	/// The protocol elements of Ldap are encoded for exchange using the
	/// Basic Encoding Rules (BER) [11] of ASN.1 [3]. However, due to the
	/// high overhead involved in using certain elements of the BER, the
	/// following additional restrictions are placed on BER-encodings of Ldap
	/// protocol elements:
	///
	///
(1) Only the definite form of length encoding will be used.

	///
	///
(2) OCTET STRING values will be encoded in the primitive form only.

	///
	///
(3) If the value of a BOOLEAN type is true, the encoding MUST have
	/// its contents octets set to hex "FF".

	///
	///
(4) If a value of a type is its default value, it MUST be absent.
	/// Only some BOOLEAN and INTEGER types have default values in this
	/// protocol definition.
	///
	/// These restrictions do not apply to ASN.1 types encapsulated inside of
	/// OCTET STRING values, such as attribute values, unless otherwise
	/// noted.

	///
	/// [3] ITU-T Rec. X.680, "Abstract Syntax Notation One (ASN.1) -
	/// Specification of Basic Notation", 1994.
	///
	/// [11] ITU-T Rec. X.690, "Specification of ASN.1 encoding rules: Basic,
	/// Canonical, and Distinguished Encoding Rules", 1994.
	///
	///
	[CLSCompliantAttribute(true)]
	public class LBEREncoder : Asn1Encoder
	{

		/* Encoders for ASN.1 simple type Contents
		*/
		public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
		{
		}
		///  BER Encode an Asn1Boolean directly into the specified output stream.
		public virtual void  encode(Asn1Boolean b, System.IO.Stream out_Renamed)
		{
			/* Encode the id */
			encode(b.getIdentifier(), out_Renamed);

			/* Encode the length */
			out_Renamed.WriteByte((System.Byte) 0x01);

			/* Encode the boolean content*/
			out_Renamed.WriteByte((byte) (b.booleanValue()?(sbyte) SupportClass.Identity(0xff):(sbyte) 0x00));

			return ;
		}

		///  Encode an Asn1Numeric directly into the specified outputstream.
		///
		/// Use a two's complement representation in the fewest number of octets
		/// possible.
		///
		/// Can be used to encode INTEGER and ENUMERATED values.
		///
		public void  encode(Asn1Numeric n, System.IO.Stream out_Renamed)
		{
			sbyte[] octets = new sbyte[8];
			sbyte len;
			long value_Renamed = n.longValue();
			long endValue = (value_Renamed < 0)?- 1:0;
			long endSign = endValue & 0x80;

			for (len = 0; len == 0 || value_Renamed != endValue || (octets[len - 1] & 0x80) != endSign; len++)
			{
				octets[len] = (sbyte) (value_Renamed & 0xFF);
				value_Renamed >>= 8;
			}

			encode(n.getIdentifier(), out_Renamed);
			out_Renamed.WriteByte((byte) len); // Length
			for (int i = len - 1; i >= 0; i--)
			// Content
				out_Renamed.WriteByte((byte) octets[i]);
			return ;
		}

		/* Asn1 TYPE NOT YET SUPPORTED
		* Encode an Asn1Real directly to a stream.
		public void encode(Asn1Real r, OutputStream out)
		throws IOException
		{
		throw new IOException("LBEREncoder: Encode to a stream not implemented");
		}
		*/

		///  Encode an Asn1Null directly into the specified outputstream.
		public void  encode(Asn1Null n, System.IO.Stream out_Renamed)
		{
			encode(n.getIdentifier(), out_Renamed);
			out_Renamed.WriteByte((System.Byte) 0x00); // Length (with no Content)
			return ;
		}

		/* Asn1 TYPE NOT YET SUPPORTED
		* Encode an Asn1BitString directly to a stream.
		public void encode(Asn1BitString bs, OutputStream out)
		throws IOException
		{
		throw new IOException("LBEREncoder: Encode to a stream not implemented");
		}
		*/

		///  Encode an Asn1OctetString directly into the specified outputstream.
		public void  encode(Asn1OctetString os, System.IO.Stream out_Renamed)
		{
			encode(os.getIdentifier(), out_Renamed);
			encodeLength(os.byteValue().Length, out_Renamed);
			sbyte[] temp_sbyteArray;
			temp_sbyteArray = os.byteValue();
			out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;;
			return ;
		}

		/* Asn1 TYPE NOT YET SUPPORTED
		* Encode an Asn1ObjectIdentifier directly to a stream.
		* public void encode(Asn1ObjectIdentifier oi, OutputStream out)
		* throws IOException
		* {
		* throw new IOException("LBEREncoder: Encode to a stream not implemented");
		* }
		*/

		/* Asn1 TYPE NOT YET SUPPORTED
		* Encode an Asn1CharacterString directly to a stream.
		* public void encode(Asn1CharacterString cs, OutputStream out)
		* throws IOException
		* {
		* throw new IOException("LBEREncoder: Encode to a stream not implemented");
		* }
		*/

		/* Encoders for ASN.1 structured types
		*/

		///  Encode an Asn1Structured into the specified outputstream.  This method
		/// can be used to encode SET, SET_OF, SEQUENCE, SEQUENCE_OF
		///
		public void  encode(Asn1Structured c, System.IO.Stream out_Renamed)
		{
			encode(c.getIdentifier(), out_Renamed);

			Asn1Object[] value_Renamed = c.toArray();

			System.IO.MemoryStream output = new System.IO.MemoryStream();

			/* Cycle through each element encoding each element */
			for (int i = 0; i < value_Renamed.Length; i++)
			{
				(value_Renamed[i]).encode(this, output);
			}

			/* Encode the length */
			encodeLength((int)output.Length, out_Renamed);

			/* Add each encoded element into the output stream */
			sbyte[] temp_sbyteArray;
			temp_sbyteArray = SupportClass.ToSByteArray(output.ToArray());
			out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;;
			return ;
		}

		///  Encode an Asn1Tagged directly into the specified outputstream.
		public void  encode(Asn1Tagged t, System.IO.Stream out_Renamed)
		{
			if (t.Explicit)
			{
				encode(t.getIdentifier(), out_Renamed);

				/* determine the encoded length of the base type. */
				System.IO.MemoryStream encodedContent = new System.IO.MemoryStream();
				t.taggedValue().encode(this, encodedContent);

				encodeLength((int)encodedContent.Length, out_Renamed);
				sbyte[] temp_sbyteArray;
				temp_sbyteArray = SupportClass.ToSByteArray(encodedContent.ToArray());
				out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;;;
			}
			else
			{
				t.taggedValue().encode(this, out_Renamed);
			}
			return ;
		}

		/* Encoders for ASN.1 useful types
		*/
		/* Encoder for ASN.1 Identifier
		*/

		///  Encode an Asn1Identifier directly into the specified outputstream.
		public void  encode(Asn1Identifier id, System.IO.Stream out_Renamed)
		{
			int c = id.Asn1Class;
			int t = id.Tag;
			sbyte ccf = (sbyte) ((c << 6) | (id.Constructed?0x20:0));

			if (t < 30)
			{
				/* single octet */
				out_Renamed.WriteByte((System.Byte) (ccf | t));
			}
			else
			{
				/* multiple octet */
				out_Renamed.WriteByte((System.Byte) (ccf | 0x1F));
				encodeTagInteger(t, out_Renamed);
			}
			return ;
		}

		/* Private helper methods
		*/

		/*
		*  Encodes the specified length into the the outputstream
		*/
		private void  encodeLength(int length, System.IO.Stream out_Renamed)
		{
			if (length < 0x80)
			{
				out_Renamed.WriteByte((System.Byte) length);
			}
			else
			{
				sbyte[] octets = new sbyte[4]; // 4 bytes sufficient for 32 bit int.
				sbyte n;
				for (n = 0; length != 0; n++)
				{
					octets[n] = (sbyte) (length & 0xFF);
					length >>= 8;
				}

				out_Renamed.WriteByte((System.Byte) (0x80 | n));

				for (int i = n - 1; i >= 0; i--)
					out_Renamed.WriteByte((byte) octets[i]);
			}
			return ;
		}

		///  Encodes the provided tag into the outputstream.
		private void  encodeTagInteger(int value_Renamed, System.IO.Stream out_Renamed)
		{
			sbyte[] octets = new sbyte[5];
			int n;
			for (n = 0; value_Renamed != 0; n++)
			{
				octets[n] = (sbyte) (value_Renamed & 0x7F);
				value_Renamed = value_Renamed >> 7;
			}
			for (int i = n - 1; i > 0; i--)
			{
				out_Renamed.WriteByte((System.Byte) (octets[i] | 0x80));
			}
			out_Renamed.WriteByte((byte) octets[0]);
			return ;
		}
	}
}


text:
<?php

namespace MwbExporter\Storage;

class ZipStorage extends Storage
{
    /**
     * @var \ZipArchive
     */
    protected $zip = null;

    public function initialize()
    {
        $filename = $this->getFile(date('Y-m-d_h-i-s').'_'.sprintf('%03d', mt_rand(1, 999)).'.zip');
        $this->zip = new \ZipArchive();
        if (false === $this->zip->open($filename, \ZipArchive::CREATE)) {
            throw new \Exception(sprintf('Can\'t create archive %s.', $filename));
        }
        $this->result = $filename;

        return $this;
    }

    public function save($filename, $content)
    {
        $this->zip->addFromString($filename, $content);

        return $this;
    }

    public function finalize()
    {
        $this->zip->close();

        return $this;
    }
}


text:
<?php
header ('Location:' .base_url(). 'admin/login');
?>


text:
node.normal[:attribute_priority_was] = "came from recipe[attribute_settings_normal::normal_in_recipe]"

execute "echo #{node[:attribute_priority_was]} > #{node[:tmpdir]}/attribute_setting.txt"


text:
tags: epidemiologi
title: Bildat folk
author: Karl Pettersson
lang: sv
---

Nu i dagarna har föreningen Vetenskap och Folkbildning annonserat förra årets
folkbildare och förvillare, som de brukar göra vid nyår [@olausson2018]. Det
första priset gick till epidemiologen Emma Frans, och det sista gick till den
så kallade hälsokejdan Life. Förvillarkedjan tänkte jag lämna därhän i det
följande. När det gäller Frans motiveras hennes pris av @voffb2017 med att hon
på olika sätt pedagogiskt och humoristiskt spridit kunskap och förklarat myter
och missförstånd kring vetenskap: hon har twittrat, haft en artikelserie i
Svenska Dagbladet och även gett ut en bok [@frans2017].

Folkbildarutmärkelsen var välförtjänt. Det florerar onekligen en hel del
vilseledande information kring vetenskap. Dels finns förstås rent
pseudovetenskapliga idéer, dels finns missvisande kommunikation av kanske i
grunden seriös forskning. Denna kan i sin tur delas upp i sådan
som forskarna själva förmedlar, t.ex.\ i syfte att blåsa upp betydelsen av sina
resultat, och sådan som andra förmedlar utan deras medverkan och de kanske
själva försöker korrigera, fast de då ofta har föga framgång. Flera av dessa teman
diskuteras av @frans2017.

Samtidigt exemplifierar @frans2017 vissa problem när det gäller kommunikation
av vetenskapliga resultat, som jag har diskuterat tidigare, och där ingen, vad
jag sett, kunnat komma med någon riktigt tillfredsställande lösning. I ett
kapitel med rubriken "[a]tt förstå statistik" diskuteras bl.a.\ diagram och
risker.

När vi läser diagram kan vi, för att undvika att bli lurade, kolla om y-axeln
"är beskuren eller inte" [@frans2017, st. 15.6]. Det ges ett exempel med ett
linjediagram från Alliansen i Göteborg som visar på hur andelen elever som lämnat
Göteborgs kommunala grundskolor med godkända betyg minskat från 79 procent 1998
till 65--70 procent åren 2011--16. Variationsområdet på y-axeln är från 60 till
85 procent, så det ser ut som en dramatisk minskning. Om y-axeln ändras så att
variationsområdet är från 0 till 100 procent ser minskningen betydligt mindre
dramatisk ut. Poängen illustreras med ett staplat diagram över andelen
tillfällen där det är vilseledande att kapa y-axeln: andelen är 99 procent, och
y-axelns variationsområde är från 98 till 100 procent. Någon definition av vad
som menas med "beskuren y-axel" ges inte. Intrycket som förmedlas är att det i
alla fall är ett tillräckligt villkor att y-axeln börjar ovanför 0.

[Den 11 december 2016](2016-12-11-skala.html) skrev jag om denna problematik.
Jag refererade till @yanofsky150608, som ger flera exempel när det *inte* är
rimligt att låta y-axeln börja på 0, som feberkurvor för människor. För
logaritmiska skalor är det rent omöjligt. Men mer generellt går det att ställa
sig frågan vad det egentligen innebär att börja på 0. I S.S.\ Stevens klassifikation
av måttskalor spelar "godtyckliga" nollpunkter en viktig roll för att skilja
mellan "intervallskalor" (som våra vanliga temperaturskalor) och "kvotskalor"
(för längd, vikt, absolut temperatur etc.). Men senare forskare har i sin tur
argumenterat för att denna "godtycklighet" inte kan avgöras oberoende av de
frågor som de statistiska undersökningarna är avsedda att besvara.

Om den relevanta nollpunkten på detta sätt är beroende av kontexten, är det
tveksamt om det går att ge någon definition av "beskuren y-axel" annat än
"y-axel som börjar ovanför en relevant baslinje för undersökningen". I så fall
blir det svårt att förneka att det är vilseledande med beskurna y-axlar, men
det finns inget enkelt, universellt sätt att avgöra om en y-axel är beskuren.
Denna problematik är dock kanske mest besvärlig för de som konstruerar diagram.
För de som läser ett diagram är det kanske tillräckligt att vara
uppmärksam på vad det egentligen är för variation diagrammet visar, därför att
en trend lätt kan fås att framstå som mer eller mindre dramatisk genom
manipulation av y-axeln.

Ett annat problemområde som diskuteras är tolkning av påståenden om att något
"ökar risken" för negativa utfall, som cancer [@frans2017, st. 15.52--15.59].
Diskussionen handlar om skillnaden mellan absoluta och relativa risker, som
illustreras med ett exempel med processat kött. Det sägs att "[d]en relativa
riskökningen" för kolorektal cancer för den som äter motsvarande någon korv om
dagen "är 1,18, det vill säga 18 procent högre" än för den som äter mindre än
så, vilket jämförs med rökning, som "ökar risken för lungcancer 20 gånger, det
vill säga med 2000 procent".^[*Riskökningarna* i exemplen är egentligen 0,18
och 19 (1900 procent).]
Men, säger Frans, det är en relativ riskökning som inte säger något om
individens absoluta risk att drabbas. Livstidsrisken för kolorektal cancer har
uppskattats till ca 5 procent. Men då innebär en riskökning på 18 procent att 6
procent av de som äter bacon eller korv får denna cancerform.^[I alla fall om
risken 5 procent är baserad på en befolkning där ingen äter en korv, eller
dess motsvarighet i bacon, om dagen.]

Jo, det är en viktig distinktion. Problemet, för den som börjar tillämpa
lärdomen vid tolkning av kohortstudier som refereras i media, är att sådana
kvoter mellan livstidsrisker sällan används som primärt utfallsmått i detta
slags studier. Ofta har studierna inte tillräckligt med information (t.ex.\ inte
tillräckligt lång uppföljningstid) för att beräkna livstidsrisker på ett
någorlunda tillförlitligt sätt. Utöver detta kan risker över lång tid lätt
påverkas av effekter på konkurrerande utfall (som olika dödsorsaker). Det har
definierats så kallade hazardtal, mått på "ögonblicklig risk" för de som
överlevt till en viss tidpunkt. Om hazardtalen inte minskar över tid och det
inte finns konkurrerande utfall (som vid total dödlighet), kommer risken över
tid att närma sig 1. Det är ofta kvoter mellan hazardtal som moderna
kohortstudier använder som utfallsmått. Dessvärre är dessa inte så lätta att
förklara på ett pedagogiskt sätt. Exempelvis [den 17 februari förra
året](2017-02-17-mjolk.html) har jag skrivit om hur medias rapportering kring
studier med detta mått tenderar att bli förvirrande. Fortfarande har jag inte
sett någon komma med någon bra lösning på problematiken.

## Referenser


text:
The \`@py\` command
===================

The ``@py`` command supplied with the default command set of Evennia
allows you to execute Python commands directly from inside the game. An
alias to ``@py`` is simply "``!``\ ". *Access to the ``@py`` command
should be severely restricted*. This is no joke - being able to execute
arbitrary Python code on the server is not something you should entrust
to just anybody.

::

    @py 1+2
    <<< 3

Available variables
-------------------

A few local variables are made available when running ``@py``. These
offer entry into the running system.

-  **self** / **me** - the calling object (i.e. you)
-  **here** - the current caller's location
-  **obj** - a dummy `Object <Objects.html>`_ instance
-  **ev** - Evennia's flat API - through this you can access all of
   Evennia.

Returning output
----------------

This is an example where we import and test one of Evennia's utilities
found in ``src/utils/utils.py``, but also accessible through
``ev.utils``:

::

    @py from ev import utils; utils.time_format(33333)
    <<< Done.

Note that we didn't get any return value, all we where told is that the
code finished executing without error. This is often the case in more
complex pieces of code which has no single obvious return value. To see
the output from the ``time_format()`` function we need to tell the
system to echo it to us explicitly with ``self.msg()``.

::

    @py from ev import utils; self.msg(utils.time_format(33333))
    09:15
    <<< Done.

If you were to use Python's standard ``print``, you will see the result
in your current ``stdout`` (your terminal by default), *if* you are
running Evennia in *interactive mode* (with the ``-i`` flag).

Finding objects
---------------

A common use for ``@py`` is to explore objects in the database, for
debugging and performing specific operations that are not covered by a
particular command.

Locating an object is best done using ``self.search()``:

::

    @py self.search("red_ball")
    <<< Ball

    @py self.search("red_ball").db.color = "red"
    <<< Done.

    @py self.search("red_ball").db.color
    <<< red

``self.search()`` is by far the most used case, but you can also search
other database tables for other Evennia entities like scripts or
configuration entities. To do this you can use the generic search
entries found in ``ev.search_*``.

::

    @py ev.search_script("sys_game_time")
    <<< [<src.utils.gametime.GameTime object at 0x852be2c>]

(Note that since this becomes a simple statement, we don't have to wrap
it in ``self.msg()`` to get the output). You can also use the database
model managers directly (accessible through the ``objects`` properties
of database models or as ``ev.managers.*``). This is a bit more flexible
since it gives you access to the full range of database search methods
defined in each manager.

::

    @py ev.managers.scripts.script_search("sys_game_time")
    <<< [<src.utils.gametime.GameTime object at 0x852be2c>]

The managers are useful for all sorts of database studies.

::

    @py ev.managers.configvalues.all()
    <<< [<ConfigValue: default_home]>, <ConfigValue:site_name>, ...]

In doing so however, keep in mind the difference between `Typeclasses
and Database Objects <Typeclasses.html>`_: Using the search commands in
the managers will return *TypeClasses*. Using Django's default search
methods (``get``, ``filter`` etc) will return *Database objects*. This
distinction can often be disregarded, but as a convention you should try
to stick with the manager search functions and work with TypeClasses in
most situations.

::

    # this uses Evennia's manager method get_id().
    # It returns a Character typeclass instance
    @py ev.managers.objects.get_id(1).__class__
    <<< Character

    # this uses the standard Django get() query.
    # It returns a django database model instance.
    @py ev.managers.objects.get(id=1).__class__
    <<< <class 'src.objects.models.ObjectDB'>

Running a Python Parser outside the game
========================================

``@py`` has the advantage of operating inside a running server, where
you can test things in real time. Much of this *can* be done from the
outside too though.

Go to the ``game`` directory and get into a new terminal.

::

    python manage.py shell

Your default Python intrepeter will start up, configured to be able to
work with and import all modules of your Evennia installation. From here
you can explore the database and test-run individual modules as desired.
Most of the time you can get by with just the ``ev`` module though. A
fully featured Python interpreter like
`iPython <http://ipython.scipy.org/moin/>`_ allow you to work over
several lines, but also has lots of other editing features, usch as
tab-completion and ``__doc__``-string reading.

::

    $ python manage.py shell

    IPython 0.10 -- An enhanced Interactive Python
    ...

    In [1]: import ev
    In [2]: ev.managers.objects.all()
    Out[3]: [<ObjectDB: Harry>, <ObjectDB: Limbo>, ...]


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Karleen & Curtis - Oct 5th 2017</title>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="css/grayscale.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                    Menu
                </button>

                        Wedding Details

                        Travel Tips

                        KC Favorites

			   Zola Registry

			   Amazon Registry

Karleen & Curtis - October 5th 2017 - Schedule

3:30-4:00 PM Roberts Regional Park (5$ Parking)
4:30 PM Roberts Regional Park - Madrone Grove, Ceremony. Announced by MC. 15 min. Read no phones/photos announcement
5:00 PM Family photos after ceremony; moms, dads, siblings only *photos of aunts, cousins, friends at reception
5:30 PM Piedmont Community Hall - Reception cocktail hour, appitizers
6:45-7PM Dinner starts, group photo! MC & Photographer announce
8:30 PM First Dance
10:30 PM Bar Last Call
11:00 PM Last song. Clean up starts
12:00 AM Permit ends, OUT of venue.

Karleen & Curtis Are Getting Hitched on October 5th 2017

                            A story of love, adventure, and growth

				 RSVP

RSVP FORM

Fill out my online form.

Use Wufoo integrations and get your data to your favorite apps.

Wedding Details

 Our wedding date is Oct 5th 2017

 Our Ceremony venue is the Madrone Grove in Roberts Regional Park.

                    10570 Skyline Blvd, Oakland CA 94619. We chose this because it's a beautiful and special area for us that is next to fun, curvy roads that we ride our turbo-charged subaru on as well as our motorycles.
                    This park is full of California's famous redwoods and is 15 minutes away from our Reception.

 Our Reception venue is Piedmont Community Hall.

                    711 Highland Ave, Oakland CA 94611 We chose this because it is in a historical part of the East Bay, a city within the city of Oakland.
                    This building is simple and elegant and is set in a park full of history and old growth trees.

 Our Caterer is Smoking Woods BBQ

									       This place is delicious and amazing.. You have to see these photos at the  Smoking Woods BBQ Instagram!

Travel Tips

Here are two very helpful websites

                    Kayak.com for Travel booking and Flight,Hotel and Rental Car Pricing for all services providers

                    AirBnB.com for independent bed and breakfast booking

 For those of you driving -

                    Google Maps can be used to plan a route

                    Weather Underground can be used to confirm weatherconditions on route.

Do I need to rent a car ?

It depends.

                        You can use the BART to get to from both SFO and OAK to Oakland, San Francisco, Berkeley.
                                     Visit BART.gov for info.

                        Lyft, Uber and taxis are prominent here.

                        Consider bicycle rentals for fun!

 Where should I stay ?

                        Again, it depends on how long your trip is and what you'd like to see. Contact either Karleen or Curtis if you need help.
                        We strongly recomend staying in Oakland or Berkeley the night of the wedding. Transbay transit stops around 11 PM.
                            Check out AIRBNB in the Lake Merrit/Grand Lake, Temescal, Rockridge, Piedmont areas of Oakland.
                        Lake Merrit/Grand Lake is near our home and has a Saturday farmer's market, dining, shops, and parks.
                        The Berkeley and Oakland Hills are gorgeous and in the vincinity of both venues.
                        Oakland Hotels, Berkeley Hotels are the second best options. Again, please reach out if you need extra help.

KC Favorites

                             Rooz Coffee (cafe, lunch, breakfast)

                            Blackberry Bistro (brunch, lunch)

                            Arizmendi(coffee, bakery, lunch)

                             Boot & Shoe Service ( Brunch, Lunch, Supper)

Copyright © Karleen & Curtis, RAM9.cc


text:
'use strict';
var thrift = require('../lib/thrift');

module.exports.transports = {
  'buffered': thrift.TBufferedTransport,
  'framed': thrift.TFramedTransport
};

module.exports.protocols = {
  'json': thrift.TJSONProtocol,
  'binary': thrift.TBinaryProtocol,
  'compact': thrift.TCompactProtocol
};


text:
//
//  Copyright (c) 2017 Google Inc.
//
//  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.
//

@import Foundation;

NS_ASSUME_NONNULL_BEGIN

/**
 * A block which is invoked on the main thread when something the Firebase Continue library
 * attempted to do asynchronously completed. The error provided to the block will be non-nil if
 * the it was unsuccessful. See the library method documentation below for more details.
 */
typedef void (^FCNContinueCompletionBlock)(NSError *_Nullable firebaseContinueError);

/**
 * @class FCNContinue
 * @brief The Firebase Continue for iOS library.
 *
 * Firebase Continue enables developers to easily integrate activity transitioning from their
 * iOS apps to the web, by way of Firebase and Chrome extensions (or Apple Handoff for users with
 * both an iOS device and macOS computer that are Apple Handoff enabled).
 * For more details, see: https://github.com/firebase/firebase-continue
 *
 * Please see the usage instructions in the relevant README file(s).
 * There is also more specific documentation within the library itself below.
 *
 * TODO: Add unit tests, including tests while the app/Firebase is offline.
 */
@interface FCNContinue : NSObject

/**
 * Attempts to asynchronously broadcast an Activity (codified as a URL) within an application
 * that the currently signed in user may wish to continue elsewhere (in the immediate future)
 * to all potential clients (ex. Chrome extension(s) and/or Apple Handoff enabled macOS computers)
 * which could allow the user to do so by opening said URL.
 *
 * Note that, by design, only the most recently successfully broadcast Activity (for a given
 * application) could possibly be relevant to the user. The Firebase Continue database rules
 * and libraries enforce this. For more details, please see the relevant README file(s).
 *
 * @param activityUrl The URL which, if the current user were to navigate to, would allow the user
 * to continue their Activity.
 * @param applicationName The name of the application, as defined in the Firebase Realtime
 * Database rules for Firebase Continue, that the user's Activity is within.
 * @param completionBlock An optional completion block which is invoked on the main thread when the
 * broadcast attempt is complete. The error provided to the block will be non-nil if the broadcast
 * was unsuccessful.
 */
+ (void)broadcastToContinueActivityWithUrl:(NSString *)activityUrl
                 withinApplicationWithName:(NSString *)applicationName
                       withCompletionBlock:(nullable FCNContinueCompletionBlock)completionBlock
    NS_SWIFT_NAME(broadcastToContinueActivity(withUrl:withinApplication:onComplete:));

/**
 * TODO: Possibly add a "dismissActivityToContinue" method akin to dismissing within the Chrome
 * extensions library. This could be used by mobile apps when an Activity that was broadcast would
 * certainly no longer be relevant to the user (rather than letting the Chrome extension library
 * itself (or the user within a Chrome extension) decide that).
 */

- (id)init __attribute__((unavailable("FCNContinue cannot be instantiated")));

@end

NS_ASSUME_NONNULL_END


text:
#ifndef _BLP_BLP_H_
#define _BLP_BLP_H_

extern unsigned long LoadBLP(char *destBuf, char *srcBuf, long *width, long *height, unsigned long *type, unsigned long *subtype);
extern unsigned long MakeBLP(char *destBuf, char *srcBuf, long width, long height, int quality);

extern unsigned long LoadTGA(char *destbuf, char *srcbuf, long *width, long *height, long *bpp, long *type);
extern unsigned long MakeTGA(char *destBuf, char *srcBuf, long width, long height, long bpp);

extern unsigned long MakeJPG(char *destBuf, char *srcBuf, long width, long height, int quality);

extern int BLP2Everything(char *srcbuf, unsigned long srcbuflen, const char *szFileDest);

#endif


text:
package com.blt.talk.message.server.handler;

import com.blt.talk.common.code.IMHeader;
import com.google.protobuf.MessageLite;

import io.netty.channel.ChannelHandlerContext;

/**
 * 登录相关Handler
 * @author 袁贵
 * @version 1.0
 * @since  3.0
 */
public interface IMLoginHandler {

    /**
     *
     * @param header 消息头
     * @param msg
     * @param ctx 连接context
     * @throws Exception
     * @since  3.0
     */
    public void login(IMHeader header, MessageLite msg, ChannelHandlerContext ctx) throws Exception;

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void logOut(IMHeader header, MessageLite body, ChannelHandlerContext ctx);

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void kickUser(IMHeader header, MessageLite body, ChannelHandlerContext ctx);

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void deviceToken(IMHeader header, MessageLite body, ChannelHandlerContext ctx);

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void kickPcClient(IMHeader header, MessageLite body, ChannelHandlerContext ctx);

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void pushShield(IMHeader header, MessageLite body, ChannelHandlerContext ctx);

    /**
     * @param header 消息头
     * @param body 消息体
     * @param ctx 连接context
     * @since  3.0
     */
    public void queryPushShield(IMHeader header, MessageLite body, ChannelHandlerContext ctx);
}


text:
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Exit32: React.ForwardRefExoticComponent<
  CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Exit32;