text:
#include <stdlib.h>

#include "jsmn.h"

#ifdef JSMN_FIRST_CHILD_NEXT_SIBLING
/**
 * Connects a (non-root) node either as a child or a sibling, given its parent.
 * Helper function that is called from the parse routine,
 */
static void
jsmn_fill_first_child_next_sibling(jsmntok_t* const tokens, int parent, int me)
{
    //if parent has no other children, then we're the first
    if (tokens[parent].first_child == -1) {
        tokens[parent].first_child = me;
    }
    //if we're not the first child, we must be a sibling
    else {
        int my_sibling = tokens[parent].first_child;
        while (tokens[my_sibling].next_sibling != -1) {
            my_sibling = tokens[my_sibling].next_sibling;
        }
        tokens[my_sibling].next_sibling = me;
    }
}
#endif

/**
 * Allocates a fresh unused token from the token pull.
 */
static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
		jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *tok;
	if (parser->toknext >= num_tokens) {
		return NULL;
	}
	tok = &tokens[parser->toknext++];
	tok->start = tok->end = -1;
	tok->size = 0;
#ifdef JSMN_PARENT_LINKS
	tok->parent = -1;
#endif
#ifdef JSMN_FIRST_CHILD_NEXT_SIBLING
        tok->first_child = -1;
        tok->next_sibling = -1;
#endif
	return tok;
}

/**
 * Fills token type and boundaries.
 */
static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
                            int start, int end) {
	token->type = type;
	token->start = start;
	token->end = end;
	token->size = 0;
}

/**
 * Fills next available token with JSON primitive.
 */
static jsmnerr_t jsmn_parse_primitive(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;
	int start;

	start = parser->pos;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		switch (js[parser->pos]) {
#ifndef JSMN_STRICT
			/* In strict mode primitive must be followed by "," or "}" or "]" */
			case ':':
#endif
			case '\t' : case '\r' : case '\n' : case ' ' :
			case ','  : case ']'  : case '}' :
				goto found;
		}
		if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
			parser->pos = start;
			return JSMN_ERROR_INVAL;
		}
	}
#ifdef JSMN_STRICT
	/* In strict mode primitive must be followed by a comma/object/array */
	parser->pos = start;
	return JSMN_ERROR_PART;
#endif

found:
	if (tokens == NULL) {
		parser->pos--;
		return 0;
	}
	token = jsmn_alloc_token(parser, tokens, num_tokens);
	if (token == NULL) {
		parser->pos = start;
		return JSMN_ERROR_NOMEM;
	}
	jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
#ifdef JSMN_PARENT_LINKS
	token->parent = parser->toksuper;
#endif
#ifdef JSMN_FIRST_CHILD_NEXT_SIBLING
        jsmn_fill_first_child_next_sibling(tokens, parser->toksuper, parser->toknext - 1);
#endif
	parser->pos--;
	return 0;
}

/**
 * Filsl next token with JSON string.
 */
static jsmnerr_t jsmn_parse_string(jsmn_parser *parser, const char *js,
		size_t len, jsmntok_t *tokens, size_t num_tokens) {
	jsmntok_t *token;

	int start = parser->pos;

	parser->pos++;

	/* Skip starting quote */
	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c = js[parser->pos];

		/* Quote: end of string */
		if (c == '\"') {
			if (tokens == NULL) {
				return 0;
			}
			token = jsmn_alloc_token(parser, tokens, num_tokens);
			if (token == NULL) {
				parser->pos = start;
				return JSMN_ERROR_NOMEM;
			}
			jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
#ifdef JSMN_PARENT_LINKS
			token->parent = parser->toksuper;
#endif
#ifdef JSMN_FIRST_CHILD_NEXT_SIBLING
                        jsmn_fill_first_child_next_sibling(tokens, parser->toksuper, parser->toknext - 1);
#endif
			return 0;
		}

		/* Backslash: Quoted symbol expected */
		if (c == '\\' && parser->pos + 1 < len) {
			int i;
			parser->pos++;
			switch (js[parser->pos]) {
				/* Allowed escaped symbols */
				case '\"': case '/' : case '\\' : case 'b' :
				case 'f' : case 'r' : case 'n'  : case 't' :
					break;
				/* Allows escaped symbol \uXXXX */
				case 'u':
					parser->pos++;
					for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) {
						/* If it isn't a hex character we have an error */
						if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
									(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
									(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
							parser->pos = start;
							return JSMN_ERROR_INVAL;
						}
						parser->pos++;
					}
					parser->pos--;
					break;
				/* Unexpected symbol */
				default:
					parser->pos = start;
					return JSMN_ERROR_INVAL;
			}
		}
	}
	parser->pos = start;
	return JSMN_ERROR_PART;
}

/**
 * Parse JSON string and fill tokens.
 */
jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
		jsmntok_t *tokens, unsigned int num_tokens) {
	jsmnerr_t r;
	int i;
	jsmntok_t *token;
	int count = 0;

	for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
		char c;
		jsmntype_t type;

		c = js[parser->pos];
		switch (c) {
			case '{': case '[':
				count++;
				if (tokens == NULL) {
					break;
				}
				token = jsmn_alloc_token(parser, tokens, num_tokens);
				if (token == NULL)
					return JSMN_ERROR_NOMEM;
				if (parser->toksuper != -1) {
					tokens[parser->toksuper].size++;
#ifdef JSMN_PARENT_LINKS
					token->parent = parser->toksuper;
#endif
#ifdef JSMN_FIRST_CHILD_NEXT_SIBLING
                                        jsmn_fill_first_child_next_sibling(tokens, parser->toksuper, parser->toknext - 1);
#endif
				}
				token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
				token->start = parser->pos;
				parser->toksuper = parser->toknext - 1;
				break;
			case '}': case ']':
				if (tokens == NULL)
					break;
				type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
#ifdef JSMN_PARENT_LINKS
				if (parser->toknext < 1) {
					return JSMN_ERROR_INVAL;
				}
				token = &tokens[parser->toknext - 1];
				for (;;) {
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						token->end = parser->pos + 1;
						parser->toksuper = token->parent;
						break;
					}
					if (token->parent == -1) {
						break;
					}
					token = &tokens[token->parent];
				}
#else
				for (i = parser->toknext - 1; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						if (token->type != type) {
							return JSMN_ERROR_INVAL;
						}
						parser->toksuper = -1;
						token->end = parser->pos + 1;
						break;
					}
				}
				/* Error if unmatched closing bracket */
				if (i == -1) return JSMN_ERROR_INVAL;
				for (; i >= 0; i--) {
					token = &tokens[i];
					if (token->start != -1 && token->end == -1) {
						parser->toksuper = i;
						break;
					}
				}
#endif
				break;
			case '\"':
				r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;
			case '\t' : case '\r' : case '\n' : case ' ':
				break;
			case ':':
				parser->toksuper = parser->toknext - 1;
				break;
			case ',':
				if (tokens != NULL &&
						tokens[parser->toksuper].type != JSMN_ARRAY &&
						tokens[parser->toksuper].type != JSMN_OBJECT) {
#ifdef JSMN_PARENT_LINKS
					parser->toksuper = tokens[parser->toksuper].parent;
#else
					for (i = parser->toknext - 1; i >= 0; i--) {
						if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
							if (tokens[i].start != -1 && tokens[i].end == -1) {
								parser->toksuper = i;
								break;
							}
						}
					}
#endif
				}
				break;
#ifdef JSMN_STRICT
			/* In strict mode primitives are: numbers and booleans */
			case '-': case '0': case '1' : case '2': case '3' : case '4':
			case '5': case '6': case '7' : case '8': case '9':
			case 't': case 'f': case 'n' :
				/* And they must not be keys of the object */
				if (tokens != NULL) {
					jsmntok_t *t = &tokens[parser->toksuper];
					if (t->type == JSMN_OBJECT ||
							(t->type == JSMN_STRING && t->size != 0)) {
						return JSMN_ERROR_INVAL;
					}
				}
#else
			/* In non-strict mode every unquoted value is a primitive */
			default:
#endif
				r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
				if (r < 0) return r;
				count++;
				if (parser->toksuper != -1 && tokens != NULL)
					tokens[parser->toksuper].size++;
				break;

#ifdef JSMN_STRICT
			/* Unexpected char in strict mode */
			default:
				return JSMN_ERROR_INVAL;
#endif
		}
	}

	for (i = parser->toknext - 1; i >= 0; i--) {
		/* Unmatched opened object or array */
		if (tokens[i].start != -1 && tokens[i].end == -1) {
			return JSMN_ERROR_PART;
		}
	}

	return count;
}

/**
 * Creates a new parser based over a given  buffer with an array of tokens
 * available.
 */
void jsmn_init(jsmn_parser *parser) {
	parser->pos = 0;
	parser->toknext = 0;
	parser->toksuper = -1;
}


text:
package org.flowable.ui.task.service.debugger;

import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RuntimeService;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.impl.el.ExpressionManager;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.scripting.ScriptingEngines;
import org.flowable.engine.event.EventLogEntry;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessDebugger;
import org.flowable.job.api.Job;
import org.flowable.variable.api.delegate.VariableScope;
import org.flowable.ui.task.model.debugger.BreakpointRepresentation;
import org.flowable.ui.task.model.debugger.ExecutionRepresentation;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.flowable.engine.impl.agenda.DebugContinueProcessOperation.HANDLER_TYPE_BREAK_POINT;

/**
 * This class implements basic methods for managing breakpoints
 *
 * @author martin.grofcik
 */
@Service
public class DebuggerService implements ProcessDebugger, ApplicationContextAware {

    protected List<BreakpointRepresentation> breakpoints = new ArrayList<>();
    protected ApplicationContext applicationContext;

    public void addBreakpoint(BreakpointRepresentation breakpointRepresentation) {
        assert breakpointRepresentation != null && isNotBlank(breakpointRepresentation.getActivityId());
        this.breakpoints.add(breakpointRepresentation);
    }

    public void removeBreakpoint(BreakpointRepresentation breakpointRepresentation) {
        assert breakpointRepresentation != null && isNotBlank(breakpointRepresentation.getActivityId());
        if (!this.breakpoints.remove(breakpointRepresentation)) {
            throw new FlowableException("Breakpoint is not set on the activityId");
        }
    }

    public List<BreakpointRepresentation> getBreakpoints() {
        return breakpoints;
    }

    public Collection<String> getBrokenExecutions(String activityId, String processInstanceId) {
        List<Job> brokenJobs = getManagementService().createSuspendedJobQuery().
                processInstanceId(processInstanceId).
                handlerType(HANDLER_TYPE_BREAK_POINT).
                list();

        ArrayList<String> executions = new ArrayList<>();
        for (Job brokenJob : brokenJobs) {
            Execution brokenJobExecution = getRuntimeService().createExecutionQuery().executionId(brokenJob.getExecutionId()).singleResult();
            if (activityId.equals(brokenJobExecution.getActivityId())) {
                executions.add(brokenJob.getExecutionId());
            }
        }
        return executions;
    }

    public List<EventLogEntry> getProcessInstanceEventLog(String processInstanceId) {
        return getManagementService().getEventLogEntriesByProcessInstanceId(processInstanceId);
    }

    public void continueExecution(String executionId) {
        Job job = getManagementService().createSuspendedJobQuery().handlerType(HANDLER_TYPE_BREAK_POINT).executionId(executionId).singleResult();
        if (job == null) {
            throw new FlowableException("No broken job found for execution '" + executionId + "'");
        }

        getManagementService().moveSuspendedJobToExecutableJob(job.getId());
        try {
            // wait until job is processed
            while (getManagementService().createJobQuery().jobId(job.getId()).count() > 0) {
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
        }
    }

    @Override
    public boolean isBreakpoint(Execution execution) {
        for (BreakpointRepresentation breakpoint : breakpoints) {
            if (breakpoint.getActivityId().equals(execution.getActivityId())) {
                if (StringUtils.isEmpty(breakpoint.getProcessDefinitionId())) {
                    return true;
                }

                if (Objects.equals(breakpoint.getProcessDefinitionId(), ((ExecutionEntity) execution).getProcessDefinitionId())) {
                    return true;
                }
            }
        }
        return false;
    }

    protected ManagementService getManagementService() {
        return this.applicationContext.getBean(ManagementService.class);
    }

    protected RuntimeService getRuntimeService() {
        return this.applicationContext.getBean(RuntimeService.class);
    }

    protected HistoryService getHistoricService() {
        return this.applicationContext.getBean(HistoryService.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public List<DebuggerRestVariable> getExecutionVariables(String executionId) {
        List<Execution> executions = getRuntimeService().createExecutionQuery().executionId(executionId).list();
        if (executions.isEmpty()) {
            return getHistoricService().createHistoricVariableInstanceQuery().executionId(executionId).list().stream().
                    map(DebuggerRestVariable::new).
                    collect(Collectors.toList());
        }
        return getRuntimeService().getVariableInstances(executionId).values().stream().
                map(DebuggerRestVariable::new).
                collect(Collectors.toList());
    }

    public List<ExecutionRepresentation> getExecutions(String processInstanceId) {
        List<Execution> executions = getRuntimeService().createExecutionQuery().processInstanceId(processInstanceId).list();
        List<ExecutionRepresentation> executionRepresentations = new ArrayList<>(executions.size());
        for (Execution execution : executions) {
            executionRepresentations.add(new ExecutionRepresentation(execution.getId(), execution.getParentId(),
                    execution.getProcessInstanceId(), execution.getSuperExecutionId(), execution.getActivityId(),
                    execution.isSuspended(), execution.getTenantId()));
        }
        return executionRepresentations;
    }

    public Object evaluateExpression(final String executionId, final String expressionString) {
        final ProcessEngineConfigurationImpl processEngineConfiguration = this.applicationContext.getBean(ProcessEngineConfigurationImpl.class);
        return processEngineConfiguration.getManagementService().executeCommand(commandContext -> {
            ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
            Expression expression = expressionManager.createExpression(expressionString);
            Execution execution = Context.getProcessEngineConfiguration().getExecutionEntityManager().findById(executionId);
            return expression.getValue((VariableScope) execution);
        });
    }

    public void evaluateScript(final String executionId, final String scriptLanguage, final String script) {
        getManagementService().executeCommand(
                (Command<Void>) commandContext -> {
                    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
                    Execution execution = Context.getProcessEngineConfiguration().getExecutionEntityManager().findById(executionId);
                    scriptingEngines.evaluate(script, scriptLanguage, (ExecutionEntityImpl) execution, false);
                    return null;
                }
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        if (! $schema->hasColumn('migrations', 'id')) {
            $schema->table('migrations', function (Blueprint $table) {
                $table->increments('id')->first();
            });
        }
    },

    'down' => function (Builder $schema) {
        $schema->table('migrations', function (Blueprint $table) {
            $table->dropColumn('id');
        });
    }
];


text:
<?php

use yii\helpers\Html;
use yii\helpers\StringHelper;
use yii\widgets\Pjax;

/* @var $pageInfo \Embed\Adapters\AdapterInterface data from request */
/* @var $linkPreviewModel \yii2mod\linkpreview\models\LinkPreviewModel */
/* @var $pjaxContainerId string */

?>
<?php Pjax::begin(['timeout' => 5000, 'enablePushState' => false, 'id' => $pjaxContainerId]); ?>
<?php if (!empty($pageInfo)) : ?>

                <a href="<?php echo $pageInfo->getUrl(); ?>" class="preview-link-container" target="_blank">
                    <?php echo Html::img($pageInfo->getImage(), ['id' => 'preview-image']); ?>
                    <?php if ($pageInfo->getType() === 'video') : ?>

                    <?php endif; ?>

                    <?php echo Html::a($pageInfo->getTitle(), $pageInfo->getUrl(), ['target' => '_blank']); ?>

                    <?php echo StringHelper::truncateWords($pageInfo->getDescription(), 50); ?>

                    <?php echo $pageInfo->getRequest()->getHost(); ?>

                <?php echo Html::activeHiddenInput($linkPreviewModel, 'image', ['value' => $pageInfo->getImage()]); ?>
                <?php echo Html::activeHiddenInput($linkPreviewModel, 'title', ['value' => $pageInfo->getTitle()]); ?>
                <?php echo Html::activeHiddenInput($linkPreviewModel, 'url', ['value' => $pageInfo->getUrl()]); ?>
                <?php echo Html::activeHiddenInput($linkPreviewModel, 'canonicalUrl', ['value' => $pageInfo->getRequest()->getHost()]); ?>
                <?php echo Html::activeHiddenInput($linkPreviewModel, 'description', ['value' => $pageInfo->getDescription()]); ?>
                <?php echo Html::activeHiddenInput($linkPreviewModel, 'code', ['value' => $pageInfo->getCode()]); ?>

<?php endif; ?>
<?php Pjax::end(); ?>


text:
//
//  NSNotificationCenter+Extension.h
//  BaseProject
//
//  Created by 曹冬冬 on 16/9/18.
//  Copyright © 2016年 曹冬冬. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSNotificationCenter (Extension)

/**
 *  只发送一个通知
 */
+ (void)postNotification:(NSString *)notiname;

/**
 *  发送一个通知
 *
 *  @param notiname 通知名字
 *  @param object 通知内容
 */
+ (void)postNotification:(NSString *)notiname object:(id)object;

/**
 *  移除所有通知的注册者
 */
+ (void)removeAllObserverForObj:(id)obj;

/**
 *  注册一个通知
 */
+ (void)addObserver:(id)observer action:(SEL)action name:(NSString *)name;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 10(no. 54): 57 (1881)

#### Original name
Irpex grossus Kalchbr.

### Remarks
null


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>Leetcode 4</title>

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

    <link href="/css/clean-blog.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.5.2/animate.min.css">

            Haifeng Jin's Blog

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

        </button>

                        Home

                        Technology

                        Competitive

                        Chinese

                              Contact

                                Linkedin

                                GitHub

                                Google Scholar

                                E-mail

            <form class="form-inline my-2 my-lg-0">
              <input class="form-control mr-sm-2" type="search" onkeydown="if(event.keyCode==13) googlesearch();" name="search-key-words" placeholder="Search" aria-label="Search">
              <button class="btn btn-outline-success my-2 my-sm-0" onclick="googlesearch()">Search</button>
            </form>

Tutorial

                        The Art of Competitive Programming

Leetcode 4

			Posted on 21 Feb 2017

			binary search

Problem Link

Tutorial

First, I thought binary search the median value , and every time see if there is correct number of items less than  altogether in both arrays.
However, it involves another two binary searches to locate the position of  in both arrays, within the binary search of ,
It make the complexity rise to .

The best way is to binary search a divide position in the longer array.
Imagine, we divide the two arrays into 4 halves, all the elements in the left two halves are less than the right two halves, this division would help us locate the median.
Every time we have a divide position in the longer array, we can directly calculate where to divide in the second array, since the total number of elements in the left halves should equal to that of the right halves.
Then, we check whether this division is valid, by comparing the right most elements in the left halves and the left most elements in the right halves.
The complexity is .

Solution

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        if len(nums1) < len(nums2):
            nums1, nums2 = nums2, nums1

        self.n = len(nums1) + len(nums2)

        if not nums2:
            return (nums1[(self.n + 1) / 2 - 1] + nums1[self.n / 2]) / 2.0

        l = 0
        r = len(nums1)
        while l < r:
            mid = (l + r) / 2
            if self.ok(mid, nums1, nums2):
                r = mid
            else:
                l = mid + 1
        l1, r1 = self.get_lr(nums1, l)
        l2, r2 = self.get_lr(nums2, self.n / 2 - l)
        if self.n % 2 == 1:
            return min(r1, r2)
        return (max(l1, l2) + min(r1, r2)) / 2.0

    def ok(self, a, nums1, nums2):
        b = self.n / 2 - a
        if b > len(nums2):
            return False
        if b < 0:
            return True
        l1, r1 = self.get_lr(nums1, a)
        l2, r2 = self.get_lr(nums2, b)
        if l2 > r1:
            return False
        return True

    def get_lr(self, nums, n):
        l = nums[n - 1] if n != 0 else -float('inf')
        r = nums[n] if n != len(nums) else float('inf')
        return l, r

    Please enable JavaScript to view the comments powered by Disqus.

<big>Introduction</big>

Here are some write-ups for the competitive programming problems I solved.

<big>Code Library</big>

My code library link on GitHub.


text:
import React, { Component } from 'react';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { CookiesProvider } from 'react-cookie';
import reducer from './reducers';
import Layout from './components/Layout';

const middleware = process.env.NODE_ENV === 'production' ? applyMiddleware(thunk) : applyMiddleware(logger, thunk);
const store = createStore(reducer, middleware);

/**
 * @class
 * Main component wrapping all components with state and cookie providers
 * */
export default class App extends Component {
  render() {
    return (
      <CookiesProvider>
        <Provider store={store}>
          <Layout />
        </Provider>
      </CookiesProvider>
    );
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<role oid="5cf5b6c8-b968-11e7-b77d-6b029450f900"
      xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
      xmlns:org='http://midpoint.evolveum.com/xml/ns/public/common/org-3'>
    <name>Attorney Manager Workitems</name>
    <description>Power of attorney for subordinate employees. Authorizations limited to workitems.</description>

    <authorization>
        <name>attorney-manager-read-all</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
    </authorization>

    <authorization>
        <name>attorney-manager-workitems</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#attorney</action>
        <object>
            <type>UserType</type>
            <orgRelation>
                <subjectRelation>org:manager</subjectRelation>
                <scope>allDescendants</scope>
                <includeReferenceOrg>true</includeReferenceOrg>
            </orgRelation>
        </object>
        <limitations>
            <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#myWorkItems</action>
        </limitations>
    </authorization>

</role>


text:
import os

from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from django_ffmpeg import defaults as ffmpeg_settings

class DjangoFfmpegConfig(AppConfig):
    name = 'django_ffmpeg'
    verbose_name = _('Videos')

    def ready(self):
        self._make_directories()

    def _make_directories(self):
        dirs = (
            ffmpeg_settings.FFMPEG_ORIG_VIDEO,
            ffmpeg_settings.FFMPEG_THUMB_VIDEO,
            ffmpeg_settings.FFMPEG_CONV_VIDEO,
        )
        for _ in dirs:
            os.makedirs(os.path.join(
                settings.MEDIA_ROOT,
                ffmpeg_settings.FFMPEG_PRE_DIR,
                _
            ), exist_ok =True)


text:
var base = require('./karma.base.js')

module.exports = function (config) {
  var options = Object.assign(base, {
    browsers: ['PhantomJS'],
    reporters: ['mocha', 'coverage'],
    coverageReporter: {
      reporters: [
        { type: 'lcov', dir: '../../coverage', subdir: '.' },
        { type: 'text-summary', dir: '../../coverage', subdir: '.' }
      ]
    },
    singleRun: true
  })

  // add babel-plugin-coverage for code intrumentation
  options.webpack.babel = {
    plugins: [['__coverage__', {
      ignore: [
        '../../test/'
      ]
    }]]
  }

  config.set(options)
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.mac.foundation;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.sun.jna.Pointer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.awt.AWTAccessor;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import static com.intellij.ui.mac.foundation.Foundation.*;

/**
 * @author pegov
 */
public class MacUtil {
  private static final Logger LOG = Logger.getInstance("#com.intellij.ui.mac.foundation.MacUtil");
  public static final String MAC_NATIVE_WINDOW_SHOWING = "MAC_NATIVE_WINDOW_SHOWING";

  private MacUtil() {
  }

  @Nullable
  public static ID findWindowForTitle(@Nullable String title) {
    if (title == null || title.isEmpty()) return null;
    final ID pool = invoke("NSAutoreleasePool", "new");

    ID focusedWindow = null;
    try {
      final ID sharedApplication = invoke("NSApplication", "sharedApplication");
      final ID windows = invoke(sharedApplication, "windows");
      final ID windowEnumerator = invoke(windows, "objectEnumerator");

      while (true) {
        // dirty hack: walks through all the windows to find a cocoa window to show sheet for
        final ID window = invoke(windowEnumerator, "nextObject");
        if (0 == window.intValue()) break;

        final ID windowTitle = invoke(window, "title");
        if (windowTitle != null && windowTitle.intValue() != 0) {
          final String titleString = toStringViaUTF8(windowTitle);
          if (Comparing.equal(titleString, title)) {
            focusedWindow = window;
            break;
          }
        }
      }
    }
    finally {
      invoke(pool, "release");
    }

    return focusedWindow;
  }

  public static synchronized void startModal(JComponent component, String key) {
    try {
      if (SwingUtilities.isEventDispatchThread()) {
        EventQueue theQueue = component.getToolkit().getSystemEventQueue();

        while (component.getClientProperty(key) == Boolean.TRUE) {
          AWTEvent event = theQueue.getNextEvent();
          Object source = event.getSource();
          if (event instanceof ActiveEvent) {
            ((ActiveEvent)event).dispatch();
          }
          else if (source instanceof Component) {
            ((Component)source).dispatchEvent(event);
          }
          else if (source instanceof MenuComponent) {
            ((MenuComponent)source).dispatchEvent(event);
          }
          else {
            LOG.debug("Unable to dispatch: " + event);
          }
        }
      }
      else {
        assert false: "Should be called from Event-Dispatch Thread only!";
        while (component.getClientProperty(key) == Boolean.TRUE) {
          // TODO:
          //wait();
        }
      }
    }
    catch (InterruptedException ignored) {
    }
  }

  public static synchronized void startModal(JComponent component) {
    startModal(component, MAC_NATIVE_WINDOW_SHOWING);
  }

  public static boolean isFullKeyboardAccessEnabled() {
    if (!SystemInfo.isMacOSSnowLeopard) return false;
    final AtomicBoolean result = new AtomicBoolean();
    executeOnMainThread(true, true,
                        () -> result.set(invoke(invoke("NSApplication", "sharedApplication"), "isFullKeyboardAccessEnabled").intValue() == 1));
    return result.get();
  }

  public static void adjustFocusTraversal(@NotNull Disposable disposable) {
    if (!SystemInfo.isMacOSSnowLeopard) return;
    final AWTEventListener listener = new AWTEventListener() {
      @Override
      public void eventDispatched(AWTEvent event) {
        if (event instanceof KeyEvent
            && ((KeyEvent)event).getKeyCode() == KeyEvent.VK_TAB
            && (!(event.getSource() instanceof JTextComponent))
            && (!(event.getSource() instanceof JList))
            && !isFullKeyboardAccessEnabled())
          ((KeyEvent)event).consume();
      }
    };
    Disposer.register(disposable, new Disposable() {
      @Override
      public void dispose() {
        Toolkit.getDefaultToolkit().removeAWTEventListener(listener);
      }
    });
    Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
  }

  public static ID findWindowFromJavaWindow(final Window w) {
    ID windowId = null;
    if (Registry.is("skip.untitled.windows.for.mac.messages")) {
      try {
        Class <?> cWindowPeerClass  = AWTAccessor.getComponentAccessor().getPeer(w).getClass();
        Method getPlatformWindowMethod = cWindowPeerClass.getDeclaredMethod("getPlatformWindow");
        Object cPlatformWindow = getPlatformWindowMethod.invoke(AWTAccessor.getComponentAccessor().getPeer(w));
        Class <?> cPlatformWindowClass = cPlatformWindow.getClass();
        Method getNSWindowPtrMethod = cPlatformWindowClass.getDeclaredMethod("getNSWindowPtr");
        windowId = new ID((Long)getNSWindowPtrMethod.invoke(cPlatformWindow));
      }
      catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        LOG.debug(e);
      }
    }
    else {
      String foremostWindowTitle = getWindowTitle(w);
      windowId = findWindowForTitle(foremostWindowTitle);
    }
    return windowId;
  }

  @Nullable
  public static String getWindowTitle(Window documentRoot) {
    String windowTitle = null;
    if (documentRoot instanceof Frame) {
      windowTitle = ((Frame)documentRoot).getTitle();
    }
    else if (documentRoot instanceof Dialog) {
      windowTitle = ((Dialog)documentRoot).getTitle();
    }
    return windowTitle;
  }

  @SuppressWarnings("unused")
  private static class NSActivityOptions {
    // Used for activities that require the computer to not idle sleep. This is included in NSActivityUserInitiated.
    private static final long idleSystemSleepDisabled = 1L << 20;

    // App is performing a user-requested action.
    private static final long userInitiated = 0x00FFFFFFL | idleSystemSleepDisabled;
    private static final long userInitiatedAllowingIdleSystemSleep = userInitiated & ~idleSystemSleepDisabled;

    // Used for activities that require the highest amount of timer and I/O precision available. Very few applications should need to use this constant.
    private static final long latencyCritical = 0xFF00000000L;
  }

  public interface Activity {
    /**
     * Ends activity, allowing macOS to trigger AppNap (idempotent).
     */
    void matrixHasYou();
  }

  private static final class ActivityImpl extends AtomicReference<ID> implements Activity {
    private static final ID processInfoCls = getObjcClass("NSProcessInfo");
    private static final Pointer processInfoSel = createSelector("processInfo");
    private static final Pointer beginActivityWithOptionsReasonSel = createSelector("beginActivityWithOptions:reason:");
    private static final Pointer endActivitySel = createSelector("endActivity:");
    private static final Pointer retainSel = createSelector("retain");
    private static final Pointer releaseSel = createSelector("release");

    private ActivityImpl(@NotNull Object reason) {
      super(begin(reason));
    }

    @Override
    public void matrixHasYou() { end(getAndSet(null)); }

    private static ID getProcessInfo() { return invoke(processInfoCls, processInfoSel); }

    private static ID begin(@NotNull Object reason) {
      // http://lists.apple.com/archives/java-dev/2014/Feb/msg00053.html
      // https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSProcessInfo_Class/index.html#//apple_ref/c/tdef/NSActivityOptions
      return invoke(invoke(getProcessInfo(), beginActivityWithOptionsReasonSel,
                           NSActivityOptions.userInitiatedAllowingIdleSystemSleep, nsString(reason.toString())),
                    retainSel);
    }

    private static void end(@Nullable ID activityToken) {
      if (activityToken == null) return;
      invoke(getProcessInfo(), endActivitySel, activityToken);
      invoke(activityToken, releaseSel);
    }
  }

  public static Activity wakeUpNeo(@NotNull Object reason) {
    return SystemInfo.isMacOSMavericks && Registry.is("idea.mac.prevent.app.nap") ? new ActivityImpl(reason) : null;
  }

  @NotNull
  public static Color colorFromNative(ID color) {
    final ID colorSpace = invoke("NSColorSpace", "genericRGBColorSpace");
    final ID colorInSpace = invoke(color, "colorUsingColorSpace:", colorSpace);
    final long red = invoke(colorInSpace, "redComponent").longValue();
    final long green = invoke(colorInSpace, "greenComponent").longValue();
    final long blue = invoke(colorInSpace, "blueComponent").longValue();
    final long alpha = invoke(colorInSpace, "alphaComponent").longValue();
    final double realAlpha = alpha != 0 && (int)((alpha >> 52) & 0x7ffL) == 0 ? 1.0 : Double.longBitsToDouble(alpha);
    //noinspection UseJBColor
    return new Color((float)Double.longBitsToDouble(red),
                     (float)Double.longBitsToDouble(green),
                     (float)Double.longBitsToDouble(blue),
                     (float)realAlpha);
  }
}


text:
opa_value *opa_base64_is_valid(opa_value *a);
opa_value *opa_base64_decode(opa_value *a);
opa_value *opa_base64_encode(opa_value *a);
opa_value *opa_base64_url_decode(opa_value *a);
opa_value *opa_base64_url_encode(opa_value *a);
opa_value *opa_json_unmarshal(opa_value *a);
opa_value *opa_json_marshal(opa_value *a);
opa_value *opa_json_is_valid(opa_value *a);

#endif


text:
package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

var (
	BuildVersion = "0.1"
)

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version information",
}

func init() {
	cmd := versionCmd
	rootCommand.AddCommand(cmd)

	cmd.Run = func(cmd *cobra.Command, args []string) {
		fmt.Printf("%s Version %s\n", appName, BuildVersion)
	}
}


text:
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ExpressiveAnnotations.Attributes;
using ExpressiveAnnotations.MvcUnobtrusive.Validators;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ExpressiveAnnotations.MvcUnobtrusive.Tests
{
    [TestClass]
    public class ValidatorsTest
    {
        [TestInitialize]
        public void Setup()
        {
            HttpContext.Current = new HttpContext(
                new HttpRequest(string.Empty, "http://tempuri.org", string.Empty),
                new HttpResponse(new StringWriter())
                );
        }

        [TestMethod]
        public void verify_client_validation_rules()
        {
            var model = new Model();
            var assertAttributes = Enumerable.Range(0, 28).Select(x => new AssertThatAttribute(string.Format("Value > {0}", x))).ToArray();
            var requirAttributes = Enumerable.Range(0, 28).Select(x => new RequiredIfAttribute(string.Format("Value > {0}", x))).ToArray();

            var metadata = GetModelMetadata(model);
            var controllerContext = GetControllerContext();

            try
            {
                for (var i = 0; i < assertAttributes.Length; i++)
                {
                    var attribute = assertAttributes[i];
                    var validator = new AssertThatValidator(metadata, controllerContext, attribute);
                    var rule = validator.GetClientValidationRules().Single();
                    var suffix = i == 0 ? string.Empty : char.ConvertFromUtf32(96 + i);
                    Assert.AreEqual(string.Format("assertthat{0}", suffix), rule.ValidationType);
                }
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
                Assert.AreEqual(
                    "No more than 27 unique attributes of the same type can be applied for a single field or property.",
                    e.Message);
            }

            try
            {
                for (var i = 0; i < requirAttributes.Length; i++)
                {
                    var attribute = requirAttributes[i];
                    var validator = new RequiredIfValidator(metadata, controllerContext, attribute);
                    var rule = validator.GetClientValidationRules().Single();
                    var suffix = i == 0 ? string.Empty : char.ConvertFromUtf32(96 + i);
                    Assert.AreEqual(string.Format("requiredif{0}", suffix), rule.ValidationType);
                }
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException);
                Assert.AreEqual(
                    "No more than 27 unique attributes of the same type can be applied for a single field or property.",
                    e.Message);
            }
        }

        [TestMethod]
        public void client_validation_rules_are_json_formatting_insensitive()
        {
            var settings = JsonConvert.DefaultSettings;
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            var model = new Model {Value = 1, Status = State.High};
            var metadata = GetModelMetadata(model);
            var controllerContext = GetControllerContext();

            var assert = new AssertThatValidator(metadata, controllerContext, new AssertThatAttribute("Value > 0 && Status == ValidatorsTest.State.High"));
            var assertRule = assert.GetClientValidationRules().Single();

            Assert.AreEqual("{\"Value\":\"numeric\",\"Status\":\"numeric\"}", (string)assertRule.ValidationParameters["fieldsmap"], false, CultureInfo.InvariantCulture);
            Assert.AreEqual("{\"ValidatorsTest.State.High\":0}", (string)assertRule.ValidationParameters["constsmap"], false, CultureInfo.InvariantCulture);
            // expression is not a json actually, but tested for the sake of clarity
            Assert.AreEqual("Value > 0 && Status == ValidatorsTest.State.High", (string)assertRule.ValidationParameters["expression"], false, CultureInfo.InvariantCulture);

            var requir = new RequiredIfValidator(metadata, controllerContext, new RequiredIfAttribute("Value > 0 && Status == ValidatorsTest.State.High"));
            var requirRule = requir.GetClientValidationRules().Single();

            Assert.AreEqual("{\"Value\":\"numeric\",\"Status\":\"numeric\"}", (string)requirRule.ValidationParameters["fieldsmap"], false, CultureInfo.InvariantCulture);
            Assert.AreEqual("{\"ValidatorsTest.State.High\":0}", (string)requirRule.ValidationParameters["constsmap"], false, CultureInfo.InvariantCulture);
            Assert.AreEqual("false", (string)requirRule.ValidationParameters["allowempty"], false, CultureInfo.InvariantCulture);
            // expression is not a json actually, but tested for the sake of clarity
            Assert.AreEqual("Value > 0 && Status == ValidatorsTest.State.High", (string)requirRule.ValidationParameters["expression"], false, CultureInfo.InvariantCulture);

            JsonConvert.DefaultSettings = settings; // reset settings to original state
        }

        [TestMethod]
        public void possible_naming_colission_at_client_side_are_detected()
        {
            // A.B.C = 0    {"A":{"B":{"C":0}}}
            // A.D = true   {"A":{"D":true}}
            // can be merged into: {"A":{"B":{"C":0},"D":true}}

            // A.B.C = 0    {"A":{"B":{"C":0}}}
            // A.B = true   {"A":{"B":true}}
            // cannot be merged at 1st level - B object would be overwritten

            string name;
            int level;
            Assert.IsFalse(Helper.SegmentsCollide(new string[0], new string[0], out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new[] {"A"}, new string[0], out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new string[0], new[] {"A"}, out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new[] {"A"}, new[] {"B"}, out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new[] {"A.A"}, new[] {"A.B"}, out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new[] {"A.B.C"}, new[] {"A.B.D"}, out name, out level));
            Assert.IsFalse(Helper.SegmentsCollide(new[] {"A.B.C", "A.B.E"}, new[] {"B.B", "B.C", "B.E"}, out name, out level));

            Assert.AreEqual(null, name);
            Assert.AreEqual(level, -1);

            Assert.IsTrue(Helper.SegmentsCollide(new[] {"A"}, new[] {"A"}, out name, out level));
            Assert.AreEqual("A", name);
            Assert.AreEqual(level, 0);

            Assert.IsTrue(Helper.SegmentsCollide(new[] {"A.B"}, new[] {"A.B"}, out name, out level));
            Assert.AreEqual("B", name);
            Assert.AreEqual(level, 1);

            Assert.IsTrue(Helper.SegmentsCollide(new[] {"A.B.C"}, new[] {"A.B"}, out name, out level));
            Assert.AreEqual("B", name);
            Assert.AreEqual(level, 1);
        }

        [TestMethod]
        public void verify_validators_caching()
        {
            const int testLoops = 10;
            var generatedCode = string.Join(" && ", Enumerable.Repeat(0, 100).Select(x => "true"));

            var model = new Model();
            var metadata = GetModelMetadata(model);
            var controllerContext = GetControllerContext();

            var nonCached = MeasureExecutionTime(() => new AssertThatValidator(metadata, controllerContext, new AssertThatAttribute(generatedCode)));
            for (var i = 0; i < testLoops; i++)
            {
                var cached = MeasureExecutionTime(() => new AssertThatValidator(metadata, controllerContext, new AssertThatAttribute(generatedCode)));
                Assert.IsTrue(nonCached > cached);
            }

            nonCached = MeasureExecutionTime(() => new RequiredIfValidator(metadata, controllerContext, new RequiredIfAttribute(generatedCode)));
            for (var i = 0; i < testLoops; i++)
            {
                var cached = MeasureExecutionTime(() => new RequiredIfValidator(metadata, controllerContext, new RequiredIfAttribute(generatedCode)));
                Assert.IsTrue(nonCached > cached);
            }
        }

        private long MeasureExecutionTime(Action action)
        {
            var stopwatch = Stopwatch.StartNew();
            action();
            stopwatch.Stop();
            return stopwatch.ElapsedTicks;
        }

        private ModelMetadata GetModelMetadata(Model model)
        {
            var metadata = new ModelMetadata(ModelMetadataProviders.Current, model.GetType(), () => model, model.Value.GetType(), "Value");
            return metadata;
        }

        private ControllerContext GetControllerContext()
        {
            var request = new Mock<HttpRequestBase>();
            request.Setup(r => r.HttpMethod).Returns("GET");
            var mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(c => c.Request).Returns(request.Object);
            var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
            return controllerContext;
        }

        public enum State
        {
            High,
            Low
        }

        public class Model
        {
            public int Value { get; set; }
            public State Status { get; set; }
        }
    }
}