text:
body {background: url(../style/all/030d.jpg)  #000 no-repeat;background-size:100% 100%;}
.Panel.Top {background-color: transparent;}
.Panel.Bottom {background-color: transparent;}
.MsgList .MsgItem{background-color: rgba(255, 255, 255, 0.65);}
.MsgList .MsgItem .nickname { color:#e7234f;text-shadow: none;}
.MsgList .MsgItem .msgword { color:#e7234f;text-shadow: none;}
/**/
.lottery-left {background-color:rgba(157,22,28,0.6);}
.lottery-right {background-color:rgba(157,22,28,0.6);}


text:
package com.siriusit.spezg.multilib.domain.jpa;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import com.siriusit.spezg.multilib.domain.BinaryAttachment;
import com.siriusit.spezg.multilib.domain.Unit;

/**
 *
 * @author Tommy Bø <Tommy.Bo@SiriusIT.com>
 */
@Entity
@Table(name = "ATTACHMENT")
@NamedQueries({ @NamedQuery(name = "findAttachmentByUnitAndType", query = "select a from BinaryAttachmentDomainObject a where a.unit.id = :unitId and a.type = :type") })
public class BinaryAttachmentDomainObject implements Serializable, BinaryAttachment {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;
    @ManyToOne(targetEntity = UnitDomainObject.class)
    @JoinColumn(name = "unit_id")
    private Unit unit;
    @Column(name = "title", length = 128)
    private String type;
    @Column(name = "mime_type", length = 128)
    private String mimeType;
    @Lob
    @Column(name = "content")
    private byte[] content;

    @Override
    public byte[] getContent() {
        return content;
    }

    @Override
    public void setContent(byte[] content) {
        this.content = content;
    }

    @Override
    public String getMimeType() {
        return mimeType;
    }

    @Override
    public void setMimeType(String mimeType) {
        this.mimeType = mimeType;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public Unit getUnit() {
        return unit;
    }

    @Override
    public void setUnit(Unit unit) {
        this.unit = unit;
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface LocalyticsProvider ()

- (void) startLocalytics;
- (void) stopLocalytics;

@end

@implementation LocalyticsProvider
#ifdef AR_LOCALYTICS_EXISTS

- (id)initWithIdentifier:(NSString *)identifier {
    NSAssert([LocalyticsSession class], @"Localytics is not included");

    if( ( self = [super init] ) ) {

        [[LocalyticsSession sharedLocalyticsSession] LocalyticsSession:identifier];

        for( NSString *activeEvent in @[ UIApplicationDidBecomeActiveNotification,
                                         UIApplicationWillEnterForegroundNotification ]) {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(startLocalytics)
                                                         name:activeEvent
                                                       object:nil];
        }

        for( NSString *inactiveEvent in @[ UIApplicationWillResignActiveNotification,
                                           UIApplicationWillTerminateNotification,
                                           UIApplicationDidEnterBackgroundNotification ]) {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(stopLocalytics)
                                                         name:inactiveEvent
                                                       object:nil];
        }
    }

    return self;
}

- (void)identifyUserWithID:(NSString *)userID andEmailAddress:(NSString *)email {
    if (userID) {
        [[LocalyticsSession sharedLocalyticsSession] setCustomerId:userID];
    }

    if (email) {
        [[LocalyticsSession sharedLocalyticsSession] setCustomerEmail:email];
    }
}

-(void)setUserProperty:(NSString *)property toValue:(NSString *)value {
    [[LocalyticsSession sharedLocalyticsSession] setValueForIdentifier:property value:value];
}

- (void)event:(NSString *)event withProperties:(NSDictionary *)properties {
    [[LocalyticsSession sharedLocalyticsSession] tagEvent:event attributes:properties];
}

- (void)didShowNewPageView:(NSString *)pageTitle {
    [[LocalyticsSession sharedLocalyticsSession] tagScreen:pageTitle];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Localytics events

- (void)startLocalytics {
    [[LocalyticsSession sharedLocalyticsSession] open];
    [[LocalyticsSession sharedLocalyticsSession] upload];
}

- (void)stopLocalytics {
    [[LocalyticsSession sharedLocalyticsSession] close];
    [[LocalyticsSession sharedLocalyticsSession] upload];
}

#endif
@end


text:
#ifndef _NUTI_NMLMODELLODTREELAYER_H_
#define _NUTI_NMLMODELLODTREELAYER_H_

#include "layers/Layer.h"
#include "components/CancelableTask.h"
#include "components/CancelableThreadPool.h"
#include "datasources/NMLModelLODTreeDataSource.h"
#include "renderers/NMLModelLODTreeRenderer.h"
#include "graphics/ViewState.h"
#include "utils/LRUCache.h"

#include <memory>

namespace Nuti {
    class CullState;

    /**
     * An advanced layer for 3D models that supports automatic Level of Detail (LOD) calculation based on view.
     * Should be used together with corresponding data source.
     */
    class NMLModelLODTreeLayer : public Layer {
    public:
        /**
         * Constructs a NMLModelLODTreeLayer object from a data source.
         * @param dataSource The data source from which this layer loads data.
         */
        NMLModelLODTreeLayer(const std::shared_ptr<NMLModelLODTreeDataSource>& dataSource);
        virtual ~NMLModelLODTreeLayer();

        /**
         * Returns the data source of this layer.
         * @return The data source that was bound to this vector layer on construction.
         */
        std::shared_ptr<NMLModelLODTreeDataSource> getDataSource() const;

        /**
         * Returns memory usage constraints for the layer.
         * @return The memory usage constraints for the layer.
         */
        unsigned int getMaxMemorySize() const;
        /**
         * Set memory usage constraints for the layer. The specified limit is not exact,
         * but should be relatively close to the actual memory usage of the layer.
         * If specific view requires more data than specified limit, then lower LOD levels
         * of the models are used. The default is 40MB.
         * @param size The memory limit in bytes.
         */
        void setMaxMemorySize(unsigned int size);

        /**
         * Returns relative model LOD resolution.
         * @return The relative model LOD resolution.
         */
        float getLODResolutionFactor() const;
        /**
         * Set relative model LOD resolution. Higher values than 1 result in higher details
         * (but slower performance and higher memory usage), while lower values give better
         * performance but lower quality. The default is 1.
         * @param factor The relative LOD resolution factor.
         */
        void setLODResolutionFactor(float factor);

        virtual bool isUpdateInProgress() const;

    protected:
        virtual void offsetLayerHorizontally(double offset) ;

        virtual void onSurfaceCreated(ShaderManager& shaderManager);
        virtual bool onDrawFrame(float deltaSeconds, BillboardSorter& BillboardSorter, LRUTextureCache<std::shared_ptr<Bitmap> >& styleCache, const ViewState& viewState);
        virtual void onSurfaceDestroyed();

        virtual void calculateRayIntersectedElements(const Projection& projection, const MapPos& rayOrig, const MapVec& rayDir, const ViewState& viewState, std::vector<VectorElementClickInfo>& results) const;

        virtual void registerDataSourceListener();
        virtual void unregisterDataSourceListener();

        virtual void loadData(const std::shared_ptr<CullState>& cullState);

    private:
        typedef std::vector<NMLModelLODTreeDataSource::MapTile> MapTileList;
        typedef std::map<long long, std::shared_ptr<NMLModelLODTree> > ModelLODTreeMap;
        typedef LRUCache<long long, std::shared_ptr<NMLModelLODTree> > ModelLODTreeCache;
        typedef std::map<long long, std::shared_ptr<nmlGL::Mesh> > MeshMap;
        typedef LRUCache<long long, std::shared_ptr<nmlGL::Mesh> > MeshCache;
        typedef std::map<long long, std::shared_ptr<nmlGL::Texture> > TextureMap;
        typedef LRUCache<long long, std::shared_ptr<nmlGL::Texture> > TextureCache;
        typedef std::map<long long, std::shared_ptr<NMLModelLODTreeDrawData> > NodeDrawDataMap;

        class FetchingTasks {
        public:
            FetchingTasks() : _fetchingTasks(), _mutex() {}

            int getTaskCount() const {
                std::lock_guard<std::mutex> lock(_mutex);
                return static_cast<int>(_fetchingTasks.size());
            }

            void add(long long taskId) {
                std::lock_guard<std::mutex> lock(_mutex);
                _fetchingTasks.insert(taskId);
            }

            bool exists(long long taskId) {
                std::lock_guard<std::mutex> lock(_mutex);
                return _fetchingTasks.find(taskId) != _fetchingTasks.end();
            }

            void remove(long long taskId) {
                std::lock_guard<std::mutex> lock(_mutex);
                _fetchingTasks.erase(taskId);
            }
        private:
            std::unordered_set<long long> _fetchingTasks;
            mutable std::mutex _mutex;
        };

        class MapTilesFetchTask : public CancelableTask {
        public:
            MapTilesFetchTask(const std::shared_ptr<NMLModelLODTreeLayer>& layer, const std::shared_ptr<CullState>& cullState);
            virtual void run();

        private:
            std::weak_ptr<NMLModelLODTreeLayer> _layer;
            std::shared_ptr<CullState> _cullState;
        };

        class ModelLODTreeFetchTask : public CancelableTask {
        public:
            ModelLODTreeFetchTask(const std::shared_ptr<NMLModelLODTreeLayer>& layer, const NMLModelLODTreeDataSource::MapTile& mapTile);
            virtual void cancel();
            virtual void run();

        private:
            std::weak_ptr<NMLModelLODTreeLayer> _layer;
            NMLModelLODTreeDataSource::MapTile _mapTile;
        };

        class MeshFetchTask : public CancelableTask {
        public:
            MeshFetchTask(const std::shared_ptr<NMLModelLODTreeLayer>& layer, const NMLModelLODTree::MeshBinding& binding);
            virtual void cancel();
            virtual void run();

        private:
            std::weak_ptr<NMLModelLODTreeLayer> _layer;
            NMLModelLODTree::MeshBinding _binding;
        };

        class TextureFetchTask : public CancelableTask {
        public:
            TextureFetchTask(const std::shared_ptr<NMLModelLODTreeLayer>& layer, const NMLModelLODTree::TextureBinding& binding);
            virtual void cancel();
            virtual void run();

        private:
            std::weak_ptr<NMLModelLODTreeLayer> _layer;
            NMLModelLODTree::TextureBinding _binding;
        };

        bool isDataAvailable(const NMLModelLODTree* modelLODTree, int nodeId);
        bool loadModelLODTrees(const MapTileList& mapTileList, bool checkOnly);
        bool loadMeshes(const NMLModelLODTree* modelLODTree, int nodeId, bool checkOnly);
        bool loadTextures(const NMLModelLODTree* modelLODTree, int nodeId, bool checkOnly);
        void updateModelLODTrees(const MapTileList& mapTileList, ModelLODTreeMap& modelLODTreeMap);
        void updateMeshes(const NMLModelLODTree* modelLODTree, int nodeId, std::shared_ptr<nmlGL::Model> glModel, MeshMap& meshMap);
        void updateTextures(const NMLModelLODTree* modelLODTree, int nodeId, std::shared_ptr<nmlGL::Model> glModel, TextureMap& textureMap);
        void updateDrawLists(const ViewState& viewState, MeshMap& meshMap, TextureMap& textureMap, NodeDrawDataMap& nodeDrawDataMap);

        static const int MODELLODTREE_LOADING_PRIORITY_OFFSET = 1;
        static const int MESH_LOADING_PRIORITY_OFFSET = 0;
        static const int TEXTURE_LOADING_PRIORITY_OFFSET = 0;

        unsigned int _maxMemorySize;
        float _LODResolutionFactor;

        MapTileList _mapTileList;
        ViewState _mapTileListViewState;
        ModelLODTreeMap _modelLODTreeMap;
        std::shared_ptr<ModelLODTreeCache> _modelLODTreeCache;
        MeshMap _meshMap;
        std::shared_ptr<MeshCache> _meshCache;
        TextureMap _textureMap;
        std::shared_ptr<TextureCache> _textureCache;
        NodeDrawDataMap _nodeDrawDataMap;

        FetchingTasks _fetchingModelLODTrees;
        FetchingTasks _fetchingMeshes;
        FetchingTasks _fetchingTextures;

        std::shared_ptr<CancelableThreadPool> _fetchThreadPool;

        std::shared_ptr<NMLModelLODTreeDataSource> _dataSource;
        std::shared_ptr<NMLModelLODTreeRenderer> _renderer;
    };

}

#endif


text:
import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLInt,
  GraphQLList,
  GraphQLNonNull
} from 'graphql';

import { ArticleType } from './ArticleType';
import { ArticleInputType, ArticleAttributesInputType } from './ArticleInputType';
import * as ArticleServices from './ArticleServices';

export default new GraphQLObjectType({
  name: 'ArticleMutations',
  description: 'Article API Mutations',
  fields: () => ({
    createArticle: {
      type: ArticleType,
      description: 'Create a new article.',
      args: {
        article: { type: ArticleInputType }
      },
      resolve: (root, { article }) => {
        return ArticleServices.createArticle(article);
      }
    },
    updateArticle: {
      type: ArticleType,
      description: 'Update an article article, and optionally any related articles.',
      args: {
        article: { type: ArticleAttributesInputType }
      },
      resolve: (root, { article }) => {
        return ArticleServices.createOrUpdateArticle(article);
      }
    }
  })
});


text:
package core;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

/**
 * @author Francisco Assis Souza Rodrigues
 */

/**
 * Criar um JPanel em que desenhar e ouvir eventos de teclado e mouse.
 *
 */

public abstract class Canvas extends JPanel implements KeyListener,
        MouseListener {

    private static final long serialVersionUID = 1L;

    // Estados Teclado
    // Aqui estão os estados armazenados por teclas do teclado é precionada ou
    // não.
    private static boolean[] keyboardState = new boolean[525];

    // Mouse
    // Esta os estados de teclas do mouse armazenados - é precionado ou não.
    private static boolean[] mouseState = new boolean[3];

    public Canvas() {
        // Usamos buffer duplo para desenhar na tela.
        this.setDoubleBuffered(true);
        this.setFocusable(true);
        this.setBackground(Color.black);

        // Se você vai desenhar o seu próprio cursor do mouse ou se você só quer
        // que o cursor do mouse disapear, insira "verdadeiro" em se cursor do
        // mouse condição e serão removidos.
        if (false) {
            BufferedImage blankCursorImg = new BufferedImage(16, 16,
                    BufferedImage.TYPE_INT_ARGB);

            Cursor blankCursor = Toolkit.getDefaultToolkit()
                    .createCustomCursor(blankCursorImg, new Point(0, 0), null);

            this.setCursor(blankCursor);
        }

        // Adiciona o ouvinte teclado para JPanel para receber os principais
        // eventos deste componente.
        this.addKeyListener(this);

        // Adiciona o ouvinte mouse para JPanel para receber eventos de mouse a
        // partir deste componente.
        this.addMouseListener(this);
    }

    // Este método é substituído em Framework.java e é usado para desenhar na
    // tela.
    public abstract void Draw(Graphics2D g2d);

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g2d);
        Draw(g2d);
    }

    // Teclado

    /**
     * @param key
     *            Número de chave para o qual você deseja verificar o estado.
     * @return true se a tecla está em baixo, falso se a chave não está em
     *         baixo.
     */
    public static boolean keyboardKeyState(int key) {
        return keyboardState[key];
    }

    // Métodos do ouvinte teclado.
    @Override
    public void keyPressed(KeyEvent e) {
        keyboardState[e.getKeyCode()] = true;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keyboardState[e.getKeyCode()] = false;
        keyReleasedFramework(e);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    public abstract void keyReleasedFramework(KeyEvent e);

    /**
     * Botão do mouse "botão" é preciondao? O parâmetro "botão" pode ser
     * "MouseEvent.BUTTON1" - Indica botão do mouse # 1 ou "MouseEvent.BUTTON2"
     * - Indica botão do mouse # 2 ...
     *
     * @param button
     *            Número de botão do mouse para o qual você deseja verificar o
     *            estado.
     * @return true se o botão está em baixo, falso se o botão não precionadao.
     */
    public static boolean mouseButtonState(int button) {
        return mouseState[button - 1];
    }

    // Define status da tecla mouse.
    private void mouseKeyStatus(MouseEvent e, boolean status) {
        if (e.getButton() == MouseEvent.BUTTON1)
            mouseState[0] = status;

        else if (e.getButton() == MouseEvent.BUTTON2)
            mouseState[1] = status;

        else if (e.getButton() == MouseEvent.BUTTON3)
            mouseState[2] = status;
    }

    // Métodos do ouvinte mouse.
    @Override
    public void mousePressed(MouseEvent e) {
        mouseKeyStatus(e, true);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        mouseKeyStatus(e, false);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;

namespace Kudu.Core.Tracing
{
    public class CascadeTracer : ITracer
    {
        private readonly ITracer _primary;
        private readonly ITracer _secondary;

        public CascadeTracer(ITracer primary, ITracer secondary)
        {
            _primary = primary;
            _secondary = secondary;
        }

        public TraceLevel TraceLevel
        {
            // both should have the same tracelevel
            get { return _primary.TraceLevel; }
        }

        public IDisposable Step(string message, IDictionary<string, string> attributes)
        {
            IDisposable primary = _primary.Step(message, attributes);
            IDisposable secondary = _secondary.Step(message, attributes);

            return new DisposableAction(() =>
            {
                primary.Dispose();
                secondary.Dispose();
            });
        }

        public void Trace(string message, IDictionary<string, string> attributes)
        {
            _primary.Trace(message, attributes);
            _secondary.Trace(message, attributes);
        }
    }
}


text:
ExParameterized
===============

![Elixir CI](https://github.com/KazuCocoa/ex_parameterized/workflows/Elixir%20CI/badge.svg?branch=master)
[![](https://img.shields.io/hexpm/v/ex_parameterized.svg?style=flat)](https://hex.pm/packages/ex_parameterized)

## Description

This library support parameterized test with `test_with_params` macro.

### Support
- `test` macro provided by ExUnit.Case and ExUnit.CaseTemplate
- `Callback` like `setup` provided by ExUnit.Callback

## Demo

Clone this repository and run test with `mix test`.
You can see some example in `test/ex_parameterized_*.exs`

## Usage

Please see module [docs](https://hexdocs.pm/ex_parameterized/ExUnit.Parameterized.html#content).

## Install

First, add Reporter to your mix.exs dependencies:

```elixir
def deps do
  [
    {:ex_parameterized, "~> 1.3.7"}
  ]
end
```

and run `$ mix deps.get`.

## QuickUse

Should set `use ExUnit.Parameterized` in module.

```elixir
defmodule MyExampleTest do
  use ExUnit.Case, async: true
  use ExUnit.Parameterized        # Required

  test_with_params "add params",  # description
    fn (a, b, expected) ->        # test case
      assert a + b == expected
    end do
      [
        {1, 2, 3},                 # parameters
        "description": {1, 4, 5},  # parameters with description
      ]
  end
end
```

## Licence

[MIT](https://github.com/KazuCocoa/ex_parameterized/blob/master/LICENSE)


text:
module Brightbox
  command [:lbs] do |cmd|
    cmd.desc I18n.t("lbs.lock.desc")
    cmd.arg_name "[lbs-id...]"
    cmd.command [:lock] do |c|
      c.action do |_global_options, _options, args|
        raise "You must specify load balancers as arguments" if args.empty?

        balancers = LoadBalancer.find_or_call(args) do |balancer|
          raise "Couldn't find #{balancer}"
        end

        balancers.each do |balancer|
          info "Locking #{balancer}"
          balancer.lock!
        end
      end
    end

    cmd.desc I18n.t("lbs.unlock.desc")
    cmd.arg_name "[lbs-id...]"
    cmd.command [:unlock] do |c|
      c.action do |_global_options, _options, args|
        raise "You must specify load balancers as arguments" if args.empty?

        balancers = LoadBalancer.find_or_call(args) do |balancer|
          raise "Couldn't find #{balancer}"
        end

        balancers.each do |balancer|
          info "Unlocking #{balancer}"
          balancer.unlock!
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menuItemQuiz"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="@string/menuItemQuiz"
        android:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menuItemNewAgent"
        android:icon="@android:drawable/ic_menu_add"
        android:title="@string/menuItemNewAgent"
        android:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menuItemCheckAlphabets"
        android:title="@string/menuItemCheckAlphabets"
        android:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menuItemSettings"
        android:icon="@android:drawable/ic_menu_preferences"
        android:title="@string/menuItemSettings"
        android:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menuItemAbout"
        android:icon="@android:drawable/ic_menu_info_details"
        android:title="@string/menuItemAbout"
        android:showAsAction="ifRoom"/>
</menu>


text:
// InProcPlugHole.h : Declaration of the CInProcPlugHole

#ifndef __INPROCPLUGHOLE_H_
#define __INPROCPLUGHOLE_H_

#undef TRACE
#ifdef _DEBUG
	#define TRACE				::trace
#else
	inline void __cdecl traceX(LPCTSTR, ...)  {}
	#define TRACE				1 ? ((void)0) : ::traceX
#endif

#include "..\DolphinSmalltalk.h"
#include <map>

_COM_SMARTPTR_TYPEDEF(IIPDolphin, __uuidof(IIPDolphin));

/////////////////////////////////////////////////////////////////////////////
// CInProcPlugHole
class ATL_NO_VTABLE CInProcPlugHole :
	public CComObjectRootEx<CComMultiThreadModel>,	// N.B. A free threaded object
	public CComCoClass<CInProcPlugHole, &CLSID_DolphinIPPlugHole>,
	public ISupportErrorInfoImpl<&IID_IIPPlugHole>,
	public IIPPlugHole
{
	HANDLE m_hDolphinThread;

	// The inter-thread marshalled plug-in session object in the image, of which there is
	// only a single instance
	IStream* m_piMarshalledPeer;

	// The id (returned by CoGetCurrentProcess()) of the thread that started the VM
	DWORD	m_dwVMStarterId;

	// Map of unmarshalled peer pointers, one for each thread
	typedef std::map<DWORD, IIPDolphinPtr> PEERMAP;
	PEERMAP m_mapPeers;

	// Win32 event signalled when the peer has been registered by the image
	HANDLE	m_hPeerAvailable;

	wchar_t	achImagePath[_MAX_PATH+1];
	LPVOID	m_pImageData;
	size_t	m_cImageSize;

private:
	void ReleasePeer();
	IIPDolphinPtr GetPeerForCurrentThread();
	void WaitForPeerToStart() const;
	DWORD WaitForPeerToTerminate();
	void UpdateImagePathForCLSID(REFCLSID clsid);
	HRESULT StartVM(CLSCTX ctx);
	HRESULT StartPeer(IIPDolphin** ppiPeer, REFCLSID rclsid, CLSCTX ctx);
	HRESULT GetPeer(IIPDolphin** ppiPeer, REFCLSID rclsid=CLSID_NULL, CLSCTX ctx=CLSCTX_INPROC_SERVER);
	IIPDolphinPtr GetPeerNoWait();

protected:

	HRESULT FinalConstruct();
	void FinalRelease();

public:
	CInProcPlugHole();
	~CInProcPlugHole();

	LPCWSTR GetImagePath() const
	{
		return achImagePath;
	}

//DECLARE_REGISTRY_RESOURCEID(IDR_NPPLUGHOLE)

DECLARE_PROTECT_FINAL_CONSTRUCT()

BEGIN_COM_MAP(CInProcPlugHole)
	COM_INTERFACE_ENTRY(IIPPlugHole)
	COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()

public:
	void SetImageInfo(LPCWSTR szImagePath, LPVOID imageData, size_t imageSize);

	// Handle incoming from Windows/COM - mostly these just forward to the peer object
	HRESULT Initialize(REFCLSID rclsid, CLSCTX ctx);
	HRESULT Shutdown();

	// The calling thread is detaching from the Process, so remove any resources associated with it
	void ThreadDetach();

	HRESULT CanUnloadNow();
	HRESULT GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv);
	HRESULT RegisterServer();
	HRESULT UnregisterServer();

public:

// IIPPlugHole
public:
	STDMETHOD(get_Peer)(/*[out, retval]*/ IUnknown** pVal);
	STDMETHOD(put_Peer)(/*[in]*/ IUnknown* newVal);
};

#endif //__NPPLUGHOLE_H_


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

  <title>Description of writeSDA</title>
  <meta name="keywords" content="writeSDA">
  <meta name="description" content="writeSDA Write archive records">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../m2html.css">

Home >  .. > SMASHtoolbox > programs > SDAbrowser > writeSDA.m

writeSDA

PURPOSE

writeSDA Write archive records

SYNOPSIS

function writeSDA(filename,label,varargin)

DESCRIPTION

 writeSDA Write archive records

 This function writes records to a Sandia Data Archive (SDA) file.
 Individual records can be created from any MATLAB variable using a text
 label.
    writeSDA(filename,label,variable);
    writeSDA(filename,label,variable,description);
    writeSDA(filename,label,variable,description,deflate);
 The optional input "description" assocates a text description (of
 arbitrary length) with the record.  The optional input "deflate" is an
 integer from 0 to 9 that controls the lossless compression level.
 NOTE: SDA records must have a unique label!  Specifying a label already
 present in the archive will generate an error.

 Calling this function with an asterisk:
    writeSDA(filename,'*'); % no compression
    writeSDA(filename,'*',deflate); % specify compression
 writes every variable in the current workspace to the archive file.

 Text and binary files can also be imported into the archive.
    writeSDA(filename,'-import',insertfile);
    writeSDA(filename,'-import',insertfile,description);
    writeSDA(filename,'-import',insertfile,description,deflate);

 See also probeSDA, readSDA, SDAbrowser

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

SOURCE CODE

0001 % writeSDA Write archive records
0002 %
0003 % This function writes records to a Sandia Data Archive (SDA) file.
0004 % Individual records can be created from any MATLAB variable using a text
0005 % label.
0006 %    writeSDA(filename,label,variable);
0007 %    writeSDA(filename,label,variable,description);
0008 %    writeSDA(filename,label,variable,description,deflate);
0009 % The optional input "description" assocates a text description (of
0010 % arbitrary length) with the record.  The optional input "deflate" is an
0011 % integer from 0 to 9 that controls the lossless compression level.
0012 % NOTE: SDA records must have a unique label!  Specifying a label already
0013 % present in the archive will generate an error.
0014 %
0015 % Calling this function with an asterisk:
0016 %    writeSDA(filename,'*'); % no compression
0017 %    writeSDA(filename,'*',deflate); % specify compression
0018 % writes every variable in the current workspace to the archive file.
0019 %
0020 % Text and binary files can also be imported into the archive.
0021 %    writeSDA(filename,'-import',insertfile);
0022 %    writeSDA(filename,'-import',insertfile,description);
0023 %    writeSDA(filename,'-import',insertfile,description,deflate);
0024 %
0025 % See also probeSDA, readSDA, SDAbrowser
0026 %
0027
0028 %
0029 % created February 3, 2017 by Daniel Dolan (Sandia National Laboratories)
0030 %
0031 function writeSDA(filename,label,varargin)
0032
0033 % manage input
0034 assert(nargin >= 2,'ERROR: insufficient input');
0035 try
0036     archive=SMASH.FileAccess.SDAfile(filename);
0037 catch
0038     error('ERROR: invalid archive file');
0039 end
0040
0041 % write requested record(s)
0042 if (nargin==2) && strcmp(label,'*')
0043     if nargin<3
0044         deflate=1;
0045     else
0046         deflate=varargin{1};
0047     end
0048     command=sprintf('SMASH.FileAccess.workspace2sda(''%s'',%d)',...
0049         filename,deflate);
0050     evalin('caller',command);
0051 elseif strcmpi(label,'-import')
0052     source=varargin{1};
0053     assert(exist(source,'file')==2,'ERROR: insertion file not found');
0054     import(archive,source,varargin{:});
0055 else
0056     assert(nargin >= 3,'ERROR: insufficient input');
0057     insert(archive,label,varargin{:});
0058 end
0059
0060 end

<address>Generated on Tue 10-Nov-2020 17:53:50 by m2html © 2005</address>


text:
import multiprocessing
import os

import mmcv
import numpy as np

try:
    from panopticapi.evaluation import OFFSET, VOID, PQStat
    from panopticapi.utils import rgb2id
except ImportError:
    PQStat = None
    rgb2id = None
    VOID = 0
    OFFSET = 256 * 256 * 256

def pq_compute_single_core(proc_id,
                           annotation_set,
                           gt_folder,
                           pred_folder,
                           categories,
                           file_client=None,
                           print_log=False):
    """The single core function to evaluate the metric of Panoptic
    Segmentation.

    Same as the function with the same name in `panopticapi`. Only the function
    to load the images is changed to use the file client.

    Args:
        proc_id (int): The id of the mini process.
        gt_folder (str): The path of the ground truth images.
        pred_folder (str): The path of the prediction images.
        categories (str): The categories of the dataset.
        file_client (object): The file client of the dataset. If None,
            the backend will be set to `disk`.
        print_log (bool): Whether to print the log. Defaults to False.
    """
    if PQStat is None:
        raise RuntimeError(
            'panopticapi is not installed, please install it by: '
            'pip install git+https://github.com/cocodataset/'
            'panopticapi.git.')

    if file_client is None:
        file_client_args = dict(backend='disk')
        file_client = mmcv.FileClient(**file_client_args)

    pq_stat = PQStat()

    idx = 0
    for gt_ann, pred_ann in annotation_set:
        if print_log and idx % 100 == 0:
            print('Core: {}, {} from {} images processed'.format(
                proc_id, idx, len(annotation_set)))
        idx += 1
        # The gt images can be on the local disk or `ceph`, so we use
        # file_client here.
        img_bytes = file_client.get(
            os.path.join(gt_folder, gt_ann['file_name']))
        pan_gt = mmcv.imfrombytes(img_bytes, flag='color', channel_order='rgb')
        pan_gt = rgb2id(pan_gt)

        # The predictions can only be on the local dist now.
        pan_pred = mmcv.imread(
            os.path.join(pred_folder, pred_ann['file_name']),
            flag='color',
            channel_order='rgb')
        pan_pred = rgb2id(pan_pred)

        gt_segms = {el['id']: el for el in gt_ann['segments_info']}
        pred_segms = {el['id']: el for el in pred_ann['segments_info']}

        # predicted segments area calculation + prediction sanity checks
        pred_labels_set = set(el['id'] for el in pred_ann['segments_info'])
        labels, labels_cnt = np.unique(pan_pred, return_counts=True)
        for label, label_cnt in zip(labels, labels_cnt):
            if label not in pred_segms:
                if label == VOID:
                    continue
                raise KeyError(
                    'In the image with ID {} segment with ID {} is '
                    'presented in PNG and not presented in JSON.'.format(
                        gt_ann['image_id'], label))
            pred_segms[label]['area'] = label_cnt
            pred_labels_set.remove(label)
            if pred_segms[label]['category_id'] not in categories:
                raise KeyError(
                    'In the image with ID {} segment with ID {} has '
                    'unknown category_id {}.'.format(
                        gt_ann['image_id'], label,
                        pred_segms[label]['category_id']))
        if len(pred_labels_set) != 0:
            raise KeyError(
                'In the image with ID {} the following segment IDs {} '
                'are presented in JSON and not presented in PNG.'.format(
                    gt_ann['image_id'], list(pred_labels_set)))

        # confusion matrix calculation
        pan_gt_pred = pan_gt.astype(np.uint64) * OFFSET + pan_pred.astype(
            np.uint64)
        gt_pred_map = {}
        labels, labels_cnt = np.unique(pan_gt_pred, return_counts=True)
        for label, intersection in zip(labels, labels_cnt):
            gt_id = label // OFFSET
            pred_id = label % OFFSET
            gt_pred_map[(gt_id, pred_id)] = intersection

        # count all matched pairs
        gt_matched = set()
        pred_matched = set()
        for label_tuple, intersection in gt_pred_map.items():
            gt_label, pred_label = label_tuple
            if gt_label not in gt_segms:
                continue
            if pred_label not in pred_segms:
                continue
            if gt_segms[gt_label]['iscrowd'] == 1:
                continue
            if gt_segms[gt_label]['category_id'] != pred_segms[pred_label][
                    'category_id']:
                continue

            union = pred_segms[pred_label]['area'] + gt_segms[gt_label][
                'area'] - intersection - gt_pred_map.get((VOID, pred_label), 0)
            iou = intersection / union
            if iou > 0.5:
                pq_stat[gt_segms[gt_label]['category_id']].tp += 1
                pq_stat[gt_segms[gt_label]['category_id']].iou += iou
                gt_matched.add(gt_label)
                pred_matched.add(pred_label)

        # count false positives
        crowd_labels_dict = {}
        for gt_label, gt_info in gt_segms.items():
            if gt_label in gt_matched:
                continue
            # crowd segments are ignored
            if gt_info['iscrowd'] == 1:
                crowd_labels_dict[gt_info['category_id']] = gt_label
                continue
            pq_stat[gt_info['category_id']].fn += 1

        # count false positives
        for pred_label, pred_info in pred_segms.items():
            if pred_label in pred_matched:
                continue
            # intersection of the segment with VOID
            intersection = gt_pred_map.get((VOID, pred_label), 0)
            # plus intersection with corresponding CROWD region if it exists
            if pred_info['category_id'] in crowd_labels_dict:
                intersection += gt_pred_map.get(
                    (crowd_labels_dict[pred_info['category_id']], pred_label),
                    0)
            # predicted segment is ignored if more than half of
            # the segment correspond to VOID and CROWD regions
            if intersection / pred_info['area'] > 0.5:
                continue
            pq_stat[pred_info['category_id']].fp += 1

    if print_log:
        print('Core: {}, all {} images processed'.format(
            proc_id, len(annotation_set)))
    return pq_stat

def pq_compute_multi_core(matched_annotations_list,
                          gt_folder,
                          pred_folder,
                          categories,
                          file_client=None,
                          nproc=32):
    """Evaluate the metrics of Panoptic Segmentation with multithreading.

    Same as the function with the same name in `panopticapi`.

    Args:
        matched_annotations_list (list): The matched annotation list. Each
            element is a tuple of annotations of the same image with the
            format (gt_anns, pred_anns).
        gt_folder (str): The path of the ground truth images.
        pred_folder (str): The path of the prediction images.
        categories (str): The categories of the dataset.
        file_client (object): The file client of the dataset. If None,
            the backend will be set to `disk`.
        nproc (int): Number of processes for panoptic quality computing.
            Defaults to 32. When `nproc` exceeds the number of cpu cores,
            the number of cpu cores is used.
    """
    if PQStat is None:
        raise RuntimeError(
            'panopticapi is not installed, please install it by: '
            'pip install git+https://github.com/cocodataset/'
            'panopticapi.git.')

    if file_client is None:
        file_client_args = dict(backend='disk')
        file_client = mmcv.FileClient(**file_client_args)

    cpu_num = min(nproc, multiprocessing.cpu_count())

    annotations_split = np.array_split(matched_annotations_list, cpu_num)
    print('Number of cores: {}, images per core: {}'.format(
        cpu_num, len(annotations_split[0])))
    workers = multiprocessing.Pool(processes=cpu_num)
    processes = []
    for proc_id, annotation_set in enumerate(annotations_split):
        p = workers.apply_async(pq_compute_single_core,
                                (proc_id, annotation_set, gt_folder,
                                 pred_folder, categories, file_client))
        processes.append(p)

    # Close the process pool, otherwise it will lead to memory
    # leaking problems.
    workers.close()
    workers.join()

    pq_stat = PQStat()
    for p in processes:
        pq_stat += p.get()

    return pq_stat


text:
<?php
namespace LolAPI\Service\Summoner\Ver1_4\Masteries\DTO;

class MasteriesDTO
{
    /**
     * Summoner DTOs
     * @var MasteryPagesDTO[]
     */
    private $masteryPagesDTOs;

    /**
     * Summoner.Masteries DTO
     * @param MasteryPagesDTO[] $masteryPagesDTOs
     */
    public function __construct(array $masteryPagesDTOs)
    {
        $this->masteryPagesDTOs = $masteryPagesDTOs;
    }

    /**
     * Returns mastery pages DTOs
     * @return \LolAPI\Service\Summoner\Ver1_4\Masteries\DTO\MasteryPagesDTO[]
     */
    public function getMasteryPagesDTOs()
    {
        return $this->masteryPagesDTOs;
    }
}


text:
"""adopteitor URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from rest_framework.urlpatterns import format_suffix_patterns
import views
from authentication.views import AccountViewSet, LoginView, LogoutView

from django.contrib.auth import get_user_model
User = get_user_model()

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'Animal', views.AnimalViewSet, base_name="Animal")
router.register(r'Persona', views.PersonaViewSet)
router.register(r'FormularioAdopcion', views.FormularioAdopcionViewSet)
router.register(r'AdoptarAnimal', views.AdoptarAnimalViewSet)
router.register(r'accounts', AccountViewSet)
router.register(r'Subscripcion', views.SubscripcionViewSet)
router.register(r'Ipn', views.IpnViewSet)
urlpatterns = [
 url(r'^api/v1/', include(router.urls)),
    url(r'^admin/', include(admin.site.urls)),
   url(r'^', include(router.urls)),
   url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
   url(r'^login/$', LoginView.as_view(), name='login'),
   url(r'^logout/$', LogoutView.as_view(), name='logout'),
]


text:
<?php

namespace Bundle\CommonBundle\Entity\Config;

use Bundle\CommonBundle\Entity\Core\BaseRepository;
use Bundle\CommonBundle\Entity\Config\Config;

/**
 * ConfigRepository
 */
class ConfigRepository extends BaseRepository
{
    /**
     * Получает параметр по его коду, либо создает если не существует
     * @param string $code
     * @param integer||null $default
     * @return \Bundle\CommonBundle\Entity\Config\Config
     */
    public function get($code, $default = null)
    {
        if (! $param = $this->findOneByCode($code)) {
            $param = new Config($code, $default);
        }

        return $param;
    }
}


text:
    <input type='checkbox' id='${id}_chbx'
        data-dojo-attach-point='checkbox' value='${layerId}'>

        ${name}

    <select data-dojo-attach-event='change: onYearChange'
        data-dojo-attach-point='select'>
        <option value='current'>2020</option>
        <option value='historic1'>2019</option>
        <option value='historic2'>2018</option>
        <option value='historic3'>2017</option>
    </select>


text:
'use strict';

const EventTarget = require('event-target-shim');
const RCTNetworking = require('RCTNetworking');

const base64 = require('base64-js');
const invariant = require('fbjs/lib/invariant');
const warning = require('fbjs/lib/warning');

type ResponseType = '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
type Response = ?Object | string;

type XHRInterceptor = {
  requestSent(
    id: number,
    url: string,
    method: string,
    headers: Object
  ): void,
  responseReceived(
    id: number,
    url: string,
    status: number,
    headers: Object
  ): void,
  dataReceived(
    id: number,
    data: string
  ): void,
  loadingFinished(
    id: number,
    encodedDataLength: number
  ): void,
  loadingFailed(
    id: number,
    error: string
  ): void,
};

const UNSENT = 0;
const OPENED = 1;
const HEADERS_RECEIVED = 2;
const LOADING = 3;
const DONE = 4;

const SUPPORTED_RESPONSE_TYPES = {
  arraybuffer: typeof global.ArrayBuffer === 'function',
  blob: typeof global.Blob === 'function',
  document: false,
  json: true,
  text: true,
  '': true,
};

const REQUEST_EVENTS = [
  'abort',
  'error',
  'load',
  'loadstart',
  'progress',
  'timeout',
  'loadend',
];

const XHR_EVENTS = REQUEST_EVENTS.concat('readystatechange');

class XMLHttpRequestEventTarget extends EventTarget(...REQUEST_EVENTS) {
  onload: ?Function;
  onloadstart: ?Function;
  onprogress: ?Function;
  ontimeout: ?Function;
  onerror: ?Function;
  onloadend: ?Function;
}

/**
 * Shared base for platform-specific XMLHttpRequest implementations.
 */
class XMLHttpRequest extends EventTarget(...XHR_EVENTS) {

  static UNSENT: number = UNSENT;
  static OPENED: number = OPENED;
  static HEADERS_RECEIVED: number = HEADERS_RECEIVED;
  static LOADING: number = LOADING;
  static DONE: number = DONE;

  static _interceptor: ?XHRInterceptor = null;

  UNSENT: number = UNSENT;
  OPENED: number = OPENED;
  HEADERS_RECEIVED: number = HEADERS_RECEIVED;
  LOADING: number = LOADING;
  DONE: number = DONE;

  // EventTarget automatically initializes these to `null`.
  onload: ?Function;
  onloadstart: ?Function;
  onprogress: ?Function;
  ontimeout: ?Function;
  onerror: ?Function;
  onloadend: ?Function;
  onreadystatechange: ?Function;

  readyState: number = UNSENT;
  responseHeaders: ?Object;
  status: number = 0;
  timeout: number = 0;
  responseURL: ?string;

  upload: XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();

  _requestId: ?number;
  _subscriptions: [any];

  _aborted: boolean = false;
  _cachedResponse: Response;
  _hasError: boolean = false;
  _headers: Object;
  _lowerCaseResponseHeaders: Object;
  _method: ?string = null;
  _response: string | ?Object;
  _responseType: ResponseType;
  _response: string = '';
  _sent: boolean;
  _url: ?string = null;
  _timedOut: boolean = false;
  _trackingName: string = 'unknown';
  _incrementalEvents: boolean = false;

  static setInterceptor(interceptor: ?XHRInterceptor) {
    XMLHttpRequest._interceptor = interceptor;
  }

  constructor() {
    super();
    this._reset();
  }

  _reset(): void {
    this.readyState = this.UNSENT;
    this.responseHeaders = undefined;
    this.status = 0;
    delete this.responseURL;

    this._requestId = null;

    this._cachedResponse = undefined;
    this._hasError = false;
    this._headers = {};
    this._response = '';
    this._responseType = '';
    this._sent = false;
    this._lowerCaseResponseHeaders = {};

    this._clearSubscriptions();
    this._timedOut = false;
  }

  get responseType(): ResponseType {
    return this._responseType;
  }

  set responseType(responseType: ResponseType): void {
    if (this._sent) {
      throw new Error(
        'Failed to set the \'responseType\' property on \'XMLHttpRequest\': The ' +
        'response type cannot be set after the request has been sent.'
      );
    }
    if (!SUPPORTED_RESPONSE_TYPES.hasOwnProperty(responseType)) {
      warning(
        false,
        `The provided value '${responseType}' is not a valid 'responseType'.`
      );
      return;
    }

    // redboxes early, e.g. for 'arraybuffer' on ios 7
    invariant(
      SUPPORTED_RESPONSE_TYPES[responseType] || responseType === 'document',
      `The provided value '${responseType}' is unsupported in this environment.`
    );
    this._responseType = responseType;
  }

  get responseText(): string {
    if (this._responseType !== '' && this._responseType !== 'text') {
      throw new Error(
        "The 'responseText' property is only available if 'responseType' " +
        `is set to '' or 'text', but it is '${this._responseType}'.`
      );
    }
    if (this.readyState < LOADING) {
      return '';
    }
    return this._response;
  }

  get response(): Response {
    const {responseType} = this;
    if (responseType === '' || responseType === 'text') {
      return this.readyState < LOADING || this._hasError
        ? ''
        : this._response;
    }

    if (this.readyState !== DONE) {
      return null;
    }

    if (this._cachedResponse !== undefined) {
      return this._cachedResponse;
    }

    switch (responseType) {
      case 'document':
        this._cachedResponse = null;
        break;

      case 'arraybuffer':
        this._cachedResponse = base64.toByteArray(this._response).buffer;
        break;

      case 'blob':
        this._cachedResponse = new global.Blob(
          [base64.toByteArray(this._response).buffer],
          {type: this.getResponseHeader('content-type') || ''}
        );
        break;

      case 'json':
        try {
          this._cachedResponse = JSON.parse(this._response);
        } catch (_) {
          this._cachedResponse = null;
        }
        break;

      default:
        this._cachedResponse = null;
    }

    return this._cachedResponse;
  }

  // exposed for testing
  __didCreateRequest(requestId: number): void {
    this._requestId = requestId;

    XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.requestSent(
      requestId,
      this._url || '',
      this._method || 'GET',
      this._headers);
  }

  // exposed for testing
  __didUploadProgress(
    requestId: number,
    progress: number,
    total: number
  ): void {
    if (requestId === this._requestId) {
      this.upload.dispatchEvent({
        type: 'progress',
        lengthComputable: true,
        loaded: progress,
        total,
      });
    }
  }

  __didReceiveResponse(
    requestId: number,
    status: number,
    responseHeaders: ?Object,
    responseURL: ?string
  ): void {
    if (requestId === this._requestId) {
      this.status = status;
      this.setResponseHeaders(responseHeaders);
      this.setReadyState(this.HEADERS_RECEIVED);
      if (responseURL || responseURL === '') {
        this.responseURL = responseURL;
      } else {
        delete this.responseURL;
      }

      XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.responseReceived(
        requestId,
        responseURL || this._url || '',
        status,
        responseHeaders || {});
    }
  }

  __didReceiveData(requestId: number, response: string): void {
    if (requestId !== this._requestId) {
      return;
    }
    this._response = response;
    this._cachedResponse = undefined; // force lazy recomputation
    this.setReadyState(this.LOADING);

    XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.dataReceived(
      requestId,
      response);
  }

  __didReceiveIncrementalData(
    requestId: number,
    responseText: string,
    progress: number,
    total: number
  ) {
    if (requestId !== this._requestId) {
      return;
    }
    if (!this._response) {
      this._response = responseText;
    } else {
      this._response += responseText;
    }

    XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.dataReceived(
      requestId,
      responseText);

    this.setReadyState(this.LOADING);
    this.__didReceiveDataProgress(requestId, progress, total);
  }

  __didReceiveDataProgress(
    requestId: number,
    loaded: number,
    total: number
  ): void {
    if (requestId !== this._requestId) {
      return;
    }
    this.dispatchEvent({
      type: 'progress',
      lengthComputable: total >= 0,
      loaded,
      total,
    });
  }

  // exposed for testing
  __didCompleteResponse(
    requestId: number,
    error: string,
    timeOutError: boolean
  ): void {
    if (requestId === this._requestId) {
      if (error) {
        if (this._responseType === '' || this._responseType === 'text') {
          this._response = error;
        }
        this._hasError = true;
        if (timeOutError) {
          this._timedOut = true;
        }
      }
      this._clearSubscriptions();
      this._requestId = null;
      this.setReadyState(this.DONE);

      if (error) {
        XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.loadingFailed(
          requestId,
          error);
      } else {
        XMLHttpRequest._interceptor && XMLHttpRequest._interceptor.loadingFinished(
          requestId,
          this._response.length);
      }
    }
  }

  _clearSubscriptions(): void {
    (this._subscriptions || []).forEach(sub => {
      sub.remove();
    });
    this._subscriptions = [];
  }

  getAllResponseHeaders(): ?string {
    if (!this.responseHeaders) {
      // according to the spec, return null if no response has been received
      return null;
    }
    var headers = this.responseHeaders || {};
    return Object.keys(headers).map((headerName) => {
      return headerName + ': ' + headers[headerName];
    }).join('\r\n');
  }

  getResponseHeader(header: string): ?string {
    var value = this._lowerCaseResponseHeaders[header.toLowerCase()];
    return value !== undefined ? value : null;
  }

  setRequestHeader(header: string, value: any): void {
    if (this.readyState !== this.OPENED) {
      throw new Error('Request has not been opened');
    }
    this._headers[header.toLowerCase()] = String(value);
  }

  /**
   * Custom extension for tracking origins of request.
   */
  setTrackingName(trackingName: string): XMLHttpRequest {
    this._trackingName = trackingName;
    return this;
  }

  open(method: string, url: string, async: ?boolean): void {
    /* Other optional arguments are not supported yet */
    if (this.readyState !== this.UNSENT) {
      throw new Error('Cannot open, already sending');
    }
    if (async !== undefined && !async) {
      // async is default
      throw new Error('Synchronous http requests are not supported');
    }
    if (!url) {
      throw new Error('Cannot load an empty url');
    }
    this._method = method.toUpperCase();
    this._url = url;
    this._aborted = false;
    this.setReadyState(this.OPENED);
  }

  send(data: any): void {
    if (this.readyState !== this.OPENED) {
      throw new Error('Request has not been opened');
    }
    if (this._sent) {
      throw new Error('Request has already been sent');
    }
    this._sent = true;
    const incrementalEvents = this._incrementalEvents ||
      !!this.onreadystatechange ||
      !!this.onprogress;

    this._subscriptions.push(RCTNetworking.addListener(
      'didSendNetworkData',
      (args) => this.__didUploadProgress(...args)
    ));
    this._subscriptions.push(RCTNetworking.addListener(
      'didReceiveNetworkResponse',
      (args) => this.__didReceiveResponse(...args)
    ));
    this._subscriptions.push(RCTNetworking.addListener(
      'didReceiveNetworkData',
      (args) => this.__didReceiveData(...args)
    ));
    this._subscriptions.push(RCTNetworking.addListener(
      'didReceiveNetworkIncrementalData',
      (args) => this.__didReceiveIncrementalData(...args)
    ));
    this._subscriptions.push(RCTNetworking.addListener(
      'didReceiveNetworkDataProgress',
      (args) => this.__didReceiveDataProgress(...args)
    ));
    this._subscriptions.push(RCTNetworking.addListener(
      'didCompleteNetworkResponse',
      (args) => this.__didCompleteResponse(...args)
    ));

    let nativeResponseType = 'text';
    if (this._responseType === 'arraybuffer' || this._responseType === 'blob') {
      nativeResponseType = 'base64';
    }

    invariant(this._method, 'Request method needs to be defined.');
    invariant(this._url, 'Request URL needs to be defined.');
    RCTNetworking.sendRequest(
      this._method,
      this._trackingName,
      this._url,
      this._headers,
      data,
      nativeResponseType,
      incrementalEvents,
      this.timeout,
      this.__didCreateRequest.bind(this),
    );
  }

  abort(): void {
    this._aborted = true;
    if (this._requestId) {
      RCTNetworking.abortRequest(this._requestId);
    }
    // only call onreadystatechange if there is something to abort,
    // below logic is per spec
    if (!(this.readyState === this.UNSENT ||
        (this.readyState === this.OPENED && !this._sent) ||
        this.readyState === this.DONE)) {
      this._reset();
      this.setReadyState(this.DONE);
    }
    // Reset again after, in case modified in handler
    this._reset();
  }

  setResponseHeaders(responseHeaders: ?Object): void {
    this.responseHeaders = responseHeaders || null;
    var headers = responseHeaders || {};
    this._lowerCaseResponseHeaders =
      Object.keys(headers).reduce((lcaseHeaders, headerName) => {
        lcaseHeaders[headerName.toLowerCase()] = headers[headerName];
        return lcaseHeaders;
      }, {});
  }

  setReadyState(newState: number): void {
    this.readyState = newState;
    this.dispatchEvent({type: 'readystatechange'});
    if (newState === this.DONE) {
      if (this._aborted) {
        this.dispatchEvent({type: 'abort'});
      } else if (this._hasError) {
        if (this._timedOut) {
          this.dispatchEvent({type: 'timeout'});
        } else {
          this.dispatchEvent({type: 'error'});
        }
      } else {
        this.dispatchEvent({type: 'load'});
      }
      this.dispatchEvent({type: 'loadend'});
    }
  }

  /* global EventListener */
  addEventListener(type: string, listener: EventListener): void {
    // If we dont' have a 'readystatechange' event handler, we don't
    // have to send repeated LOADING events with incremental updates
    // to responseText, which will avoid a bunch of native -> JS
    // bridge traffic.
    if (type === 'readystatechange' || type === 'progress') {
      this._incrementalEvents = true;
    }
    super.addEventListener(type, listener);
  }
}

module.exports = XMLHttpRequest;


text:
The JavaScript **arguments object** is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats `...`, both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.

```
codeFor('splats', true)
```


text:
babel src --presets babel-preset-es2015 --out-dir dist/src
babel lib --presets babel-preset-es2015 --out-dir dist/lib


text:
using DragonSpark.Application.Model;

namespace DragonSpark.Presentation.Components.Content.Rendering;

sealed class PreRenderExpiration : SlidingExpiration
{
	public static PreRenderExpiration Default { get; } = new();

	PreRenderExpiration() : base(PreRenderingWindow.Default) {}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace viadf.Models
{
    public class CreateRouteModel
    {
        public List<viadflib.Type> TypeList { get; set; }

        public int? id { get; set; }
        public string routename { get; set; }
        public string email { get; set; }
        public string description { get; set; }
        public int type { get; set; }

        public int? parentId { get; set; }

        public int status { get; set; }

        public string origin { get; set; }
        public string destination { get; set; }
        public string mapdata1 { get; set; }
        public string mapdata2 { get; set; }
        public string mapnames { get; set; }

        public bool Valid { get; set; }

        public string GetMapNameAtPosition(string coords)
        {
            if (NameDictionary.Keys.Contains(coords))
            {
                return NameDictionary[coords];
            }
            else
            {
                return null;
            }
        }

        public Dictionary<string, string> NameDictionary
        {
            get
            {
                var dict = new Dictionary<string, string>();
                if (!string.IsNullOrWhiteSpace(mapnames))
                {
                    var namecoords = mapnames.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var nc in namecoords)
                    {
                        var values = nc.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                        dict[values[0]] = values[1];
                    }
                }
                return dict;
            }
        }

        public string[] Positions1
        {
            get
            {
                if (string.IsNullOrWhiteSpace(mapdata1))
                {
                    return new string[0];
                }
                else
                {
                    return mapdata1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                }
            }
        }

        public string[] Positions2
        {
            get
            {
                if (string.IsNullOrWhiteSpace(mapdata2))
                {
                    return new string[0];
                }
                else
                {
                    return mapdata2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                }
            }
        }
    }

}


text:
package com.xylon.core.catalina.valves;

public class NSQException extends Exception {

	public NSQException(Throwable t) {
		super(t);
	}

	public NSQException(String string) {
		super(string);
	}

}


text:
<?php
	namespace Storage;

	class FileMetadata extends \ORM\BaseModel {

        public $file_id;
        public $key;
        public $value;
		public $tableName = 'storage_file_metadata';
        public $fields = array('file_id','key','value');

		public function __construct($file_id,$key = null) {
			$this->file_id = $file_id;
			if (defined($key)) {
				$this->key = $key;
			}
		}

        /**
         * get by file
         *
         * @param \Storage\File $file
         */
		public function getByFile($file) {
	      if ($file->id) {
		    $getObjectQuery = "SELECT `file_id` FROM `$this->tableName` WHERE `file_id` = ?";
		    print $getObjectQuery;
		    $rs = $this->execute($getObjectQuery, array($file->id));
            if ($rs) {
                list($file_id) = $rs->FetchRow();
                if ($file_id) {
                    $this->file_id = $file_id;
                    return $this->details();
                }
            }
            $this->_error = "ERROR: no records found for this value.";
            return false;
	      }
	      return false;
		}

	}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _03.Non_Digit_Count
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = Console.ReadLine();

            var regex = new Regex("\\D");
            var matches = regex.Matches(text);

            Console.WriteLine($"Non-digits: {matches.Count}");
        }
    }
}


text:
export {selection, select} from 'd3-selection';
export {default as textwrap} from './src/textwrap';


text:
#ifndef DCOOKIES_H
#define DCOOKIES_H

#ifdef CONFIG_PROFILING

#include <linux/dcache.h>
#include <linux/path.h>
#include <linux/types.h>

struct dcookie_user;

/**
 * dcookie_register - register a user of dcookies
 *
 * Register as a dcookie user. Returns %NULL on failure.
 */
struct dcookie_user * dcookie_register(void);

/**
 * dcookie_unregister - unregister a user of dcookies
 *
 * Unregister as a dcookie user. This may invalidate
 * any dcookie values returned from get_dcookie().
 */
void dcookie_unregister(struct dcookie_user * user);

/**
 * get_dcookie - acquire a dcookie
 *
 * Convert the given dentry/vfsmount pair into
 * a cookie value.
 *
 * Returns -EINVAL if no living task has registered as a
 * dcookie user.
 *
 * Returns 0 on success, with *cookie filled in
 */
int get_dcookie(struct path *path, unsigned long *cookie);

#else

static inline struct dcookie_user * dcookie_register(void)
{
	return NULL;
}

static inline void dcookie_unregister(struct dcookie_user * user)
{
	return;
}

static inline int get_dcookie(struct path *path, unsigned long *cookie)
{
	return -ENOSYS;
}

#endif /* CONFIG_PROFILING */

#endif /* DCOOKIES_H */


text:
package org.springframework.boot.jdbc;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Example configuration for configuring a very basic custom {@link DataSource}.
 *
 * @author Stephane Nicoll
 */
public class BasicDataSourceExample {

	/**
	 * A configuration that exposes an empty {@link DataSource}.
	 */
	@Configuration
	static class BasicDataSourceConfiguration {

		// tag::configuration[]
		@Bean
		@ConfigurationProperties("app.datasource")
		public DataSource dataSource() {
			return DataSourceBuilder.create().build();
		}
		// end::configuration[]

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>mytodolist</artifactId>
        <groupId>nl.pc</groupId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <name>My Todo List: the My Todo list ear</name>
    <artifactId>mytodolist-ear</artifactId>
    <packaging>ear</packaging>

    <dependencies>

        <!-- Depend on the ejb module and war so that we can package them -->
        <dependency>
            <groupId>nl.pc</groupId>
            <artifactId>mytodolist-web</artifactId>
            <version>${project.version}</version>
            <type>war</type>
        </dependency>
        <dependency>
            <groupId>nl.pc</groupId>
            <artifactId>mytodolist-service</artifactId>
            <version>${project.version}</version>
            <type>ejb</type>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>${version.ear.plugin}</version>
                <configuration>
                    <!-- Tell Maven we are using Java EE 7 -->
                    <version>7</version>
                    <!-- Use Java EE ear libraries as needed. Java EE ear libraries
                        are in easy way to package any libraries needed in the ear, and automatically
                        have any modules (EJB-JARs and WARs) use them -->
                    <defaultLibBundleDir>lib</defaultLibBundleDir>
                    <fileNameMapping>no-version</fileNameMapping>

                    <modules>
                        <webModule>
                            <groupId>nl.pc</groupId>
                            <artifactId>mytodolist-web</artifactId>
                            <contextRoot>/mytodolist</contextRoot>
                        </webModule>
                    </modules>

                </configuration>
            </plugin>
            <!-- The WildFly plugin deploys your ear to a local WildFly container -->
            <!-- Due to Maven's lack of intelligence with EARs we need to configure
                the wildfly maven plugin to skip deployment for all modules. We then enable
                it specifically in the ear module. -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <configuration>
                    <filename>${project.artifactId}.ear</filename>
                    <skip>false</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
id: 587d78ae367417b2b2512aff
title: Usa la propiedad order para reorganizar los elementos
challengeType: 0
videoUrl: 'https://scrimba.com/p/pVaDAv/cMbvNAG'
forumTopicId: 301116
dashedName: use-the-order-property-to-rearrange-items
---

# --description--

La propiedad `order` se utiliza para indicarle a CSS el orden en que aparecen los elementos flexibles en el contenedor flex. Por defecto, los elementos aparecerán en el mismo orden que vienen en el HTML de origen. La propiedad toma números como valores, y se pueden usar números negativos.

# --instructions--

Agrega la propiedad CSS `order` tanto a `#box-1` como a `#box-2`. Da a `#box-1` un valor de `2` y a `#box-2` un valor de `1`.

# --hints--

El elemento `#box-1` debe tener la propiedad `order` establecida en un valor de `2`.

```js
assert($('#box-1').css('order') == '2');
```

El elemento `#box-2` debe tener la propiedad `order` establecida en un valor de `1`.

```js
assert($('#box-2').css('order') == '1');
```

# --seed--

## --seed-contents--

```html
<style>
  #box-container {
    display: flex;
    height: 500px;
  }
  #box-1 {
    background-color: dodgerblue;

    height: 200px;
    width: 200px;
  }

  #box-2 {
    background-color: orangered;

    height: 200px;
    width: 200px;
  }
</style>

<div id="box-container">
  <div id="box-1"></div>
  <div id="box-2"></div>
</div>
```

# --solutions--

```html
<style>
  #box-container {
    display: flex;
    height: 500px;
  }
  #box-1 {
    background-color: dodgerblue;
    order: 2;
    height: 200px;
    width: 200px;
  }

  #box-2 {
    background-color: orangered;
    order: 1;
    height: 200px;
    width: 200px;
  }
</style>

<div id="box-container">
  <div id="box-1"></div>
  <div id="box-2"></div>
</div>
```


text:
function toolbox_prompt_info() {
  [[ -f /run/.toolboxenv ]] && echo "⬢"
}

alias tb="toolbox enter"


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

<title>utils.xml Class Hierarchy</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package utils.xml

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

utils.xml.XmlHelper

utils.xml.XmlHelperTest

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.lorislab.smonitor.gwt.uc.cell;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

/**
 *
 * @author Andrej Petras
 */
public final class SpanCell extends AbstractCell<String> {

    /**
     * The template.
     */
    private static SpanCell.Template template;

    public SpanCell() {
        if (template == null) {
            template = GWT.create(SpanCell.Template.class);
        }
    }

    @Override
    public void render(Context context, String value, SafeHtmlBuilder sb) {
        sb.append(template.span(value));
    }

    /**
     * The template.
     */
    interface Template extends SafeHtmlTemplates {

        /**
         * The begin.
         */
        @SafeHtmlTemplates.Template("<span class=\"{0}\">")
        SafeHtml span(String styleName);
    }
}


text:
#pragma once
#include "FBCommonHeaders/Types.h"
namespace fb{
	FB_DECLARE_SMART_PTR(VideoTest);
	class VideoTest{
		FB_DECLARE_PIMPL_NON_COPYABLE(VideoTest);
		VideoTest();
		~VideoTest();

	public:
		static VideoTestPtr Create();
	};
}


text:
package org.nognog.freeSquare.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import org.nognog.freeSquare.FreeSquare;

public class DesktopLauncher {
	public static void main (String[] arg) {
		LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
		new LwjglApplication(new FreeSquare(), config);
	}
}


text:
package com.helger.commons.supplementary.test.benchmark;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.string.StringHelper;
import com.helger.commons.timing.StopWatch;

public final class BenchmarkCharContains
{
  @FunctionalInterface
  interface IDoIt
  {
    boolean containsPathSep (String s);
  }

  public static final IDoIt s_a1 = s -> {
    if (s != null)
      for (final char c : s.toCharArray ())
        if (c == '/' || c == '\\')
          return true;
    return false;
  };

  public static final IDoIt s_a2 = s -> s.indexOf ('/') >= 0 || s.indexOf ('\\') >= 0;

  private static final Logger LOGGER = LoggerFactory.getLogger (BenchmarkCharContains.class);

  private BenchmarkCharContains ()
  {}

  public static void main (final String [] args)
  {
    final ICommonsList <String> aStrs = new CommonsArrayList <> ();

    for (int j = 0; j < 100; ++j)
      for (int i = 'a'; i <= 'z'; ++i)
      {
        final char c = (char) i;
        String sc = Character.toString (c);
        aStrs.add (sc);
        aStrs.add (sc + "/" + sc);
        aStrs.add (sc + "\\" + sc);
        sc = StringHelper.getRepeated (c, 100);
        aStrs.add (sc);
        aStrs.add (sc + "/" + sc);
        aStrs.add (sc + "\\" + sc);
      }

    final StopWatch aSW1 = StopWatch.createdStarted ();
    int nSum1 = 0;
    for (final String s : aStrs)
      nSum1 += s_a1.containsPathSep (s) ? 1 : 0;
    aSW1.stop ();
    LOGGER.info ("Version 1 took " + aSW1.getMillis ());

    final StopWatch aSW2 = StopWatch.createdStarted ();
    int nSum2 = 0;
    for (final String s : aStrs)
      nSum2 += s_a2.containsPathSep (s) ? 1 : 0;
    aSW2.stop ();
    LOGGER.info ("Version 2 took " + aSW2.getMillis ());

    if (nSum1 != nSum2)
      throw new IllegalStateException ("Dont match! " + nSum1 + " -- " + nSum2);
  }
}


text:
require 'object_browser_gtk'

class Term
  attr_reader :operator, :left, :right

  def initialize(operator, left, right)
    @operator = operator
    @left = left
    @right = right
  end

  def value
    @value ||= left.value.send(:operator, right.value)
  end

  def to_s
    "(#{left} #{operator} #{right})"
  end
end

term = Term.new(:*, Term.new(:+, 10, 10), Term.new(:-, 10, 8))
ObjectBrowser::UI::Gtk::browse(term)
puts term


text:
require 'test_helper'

module Cards
  class GameTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
class StoresController < ApplicationController

  def index
    @search_term = params[:term]
    @search_location = params[:location]
  end

  def show
    @store = Store.find_by(yelp_id: params[:yelp_id])
    @store_list = StoreList.new
    @store_tag = StoreTag.new
    @comments = @store.comments
  end

  def search
    # using the search term to find the business from yelp
    parameters = { term: params[:term], category_filter: params[:category_filter], limit: 5, location: params[:location] }

    begin
      results = Yelp.client.search(params[:location], parameters)
    rescue
      return render json: []
    end

    stores = results.businesses.map do |business|
      {name: business.name,
       address: business.location.display_address.push(business.location.country_code).join(", "),
       neighborhoods: business.location.neighborhoods,
       phone: business.display_phone,
       description: business.categories.flatten.join(", "),
       longitude: business.location.coordinate.longitude,
       latitude: business.location.coordinate.latitude,
       img_url:"#{business.image_url.slice!(-6..-1)}" + "o.jpg",
       rating_url: business.rating_img_url,
       yelp_id: business.id,
       longitude_delta: results.region.span.longitude_delta,
       latitude_delta: results.region.span.latitude_delta,
       review_count: business.review_count}
    end
    # creating or finding the store by results
    stores.each do |store|
      unless Store.exists?(yelp_id: store[:yelp_id])
        Store.create(store)
      end
    end

    #does not add to list if it is in favorites because it will be already shown
    if logged_in?
      StoreUser.where(user_id: current_user.id).each do |store_user|
        store = Store.find_by(id: store_user.store_id)
        store_in_list = stores.find do |store_in_list|
          store_in_list[:yelp_id] == store.yelp_id
        end
        stores.delete(store_in_list)
      end
    end

    render json: stores
  end

  def favorites
    logged_in? ? render(json: current_user.stores) : render(json: [])
  end

  private
  def store_params
    params.require(:store).permit(:name, :address, :description, :email, :neighborhoods, :phone, :longitude, :latitude, :image_url, :rating_url, :yelp_id, :favorite, :longitude_delta, :latitude_delta, :review_count)
  end

end


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

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>All Classes - Graffiti Touch</title>
      <base target="classFrame">
      <link rel="stylesheet" href="style.css" type="text/css" media="screen">
      <link rel="stylesheet" href="print.css" type="text/css" media="print">
      <link rel="stylesheet" href="override.css" type="text/css">

All Classes

            BackwardLineBrush

            BitmapCacheRenderMode

            Brush

            Conversions

            DiamondBrush

            ForwardLineBrush

            GraffitiCanvas

            HorizontalLineBrush

            IBrush

            IInteractionEventManager

            InteractionInstance

            InteractiveInstanceObjectPool

            RoundBrush

            SquareBrush

            TouchInteractionEventManager

            VerticalLineBrush


text: Android app for record note


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="曹浩之Helloted的技术博客,用于记录一些技术成长过程中的技术分享,包括客户端iOS/Android,后台Pyhon/Java,跨平台开发Flutter">

    <title>热修复=Runtime+Javascriptcore - Helloted Blog</title>

    <link rel="canonical" href="http://www.helloted.com/ios/2017/04/30/hotfix/">

    <link rel="shortcut icon" href="/img/favicon.ico">

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

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

     <link rel="stylesheet" href="/css/clean-blog.css">

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

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Helloted Blog

                    Home

                    Categorys

                    Archive

                    About

                    APP

                    Mac App

热修复=Runtime+Javascriptcore

通过运行时Runtime与Javascriptcore来实现热修复

                    Posted by Ted on April 30, 2017

一、运行时

热修复的基本原理就是Runtime运行时的方法替换,主要是下列几个方法

class_replaceMethod:方法替换

method_exchangeImplementations:IMP交换

实例,当我们要对某个类的old_method方法以new_method方法替换掉,则新建一个Category,在其load类方法(Load方法每次APP加载都会调用)中实现以下:

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(old_method);
        SEL swizzledSelector = @selector(new_method);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));

        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });

二、Javascriptcore

Javascriptcore是一个iOS原生框架,用于javascript与Objecive C语言进行相互调用,而我们热修改需要用到的就是javascript可以调用OC方法

三、热修复

                        ← 上一篇

                        下一篇 →

Copyright © Helloted 2022


text:
using System;
using System.Collections;

namespace Server.Engines.Reports
{
	public class Snapshot : PersistableObject
	{
		#region Type Identification
		public static readonly PersistableType ThisTypeID = new PersistableType( "ss", new ConstructCallback( Construct ) );

		private static PersistableObject Construct()
		{
			return new Snapshot();
		}

		public override PersistableType TypeID{ get{ return ThisTypeID; } }
		#endregion

		private DateTime m_TimeStamp;
		private ObjectCollection m_Children;

		public DateTime TimeStamp{ get{ return m_TimeStamp; } set{ m_TimeStamp = value; } }
		public ObjectCollection Children{ get{ return m_Children; } set{ m_Children = value; } }

		public Snapshot()
		{
			m_Children = new ObjectCollection();
		}

		public override void SerializeAttributes( PersistanceWriter op )
		{
			op.SetDateTime( "t", m_TimeStamp );
		}

		public override void DeserializeAttributes( PersistanceReader ip )
		{
			m_TimeStamp = ip.GetDateTime( "t" );
		}

		public override void SerializeChildren( PersistanceWriter op )
		{
			for ( int i = 0; i < m_Children.Count; ++i )
				m_Children[i].Serialize( op );
		}

		public override void DeserializeChildren( PersistanceReader ip )
		{
			while ( ip.HasChild )
				m_Children.Add( ip.GetChild() );
		}
	}
}


text:
<!--
This file is part of dependency-check-utils.

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.

Copyright (c) 2014 - Jeremy Long. All Rights Reserved.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.owasp</groupId>
        <artifactId>dependency-check-parent</artifactId>
        <version>3.1.2-SNAPSHOT</version>
    </parent>

    <artifactId>dependency-check-utils</artifactId>
    <name>Dependency-Check Utils</name>
    <description>dependency-check-utils is a collection of common utility classes used within dependency-check that might be useful in other projects.</description>
    <properties>
        <findbugs.onlyAnalyze>org.owasp.dependencycheck.utils.*</findbugs.onlyAnalyze>
    </properties>
    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
/* globals fileUploadHandler, Handlebars, fileUpload, modal */
/* exported fileUpload */
import _ from 'underscore';
import s from 'underscore.string';

function readAsDataURL(file, callback) {
	const reader = new FileReader();
	reader.onload = ev => callback(ev.target.result, file);

	return reader.readAsDataURL(file);
}

function getUploadPreview(file, callback) {
	// If greater then 10MB don't try and show a preview
	if (file.file.size > (10 * 1000000)) {
		return callback(file, null);
	} else if (file.file.type == null) {
		callback(file, null);
	} else if ((file.file.type.indexOf('audio') > -1) || (file.file.type.indexOf('video') > -1) || (file.file.type.indexOf('image') > -1)) {
		file.type = file.file.type.split('/')[0];

		return readAsDataURL(file.file, content => callback(file, content));
	} else {
		return callback(file, null);
	}
}

function formatBytes(bytes, decimals) {
	if (bytes === 0) {
		return '0 Bytes';
	}

	const k = 1000;
	const dm = (decimals + 1) || 3;

	const sizes = [
		'Bytes',
		'KB',
		'MB',
		'GB',
		'TB',
		'PB'
	];

	const i = Math.floor(Math.log(bytes) / Math.log(k));

	return `${ parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) } ${ sizes[i] }`;
}

fileUpload = function(filesToUpload) {
	const roomId = Session.get('openedRoom');
	const files = [].concat(filesToUpload);

	function consume() {
		const file = files.pop();
		if ((file == null)) {
			modal.close();
			return;
		}

		if (!RocketChat.fileUploadIsValidContentType(file.file.type)) {
			modal.open({
				title: t('FileUpload_MediaType_NotAccepted'),
				text: file.file.type || `*.${ s.strRightBack(file.file.name, '.') }`,
				type: 'error',
				timer: 3000
			});
			return;
		}

		if (file.file.size === 0) {
			modal.open({
				title: t('FileUpload_File_Empty'),
				type: 'error',
				timer: 1000
			});
			return;
		}

		return getUploadPreview(file, function(file, preview) {
			let text = '';

			if (file.type === 'audio') {
				text = `\

	<audio  style="width: 100%;" controls="controls">
		<source src="${ preview }" type="audio/wav">
		Your browser does not support the audio element.
	</audio>

		<input class="rc-input__element" id='file-name' style='display: inherit;' value='${ Handlebars._escape(file.name) }' placeholder='${ t('Upload_file_name') }'>

		<input class="rc-input__element" id='file-description' style='display: inherit;' value='' placeholder='${ t('Upload_file_description') }'>

`;
			} else if (file.type === 'video') {
				text = `\

	<video  style="width: 100%;" controls="controls">
		<source src="${ preview }" type="video/webm">
		Your browser does not support the video element.
	</video>

		<input class="rc-input__element" id='file-name' style='display: inherit;' value='${ Handlebars._escape(file.name) }' placeholder='${ t('Upload_file_name') }'>

		<input class="rc-input__element" id='file-description' style='display: inherit;' value='' placeholder='${ t('Upload_file_description') }'>

`;
			} else if (file.type === 'image') {
				text = `\

		<input class="rc-input__element" id='file-name' style='display: inherit;' value='${ Handlebars._escape(file.name) }' placeholder='${ t('Upload_file_name') }'>

		<input class="rc-input__element" id='file-description' style='display: inherit;' value='' placeholder='${ t('Upload_file_description') }'>

`;
			} else {
				const fileSize = formatBytes(file.file.size);

				text = `\

${ Handlebars._escape(file.name) } - ${ fileSize }

		<input class="rc-input__element" id='file-name' style='display: inherit;' value='${ Handlebars._escape(file.name) }' placeholder='${ t('Upload_file_name') }'>

		<input class="rc-input__element" id='file-description' style='display: inherit;' value='' placeholder='${ t('Upload_file_description') }'>

`;
			}

			return modal.open({
				title: t('Upload_file_question'),
				text,
				showCancelButton: true,
				closeOnConfirm: false,
				closeOnCancel: false,
				confirmButtonText: t('Send'),
				cancelButtonText: t('Cancel'),
				html: true,
				onRendered: () => $('#file-name').focus()
			}, function(isConfirm) {

				const record = {
					name: document.getElementById('file-name').value || file.name || file.file.name,
					size: file.file.size,
					type: file.file.type,
					rid: roomId,
					description: document.getElementById('file-description').value
				};

				consume();
				if (!isConfirm) {
					return;
				}
				const upload = fileUploadHandler('Uploads', record, file.file);

				let uploading = Session.get('uploading') || [];
				uploading.push({
					id: upload.id,
					name: upload.getFileName(),
					percentage: 0
				});

				Session.set('uploading', uploading);

				upload.onProgress = function(progress) {
					uploading = Session.get('uploading');

					const item = _.findWhere(uploading, {id: upload.id});
					if (item != null) {
						item.percentage = Math.round(progress * 100) || 0;
						return Session.set('uploading', uploading);
					}
				};

				upload.start(function(error, file, storage) {
					if (error) {
						let uploading = Session.get('uploading');
						if (!Array.isArray(uploading)) {
							uploading = [];
						}

						const item = _.findWhere(uploading, { id: upload.id });

						if (_.isObject(item)) {
							item.error = error.message;
							item.percentage = 0;
						} else {
							uploading.push({
								error: error.error,
								percentage: 0
							});
						}

						Session.set('uploading', uploading);
						return;
					}

					if (file) {
						Meteor.call('sendFileMessage', roomId, storage, file, () => {
							Meteor.setTimeout(() => {
								const uploading = Session.get('uploading');
								if (uploading !== null) {
									const item = _.findWhere(uploading, {
										id: upload.id
									});
									return Session.set('uploading', _.without(uploading, item));
								}
							}, 2000);
						});
					}
				});

				Tracker.autorun(function(c) {
					const cancel = Session.get(`uploading-cancel-${ upload.id }`);
					if (cancel) {
						let item;
						upload.stop();
						c.stop();

						uploading = Session.get('uploading');
						if (uploading != null) {
							item = _.findWhere(uploading, {id: upload.id});
							if (item != null) {
								item.percentage = 0;
							}
							Session.set('uploading', uploading);
						}

						return Meteor.setTimeout(function() {
							uploading = Session.get('uploading');
							if (uploading != null) {
								item = _.findWhere(uploading, {id: upload.id});
								return Session.set('uploading', _.without(uploading, item));
							}
						}, 1000);
					}
				});
			});
		});
	}

	consume();
};


text:
import React from "react";
import { ThemeProvider } from "styled-components";
import { storiesOf } from "@storybook/react";

import Checkbox from "./";

import { colors } from "../styles/colors.js";
import { generateFlexedThemeBackground } from "../styles/index.js";

function wrapComponentWithContainerAndTheme(theme, Component) {
  const storyContainerStyle = generateFlexedThemeBackground(
    { theme },
    { height: "30px", paddingLeft: "16px" }
  );
  return (
    <ThemeProvider theme={theme}>

{Component}

    </ThemeProvider>
  );
}

function renderChapterWithTheme(theme) {
  return {
    info: `
      Usage

      ~~~
      import React from 'react';
      import { Checkbox } from 'insidesales-components';
      ~~~
    `,
    chapters: [
      {
        sections: [
          {
            title: "Default",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(theme, <Checkbox />)
          },
          {
            title: "With label",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(
                theme,
                <Checkbox label={"Some Checkbox"} />
              )
          },
          {
            title: "Checked",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(theme, <Checkbox checked />)
          },
          {
            title: "Disabled",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(theme, <Checkbox disabled />)
          },
          {
            title: "Checked Disabled",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(
                theme,
                <Checkbox checked disabled />
              )
          },
          {
            title: "Checked Green Disabled",
            sectionFn: () =>
              wrapComponentWithContainerAndTheme(
                theme,
                <Checkbox checked greenDisabled />
              )
          }
        ]
      }
    ]
  };
}

storiesOf("Form", module)
  .addWithChapters("Default Checkbox", renderChapterWithTheme({}))
  .addWithChapters(
    "Checkbox w/ BlueYellow",
    renderChapterWithTheme(colors.blueYellowTheme)
  );


text:
How to Manage Configuration for Complex Backends
================================================

The recommended way to start configuring your backend is to use the
``config/packages/easy_admin.yaml`` file and put your configuration under the
``easy_admin`` key. However, for medium-sized and large backends this
configuration can be very long and hard to maintain.

Splitting Configuration into Several Files
------------------------------------------

If your application keeps growing, it's better to split the configuration into
different files.

Consider an application which defines the following configuration:

.. code-block:: yaml

    # config/packages/easy_admin.yaml
    easy_admin:
        site_name: '...'
        # ...
        design:
            # ...
        entities:
            Product:
                # ...
            User:
                # ...
            Category:
                # ...
            # ...

This configuration is going to be divided into four different files:

* ``design.yml`` for design related configuration;
* ``product.yml`` for the configuration related to ``Product`` entity;
* ``user.yml`` for the configuration related to ``User`` entity;
* ``basic.yml`` for the rest of the configuration, including any entity
  different from ``Product`` and ``User``.

First, create a new ``config/packages/easy_admin/`` directory to store the new
files so they don't mess with the other Symfony configuration files. Then,
create the four files with these contents:

.. code-block:: yaml

    # config/packages/easy_admin/basic.yml
    easy_admin:
        site_name: '...'
        # ...

    # config/packages/easy_admin/design.yml
    easy_admin:
        design:
            # ...

    # config/packages/easy_admin/product.yml
    easy_admin:
        entities:
            Product:
                # ...

    # config/packages/easy_admin/user.yml
    easy_admin:
        entities:
            User:
                # ...

.. note::

    Beware that each configuration file must define its contents under
    the ``easy_admin`` key. Otherwise, Symfony won't be able to merge
    the different configurations.

Lastly, update the contents of the main ``easy_admin.yaml`` file to import all
these new files:

.. code-block:: yaml

    # config/packages/easy_admin.yaml
    imports:
        - { resource: easy_admin/ }