file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
source_code_component.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
ngOnChanges(changes: SimpleChanges): void {
if (this.monaco === null) {
return;
}
const editorNewlyCreated = changes['monaco'] && this.editor === null;
if (this.editor === null) {
this.editor = this.monaco.editor.create(
this.codeViewerContainer.nativeElement,
{
... | {
if (this.editor) {
this.editor.layout();
}
} | identifier_body |
expr-copy.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
struct A { a: int }
pub fn main() {
let mut x = A {a: 10};
f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
}
| {
arg.a = 100;
} | identifier_body |
expr-copy.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
} | struct A { a: int }
pub fn main() {
let mut x = A {a: 10}; | random_line_split |
expr-copy.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | { a: int }
pub fn main() {
let mut x = A {a: 10};
f(&mut x);
assert_eq!(x.a, 100);
x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
}
| A | identifier_name |
issue-3794.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
}
| {
s.print();
} | identifier_body |
issue-3794.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | s.print();
}
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
} | fn print_t(t: &T) {
t.print();
}
fn print_s(s: &S) { | random_line_split |
issue-3794.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (s: &S) {
s.print();
}
pub fn main() {
let s: Box<S> = box S { s: 5 };
print_s(&*s);
let t: Box<T> = s as Box<T>;
print_t(&*t);
}
| print_s | identifier_name |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDIN... |
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if !http::should_keep_alive(se... | { &mut self.headers } | identifier_body |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDIN... | .into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let... | ).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap() | random_line_split |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDIN... | (&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new c... | method | identifier_name |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use std::net::Shutdown;
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDIN... |
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers={:... | {
uri.push('?');
uri.push_str(&q[..]);
} | conditional_block |
pl.js | OC.L10N.register(
"systemtags",
{
"Tags" : "Etykiety",
"Tagged files" : "Otagowane pliki",
"Select tags to filter by" : "Wybierz tagi do filtru",
"Please select tags to filter by" : "Proszę wybrać tagi do filtrów",
"No files found for the selected tags" : "Nie znaleziono plików dla wybranych... | "%1$s deleted system tag %2$s" : "%1$s usunięty system etykiet%2$s",
"%1$s updated system tag %3$s to %2$s" : "%1$s zaktualizowany system etykiet%3$s do %2$s",
"%1$s assigned system tag %3$s to %2$s" : "%1$s przypisywalny system etykiet%3$s do %2$s",
"%1$s unassigned system tag %3$s from %2$s" : "%1$s n... | "<strong>System tags</strong> for a file have been modified" : "<strong>System etykiet</strong> dla pliku został zmieniony",
"%1$s assigned system tag %3$s" : "%1$s przypisywalny system etykiet%3$s",
"%1$s unassigned system tag %3$s" : "%1$s nieprzypisany system etykiet%3$s",
"%1$s created system tag %2... | random_line_split |
longRunningTaskWrapper.ts | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
export async function longRunningTaskWrapper<T>({
name,
idForLogging,
task,
suppressErrorDialog,
}: {
name: string;
idForLogging: string;
task: () => Promise<T>;
suppressErrorDialog?: boolean;
}): Promise<T> {
const idL... |
throw error;
}
}
| {
window.log.info(`longRunningTaskWrapper/${idLog}: Showing error dialog`);
// Note: this component uses a portal to render itself into the top-level DOM. No
// need to attach it to the DOM here.
const errorView = new window.Whisper.ReactWrapperView({
className: 'error-modal-wrapper',... | conditional_block |
longRunningTaskWrapper.ts | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
export async function longRunningTaskWrapper<T>({
name,
idForLogging,
task,
suppressErrorDialog,
}: {
name: string;
idForLogging: string;
task: () => Promise<T>;
suppressErrorDialog?: boolean;
}): Promise<T> {
const idL... | // Note: this component uses a portal to render itself into the top-level DOM. No
// need to attach it to the DOM here.
const errorView = new window.Whisper.ReactWrapperView({
className: 'error-modal-wrapper',
Component: window.Signal.Components.ErrorModal,
props: {
... | }
if (!suppressErrorDialog) {
window.log.info(`longRunningTaskWrapper/${idLog}: Showing error dialog`);
| random_line_split |
longRunningTaskWrapper.ts | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
export async function longRunningTaskWrapper<T>({
name,
idForLogging,
task,
suppressErrorDialog,
}: {
name: string;
idForLogging: string;
task: () => Promise<T>;
suppressErrorDialog?: boolean;
}): Promise<T> | // show a spinner until it's done
try {
window.log.info(`longRunningTaskWrapper/${idLog}: Starting task`);
const result = await task();
window.log.info(
`longRunningTaskWrapper/${idLog}: Task completed successfully`
);
if (progressTimeout) {
clearTimeout(progressTimeout);
pr... | {
const idLog = `${name}/${idForLogging}`;
const ONE_SECOND = 1000;
const TWO_SECONDS = 2000;
let progressView: typeof window.Whisper.ReactWrapperView | undefined;
let spinnerStart;
let progressTimeout: NodeJS.Timeout | undefined = setTimeout(() => {
window.log.info(`longRunningTaskWrapper/${idLog}: Cr... | identifier_body |
longRunningTaskWrapper.ts | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
export async function | <T>({
name,
idForLogging,
task,
suppressErrorDialog,
}: {
name: string;
idForLogging: string;
task: () => Promise<T>;
suppressErrorDialog?: boolean;
}): Promise<T> {
const idLog = `${name}/${idForLogging}`;
const ONE_SECOND = 1000;
const TWO_SECONDS = 2000;
let progressView: typeof window.Whisp... | longRunningTaskWrapper | identifier_name |
container_debug_adapter.js | import Ember from 'ember-metal'; // Ember as namespace
import {
A as emberA,
typeOf,
String as StringUtils,
Namespace,
Object as EmberObject
} from 'ember-runtime';
/**
@module ember
@submodule ember-extension-support
*/
/**
The `ContainerDebugAdapter` helps the container and resolver interface
with too... |
Example:
```javascript
Application.initializer({
name: "containerDebugAdapter",
initialize(application) {
application.register('container-debug-adapter:main', require('app/container-debug-adapter'));
}
});
```
@class ContainerDebugAdapter
@namespace Ember
@extends Ember.Object
@s... | * `catalogEntriesByType`
The adapter will need to be registered
in the application's container as `container-debug-adapter:main`. | random_line_split |
container_debug_adapter.js | import Ember from 'ember-metal'; // Ember as namespace
import {
A as emberA,
typeOf,
String as StringUtils,
Namespace,
Object as EmberObject
} from 'ember-runtime';
/**
@module ember
@submodule ember-extension-support
*/
/**
The `ContainerDebugAdapter` helps the container and resolver interface
with too... |
return true;
},
/**
Returns the available classes a given type.
@method catalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route".
@return {Array} An array of strings.
@public
*/
catalogEntriesByType(type) {
let namespaces = emberA(Namespace.NAMESPAC... | {
return false;
} | conditional_block |
container_debug_adapter.js | import Ember from 'ember-metal'; // Ember as namespace
import {
A as emberA,
typeOf,
String as StringUtils,
Namespace,
Object as EmberObject
} from 'ember-runtime';
/**
@module ember
@submodule ember-extension-support
*/
/**
The `ContainerDebugAdapter` helps the container and resolver interface
with too... |
});
| {
let namespaces = emberA(Namespace.NAMESPACES);
let types = emberA();
let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`);
namespaces.forEach(namespace => {
if (namespace !== Ember) {
for (let key in namespace) {
if (!namespace.hasOwnProperty(key)) { continue; }
... | identifier_body |
container_debug_adapter.js | import Ember from 'ember-metal'; // Ember as namespace
import {
A as emberA,
typeOf,
String as StringUtils,
Namespace,
Object as EmberObject
} from 'ember-runtime';
/**
@module ember
@submodule ember-extension-support
*/
/**
The `ContainerDebugAdapter` helps the container and resolver interface
with too... | (type) {
let namespaces = emberA(Namespace.NAMESPACES);
let types = emberA();
let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`);
namespaces.forEach(namespace => {
if (namespace !== Ember) {
for (let key in namespace) {
if (!namespace.hasOwnProperty(key)) { conti... | catalogEntriesByType | identifier_name |
aggregation_cursor.ts | import type { Document } from '../bson';
import type { ExplainVerbosityLike } from '../explain';
import { AggregateOperation, AggregateOptions } from '../operations/aggregate';
import { executeOperation, ExecutionResult } from '../operations/execute_operation';
import type { Topology } from '../sdam/topology';
import t... |
}
| {
assertUninitialized(this);
this[kPipeline].push({ $geoNear });
return this;
} | identifier_body |
aggregation_cursor.ts | import type { Document } from '../bson';
import type { ExplainVerbosityLike } from '../explain';
import { AggregateOperation, AggregateOptions } from '../operations/aggregate';
import { executeOperation, ExecutionResult } from '../operations/execute_operation';
import type { Topology } from '../sdam/topology';
import t... | ($out: { db: string; coll: string } | string): this {
assertUninitialized(this);
this[kPipeline].push({ $out });
return this;
}
/**
* Add a project stage to the aggregation pipeline
*
* @remarks
* In order to strictly type this function you must provide an interface
* that represents the... | out | identifier_name |
aggregation_cursor.ts | import type { Document } from '../bson';
import type { ExplainVerbosityLike } from '../explain';
import { AggregateOperation, AggregateOptions } from '../operations/aggregate';
import { executeOperation, ExecutionResult } from '../operations/execute_operation';
import type { Topology } from '../sdam/topology';
import t... | }
/** Add an out stage to the aggregation pipeline */
out($out: { db: string; coll: string } | string): this {
assertUninitialized(this);
this[kPipeline].push({ $out });
return this;
}
/**
* Add a project stage to the aggregation pipeline
*
* @remarks
* In order to strictly type this... | /** Add a match stage to the aggregation pipeline */
match($match: Document): this {
assertUninitialized(this);
this[kPipeline].push({ $match });
return this; | random_line_split |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those o... | () {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 {
println!("Usage: png2icns <path> [<ostype>]");
return;
}
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect(... | main | identifier_name |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those o... | png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
} | png_path.with_extension(format!("{}.icns", ostype))
} else {
family.add_icon(&image).expect("failed to encode image"); | random_line_split |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those o... |
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("failed to open PNG file"));
let image = Image::read_png(png_file).expect("failed to read PNG file");
let mut family = IconFamily::new();
let icns_... | {
println!("Usage: png2icns <path> [<ostype>]");
return;
} | conditional_block |
png2icns.rs | //! Creates an ICNS file containing a single image, read from a PNG file.
//!
//! To create an ICNS file from a PNG, run:
//!
//! ```shell
//! cargo run --example png2icns <path/to/file.png>
//! # ICNS will be saved to path/to/file.icns
//! ```
//!
//! Note that the dimensions of the input image must be exactly those o... | family.add_icon(&image).expect("failed to encode image");
png_path.with_extension("icns")
};
let icns_file = BufWriter::new(File::create(icns_path)
.expect("failed to create ICNS file"));
family.write(icns_file).expect("failed to write ICNS file");
}
| {
let num_args = env::args().count();
if num_args < 2 || num_args > 3 {
println!("Usage: png2icns <path> [<ostype>]");
return;
}
let png_path = env::args().nth(1).unwrap();
let png_path = Path::new(&png_path);
let png_file = BufReader::new(File::open(png_path)
.expect("fa... | identifier_body |
latex_directory_1_2.py | #!/usr/bin/env python
"Module to aggregate all pdf figures of a directory \
into a single latex file, and compile it."
from __future__ import division, print_function
import os
import sys
import re
from optparse import OptionParser
_VERSION = '1.0'
def latex_dir(outfile_name, directory, column=2, eps=False):
"Pr... |
latex_dir(outfile_name, directory, options.column, eps=options.eps)
#compile the tex file
if options.eps:
os.execlp('latex', 'latex', '-interaction=nonstopmode',
'-output-directory', directory, outfile_name)
else:
os.execlp('pdflatex', 'pdfl... | print("invalid number of columns")
parser.print_help()
exit(5) | conditional_block |
latex_directory_1_2.py | #!/usr/bin/env python
"Module to aggregate all pdf figures of a directory \
into a single latex file, and compile it."
from __future__ import division, print_function
import os
import sys
import re
from optparse import OptionParser
_VERSION = '1.0'
def latex_dir(outfile_name, directory, column=2, eps=False):
| \setlength{\headheight}{12.0pt}
%%\setlength{\headsep}{0.0in}
%%\setlength{\textwidth}{7.43in}
\setlength{\textwidth}{7.10in}
%%\setlength{\textwidth}{6in}
\setlength{\hoffset}{-0.4in}
\setlength{\columnsep}{0.25in}
\setlength{\oddsidemargin}{0.0in}
\setlength{\evensidemargin}{0.0in}
%% more than .95 of text and fig... | "Print latex source file"
print(directory)
with open(outfile_name, 'w') as outfile:
outfile.write(r"""\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage{fancyhdr}
\def\goodgap{\hspace{\subfigtopskip}\hspace{\subfigbottomskip}}
\usepackage%(include_pdf_packa... | identifier_body |
latex_directory_1_2.py | #!/usr/bin/env python
"Module to aggregate all pdf figures of a directory \
into a single latex file, and compile it."
from __future__ import division, print_function
import os
import sys | _VERSION = '1.0'
def latex_dir(outfile_name, directory, column=2, eps=False):
"Print latex source file"
print(directory)
with open(outfile_name, 'w') as outfile:
outfile.write(r"""\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage{fancyhdr}
\def\goodgap{... | import re
from optparse import OptionParser
| random_line_split |
latex_directory_1_2.py | #!/usr/bin/env python
"Module to aggregate all pdf figures of a directory \
into a single latex file, and compile it."
from __future__ import division, print_function
import os
import sys
import re
from optparse import OptionParser
_VERSION = '1.0'
def | (outfile_name, directory, column=2, eps=False):
"Print latex source file"
print(directory)
with open(outfile_name, 'w') as outfile:
outfile.write(r"""\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage{fancyhdr}
\def\goodgap{\hspace{\subfigtopskip}\hspace{... | latex_dir | identifier_name |
emission.py | # -*- coding: utf-8 -*-
"""
Python module for generating fake total emission in a magnitude band along a sightline.
This uses the Arepo/Illustris output GFM_Photometrics to get photometric band data,
which may or may not be accurate.
"""
from __future__ import print_function
import math
import os.path as path
import ... |
def get_emflux(self, band, pixelsz=1):
"""
Get the density weighted flux in each pixel for a given species.
band: rest-frame optical band observed in
pixelsz: Angular size of the pixels in arcseconds
"""
#Mapping from bandname to number
dist = distance(pixel... | """Read the particle data for a single interpolation"""
bands = {'U':0, 'B':1, 'V':2,'K':3,'g':4,'r':5,'i':6,'z':7}
nband = bands[band]
pos = self.snapshot_set.get_data(4,"Position", segment = fn).astype(np.float32)
#Set each stellar radius to the pixel size
hh = hhmult*np.ones(n... | identifier_body |
emission.py | # -*- coding: utf-8 -*-
"""
Python module for generating fake total emission in a magnitude band along a sightline.
This uses the Arepo/Illustris output GFM_Photometrics to get photometric band data,
which may or may not be accurate.
"""
from __future__ import print_function
import math
import os.path as path
import ... |
pos = pos[ind,:]
hh = hh[ind]
#Find the magnitude of stars in this band
emflux = maginJy(self.snapshot_set.get_data(4,"GFM_StellarPhotometrics", segment = fn).astype(np.float32)[ind][:,nband],band)
fluxx = np.array([ np.sum(emflux[self.particles_near_lines(pos, hh,np.array([ax,]... | raise ValueError("No stars") | conditional_block |
emission.py | # -*- coding: utf-8 -*-
"""
Python module for generating fake total emission in a magnitude band along a sightline.
This uses the Arepo/Illustris output GFM_Photometrics to get photometric band data,
which may or may not be accurate.
"""
from __future__ import print_function
import math
import os.path as path
import ... | (arcsec, redshift, hubble, OmegaM):
"""Find the size of something in comoving kpc/h from the size on the sky in arcseconds.
"""
#First arcsec to radians
#2 pi radians -> degrees -> arcminute -> arcsecond
rad = 2*math.pi/360./60./60. * arcsec
#Then to physical kpc
atime = 1./(1+redshift)
... | distance | identifier_name |
emission.py | # -*- coding: utf-8 -*-
"""
Python module for generating fake total emission in a magnitude band along a sightline. | This uses the Arepo/Illustris output GFM_Photometrics to get photometric band data,
which may or may not be accurate.
"""
from __future__ import print_function
import math
import os.path as path
import shutil
import h5py
import numpy as np
from . import spectra as ss
def maginJy(mag, band):
"""Convert a magnitud... | random_line_split | |
margin.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import DEFAULT_RULES_AND_PAGE %>
${helpers.fo... | "scroll-margin",
"scroll-margin-%s",
"specified::Length::parse",
engines="gecko",
spec="https://drafts.csswg.org/css-scroll-snap-1/#propdef-scroll-margin",
)}
${helpers.two_properties_shorthand(
"scroll-margin-block",
"scroll-margin-block-start",
"scroll-margin-block-end",
"specifie... | ${helpers.four_sides_shorthand( | random_line_split |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn | () -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
... | main | identifier_name |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
... |
// Soldier - walk animation
let mut source_rect_2 = Rect::new(0, 64, sprite_tile_size.0, sprite_tile_size.0);
let mut dest_rect_2 = Rect::new(0, 64, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_2.center_on(Point::new(440, 360));
let mut running = true;
while running {
for... | let mut dest_rect_1 = Rect::new(0, 32, sprite_tile_size.0 * 4, sprite_tile_size.0 * 4);
dest_rect_1.center_on(Point::new(0, 240)); | random_line_split |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use std::time::Duration;
fn main() -> Result<(), String> |
let mut event_pump = sdl_context.event_pump()?;
// animation sheet and extras are available from
// https://opengameart.org/content/a-platformer-in-the-forest
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?;
let texture = texture_creator
.create_tex... | {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2", 640, 480)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window
.into_canvas()
.accelerated()
... | identifier_body |
replicationControllersMock.js | (function() {
'use strict';
angular.module('replicationControllers', [])
.service('replicationControllerService', ['$q', ReplicationControllerDataService]);
/**
* Replication Controller DataService
* Mock async data service.
*
* @returns {{loadAll: Function}}
* @constructor
*/
function... | ($q) {
var replicationControllers = {
"kind": "List",
"apiVersion": "v1",
"metadata": {},
"items": [
{
"kind": "ReplicationController",
"apiVersion": "v1",
"metadata": {
"name": "redis-master",
"namespace": "default",
... | ReplicationControllerDataService | identifier_name |
replicationControllersMock.js | (function() {
'use strict';
angular.module('replicationControllers', [])
.service('replicationControllerService', ['$q', ReplicationControllerDataService]);
/**
* Replication Controller DataService
* Mock async data service.
*
* @returns {{loadAll: Function}}
* @constructor
*/
function... | "selector": {
"name": "redis-master"
},
"template": {
"metadata": {
"creationTimestamp": null,
"labels": {
"name": "redis-master"
}
... | "spec": {
"replicas": 1, | random_line_split |
replicationControllersMock.js | (function() {
'use strict';
angular.module('replicationControllers', [])
.service('replicationControllerService', ['$q', ReplicationControllerDataService]);
/**
* Replication Controller DataService
* Mock async data service.
*
* @returns {{loadAll: Function}}
* @constructor
*/
function... | "spec": {
"replicas": 1,
"selector": {
"name": "redis-master"
},
"template": {
"metadata": {
"creationTimestamp": null,
"labels": {
... | {
var replicationControllers = {
"kind": "List",
"apiVersion": "v1",
"metadata": {},
"items": [
{
"kind": "ReplicationController",
"apiVersion": "v1",
"metadata": {
"name": "redis-master",
"namespace": "default",
... | identifier_body |
extract_images.py | from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import decompress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export functi... | (filepath):
lines = open(filepath, 'rb')
while True:
# clever trick!
# when next() raises StopIteration, it stops this generator too
line = next(lines)
if not line.startswith(b'DEFINE '):
continue
_, kind, number = line.split()
kind = kind.decode('ascii')
number = int(number)
r... | parse_images | identifier_name |
extract_images.py | from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import decompress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export functi... | turtle.penup()
else:
turtle.setpos(pos)
turtle.pendown()
turtle.dot(size=10)
_input('Press enter to continue')
turtle.clear()
turtle.bye()
if __name__ == '__main__':
main()
| ap = ArgumentParser()
ap.add_argument('--speed', type=int, default=10,
help='Number 1-10 for drawing speed, or 0 for no added delay')
ap.add_argument('program')
args = ap.parse_args()
for kind, number, path in parse_images(args.program):
title = '%s #%d, path length %d' % (kind, number, p... | identifier_body |
extract_images.py | from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import decompress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export functi... | turtle.title(title)
turtle.speed(args.speed)
turtle.setworldcoordinates(0, 655.36, 655.36, 0)
turtle.pen(shown=False, pendown=False, pensize=10)
for i,pos in enumerate(path):
if pen_up[i]:
turtle.penup()
else:
turtle.setpos(pos)
turtle.pendown()
turtle.dot... | if not path.size:
continue
pen_up = (path==0).all(axis=1)
# convert from path (0 to 65536) to turtle coords (0 to 655.36)
path = path / 100. | random_line_split |
extract_images.py | from __future__ import print_function
import numpy as np
import turtle
from argparse import ArgumentParser
from base64 import decodestring
from zlib import decompress
# Python 2/3 compat
try:
_input = raw_input
except NameError:
_input = input
'''TODO:
* add a matplotlib-based plotter
* add a path export functi... |
_input('Press enter to continue')
turtle.clear()
turtle.bye()
if __name__ == '__main__':
main()
| turtle.setpos(pos)
turtle.pendown()
turtle.dot(size=10) | conditional_block |
component.ts | import {Component} from '@angular/core';
import {Location} from '@angular/common';
import {RouteParams} from '@angular/router-deprecated';
import {BlogService} from '../../../../data/fixtures/blog-service';
import {Blog} from '../../../../data/models/blog';
import {MetaData} from 'app/services/metadata'
import {ROUTER_... | () {
this.listExpanded = !this.listExpanded;
}
Select(b: Blog) {
this.blog = b;
this.loc.go(`blogs/${b.id}`);
// Set metadata
this.metadata.setTitle(`${b.title} | Evan Kirsch`);
this.metadata.setMeta('keywords', b.content.tags);
this.metadata.setMeta('description', b... | drawerClick | identifier_name |
component.ts | import {Component} from '@angular/core';
import {Location} from '@angular/common';
import {RouteParams} from '@angular/router-deprecated';
import {BlogService} from '../../../../data/fixtures/blog-service';
import {Blog} from '../../../../data/models/blog';
import {MetaData} from 'app/services/metadata'
import {ROUTER_... |
DisplayState(): string {
if (this.listExpanded) {
return "expanded";
}
return "collapsed";
}
}
| {
if (this.listExpanded) {
return "is-active";
}
return "is-inactive";
} | identifier_body |
component.ts | import {Component} from '@angular/core';
import {Location} from '@angular/common';
import {RouteParams} from '@angular/router-deprecated';
import {BlogService} from '../../../../data/fixtures/blog-service';
import {Blog} from '../../../../data/models/blog';
import {MetaData} from 'app/services/metadata'
import {ROUTER_... |
return "is-inactive";
}
DisplayState(): string {
if (this.listExpanded) {
return "expanded";
}
return "collapsed";
}
}
| {
return "is-active";
} | conditional_block |
component.ts | import {Component} from '@angular/core';
import {Location} from '@angular/common';
import {RouteParams} from '@angular/router-deprecated';
import {BlogService} from '../../../../data/fixtures/blog-service';
import {Blog} from '../../../../data/models/blog';
import {MetaData} from 'app/services/metadata'
import {ROUTER_... | // Set metadata
this.metadata.setTitle(`${b.title} | Evan Kirsch`);
this.metadata.setMeta('keywords', b.content.tags);
this.metadata.setMeta('description', b.shortContent);
if (this.IsMobileDisplay()) {
this.listExpanded = false;
}
}
ListState(): string {
if (... |
Select(b: Blog) {
this.blog = b;
this.loc.go(`blogs/${b.id}`);
| random_line_split |
discreteBarChart.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Examples for Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
""" |
from nvd3 import discreteBarChart
#Open File for test
output_file = open('test_discreteBarChart.html', 'w')
type = "discreteBarChart"
chart = discreteBarChart(name='mygraphname', height=400, width=600)
chart.set_containerheader("\n\n<h2>" + type + "</h2>\n\n")
xdata = ["A", "B", "C", "D", "E", "F", "G"]
ydata = [3,... | random_line_split | |
match-pipe-binding.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
}
fn test5() {
match (1, 2, 3) {
(1, ref a, ref b) | ... | (1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2); | random_line_split |
match-pipe-binding.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ,
_ => panic!(),
}
}
pub fn main() {
test1();
test2();
test3();
test4();
test5();
}
| {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
} | conditional_block |
match-pipe-binding.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
((1, a), (2, b)) | ((2, b), (1, a)) => {
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
_ => panic!(),
}
}
fn test2() {
match (1, 2, 3) {
... | test1 | identifier_name |
match-pipe-binding.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test3() {
match (1, 2, 3) {
(1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
_ => panic!(),
}
}
fn test4() {
match (1, 2, 3) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
asser... | {
match (1, 2, 3) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
},
_ => panic!(),
}
} | identifier_body |
startup.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divis... |
else:
import fcntl
fcntl.lockf(self.fp, fcntl.LOCK_UN)
if os.path.isfile(self.lockfile):
os.unlink(self.lockfile)
except Exception as e:
Log.warning("Problem with SingleInstance __del__()", e)
sys.exit(-1)
| os.close(self.fd)
os.unlink(self.lockfile) | conditional_block |
startup.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divis... | def __del__(self):
temp, self.initialized = self.initialized, False
if not temp:
return
try:
if sys.platform == "win32":
if hasattr(self, "fd"):
os.close(self.fd)
os.unlink(self.lockfile)
else:
... |
def __exit__(self, type, value, traceback):
self.__del__()
| random_line_split |
startup.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divis... |
def argparse(defs, complain=True):
parser = _ArgParser()
for d in listwrap(defs):
args = d.copy()
name = args.name
args.name = None
parser.add_argument(*unwrap(listwrap(name)), **args)
namespace, unknown = parser.parse_known_args()
if unknown and complain:
Log.... | Log.error("argparse error: {{error}}", error=message) | identifier_body |
startup.py | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divis... | (self):
temp, self.initialized = self.initialized, False
if not temp:
return
try:
if sys.platform == "win32":
if hasattr(self, "fd"):
os.close(self.fd)
os.unlink(self.lockfile)
else:
impor... | __del__ | identifier_name |
company-card.component.ts | import {
Component, Input, OnInit, ChangeDetectionStrategy,
trigger, state, style, transition, animate
} from '@angular/core';
import { ICompany } from '_models/_gen/modelInterfaces';
import { TrackByService } from 'core/services/trackby.service';
import 'style-loader!./company-card.component.scss';
@Compone... | {
}
}
| OnInit() | identifier_name |
company-card.component.ts | import {
Component, Input, OnInit, ChangeDetectionStrategy,
trigger, state, style, transition, animate
} from '@angular/core';
import { ICompany } from '_models/_gen/modelInterfaces';
import { TrackByService } from 'core/services/trackby.service';
import 'style-loader!./company-card.component.scss';
@Compone... |
@Input() companies: ICompany[] = [];
constructor(private trackbyService: TrackByService) { }
ngOnInit() {
}
} | })
export class CompaniesCardComponent implements OnInit { | random_line_split |
company-card.component.ts | import {
Component, Input, OnInit, ChangeDetectionStrategy,
trigger, state, style, transition, animate
} from '@angular/core';
import { ICompany } from '_models/_gen/modelInterfaces';
import { TrackByService } from 'core/services/trackby.service';
import 'style-loader!./company-card.component.scss';
@Compone... | }
|
}
| identifier_body |
aiplatform_generated_aiplatform_v1_dataset_service_list_annotations_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# Handle the response
for response in page_result:
print(response)
# [END aiplatform_generated_aiplatform_v1_DatasetService_ListAnnotations_sync] | parent="parent_value",
)
# Make the request
page_result = client.list_annotations(request=request) | random_line_split |
aiplatform_generated_aiplatform_v1_dataset_service_list_annotations_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ():
# Create a client
client = aiplatform_v1.DatasetServiceClient()
# Initialize request argument(s)
request = aiplatform_v1.ListAnnotationsRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_annotations(request=request)
# Handle the response
for... | sample_list_annotations | identifier_name |
aiplatform_generated_aiplatform_v1_dataset_service_list_annotations_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [END aiplatform_generated_aiplatform_v1_DatasetService_ListAnnotations_sync]
| client = aiplatform_v1.DatasetServiceClient()
# Initialize request argument(s)
request = aiplatform_v1.ListAnnotationsRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_annotations(request=request)
# Handle the response
for response in page_result:
... | identifier_body |
aiplatform_generated_aiplatform_v1_dataset_service_list_annotations_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [END aiplatform_generated_aiplatform_v1_DatasetService_ListAnnotations_sync]
| print(response) | conditional_block |
getMethod.js | /*
module ในการเก็บ route ใน เมธอด GET
*/
var fs = require('fs');
var path = require('path');
var getRoutes = {};
getRoutes['/'] = require('./get/index.js').getPage;
getRoutes['/level'] = require('./get/level.js').getPage;
getRoutes['/play'] = require('./get/play.js').getPage;
getRoutes['Error 404'] = (req, res) ... | 'Content-Length': data.length
});
res.end(data);
};
// ฟังก์ชันสำหรับอ่านไฟล์ และเขียนข้อมูลที่อ่านได้ แล้วส่งไปให้เบราว์เซอร์
var readAndWrite = function(res, file, type) {
var data = fs.readFileSync(file);
res.writeHead(200, {
'Content-Type': type,
'Content-Length': data.length
});
res.end(da... | var data = '<h1>Error 404 : ' + req.url + ' not found!!</h1>';
res.writeHead(404, {
'Content-Type': 'text/html', | random_line_split |
ScrollStrategy.js | /**
enyo.ScrollStrategy is a helper kind which implements a default scrolling strategy for an <a href="#enyo.Scroller">enyo.Scroller</a>.
enyo.ScrollStrategy is not typically created in application code.
*/
enyo.kind({
name: "enyo.ScrollStrategy",
noDom: true,
events: {
onScroll: "doScroll"
},
published: {
... | },
setScrollLeft: function(inLeft) {
this.scrollLeft = inLeft;
if (this.scrollNode) {
this.scrollNode.scrollLeft = this.scrollLeft;
}
},
getScrollLeft: function() {
return this.scrollNode ? this.scrollNode.scrollLeft : this.scrollLeft;
},
getScrollTop: function() {
return this.scrollNode ? this.scroll... | this.scrollNode.scrollTop = this.scrollTop;
}
| conditional_block |
ScrollStrategy.js | /**
enyo.ScrollStrategy is a helper kind which implements a default scrolling strategy for an <a href="#enyo.Scroller">enyo.Scroller</a>.
enyo.ScrollStrategy is not typically created in application code.
*/
enyo.kind({
name: "enyo.ScrollStrategy",
noDom: true,
events: {
onScroll: "doScroll"
},
published: {
... | // NOTE: mobile native scrollers need touchmove. Indicate this by
// setting the requireTouchmove property to true (must do this in move event
// because must respond to first move or native action fails).
move: function(inSender, inEvent) {
var dy = inEvent.pageY - this.downY;
var dx = inEvent.pageX - this.d... | this.downX = inEvent.pageX;
this.canVertical = sb.maxTop > 0 && this.vertical != "hidden";
this.canHorizontal = sb.maxLeft > 0 && this.horizontal != "hidden";
}, | random_line_split |
constants.py | from datetime import date, time
NO_TITLE = u"__NO_TITLE__"
NO_AUTHOR_NAME = 'None'
NO_CATEGORY_NAME = 'None'
NON_EXISTENT_ARTICLE_TITLE = 'NON_EXISTENT'
NO_DATE = date(1970, 01, 01)
NO_TIME = time(0, 0) | GHOST_LINK_TITLE = u"__GHOST_LINK__"
GHOST_LINK_URL = u"__GHOST_LINK__"
PAYWALLED_CONTENT = u"__PAYWALLED__"
RENDERED_STORIFY_TITLE = u"__RENDERED_STORIFY__"
RENDERED_TWEET_TITLE = u"__RENDERED_TWEET__"
EMBEDDED_VIDEO_TITLE = u"__EMBEDDED_VIDEO_TITLE__"
EMBEDDED_VIDEO_URL = u"__EMBEDDED_VIDEO_URL__" | NO_URL = u"__NO_URL__"
UNFINISHED_TAG = u"unfinished"
GHOST_LINK_TAG = u"ghost link" | random_line_split |
exampleSelector.js | const createImmutableEqualsSelector = require('./customSelectorCreator');
const compare = require('../util/compare');
const exampleReducers = require('../reducers/exampleReducers');
/**
* Get state function
*/
const getSortingState = exampleReducers.getSortingState;
const getPaginationState = exampleReducers.getPagi... |
module.exports = paginationSelector; | ],
(sortedData, paginationCondition) => pagination(sortedData, paginationCondition.get('start'), paginationCondition.get('end'))
) | random_line_split |
traits.rs | // Copyright 2015 The Ramp Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations und... | // http://www.apache.org/licenses/LICENSE-2.0
// | random_line_split |
url_scraper_dict.py | UL_CATEGORY_LI = '//ul[@class="category"]/li'
H2_A_TITLELINK = './h2/a[@class="titlelink"]'
SPAN_A_TITLELINK = './span/a[@class="titlelink"]' | """Mapping of relative URL (for EOPSS pages) to the xpath needed
to extract documents (1st xpath for section, 2nd xpath for document link)
"""
MASSGOV_DICT = {
'homeland-sec/grants/docs/':
[
UL_CATEGORY_LI,
'./h2/span/a[@class="titlelink"]'
],
... | DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield")]/p'
CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ]
BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ]
| random_line_split |
message_widget.py | from __future__ import absolute_import, division, print_function
import os
from time import ctime
from qtpy import QtWidgets
from glue import core
from glue.utils.qt import load_ui
class MessageWidget(QtWidgets.QWidget, core.hub.HubListener):
""" This simple class displays all messages broadcast
by a hub. I... | row = self.ui.messageTable.rowCount() * 0
self.ui.messageTable.insertRow(0)
tm = QtWidgets.QTableWidgetItem(ctime().split()[3])
typ = str(type(message)).split("'")[-2].split('.')[-1]
mtyp = QtWidgets.QTableWidgetItem(typ)
typ = str(type(message.sender)).split("'")[-2].split('.')[... | identifier_body | |
message_widget.py | from __future__ import absolute_import, division, print_function
import os
from time import ctime
from qtpy import QtWidgets
from glue import core
from glue.utils.qt import load_ui
class MessageWidget(QtWidgets.QWidget, core.hub.HubListener):
""" This simple class displays all messages broadcast
by a hub. I... | self.ui.messageTable.resizeColumnsToContents() | sender = QtWidgets.QTableWidgetItem(typ)
self.ui.messageTable.setItem(row, 0, tm)
self.ui.messageTable.setItem(row, 1, mtyp)
self.ui.messageTable.setItem(row, 2, sender) | random_line_split |
message_widget.py | from __future__ import absolute_import, division, print_function
import os
from time import ctime
from qtpy import QtWidgets
from glue import core
from glue.utils.qt import load_ui
class MessageWidget(QtWidgets.QWidget, core.hub.HubListener):
""" This simple class displays all messages broadcast
by a hub. I... | (self, hub):
# catch all messages
hub.subscribe(self, core.message.Message,
handler=self.process_message,
filter=lambda x: True)
def process_message(self, message):
row = self.ui.messageTable.rowCount() * 0
self.ui.messageTable.insertRow(0... | register_to_hub | identifier_name |
mapNodesToColumns.js | export default function mapNodesToColumns({
children = [],
columns = 1,
dimensions = [],
} = {}) {
let nodes = []
let heights = []
if (columns === 1) {
return children
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) ... | let index = heights.indexOf(Math.min(...heights))
nodes[index].push(child)
heights[index] += height / width
})
}
// equally spread the children across the columns
else {
for(let i=0; i<columns; i++) {
nodes[i] = children.filter((child, j) => j % columns === i)
}
}
return n... | heights[i] = 0
}
children.forEach((child, i) => {
let { width, height } = dimensions[i] | random_line_split |
mapNodesToColumns.js | export default function mapNodesToColumns({
children = [],
columns = 1,
dimensions = [],
} = {}) {
let nodes = []
let heights = []
if (columns === 1) {
return children
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) ... |
return nodes
} | {
for(let i=0; i<columns; i++) {
nodes[i] = children.filter((child, j) => j % columns === i)
}
} | conditional_block |
mapNodesToColumns.js | export default function mapNodesToColumns({
children = [],
columns = 1,
dimensions = [],
} = {}) | }
// equally spread the children across the columns
else {
for(let i=0; i<columns; i++) {
nodes[i] = children.filter((child, j) => j % columns === i)
}
}
return nodes
} | {
let nodes = []
let heights = []
if (columns === 1) {
return children
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) {
for(let i=0; i<columns; i++) {
nodes[i] = []
heights[i] = 0
}
children.forEac... | identifier_body |
mapNodesToColumns.js | export default function | ({
children = [],
columns = 1,
dimensions = [],
} = {}) {
let nodes = []
let heights = []
if (columns === 1) {
return children
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) {
for(let i=0; i<columns; i++) {
... | mapNodesToColumns | identifier_name |
DataModule.ts | import Express = require("express");
import Geohash = require("latlon-geohash");
import Nconf = require("nconf");
import Path = require("path");
import * as multer from "multer";
import { Picnic } from "../../models/Picnic";
import { User } from "../../models/User";
import { Module } from "../Module";
import { UserMo... | source: {
name: fields.source_name,
retrieved: Date.now(),
url: fields.source_url,
},
type: "table",
user,
},
type: "Feature",
});
// Switch form text (yes/no) to boolean
switch (fields.sheltered.toLowerCase()... | url: fields.license_url,
}, | random_line_split |
DataModule.ts | import Express = require("express");
import Geohash = require("latlon-geohash");
import Nconf = require("nconf");
import Path = require("path");
import * as multer from "multer";
import { Picnic } from "../../models/Picnic";
import { User } from "../../models/User";
import { Module } from "../Module";
import { UserMo... | extends Module {
public addRoutes(app: Express.Application) {
// Tables
app.post("/data/tables/find/near", (req: Express.Request, res: Express.Response) => {
const bounds = req.body;
const query = Picnic.find({}).limit(picknicConfig.data.near.default).where("geometry").near(bounds).lean();
... | DataModule | identifier_name |
cms_plugins.py | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template import loader
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.models.imagemodels import Image
cla... |
def get_folder_files(self, folder, user):
qs_files = folder.files.filter(image__isnull=True)
if user.is_staff:
return qs_files
else:
return qs_files.filter(is_public=True)
def get_folder_images(self, folder, user):
qs_files = folder.files.instance_of(Im... | fieldsets[0][1]['fields'].append('style') | conditional_block |
cms_plugins.py | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template import loader
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.models.imagemodels import Image
cla... | (self, context, instance, placeholder):
self.render_template = select_template((
'cmsplugin_filer_folder/folder.html', # backwards compatibility. deprecated!
self.TEMPLATE_NAME % instance.style,
self.TEMPLATE_NAME % 'default')
).template
folder_files = self.... | render | identifier_name |
cms_plugins.py | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template import loader
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.models.imagemodels import Image
cla... |
plugin_pool.register_plugin(FilerFolderPlugin)
| self.render_template = select_template((
'cmsplugin_filer_folder/folder.html', # backwards compatibility. deprecated!
self.TEMPLATE_NAME % instance.style,
self.TEMPLATE_NAME % 'default')
).template
folder_files = self.get_folder_files(instance.folder,
... | identifier_body |
cms_plugins.py | from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template import loader
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.models.imagemodels import Image
cla... | self.TEMPLATE_NAME % instance.style,
self.TEMPLATE_NAME % 'default')
).template
folder_files = self.get_folder_files(instance.folder,
context['request'].user)
folder_images = self.get_folder_images(instance.folder,
... | return folder.get_children()
def render(self, context, instance, placeholder):
self.render_template = select_template((
'cmsplugin_filer_folder/folder.html', # backwards compatibility. deprecated! | random_line_split |
jquery-s.js | //https://github.com/deadlyicon/s.js
!function(jQuery, DOCUMENT, undefined){
jQuery.prototype.toSelector = function(){
return S(this.selector);
};
S.prototype.get = function(){
return jQuery(this.toSelector());
};
S.prototype.bind = function(types, data, fn){
var index, wrapper;
if (typeof... | (fn){
fn.sjs_wrapper = function(){
var args = Array.prototype.slice.apply(arguments);
args.unshift(jQuery(this));
fn.apply(this, args);
};
fn.sjs_wrapper.wraps = fn;
}
}(jQuery, jQuery(document));
| wrapEventHandler | identifier_name |
jquery-s.js | //https://github.com/deadlyicon/s.js
!function(jQuery, DOCUMENT, undefined){ | };
S.prototype.get = function(){
return jQuery(this.toSelector());
};
S.prototype.bind = function(types, data, fn){
var index, wrapper;
if (typeof data === 'function') fn = data; data = undefined;
fn.sjs_wrapper || wrapEventHandler(fn);
DOCUMENT.delegate(this, types, data, fn.sjs_wrappe... |
jQuery.prototype.toSelector = function(){
return S(this.selector); | random_line_split |
jquery-s.js | //https://github.com/deadlyicon/s.js
!function(jQuery, DOCUMENT, undefined){
jQuery.prototype.toSelector = function(){
return S(this.selector);
};
S.prototype.get = function(){
return jQuery(this.toSelector());
};
S.prototype.bind = function(types, data, fn){
var index, wrapper;
if (typeof... |
}(jQuery, jQuery(document));
| {
fn.sjs_wrapper = function(){
var args = Array.prototype.slice.apply(arguments);
args.unshift(jQuery(this));
fn.apply(this, args);
};
fn.sjs_wrapper.wraps = fn;
} | identifier_body |
setup.py | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
install_requires = [
'requests==2.8.1... | 'Framework :: Django',
'Framework :: Django :: 1.8', # replace "X.Y" as appropriate
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', # example license
'Operating System :: OS Independent',
'Programming Language :: Python',
# Replace th... | author_email='mittal.pankul@gmail.com',
install_requires = install_requires,
classifiers=[
'Environment :: Web Environment', | random_line_split |
states.rs | use std::{cell::RefCell, rc::Rc};
use stdweb::web::event;
/// Used to store and read web events.
pub struct | {
pub mouse_move_events: Rc<RefCell<Vec<event::MouseMoveEvent>>>,
pub mouse_up_events: Rc<RefCell<Vec<event::MouseUpEvent>>>,
pub touch_start_events: Rc<RefCell<Vec<event::TouchStart>>>,
pub touch_end_events: Rc<RefCell<Vec<event::TouchEnd>>>,
pub touch_move_events: Rc<RefCell<Vec<event::TouchMove>... | EventState | identifier_name |
states.rs | use std::{cell::RefCell, rc::Rc};
use stdweb::web::event;
/// Used to store and read web events.
pub struct EventState { | pub touch_start_events: Rc<RefCell<Vec<event::TouchStart>>>,
pub touch_end_events: Rc<RefCell<Vec<event::TouchEnd>>>,
pub touch_move_events: Rc<RefCell<Vec<event::TouchMove>>>,
pub mouse_down_events: Rc<RefCell<Vec<event::MouseDownEvent>>>,
pub scroll_events: Rc<RefCell<Vec<event::MouseWheelEvent>>>... | pub mouse_move_events: Rc<RefCell<Vec<event::MouseMoveEvent>>>,
pub mouse_up_events: Rc<RefCell<Vec<event::MouseUpEvent>>>, | random_line_split |
error.rs | use snafu::Snafu;
/// Represents an error during serialization/deserialization process
#[derive(Debug, Snafu)]
pub enum | {
#[snafu(display("Wrong encoding"))]
WrongEncoding {},
#[snafu(display("{}", source))]
#[snafu(context(false))]
UnknownSpecVersion {
source: crate::event::UnknownSpecVersion,
},
#[snafu(display("Unknown attribute in this spec version: {}", name))]
UnknownAttribute { name: Strin... | Error | identifier_name |
error.rs | use snafu::Snafu;
/// Represents an error during serialization/deserialization process
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Wrong encoding"))]
WrongEncoding {},
#[snafu(display("{}", source))]
#[snafu(context(false))]
UnknownSpecVersion {
source: crate::event::UnknownSp... | IOError { source: std::io::Error },
#[snafu(display("Other error: {}", source))]
Other {
source: Box<dyn std::error::Error + Send + Sync>,
},
}
/// Result type alias for return values during serialization/deserialization process
pub type Result<T> = std::result::Result<T, Error>; | #[snafu(display("IO Error: {}", source))]
#[snafu(context(false))] | random_line_split |
markdownx-widget.js | let widget = document.getElementsByClassName('markdownx-widget')[0];
let element = document.getElementsByClassName('markdownx');
let element_divs = element[0].getElementsByTagName('div');
let div_editor = element_divs[0];
let div_preview = element_divs[1];
let navbar_bar = document.getElementsByClassName('markdownx-to... | tn_fullscreen.setAttribute('class', 'active');
widget.setAttribute('class', 'markup-widget fullscreen');
}
}
Object.keys(element).map(key =>
element[key].addEventListener('markdownx.update', refresh_pretty)
);
btn_preview.addEventListener('click', enable_preview);
btn_fullscreen.addEventListen... | reen.setAttribute('class', '');
widget.setAttribute('class', 'markup-widget');
}
else{
b | conditional_block |
markdownx-widget.js | let widget = document.getElementsByClassName('markdownx-widget')[0];
let element = document.getElementsByClassName('markdownx');
let element_divs = element[0].getElementsByTagName('div');
let div_editor = element_divs[0];
let div_preview = element_divs[1];
let navbar_bar = document.getElementsByClassName('markdownx-to... | btn_preview.setAttribute('class', 'active');
div_editor.setAttribute('class', 'col-md-6 child-left');
div_preview.style.display = 'block';
}
};
var enable_fullscreen = function() {
var class_btn_fullscreen = btn_fullscreen.getAttribute('class');
var index = class_btn_fullscreen.inde... | div_editor.setAttribute('class', 'col-md-12 child-left');
div_preview.style.display = 'none';
}
else { | random_line_split |
DirtyFilter.js | 'use strict';
angular.module('filters.dirty', [])
.filter('returnDirtyItems', function () {
return function (modelToFilter, form, treatAsDirty, removeTheseCharacters) {
//removes pristine items
//note: treatAsDirty must be an array containing the names of items that should not be removed
for (var key in... | //console.log('key ' + key + ' did not have an element in the form');
}
if (removeTheseCharacters !== undefined && removeTheseCharacters.length > 0) {
for (var CA = 0, len = removeTheseCharacters.length; CA < len; CA++ ) {
try{
//console.log('Index of ' + key + ' is: ' ... | // * does not exist on the form
try{
//console.log('checking ' + key + ' for pristine and found it is ' + form[key].$pristine);
}
catch(err){ | random_line_split |
DirtyFilter.js | 'use strict';
angular.module('filters.dirty', [])
.filter('returnDirtyItems', function () {
return function (modelToFilter, form, treatAsDirty, removeTheseCharacters) {
//removes pristine items
//note: treatAsDirty must be an array containing the names of items that should not be removed
for (var key in... | else {
//console.log('The item ' + key + ' was found in the always dirty array and has been kept');
}
} else {
//console.log('There is no array present for dirty items, so ' + key + ' will be removed');
//remove the pristine item from the parent object
delete... | {
//console.log('The item ' + key + ' was not found in the always dirty array and has been deleted');
//remove the pristine item from the parent object
delete modelToFilter[key];
} | conditional_block |
checks.py | import socket as sk
from kivy.logger import Logger
def getWebsite():
|
def getIpPort():
sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP)
return sock_info[0][-1]
def checkInternet():
sock=sk.socket()
sock.settimeout(1)
try:
sock.connect(getIpPort())
sock.send(b'GET /HTTP/1.0\r\n\r\n')
resp=sock.recv(8)
sock.shutdown(1)
... | return "www.google.com" | identifier_body |
checks.py | import socket as sk
from kivy.logger import Logger
def getWebsite():
return "www.google.com"
def getIpPort():
sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP)
return sock_info[0][-1]
def | ():
sock=sk.socket()
sock.settimeout(1)
try:
sock.connect(getIpPort())
sock.send(b'GET /HTTP/1.0\r\n\r\n')
resp=sock.recv(8)
sock.shutdown(1)
sock.close()
if(resp==b'HTTP/1.0'):
return True
else:
return False
except Exceptio... | checkInternet | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.