text:
import { RenderBatch, ArrayRange, RenderTreeDiff, ArrayValues, RenderTreeEdit, RenderTreeFrame, RenderTreeDiffReader, RenderTreeFrameReader, RenderTreeEditReader, ArrayRangeReader, ArrayBuilderSegmentReader, ArrayBuilderSegment } from './RenderBatch';
import { decodeUtf8 } from '../../Utf8Decoder';
import { readInt32LE, readUint64LE, readLEB128, numLEB128Bytes } from '../../BinaryDecoder';

const updatedComponentsEntryLength = 4; // Each is a single int32 giving the location of the data
const referenceFramesEntryLength = 20; // 1 int for frame type, then 16 bytes for type-specific data
const disposedComponentIdsEntryLength = 4; // Each is an int32 giving the ID
const disposedEventHandlerIdsEntryLength = 8; // Each is an int64 giving the ID
const editsEntryLength = 16; // 4 ints
const stringTableEntryLength = 4; // Each is an int32 giving the string data location, or -1 for null

export class OutOfProcessRenderBatch implements RenderBatch {
  constructor(private batchData: Uint8Array) {
    const stringReader = new OutOfProcessStringReader(batchData);

    this.arrayRangeReader = new OutOfProcessArrayRangeReader(batchData);
    this.arrayBuilderSegmentReader = new OutOfProcessArrayBuilderSegmentReader(batchData);
    this.diffReader = new OutOfProcessRenderTreeDiffReader(batchData);
    this.editReader = new OutOfProcessRenderTreeEditReader(batchData, stringReader);
    this.frameReader = new OutOfProcessRenderTreeFrameReader(batchData, stringReader);
  }

  updatedComponents(): ArrayRange<RenderTreeDiff> {
    return readInt32LE(this.batchData, this.batchData.length - 20); // 5th-from-last int32
  }

  referenceFrames(): ArrayRange<RenderTreeFrame> {
    return readInt32LE(this.batchData, this.batchData.length - 16); // 4th-from-last int32
  }

  disposedComponentIds(): ArrayRange<number> {
    return readInt32LE(this.batchData, this.batchData.length - 12); // 3rd-from-last int32
  }

  disposedEventHandlerIds(): ArrayRange<number> {
    return readInt32LE(this.batchData, this.batchData.length - 8); // 2th-from-last int32
  }

  updatedComponentsEntry(values: ArrayValues<RenderTreeDiff>, index: number): RenderTreeDiff {
    const tableEntryPos = (values as any) + index * updatedComponentsEntryLength;
    return readInt32LE(this.batchData, tableEntryPos);
  }

  referenceFramesEntry(values: ArrayValues<RenderTreeFrame>, index: number): RenderTreeFrame {
    return (values as any) + index * referenceFramesEntryLength as any;
  }

  disposedComponentIdsEntry(values: ArrayValues<number>, index: number): number {
    const entryPos = (values as any) + index * disposedComponentIdsEntryLength;
    return readInt32LE(this.batchData, entryPos);
  }

  disposedEventHandlerIdsEntry(values: ArrayValues<number>, index: number): number {
    const entryPos = (values as any) + index * disposedEventHandlerIdsEntryLength;
    return readUint64LE(this.batchData, entryPos);
  }

  diffReader: RenderTreeDiffReader;

  editReader: RenderTreeEditReader;

  frameReader: RenderTreeFrameReader;

  arrayRangeReader: ArrayRangeReader;

  arrayBuilderSegmentReader: ArrayBuilderSegmentReader;
}

class OutOfProcessRenderTreeDiffReader implements RenderTreeDiffReader {
  constructor(private batchDataUint8: Uint8Array) {
  }

  componentId(diff: RenderTreeDiff) {
    // First int32 is componentId
    return readInt32LE(this.batchDataUint8, diff as any);
  }

  edits(diff: RenderTreeDiff) {
    // Entries data starts after the componentId (which is a 4-byte int)
    return (diff as any + 4);
  }

  editsEntry(values: ArrayValues<RenderTreeEdit>, index: number) {
    return (values as any) + index * editsEntryLength;
  }
}

class OutOfProcessRenderTreeEditReader implements RenderTreeEditReader {
  constructor(private batchDataUint8: Uint8Array, private stringReader: OutOfProcessStringReader) {
  }

  editType(edit: RenderTreeEdit) {
    return readInt32LE(this.batchDataUint8, edit as any); // 1st int
  }

  siblingIndex(edit: RenderTreeEdit) {
    return readInt32LE(this.batchDataUint8, edit as any + 4); // 2nd int
  }

  newTreeIndex(edit: RenderTreeEdit) {
    return readInt32LE(this.batchDataUint8, edit as any + 8); // 3rd int
  }

  moveToSiblingIndex(edit: RenderTreeEdit) {
    return readInt32LE(this.batchDataUint8, edit as any + 8); // 3rd int
  }

  removedAttributeName(edit: RenderTreeEdit) {
    const stringIndex = readInt32LE(this.batchDataUint8, edit as any + 12); // 4th int
    return this.stringReader.readString(stringIndex);
  }
}

class OutOfProcessRenderTreeFrameReader implements RenderTreeFrameReader {
  constructor(private batchDataUint8: Uint8Array, private stringReader: OutOfProcessStringReader) {
  }

  // For render frames, the 2nd-4th ints have different meanings depending on frameType.
  // It's the caller's responsibility not to evaluate properties that aren't applicable to the frameType.

  frameType(frame: RenderTreeFrame) {
    return readInt32LE(this.batchDataUint8, frame as any); // 1st int
  }

  subtreeLength(frame: RenderTreeFrame) {
    return readInt32LE(this.batchDataUint8, frame as any + 4); // 2nd int
  }

  elementReferenceCaptureId(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 4); // 2nd int
    return this.stringReader.readString(stringIndex);
  }

  componentId(frame: RenderTreeFrame) {
    return readInt32LE(this.batchDataUint8, frame as any + 8); // 3rd int
  }

  elementName(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 8); // 3rd int
    return this.stringReader.readString(stringIndex);
  }

  textContent(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 4); // 2nd int
    return this.stringReader.readString(stringIndex);
  }

  markupContent(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 4); // 2nd int
    return this.stringReader.readString(stringIndex)!;
  }

  attributeName(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 4); // 2nd int
    return this.stringReader.readString(stringIndex);
  }

  attributeValue(frame: RenderTreeFrame) {
    const stringIndex = readInt32LE(this.batchDataUint8, frame as any + 8); // 3rd int
    return this.stringReader.readString(stringIndex);
  }

  attributeEventHandlerId(frame: RenderTreeFrame) {
    return readUint64LE(this.batchDataUint8, frame as any + 12); // Bytes 12-19
  }
}

class OutOfProcessStringReader {
  private stringTableStartIndex: number;

  constructor(private batchDataUint8: Uint8Array) {
    // Final int gives start position of the string table
    this.stringTableStartIndex = readInt32LE(batchDataUint8, batchDataUint8.length - 4);
  }

  readString(index: number): string | null {
    if (index === -1) { // Special value encodes 'null'
      return null;
    } else {
      const stringTableEntryPos = readInt32LE(this.batchDataUint8, this.stringTableStartIndex + index * stringTableEntryLength);

      // By default, .NET's BinaryWriter gives LEB128-length-prefixed UTF-8 data.
      // This is convenient enough to decode in JavaScript.
      const numUtf8Bytes = readLEB128(this.batchDataUint8, stringTableEntryPos);
      const charsStart = stringTableEntryPos + numLEB128Bytes(numUtf8Bytes);
      const utf8Data = new Uint8Array(
        this.batchDataUint8.buffer,
        this.batchDataUint8.byteOffset + charsStart,
        numUtf8Bytes
      );
      return decodeUtf8(utf8Data);
    }
  }
}

class OutOfProcessArrayRangeReader implements ArrayRangeReader {
  constructor(private batchDataUint8: Uint8Array) {
  }

  count<T>(arrayRange: ArrayRange<T>) {
    // First int is count
    return readInt32LE(this.batchDataUint8, arrayRange as any);
  }

  values<T>(arrayRange: ArrayRange<T>) {
    // Entries data starts after the 'count' int (i.e., after 4 bytes)
    return arrayRange as any + 4;
  }
}

class OutOfProcessArrayBuilderSegmentReader implements ArrayBuilderSegmentReader {
  constructor(private batchDataUint8: Uint8Array) {
  }

  offset<T>(_arrayBuilderSegment: ArrayBuilderSegment<T>): number {
    // Not used by the out-of-process representation of RenderBatch data.
    // This only exists on the ArrayBuilderSegmentReader for the shared-memory representation.
    return 0;
  }

  count<T>(arrayBuilderSegment: ArrayBuilderSegment<T>) {
    // First int is count
    return readInt32LE(this.batchDataUint8, arrayBuilderSegment as any);
  }

  values<T>(arrayBuilderSegment: ArrayBuilderSegment<T>): ArrayValues<T> {
    // Entries data starts after the 'count' int (i.e., after 4 bytes)
    return arrayBuilderSegment as any + 4;
  }
}

redpajama_set_name: RedPajamaGithub


text:
class LightgunInput
{
public:
    LightgunInput() noexcept;
    LightgunInput(LightgunInput const &) = default;
    LightgunInput(LightgunInput &&) = default;
    ~LightgunInput() = default;

    LightgunInput & operator =(LightgunInput const &) = default;
    LightgunInput & operator =(LightgunInput &&) = default;

    std::int16_t x() const noexcept;
    std::int16_t y() const noexcept;
    bool trigger() const noexcept;
    bool cursor() const noexcept;
    bool turbo() const noexcept;
    bool pause() const noexcept;
    bool start() const noexcept;

    void setPort(unsigned p_port) noexcept { m_port = p_port; }

private:
    unsigned m_port;
};


text:
@import UIKit;

@interface FMViewController : UIViewController

@end


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.WpfPropertyGrid;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Nixxis.Client.Supervisor
{
    [BrowsableProperty("Palette", true)]
    [BrowsableProperty("ShowLabels", true)]
    [BrowsableProperty("ShowValues", true)]
    [BrowsableProperty("Stack100Percent", true)]
    [BrowsableProperty("SwapAxis", true)]
    [BrowsableProperty("UpdateZoomInterval", true)]
    [BrowsableProperty("Format", true)]
    public partial class DashboardWidgetStackedColumns : DashboardWidgetBase
    {

        private bool m_ShowLabels = true;

        private bool m_ShowValues = true;

        private bool m_Stack100Percent = false;

        private string m_Format = null;

        private bool m_SwapAxis = false;

        private int m_UpdateZoomInterval = 30;

        public DashboardWidgetStackedColumns()
        {
            InitializeComponent();
        }

        public override Size SetSize(Size size)
        {
            if (!Stack100Percent)
            {
                double maxZoom = (double)ExtendedPanel.VerticalZoomProperty.DefaultMetadata.DefaultValue;
                ExtendedPanel.SetSharedVerticalZoom(MainItemsControl, maxZoom);
            }

            return base.SetSize(size);
        }
        public override string WidgetName
        {
            get
            {
                return "Stacked columns";
            }
        }

        [Description("Indicates if labels are included")]
        [Category("Appearance")]
        public bool ShowLabels
        {
            get
            {
                return m_ShowLabels;
            }
            set
            {
                m_ShowLabels = value;
                FirePropertyChanged("ShowLabels");
            }
        }

        [Description("Indicates if values are also dispalyed as text")]
        [Category("Appearance")]
        public bool ShowValues
        {
            get
            {
                return m_ShowValues;
            }
            set
            {
                m_ShowValues = value;
                FirePropertyChanged("ShowValues");
            }
        }

        [Description("Indicates if columns are stacked to 100%")]
        [Category("Behavior")]
        public bool Stack100Percent
        {
            get
            {
                return m_Stack100Percent;
            }
            set
            {
                m_Stack100Percent = value;
                FirePropertyChanged("Stack100Percent");
            }
        }

        [Description("Indicates if axis must be swapped")]
        [Category("Behavior")]
        public bool SwapAxis
        {
            get
            {
                return m_SwapAxis;
            }
            set
            {
                m_SwapAxis = value;
                FirePropertyChanged("SwapAxis");
            }
        }

        [Description("Allow specifying the format")]
        [Category("Appearance")]
        public string Format
        {
            get
            {
                return m_Format;
            }
            set
            {
                m_Format = value;
                FirePropertyChanged("Format");
            }
        }

        [Description("Interval in seconds before zooming in")]
        [Category("Behavior")]
        public int UpdateZoomInterval
        {
            get
            {
                return m_UpdateZoomInterval;
            }
            set
            {
                m_UpdateZoomInterval = value;
                FirePropertyChanged("UpdateZoomInterval");
            }
        }

        public override void Timer(int counter)
        {
            if (counter % UpdateZoomInterval == 0)
            {
                if (!Stack100Percent)
                {
                    double maxZoom = (double)ExtendedPanel.VerticalZoomProperty.DefaultMetadata.DefaultValue;

                    double currentZoom = ExtendedPanel.GetSharedVerticalZoom(MainItemsControl) * 1.5;

                    if (currentZoom < maxZoom)
                        ExtendedPanel.SetSharedVerticalZoom(MainItemsControl, currentZoom);
                    else
                        ExtendedPanel.SetSharedVerticalZoom(MainItemsControl, maxZoom);
                }
            }
        }

        public override void ReadXml(System.Xml.XmlReader reader)
        {

            base.ReadXml(reader);

            try
            {
                ShowLabels = System.Xml.XmlConvert.ToBoolean(reader.ReadElementString("ShowLabels"));
                ShowValues = System.Xml.XmlConvert.ToBoolean(reader.ReadElementString("ShowValues"));
                Stack100Percent = System.Xml.XmlConvert.ToBoolean(reader.ReadElementString("Stack100Percent"));
                SwapAxis = System.Xml.XmlConvert.ToBoolean(reader.ReadElementString("SwapAxis"));
                UpdateZoomInterval = System.Xml.XmlConvert.ToInt32(reader.ReadElementString("UpdateZoomInterval"));
                Format = reader.ReadElementString("Format");
            }
            catch
            {
            }

            reader.ReadEndElement();
        }

        public override void WriteXml(System.Xml.XmlWriter writer)
        {
            base.WriteXml(writer);

            writer.WriteElementString("ShowLabels", System.Xml.XmlConvert.ToString(ShowLabels));
            writer.WriteElementString("ShowValues", System.Xml.XmlConvert.ToString(ShowValues));
            writer.WriteElementString("Stack100Percent", System.Xml.XmlConvert.ToString(Stack100Percent));
            writer.WriteElementString("SwapAxis", System.Xml.XmlConvert.ToString(SwapAxis));
            writer.WriteElementString("UpdateZoomInterval", System.Xml.XmlConvert.ToString(UpdateZoomInterval));
            writer.WriteElementString("Format", Format);
        }

    }

}


text:
namespace base {
class TickClock;
}  // namespace base

namespace policy {

class CloudPolicyClient;
class RemoteCommandsFactory;

// Service class which will connect to a CloudPolicyClient in order to fetch
// remote commands from DMServer and send results for executed commands
// back to the server.
class POLICY_EXPORT RemoteCommandsService
    : public RemoteCommandsQueue::Observer {
 public:
  RemoteCommandsService(std::unique_ptr<RemoteCommandsFactory> factory,
                        CloudPolicyClient* client);
  ~RemoteCommandsService() override;

  // Attempts to fetch remote commands, mainly supposed to be called by
  // invalidation service. Note that there will be at most one ongoing fetch
  // request and all other fetch request will be enqueued if another fetch
  // request is in-progress. And in such a case, another request will be made
  // immediately after the current ongoing request finishes.
  // Returns true if the new request was started immediately. Returns false if
  // another request was in progress already and the new request got enqueued.
  bool FetchRemoteCommands();

  // Returns whether a command fetch request is in progress or not.
  bool IsCommandFetchInProgressForTesting() const {
    return command_fetch_in_progress_;
  }

  // Set an alternative clock for testing.
  void SetClockForTesting(std::unique_ptr<base::TickClock> clock);

 private:
  // Helper function to enqueue a command which we get from server.
  void EnqueueCommand(const enterprise_management::RemoteCommand& command);

  // RemoteCommandsQueue::Observer:
  void OnJobStarted(RemoteCommandJob* command) override;
  void OnJobFinished(RemoteCommandJob* command) override;

  // Callback to handle commands we get from the server.
  void OnRemoteCommandsFetched(
      DeviceManagementStatus status,
      const std::vector<enterprise_management::RemoteCommand>& commands);

  // Whether there is a command fetch on going or not.
  bool command_fetch_in_progress_ = false;

  // Whether there is an enqueued fetch request, which indicates there were
  // additional FetchRemoteCommands() calls while a fetch request was ongoing.
  bool has_enqueued_fetch_request_ = false;

  // Command results that have not been sent back to the server yet.
  std::vector<enterprise_management::RemoteCommandResult> unsent_results_;

  // Whether at least one command has finished executing.
  bool has_finished_command_ = false;

  // ID of the latest command which has finished execution if
  // |has_finished_command_| is true. We will acknowledge this ID to the
  // server so that we can re-fetch commands that have not been executed yet
  // after a crash or browser restart.
  RemoteCommandJob::UniqueIDType lastest_finished_command_id_;

  // Collects the IDs of all fetched commands. We need this since the command ID
  // is opaque.
  // IDs will be stored in the order that they are fetched from the server,
  // and acknowledging a command will discard its ID from
  // |fetched_command_ids_|, as well as the IDs of every command before it.
  std::deque<RemoteCommandJob::UniqueIDType> fetched_command_ids_;

  RemoteCommandsQueue queue_;
  std::unique_ptr<RemoteCommandsFactory> factory_;
  CloudPolicyClient* const client_;

  base::WeakPtrFactory<RemoteCommandsService> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(RemoteCommandsService);
};

}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_COMMON_REMOTE_COMMANDS_REMOTE_COMMANDS_SERVICE_H_


text:
Default Tab Component:

Graceful Tab 1

Graceful Tab 2

Graceful Tab 3

      JavaScript expressions can be evaluated as values inside .less files. We recommend using caution with this feature
      as the LESS will not be compilable by ports and it makes the LESS harder to maintain. If possible, try to think of
      a function that can be added to achieve the same purpose and ask for it on github. We have plans to allow
      expanding the default functions available. However, if you still want to use JavaScript in .less, this is done by
      wrapping the expression with back-ticks:

      You can import both CSS and LESS files. Only LESS files import statements are processed, CSS file import
      statements are kept as they are. If you want to import a CSS file, and don't want LESS to process it, just use the
      .css extension:

      Content of imported LESS file is copied into importing style sheet and compiled together with it. Importing and
      imported files share all mixins, namespaces, variables and other structures.

      In addition, if the import statement has media queries specified in it, imported content is enclosed in the @Media
      declaration.

Html Code:

<div class="gui-tab">
 <ul class="tabs">
  <li><a href="#tab1">Graceful Tab 1</a></li>
  <li><a href="#tab2">Graceful Tab 2</a></li>
  <li data-target="#tab3"><a href="#">Graceful Tab 3</a></li>
 </ul>
 <div id="tab1" class="tab-content">
  ...
 </div>
 <div id="tab2" class="tab-content">
  ...
 </div>
 <div id="tab3" class="tab-content">
  ...
 </div>
</div>

Js Code:

$(".gui-tab").guiTab();

Bordered Tab Component:

Graceful Tab 1

Graceful Tab 2

Graceful Tab 3

      Are some elements in your style sheet proportional to other elements? Operations let you add, subtract, divide and
      multiply property values and colors, giving you the power to create complex relationships between properties.
      Operations should only be performed within parentheses in order to ensure compatibility with CSS. Functions map
      one-to-one with JavaScript code, allowing you to manipulate values however you want.

      It is possible to output rules in your CSS which allow tools to locate the source of the rule.

      Either specify the option dumpLineNumbers as above or add !dumpLineNumbers:mediaQuery to the url.

      You can use the "comments" option with FireLESS and the "mediaQuery" option with FireBug/Chrome dev tools (it is
      identical to the SCSS media query debugging format).

      As an extension to CSS, LESS is not only backwards compatible with CSS, but the extra features it adds use
      existing CSS syntax. This makes learning LESS a breeze, and if in doubt, lets you fall back to CSS.

Html Code:

<div class="gui-tab gui-tab-bordered">
 <ul class="tabs">
  <li><a href="#tab11">Graceful Tab 1</a></li>
  <li class="active"><a href="#tab22">Graceful Tab 2</a></li>
  <li><a href="#tab33">Graceful Tab 3</a></li>
 </ul>
 <div id="tab11" class="tab-content">
  ...
 </div>
 <div id="tab22" class="tab-content">
  ...
 </div>
 <div id="tab33" class="tab-content">
  ...
 </div>
</div>

Js Code:

$(".gui-tab").guiTab();


text:
package runtime

import (
	"unsafe"
)

const (
	_MEM_COMMIT   = 0x1000
	_MEM_RESERVE  = 0x2000
	_MEM_DECOMMIT = 0x4000
	_MEM_RELEASE  = 0x8000

	_PAGE_READWRITE = 0x0004
	_PAGE_NOACCESS  = 0x0001
)

//go:nosplit
func sysAlloc(n uintptr, stat *uint64) unsafe.Pointer {
	xadd64(stat, int64(n))
	return unsafe.Pointer(stdcall4(_VirtualAlloc, 0, n, _MEM_COMMIT|_MEM_RESERVE, _PAGE_READWRITE))
}

func sysUnused(v unsafe.Pointer, n uintptr) {
	r := stdcall3(_VirtualFree, uintptr(v), n, _MEM_DECOMMIT)
	if r != 0 {
		return
	}

	// Decommit failed. Usual reason is that we've merged memory from two different
	// VirtualAlloc calls, and Windows will only let each VirtualFree handle pages from
	// a single VirtualAlloc. It is okay to specify a subset of the pages from a single alloc,
	// just not pages from multiple allocs. This is a rare case, arising only when we're
	// trying to give memory back to the operating system, which happens on a time
	// scale of minutes. It doesn't have to be terribly fast. Instead of extra bookkeeping
	// on all our VirtualAlloc calls, try freeing successively smaller pieces until
	// we manage to free something, and then repeat. This ends up being O(n log n)
	// in the worst case, but that's fast enough.
	for n > 0 {
		small := n
		for small >= 4096 && stdcall3(_VirtualFree, uintptr(v), small, _MEM_DECOMMIT) == 0 {
			small /= 2
			small &^= 4096 - 1
		}
		if small < 4096 {
			throw("runtime: failed to decommit pages")
		}
		v = add(v, small)
		n -= small
	}
}

func sysUsed(v unsafe.Pointer, n uintptr) {
	r := stdcall4(_VirtualAlloc, uintptr(v), n, _MEM_COMMIT, _PAGE_READWRITE)
	if r != uintptr(v) {
		throw("runtime: failed to commit pages")
	}

	// Commit failed. See SysUnused.
	for n > 0 {
		small := n
		for small >= 4096 && stdcall4(_VirtualAlloc, uintptr(v), small, _MEM_COMMIT, _PAGE_READWRITE) == 0 {
			small /= 2
			small &^= 4096 - 1
		}
		if small < 4096 {
			throw("runtime: failed to decommit pages")
		}
		v = add(v, small)
		n -= small
	}
}

func sysFree(v unsafe.Pointer, n uintptr, stat *uint64) {
	xadd64(stat, -int64(n))
	r := stdcall3(_VirtualFree, uintptr(v), 0, _MEM_RELEASE)
	if r == 0 {
		throw("runtime: failed to release pages")
	}
}

func sysFault(v unsafe.Pointer, n uintptr) {
	// SysUnused makes the memory inaccessible and prevents its reuse
	sysUnused(v, n)
}

func sysReserve(v unsafe.Pointer, n uintptr, reserved *bool) unsafe.Pointer {
	*reserved = true
	// v is just a hint.
	// First try at v.
	v = unsafe.Pointer(stdcall4(_VirtualAlloc, uintptr(v), n, _MEM_RESERVE, _PAGE_READWRITE))
	if v != nil {
		return v
	}

	// Next let the kernel choose the address.
	return unsafe.Pointer(stdcall4(_VirtualAlloc, 0, n, _MEM_RESERVE, _PAGE_READWRITE))
}

func sysMap(v unsafe.Pointer, n uintptr, reserved bool, stat *uint64) {
	xadd64(stat, int64(n))
	p := stdcall4(_VirtualAlloc, uintptr(v), n, _MEM_COMMIT, _PAGE_READWRITE)
	if p != uintptr(v) {
		throw("runtime: cannot map pages in arena address space")
	}
}


text:
package org.cobbzilla.util.http;

import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;

import static org.cobbzilla.util.io.FileUtil.abs;

@Slf4j
public class PhantomUtil {

    static { WebDriverManager.phantomjs().setup(); }

    // ensures static-initializer above gets run
    public static void init () {}

    private PhantomJSDriver defaultDriver() {
        final DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setJavascriptEnabled(true);
        return new PhantomJSDriver(capabilities);
    }

    public PhantomJSHandle execJs(String script) {
        final PhantomJSDriver driver = defaultDriver();
        final PhantomJSHandle handle = new PhantomJSHandle(driver);
        driver.setErrorHandler(handle);
        driver.executePhantomJS(script);
        return handle;
    }

    public static final String LOAD_AND_EXEC = "var page = require('webpage').create();\n" +
            "page.open('@@URL@@', function() {\n" +
            "  page.evaluateJavaScript('@@JS@@');\n" +
            "});\n";

    public void loadPage (File file) { loadPageAndExec(file, "console.log('successfully loaded "+abs(file)+"')"); }
    public void loadPage(String url) { loadPageAndExec(url, "console.log('successfully loaded "+url+"')"); }

    public void loadPageAndExec(File file, String script) { loadPageAndExec("file://"+abs(file), script); }

    public void loadPageAndExec(String url, String script) {
        execJs(LOAD_AND_EXEC.replace("@@URL@@", url).replace("@@JS@@", script));
    }
}


text:
export ANDROID_HOME=/opt/android-sdk
path=($path $ANDROID_HOME/tools $ANDROID_HOME/platform-tools /home/bryan/Downloads/sbt/bin /home/bryan/.config/bspwm/bin /home/bryan/Projects/Academic-Writing-Check)
export JAVA_HOME=/usr/lib/jvm/default/

PATH="$(ruby -e 'puts Gem.user_dir')/bin:$PATH"

fancy-ctrl-z () {
  if [[ $#BUFFER -eq 0 ]]; then
    fg
    zle redisplay
  else
    zle push-input
    zle clear-screen
  fi
}
zle -N fancy-ctrl-z
bindkey '^Z' fancy-ctrl-z
export LD_LIBRARY_PATH=/home/bryan/Downloads/lib/legacy/ubuntu-12.04/


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--  LegendShop 版权所有 2009-2011,并保留所有权利。 -->
<hibernate-mapping>
    <class name="com.legendshop.model.entity.Myfavorite" table="ls_favorite">
        <id name="id" type="java.lang.String">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="prodId" type="java.lang.Long">
            <column name="prod_id">
                <comment>商品ID</comment>
            </column>
        </property>
        <property name="prodName" type="java.lang.String">
            <column name="prod_name">
                <comment>收藏的商品名称</comment>
            </column>
        </property>
        <property name="addtime" type="java.util.Date">
            <column name="addtime">
                <comment>收藏时间</comment>
            </column>
        </property>
        <property name="userId" type="java.lang.String">
            <column name="user_id">
                <comment>发表人ID</comment>
            </column>
        </property>
        <property name="userName" type="java.lang.String">
            <column name="user_name">
                <comment>用户名称,备用</comment>
            </column>
        </property>
    </class>
</hibernate-mapping>


text:
package poisondog.vfs.webdav;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.vfs2.util.MonitorOutputStream;
import org.apache.jackrabbit.webdav.DavException;

/**
 * @author Adam Huang <poisondog@gmail.com>
 */
public class WebdavOutputStream extends MonitorOutputStream {
	private WebdavFileFactory mFactory;
	private File mTemp;
	private String mUrl;

	public WebdavOutputStream(WebdavFileFactory factory, File temp, String url) throws IOException {
		super(new FileOutputStream(temp));
		mFactory = factory;
		mTemp = temp;
		mUrl = url;
	}

	/**
	 * Called after the stream has been closed.
	 */
	@Override
	protected void onClose() throws IOException {
		try{
			mFactory.put(mTemp, mUrl);
		}catch(DavException e) {
			throw new IOException(e.toString());
		}
	}
}


text:
"""
sentry.web.forms.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from datetime import datetime

import pytz
from django import forms
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.db.models import Q
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _

from sentry import options
from sentry.auth import password_validation
from sentry.app import ratelimiter, newsletter
from sentry.constants import LANGUAGES
from sentry.models import (Organization, OrganizationStatus, User, UserOption, UserOptionValue)
from sentry.security import capture_security_activity
from sentry.utils.auth import find_users, logger
from sentry.web.forms.fields import ReadOnlyTextField
from six.moves import range

def _get_timezone_choices():
    results = []
    for tz in pytz.common_timezones:
        now = datetime.now(pytz.timezone(tz))
        offset = now.strftime('%z')
        results.append((int(offset), tz, '(UTC%s) %s' % (offset, tz)))
    results.sort()

    for i in range(len(results)):
        results[i] = results[i][1:]
    return results

TIMEZONE_CHOICES = _get_timezone_choices()

class AuthenticationForm(forms.Form):
    username = forms.CharField(
        label=_('Account'),
        max_length=128,
        widget=forms.TextInput(attrs={
            'placeholder': _('username or email'),
        }),
    )
    password = forms.CharField(
        label=_('Password'),
        widget=forms.PasswordInput(attrs={
            'placeholder': _('password'),
        }),
    )

    error_messages = {
        'invalid_login':
        _(
            "Please enter a correct %(username)s and password. "
            "Note that both fields may be case-sensitive."
        ),
        'rate_limited':
        _("You have made too many failed authentication "
          "attempts. Please try again later."),
        'no_cookies':
        _(
            "Your Web browser doesn't appear to have cookies "
            "enabled. Cookies are required for logging in."
        ),
        'inactive':
        _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        If request is passed in, the form will validate that cookies are
        enabled. Note that the request (a HttpRequest object) must have set a
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
        running this validation.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        # Set the label for the "username" field.
        UserModel = get_user_model()
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        if not self.fields['username'].label:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean_username(self):
        value = (self.cleaned_data.get('username') or '').strip()
        if not value:
            return
        return value.lower()

    def is_rate_limited(self):
        if self._is_ip_rate_limited():
            return True
        if self._is_user_rate_limited():
            return True
        return False

    def _is_ip_rate_limited(self):
        limit = options.get('auth.ip-rate-limit')
        if not limit:
            return False

        ip_address = self.request.META['REMOTE_ADDR']
        return ratelimiter.is_limited(
            'auth:ip:{}'.format(ip_address),
            limit,
        )

    def _is_user_rate_limited(self):
        limit = options.get('auth.user-rate-limit')
        if not limit:
            return False

        username = self.cleaned_data.get('username')
        if not username:
            return False

        return ratelimiter.is_limited(
            u'auth:username:{}'.format(username),
            limit,
        )

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if not (username and password):
            raise forms.ValidationError(
                self.error_messages['invalid_login'] %
                {'username': self.username_field.verbose_name}
            )

        if self.is_rate_limited():
            logger.info(
                'user.auth.rate-limited',
                extra={
                    'ip_address': self.request.META['REMOTE_ADDR'],
                    'username': username,
                }
            )
            raise forms.ValidationError(self.error_messages['rate_limited'])

        self.user_cache = authenticate(username=username, password=password)
        if self.user_cache is None:
            raise forms.ValidationError(
                self.error_messages['invalid_login'] %
                {'username': self.username_field.verbose_name}
            )

        self.check_for_test_cookie()
        return self.cleaned_data

    def check_for_test_cookie(self):
        if self.request and not self.request.session.test_cookie_worked():
            raise forms.ValidationError(self.error_messages['no_cookies'])

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache

class RegistrationForm(forms.ModelForm):
    name = forms.CharField(
        label=_('Name'),
        max_length=30,
        widget=forms.TextInput(attrs={'placeholder': 'Jane Doe'}),
        required=True
    )
    username = forms.EmailField(
        label=_('Email'),
        max_length=128,
        widget=forms.TextInput(attrs={'placeholder': 'you@example.com'}),
        required=True
    )
    password = forms.CharField(
        required=True, widget=forms.PasswordInput(attrs={'placeholder': 'something super secret'})
    )
    subscribe = forms.BooleanField(
        label=_('Subscribe to product updates newsletter'),
        required=False,
        initial=False,
    )

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        if not newsletter.enabled:
            del self.fields['subscribe']

    class Meta:
        fields = ('username', 'name')
        model = User

    def clean_username(self):
        value = (self.cleaned_data.get('username') or '').strip()
        if not value:
            return
        if User.objects.filter(username__iexact=value).exists():
            raise forms.ValidationError(
                _('An account is already registered with that email address.')
            )
        return value.lower()

    def clean_password(self):
        password = self.cleaned_data['password']
        password_validation.validate_password(password)
        return password

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = user.username
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
            if self.cleaned_data.get('subscribe'):
                newsletter.create_or_update_subscription(user, list_id=newsletter.DEFAULT_LIST_ID)
        return user

class RecoverPasswordForm(forms.Form):
    user = forms.CharField(
        label=_('Account'),
        max_length=128,
        widget=forms.TextInput(attrs={'placeholder': _('username or email')}),
    )

    def clean_user(self):
        value = (self.cleaned_data.get('user') or '').strip()
        if not value:
            return
        users = find_users(value, with_valid_password=False)
        if not users:
            raise forms.ValidationError(_("We were unable to find a matching user."))

        users = [u for u in users if not u.is_managed]
        if not users:
            raise forms.ValidationError(
                _(
                    "The account you are trying to recover is managed and does not support password recovery."
                )
            )

        if len(users) > 1:
            raise forms.ValidationError(
                _("Multiple accounts were found matching this email address.")
            )
        return users[0]

class ChangePasswordRecoverForm(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput())

    def clean_password(self):
        password = self.cleaned_data['password']
        password_validation.validate_password(password)
        return password

class EmailForm(forms.Form):

    alt_email = forms.EmailField(
        label=_('New Email'),
        required=False,
        help_text='Designate an alternative email for this account',
    )

    password = forms.CharField(
        label=_('Current password'),
        widget=forms.PasswordInput(),
        help_text=_('You will need to enter your current account password to make changes.'),
        required=True,
    )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(EmailForm, self).__init__(*args, **kwargs)

        needs_password = user.has_usable_password()

        if not needs_password:
            del self.fields['password']

    def clean_password(self):
        value = self.cleaned_data.get('password')
        if value and not self.user.check_password(value):
            raise forms.ValidationError(_('The password you entered is not correct.'))
        elif not value:
            raise forms.ValidationError(
                _('You must confirm your current password to make changes.')
            )
        return value

class AccountSettingsForm(forms.Form):
    name = forms.CharField(required=True, label=_('Name'), max_length=30)
    username = forms.CharField(label=_('Username'), max_length=128)
    email = forms.EmailField(label=_('Email'))
    new_password = forms.CharField(
        label=_('New password'),
        widget=forms.PasswordInput(),
        required=False,
        # help_text=password_validation.password_validators_help_text_html(),
    )
    verify_new_password = forms.CharField(
        label=_('Verify new password'),
        widget=forms.PasswordInput(),
        required=False,
    )
    password = forms.CharField(
        label=_('Current password'),
        widget=forms.PasswordInput(),
        help_text='You will need to enter your current account password to make changes.',
        required=False,
    )

    def __init__(self, user, request, *args, **kwargs):
        self.user = user
        self.request = request
        super(AccountSettingsForm, self).__init__(*args, **kwargs)

        needs_password = user.has_usable_password()

        if self.user.is_managed:
            # username and password always managed, email and
            # name optionally managed
            for field in ('email', 'name', 'username'):
                if field == 'username' or field in settings.SENTRY_MANAGED_USER_FIELDS:
                    self.fields[field] = ReadOnlyTextField(label=self.fields[field].label)
                if field == 'email':
                    needs_password = False

            del self.fields['new_password']
            del self.fields['verify_new_password']

        # don't show username field if its the same as their email address
        if self.user.email == self.user.username:
            del self.fields['username']

        if not needs_password:
            del self.fields['password']

    def is_readonly(self):
        if self.user.is_managed:
            return set(('email', 'name')) == set(settings.SENTRY_MANAGED_USER_FIELDS)
        return False

    def _clean_managed_field(self, field):
        if self.user.is_managed and (
            field == 'username' or field in settings.SENTRY_MANAGED_USER_FIELDS
        ):
            return getattr(self.user, field)
        return self.cleaned_data[field]

    def clean_email(self):
        value = self._clean_managed_field('email').lower()
        if self.user.email.lower() == value:
            return value
        if User.objects.filter(Q(email__iexact=value) | Q(username__iexact=value)).exclude(
            id=self.user.id
        ).exists():
            raise forms.ValidationError(
                _("There was an error adding %s: that email is already in use") %
                self.cleaned_data['email']
            )
        return value

    def clean_name(self):
        return self._clean_managed_field('name')

    def clean_username(self):
        value = self._clean_managed_field('username')
        if User.objects.filter(username__iexact=value).exclude(id=self.user.id).exists():
            raise forms.ValidationError(_("That username is already in use."))
        return value

    def clean_password(self):
        value = self.cleaned_data.get('password')
        if value and not self.user.check_password(value):
            raise forms.ValidationError('The password you entered is not correct.')
        elif not value and (
            self.cleaned_data.get('email', self.user.email) != self.user.email or
            self.cleaned_data.get('new_password')
        ):
            raise forms.ValidationError('You must confirm your current password to make changes.')
        return value

    def clean_verify_new_password(self):
        new_password = self.cleaned_data.get('new_password')

        if new_password:
            verify_new_password = self.cleaned_data.get('verify_new_password')
            if verify_new_password is None:
                raise forms.ValidationError('You must verify your new password.')

            if new_password != verify_new_password:
                raise forms.ValidationError('Your new password and verify new password must match.')

            return verify_new_password

    def clean_new_password(self):
        new_password = self.cleaned_data.get('new_password')
        if new_password:
            password_validation.validate_password(new_password)
        return new_password

    def save(self, commit=True):
        if self.cleaned_data.get('new_password'):
            self.user.set_password(self.cleaned_data['new_password'])
            self.user.refresh_session_nonce(self.request)

            capture_security_activity(
                account=self.user,
                type='password-changed',
                actor=self.request.user,
                ip_address=self.request.META['REMOTE_ADDR'],
                send_email=True,
            )

        self.user.name = self.cleaned_data['name']

        if self.cleaned_data['email'] != self.user.email:
            new_username = self.user.email == self.user.username
        else:
            new_username = False

        self.user.email = self.cleaned_data['email']

        if self.cleaned_data.get('username'):
            self.user.username = self.cleaned_data['username']
        elif new_username and not User.objects.filter(username__iexact=self.user.email).exists():
            self.user.username = self.user.email

        if commit:
            self.user.save()

        return self.user

class AppearanceSettingsForm(forms.Form):
    language = forms.ChoiceField(
        label=_('Language'),
        choices=LANGUAGES,
        required=False,
        widget=forms.Select(attrs={'class': 'input-xlarge'})
    )
    stacktrace_order = forms.ChoiceField(
        label=_('Stacktrace order'),
        choices=(
            ('-1', _('Default (let Sentry decide)')), ('1', _('Most recent call last')),
            ('2', _('Most recent call first')),
        ),
        help_text=_('Choose the default ordering of frames in stacktraces.'),
        required=False,
        widget=forms.Select(attrs={'class': 'input-xlarge'})
    )
    timezone = forms.ChoiceField(
        label=_('Time zone'),
        choices=TIMEZONE_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'input-xxlarge'})
    )
    clock_24_hours = forms.BooleanField(
        label=_('Use a 24-hour clock'),
        required=False,
    )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(AppearanceSettingsForm, self).__init__(*args, **kwargs)

    def save(self):
        # Save user language
        UserOption.objects.set_value(
            user=self.user,
            key='language',
            value=self.cleaned_data['language'],
        )

        # Save stacktrace options
        UserOption.objects.set_value(
            user=self.user,
            key='stacktrace_order',
            value=self.cleaned_data['stacktrace_order'],
        )

        # Save time zone options
        UserOption.objects.set_value(
            user=self.user,
            key='timezone',
            value=self.cleaned_data['timezone'],
        )

        # Save clock 24 hours option
        UserOption.objects.set_value(
            user=self.user,
            key='clock_24_hours',
            value=self.cleaned_data['clock_24_hours'],
        )

        return self.user

class NotificationReportSettingsForm(forms.Form):
    organizations = forms.ModelMultipleChoiceField(
        queryset=Organization.objects.none(),
        required=False,
        widget=forms.CheckboxSelectMultiple(),
    )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(NotificationReportSettingsForm, self).__init__(*args, **kwargs)

        org_queryset = Organization.objects.filter(
            status=OrganizationStatus.VISIBLE,
            member_set__user=user,
        )

        disabled_orgs = set(
            UserOption.objects.get_value(
                user=user,
                key='reports:disabled-organizations',
                default=[],
            )
        )

        self.fields['organizations'].queryset = org_queryset
        self.fields['organizations'].initial = [
            o.id for o in org_queryset if o.id not in disabled_orgs
        ]

    def save(self):
        enabled_orgs = set((o.id for o in self.cleaned_data.get('organizations')))
        all_orgs = set(self.fields['organizations'].queryset.values_list('id', flat=True))
        UserOption.objects.set_value(
            user=self.user,
            key='reports:disabled-organizations',
            value=list(all_orgs.difference(enabled_orgs)),
        )

class NotificationDeploySettingsForm(forms.Form):
    CHOICES = [
        (UserOptionValue.all_deploys, _('All deploys')),
        (UserOptionValue.committed_deploys_only,
         _('Deploys with your commits')), (UserOptionValue.no_deploys, _('Never'))
    ]

    notifications = forms.ChoiceField(
        choices=CHOICES,
        required=False,
        widget=forms.RadioSelect(),
    )

    def __init__(self, user, organization, *args, **kwargs):
        self.user = user
        self.organization = organization
        super(NotificationDeploySettingsForm, self).__init__(*args, **kwargs)
        self.fields['notifications'].label = ""  # hide the label

        deploy_setting = UserOption.objects.get_value(
            user=user,
            organization=self.organization,
            key='deploy-emails',
            default=UserOptionValue.committed_deploys_only,
        )

        self.fields['notifications'].initial = deploy_setting

    def save(self):
        value = self.data.get('{}-notifications'.format(self.prefix), None)
        if value is not None:
            UserOption.objects.set_value(
                user=self.user,
                organization=self.organization,
                key='deploy-emails',
                value=value,
            )

class NotificationSettingsForm(forms.Form):
    alert_email = forms.EmailField(
        label=_('Email'),
        help_text=_('Designate an alternative email address to send email notifications to.'),
        required=False
    )

    subscribe_by_default = forms.BooleanField(
        label=_('Automatically subscribe to alerts for new projects'),
        help_text=_(
            "When enabled, you'll automatically subscribe to alerts when you create or join a project."
        ),
        required=False,
    )

    workflow_notifications = forms.ChoiceField(
        label=_('Preferred workflow subscription level for new projects'),
        choices=[
            (UserOptionValue.all_conversations, "Receive workflow updates for all issues."),
            (UserOptionValue.participating_only,
             "Receive workflow updates only for issues that I am participating in or have subscribed to."),
            (UserOptionValue.no_conversations, "Never receive workflow updates."),
        ],
        help_text=_("This will be automatically set as your subscription preference when you create or join a project. It has no effect on existing projects."),
        required=False,
    )

    self_notifications = forms.BooleanField(
        label=_('Receive notifications about my own activity'),
        help_text=_(
            'Enable this if you wish to receive emails for your own actions, as well as others.'
        ),
        required=False,
    )

    self_assign_issue = forms.BooleanField(
        label=_('Claim unassigned issues when resolving them'),
        help_text=_(
            "When enabled, you'll automatically be assigned to unassigned issues when marking them as resolved."
        ),
        required=False,
    )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(NotificationSettingsForm, self).__init__(*args, **kwargs)

        self.fields['alert_email'].initial = UserOption.objects.get_value(
            user=self.user,
            key='alert_email',
            default=user.email,
        )
        self.fields['subscribe_by_default'].initial = (
            UserOption.objects.get_value(
                user=self.user,
                key='subscribe_by_default',
                default='1',
            ) == '1'
        )

        self.fields['workflow_notifications'].initial = UserOption.objects.get_value(
            user=self.user,
            key='workflow:notifications',
            default=UserOptionValue.all_conversations,
            project=None,
        )

        self.fields['self_notifications'].initial = UserOption.objects.get_value(
            user=self.user, key='self_notifications', default='0'
        ) == '1'

        self.fields['self_assign_issue'].initial = UserOption.objects.get_value(
            user=self.user, key='self_assign_issue', default='0'
        ) == '1'

    def get_title(self):
        return "General"

    def save(self):
        UserOption.objects.set_value(
            user=self.user,
            key='alert_email',
            value=self.cleaned_data['alert_email'],
        )

        UserOption.objects.set_value(
            user=self.user,
            key='subscribe_by_default',
            value='1' if self.cleaned_data['subscribe_by_default'] else '0',
        )

        UserOption.objects.set_value(
            user=self.user,
            key='self_notifications',
            value='1' if self.cleaned_data['self_notifications'] else '0',
        )

        UserOption.objects.set_value(
            user=self.user,
            key='self_assign_issue',
            value='1' if self.cleaned_data['self_assign_issue'] else '0',
        )

        workflow_notifications_value = self.cleaned_data.get('workflow_notifications')
        if not workflow_notifications_value:
            UserOption.objects.unset_value(
                user=self.user,
                key='workflow:notifications',
                project=None,
            )
        else:
            UserOption.objects.set_value(
                user=self.user,
                key='workflow:notifications',
                value=workflow_notifications_value,
                project=None,
            )

class ProjectEmailOptionsForm(forms.Form):
    alert = forms.BooleanField(required=False)
    workflow = forms.ChoiceField(
        choices=[
            (UserOptionValue.no_conversations, 'Nothing'),
            (UserOptionValue.participating_only, 'Participating'),
            (UserOptionValue.all_conversations, 'Everything'),
        ],
    )
    email = forms.ChoiceField(label="", choices=(), required=False,
                              widget=forms.Select())

    def __init__(self, project, user, *args, **kwargs):
        self.project = project
        self.user = user

        super(ProjectEmailOptionsForm, self).__init__(*args, **kwargs)

        has_alerts = project.is_user_subscribed_to_mail_alerts(user)

        # This allows users who have entered an alert_email value or have specified an email
        # for notifications to keep their settings
        emails = [e.email for e in user.get_verified_emails()]
        alert_email = UserOption.objects.get_value(self.user, 'alert_email')
        specified_email = UserOption.objects.get_value(self.user, 'mail:email', project=project)
        emails.extend([user.email, alert_email, specified_email])

        choices = [(email, email) for email in sorted(set(emails)) if email]

        self.fields['email'].choices = choices

        self.fields['alert'].initial = has_alerts
        self.fields['workflow'].initial = UserOption.objects.get_value(
            user=self.user,
            project=self.project,
            key='workflow:notifications',
            default=UserOption.objects.get_value(
                user=self.user,
                project=None,
                key='workflow:notifications',
                default=UserOptionValue.all_conversations,
            ),
        )
        self.fields['email'].initial = specified_email or alert_email or user.email

    def save(self):
        UserOption.objects.set_value(
            user=self.user,
            key='mail:alert',
            value=int(self.cleaned_data['alert']),
            project=self.project,
        )

        UserOption.objects.set_value(
            user=self.user,
            key='workflow:notifications',
            value=self.cleaned_data['workflow'],
            project=self.project,
        )

        if self.cleaned_data['email']:
            UserOption.objects.set_value(
                user=self.user,
                key='mail:email',
                value=self.cleaned_data['email'],
                project=self.project,
            )
        else:
            UserOption.objects.unset_value(self.user, self.project, 'mail:email')

class TwoFactorForm(forms.Form):
    otp = forms.CharField(
        label=_('One-time password'),
        max_length=20,
        widget=forms.TextInput(
            attrs={
                'placeholder': _('Code from authenticator'),
                'autofocus': True,
            }
        ),
    )

class ConfirmPasswordForm(forms.Form):
    password = forms.CharField(
        label=_('Sentry account password'),
        widget=forms.PasswordInput(),
        help_text='You will need to enter your current Sentry account password to make changes.',
        required=True,
    )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ConfirmPasswordForm, self).__init__(*args, **kwargs)

        needs_password = user.has_usable_password()

        if not needs_password:
            del self.fields['password']

    def clean_password(self):
        value = self.cleaned_data.get('password')
        if value and not self.user.check_password(value):
            raise forms.ValidationError(_('The password you entered is not correct.'))
        elif not value:
            raise forms.ValidationError(
                _('You must confirm your current password to make changes.')
            )
        return value


text:
<?php
if(isset($_POST)){
    $username = "root";
    $password = "kostyaklushkin23";

    $login = $_POST["login"];
    $pass = $_POST["password"];

    try {
        $conn = new PDO('mysql:host=localhost; dbname=test; charset=utf8', $username, $password );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = ("SELECT * FROM users WHERE login='$login' && pass='$pass'");
        $result = $conn->query($stmt);

        $result = $result->fetchColumn();
        if($result==false){
            echo "WRONG PASSWORD OR LOGIN";
        }
        else
        {
            echo "OK";
            setcookie("user", $login, time()+3600,'/');
        }

    }
    catch(PDOException $e)
    {
        echo "Connection failed: " . $e->getMessage();
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Serialized Form (Commons FileUpload 1.2.1 API)
</TITLE>

<META NAME="date" CONTENT="2008-01-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Serialized Form

Package org.apache.commons.fileupload

Class org.apache.commons.fileupload.DefaultFileItem extends DiskFileItem implements Serializable

Class org.apache.commons.fileupload.FileItemStream.ItemSkippedException extends java.io.IOException implements Serializable

serialVersionUID: -7280778431581963740L

Class org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException extends FileUploadBase.SizeException implements Serializable

serialVersionUID: 8150776562029630058L

Class org.apache.commons.fileupload.FileUploadBase.FileUploadIOException extends java.io.IOException implements Serializable

serialVersionUID: -7047616958165584154L

Serialized Fields

cause

FileUploadException cause

The exceptions cause; we overwrite the parent
 classes field, which is available since Java
 1.4 only.

Class org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException extends FileUploadException implements Serializable

serialVersionUID: -9073026332015646668L

Class org.apache.commons.fileupload.FileUploadBase.IOFileUploadException extends FileUploadException implements Serializable

serialVersionUID: 1749796615868477269L

Serialized Fields

cause

java.io.IOException cause

The exceptions cause; we overwrite the parent
 classes field, which is available since Java
 1.4 only.

Class org.apache.commons.fileupload.FileUploadBase.SizeException extends FileUploadException implements Serializable

Serialized Fields

actual

long actual

The actual size of the request.

permitted

long permitted

The maximum permitted size of the request.

Class org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException extends FileUploadBase.SizeException implements Serializable

serialVersionUID: -2474893167098052828L

Class org.apache.commons.fileupload.FileUploadBase.UnknownSizeException extends FileUploadException implements Serializable

serialVersionUID: 7062279004812015273L

Class org.apache.commons.fileupload.FileUploadException extends java.lang.Exception implements Serializable

serialVersionUID: 8881893724388807504L

Serialized Fields

cause

java.lang.Throwable cause

The exceptions cause. We overwrite the cause of
 the super class, which isn't available in Java 1.3.

Class org.apache.commons.fileupload.MultipartStream.IllegalBoundaryException extends java.io.IOException implements Serializable

Class org.apache.commons.fileupload.MultipartStream.MalformedStreamException extends java.io.IOException implements Serializable

Package org.apache.commons.fileupload.disk

Class org.apache.commons.fileupload.disk.DiskFileItem extends java.lang.Object implements Serializable

serialVersionUID: 2237570099615271025L

Serialization Methods

readObject

private void readObject(java.io.ObjectInputStream in)
                 throws java.io.IOException,
                        java.lang.ClassNotFoundException

Reads the state of this object during deserialization.

Throws:

java.io.IOException - if an error occurs.

java.lang.ClassNotFoundException - if class cannot be found.

writeObject

private void writeObject(java.io.ObjectOutputStream out)
                  throws java.io.IOException

Writes the state of this object during serialization.

Throws:

java.io.IOException - if an error occurs.

Serialized Fields

fieldName

java.lang.String fieldName

The name of the form field as provided by the browser.

contentType

java.lang.String contentType

The content type passed by the browser, or null if
 not defined.

isFormField

boolean isFormField

Whether or not this item is a simple form field.

fileName

java.lang.String fileName

The original filename in the user's filesystem.

size

long size

The size of the item, in bytes. This is used to cache the size when a
 file item is moved from its original location.

sizeThreshold

int sizeThreshold

The threshold above which uploads will be stored on disk.

repository

java.io.File repository

The directory in which uploaded files will be stored, if stored on disk.

cachedContent

byte[] cachedContent

Cached contents of the file.

dfosFile

java.io.File dfosFile

File to allow for serialization of the content of this item.

headers

FileItemHeaders headers

The file items headers.

Package org.apache.commons.fileupload.util

Class org.apache.commons.fileupload.util.FileItemHeadersImpl extends java.lang.Object implements Serializable

serialVersionUID: -4455695752627032559L

Serialized Fields

headerNameToValueListMap

java.util.Map headerNameToValueListMap

Map of String keys to a List of
 String instances.

headerNameList

java.util.List headerNameList

List to preserve order of headers as added.  This would not be
 needed if a LinkedHashMap could be used, but don't
 want to depend on 1.4.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright ? 2002-2008 The Apache Software Foundation. All Rights Reserved.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using Sodium;

namespace PoSH_Sodium
{
    [Cmdlet(VerbsCommon.New, "Key")]
    public class GenerateKey : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            var key = new SodiumSymmetricKey()
            {
                KeyType = "Symmetric",
                Key = SecretBox.GenerateKey().ToBase64String()
            };
            WriteObject(key);
        }
    }
}


text:
package ch.shaktipat.saraswati.internal.pobject.aux;

import ch.shaktipat.saraswati.internal.pobject.PersistentObject;

public interface PersistentObjectVisitor
{
	public boolean visit( PersistentObject persistentObject );
}


text:
eSeS is a static cms generator which follows the KISS principle (keept it simple as possible). It's goal is too allow you focus on what really matters for you: your business.

eSeS was born from passion and it is build with passion. It is, and always be an open source project.

eSeS is build in php following the modern patterns and latest PSRs so it can be easily extended which makes it plugin ready.


text:
using Newtonsoft.Json;

namespace ZendeskApi_v2.Models.Topics
{
    public class IndividualTopicResponse
    {
        [JsonProperty("topic")]
        public Topic Topic { get; set; }
    }
}


text:
package user

import (
	"github.com/jeromer/haiconf/haiconf/osutils"
	. "launchpad.net/gocheck"
	"os"
)

type GroupManagerTestSuite struct {
	g *GroupManager
}

var (
	_ = Suite(&GroupManagerTestSuite{})
)

func (s *GroupManagerTestSuite) SetUpTest(c *C) {
	s.g = NewGroupManager()
}

func (s *GroupManagerTestSuite) TestGroupAddCmd(c *C) {
	n := "foo"
	s.g.Name = n

	obtained := s.g.groupAddCmd()
	expected := osutils.SystemCommand{
		Path:                 s.g.groupAddPath,
		Args:                 []string{n},
		ExecDir:              os.TempDir(),
		EnableShellExpansion: true,
	}

	c.Assert(obtained, DeepEquals, expected)
}

func (s *GroupManagerTestSuite) TestGroupDelCmd(c *C) {
	n := "foo"
	s.g.Name = n

	obtained := s.g.groupDelCmd()
	expected := osutils.SystemCommand{
		Path:                 s.g.groupDelPath,
		Args:                 []string{n},
		ExecDir:              os.TempDir(),
		EnableShellExpansion: true,
	}

	c.Assert(obtained, DeepEquals, expected)
}


text:
<?php
/**
 * Abstract Response
 */

namespace Omnipay\Common\Message;

use Omnipay\Common\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\RedirectResponse as HttpRedirectResponse;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

/**
 * Abstract Response
 *
 * This abstract class implements ResponseInterface and defines a basic
 * set of functions that all Omnipay Requests are intended to include.
 *
 * Objects of this class or a subclass are usually created in the Request
 * object (subclass of AbstractRequest) as the return parameters from the
 * send() function.
 *
 * Example -- validating and sending a request:
 *
 *
 *   $myResponse = $myRequest->send();
 *   // now do something with the $myResponse object, test for success, etc.
 *
 *
 * @see ResponseInterface
 */
abstract class AbstractResponse implements ResponseInterface
{

    /**
     * The embodied request object.
     *
     * @var RequestInterface
     */
    protected $request;

    /**
     * The data contained in the response.
     *
     * @var mixed
     */
    protected $data;

    /**
     * Constructor
     *
     * @param RequestInterface $request the initiating request.
     * @param mixed $data
     */
    public function __construct(RequestInterface $request, $data)
    {
        $this->request = $request;
        $this->data = $data;
    }

    /**
     * Get the initiating request object.
     *
     * @return RequestInterface
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isPending()
    {
        return false;
    }

    /**
     * Does the response require a redirect?
     *
     * @return boolean
     */
    public function isRedirect()
    {
        return false;
    }

    /**
     * Is the response a transparent redirect?
     *
     * @return boolean
     */
    public function isTransparentRedirect()
    {
        return false;
    }

    /**
     * Is the transaction cancelled by the user?
     *
     * @return boolean
     */
    public function isCancelled()
    {
        return false;
    }

    /**
     * Get the response data.
     *
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Response Message
     *
     * @return null|string A response message from the payment gateway
     */
    public function getMessage()
    {
        return null;
    }

    /**
     * Response code
     *
     * @return null|string A response code from the payment gateway
     */
    public function getCode()
    {
        return null;
    }

    /**
     * Gateway Reference
     *
     * @return null|string A reference provided by the gateway to represent this transaction
     */
    public function getTransactionReference()
    {
        return null;
    }

    /**
     * Get the transaction ID as generated by the merchant website.
     *
     * @return string
     */
    public function getTransactionId()
    {
        return null;
    }

    /**
     * Gets the redirect target url.
     *
     * @return string
     */
    public function getRedirectUrl()
    {
        return null;
    }

    /**
     * Get the required redirect method (either GET or POST).
     *
     * @return string
     */
    public function getRedirectMethod()
    {
        return 'GET';
    }

    /**
     * Gets the redirect form data array, if the redirect method is POST.
     *
     * @return array
     */
    public function getRedirectData()
    {
        return [];
    }

    /**
     * Automatically perform any required redirect
     *
     * This method is meant to be a helper for simple scenarios. If you want to customize the
     * redirection page, just call the getRedirectUrl() and getRedirectData() methods directly.
     *
     * @return void
     */
    public function redirect()
    {
        $this->getRedirectResponse()->send();
    }

    /**
     * @return HttpRedirectResponse|HttpResponse
     */
    public function getRedirectResponse()
    {
        $this->validateRedirect();

        if ('GET' === $this->getRedirectMethod()) {
            return HttpRedirectResponse::create($this->getRedirectUrl());
        }

        $hiddenFields = '';
        foreach ($this->getRedirectData() as $key => $value) {
            $hiddenFields .= sprintf(
                '<input type="hidden" name="%1$s" value="%2$s" />',
                htmlentities($key, ENT_QUOTES, 'UTF-8', false),
                htmlentities($value, ENT_QUOTES, 'UTF-8', false)
            )."\n";
        }

        $output = '<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Redirecting...</title>

    <form action="%1$s" method="post">

Redirecting to payment page...

            %2$s
            <input type="submit" value="Continue" />

    </form>

';
        $output = sprintf(
            $output,
            htmlentities($this->getRedirectUrl(), ENT_QUOTES, 'UTF-8', false),
            $hiddenFields
        );

        return HttpResponse::create($output);
    }

    /**
     * Validate that the current Response is a valid redirect.
     *
     * @return void
     */
    protected function validateRedirect()
    {
        if (!$this instanceof RedirectResponseInterface || !$this->isRedirect()) {
            throw new RuntimeException('This response does not support redirection.');
        }

        if (empty($this->getRedirectUrl())) {
            throw new RuntimeException('The given redirectUrl cannot be empty.');
        }

        if (!in_array($this->getRedirectMethod(), ['GET', 'POST'])) {
            throw new RuntimeException('Invalid redirect method "'.$this->getRedirectMethod().'".');
        }
    }
}


text:
.. _quickstart:

Quickstart
==========

.. module:: requests.models

Eager to get started? This page gives a good introduction in how to get started
with Requests.

First, make sure that:

* Requests is :ref:`installed <install>`
* Requests is :ref:`up-to-date <updates>`

Let's get started with some simple examples.

Make a Request
--------------

Making a request with Requests is very simple.

Begin by importing the Requests module::

    >>> import requests

Now, let's try to get a webpage. For this example, let's get GitHub's public
timeline::

    >>> r = requests.get('https://api.github.com/events')

Now, we have a :class:`Response <requests.Response>` object called ``r``. We can
get all the information we need from this object.

Requests' simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request::

    >>> r = requests.post('https://httpbin.org/post', data={'key': 'value'})

Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple::

    >>> r = requests.put('https://httpbin.org/put', data={'key': 'value'})
    >>> r = requests.delete('https://httpbin.org/delete')
    >>> r = requests.head('https://httpbin.org/get')
    >>> r = requests.options('https://httpbin.org/get')

That's all well and good, but it's also only the start of what Requests can
do.

Passing Parameters In URLs
--------------------------

You often want to send some sort of data in the URL's query string. If
you were constructing the URL by hand, this data would be given as key/value
pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.
Requests allows you to provide these arguments as a dictionary of strings,
using the ``params`` keyword argument. As an example, if you wanted to pass
``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the
following code::

    >>> payload = {'key1': 'value1', 'key2': 'value2'}
    >>> r = requests.get('https://httpbin.org/get', params=payload)

You can see that the URL has been correctly encoded by printing the URL::

    >>> print(r.url)
    https://httpbin.org/get?key2=value2&key1=value1

Note that any dictionary key whose value is ``None`` will not be added to the
URL's query string.

You can also pass a list of items as a value::

    >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

    >>> r = requests.get('https://httpbin.org/get', params=payload)
    >>> print(r.url)
    https://httpbin.org/get?key1=value1&key2=value2&key2=value3

Response Content
----------------

We can read the content of the server's response. Consider the GitHub timeline
again::

    >>> import requests

    >>> r = requests.get('https://api.github.com/events')
    >>> r.text
    '[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests will automatically decode content from the server. Most unicode
charsets are seamlessly decoded.

When you make a request, Requests makes educated guesses about the encoding of
the response based on the HTTP headers. The text encoding guessed by Requests
is used when you access ``r.text``. You can find out what encoding Requests is
using, and change it, using the ``r.encoding`` property::

    >>> r.encoding
    'utf-8'
    >>> r.encoding = 'ISO-8859-1'

If you change the encoding, Requests will use the new value of ``r.encoding``
whenever you call ``r.text``. You might want to do this in any situation where
you can apply special logic to work out what the encoding of the content will
be. For example, HTML and XML have the ability to specify their encoding in
their body. In situations like this, you should use ``r.content`` to find the
encoding, and then set ``r.encoding``. This will let you use ``r.text`` with
the correct encoding.

Requests will also use custom encodings in the event that you need them. If
you have created your own encoding and registered it with the ``codecs``
module, you can simply use the codec name as the value of ``r.encoding`` and
Requests will handle the decoding for you.

Binary Response Content
-----------------------

You can also access the response body as bytes, for non-text requests::

    >>> r.content
    b'[{"repository":{"open_issues":0,"url":"https://github.com/...

The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.

The ``br``  transfer-encoding is automatically decoded for you if a Brotli library
like `brotli <https://pypi.org/project/brotli>`_ or `brotlicffi <https://pypi.org/project/brotlicffi>`_ is installed.

For example, to create an image from binary data returned by a request, you can
use the following code::

    >>> from PIL import Image
    >>> from io import BytesIO

    >>> i = Image.open(BytesIO(r.content))

JSON Response Content
---------------------

There's also a builtin JSON decoder, in case you're dealing with JSON data::

    >>> import requests

    >>> r = requests.get('https://api.github.com/events')
    >>> r.json()
    [{'repository': {'open_issues': 0, 'url': 'https://github.com/...

In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if
the response gets a 204 (No Content), or if the response contains invalid JSON,
attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception
provides interoperability for multiple exceptions that may be thrown by different
python versions and json serialization libraries.

It should be noted that the success of the call to ``r.json()`` does **not**
indicate the success of the response. Some servers may return a JSON object in a
failed response (e.g. error details with HTTP 500). Such JSON will be decoded
and returned. To check that a request is successful, use
``r.raise_for_status()`` or check ``r.status_code`` is what you expect.

Raw Response Content
--------------------

In the rare case that you'd like to get the raw socket response from the
server, you can access ``r.raw``. If you want to do this, make sure you set
``stream=True`` in your initial request. Once you do, you can do this::

    >>> r = requests.get('https://api.github.com/events', stream=True)

    >>> r.raw
    <urllib3.response.HTTPResponse object at 0x101194810>

    >>> r.raw.read(10)
    '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

In general, however, you should use a pattern like this to save what is being
streamed to a file::

    with open(filename, 'wb') as fd:
        for chunk in r.iter_content(chunk_size=128):
            fd.write(chunk)

Using ``Response.iter_content`` will handle a lot of what you would otherwise
have to handle when using ``Response.raw`` directly. When streaming a
download, the above is the preferred and recommended way to retrieve the
content. Note that ``chunk_size`` can be freely adjusted to a number that
may better fit your use cases.

.. note::

   An important note about using ``Response.iter_content`` versus ``Response.raw``.
   ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``
   transfer-encodings.  ``Response.raw`` is a raw stream of bytes -- it does not
   transform the response content.  If you really need access to the bytes as they
   were returned, use ``Response.raw``.

Custom Headers
--------------

If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the
``headers`` parameter.

For example, we didn't specify our user-agent in the previous example::

    >>> url = 'https://api.github.com/some/endpoint'
    >>> headers = {'user-agent': 'my-app/0.0.1'}

    >>> r = requests.get(url, headers=headers)

Note: Custom headers are given less precedence than more specific sources of information. For instance:

* Authorization headers set with `headers=` will be overridden if credentials
  are specified in ``.netrc``, which in turn will be overridden by the  ``auth=``
  parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,
  or at the path specified by the `NETRC` environment variable.
* Authorization headers will be removed if you get redirected off-host.
* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
* Content-Length headers will be overridden when we can determine the length of the content.

Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.

Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.

More complicated POST requests
------------------------------

Typically, you want to send some form-encoded data — much like an HTML form.
To do this, simply pass a dictionary to the ``data`` argument. Your
dictionary of data will automatically be form-encoded when the request is made::

    >>> payload = {'key1': 'value1', 'key2': 'value2'}

    >>> r = requests.post("https://httpbin.org/post", data=payload)
    >>> print(r.text)
    {
      ...
      "form": {
        "key2": "value2",
        "key1": "value1"
      },
      ...
    }

The ``data`` argument can also have multiple values for each key. This can be
done by making ``data`` either a list of tuples or a dictionary with lists
as values. This is particularly useful when the form has multiple elements that
use the same key::

    >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
    >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
    >>> payload_dict = {'key1': ['value1', 'value2']}
    >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)
    >>> print(r1.text)
    {
      ...
      "form": {
        "key1": [
          "value1",
          "value2"
        ]
      },
      ...
    }
    >>> r1.text == r2.text
    True

There are times that you may want to send data that is not form-encoded. If
you pass in a ``string`` instead of a ``dict``, that data will be posted directly.

For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::

    >>> import json

    >>> url = 'https://api.github.com/some/endpoint'
    >>> payload = {'some': 'data'}

    >>> r = requests.post(url, data=json.dumps(payload))

Please note that the above code will NOT add the ``Content-Type`` header
(so in particular it will NOT set it to ``application/json``).

If you need that header set and you don't want to encode the ``dict`` yourself,
you can also pass it directly using the ``json`` parameter (added in version 2.4.2)
and it will be encoded automatically:

    >>> url = 'https://api.github.com/some/endpoint'
    >>> payload = {'some': 'data'}

    >>> r = requests.post(url, json=payload)

Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.

POST a Multipart-Encoded File
-----------------------------

Requests makes it simple to upload Multipart-encoded files::

    >>> url = 'https://httpbin.org/post'
    >>> files = {'file': open('report.xls', 'rb')}

    >>> r = requests.post(url, files=files)
    >>> r.text
    {
      ...
      "files": {
        "file": "<censored...binary...data>"
      },
      ...
    }

You can set the filename, content_type and headers explicitly::

    >>> url = 'https://httpbin.org/post'
    >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

    >>> r = requests.post(url, files=files)
    >>> r.text
    {
      ...
      "files": {
        "file": "<censored...binary...data>"
      },
      ...
    }

If you want, you can send strings to be received as files::

    >>> url = 'https://httpbin.org/post'
    >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

    >>> r = requests.post(url, files=files)
    >>> r.text
    {
      ...
      "files": {
        "file": "some,data,to,send\\nanother,row,to,send\\n"
      },
      ...
    }

In the event you are posting a very large file as a ``multipart/form-data``
request, you may want to stream the request. By default, ``requests`` does not
support this, but there is a separate package which does -
``requests-toolbelt``. You should read `the toolbelt's documentation
<https://toolbelt.readthedocs.io>`_ for more details about how to use it.

For sending multiple files in one request refer to the :ref:`advanced <advanced>`
section.

.. warning:: It is strongly recommended that you open files in :ref:`binary
             mode <tut-files>`. This is because Requests may attempt to provide
             the ``Content-Length`` header for you, and if it does this value
             will be set to the number of *bytes* in the file. Errors may occur
             if you open the file in *text mode*.

Response Status Codes
---------------------

We can check the response status code::

    >>> r = requests.get('https://httpbin.org/get')
    >>> r.status_code
    200

Requests also comes with a built-in status code lookup object for easy
reference::

    >>> r.status_code == requests.codes.ok
    True

If we made a bad request (a 4XX client error or 5XX server error response), we
can raise it with
:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::

    >>> bad_r = requests.get('https://httpbin.org/status/404')
    >>> bad_r.status_code
    404

    >>> bad_r.raise_for_status()
    Traceback (most recent call last):
      File "requests/models.py", line 832, in raise_for_status
        raise http_error
    requests.exceptions.HTTPError: 404 Client Error

But, since our ``status_code`` for ``r`` was ``200``, when we call
``raise_for_status()`` we get::

    >>> r.raise_for_status()
    None

All is well.

Response Headers
----------------

We can view the server's response headers using a Python dictionary::

    >>> r.headers
    {
        'content-encoding': 'gzip',
        'transfer-encoding': 'chunked',
        'connection': 'close',
        'server': 'nginx/1.0.4',
        'x-runtime': '148ms',
        'etag': '"e1ca502697e5c9317743dc078f67693f"',
        'content-type': 'application/json'
    }

The dictionary is special, though: it's made just for HTTP headers. According to
`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names
are case-insensitive.

So, we can access the headers using any capitalization we want::

    >>> r.headers['Content-Type']
    'application/json'

    >>> r.headers.get('content-type')
    'application/json'

It is also special in that the server could have sent the same header multiple
times with different values, but requests combines them so they can be
represented in the dictionary within a single mapping, as per
`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:

    A recipient MAY combine multiple header fields with the same field name
    into one "field-name: field-value" pair, without changing the semantics
    of the message, by appending each subsequent field value to the combined
    field value in order, separated by a comma.

Cookies
-------

If a response contains some Cookies, you can quickly access them::

    >>> url = 'http://example.com/some/cookie/setting/url'
    >>> r = requests.get(url)

    >>> r.cookies['example_cookie_name']
    'example_cookie_value'

To send your own cookies to the server, you can use the ``cookies``
parameter::

    >>> url = 'https://httpbin.org/cookies'
    >>> cookies = dict(cookies_are='working')

    >>> r = requests.get(url, cookies=cookies)
    >>> r.text
    '{"cookies": {"cookies_are": "working"}}'

Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,
which acts like a ``dict`` but also offers a more complete interface,
suitable for use over multiple domains or paths.  Cookie jars can
also be passed in to requests::

    >>> jar = requests.cookies.RequestsCookieJar()
    >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
    >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
    >>> url = 'https://httpbin.org/cookies'
    >>> r = requests.get(url, cookies=jar)
    >>> r.text
    '{"cookies": {"tasty_cookie": "yum"}}'

Redirection and History
-----------------------

By default Requests will perform location redirection for all verbs except
HEAD.

We can use the ``history`` property of the Response object to track redirection.

The :attr:`Response.history <requests.Response.history>` list contains the
:class:`Response <requests.Response>` objects that were created in order to
complete the request. The list is sorted from the oldest to the most recent
response.

For example, GitHub redirects all HTTP requests to HTTPS::

    >>> r = requests.get('http://github.com/')

    >>> r.url
    'https://github.com/'

    >>> r.status_code
    200

    >>> r.history
    [<Response [301]>]

If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
redirection handling with the ``allow_redirects`` parameter::

    >>> r = requests.get('http://github.com/', allow_redirects=False)

    >>> r.status_code
    301

    >>> r.history
    []

If you're using HEAD, you can enable redirection as well::

    >>> r = requests.head('http://github.com/', allow_redirects=True)

    >>> r.url
    'https://github.com/'

    >>> r.history
    [<Response [301]>]

Timeouts
--------

You can tell Requests to stop waiting for a response after a given number of
seconds with the ``timeout`` parameter. Nearly all production code should use
this parameter in nearly all requests. Failure to do so can cause your program
to hang indefinitely::

    >>> requests.get('https://github.com/', timeout=0.001)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

.. admonition:: Note

    ``timeout`` is not a time limit on the entire response download;
    rather, an exception is raised if the server has not issued a
    response for ``timeout`` seconds (more precisely, if no bytes have been
    received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do
    not time out.

Errors and Exceptions
---------------------

In the event of a network problem (e.g. DNS failure, refused connection, etc),
Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.

:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will
raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request
returned an unsuccessful status code.

If a request times out, a :exc:`~requests.exceptions.Timeout` exception is
raised.

If a request exceeds the configured number of maximum redirections, a
:exc:`~requests.exceptions.TooManyRedirects` exception is raised.

All exceptions that Requests explicitly raises inherit from
:exc:`requests.exceptions.RequestException`.

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

Ready for more? Check out the :ref:`advanced <advanced>` section.

If you're on the job market, consider taking `this programming quiz <https://triplebyte.com/a/b1i2FB8/requests-docs-1>`_. A substantial donation will be made to this project, if you find a job through this platform.


text:
var SerialPort = require('serialport').SerialPort,
    serialPort = new SerialPort('/dev/ttyUSB0', {
        baudrate: 19200
    }),
    Printer = require('thermalprinter'),
    Twitter = require('node-twitter');

var twitterStreamClient = new Twitter.StreamClient(
    '1B5KBUELhN2NY1zuDs0xxyO8p',
    'y6XMwwVVTC3CUaZAEYm1DZWa3FF3XVnKNRXLWlvEA0aEFAeWyn',
    '102975831-9JzJ4wuYfXyUuEww1N6UHUFdsl1W4jkqtgSIsLvr',
    'XnD4yRh6g95FidbRrMZWvJmuG0nH8B06uMytL2EYdrFEE'
);

var keywords = [process.argv[2]] || ['#whitegirlproblems'],
    locations = [process.argv[3]] || null,
    users = [process.argv[4]] || null;

serialPort.on('open',function() {
    var printer = new Printer(serialPort);
    printer.on('ready', function() {
        twitterStreamClient.on('close', function() {
            console.log('Connection closed.');
        });
        twitterStreamClient.on('end', function() {
            console.log('End of Line.');
        });
        twitterStreamClient.on('error', function(error) {
            console.log('Error: ' + (error.code ? error.code + ' ' + error.message : error.message));
        });
        twitterStreamClient.on('tweet', function(tweet) {
            printer.printLine(tweet.text).lineFeed(3).print(function() {
                console.log(tweet);
            });
        });

        twitterStreamClient.start(keywords, locations, users);
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
	<session-factory>
		<property name="connection.driver_class">org.postgresql.Driver</property>
		<property name="connection.url">jdbc:postgresql://localhost:5432/recipes</property>
		<property name="connection.username">postgres</property>
		<property name="connection.password">postgres</property>
		<property name="connection.pool_size">1</property>

		<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

		<property name="hbm2ddl.auto">create</property>
	</session-factory>
</hibernate-configuration>


text:
#pragma once

#include "py/obj.h"

typedef struct {
    mp_obj_base_t base;
    int16_t value;
    int16_t name;
} cp_enum_obj_t;

#define MAKE_ENUM_VALUE(type, prefix, name, value) \
    const cp_enum_obj_t prefix##_##name##_obj = {  \
        { &type }, value, MP_QSTR_##name, \
    }

#define MAKE_ENUM_MAP(name) \
    const mp_rom_map_elem_t name##_locals_table[] =

#define MAKE_ENUM_MAP_ENTRY(prefix, name) \
    { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_PTR(&prefix##_##name##_obj) }

#define MAKE_PRINTER(module, typename) \
    STATIC void typename##_##print(const mp_print_t * print, mp_obj_t self_in, mp_print_kind_t kind) { \
        cp_enum_obj_print_helper(MP_QSTR_##module, print, self_in, kind); \
    }

#define MAKE_ENUM_TYPE(module, type, typename) \
    const mp_obj_type_t typename##_type = { \
        { &mp_type_type }, \
        .name = MP_QSTR_##type, \
        .print = typename##_print, \
        .locals_dict = (mp_obj_dict_t *)&typename##_locals_dict, \
    }

mp_obj_t cp_enum_find(const mp_obj_type_t *type, int value);
int cp_enum_value(const mp_obj_type_t *type, mp_obj_t obj);
void cp_enum_obj_print_helper(uint16_t module, const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind);