text:
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

// ReSharper disable InconsistentNaming

namespace Z.Expressions.SqlServer.Eval
{
    public partial struct SQLNET
    {
        /// Eval the code or expression and return an int value.
        /// <returns>The int value from the evaluated code or expression.</returns>
        [SqlMethod(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
        public SqlInt32 EvalReadAccessInt()
        {
            return EvalInt();
        }

        /// Eval the code or expression and return an int value.
        /// <returns>The int value from the evaluated code or expression.</returns>
        [SqlMethod(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
        public SqlInt32 evalreadaccessint()
        {
            return EvalReadAccessInt();
        }

        /// Eval the code or expression and return an int value.
        /// <returns>The int value from the evaluated code or expression.</returns>
        [SqlMethod(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
        public SqlInt32 EVALREADACCESSINT()
        {
            return EvalReadAccessInt();
        }
    }
}


text:
title: AFHARchiver
source: https://github.com/mutualmobile/AFHARchiver
language: objc
license: MIT License
---

An AFNetworking extension to automatically generate HTTP Archive files of all of your network requests!

redpajama_set_name: RedPajamaGithub


text:
const Preloader = /** @constructor */ function () { // eslint-disable-line no-unused-vars
	function getTrackedResponse(response, load_status) {
		function onloadprogress(reader, controller) {
			return reader.read().then(function (result) {
				if (load_status.done) {
					return Promise.resolve();
				}
				if (result.value) {
					controller.enqueue(result.value);
					load_status.loaded += result.value.length;
				}
				if (!result.done) {
					return onloadprogress(reader, controller);
				}
				load_status.done = true;
				return Promise.resolve();
			});
		}
		const reader = response.body.getReader();
		return new Response(new ReadableStream({
			start: function (controller) {
				onloadprogress(reader, controller).then(function () {
					controller.close();
				});
			},
		}), { headers: response.headers });
	}

	function loadFetch(file, tracker, fileSize, raw) {
		tracker[file] = {
			total: fileSize || 0,
			loaded: 0,
			done: false,
		};
		return fetch(file).then(function (response) {
			if (!response.ok) {
				return Promise.reject(new Error(`Failed loading file '${file}'`));
			}
			const tr = getTrackedResponse(response, tracker[file]);
			if (raw) {
				return Promise.resolve(tr);
			}
			return tr.arrayBuffer();
		});
	}

	function retry(func, attempts = 1) {
		function onerror(err) {
			if (attempts <= 1) {
				return Promise.reject(err);
			}
			return new Promise(function (resolve, reject) {
				setTimeout(function () {
					retry(func, attempts - 1).then(resolve).catch(reject);
				}, 1000);
			});
		}
		return func().catch(onerror);
	}

	const DOWNLOAD_ATTEMPTS_MAX = 4;
	const loadingFiles = {};
	const lastProgress = { loaded: 0, total: 0 };
	let progressFunc = null;

	const animateProgress = function () {
		let loaded = 0;
		let total = 0;
		let totalIsValid = true;
		let progressIsFinal = true;

		Object.keys(loadingFiles).forEach(function (file) {
			const stat = loadingFiles[file];
			if (!stat.done) {
				progressIsFinal = false;
			}
			if (!totalIsValid || stat.total === 0) {
				totalIsValid = false;
				total = 0;
			} else {
				total += stat.total;
			}
			loaded += stat.loaded;
		});
		if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
			lastProgress.loaded = loaded;
			lastProgress.total = total;
			if (typeof progressFunc === 'function') {
				progressFunc(loaded, total);
			}
		}
		if (!progressIsFinal) {
			requestAnimationFrame(animateProgress);
		}
	};

	this.animateProgress = animateProgress;

	this.setProgressFunc = function (callback) {
		progressFunc = callback;
	};

	this.loadPromise = function (file, fileSize, raw = false) {
		return retry(loadFetch.bind(null, file, loadingFiles, fileSize, raw), DOWNLOAD_ATTEMPTS_MAX);
	};

	this.preloadedFiles = [];
	this.preload = function (pathOrBuffer, destPath, fileSize) {
		let buffer = null;
		if (typeof pathOrBuffer === 'string') {
			const me = this;
			return this.loadPromise(pathOrBuffer, fileSize).then(function (buf) {
				me.preloadedFiles.push({
					path: destPath || pathOrBuffer,
					buffer: buf,
				});
				return Promise.resolve();
			});
		} else if (pathOrBuffer instanceof ArrayBuffer) {
			buffer = new Uint8Array(pathOrBuffer);
		} else if (ArrayBuffer.isView(pathOrBuffer)) {
			buffer = new Uint8Array(pathOrBuffer.buffer);
		}
		if (buffer) {
			this.preloadedFiles.push({
				path: destPath,
				buffer: pathOrBuffer,
			});
			return Promise.resolve();
		}
		return Promise.reject(new Error('Invalid object for preloading'));
	};
};


text:
package pl.mantis.tests;

import biz.futureware.mantis.rpc.soap.client.MantisConnectLocator;
import biz.futureware.mantis.rpc.soap.client.MantisConnectPortType;
import biz.futureware.mantis.rpc.soap.client.ProjectData;
import org.testng.annotations.Test;

import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

public class SoapTests {

    @Test
    public void testGetProjects() throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = new MantisConnectLocator()
                .getMantisConnectPort(new URL("http://localhost/mantisbt-1.2.19/api/soap/mantisconnect.php"));
        ProjectData[] projects = mc.mc_projects_get_user_accessible("administrator", "root");
        System.out.println(projects.length);
        for (ProjectData project : projects) {
            System.out.println(project.getName());
        }
    }
}


text:
The wallet has been created by starting Bitcoin Core with the options
`-regtest -datadir=/tmp -nowallet -walletdir=$(pwd)/test/functional/data/wallets/`.

In the source code, `WalletFeature::FEATURE_LATEST` has been modified to be large, so that the minversion is too high
for a current build of the wallet.

The wallet has then been created with the RPC `createwallet high_minversion true true`, so that a blank wallet with
private keys disabled is created.


text:
User Management

          <input class="form-control col-md-4" type="text" ng-model="search" placeholder="Search" />

          <button class="btn btn-primary" ui-sref="admin.user">สร้าง</button>

  <pagination boundary-links="true" max-size="8" items-per-page="itemsPerPage" total-items="filterLength" ng-model="currentPage"
    ng-change="pageChanged()"></pagination>


text:
'use strict';

const
	stream = require('stream'),
	util = require('util'),

	debug = require('debug')('lame:decoder'),

	binding = require('./bindings'),

	SAFE_BUFFER_LENGTH = binding.mpg123_safe_buffer();

// one-time initialization calls
binding.mpg123_init();
process.once('exit', binding.mpg123_safe_exit);

function readDecodedData (decoder, done) {
	// read decoded bytes from the Decoder into a buffer
	let decodedBytes = new Buffer(SAFE_BUFFER_LENGTH);

	return binding.mpg123_read(
		decoder.handle,
		decodedBytes,
		decodedBytes.length,
		(readResult, bytesRead, meta) => {
			debug(
				'_transform(): mpg123_read(): result %d, %d bytes read, meta %d',
				readResult,
				bytesRead,
				meta);

			// check to see if ID3 data should be read
			if (decoder.id3) {
				// bitwise operator on meta to determine if ID3 info is available
				if (meta & binding.MPG123_NEW_ID3) {
					debug('_transform(): MPG123_NEW_ID3');
					readID3Info(decoder);
				}
			}

			if (bytesRead > 0) {
				if (decodedBytes.length !== bytesRead) {
					debug(
						'_transform(): mpg123_read(): slicing output buffer from %d to %d',
						decodedBytes.length,
						bytesRead);

					decodedBytes = decodedBytes.slice(0, bytesRead);
				}

				// write decoded bytes to underlying stream
				decoder.push(decodedBytes);
			}

			if (readResult === binding.MPG123_DONE) {
				debug('_transform(): decoding completed');
				return done();
			}

			if (readResult === binding.MPG123_NEED_MORE) {
				debug('_transform(): decoder needs additional data');
				return done();
			}

			if (readResult === binding.MPG123_NEW_FORMAT) {
				let format = binding.mpg123_getformat(decoder.handle);
				debug('_transform(): new format: %o', format);
				decoder.emit('format', format);

				return readDecodedData(decoder, done);
			}

			if (readResult !== binding.MPG123_OK) {
				return done(
					new Error([
						'_transform(): mpg123_read(): failed with code',
						readResult].join(' ')));
			}

			debug('_transform(): mpg123_read(): continuing to read decoded data');
			return readDecodedData(decoder, done);
		});
}

function readID3Info (decoder) {
	return binding.mpg123_id3(decoder.handle, (id3Result, id3Info) => {
		if (id3Result !== binding.MPG123_OK) {
			return decoder.emit(
				new Error(['mpg123_id3() failed ', id3Result].join('')));
		}

		let eventName = ['id3v', id3Info.tag ? 1 : 2].join('');

		return decoder.emit(eventName, id3Info);
	});
}

function Decoder (options) {
	if (!(this instanceof Decoder)) {
		return new Decoder(options);
	}

	// super
	stream.Transform.call(this, options);

	// internal property defining whether or not to read id3 tags
	this.id3 = (options && options.id3) ? options.id3 : false;

	// create new binding instance for decoding
	this.handle = binding.mpg123_new(options ? options.decoder : null);

	if (!Buffer.isBuffer(this.handle)) {
		throw new Error([
			'decoder: unexpected return value: mpg123_new()',
			this.mediaHandle].join(' '));
	}

	let result = binding.mpg123_open_feed(this.handle);

	if (binding.MPG123_OK !== result) {
		throw new Error([
			'decoder: mpg123_open_feed failed',
			result].join(' '));
	}

	debug('created new Decoder instance');
}

Decoder.prototype._transform = function (chunk, encoding, done) {
	debug('_transform(): %d bytes', chunk.length);
	let self = this;

	// feed the source buffer into the Decoder
	return binding.mpg123_feed(this.handle, chunk, chunk.length, (feedResult) => {
		debug('_transform(): mpg123_feed(): return code %d', feedResult);

		if (feedResult !== binding.MPG123_OK) {
			return done(
				new Error(['_transform(): mpg123_feed(): failed', feedResult].join(' ')));
		}

		return readDecodedData(self, done);
	});
};

Decoder.prototype.close = function (callback) {
	debug('close(): called');

	// clean up the decoder
	return binding.mpg123_safe_exit();
};

// Decoder inherits from Transform
util.inherits(Decoder, stream.Transform);

module.exports = Decoder;


text:
<?php

namespace FOS\OAuthServerBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * @author Andras Ratz <ratz.andras86@gmail.com>
 */
class TokenStorageCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('fos_oauth_server.security.authentication.listener');

        if ($container->hasDefinition('security.token_storage') === false) {
            $definition->replaceArgument(0, new Reference('security.context'));
        }
    }
}


text:
layout: post
title: Kitty Keys
type: Inspiration
image: kitty-keys.png
link: http://www.kittykeys.com
authorName: Tim Holman
authorUrl: http://tholman.com
authorGithub: tholman
---

_Sick of the normal sound your keyboard makes as you type? Of course you are. [Kitty Keys](http://www.kittykeys.com) is just for you._

Simply install this extension in Chrome or Firefox and enjoy every day of life like it's your last!

[Kitty Keys](http://www.kittykeys.com) - by [Yvonne Cheng](http://mindeveon.com)


text:
/*
 * rocsmqthread.c
 *
 *  Created on: 05.10.2015
 *      Author: tecdroid
 */

#include "rocsmqthread.h"

t_processdata pdata = {
		1, 0, 0, 0
};

/**
 * add a message to the rocsmq
 */
void rocsmq_add(p_rocsmq_message message) {
	pthread_mutex_lock(&pdata.mutex);

	p_linkedlist listitem;
	listitem = ll_create(message, sizeof(t_rocsmq_message));
	pdata.queue = ll_add(pdata.queue,listitem,LL_BACK, 0);

	pthread_mutex_unlock(&pdata.mutex);
}

/**
 * rocsmq threaed function
 */
void * rocsmq_thread (void *data) {
	t_rocsmq_message message;

	while (pdata.running) {
		if (rocsmq_recv(pdata.sock,&message,0)) {
			rocsmq_add((p_rocsmq_message) &message);
		}
		rocsmq_delayms(50);
	}
	return 0;
}

/**
 * get next message from message queue
 */
void rocsmq_get_message (p_rocsmq_message message) {
	pthread_mutex_lock(&pdata.mutex);

	p_linkedlist listitem;
	pdata.queue = ll_pop(pdata.queue,&listitem,LL_FRONT,0);
	memcpy(message,listitem->data, sizeof(t_rocsmq_message));
	ll_destroy(listitem);

	pthread_mutex_unlock(&pdata.mutex);
}

/**
 * start the rocsmq thread
 */
pthread_t rocsmq_start_thread(int socket) {
	pdata.sock = socket;

	// create mutex
	int res = pthread_mutex_init(&pdata.mutex, NULL);
	if (0 != res) {
	  fprintf(stderr, "Couldn't create mutex: %d", res);
	  return 0;
	}

	// create thread
	pthread_t thread;
	res = pthread_create(&thread, NULL, rocsmq_thread,NULL);
	if (0 != res) {
		fprintf(stderr, "Couldn't create thread: %d", res);
		return 0;
	}

	// activate thread
	rocsmq_thread_set_running(1);

	// return thread
	return thread;
}

/**
 * destroy the rocsmq thread
 */
void rocsmq_destroy_thread(pthread_t thread) {
	void *thread_result = 0;
	rocsmq_thread_set_running(0);
	pthread_join(thread, &thread_result);
	pthread_mutex_destroy(&pdata.mutex);
}

/**
 * has queue more messages?
 */
int rocsmq_has_messages(){
	int x;
	pthread_mutex_lock(&pdata.mutex);
	x = (pdata.queue != 0);
	pthread_mutex_unlock(&pdata.mutex);
	return x;
}

/**
 * @param run
 */
void rocsmq_thread_set_running(int run) {
	pthread_mutex_lock(&pdata.mutex);

	pdata.running = run;

	pthread_mutex_unlock(&pdata.mutex);
}

/**
 * @return running
 */
int rocsmq_thread_is_running() {
	int run;
	pthread_mutex_lock(&pdata.mutex);
	run = pdata.running;
	pthread_mutex_unlock(&pdata.mutex);

	return run;
}


text:
package org.jetbrains.yaml.navigation;

import com.intellij.psi.PsiElement;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorIntegerDescriptor;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLFileBasedIndexUtil;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLSequence;
import org.jetbrains.yaml.psi.YamlRecursivePsiElementVisitor;

import java.util.Map;

public final class YAMLKeysIndex extends FileBasedIndexExtension<String, Integer> {
  @NonNls
  public static final ID<String, Integer> KEY = ID.create("yaml.keys.name");

  @Override
  public int getVersion() {
    return 1;
  }

  @NotNull
  @Override
  public DataIndexer<String, Integer, FileContent> getIndexer() {
    return new DataIndexer<>() {
      @NotNull
      @Override
      public Map<String, Integer> map(@NotNull FileContent inputData) {
        Object2IntMap<String> map = new Object2IntOpenHashMap<>();
        inputData.getPsiFile().accept(new YamlRecursivePsiElementVisitor() {
          @Override
          public void visitKeyValue(@NotNull YAMLKeyValue keyValue) {
            PsiElement key = keyValue.getKey();
            if (key != null) {
              map.put(YAMLUtil.getConfigFullName(keyValue), key.getTextOffset());
            }
            super.visitKeyValue(keyValue);
          }

          @Override
          public void visitSequence(@NotNull YAMLSequence sequence) {
            // Do not visit children
          }
        });
        return map;
      }
    };
  }

  @NotNull
  @Override
  public KeyDescriptor<String> getKeyDescriptor() {
    return EnumeratorStringDescriptor.INSTANCE;
  }

  @NotNull
  @Override
  public DataExternalizer<Integer> getValueExternalizer() {
    return EnumeratorIntegerDescriptor.INSTANCE;
  }

  @NotNull
  @Override
  public ID<String, Integer> getName() {
    return KEY;
  }

  @NotNull
  @Override
  public FileBasedIndex.InputFilter getInputFilter() {
    return YAMLFileBasedIndexUtil.YAML_INPUT_FILTER;
  }

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


text:
We can set a FTP server on GCE instance to transfer files between local and servers.

> Instance run as Linux server can use SCP to transfer files.

### Enable FTP server

1. Go to **[Server Manager]** → **[Add roles and features]**, and then install **FTP Server** as below,

![](assets/001.png)

2. Create a FTP server on IIS with port 21.

![](assets/002.png)

3. Check the Firewall's inbound/outbound rules.

![](assets/003.png)

![](assets/004.png)

4. Create Firewall rule on GCP

```
$ gcloud compute firewall-rules create default-allow-ftp --allow tcp:21 --source-ranges 0.0.0.0/0
$ gcloud compute firewall-rules create default-allow-passive-ftp --allow tcp:49152-65535 --source-ranges 0.0.0.0/0
```

## Options

1.


text:
package org.apache.flink.runtime.blob;

import org.apache.flink.configuration.BlobServerOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.SecurityOptions;
import org.apache.flink.runtime.net.SSLUtilsTest;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.IOException;

/** This class contains unit tests for the {@link BlobClient} with ssl enabled. */
public class BlobClientSslTest extends BlobClientTest {

    /** The instance of the SSL BLOB server used during the tests. */
    private static TestBlobServer blobSslServer;

    /** Instance of a non-SSL BLOB server with SSL-enabled security options. */
    private static BlobServer blobNonSslServer;

    /** The SSL blob service client configuration. */
    private static Configuration sslClientConfig;

    /** The non-SSL blob service client configuration with SSL-enabled security options. */
    private static Configuration nonSslClientConfig;

    @ClassRule public static TemporaryFolder temporarySslFolder = new TemporaryFolder();

    /** Starts the SSL enabled BLOB server. */
    @BeforeClass
    public static void startSSLServer() throws IOException {
        Configuration config =
                SSLUtilsTest.createInternalSslConfigWithKeyAndTrustStores(
                        SecurityOptions.SSL_PROVIDER.defaultValue());
        config.setString(
                BlobServerOptions.STORAGE_DIRECTORY,
                temporarySslFolder.newFolder().getAbsolutePath());

        blobSslServer = new TestBlobServer(config, new VoidBlobStore());
        blobSslServer.start();

        sslClientConfig = config;
    }

    @BeforeClass
    public static void startNonSSLServer() throws IOException {
        Configuration config =
                SSLUtilsTest.createInternalSslConfigWithKeyAndTrustStores(
                        SecurityOptions.SSL_PROVIDER.defaultValue());
        config.setString(
                BlobServerOptions.STORAGE_DIRECTORY,
                temporarySslFolder.newFolder().getAbsolutePath());
        config.setBoolean(BlobServerOptions.SSL_ENABLED, false);

        blobNonSslServer = new BlobServer(config, new VoidBlobStore());
        blobNonSslServer.start();

        nonSslClientConfig = config;
    }

    /** Shuts the BLOB server down. */
    @AfterClass
    public static void stopServers() throws IOException {
        if (blobSslServer != null) {
            blobSslServer.close();
        }
        if (blobNonSslServer != null) {
            blobNonSslServer.close();
        }
    }

    @Override
    protected boolean isSSLEnabled() {
        return true;
    }

    protected Configuration getBlobClientConfig() {
        return sslClientConfig;
    }

    protected TestBlobServer getBlobServer() {
        return blobSslServer;
    }

    /** Verify ssl client to ssl server upload. */
    @Test
    public void testUploadJarFilesHelper() throws Exception {
        uploadJarFile(blobSslServer, sslClientConfig);
    }

    /** Verify ssl client to non-ssl server failure. */
    @Test(expected = IOException.class)
    public void testSSLClientFailure() throws Exception {
        // SSL client connected to non-ssl server
        uploadJarFile(blobServer, sslClientConfig);
    }

    /** Verify ssl client to non-ssl server failure. */
    @Test(expected = IOException.class)
    public void testSSLClientFailure2() throws Exception {
        // SSL client connected to non-ssl server
        uploadJarFile(blobNonSslServer, sslClientConfig);
    }

    /** Verify non-ssl client to ssl server failure. */
    @Test(expected = IOException.class)
    public void testSSLServerFailure() throws Exception {
        // Non-SSL client connected to ssl server
        uploadJarFile(blobSslServer, clientConfig);
    }

    /** Verify non-ssl client to ssl server failure. */
    @Test(expected = IOException.class)
    public void testSSLServerFailure2() throws Exception {
        // Non-SSL client connected to ssl server
        uploadJarFile(blobSslServer, nonSslClientConfig);
    }

    /** Verify non-ssl connection sanity. */
    @Test
    public void testNonSSLConnection() throws Exception {
        uploadJarFile(blobServer, clientConfig);
    }

    /** Verify non-ssl connection sanity. */
    @Test
    public void testNonSSLConnection2() throws Exception {
        uploadJarFile(blobServer, nonSslClientConfig);
    }

    /** Verify non-ssl connection sanity. */
    @Test
    public void testNonSSLConnection3() throws Exception {
        uploadJarFile(blobNonSslServer, clientConfig);
    }

    /** Verify non-ssl connection sanity. */
    @Test
    public void testNonSSLConnection4() throws Exception {
        uploadJarFile(blobNonSslServer, nonSslClientConfig);
    }
}


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='_messages.proto',
  package='gateway',
  serialized_pb=_b('\n\x0f_messages.proto\x12\x07gateway\"\x8a\x01\n\x13LoginRequestMessage\x12?\n\x0chandlingType\x18\x01 \x02(\x0e\x32).gateway.LoginRequestMessage.HandlingType\x12\x0f\n\x07steamId\x18\x02 \x01(\x03\"!\n\x0cHandlingType\x12\x11\n\rWITH_STEAM_ID\x10\x00\"?\n\x14LoginResponseMessage\x12\'\n\nstatusCode\x18\x01 \x02(\x0e\x32\x13.gateway.StatusCode*2\n\tMessageId\x12\x11\n\rLOGIN_REQUEST\x10\x01\x12\x12\n\x0eLOGIN_RESPONSE\x10\x02*K\n\nStatusCode\x12\x0b\n\x07SUCCESS\x10\x00\x12\x15\n\x11\x41LREADY_LOGGED_IN\x10\x01\x12\x19\n\x15INVALID_LOGIN_REQUEST\x10\x02')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_MESSAGEID = _descriptor.EnumDescriptor(
  name='MessageId',
  full_name='gateway.MessageId',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='LOGIN_REQUEST', index=0, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='LOGIN_RESPONSE', index=1, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=234,
  serialized_end=284,
)
_sym_db.RegisterEnumDescriptor(_MESSAGEID)

MessageId = enum_type_wrapper.EnumTypeWrapper(_MESSAGEID)
_STATUSCODE = _descriptor.EnumDescriptor(
  name='StatusCode',
  full_name='gateway.StatusCode',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='SUCCESS', index=0, number=0,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='ALREADY_LOGGED_IN', index=1, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='INVALID_LOGIN_REQUEST', index=2, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=286,
  serialized_end=361,
)
_sym_db.RegisterEnumDescriptor(_STATUSCODE)

StatusCode = enum_type_wrapper.EnumTypeWrapper(_STATUSCODE)
LOGIN_REQUEST = 1
LOGIN_RESPONSE = 2
SUCCESS = 0
ALREADY_LOGGED_IN = 1
INVALID_LOGIN_REQUEST = 2

_LOGINREQUESTMESSAGE_HANDLINGTYPE = _descriptor.EnumDescriptor(
  name='HandlingType',
  full_name='gateway.LoginRequestMessage.HandlingType',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='WITH_STEAM_ID', index=0, number=0,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=134,
  serialized_end=167,
)
_sym_db.RegisterEnumDescriptor(_LOGINREQUESTMESSAGE_HANDLINGTYPE)

_LOGINREQUESTMESSAGE = _descriptor.Descriptor(
  name='LoginRequestMessage',
  full_name='gateway.LoginRequestMessage',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='handlingType', full_name='gateway.LoginRequestMessage.handlingType', index=0,
      number=1, type=14, cpp_type=8, label=2,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='steamId', full_name='gateway.LoginRequestMessage.steamId', index=1,
      number=2, type=3, cpp_type=2, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
    _LOGINREQUESTMESSAGE_HANDLINGTYPE,
  ],
  options=None,
  is_extendable=False,
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=29,
  serialized_end=167,
)

_LOGINRESPONSEMESSAGE = _descriptor.Descriptor(
  name='LoginResponseMessage',
  full_name='gateway.LoginResponseMessage',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='statusCode', full_name='gateway.LoginResponseMessage.statusCode', index=0,
      number=1, type=14, cpp_type=8, label=2,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=169,
  serialized_end=232,
)

_LOGINREQUESTMESSAGE.fields_by_name['handlingType'].enum_type = _LOGINREQUESTMESSAGE_HANDLINGTYPE
_LOGINREQUESTMESSAGE_HANDLINGTYPE.containing_type = _LOGINREQUESTMESSAGE
_LOGINRESPONSEMESSAGE.fields_by_name['statusCode'].enum_type = _STATUSCODE
DESCRIPTOR.message_types_by_name['LoginRequestMessage'] = _LOGINREQUESTMESSAGE
DESCRIPTOR.message_types_by_name['LoginResponseMessage'] = _LOGINRESPONSEMESSAGE
DESCRIPTOR.enum_types_by_name['MessageId'] = _MESSAGEID
DESCRIPTOR.enum_types_by_name['StatusCode'] = _STATUSCODE

LoginRequestMessage = _reflection.GeneratedProtocolMessageType('LoginRequestMessage', (_message.Message,), dict(
  DESCRIPTOR = _LOGINREQUESTMESSAGE,
  __module__ = '_messages_pb2'
  # @@protoc_insertion_point(class_scope:gateway.LoginRequestMessage)
  ))
_sym_db.RegisterMessage(LoginRequestMessage)

LoginResponseMessage = _reflection.GeneratedProtocolMessageType('LoginResponseMessage', (_message.Message,), dict(
  DESCRIPTOR = _LOGINRESPONSEMESSAGE,
  __module__ = '_messages_pb2'
  # @@protoc_insertion_point(class_scope:gateway.LoginResponseMessage)
  ))
_sym_db.RegisterMessage(LoginResponseMessage)

# @@protoc_insertion_point(module_scope)


text:
module Ezid
  #
  # An EZID session
  #
  # @api private
  #
  class Session

    attr_reader :cookie

    def initialize(cookie=nil)
      open(cookie) if cookie
    end

    def inspect
      super.sub(/@cookie="[^\"]+"/, "OPEN")
    end

    def open(cookie)
      @cookie = cookie
    end

    def close
      @cookie = nil
    end

    def closed?
      cookie.nil?
    end

    def open?
      !closed?
    end

  end
end


text:
module DropboxApi::Endpoints::Files
  class CreateFolderBatchCheck < DropboxApi::Endpoints::Rpc
    Method      = :post
    Path        = '/2/files/create_folder_batch/check'
    ResultType  = DropboxApi::Results::CreateFolderBatchResult
    ErrorType   = DropboxApi::Errors::PollError

    # Returns the status of an asynchronous job for create_folder_batch.
    # If success, it returns list of result for each entry.
    #
    # @param async_job_id [String] Id of the asynchronous job.
    #   This is the value of a response returned from the method that launched
    #   the job.
    # @return [Array] A list of one result for each entry.
    add_endpoint :create_folder_batch_check do |async_job_id|
      perform_request({
        async_job_id: async_job_id
      })
    end
  end
end


text:
(function() {

  // fallback for util methods.
  var util = (typeof module !== 'undefined') ? require('util') : (function() {

    var to = Object.prototype.toString;

    function isArray(value) {
      return (
          typeof value === 'object' &&
          to.call(value) === '[object Array]');
    }

    function isDate(value) {
      return (
          typeof value === 'object' &&
          to.call(value) === '[object Date]');
    }

    function isRegExp(value) {
      return (
          typeof value === 'object' &&
          to.call(value) === '[object RegExp]');
    }

    return {
      // use Array.isArray if implemented.
      isArray: Array.isArray || isArray,
      isDate: isDate,
      isRegExp: isRegExp
    };

  }());

  // fallback for Object.keys.
  var getKeys = Object.keys || function(object) {
    var keys = [],
        key;

    if (object === null || typeof object !== 'object') {
      throw new TypeError('parameter type is not an Object');
    }

    for (key in object) {
      object.hasOwnProperty(key) && keys.push(key);
    }

    return keys;
  };

  /**
   * get element index from array.
   *
   * @private
   * @param {Array} array target array.
   * @param {*} searchElement find element.
   * @throws {TypeError} when parameter array is not an array.
   * @return {Number} return index of array. return -1 if element not found.
   */
  function indexOfArray(array, searchElement) {
    var i, len;

    if (!util.isArray(array)) {
      throw new TypeError('parameter type is not an Array');
    }

    for (i = 0, len = array.length; i < len; ++i) {
      if (array[i] === searchElement) {
        return i;
      }
    }

    return -1;
  }

  /**
   * get deep copy of target.
   *
   * return deep copy if target is Date, RegExp or primitive types.
   * return shallow copy if target is function.
   *
   * do recursive copy if target is Array or Object.
   * also can copy if target has circular reference.
   *
   * @param {*} target target of deep copy.
   * @return {*} deep copy value.
   */
  function deepcopy(target) {
    var clone = (util.isArray(target)) ? [] : {},
        visited = [target],
        ref = [clone];

    /**
     * get deep copy of target.
     *
     * @private
     * @param {*} target target of deep copy.
     * @param {Object|Array} clone reference of deep copy value.
     * @param {Object[]} visited copied references.
     * @param {Object[]} ref reference of own.
     * @return {*} deep copy value.
     */
    function deepcopy_(target, clone, visited, ref) {
      var keys, i, len, key, value, index, object, reference;

      // number, string, boolean, null, undefined and function.
      if (target === null || typeof target !== 'object') {
        return target;
      }

      if (util.isDate(target)) {
        return new Date(Number(target));
      }

      if (util.isRegExp(target)) {
        return new RegExp(
            target.source,
            String(target).slice(target.source.length + 2));
      }

      keys = getKeys(target);

      for (i = 0, len = keys.length; i < len; ++i) {
        key = keys[i];
        value = target[key];

        if (value !== null && typeof value === 'object') {
          index = indexOfArray(visited, value);
          if (index === -1) {
            object = (util.isArray(value)) ? [] : {};
            visited.push(value);
            ref.push(object);
          } else {
            reference = ref[index];
          }
        }

        // value is not reference type if object is undefined.
        // not used object variable if target is not reference type.
        clone[key] = reference || deepcopy_(value, object, visited, ref);
        index = object = reference = null;
      }

      return clone;
    }

    return deepcopy_(target, clone, visited, ref);
  }

  // export function.
  if (typeof module !== 'undefined') {
    module.exports = deepcopy;
  } else {
    this.deepcopy = deepcopy;
  }

}());


text:
from django.core.urlresolvers import reverse
from django.contrib.syndication.views import Feed
from django.contrib.sites.models import Site
from django.utils.feedgenerator import Rss201rev2Feed
from django.utils.http import urlquote
from django.shortcuts import get_object_or_404
from django.contrib.markup.templatetags.markup import markdown
from django.utils.translation import ugettext_lazy as _
from django.contrib.markup.templatetags.markup import markdown

from tagging.models import Tag

from gallery.models import Album, Image

class MediaRSSFeed(Rss201rev2Feed):
    """Basic implementation of Yahoo Media RSS (mrss)
    http://video.search.yahoo.com/mrss

    Includes these elements in the Item feed:
    media:content
        url, width, height
    media:thumbnail
        url, width, height
    media:description
    media:title
    media:keywords
    """
    def rss_attributes(self):
        attrs = super(MediaRSSFeed, self).rss_attributes()
        attrs['xmlns:media'] = 'http://search.yahoo.com/mrss/'
        attrs['xmlns:atom'] = 'http://www.w3.org/2005/Atom'
        return attrs

    def add_item_elements(self, handler, item):
        """Callback to add elements to each item (item/entry) element."""
        super(MediaRSSFeed, self).add_item_elements(handler, item)

        if 'media:title' in item:
            handler.addQuickElement(u"media:title", item['title'])
        if 'media:description' in item:
            handler.addQuickElement(u"media:description", item['description'])

        if 'content_url' in item:
            content = dict(url=item['content_url'])
            if 'content_width' in item:
                content['width'] = str(item['content_width'])
            if 'content_height' in item:
                content['height'] = str(item['content_height'])
            handler.addQuickElement(u"media:content", '', content)

        if 'thumbnail_url' in item:
            thumbnail = dict(url=item['thumbnail_url'])
            if 'thumbnail_width' in item:
                thumbnail['width'] = str(item['thumbnail_width'])
            if 'thumbnail_height' in item:
                thumbnail['height'] = str(item['thumbnail_height'])
            handler.addQuickElement(u"media:thumbnail", '', thumbnail)

        if 'keywords' in item:
            handler.addQuickElement(u"media:keywords", item['keywords'])

class GalleryFeed(Feed):
    feed_type = MediaRSSFeed
    item_limit = 20

    def title(self):
        return _("Gallery feed")

    def link(self):
        return reverse('gallery', kwargs={"path" : "" })

    def items(self):
        return Image.objects.filter(is_public=True).order_by("-date_added")[0:20]

    def item_pubdate(self, obj):
        return obj.date_added

    def item_extra_kwargs(self, obj):
        root = "http://" + Site.objects.get_current().domain

        item = {'media:title': obj.title,
                'media:description': obj.text,
                'content_url': root + obj.display_image.url,
                'content_width': obj.display_image.width,
                'content_height': obj.display_image.height,
                'thumbnail_url': root + obj.thumbnail_image.url,
                'thumbnail_width': obj.thumbnail_image.width,
                'thumbnail_height': obj.thumbnail_image.height,
               }

#        if len(obj.tags) > 0:
#           keywords = [tag.name for tag in Tag.objects.get_for_object(obj)]
#           item['keywords'] = keywords

        return item

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return markdown(item.text)

    def item_categories(self, item):
      return [tag.name for tag in Tag.objects.get_for_object(item)]

    def item_guid(self, item):
      return "gallery_item_%d" % item.id

class AlbumFeed(Feed):
    feed_type = MediaRSSFeed
    item_limit = 20

    def get_object(self, request, album_id):
        return get_object_or_404(Album, pk=album_id)

    def title(self, album):
        return album.title

    def description(self, album):
        return album.text

    def link(self, album):
        return reverse('gallery', kwargs={"path" : album.slug() })

    def items(self, album):
        q = album.get_descendants(include_self=True).filter(is_public=True).values("id")
        return Image.objects.filter(album__in=q, is_public=True).order_by("-date_added")[0:20]

    def item_title(self, item):
      return item.title

    def item_description(self, item):
      return markdown(item.text)

    def item_pubdate(self, obj):
        return obj.date_added

    def item_extra_kwargs(self, obj):
        root = "http://" + Site.objects.get_current().domain

        item = {'media:title': obj.title,
                'media:description': obj.text,
                'content_url': root + obj.display_image.url,
                'content_width': obj.display_image.width,
                'content_height': obj.display_image.height,
                'thumbnail_url': root + obj.thumbnail_image.url,
                'thumbnail_width': obj.thumbnail_image.width,
                'thumbnail_height': obj.thumbnail_image.height,
               }

#        if len(obj.tags) > 0:
#           keywords = [tag.name for tag in Tag.objects.get_for_object(obj)]
#           item['keywords'] = keywords

        return item

    def item_categories(self, item):
      return [tag.name for tag in Tag.objects.get_for_object(item)]

    def item_guid(self, item):
      return "gallery_item_%d" % item.id


text:
#include "third_party/blink/renderer/core/loader/image_loader.h"

#include <memory>
#include <utility>

#include "services/network/public/mojom/web_client_hints_types.mojom-blink.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_name.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/increment_load_event_delay_count.h"
#include "third_party/blink/renderer/core/frame/frame_owner.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/cross_origin_attribute.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/loading_attribute.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/layout/layout_video.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_image.h"
#include "third_party/blink/renderer/core/loader/importance_attribute.h"
#include "third_party/blink/renderer/core/loader/lazy_image_helper.h"
#include "third_party/blink/renderer/core/loader/subresource_redirect_util.h"
#include "third_party/blink/renderer/core/probe/async_task_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loading_log.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"

namespace blink {

namespace {

bool CheckForUnoptimizedImagePolicy(ExecutionContext* context,
                                    ImageResourceContent* new_image) {
  if (!context || !new_image)
    return false;

  // Render the image as a placeholder image if the image is not sufficiently
  // well-compressed, according to the unoptimized image policies on
  // |document|.
  if (RuntimeEnabledFeatures::ExperimentalPoliciesEnabled() &&
      !new_image->IsAcceptableCompressionRatio(*context)) {
    return true;
  }

  return false;
}

// This implements the HTML Standard's list of available images tuple-matching
// logic [1]. In our implementation, it is only used to determine whether or not
// we should skip queueing the microtask that continues the rest of the image
// loading algorithm. But the actual decision to reuse the image is determined
// by ResourceFetcher, and is much stricter.
// [1]:
// https://html.spec.whatwg.org/multipage/images.html#updating-the-image-data:list-of-available-images
bool CanReuseFromListOfAvailableImages(
    const Resource* resource,
    CrossOriginAttributeValue cross_origin_attribute,
    const SecurityOrigin* origin) {
  const ResourceRequestHead& request = resource->GetResourceRequest();
  bool is_same_origin = request.RequestorOrigin()->IsSameOriginWith(origin);
  if (cross_origin_attribute != kCrossOriginAttributeNotSet && !is_same_origin)
    return false;

  if (request.GetCredentialsMode() ==
          network::mojom::CredentialsMode::kSameOrigin &&
      cross_origin_attribute != kCrossOriginAttributeAnonymous) {
    return false;
  }

  return true;
}

}  // namespace

class ImageLoader::Task {
 public:
  Task(ImageLoader* loader,
       UpdateFromElementBehavior update_behavior,
       network::mojom::ReferrerPolicy referrer_policy)
      : loader_(loader),
        update_behavior_(update_behavior),
        referrer_policy_(referrer_policy) {
    ExecutionContext* context = loader_->GetElement()->GetExecutionContext();
    async_task_context_.Schedule(context, "Image");
    world_ = context->GetCurrentWorld();
  }

  void Run() {
    if (!loader_)
      return;
    ExecutionContext* context = loader_->GetElement()->GetExecutionContext();
    probe::AsyncTask async_task(context, &async_task_context_);
    loader_->DoUpdateFromElement(world_, update_behavior_, referrer_policy_);
  }

  void ClearLoader() {
    loader_ = nullptr;
    world_ = nullptr;
  }

  base::WeakPtr<Task> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }

 private:
  WeakPersistent<ImageLoader> loader_;
  UpdateFromElementBehavior update_behavior_;
  scoped_refptr<const DOMWrapperWorld> world_;
  network::mojom::ReferrerPolicy referrer_policy_;

  probe::AsyncTaskContext async_task_context_;
  base::WeakPtrFactory<Task> weak_factory_{this};
};

ImageLoader::ImageLoader(Element* element)
    : element_(element),
      image_complete_(true),
      suppress_error_events_(false),
      was_deferred_explicitly_(false),
      lazy_image_load_state_(LazyImageLoadState::kNone) {
  RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this;
}

ImageLoader::~ImageLoader() = default;

void ImageLoader::Dispose() {
  RESOURCE_LOADING_DVLOG(1)
      << "~ImageLoader " << this
      << "; has pending load event=" << pending_load_event_.IsActive()
      << ", has pending error event=" << pending_error_event_.IsActive();

  if (image_content_) {
    delay_until_image_notify_finished_ = nullptr;
  }
}

static bool ImageTypeNeedsDecode(const Image& image) {
  // SVG images are context sensitive, and decoding them without the proper
  // context will just end up wasting memory (and CPU).
  // TODO(vmpstr): Generalize this to be all non-lazy decoded images.
  if (IsA<SVGImage>(image))
    return false;
  return true;
}

void ImageLoader::DispatchDecodeRequestsIfComplete() {
  // If the current image isn't complete, then we can't dispatch any decodes.
  // This function will be called again when the current image completes.
  if (!image_complete_)
    return;

  bool is_active = GetElement()->GetDocument().IsActive();
  // If any of the following conditions hold, we either have an inactive
  // document or a broken/non-existent image. In those cases, we reject any
  // pending decodes.
  if (!is_active || !GetContent() || GetContent()->ErrorOccurred()) {
    RejectPendingDecodes();
    return;
  }

  LocalFrame* frame = GetElement()->GetDocument().GetFrame();
  auto* it = decode_requests_.begin();
  while (it != decode_requests_.end()) {
    // If the image already in kDispatched state or still in kPendingMicrotask
    // state, then we don't dispatch decodes for it. So, the only case to handle
    // is if we're in kPendingLoad state.
    auto& request = *it;
    if (request->state() != DecodeRequest::kPendingLoad) {
      ++it;
      continue;
    }
    Image* image = GetContent()->GetImage();
    if (!ImageTypeNeedsDecode(*image)) {
      // If the image is of a type that doesn't need decode, resolve the
      // promise.
      request->Resolve();
      it = decode_requests_.erase(it);
      continue;
    }
    // ImageLoader should be kept alive when decode is still pending. JS may
    // invoke 'decode' without capturing the Image object. If GC kicks in,
    // ImageLoader will be destroyed, leading to unresolved/unrejected Promise.
    frame->GetChromeClient().RequestDecode(
        frame, image->PaintImageForCurrentFrame(),
        WTF::Bind(&ImageLoader::DecodeRequestFinished,
                  WrapCrossThreadPersistent(this), request->request_id()));
    request->NotifyDecodeDispatched();
    ++it;
  }
}

void ImageLoader::DecodeRequestFinished(uint64_t request_id, bool success) {
  // First we find the corresponding request id, then we either resolve or
  // reject it and remove it from the list.
  for (auto* it = decode_requests_.begin(); it != decode_requests_.end();
       ++it) {
    auto& request = *it;
    if (request->request_id() != request_id)
      continue;

    if (success)
      request->Resolve();
    else
      request->Reject();
    decode_requests_.erase(it);
    break;
  }
}

void ImageLoader::RejectPendingDecodes(UpdateType update_type) {
  // Normally, we only reject pending decodes that have passed the
  // kPendingMicrotask state, since pending mutation requests still have an
  // outstanding microtask that will run and might act on a different image than
  // the current one. However, as an optimization, there are cases where we
  // synchronously update the image (see UpdateFromElement). In those cases, we
  // have to reject even the pending mutation requests because conceptually they
  // would have been scheduled before the synchronous update ran, so they
  // referred to the old image.
  for (auto* it = decode_requests_.begin(); it != decode_requests_.end();) {
    auto& request = *it;
    if (update_type == UpdateType::kAsync &&
        request->state() == DecodeRequest::kPendingMicrotask) {
      ++it;
      continue;
    }
    request->Reject();
    it = decode_requests_.erase(it);
  }
}

void ImageLoader::Trace(Visitor* visitor) const {
  visitor->Trace(image_content_);
  visitor->Trace(image_content_for_image_document_);
  visitor->Trace(element_);
  visitor->Trace(decode_requests_);
  ImageResourceObserver::Trace(visitor);
}

void ImageLoader::SetImageForTest(ImageResourceContent* new_image) {
  DCHECK(new_image);
  SetImageWithoutConsideringPendingLoadEvent(new_image);
}

bool ImageLoader::ShouldUpdateOnInsertedInto(
    ContainerNode& insertion_point,
    network::mojom::ReferrerPolicy referrer_policy) const {
  // If we're being inserted into a disconnected tree, we don't need to update.
  if (!insertion_point.isConnected())
    return false;

  // If the base element URL changed, it means that we might be in the process
  // of fetching a wrong image. We should update to ensure we fetch the correct
  // image. This can happen when inserting content into an iframe which has a
  // base element. See crbug.com/897545 for more details.
  if (element_->GetDocument().ValidBaseElementURL() != last_base_element_url_)
    return true;

  // If we already have image content, then we don't need an update.
  if (image_content_)
    return false;

  // Finally, try to update if we're idle. This could be an indication that we
  // skipped a previous load when inserted into an inactive document. Note that
  // if we're not idle, we should also update our referrer policy if it has
  // changed.
  return !HasPendingActivity() || referrer_policy != last_referrer_policy_;
}

bool ImageLoader::ImageIsPotentiallyAvailable() const {
  bool is_lazyload = lazy_image_load_state_ == LazyImageLoadState::kDeferred;

  bool image_has_loaded = image_content_ && !image_content_->IsLoading() &&
                          !image_content_->ErrorOccurred();
  bool image_still_loading = !image_has_loaded && HasPendingActivity() &&
                             !HasPendingError() &&
                             !element_->ImageSourceURL().IsEmpty();
  bool image_has_image = image_content_ && image_content_->HasImage();
  bool image_is_document = element_->GetDocument().IsImageDocument() &&
                           image_content_ && !image_content_->ErrorOccurred();

  // Icky special case for deferred images:
  // A deferred image is not loading, does have pending activity, does not
  // have an error, but it does have an ImageResourceContent associated
  // with it, so |image_has_loaded| will be true even though the image hasn't
  // actually loaded. Fixing the definition of |image_has_loaded| isn't
  // sufficient, because a deferred image does have pending activity, does not
  // have a pending error, and does have a source URL, so if |image_has_loaded|
  // was correct, |image_still_loading| would become wrong.
  //
  // Instead of dealing with that, there's a separate check that the
  // ImageResourceContent has non-null image data associated with it, which
  // isn't folded into |image_has_loaded| above.
  return (image_has_loaded && image_has_image) || image_still_loading ||
         image_is_document || is_lazyload;
}

void ImageLoader::ClearImage() {
  SetImageWithoutConsideringPendingLoadEvent(nullptr);
}

void ImageLoader::SetImageWithoutConsideringPendingLoadEvent(
    ImageResourceContent* new_image_content) {
  DCHECK(failed_load_url_.IsEmpty());
  ImageResourceContent* old_image_content = image_content_.Get();
  if (new_image_content != old_image_content) {
    if (pending_load_event_.IsActive())
      pending_load_event_.Cancel();
    if (pending_error_event_.IsActive())
      pending_error_event_.Cancel();
    UpdateImageState(new_image_content);
    if (new_image_content) {
      new_image_content->AddObserver(this);
    }
    if (old_image_content) {
      old_image_content->RemoveObserver(this);
    }
  }

  if (LayoutImageResource* image_resource = GetLayoutImageResource())
    image_resource->ResetAnimation();
}

static void ConfigureRequest(
    FetchParameters& params,
    Element& element,
    const ClientHintsPreferences& client_hints_preferences) {
  CrossOriginAttributeValue cross_origin = GetCrossOriginAttributeValue(
      element.FastGetAttribute(html_names::kCrossoriginAttr));
  if (cross_origin != kCrossOriginAttributeNotSet) {
    params.SetCrossOriginAccessControl(
        element.GetExecutionContext()->GetSecurityOrigin(), cross_origin);
  }

  if (RuntimeEnabledFeatures::PriorityHintsEnabled(
          element.GetExecutionContext())) {
    mojom::FetchImportanceMode importance_mode =
        GetFetchImportanceAttributeValue(
            element.FastGetAttribute(html_names::kImportanceAttr));
    params.SetFetchImportanceMode(importance_mode);
  }

  auto* html_image_element = DynamicTo<HTMLImageElement>(element);
  if ((client_hints_preferences.ShouldSend(
           network::mojom::WebClientHintsType::kResourceWidth_DEPRECATED) ||
       client_hints_preferences.ShouldSend(
           network::mojom::WebClientHintsType::kResourceWidth)) &&
      html_image_element) {
    params.SetResourceWidth(html_image_element->GetResourceWidth());
  }
}

inline void ImageLoader::DispatchErrorEvent() {
  // There can be cases where DispatchErrorEvent() is called when there is
  // already a scheduled error event for the previous load attempt.
  // In such cases we cancel the previous event (by overwriting
  // |pending_error_event_|) and then re-schedule a new error event here.
  // crbug.com/722500
  pending_error_event_ = PostCancellableTask(
      *GetElement()->GetDocument().GetTaskRunner(TaskType::kDOMManipulation),
      FROM_HERE,
      WTF::Bind(&ImageLoader::DispatchPendingErrorEvent, WrapPersistent(this),
                std::make_unique<IncrementLoadEventDelayCount>(
                    GetElement()->GetDocument())));
}

inline void ImageLoader::CrossSiteOrCSPViolationOccurred(
    AtomicString image_source_url) {
  failed_load_url_ = image_source_url;
}

inline void ImageLoader::ClearFailedLoadURL() {
  failed_load_url_ = AtomicString();
}

inline void ImageLoader::EnqueueImageLoadingMicroTask(
    UpdateFromElementBehavior update_behavior,
    network::mojom::ReferrerPolicy referrer_policy) {
  auto task = std::make_unique<Task>(this, update_behavior, referrer_policy);
  pending_task_ = task->GetWeakPtr();
  Microtask::EnqueueMicrotask(WTF::Bind(&Task::Run, std::move(task)));
  delay_until_do_update_from_element_ =
      std::make_unique<IncrementLoadEventDelayCount>(element_->GetDocument());
}

void ImageLoader::UpdateImageState(ImageResourceContent* new_image_content) {
  image_content_ = new_image_content;
  if (!new_image_content) {
    image_content_for_image_document_ = nullptr;
    image_complete_ = true;
    if (lazy_image_load_state_ == LazyImageLoadState::kDeferred) {
      LazyImageHelper::StopMonitoring(GetElement());
      lazy_image_load_state_ = LazyImageLoadState::kNone;
    }
  } else {
    image_complete_ = false;
    if (lazy_image_load_state_ == LazyImageLoadState::kDeferred)
      LazyImageHelper::StartMonitoring(GetElement());
  }
  delay_until_image_notify_finished_ = nullptr;
}

void ImageLoader::DoUpdateFromElement(
    scoped_refptr<const DOMWrapperWorld> world,
    UpdateFromElementBehavior update_behavior,
    network::mojom::ReferrerPolicy referrer_policy,
    UpdateType update_type) {
  // FIXME: According to
  // http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content.html#the-img-element:the-img-element-55
  // When "update image" is called due to environment changes and the load
  // fails, onerror should not be called. That is currently not the case.
  //
  // We don't need to call clearLoader here: Either we were called from the
  // task, or our caller updateFromElement cleared the task's loader (and set
  // pending_task_ to null).
  pending_task_.reset();
  // Make sure to only decrement the count when we exit this function
  std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter;
  load_delay_counter.swap(delay_until_do_update_from_element_);

  Document& document = element_->GetDocument();
  if (!document.IsActive())
    return;

  AtomicString image_source_url = element_->ImageSourceURL();
  const KURL url = ImageSourceToKURL(image_source_url);
  ImageResourceContent* new_image_content = nullptr;
  if (!url.IsNull() && !url.IsEmpty()) {
    // Unlike raw <img>, we block mixed content inside of <picture> or
    // <img srcset>.
    ResourceLoaderOptions resource_loader_options(std::move(world));
    resource_loader_options.initiator_info.name = GetElement()->localName();
    ResourceRequest resource_request(url);
    if (update_behavior == kUpdateForcedReload) {
      resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache);
      resource_request.SetPreviewsState(PreviewsTypes::kPreviewsNoTransform);
    }

    resource_request.SetReferrerPolicy(referrer_policy);

    // Correct the RequestContext if necessary.
    if (IsA<HTMLPictureElement>(GetElement()->parentNode()) ||
        !GetElement()->FastGetAttribute(html_names::kSrcsetAttr).IsNull()) {
      resource_request.SetRequestContext(
          mojom::blink::RequestContextType::IMAGE_SET);
      resource_request.SetRequestDestination(
          network::mojom::RequestDestination::kImage);
    } else if (IsA<HTMLObjectElement>(GetElement())) {
      resource_request.SetRequestContext(
          mojom::blink::RequestContextType::OBJECT);
      resource_request.SetRequestDestination(
          network::mojom::RequestDestination::kObject);
    } else if (IsA<HTMLEmbedElement>(GetElement())) {
      resource_request.SetRequestContext(
          mojom::blink::RequestContextType::EMBED);
      resource_request.SetRequestDestination(
          network::mojom::RequestDestination::kEmbed);
    }

    bool page_is_being_dismissed =
        document.PageDismissalEventBeingDispatched() != Document::kNoDismissal;
    if (page_is_being_dismissed) {
      resource_request.SetHttpHeaderField(http_names::kCacheControl,
                                          "max-age=0");
      resource_request.SetKeepalive(true);
      resource_request.SetRequestContext(
          mojom::blink::RequestContextType::PING);
      UseCounter::Count(document, WebFeature::kImageLoadAtDismissalEvent);
    }

    // Plug-ins should not load via service workers as plug-ins may have their
    // own origin checking logic that may get confused if service workers
    // respond with resources from another origin.
    // https://w3c.github.io/ServiceWorker/#implementer-concerns
    auto* html_element = DynamicTo<HTMLElement>(GetElement());
    if (html_element && html_element->IsPluginElement()) {
      resource_request.SetSkipServiceWorker(true);
    }

    DCHECK(document.GetFrame());
    auto* frame = document.GetFrame();

    FetchParameters params(std::move(resource_request),
                           resource_loader_options);
    ConfigureRequest(params, *element_, frame->GetClientHintsPreferences());

    if (update_behavior != kUpdateForcedReload &&
        lazy_image_load_state_ != LazyImageLoadState::kFullImage) {
      if (auto* html_image = DynamicTo<HTMLImageElement>(GetElement())) {
        LoadingAttributeValue loading_attr = GetLoadingAttributeValue(
            html_image->FastGetAttribute(html_names::kLoadingAttr));
        switch (LazyImageHelper::DetermineEligibilityAndTrackVisibilityMetrics(
            *frame, html_image, params.Url())) {
          case LazyImageHelper::Eligibility::kEnabledFullyDeferred:
            lazy_image_load_state_ = LazyImageLoadState::kDeferred;
            was_deferred_explicitly_ =
                (loading_attr == LoadingAttributeValue::kLazy);
            params.SetLazyImageDeferred();
            if (frame->Client()) {
              frame->Client()->DidObserveLazyLoadBehavior(
                  WebLocalFrameClient::LazyLoadBehavior::kDeferredImage);
            }
            break;
          case LazyImageHelper::Eligibility::kDisabled:
            break;
        }
      }
    }

    // If we're now loading in a once-deferred image, make sure it doesn't block
    // the load event.
    if (was_deferred_explicitly_ &&
        lazy_image_load_state_ == LazyImageLoadState::kFullImage) {
      params.SetLazyImageNonBlocking();
    }

    if (ShouldEnableSubresourceRedirect(
            DynamicTo<HTMLImageElement>(GetElement()), params.Url())) {
      auto& subresource_request = params.MutableResourceRequest();
      subresource_request.SetPreviewsState(
          subresource_request.GetPreviewsState() |
          PreviewsTypes::kSubresourceRedirectOn);
    }

    new_image_content = ImageResourceContent::Fetch(params, document.Fetcher());

    // If this load is starting while navigating away, treat it as an auditing
    // keepalive request, and don't report its results back to the element.
    if (page_is_being_dismissed)
      new_image_content = nullptr;

    ClearFailedLoadURL();
  } else {
    if (!image_source_url.IsNull()) {
      // Fire an error event if the url string is not empty, but the KURL is.
      DispatchErrorEvent();
    }
    NoImageResourceToLoad();
  }

  ImageResourceContent* old_image_content = image_content_.Get();
  if (old_image_content != new_image_content)
    RejectPendingDecodes(update_type);

  if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() &&
      element_->GetLayoutObject()->IsImage() &&
      new_image_content == old_image_content) {
    To<LayoutImage>(element_->GetLayoutObject())->IntrinsicSizeChanged();
  } else {
    bool is_lazyload = lazy_image_load_state_ == LazyImageLoadState::kDeferred;

    // Loading didn't start (loading of images was disabled). We show fallback
    // contents here, while we don't dispatch an 'error' event etc., because
    // spec-wise the image remains in the "Unavailable" state.
    if (new_image_content &&
        new_image_content->GetContentStatus() == ResourceStatus::kNotStarted &&
        !is_lazyload)
      NoImageResourceToLoad();

    if (pending_load_event_.IsActive())
      pending_load_event_.Cancel();

    // Cancel error events that belong to the previous load, which is now
    // cancelled by changing the src attribute. If newImage is null and
    // has_pending_error_event_ is true, we know the error event has been just
    // posted by this load and we should not cancel the event.
    // FIXME: If both previous load and this one got blocked with an error, we
    // can receive one error event instead of two.
    if (pending_error_event_.IsActive() && new_image_content)
      pending_error_event_.Cancel();

    UpdateImageState(new_image_content);

    UpdateLayoutObject();
    // If newImage exists and is cached, addObserver() will result in the load
    // event being queued to fire. Ensure this happens after beforeload is
    // dispatched.
    if (new_image_content) {
      new_image_content->AddObserver(this);
    }
    if (old_image_content) {
      old_image_content->RemoveObserver(this);
    }
  }

  if (LayoutImageResource* image_resource = GetLayoutImageResource())
    image_resource->ResetAnimation();
}

void ImageLoader::UpdateFromElement(
    UpdateFromElementBehavior update_behavior,
    network::mojom::ReferrerPolicy referrer_policy) {
  if (!element_->GetDocument().IsActive()) {
    return;
  }

  AtomicString image_source_url = element_->ImageSourceURL();
  suppress_error_events_ = (update_behavior == kUpdateSizeChanged);
  last_base_element_url_ =
      element_->GetDocument().ValidBaseElementURL().GetString();
  last_referrer_policy_ = referrer_policy;

  if (update_behavior == kUpdateIgnorePreviousError)
    ClearFailedLoadURL();

  if (!failed_load_url_.IsEmpty() && image_source_url == failed_load_url_)
    return;

  // Prevent the creation of a ResourceLoader (and therefore a network request)
  // for ImageDocument loads. In this case, the image contents have already been
  // requested as a main resource and ImageDocumentParser will take care of
  // funneling the main resource bytes into |image_content_for_image_document_|,
  // so just pick up the ImageResourceContent that has been provided.
  if (image_content_for_image_document_) {
    DCHECK_NE(update_behavior, kUpdateForcedReload);
    SetImageWithoutConsideringPendingLoadEvent(
        image_content_for_image_document_);
    image_content_for_image_document_ = nullptr;
    return;
  }

  // If we have a pending task, we have to clear it -- either we're now loading
  // immediately, or we need to reset the task's state.
  if (pending_task_) {
    pending_task_->ClearLoader();
    pending_task_.reset();
    // Here we need to clear delay_until_do_update_from_element to avoid causing
    // a memory leak in case it's already created.
    delay_until_do_update_from_element_ = nullptr;
  }

  if (ShouldLoadImmediately(ImageSourceToKURL(image_source_url))) {
    DoUpdateFromElement(element_->GetExecutionContext()->GetCurrentWorld(),
                        update_behavior, referrer_policy, UpdateType::kSync);
    return;
  }
  // Allow the idiom "img.src=''; img.src='.." to clear down the image before an
  // asynchronous load completes.
  if (image_source_url.IsEmpty()) {
    ImageResourceContent* image = image_content_.Get();
    if (image) {
      image->RemoveObserver(this);
    }
    image_content_ = nullptr;
    image_content_for_image_document_ = nullptr;
    delay_until_image_notify_finished_ = nullptr;
    if (lazy_image_load_state_ != LazyImageLoadState::kNone) {
      LazyImageHelper::StopMonitoring(GetElement());
      lazy_image_load_state_ = LazyImageLoadState::kNone;
    }
  }

  // Don't load images for inactive documents or active documents without V8
  // context. We don't want to slow down the raw HTML parsing case by loading
  // images we don't intend to display.
  if (element_->GetDocument().IsActive())
    EnqueueImageLoadingMicroTask(update_behavior, referrer_policy);
}

KURL ImageLoader::ImageSourceToKURL(AtomicString image_source_url) const {
  KURL url;

  // Don't load images for inactive documents. We don't want to slow down the
  // raw HTML parsing case by loading images we don't intend to display.
  Document& document = element_->GetDocument();
  if (!document.IsActive())
    return url;

  // Do not load any image if the 'src' attribute is missing or if it is
  // an empty string.
  if (!image_source_url.IsNull()) {
    String stripped_image_source_url =
        StripLeadingAndTrailingHTMLSpaces(image_source_url);
    if (!stripped_image_source_url.IsEmpty())
      url = document.CompleteURL(stripped_image_source_url);
  }
  return url;
}

bool ImageLoader::ShouldLoadImmediately(const KURL& url) const {
  // We force any image loads which might require alt content through the
  // asynchronous path so that we can add the shadow DOM for the alt-text
  // content when style recalc is over and DOM mutation is allowed again.
  if (!url.IsNull()) {
    Resource* resource = GetMemoryCache()->ResourceForURL(
        url, element_->GetDocument().Fetcher()->GetCacheIdentifier(url));

    if (resource && !resource->ErrorOccurred() &&
        CanReuseFromListOfAvailableImages(
            resource,
            GetCrossOriginAttributeValue(
                element_->FastGetAttribute(html_names::kCrossoriginAttr)),
            element_->GetExecutionContext()->GetSecurityOrigin())) {
      return true;
    }
  }

  return (IsA<HTMLObjectElement>(*element_) ||
          IsA<HTMLEmbedElement>(*element_));
}

void ImageLoader::ImageChanged(ImageResourceContent* content,
                               CanDeferInvalidation) {
  DCHECK_EQ(content, image_content_.Get());
  if (image_complete_ || !content->IsLoading() ||
      delay_until_image_notify_finished_)
    return;

  Document& document = element_->GetDocument();
  if (!document.IsActive())
    return;

  delay_until_image_notify_finished_ =
      std::make_unique<IncrementLoadEventDelayCount>(document);
}

void ImageLoader::ImageNotifyFinished(ImageResourceContent* content) {
  RESOURCE_LOADING_DVLOG(1)
      << "ImageLoader::imageNotifyFinished " << this
      << "; has pending load event=" << pending_load_event_.IsActive();

  DCHECK(failed_load_url_.IsEmpty());
  DCHECK_EQ(content, image_content_.Get());

  CHECK(!image_complete_);

  if (lazy_image_load_state_ == LazyImageLoadState::kDeferred) {
    // LazyImages: if a placeholder is loaded, suppress load events and do not
    // consider the image as loaded, except for unblocking document load events.
    // The final image load (including load events) occurs when the
    // non-placeholder image loading (triggered by LoadDeferredImage()) is
    // finished.
    if (image_content_ && image_content_->GetImage()->IsPlaceholderImage()) {
      delay_until_image_notify_finished_ = nullptr;
      return;
    }
    // A placeholder was requested, but the result was an error or a full image.
    // In these cases, consider this as the final image and suppress further
    // reloading and proceed to the image load completion process below.
    LazyImageHelper::StopMonitoring(GetElement());
    lazy_image_load_state_ = LazyImageLoadState::kFullImage;
  }

  image_complete_ = true;
  delay_until_image_notify_finished_ = nullptr;

  UpdateLayoutObject();

  if (image_content_ && image_content_->HasImage()) {
    Image& image = *image_content_->GetImage();

    if (auto* svg_image = DynamicTo<SVGImage>(image)) {
      // SVG's document should be completely loaded before access control
      // checks, which can occur anytime after ImageNotifyFinished()
      // (See SVGImage::CurrentFrameHasSingleSecurityOrigin()).
      // We check the document is loaded here to catch violation of the
      // assumption reliably.
      svg_image->CheckLoaded();
      svg_image->UpdateUseCounters(GetElement()->GetDocument());
    }
  }

  // TODO(loonybear): support image policies on other images in addition to
  // HTMLImageElement.
  // crbug.com/930281
  auto* html_image_element = DynamicTo<HTMLImageElement>(element_.Get());
  if (CheckForUnoptimizedImagePolicy(element_->GetExecutionContext(),
                                     image_content_) &&
      html_image_element)
    html_image_element->SetImagePolicyViolated();

  DispatchDecodeRequestsIfComplete();

  if (html_image_element)
    LazyImageHelper::RecordMetricsOnLoadFinished(html_image_element);

  if (content->ErrorOccurred()) {
    pending_load_event_.Cancel();

    absl::optional<ResourceError> error = content->GetResourceError();
    if (error && error->IsAccessCheck())
      CrossSiteOrCSPViolationOccurred(AtomicString(error->FailingURL()));

    // The error event should not fire if the image data update is a result of
    // environment change.
    // https://html.spec.whatwg.org/C/#the-img-element:the-img-element-55
    if (!suppress_error_events_)
      DispatchErrorEvent();
    return;
  }

  content->RecordDecodedImageType(&element_->GetDocument());

  CHECK(!pending_load_event_.IsActive());
  pending_load_event_ = PostCancellableTask(
      *GetElement()->GetDocument().GetTaskRunner(TaskType::kDOMManipulation),
      FROM_HERE,
      WTF::Bind(&ImageLoader::DispatchPendingLoadEvent, WrapPersistent(this),
                std::make_unique<IncrementLoadEventDelayCount>(
                    GetElement()->GetDocument())));
}

LayoutImageResource* ImageLoader::GetLayoutImageResource() {
  LayoutObject* layout_object = element_->GetLayoutObject();

  if (!layout_object)
    return nullptr;

  // We don't return style generated image because it doesn't belong to the
  // ImageLoader. See <https://bugs.webkit.org/show_bug.cgi?id=42840>
  if (layout_object->IsImage() &&
      !To<LayoutImage>(layout_object)->IsGeneratedContent())
    return To<LayoutImage>(layout_object)->ImageResource();

  if (layout_object->IsSVGImage())
    return To<LayoutSVGImage>(layout_object)->ImageResource();

  if (auto* layout_video = DynamicTo<LayoutVideo>(layout_object))
    return layout_video->ImageResource();

  return nullptr;
}

void ImageLoader::UpdateLayoutObject() {
  LayoutImageResource* image_resource = GetLayoutImageResource();

  if (!image_resource)
    return;

  // Only update the layoutObject if it doesn't have an image or if what we have
  // is a complete image.  This prevents flickering in the case where a dynamic
  // change is happening between two images.
  ImageResourceContent* cached_image_content = image_resource->CachedImage();
  if (image_content_ != cached_image_content &&
      (image_complete_ || !cached_image_content))
    image_resource->SetImageResource(image_content_.Get());
}

bool ImageLoader::HasPendingEvent() const {
  // Regular image loading is in progress.
  if (image_content_ && !image_complete_)
    return true;

  if (pending_load_event_.IsActive() || pending_error_event_.IsActive())
    return true;

  return false;
}

void ImageLoader::DispatchPendingLoadEvent(
    std::unique_ptr<IncrementLoadEventDelayCount> count) {
  if (!image_content_)
    return;
  CHECK(image_complete_);
  DispatchLoadEvent();

  // Checks Document's load event synchronously here for performance.
  // This is safe because DispatchPendingLoadEvent() is called asynchronously.
  count->ClearAndCheckLoadEvent();
}

void ImageLoader::DispatchPendingErrorEvent(
    std::unique_ptr<IncrementLoadEventDelayCount> count) {
  GetElement()->DispatchEvent(*Event::Create(event_type_names::kError));

  // Checks Document's load event synchronously here for performance.
  // This is safe because DispatchPendingErrorEvent() is called asynchronously.
  count->ClearAndCheckLoadEvent();
}

bool ImageLoader::GetImageAnimationPolicy(
    mojom::blink::ImageAnimationPolicy& policy) {
  if (!GetElement()->GetDocument().GetSettings())
    return false;

  policy = GetElement()->GetDocument().GetSettings()->GetImageAnimationPolicy();
  return true;
}

ScriptPromise ImageLoader::Decode(ScriptState* script_state,
                                  ExceptionState& exception_state) {
  // It's possible that |script_state|'s context isn't valid, which means we
  // should immediately reject the request. This is possible in situations like
  // the document that created this image was already destroyed (like an img
  // that comes from iframe.contentDocument.createElement("img") and the iframe
  // is destroyed).
  if (!script_state->ContextIsValid()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kEncodingError,
                                      "The source image cannot be decoded.");
    return ScriptPromise();
  }

  UseCounter::Count(GetElement()->GetDocument(), WebFeature::kImageDecodeAPI);

  auto* request = MakeGarbageCollected<DecodeRequest>(
      this, MakeGarbageCollected<ScriptPromiseResolver>(script_state));
  Microtask::EnqueueMicrotask(
      WTF::Bind(&DecodeRequest::ProcessForTask, WrapWeakPersistent(request)));
  decode_requests_.push_back(request);
  return request->promise();
}

void ImageLoader::LoadDeferredImage(
    network::mojom::ReferrerPolicy referrer_policy) {
  if (lazy_image_load_state_ != LazyImageLoadState::kDeferred)
    return;
  DCHECK(!image_complete_);
  lazy_image_load_state_ = LazyImageLoadState::kFullImage;

  // If the image has been fully deferred (no placeholder fetch), report it as
  // fully loaded now.
  LocalFrame* frame = element_->GetDocument().GetFrame();
  if (frame && frame->Client()) {
    frame->Client()->DidObserveLazyLoadBehavior(
        WebLocalFrameClient::LazyLoadBehavior::kLazyLoadedImage);
  }
  UpdateFromElement(kUpdateNormal, referrer_policy);
}

void ImageLoader::ElementDidMoveToNewDocument() {
  if (delay_until_do_update_from_element_) {
    delay_until_do_update_from_element_->DocumentChanged(
        element_->GetDocument());
  }
  if (delay_until_image_notify_finished_) {
    delay_until_image_notify_finished_->DocumentChanged(
        element_->GetDocument());
  }
  ClearFailedLoadURL();
  ClearImage();
}

// Indicates the next available id that we can use to uniquely identify a decode
// request.
uint64_t ImageLoader::DecodeRequest::s_next_request_id_ = 0;

ImageLoader::DecodeRequest::DecodeRequest(ImageLoader* loader,
                                          ScriptPromiseResolver* resolver)
    : request_id_(s_next_request_id_++), resolver_(resolver), loader_(loader) {}

void ImageLoader::DecodeRequest::Resolve() {
  resolver_->Resolve();
  loader_ = nullptr;
}

void ImageLoader::DecodeRequest::Reject() {
  resolver_->Reject(MakeGarbageCollected<DOMException>(
      DOMExceptionCode::kEncodingError, "The source image cannot be decoded."));
  loader_ = nullptr;
}

void ImageLoader::DecodeRequest::ProcessForTask() {
  // We could have already processed (ie rejected) this task due to a sync
  // update in UpdateFromElement. In that case, there's nothing to do here.
  if (!loader_)
    return;

  DCHECK_EQ(state_, kPendingMicrotask);
  state_ = kPendingLoad;
  loader_->DispatchDecodeRequestsIfComplete();
}

void ImageLoader::DecodeRequest::NotifyDecodeDispatched() {
  DCHECK_EQ(state_, kPendingLoad);
  state_ = kDispatched;
}

void ImageLoader::DecodeRequest::Trace(Visitor* visitor) const {
  visitor->Trace(resolver_);
  visitor->Trace(loader_);
}

}  // namespace blink


text:
<?php

abstract class Standard_Model
{
	protected $_data;

	protected static $_tables = array();

	protected $_buffering = false;
	protected $_buffer = array();

	public function __construct(array $data = null)
	{
		if(!empty($data))
		{
			foreach($data as $column => $value)
			{
				$this->setColumn($column, $value);
			}
		}
	}

	public function __set($name, $value)
	{
		return $this->setColumn($name, $value);
	}

	public function __get($name)
	{
		return $this->getColumn($name);
	}

	public function __sleep()
	{
		return array('_data');
	}

	public function toArray()
	{
		$data = array();
		foreach($this->_columns as $name => $value)
		{
			$data[$name] = $this->getColumn($name);
		}

		return $data;
	}

	public function setColumn($name, $value)
	{
		$method = 'set' . Standard_Inflector::toCamelCase($name);
		if (method_exists($this, $method))
		{
			$this->$method($value);
		}
		elseif(isset($this->_columns[$name]))
		{
			$type = $this->_columns[$name];
			$method = 'filter' . ucfirst($type);
			if(method_exists($this, $method))
				$value = $this->$method($value);

			$this->_data[$name] = $value;
		}
		else
		{
			throw new Exception("Invalid attribute $name specified");
		}

		return $this;
	}

	public function getColumn($name)
	{
		$method = 'get' . Standard_Inflector::toCamelCase($name);
		if (method_exists($this, $method))
		{
			return $this->$method();
		}
		elseif(isset($this->_data[$name]))
		{
			return $this->_data[$name];
		}

		return null;
	}

	public function getDbTable()
	{
		if(empty($this->_dbTable))
			throw new Exception('There is no dbtable for this class');

		$class = $this->_dbTable;
		if(!isset(self::$_tables[$class]))
		{
			$table = new $class();
			if(!($table instanceof Standard_Db_Table))
				throw new Exception('Invalid table class');

			self::$_tables[$class] = $table;
		}

		return self::$_tables[$class];
	}

	public function loadFromDb($row)
	{
		if($row instanceof Zend_Db_Table_Row)
		{
			$data = $row->toArray();
		}
		elseif($row instanceof stdClass)
		{
			$data = (array) $row;
		}
		elseif(is_array($row))
		{
			$data = $row;
		}

		foreach($data as $column => $value)
		{
			if(isset($this->_columns))
				$this->_data[$column] = $value;
		}

		return $this;
	}

	public function filterString($value)
	{
		return trim($value);
	}

	public function filterTimestamp($value)
	{
		if(empty($value) || is_numeric($value))
		{
			return $value;
		}
		elseif(is_string($value))
		{
			$time = strtotime($value);
			if($time === false)
				throw new Exception("Value could not be translated into a timestamp: $value");
			return $time;
		}
		else
		{
			throw new Exception('Value could not be translated into a timestamp: ' . print_r($value));
		}
	}

    public function displayDate($column = 'date', $format = '%m/%d/%y')
    {
		if($this->$column == 0 || $this->$column == '')
			return '';

        return strftime($format, (int) $this->$column);
    }

    public function displayDateTime($column = 'date', $format = '%m/%d/%y %l:%M %p')
    {
		if($this->$column == 0 || $this->$column == '')
			return '';

        return strftime($format, (int) $this->$column);
    }

    public function displayTime($column = 'date', $format = '%l:%M %p')
    {
		if($this->$column == 0 || $this->$column == '')
			return '';

        return strftime($format, (int) $this->$column);
    }

	public function displayDaysFromNow($column = 'date')
	{
		if($this->$column == 0 || $this->$column == '')
			return '';

		$day = 60 * 60 * 24;
		$date = $this->$column;
		$now = time();
		$tomorrow = strtotime('tomorrow');
		$delta = $date - $now;
		if($delta < $day && $date < $tomorrow)
		{
			return 'today';
		}
		elseif($delta <= $day && $date > $tomorrow)
		{
			return 'tomorrow';
		}
		else
		{
			$days = floor($delta/$day);
			$daysWord = ($days > 1) ? 'days' : 'day';
			return "$days $daysWord from now";
		}
	}

    public function displayCurrency($column = 'amount')
    {
		$currency = new Zend_Currency(array('value' => $this->$column));
        return (string) $currency;
    }

	public function save()
	{
		$table = $this->getDbTable();
		$data = $this->_data;

		if($this->_buffering)
		{
			$this->_buffer[] = $data;
			return $this;
		}

		if(isset($data['id']) && $data['id'] > 0)
		{
			$where = array('id = ?' => $data['id']);
			unset($data['id']);
			$table->update($data, $where);
		}
		else
		{
			$id = $table->insert($data);
			$this->_data['id'] = $id;
		}

		return $this;
	}

	public function find($id)
	{
		$table = $this->getDbTable();
		$rows = $table->find($id);
		if(count($rows) < 1)
		{
			return false;
		}

		$row = $rows->current();
		return $this->loadFromDb($row);
	}

	public function fetchByUser(App_Model_User $user)
	{
		$table = $this->getDbTable();
		$rows = $table->fetchByUserId($user->id);
		$items = array();
		$class = get_class($this);
		foreach($rows as $row)
		{
			$item = new $class();
			$item->loadFromDb($row);
			$items[$item->id] = $item;
		}

		return $items;
	}

	public function findMany(array $ids)
	{
		if(empty($ids)) return array();

		$table = $this->getDbTable();
		$rows = $table->findMany($ids);
		$items = array();
		$class = get_class($this);
		foreach($rows as $row)
		{
			$item = new $class();
			$item->loadFromDb($row);
			$items[$item->id] = $item;
		}

		return $items;
	}

	public function buffer()
	{
		$this->_buffering = true;
	}

	public function flush()
	{
		$table = $this->getDbTable();
		$table->bulkInsert($this->_buffer);
		$this->_buffer = array();
	}

	public function delete()
	{
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $this->id);
		$table->delete($where);
		return true;
	}

	protected function _countMonths($start, $end)
	{
		$monthStart = strtotime(strftime('%m/01/%Y', $start));
		$monthEnd = strtotime(strftime('%m/01/%Y', $end));
		$months = 0;
		for($i = $monthStart; $i < $monthEnd; $i= strtotime('+1 month', $i))
		{
			$months++;
		}

		return $months;
	}
}


text:
title: Anahi Pereyra y orquesta de canciones a pedal 🎵
layout: post-novedad
featured: false
categoria: noticia
image_url: /img/anahi-pereyra-orquesta-de-cancionas-a-pedal.jpg
meta: Música del mundo con bases latinoamericanas el proximos sábado 27 de octubre.
---

Este sábado 27/10 a las 22hs. Entrada a la gorra. Buffet delisioso. Momento hermoso para compartir..
Anahi pereyra y la orquesta de canciones a pedal
Musica del mundo con bases latinoamericanas

Anahi pereyra-- Voz, Percusion, Guitarra

Leonardo garcia-- Bajo electrico

Lucas sanchez-- Percusion Bateria

El repertorio que compartimos esta creado desde el maravilloso lugar
Que tiene la musica en nuestras vidas.
La musica herramienta primordial de sosten, fortaleza, felicidad.
Musica creada por nosotrxs mismxs y musicas interpretadas desde nuestro sentir.
Musica con bases poeticas que refuerzan el sentido de melodias y armonias.
Musica nacida desde una voz latinoamericana y viajada por otras partes
Del mundo ,unidas por un eje en común. La canción

Les esperamos


text:
<?xml version="1.0" encoding="UTF-8"?>
<info>
	<uuid>00000000000000000000</uuid>
	<name>compdevmgr</name>
	<description>Service Management component</description>
	<company>Nsynapse Inc.</company>
	<developer>Byunghun Hwang</developer>
	<email>bhhwang@nsynapse.com</email>
	<url>http://www.nsynapse.com</url>
	<license>MIT</license>
	<version>0.0.1</version>
	<category></category>
	<tags></tags>

</info>

<property>
	<address>225.0.0.37</address>
	<port>21928</port>
	<maxconnection>3</maxconnection>
</property>

<service name="devmgrpub" method="publish" topic="service/compdevmgr:announce"></service>
<service name="devmgrsub" method="subscribe" topic="service/compdevmgr:deviceprofile">
	<required name="mac"></required>
	<argument name="profile" type="string"></argument>
</service>


text:
#define pr_fmt(fmt) "pinconfig core: " fmt

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinconf.h>
#include "core.h"
#include "pinconf.h"

int pinconf_check_ops(struct pinctrl_dev *pctldev)
{
	const struct pinconf_ops *ops = pctldev->desc->confops;

	/* We must be able to read out pin status */
	if (!ops->pin_config_get && !ops->pin_config_group_get)
		return -EINVAL;
	/* We have to be able to config the pins in SOME way */
	if (!ops->pin_config_set && !ops->pin_config_group_set)
		return -EINVAL;
	return 0;
}

int pinconf_validate_map(struct pinctrl_map const *map, int i)
{
	if (!map->data.configs.group_or_pin) {
		pr_err("failed to register map %s (%d): no group/pin given\n",
		       map->name, i);
		return -EINVAL;
	}

	if (map->data.configs.num_configs &&
			!map->data.configs.configs) {
		pr_err("failed to register map %s (%d): no configs ptr given\n",
		       map->name, i);
		return -EINVAL;
	}

	return 0;
}

int pin_config_get_for_pin(struct pinctrl_dev *pctldev, unsigned pin,
			   unsigned long *config)
{
	const struct pinconf_ops *ops = pctldev->desc->confops;

	if (!ops || !ops->pin_config_get) {
		dev_err(pctldev->dev, "cannot get pin configuration, missing "
			"pin_config_get() function in driver\n");
		return -EINVAL;
	}

	return ops->pin_config_get(pctldev, pin, config);
}

/**
 * pin_config_get() - get the configuration of a single pin parameter
 * @dev_name: name of the pin controller device for this pin
 * @name: name of the pin to get the config for
 * @config: the config pointed to by this argument will be filled in with the
 *	current pin state, it can be used directly by drivers as a numeral, or
 *	it can be dereferenced to any struct.
 */
int pin_config_get(const char *dev_name, const char *name,
			  unsigned long *config)
{
	struct pinctrl_dev *pctldev;
	int pin;

	mutex_lock(&pinctrl_mutex);

	pctldev = get_pinctrl_dev_from_devname(dev_name);
	if (!pctldev) {
		pin = -EINVAL;
		goto unlock;
	}

	pin = pin_get_from_name(pctldev, name);
	if (pin < 0)
		goto unlock;

	pin = pin_config_get_for_pin(pctldev, pin, config);

unlock:
	mutex_unlock(&pinctrl_mutex);
	return pin;
}
EXPORT_SYMBOL(pin_config_get);

static int pin_config_set_for_pin(struct pinctrl_dev *pctldev, unsigned pin,
			   unsigned long config)
{
	const struct pinconf_ops *ops = pctldev->desc->confops;
	int ret;

	if (!ops || !ops->pin_config_set) {
		dev_err(pctldev->dev, "cannot configure pin, missing "
			"config function in driver\n");
		return -EINVAL;
	}

	ret = ops->pin_config_set(pctldev, pin, config);
	if (ret) {
		dev_err(pctldev->dev,
			"unable to set pin configuration on pin %d\n", pin);
		return ret;
	}

	return 0;
}

/**
 * pin_config_set() - set the configuration of a single pin parameter
 * @dev_name: name of pin controller device for this pin
 * @name: name of the pin to set the config for
 * @config: the config in this argument will contain the desired pin state, it
 *	can be used directly by drivers as a numeral, or it can be dereferenced
 *	to any struct.
 */
int pin_config_set(const char *dev_name, const char *name,
		   unsigned long config)
{
	struct pinctrl_dev *pctldev;
	int pin, ret;

	mutex_lock(&pinctrl_mutex);

	pctldev = get_pinctrl_dev_from_devname(dev_name);
	if (!pctldev) {
		ret = -EINVAL;
		goto unlock;
	}

	pin = pin_get_from_name(pctldev, name);
	if (pin < 0) {
		ret = pin;
		goto unlock;
	}

	ret = pin_config_set_for_pin(pctldev, pin, config);

unlock:
	mutex_unlock(&pinctrl_mutex);
	return ret;
}
EXPORT_SYMBOL(pin_config_set);

int pin_config_group_get(const char *dev_name, const char *pin_group,
			 unsigned long *config)
{
	struct pinctrl_dev *pctldev;
	const struct pinconf_ops *ops;
	int selector, ret;

	mutex_lock(&pinctrl_mutex);

	pctldev = get_pinctrl_dev_from_devname(dev_name);
	if (!pctldev) {
		ret = -EINVAL;
		goto unlock;
	}
	ops = pctldev->desc->confops;

	if (!ops || !ops->pin_config_group_get) {
		dev_err(pctldev->dev, "cannot get configuration for pin "
			"group, missing group config get function in "
			"driver\n");
		ret = -EINVAL;
		goto unlock;
	}

	selector = pinctrl_get_group_selector(pctldev, pin_group);
	if (selector < 0) {
		ret = selector;
		goto unlock;
	}

	ret = ops->pin_config_group_get(pctldev, selector, config);

unlock:
	mutex_unlock(&pinctrl_mutex);
	return ret;
}
EXPORT_SYMBOL(pin_config_group_get);

int pin_config_group_set(const char *dev_name, const char *pin_group,
			 unsigned long config)
{
	struct pinctrl_dev *pctldev;
	const struct pinconf_ops *ops;
	const struct pinctrl_ops *pctlops;
	int selector;
	const unsigned *pins;
	unsigned num_pins;
	int ret;
	int i;

	mutex_lock(&pinctrl_mutex);

	pctldev = get_pinctrl_dev_from_devname(dev_name);
	if (!pctldev) {
		ret = -EINVAL;
		goto unlock;
	}
	ops = pctldev->desc->confops;
	pctlops = pctldev->desc->pctlops;

	if (!ops || (!ops->pin_config_group_set && !ops->pin_config_set)) {
		dev_err(pctldev->dev, "cannot configure pin group, missing "
			"config function in driver\n");
		ret = -EINVAL;
		goto unlock;
	}

	selector = pinctrl_get_group_selector(pctldev, pin_group);
	if (selector < 0) {
		ret = selector;
		goto unlock;
	}

	ret = pctlops->get_group_pins(pctldev, selector, &pins, &num_pins);
	if (ret) {
		dev_err(pctldev->dev, "cannot configure pin group, error "
			"getting pins\n");
		goto unlock;
	}

	/*
	 * If the pin controller supports handling entire groups we use that
	 * capability.
	 */
	if (ops->pin_config_group_set) {
		ret = ops->pin_config_group_set(pctldev, selector, config);
		/*
		 * If the pin controller prefer that a certain group be handled
		 * pin-by-pin as well, it returns -EAGAIN.
		 */
		if (ret != -EAGAIN)
			goto unlock;
	}

	/*
	 * If the controller cannot handle entire groups, we configure each pin
	 * individually.
	 */
	if (!ops->pin_config_set) {
		ret = 0;
		goto unlock;
	}

	for (i = 0; i < num_pins; i++) {
		ret = ops->pin_config_set(pctldev, pins[i], config);
		if (ret < 0)
			goto unlock;
	}

	ret = 0;

unlock:
	mutex_unlock(&pinctrl_mutex);

	return ret;
}
EXPORT_SYMBOL(pin_config_group_set);

int pinconf_map_to_setting(struct pinctrl_map const *map,
			  struct pinctrl_setting *setting)
{
	struct pinctrl_dev *pctldev = setting->pctldev;
	int pin;

	switch (setting->type) {
	case PIN_MAP_TYPE_CONFIGS_PIN:
		pin = pin_get_from_name(pctldev,
					map->data.configs.group_or_pin);
		if (pin < 0) {
			dev_err(pctldev->dev, "could not map pin config for \"%s\"",
				map->data.configs.group_or_pin);
			return pin;
		}
		setting->data.configs.group_or_pin = pin;
		break;
	case PIN_MAP_TYPE_CONFIGS_GROUP:
		pin = pinctrl_get_group_selector(pctldev,
					 map->data.configs.group_or_pin);
		if (pin < 0) {
			dev_err(pctldev->dev, "could not map group config for \"%s\"",
				map->data.configs.group_or_pin);
			return pin;
		}
		setting->data.configs.group_or_pin = pin;
		break;
	default:
		return -EINVAL;
	}

	setting->data.configs.num_configs = map->data.configs.num_configs;
	setting->data.configs.configs = map->data.configs.configs;

	return 0;
}

void pinconf_free_setting(struct pinctrl_setting const *setting)
{
}

int pinconf_apply_setting(struct pinctrl_setting const *setting)
{
	struct pinctrl_dev *pctldev = setting->pctldev;
	const struct pinconf_ops *ops = pctldev->desc->confops;
	int i, ret;

	if (!ops) {
		dev_err(pctldev->dev, "missing confops\n");
		return -EINVAL;
	}

	switch (setting->type) {
	case PIN_MAP_TYPE_CONFIGS_PIN:
		if (!ops->pin_config_set) {
			dev_err(pctldev->dev, "missing pin_config_set op\n");
			return -EINVAL;
		}
		for (i = 0; i < setting->data.configs.num_configs; i++) {
			ret = ops->pin_config_set(pctldev,
					setting->data.configs.group_or_pin,
					setting->data.configs.configs[i]);
			if (ret < 0) {
				dev_err(pctldev->dev,
					"pin_config_set op failed for pin %d config %08lx\n",
					setting->data.configs.group_or_pin,
					setting->data.configs.configs[i]);
				return ret;
			}
		}
		break;
	case PIN_MAP_TYPE_CONFIGS_GROUP:
		if (!ops->pin_config_group_set) {
			dev_err(pctldev->dev,
				"missing pin_config_group_set op\n");
			return -EINVAL;
		}
		for (i = 0; i < setting->data.configs.num_configs; i++) {
			ret = ops->pin_config_group_set(pctldev,
					setting->data.configs.group_or_pin,
					setting->data.configs.configs[i]);
			if (ret < 0) {
				dev_err(pctldev->dev,
					"pin_config_group_set op failed for group %d config %08lx\n",
					setting->data.configs.group_or_pin,
					setting->data.configs.configs[i]);
				return ret;
			}
		}
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

#ifdef CONFIG_DEBUG_FS

void pinconf_show_map(struct seq_file *s, struct pinctrl_map const *map)
{
	int i;

	switch (map->type) {
	case PIN_MAP_TYPE_CONFIGS_PIN:
		seq_printf(s, "pin ");
		break;
	case PIN_MAP_TYPE_CONFIGS_GROUP:
		seq_printf(s, "group ");
		break;
	default:
		break;
	}

	seq_printf(s, "%s\n", map->data.configs.group_or_pin);

	for (i = 0; i < map->data.configs.num_configs; i++)
		seq_printf(s, "config %08lx\n", map->data.configs.configs[i]);
}

void pinconf_show_setting(struct seq_file *s,
			  struct pinctrl_setting const *setting)
{
	struct pinctrl_dev *pctldev = setting->pctldev;
	const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
	struct pin_desc *desc;
	int i;

	switch (setting->type) {
	case PIN_MAP_TYPE_CONFIGS_PIN:
		desc = pin_desc_get(setting->pctldev,
				    setting->data.configs.group_or_pin);
		seq_printf(s, "pin %s (%d)",
			   desc->name ? desc->name : "unnamed",
			   setting->data.configs.group_or_pin);
		break;
	case PIN_MAP_TYPE_CONFIGS_GROUP:
		seq_printf(s, "group %s (%d)",
			   pctlops->get_group_name(pctldev,
					setting->data.configs.group_or_pin),
			   setting->data.configs.group_or_pin);
		break;
	default:
		break;
	}

	/*
	 * FIXME: We should really get the pin controler to dump the config
	 * values, so they can be decoded to something meaningful.
	 */
	for (i = 0; i < setting->data.configs.num_configs; i++)
		seq_printf(s, " %08lx", setting->data.configs.configs[i]);

	seq_printf(s, "\n");
}

static void pinconf_dump_pin(struct pinctrl_dev *pctldev,
			     struct seq_file *s, int pin)
{
	const struct pinconf_ops *ops = pctldev->desc->confops;

	/* no-op when not using generic pin config */
	pinconf_generic_dump_pin(pctldev, s, pin);
	if (ops && ops->pin_config_dbg_show)
		ops->pin_config_dbg_show(pctldev, s, pin);
}

static int pinconf_pins_show(struct seq_file *s, void *what)
{
	struct pinctrl_dev *pctldev = s->private;
	unsigned i, pin;

	seq_puts(s, "Pin config settings per pin\n");
	seq_puts(s, "Format: pin (name): pinmux setting array\n");

	mutex_lock(&pinctrl_mutex);

	/* The pin number can be retrived from the pin controller descriptor */
	for (i = 0; i < pctldev->desc->npins; i++) {
		struct pin_desc *desc;

		pin = pctldev->desc->pins[i].number;
		desc = pin_desc_get(pctldev, pin);
		/* Skip if we cannot search the pin */
		if (desc == NULL)
			continue;

		seq_printf(s, "pin %d (%s):", pin,
			   desc->name ? desc->name : "unnamed");

		pinconf_dump_pin(pctldev, s, pin);

		seq_printf(s, "\n");
	}

	mutex_unlock(&pinctrl_mutex);

	return 0;
}

static void pinconf_dump_group(struct pinctrl_dev *pctldev,
			       struct seq_file *s, unsigned selector,
			       const char *gname)
{
	const struct pinconf_ops *ops = pctldev->desc->confops;

	/* no-op when not using generic pin config */
	pinconf_generic_dump_group(pctldev, s, gname);
	if (ops && ops->pin_config_group_dbg_show)
		ops->pin_config_group_dbg_show(pctldev, s, selector);
}

static int pinconf_groups_show(struct seq_file *s, void *what)
{
	struct pinctrl_dev *pctldev = s->private;
	const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
	const struct pinconf_ops *ops = pctldev->desc->confops;
	unsigned selector = 0;

	if (!ops || !ops->pin_config_group_get)
		return 0;

	seq_puts(s, "Pin config settings per pin group\n");
	seq_puts(s, "Format: group (name): pinmux setting array\n");

	mutex_lock(&pinctrl_mutex);

	while (pctlops->list_groups(pctldev, selector) >= 0) {
		const char *gname = pctlops->get_group_name(pctldev, selector);

		seq_printf(s, "%u (%s):", selector, gname);
		pinconf_dump_group(pctldev, s, selector, gname);
		seq_printf(s, "\n");

		selector++;
	}

	mutex_unlock(&pinctrl_mutex);

	return 0;
}

static int pinconf_pins_open(struct inode *inode, struct file *file)
{
	return single_open(file, pinconf_pins_show, inode->i_private);
}

static int pinconf_groups_open(struct inode *inode, struct file *file)
{
	return single_open(file, pinconf_groups_show, inode->i_private);
}

static const struct file_operations pinconf_pins_ops = {
	.open		= pinconf_pins_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

static const struct file_operations pinconf_groups_ops = {
	.open		= pinconf_groups_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

void pinconf_init_device_debugfs(struct dentry *devroot,
			 struct pinctrl_dev *pctldev)
{
	debugfs_create_file("pinconf-pins", S_IFREG | S_IRUGO,
			    devroot, pctldev, &pinconf_pins_ops);
	debugfs_create_file("pinconf-groups", S_IFREG | S_IRUGO,
			    devroot, pctldev, &pinconf_groups_ops);
}

#endif