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 |
|---|---|---|---|---|
issue-888-enum-var-decl-jump.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod Halide {
#[allow(unused_imports)]
use self::supe... |
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum a {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
}
| {
assert_eq!(
::std::mem::size_of::<Type>(),
1usize,
concat!("Size of: ", stringify!(Type))
);
assert_eq!(
::std::mem::align_of::<Type>(),
1usize,
concat!("Alignment of ", stringify!(Type)... | identifier_body |
issue-888-enum-var-decl-jump.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod Halide {
#[allow(unused_imports)]
use self::supe... | () {
assert_eq!(
::std::mem::size_of::<Type>(),
1usize,
concat!("Size of: ", stringify!(Type))
);
assert_eq!(
::std::mem::align_of::<Type>(),
1usize,
concat!("Alignment of ", stringify!(Ty... | bindgen_test_layout_Type | identifier_name |
issue-888-enum-var-decl-jump.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod Halide {
#[allow(unused_imports)]
use self::supe... | fn bindgen_test_layout_Type() {
assert_eq!(
::std::mem::size_of::<Type>(),
1usize,
concat!("Size of: ", stringify!(Type))
);
assert_eq!(
::std::mem::align_of::<Type>(),
1usize,
con... | }
#[test] | random_line_split |
SelectDisplayMode.component.js | import React, { PropTypes } from 'react';
import { Nav, NavDropdown, MenuItem } from 'react-bootstrap';
import uuid from 'uuid';
import Icon from '../../../Icon';
function getIcon(selected) {
switch (selected) {
case 'table': return 'talend-table';
case 'large': return 'talend-expanded';
case 'tile': return 'talen... | </MenuItem>
);
return (
<Nav>
<NavDropdown
id={id || uuid.v4()}
title={displayIcon}
onSelect={onChangeMode}
>
{options.map(option => getMenuItem(option))}
</NavDropdown>
</Nav>
);
}
SelectDisplayMode.propTypes = {
id: PropTypes.string,
mode: PropTypes.string,
onChange: PropTypes.fun... | >
<Icon name={getIcon(option)} />
{getLabel(option)} | random_line_split |
SelectDisplayMode.component.js | import React, { PropTypes } from 'react';
import { Nav, NavDropdown, MenuItem } from 'react-bootstrap';
import uuid from 'uuid';
import Icon from '../../../Icon';
function getIcon(selected) {
switch (selected) {
case 'table': return 'talend-table';
case 'large': return 'talend-expanded';
case 'tile': return 'talen... | ({ id, mode, onChange }) {
const selected = mode || 'table';
const displayIcon = (<Icon name={getIcon(selected)} />);
const onChangeMode = (value, event) => {
onChange(event, value);
};
const getMenuItem = option => (
<MenuItem
id={id && `${id}-${option}`}
key={option}
eventKey={option}
>
<Icon n... | SelectDisplayMode | identifier_name |
SelectDisplayMode.component.js | import React, { PropTypes } from 'react';
import { Nav, NavDropdown, MenuItem } from 'react-bootstrap';
import uuid from 'uuid';
import Icon from '../../../Icon';
function getIcon(selected) |
function getLabel(selected) {
switch (selected) {
case 'table': return 'Table';
case 'large': return 'Expanded';
case 'tile': return 'Tile';
default: return 'Table';
}
}
const options = ['table', 'large', 'tile'];
function SelectDisplayMode({ id, mode, onChange }) {
const selected = mode || 'table';
const d... | {
switch (selected) {
case 'table': return 'talend-table';
case 'large': return 'talend-expanded';
case 'tile': return 'talend-tiles';
default: return 'talend-table';
}
} | identifier_body |
.jsdoc.js | "recurseDepth": 10,
"source": {
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"sourceType": "module",
"tags": {
"allowUnknownTags": true,
"dictionaries": ["jsdoc","closure"]
},
"templates": {
"cleverLinks": false,
"... | 'use strict';
module.exports = {
"plugins": [], | random_line_split | |
pomodoro.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'aen'
import pygame
import sys
from pygame.locals import USEREVENT, QUIT, MOUSEBUTTONDOWN
def pomodoro():
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
pygame.init()
# set up the window
font = pygame.font.Font('fr... | (click_x, click_y, stop_icon_x, stop_icon_y):
if (stop_icon_x <= click_x <= stop_icon_x + 64) \
and (stop_icon_y <= click_y <= stop_icon_y + 64):
return True
else:
return False
def pomodoro_run(pomodoro_time):
pomo_start_sound.play()
timeleft = pomodoro_time
pygame.time... | click_on_stop | identifier_name |
pomodoro.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'aen' |
def pomodoro():
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
pygame.init()
# set up the window
font = pygame.font.Font('freesansbold.ttf', 48) # initialize a font
# define a colors
black = (0, 0, 0)
white = (255, 255, 255)
grey = (150, 150, 150)
red ... |
import pygame
import sys
from pygame.locals import USEREVENT, QUIT, MOUSEBUTTONDOWN
| random_line_split |
pomodoro.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'aen'
import pygame
import sys
from pygame.locals import USEREVENT, QUIT, MOUSEBUTTONDOWN
def pomodoro():
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
pygame.init()
# set up the window
font = pygame.font.Font('fr... |
else:
return False
def click_on_stop(click_x, click_y, stop_icon_x, stop_icon_y):
if (stop_icon_x <= click_x <= stop_icon_x + 64) \
and (stop_icon_y <= click_y <= stop_icon_y + 64):
return True
else:
return False
def pomodoro_run(pomodoro_time):
pomo_start_sound.... | return True | conditional_block |
pomodoro.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'aen'
import pygame
import sys
from pygame.locals import USEREVENT, QUIT, MOUSEBUTTONDOWN
def pomodoro():
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=512)
pygame.init()
# set up the window
font = pygame.font.Font('fr... |
if __name__ == '__main__':
pomodoro() | pomo_end_sound.play()
pomodoro_stop() | identifier_body |
resource_files.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 http://mozilla.org/MPL/2.0/. */
#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Pat... |
// FIXME: Find a way to not rely on the executable being
// under `<servo source>[/$target_triple]/target/debug`
// or `<servo source>[/$target_triple]/target/release`.
let mut path = env::current_exe().expect("can't get exe path");
// Follow symlink
path = path.canonicalize().expect("path doe... | {
return PathBuf::from(path);
} | conditional_block |
resource_files.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 http://mozilla.org/MPL/2.0/. */
#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Pat... | {
let mut path = resources_dir_path();
path.push(relative_path);
let mut file = try!(File::open(&path));
let mut data = Vec::new();
try!(file.read_to_end(&mut data));
Ok(data)
} | identifier_body | |
resource_files.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 http://mozilla.org/MPL/2.0/. */
#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Pat... |
pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> {
let mut path = resources_dir_path();
path.push(relative_path);
let mut file = try!(File::open(&path));
let mut data = Vec::new();
try!(file.read_to_end(&mut data));
Ok(data)
} | *dir = Some(path.to_str().unwrap().to_owned());
path
} | random_line_split |
resource_files.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 http://mozilla.org/MPL/2.0/. */
#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Pat... | () -> PathBuf {
let mut dir = CMD_RESOURCE_DIR.lock().unwrap();
if let Some(ref path) = *dir {
return PathBuf::from(path);
}
// FIXME: Find a way to not rely on the executable being
// under `<servo source>[/$target_triple]/target/debug`
// or `<servo source>[/$target_triple]/target/re... | resources_dir_path | identifier_name |
TextZones.ts | import { Universe } from '@ephox/boss';
import { Fun, Optional } from '@ephox/katamari';
import * as Parent from '../api/general/Parent';
import { ZoneViewports } from '../api/general/ZoneViewports';
import * as Clustering from '../words/Clustering';
import { WordDecision, WordDecisionItem } from '../words/WordDecisio... | zones: []
};
};
export {
fromRange,
transformEdges,
fromBounded,
fromBoundedWith,
fromInline,
empty
}; | const empty = <E>(): Zones<E> => {
return { | random_line_split |
TextZones.ts | import { Universe } from '@ephox/boss';
import { Fun, Optional } from '@ephox/katamari';
import * as Parent from '../api/general/Parent';
import { ZoneViewports } from '../api/general/ZoneViewports';
import * as Clustering from '../words/Clustering';
import { WordDecision, WordDecisionItem } from '../words/WordDecisio... | else {
return WordDecision.detail(universe, element);
}
};
};
const fromInline = <E, D>(universe: Universe<E, D>, element: E, envLang: string, viewport: ZoneViewports<E>): Zones<E> => {
// Create a cluster that branches to the edge of words, and then apply the zones. We will move
// past language boun... | {
return rightEdge;
} | conditional_block |
create.js |
import isObject from 'lodash-es/isObject'
import isEmpty from 'lodash-es/isEmpty'
import isFunction from 'lodash-es/isFunction'
import isArray from 'lodash-es/isArray'
import reduce from 'lodash-es/reduce'
import cloneDeep from 'lodash-es/cloneDeep'
import Observable from 'zen-observable'
import * as most from 'most'
... | }
}
`)
}
let observable = new Observable(observer => {
let keys = Object.keys(controller.args)
let args = keys.reduce((acc, x) => {
acc[x] = undefined
return acc
}, {})
let unsubs = keys.map(key => {
return db.on(controller.args[key], val => {
args[key] = v... | {
let off = () => {}
if (!controller.args || !controller.fn) {
throw new Error(`Controller [${name}] should look like:
--
{
args: Object,
fn: Function | Observable
}
--
example:
{
args: {
foo: '/bam/bar/foo',
baz: '/boo/baz'
... | identifier_body |
create.js | import isObject from 'lodash-es/isObject'
import isEmpty from 'lodash-es/isEmpty'
import isFunction from 'lodash-es/isFunction'
import isArray from 'lodash-es/isArray'
import reduce from 'lodash-es/reduce'
import cloneDeep from 'lodash-es/cloneDeep'
import Observable from 'zen-observable'
import * as most from 'most'
... | }
}
`)
}
let observable = new Observable(observer => {
let keys = Object.keys(controller.args)
let args = keys.reduce((acc, x) => {
acc[x] = undefined
return acc
}, {})
let unsubs = keys.map(key => {
return db.on(controller.args[key], val => {
args[key] = v... | baz: '/boo/baz'
},
fn: args => {
args.foo // The value at /bam/bar/foo
args.baz // => /boo/baz | random_line_split |
create.js |
import isObject from 'lodash-es/isObject'
import isEmpty from 'lodash-es/isEmpty'
import isFunction from 'lodash-es/isFunction'
import isArray from 'lodash-es/isArray'
import reduce from 'lodash-es/reduce'
import cloneDeep from 'lodash-es/cloneDeep'
import Observable from 'zen-observable'
import * as most from 'most'
... | }
let observable = new Observable(observer => {
let keys = Object.keys(controller.args)
let args = keys.reduce((acc, x) => {
acc[x] = undefined
return acc
}, {})
let unsubs = keys.map(key => {
return db.on(controller.args[key], val => {
args[key] = val
observer.... | {
throw new Error(`Controller [${name}] should look like:
--
{
args: Object,
fn: Function | Observable
}
--
example:
{
args: {
foo: '/bam/bar/foo',
baz: '/boo/baz'
},
fn: args => {
args.foo // The value at /bam... | conditional_block |
create.js |
import isObject from 'lodash-es/isObject'
import isEmpty from 'lodash-es/isEmpty'
import isFunction from 'lodash-es/isFunction'
import isArray from 'lodash-es/isArray'
import reduce from 'lodash-es/reduce'
import cloneDeep from 'lodash-es/cloneDeep'
import Observable from 'zen-observable'
import * as most from 'most'
... | (db, controller, name) {
let off = () => {}
if (!controller.args || !controller.fn) {
throw new Error(`Controller [${name}] should look like:
--
{
args: Object,
fn: Function | Observable
}
--
example:
{
args: {
foo: '/bam/bar/foo',
... | createController | identifier_name |
make-pathway2list.py | #!/usr/bin/env python
import os
import sys
## A name of directory containing 'path:...' file
## You can download them using 'make-wget_pathway.sh' script
dir_name = sys.argv[1]
f_summary = open('%s.summary'%dir_name,'w')
f_genes = open('%s.genes'%dir_name,'w')
f_compounds = open('%s.compounds'%dir_name,'w')
gene_to... | f_genes.close()
f_compounds.close() | random_line_split | |
make-pathway2list.py | #!/usr/bin/env python
import os
import sys
## A name of directory containing 'path:...' file
## You can download them using 'make-wget_pathway.sh' script
dir_name = sys.argv[1]
f_summary = open('%s.summary'%dir_name,'w')
f_genes = open('%s.genes'%dir_name,'w')
f_compounds = open('%s.compounds'%dir_name,'w')
gene_to... |
f.close()
if( len(gene_list) == 0 ):
sys.stderr.write('//SKIP// %s(%d) %s\n'%(path_id, len(gene_list), path_name))
continue
f_summary.write('path:%s\t%s\t%d\t%d\n'%(path_id, path_name, len(gene_list), len(comp_list)))
f_summary.close()
f_genes.close()
f_compounds.close()
| prev_tag = tmp_tag | conditional_block |
filetransfer.py | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2010 Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
#... | (P2PSession):
def __init__(self, session_manager, peer, guid, message=None):
P2PSession.__init__(self, session_manager, peer, guid,
EufGuid.FILE_TRANSFER, ApplicationID.FILE_TRANSFER, message)
self._filename = ""
self._size = 0
self._has_preview = False
self.... | FileTransferSession | identifier_name |
filetransfer.py | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2010 Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
#... |
self._accept()
def reject(self):
self._decline(603)
def cancel(self):
self._close()
def send(self, data):
self._data = data
self._send_data("\x00" * 4)
self._send_data(self._data)
def parse_context(self, context):
try:
info = struc... | self.set_receive_data_buffer(buffer, self._size) | conditional_block |
filetransfer.py | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2010 Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
#... |
def reject(self):
self._decline(603)
def cancel(self):
self._close()
def send(self, data):
self._data = data
self._send_data("\x00" * 4)
self._send_data(self._data)
def parse_context(self, context):
try:
info = struct.unpack("<5I", context... | if buffer is not None:
self.set_receive_data_buffer(buffer, self._size)
self._accept() | identifier_body |
filetransfer.py | # -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn | # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Pub... | #
# Copyright (C) 2010 Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | random_line_split |
action.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::error::*;
use anyhow::Result;
use log::{error, info};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Inst... |
}
Ok(())
}
}
| {
info!("{} Cloud Sync was successful", sid);
return Ok(());
} | conditional_block |
action.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::error::*;
use anyhow::Result;
use log::{error, info};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Inst... |
info!(
"{} Fire `hg cloud sync` attempt {}, spawned process id '{}'",
sid,
i,
child.id()
);
let output = child.wait_with_output()?;
info!(
"{} stdout: \n{}",
sid,
... | {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
workspace_args.append(&mut vec![
"--workspace-version".to_owned(),
version.to_string(),
]);
}
for i in 0..retries {
... | identifier_body |
action.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::error::*;
use anyhow::Result;
use log::{error, info}; | use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Instant;
pub struct CloudSyncTrigger;
impl CloudSyncTrigger {
pub fn fire<P: AsRef<Path>>(
sid: &String,
path: P,
retries: u32,
version: Option<u64>,
workspace: String,
) -> Result<()> {
let... | random_line_split | |
action.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::error::*;
use anyhow::Result;
use log::{error, info};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Inst... | <P: AsRef<Path>>(
sid: &String,
path: P,
retries: u32,
version: Option<u64>,
workspace: String,
) -> Result<()> {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
workspace_args.append(&m... | fire | identifier_name |
make_erpnext_demo.py | if __name__=="__main__":
import sys
sys.path.extend([".", "lib", "app"])
import webnotes, os
import utilities.demo.make_demo
def make_demo_app():
webnotes.mute_emails = 1
webnotes.connect()
utilities.demo.make_demo.make(reset=True, simulate=False)
# setup demo user etc so that the site it up faster, while the d... | make_demo_app() | conditional_block | |
make_erpnext_demo.py | if __name__=="__main__":
import sys
sys.path.extend([".", "lib", "app"])
import webnotes, os
import utilities.demo.make_demo
def make_demo_app():
webnotes.mute_emails = 1
webnotes.connect()
utilities.demo.make_demo.make(reset=True, simulate=False)
# setup demo user etc so that the site it up faster, while the d... | p.doc.email = "demo@owrang.yellowen.com"
p.doc.first_name = "Demo"
p.doc.last_name = "User"
p.doc.enabled = 1
p.doc.user_type = "Owrang Demo"
p.doc.send_invite_email = 0
p.doc.new_password = "demo"
p.insert()
add_roles(p)
p.save()
# make system manager user
if webnotes.conn.exists("Profile", "admin@owrang... | if webnotes.conn.exists("Profile", "demo@owrang.yellowen.com"):
webnotes.delete_doc("Profile", "demo@owrang.yellowen.com")
p = webnotes.new_bean("Profile") | random_line_split |
make_erpnext_demo.py | if __name__=="__main__":
import sys
sys.path.extend([".", "lib", "app"])
import webnotes, os
import utilities.demo.make_demo
def make_demo_app():
webnotes.mute_emails = 1
webnotes.connect()
utilities.demo.make_demo.make(reset=True, simulate=False)
# setup demo user etc so that the site it up faster, while the d... | ():
roles = ["Accounts Manager", "Analytics", "Expense Approver", "Accounts User",
"Leave Approver", "Blogger", "Customer", "Sales Manager", "Employee", "Support Manager",
"HR Manager", "HR User", "Maintenance Manager", "Maintenance User", "Material Manager",
"Material Master Manager", "Material User", "Manuf... | make_demo_user | identifier_name |
make_erpnext_demo.py | if __name__=="__main__":
import sys
sys.path.extend([".", "lib", "app"])
import webnotes, os
import utilities.demo.make_demo
def make_demo_app():
webnotes.mute_emails = 1
webnotes.connect()
utilities.demo.make_demo.make(reset=True, simulate=False)
# setup demo user etc so that the site it up faster, while the d... |
# make demo user
if webnotes.conn.exists("Profile", "demo@owrang.yellowen.com"):
webnotes.delete_doc("Profile", "demo@owrang.yellowen.com")
p = webnotes.new_bean("Profile")
p.doc.email = "demo@owrang.yellowen.com"
p.doc.first_name = "Demo"
p.doc.last_name = "User"
p.doc.enabled = 1
p.doc.user_type = "Owra... | for role in roles:
p.doclist.append({
"doctype": "UserRole",
"parentfield": "user_roles",
"role": role
}) | identifier_body |
findOverlapGene.py | import subprocess
import os.path
import re
import argparse
import sys
from pybedtools import BedTool
DEBUG = False
parser = argparse.ArgumentParser(description="find overlap gene.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
if not DEBUG:
parser.add_argument('-i', '--i... | input_file=args.input
gene_file = args.gene_sorted_bed
output_file=args.output
else:
input_file= "/scratch/cqs/shengq1/vickers/20170720_AGO_human_CLIP/macs2/result/GSM1020022/GSM1020022_peaks.narrowPeak.bed"
gene_file = "/scratch/cqs/shengq1/references/smallrna/v3/hg19_miRBase21_GtRNAdb2_gencode19_ncbi.sorted... | parser.add_argument('-g', '--gene_sorted_bed', action='store', nargs='?', help='Gene locus file (sorted bed format)', required=True)
parser.add_argument('-o', '--output', action='store', nargs='?', help='Output overlap file', required=True)
args = parser.parse_args() | random_line_split |
findOverlapGene.py | import subprocess
import os.path
import re
import argparse
import sys
from pybedtools import BedTool
DEBUG = False
parser = argparse.ArgumentParser(description="find overlap gene.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
if not DEBUG:
parser.add_argument('-i', '--i... |
closet = [nearest for nearest in BedTool(input_file).closest(gene_file, d=True)]
with open(output_file, 'w') as w:
for nearest in closet:
overlap = nearest.fields[12]
if overlap == u'0':
w.write(str(nearest))
| input_file= "/scratch/cqs/shengq1/vickers/20170720_AGO_human_CLIP/macs2/result/GSM1020022/GSM1020022_peaks.narrowPeak.bed"
gene_file = "/scratch/cqs/shengq1/references/smallrna/v3/hg19_miRBase21_GtRNAdb2_gencode19_ncbi.sorted.bed"
output_file="/scratch/cqs/shengq1/vickers/20170720_AGO_human_CLIP/macs2/result/GSM102... | conditional_block |
gogo_octogist.py | '''
Use the Github API to get the most recent Gist for a list of users
Created on 5 Nov 2019
@author: si
'''
from datetime import datetime
import sys
import requests
class OctoGist:
def __init__(self):
self.base_url = 'https://api.github.com'
self.items_per_page = 100
self.gist_path = (f... | self.log(msg, "WARNING")
if max_docs is not None and docs_fetched > max_docs:
return
def log(self, msg, level="INFO"):
"""
Dependency injection ready logger.
:param: msg (str)
:param: level (str) , DEBUG, INFO, WARNING, ERROR, CRITICAL
... | ) | random_line_split |
gogo_octogist.py | '''
Use the Github API to get the most recent Gist for a list of users
Created on 5 Nov 2019
@author: si
'''
from datetime import datetime
import sys
import requests
class OctoGist:
def __init__(self):
self.base_url = 'https://api.github.com'
self.items_per_page = 100
self.gist_path = (f... |
# overall sort for all users
one_gist_per_user = [(username, gist) for username, gist in latest_gist.items()]
one_gist_per_user.sort(key=lambda g: g[1][target_field], reverse=True)
for username, gist in one_gist_per_user:
# description is optional
gi... | if username not in latest_gist \
or gist_doc[target_field] > latest_gist[username][target_field]:
latest_gist[username] = gist_doc | conditional_block |
gogo_octogist.py | '''
Use the Github API to get the most recent Gist for a list of users
Created on 5 Nov 2019
@author: si
'''
from datetime import datetime
import sys
import requests
class OctoGist:
def __init__(self):
|
def go(self, usernames):
"""
:param: usernames (str) comma separated list of user names
"""
# sort order doesn't exist on the per user gist endpoint. Only on /search/
# so find latest entry by iterating through all docs.
target_field = 'created_at' # or could be '... | self.base_url = 'https://api.github.com'
self.items_per_page = 100
self.gist_path = (f'{self.base_url}/users/'
'{username}'
f'/gists?per_page={self.items_per_page}'
)
# support 1.1 keep alive
self.requests_ses... | identifier_body |
gogo_octogist.py | '''
Use the Github API to get the most recent Gist for a list of users
Created on 5 Nov 2019
@author: si
'''
from datetime import datetime
import sys
import requests
class | :
def __init__(self):
self.base_url = 'https://api.github.com'
self.items_per_page = 100
self.gist_path = (f'{self.base_url}/users/'
'{username}'
f'/gists?per_page={self.items_per_page}'
)
# support 1.1 ke... | OctoGist | identifier_name |
chromosome_surgery.py | #!/usr/bin/env python3
import sys
from Bio import SeqIO
from argparse import ArgumentParser, RawDescriptionHelpFormatter
usage = "Chromosome surgery: Splice something into and/or out of a chromosome."
# Main Parsers
parser = ArgumentParser(description=usage, formatter_class=RawDescriptionHelpFormatter)
parser.add_arg... | pass # The incision will be applied first, no need to adjust it. The excision is unaffected by the incision anyway.
else:
sys.stderr.write('Error: Cannot apply the specified coordinates. Excision end must be after excision start, and the incision cannot be inside the excision.')
# Parse and... | elif args.excision_start < incision and args.excision_end < incision: | random_line_split |
chromosome_surgery.py | #!/usr/bin/env python3
import sys
from Bio import SeqIO
from argparse import ArgumentParser, RawDescriptionHelpFormatter
usage = "Chromosome surgery: Splice something into and/or out of a chromosome."
# Main Parsers
parser = ArgumentParser(description=usage, formatter_class=RawDescriptionHelpFormatter)
parser.add_arg... |
if (not no_insert) and not (no_excision):
# Do excision after the incision.
# Adjust coordinates.
if args.excision_start > args.incision and args.excision_end > args.incision:
excision_start = args.excision_start + len(splice_in)
excision_end = args.excision_end + len(splice_in)
e... | excision_start = args.excision_start
excision_end = args.excision_end
# Pythonize start coordinate from 1-based left-closed to 0-based left-closed.
excision_start -= 1
# No need to change the end coordinate. The 1-based right-closed index is the same location as the 0-based right-open substring end. | conditional_block |
guts.rs | 64 = BLOCK64 * BUFBLOCKS;
pub(crate) const BUFSZ: usize = BUFSZ64 as usize;
#[derive(Clone, PartialEq, Eq)]
pub struct ChaCha {
pub(crate) b: vec128_storage,
pub(crate) c: vec128_storage,
pub(crate) d: vec128_storage,
}
#[derive(Clone)]
pub struct State<V> {
pub(crate) a: V,
pub(crate) b: V,
p... |
#[inline(always)]
fn pos64<M: Machine>(&self, m: M) -> u64 {
let d: M::u32x4 = m.unpack(self.d);
((d.extract(1) as u64) << 32) | d.extract(0) as u64
}
/// Produce 4 blocks of output, advancing the state
#[inline(always)]
pub fn refill4(&mut self, drounds: u32, out: &mut [u8; B... | {
init_chacha(key, nonce)
} | identifier_body |
guts.rs | u64 = BLOCK64 * BUFBLOCKS;
pub(crate) const BUFSZ: usize = BUFSZ64 as usize;
#[derive(Clone, PartialEq, Eq)]
pub struct ChaCha {
pub(crate) b: vec128_storage,
pub(crate) c: vec128_storage,
pub(crate) d: vec128_storage,
}
#[derive(Clone)]
pub struct State<V> {
pub(crate) a: V,
pub(crate) b: V,
... | let d3 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0);
pos = pos.wrapping_add(1);
let d4 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0);
let (a, b, c, d) = (
x.a.to_lanes(),
x.b.to_lanes(),
x.c.to_lanes(),
x.d.to_lanes(),
);
let sb = m.unpack(... | pos = pos.wrapping_add(1);
let d1 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0);
pos = pos.wrapping_add(1);
let d2 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0);
pos = pos.wrapping_add(1); | random_line_split |
guts.rs | 64 = BLOCK64 * BUFBLOCKS;
pub(crate) const BUFSZ: usize = BUFSZ64 as usize;
#[derive(Clone, PartialEq, Eq)]
pub struct ChaCha {
pub(crate) b: vec128_storage,
pub(crate) c: vec128_storage,
pub(crate) d: vec128_storage,
}
#[derive(Clone)]
pub struct State<V> {
pub(crate) a: V,
pub(crate) b: V,
p... | (&mut self, drounds: u32, out: &mut [u8; BUFSZ]) {
refill_wide(self, drounds, out)
}
#[inline(always)]
pub fn set_stream_param(&mut self, param: u32, value: u64) {
set_stream_param(self, param, value)
}
#[inline(always)]
pub fn get_stream_param(&self, param: u32) -> u64 {
... | refill4 | identifier_name |
active_app_02_objc_bridge.py | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2015 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2015-11-23
#
"""Get app info with AppKit via objc bridge."""
from __future__ import print_function, unicode_literals, absolute_import
import time
import unicoded... | ():
"""Return (name, bundle_id and path) of frontmost application.
Raise a `RuntimeError` if frontmost application cannot be
determined.
"""
for app in NSWorkspace.sharedWorkspace().runningApplications():
if app.isActive():
app_name = app.localizedName()
bundle_id =... | get_frontmost_app | identifier_name |
active_app_02_objc_bridge.py | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2015 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2015-11-23
#
"""Get app info with AppKit via objc bridge."""
from __future__ import print_function, unicode_literals, absolute_import
import time
import unicoded... |
def get_frontmost_app():
"""Return (name, bundle_id and path) of frontmost application.
Raise a `RuntimeError` if frontmost application cannot be
determined.
"""
for app in NSWorkspace.sharedWorkspace().runningApplications():
if app.isActive():
app_name = app.localizedName()... | """Decode bytestring to Unicode."""
if isinstance(s, str):
s = unicode(s, 'utf-8')
elif not isinstance(s, unicode):
raise TypeError("str or unicode required, not {}".format(type(s)))
return unicodedata.normalize('NFC', s) | identifier_body |
active_app_02_objc_bridge.py | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2015 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2015-11-23
#
"""Get app info with AppKit via objc bridge."""
from __future__ import print_function, unicode_literals, absolute_import
import time
import unicoded... |
def get_frontmost_app():
"""Return (name, bundle_id and path) of frontmost application.
Raise a `RuntimeError` if frontmost application cannot be
determined.
"""
for app in NSWorkspace.sharedWorkspace().runningApplications():
if app.isActive():
app_name = app.localizedName()
... | random_line_split | |
active_app_02_objc_bridge.py | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2015 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2015-11-23
#
"""Get app info with AppKit via objc bridge."""
from __future__ import print_function, unicode_literals, absolute_import
import time
import unicoded... |
elif not isinstance(s, unicode):
raise TypeError("str or unicode required, not {}".format(type(s)))
return unicodedata.normalize('NFC', s)
def get_frontmost_app():
"""Return (name, bundle_id and path) of frontmost application.
Raise a `RuntimeError` if frontmost application cannot be
det... | s = unicode(s, 'utf-8') | conditional_block |
rt.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | pub fn error_trap_push() {
unsafe { ffi::gdk_error_trap_push() }
}
pub fn error_trap_pop() {
unsafe { ffi::gdk_error_trap_pop() }
}
pub fn error_trap_pop_ignored() {
unsafe { ffi::gdk_error_trap_pop_ignored() }
} | unsafe { ffi::gdk_flush() }
}
| identifier_body |
rt.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | unsafe {
FromGlibPtr::borrow(
ffi::gdk_get_display_arg_name())
}
}
pub fn notify_startup_complete() {
unsafe { ffi::gdk_notify_startup_complete() }
}
pub fn notify_startup_complete_with_id(startup_id: &str) {
unsafe {
ffi::gdk_notify_startup_complete_with_id(startup_id.borr... | pub fn get_display_arg_name() -> Option<String> { | random_line_split |
rt.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | {
unsafe { ffi::gdk_error_trap_pop() }
}
pub fn error_trap_pop_ignored() {
unsafe { ffi::gdk_error_trap_pop_ignored() }
} | ror_trap_pop() | identifier_name |
example_all_O2.py | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_i... |
# for < 4 images pad using a blank quadrant
r, c = Q0.shape
Q = np.zeros((4, r, c))
indx = np.triu_indices(iabelQ[0].shape[0])
iq = 0
for q in range(4):
Q[q] = iabelQ[iq].copy()
ann_plt(q, 0, meth[iq])
ax1.plot(*(sp[iq]), label=meth[iq], alpha=0.5)
iq += 1
if iq < len(transforms):
Q[q][in... | annot_angle = -(30+30*subquad+quad*90)*np.pi/180
annot_coord = (h/2+(h*0.8)*np.cos(annot_angle)/2,
w/2+(w*0.8)*np.sin(annot_angle)/2)
ax0.annotate(txt, annot_coord, color="yellow", horizontalalignment='left') | identifier_body |
example_all_O2.py | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_i... |
# reassemble image from transformed (part-)quadrants
im = abel.tools.symmetry.put_image_quadrants((Q[0], Q[1], Q[2], Q[3]),
original_image_shape=IModd.shape)
ax0.axis('off')
ax0.set_title("inverse Abel transforms")
ax0.imshow(im, vmin=0, vmax=0.8)
ax1.set_title("speed d... | Q[q] = iabelQ[iq].copy()
ann_plt(q, 0, meth[iq])
ax1.plot(*(sp[iq]), label=meth[iq], alpha=0.5)
iq += 1
if iq < len(transforms):
Q[q][indx] = np.triu(iabelQ[iq])[indx]
ann_plt(q, 1, meth[iq])
ax1.plot(*(sp[iq]), label=meth[iq], alpha=0.5)
iq += 1 | conditional_block |
example_all_O2.py | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_i... |
h, w = IModd.shape
print("centered image 'data/O2-ANU2048.txt' shape = {:d}x{:d}".format(h, w))
# split image into quadrants
Q = abel.tools.symmetry.get_image_quadrants(IModd, reorient=True)
Q0 = Q[0]
Q0fresh = Q0.copy() # keep clean copy
print ("quadrant shape {}".format(Q0.shape))
# Intensity mask used for int... | IModd = abel.tools.center.center_image(IM, center="slice", odd_size=True) | random_line_split |
example_all_O2.py | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_i... | (quad, subquad, txt):
# -ve because numpy coords from top
annot_angle = -(30+30*subquad+quad*90)*np.pi/180
annot_coord = (h/2+(h*0.8)*np.cos(annot_angle)/2,
w/2+(w*0.8)*np.sin(annot_angle)/2)
ax0.annotate(txt, annot_coord, color="yellow", horizontalalignment='left')
# for < 4 images... | ann_plt | identifier_name |
main.js | /*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
var ledController = require("./ledController.js");
ledController.clear();
ledController.smile();
var motorController = require("./motorController.js")
motorController.go();
motorController.stop();
//motorController.demo(... |
});
req1.end();
}
readMotions();
motorController.stop();
var loopCounter = 0;
setInterval(function() {
readMotions();
}, 200);
| {
var payload = JSON.parse(res.payload);
var newAction = payload.data[0].value;
if (newAction !== lastAction)
{
lastAction = newAction;
motorController.doAction(newAction);
}
} | conditional_block |
main.js | /*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
var ledController = require("./ledController.js");
ledController.clear();
ledController.smile();
var motorController = require("./motorController.js")
motorController.go();
motorController.stop();
//motorController.demo(... | ()
{
//read latest write
var req1 = client.thingReadLatest(motionKEY);
//event fired when the response arrives
req1.on('response',function(res){
if (res.statusCode == 200 && res.payload !== undefined)
{
var payload = JSON.parse(res.payload);
var newAction = paylo... | readMotions | identifier_name |
main.js | /*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
var ledController = require("./ledController.js");
ledController.clear();
ledController.smile();
var motorController = require("./motorController.js")
motorController.go();
motorController.stop();
//motorController.demo(... |
readMotions();
motorController.stop();
var loopCounter = 0;
setInterval(function() {
readMotions();
}, 200);
| {
//read latest write
var req1 = client.thingReadLatest(motionKEY);
//event fired when the response arrives
req1.on('response',function(res){
if (res.statusCode == 200 && res.payload !== undefined)
{
var payload = JSON.parse(res.payload);
var newAction = payload.... | identifier_body |
main.js | /*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
var ledController = require("./ledController.js");
ledController.clear();
ledController.smile();
var motorController = require("./motorController.js")
motorController.go();
motorController.stop();
//motorController.demo(... | //read latest write
var req1 = client.thingReadLatest(motionKEY);
//event fired when the response arrives
req1.on('response',function(res){
if (res.statusCode == 200 && res.payload !== undefined)
{
var payload = JSON.parse(res.payload);
var newAction = payload.da... | function readMotions()
{ | random_line_split |
sale_order.py | # -*- coding: utf-8 -*-
from openerp import models, api
class sale_order_line(models.Model):
_inherit = "sale.order.line"
@api.one | invoice_line_ids = [((0, 0, {
'product_id': self.product_id.id,
'analytic_account_id': self.order_id.project_id.id,
'name': self.name,
'quantity': self.product_uom_qty,
'uom_id': self.product_uom.id,
'price_unit'... | def button_confirm(self):
if self.product_id.recurring_invoice and self.order_id.project_id: | random_line_split |
sale_order.py | # -*- coding: utf-8 -*-
from openerp import models, api
class sale_order_line(models.Model):
| _inherit = "sale.order.line"
@api.one
def button_confirm(self):
if self.product_id.recurring_invoice and self.order_id.project_id:
invoice_line_ids = [((0, 0, {
'product_id': self.product_id.id,
'analytic_account_id': self.order_id.project_id.id,
... | identifier_body | |
sale_order.py | # -*- coding: utf-8 -*-
from openerp import models, api
class sale_order_line(models.Model):
_inherit = "sale.order.line"
@api.one
def | (self):
if self.product_id.recurring_invoice and self.order_id.project_id:
invoice_line_ids = [((0, 0, {
'product_id': self.product_id.id,
'analytic_account_id': self.order_id.project_id.id,
'name': self.name,
'quantity': self.product_u... | button_confirm | identifier_name |
sale_order.py | # -*- coding: utf-8 -*-
from openerp import models, api
class sale_order_line(models.Model):
_inherit = "sale.order.line"
@api.one
def button_confirm(self):
if self.product_id.recurring_invoice and self.order_id.project_id:
|
return super(sale_order_line, self).button_confirm()
| invoice_line_ids = [((0, 0, {
'product_id': self.product_id.id,
'analytic_account_id': self.order_id.project_id.id,
'name': self.name,
'quantity': self.product_uom_qty,
'uom_id': self.product_uom.id,
'price_unit': self.price... | conditional_block |
scroll-dispatcher.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementRef, Injectable, NgZone, Optional, SkipSelf} from '@angular/core';
import {Platform} from '@angular/cd... | (
parentDispatcher: ScrollDispatcher, ngZone: NgZone, platform: Platform) {
return parentDispatcher || new ScrollDispatcher(ngZone, platform);
}
/** @docs-private */
export const SCROLL_DISPATCHER_PROVIDER = {
// If there is already a ScrollDispatcher available, use that. Otherwise, provide a new one.
provid... | SCROLL_DISPATCHER_PROVIDER_FACTORY | identifier_name |
scroll-dispatcher.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementRef, Injectable, NgZone, Optional, SkipSelf} from '@angular/core';
import {Platform} from '@angular/cd... |
/**
* Returns an observable that emits an event whenever any of the registered Scrollable
* references (or window, document, or body) fire a scrolled event. Can provide a time in ms
* to override the default "throttle" time.
*/
scrolled(auditTimeInMs: number = DEFAULT_SCROLL_TIME): Observable<void> {
... | {
const scrollableReference = this.scrollableReferences.get(scrollable);
if (scrollableReference) {
scrollableReference.unsubscribe();
this.scrollableReferences.delete(scrollable);
}
} | identifier_body |
scroll-dispatcher.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementRef, Injectable, NgZone, Optional, SkipSelf} from '@angular/core';
import {Platform} from '@angular/cd... |
} while (element = element.parentElement);
return false;
}
/** Sets up the global scroll and resize listeners. */
private _addGlobalListener() {
this._globalSubscription = this._ngZone.runOutsideAngular(() => {
return fromEvent(window.document, 'scroll').subscribe(() => this._scrolled.next())... | { return true; } | conditional_block |
scroll-dispatcher.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementRef, Injectable, NgZone, Optional, SkipSelf} from '@angular/core';
import {Platform} from '@angular/cd... | @Injectable()
export class ScrollDispatcher {
constructor(private _ngZone: NgZone, private _platform: Platform) { }
/** Subject for notifying that a registered scrollable reference element has been scrolled. */
private _scrolled: Subject<void> = new Subject<void>();
/** Keeps track of the global `scroll` and ... |
/**
* Service contained all registered Scrollable references and emits an event when any one of the
* Scrollable references emit a scrolled event.
*/ | random_line_split |
operands.rs | // This example shows how to get operands details.
|
use capstone_rust::capstone as cs;
fn main() {
// Buffer of code.
let code = vec![0x01, 0xc0, 0x33, 0x19, 0x66, 0x83, 0xeb, 0x0a, 0xe8, 0x0c, 0x00, 0x00,
0x00, 0x21, 0x5c, 0xca, 0xfd];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enab... | extern crate capstone_rust; | random_line_split |
operands.rs | // This example shows how to get operands details.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn | () {
// Buffer of code.
let code = vec![0x01, 0xc0, 0x33, 0x19, 0x66, 0x83, 0xeb, 0x0a, 0xe8, 0x0c, 0x00, 0x00,
0x00, 0x21, 0x5c, 0xca, 0xfd];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want t... | main | identifier_name |
operands.rs | // This example shows how to get operands details.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn main() | // Get the current operand.
let op: cs::cs_x86_op = arch.operands[i as usize];
match op.type_ {
cs::x86_op_type::X86_OP_REG => {
let reg: &cs::x86_reg = op.reg();
println!(" Register operand: {}", dec.r... | {
// Buffer of code.
let code = vec![0x01, 0xc0, 0x33, 0x19, 0x66, 0x83, 0xeb, 0x0a, 0xe8, 0x0c, 0x00, 0x00,
0x00, 0x21, 0x5c, 0xca, 0xfd];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want to g... | identifier_body |
main.js | // your answer would go here
$(function (){
var container = $('#rating-container');
$('#max-value').val('');
var update_circles =function (){
for (var i = 0; i < container.attr('max-value'); i++){
container.append('<div class="rating-circle"></div>');
}
}
$('#save... |
container.delegate('.rating-circle', 'click', function(){
$(this).prevAll().andSelf().addClass('rating-chosen');
$(this).nextAll().removeClass('rating-chosen-removed rating-chosen');
});
update_circles();
}); | random_line_split | |
main.js | // your answer would go here
$(function (){
var container = $('#rating-container');
$('#max-value').val('');
var update_circles =function (){
for (var i = 0; i < container.attr('max-value'); i++){
container.append('<div class="rating-circle"></div>');
}
}
$('#save... |
update_circles();
});
container.delegate('.rating-circle', 'mouseover', function(){
$('.rating-chosen').addClass('rating-chosen-removed');
$('.rating-chosen').removeClass('rating-chosen');
$(this).prevAll().andSelf().addClass('rating-hover');
});
container.delegate('.r... | {
alert('Please input number from 1 to 99');
} | conditional_block |
macros.rs | except that a newline is not printed at
/// the end of the message.
///
/// Note that stdout is frequently line-buffered by default so it may be
/// necessary to use `io::stdout().flush()` to ensure the output is emitted
/// immediately.
///
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
/// # Exa... | /// let mut file = try!(File::create("my_best_friends.txt"));
/// try!(file.write_all(b"This is a list of my best friends."));
/// println!("I wrote to the file");
/// Ok(())
/// }
/// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), io::Error> {
/// let mut file = try!(Fil... | /// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn write_to_file_using_try() -> Result<(), io::Error> { | random_line_split |
FamilyCounter.py | from __future__ import print_function
import pandas as pd
from sklearn.base import TransformerMixin
class FamilyCounter(TransformerMixin):
def __init__(self, use=True):
self.use = use
def transform(self, features_raw, **transform_params):
if self.use:
features = features_raw.copy... | (self, **params):
if 'use' in params:
self.use = params.get('use') | set_params | identifier_name |
FamilyCounter.py | from __future__ import print_function
import pandas as pd
from sklearn.base import TransformerMixin
class FamilyCounter(TransformerMixin):
def __init__(self, use=True):
|
def transform(self, features_raw, **transform_params):
if self.use:
features = features_raw.copy(deep=True)
family = features_raw[['SibSp', 'Parch']]\
.apply(lambda x: x[0] + x[1], axis=1)
features.drop('SibSp', axis=1, inplace=True)
features... | self.use = use | identifier_body |
FamilyCounter.py | from __future__ import print_function
import pandas as pd
from sklearn.base import TransformerMixin
class FamilyCounter(TransformerMixin):
def __init__(self, use=True):
self.use = use
def transform(self, features_raw, **transform_params):
if self.use:
features = features_raw.copy... | self.use = params.get('use') | conditional_block | |
FamilyCounter.py | from __future__ import print_function
import pandas as pd
from sklearn.base import TransformerMixin
class FamilyCounter(TransformerMixin):
def __init__(self, use=True): | if self.use:
features = features_raw.copy(deep=True)
family = features_raw[['SibSp', 'Parch']]\
.apply(lambda x: x[0] + x[1], axis=1)
features.drop('SibSp', axis=1, inplace=True)
features.drop('Parch', axis=1, inplace=True)
return pd.co... | self.use = use
def transform(self, features_raw, **transform_params): | random_line_split |
main.js | (function($) {
$(document).ready( function() {
//prettyPhoto
$("a[rel^='prettyPhoto']").prettyPhoto({changepicturecallback: onPictureChanged,});
// TABS
(function() {
$('.b-tabs').on('click', 'li', function() {
var title = $(this),
tab = title.parent().siblings().children().eq(title.ind... |
});
});
});
})(jQuery);
// EXPERIENCIAS
(function ($) {
$(document).ready(function() {
$('.experiencia-link').on('click', function() {
moveButtons(".pp_details");
});
});
})(jQuery);
function moveButtons(dest) {
//alert('{^-^}');
jQuery('.pp_full_res > iframe').contents().find("... | {
jQuery(this).val(swap_val[i]);
} | conditional_block |
main.js | (function($) {
$(document).ready( function() {
//prettyPhoto
$("a[rel^='prettyPhoto']").prettyPhoto({changepicturecallback: onPictureChanged,});
// TABS
(function() {
$('.b-tabs').on('click', 'li', function() {
var title = $(this),
tab = title.parent().siblings().children().eq(title.ind... | // BUTTON UP
var btnUp = $('<div/>', {'class':'btn-up'});
btnUp.appendTo('body');
$(document)
.on('click', '.btn-up', function() {
$('html, body').animate({
scrollTop: 0
}, 700);
});
$(window)
.on('scroll', function() {
if ($(this).scrollTop() > 200)
$('.btn-up').addCl... | });
| random_line_split |
main.js | (function($) {
$(document).ready( function() {
//prettyPhoto
$("a[rel^='prettyPhoto']").prettyPhoto({changepicturecallback: onPictureChanged,});
// TABS
(function() {
$('.b-tabs').on('click', 'li', function() {
var title = $(this),
tab = title.parent().siblings().children().eq(title.ind... | (dest) {
//alert('{^-^}');
jQuery('.pp_full_res > iframe').contents().find(".sharethis-buttons").appendTo(dest);
jQuery('.pp_full_res > iframe').contents().find(".sharethis-buttons").hide();
//$('.pp_social').hide();
}
function onPictureChanged() {
moveButtons(".pp_details");
var href = "http://pinterest... | moveButtons | identifier_name |
main.js | (function($) {
$(document).ready( function() {
//prettyPhoto
$("a[rel^='prettyPhoto']").prettyPhoto({changepicturecallback: onPictureChanged,});
// TABS
(function() {
$('.b-tabs').on('click', 'li', function() {
var title = $(this),
tab = title.parent().siblings().children().eq(title.ind... | {
moveButtons(".pp_details");
var href = "http://pinterest.com/pin/create/button/?url="+ encodeURIComponent(location.href.replace(location.hash,"")) +"&media="+jQuery("#fullResImage").attr("src");
jQuery(".pp_social").append("<div class='pinterest' ><a href='"+ href +"' class='pin-it-button' count-layout='horizonta... | identifier_body | |
redirect.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... |
force = request.GET.get('force', None)
response = HttpResponse()
if force == '' and request.user.is_authenticated():
logout(request)
if request.user.is_authenticated():
# if user has not signed the approval terms
# redirect to approval terms with next the request path
i... | return HttpResponseForbidden(_(
astakos_messages.NOT_ALLOWED_NEXT_PARAM)) | conditional_block |
redirect.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | if not request.user.signed_terms:
# first build next parameter
parts = list(urlsplit(request.build_absolute_uri()))
params = dict(parse_qsl(parts[3], keep_blank_values=True))
parts[3] = urlencode(params)
next = urlunsplit(parts)
# build ur... |
if request.user.is_authenticated():
# if user has not signed the approval terms
# redirect to approval terms with next the request path | random_line_split |
redirect.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | (request):
"""
If there is no ``next`` request parameter redirects to astakos index page
displaying an error message.
If the request user is authenticated and has signed the approval terms,
redirects to `next` request parameter. If not, redirects to approval terms
in order to return back here af... | login | identifier_name |
redirect.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... |
if request.user.is_authenticated():
# if user has not signed the approval terms
# redirect to approval terms with next the request path
if not request.user.signed_terms:
# first build next parameter
parts = list(urlsplit(request.build_absolute_uri()))
par... | """
If there is no ``next`` request parameter redirects to astakos index page
displaying an error message.
If the request user is authenticated and has signed the approval terms,
redirects to `next` request parameter. If not, redirects to approval terms
in order to return back here after agreeing wi... | identifier_body |
edit_message_reply_markup.rs | use crate::requests::*;
use crate::types::*;
/// Use this method to edit only the reply markup of messages sent by the bot.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct EditMessageReplyMarkup {
chat_id: ChatRef,
message_id: MessageId,
... |
}
impl EditMessageReplyMarkup {
pub fn new<C, M, R>(chat: C, message_id: M, reply_markup: Option<R>) -> Self
where
C: ToChatRef,
M: ToMessageId,
R: Into<ReplyMarkup>,
{
EditMessageReplyMarkup {
chat_id: chat.to_chat_ref(),
message_id: message_id.to_m... | {
Self::Type::serialize(RequestUrl::method("editMessageReplyMarkup"), self)
} | identifier_body |
edit_message_reply_markup.rs | use crate::requests::*;
use crate::types::*;
/// Use this method to edit only the reply markup of messages sent by the bot.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct | {
chat_id: ChatRef,
message_id: MessageId,
#[serde(skip_serializing_if = "Option::is_none")]
reply_markup: Option<ReplyMarkup>,
}
impl Request for EditMessageReplyMarkup {
type Type = JsonRequestType<Self>;
type Response = JsonIdResponse<Message>;
fn serialize(&self) -> Result<HttpRequest... | EditMessageReplyMarkup | identifier_name |
edit_message_reply_markup.rs | use crate::requests::*;
use crate::types::*;
/// Use this method to edit only the reply markup of messages sent by the bot.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct EditMessageReplyMarkup {
chat_id: ChatRef,
message_id: MessageId,
... | {
EditMessageReplyMarkup::new(self.to_source_chat(), self.to_message_id(), reply_markup)
}
} | random_line_split | |
index3.js | grid.createFlatGrid(nx,nz,1,1);
grid.createIndices(nx,nz);
grid.createUVGrid(nx,nz);
// per instance data
// offsets = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( false );
p0s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ),... | onWindowResize | identifier_name | |
index3.js | (blob) {
saveAs(blob, "output" + MathUtils.GenerateUUID() + ".png");
});
}
else {
renderer.domElement.toBlob(function (blob) {
saveAs(blob, "output" + MathUtils.GenerateUUID() + ".jpg");
}, "image/jpeg");
}
}
////////////////////////////////////////////////
... | {
for (var i = 0; i < n; ++i) {
// particles are nomralised [0,1] -> remap to [-h,h]
var nx = Math.random()*0.99 ;
var ny = Math.random()*0.99 ;
var direction = (Math.random() < 0.5)? -1 : 1;
var thickness = 0.5 + Math.random()*1.5;
var nsteps = 30 + Math.random()*1... | identifier_body | |
index3.js | x*(p1.y - p0.y);
var x1 = p2.x + x*(p2.x - p3.x);
var y1 = p2.y + x*(p2.y - p3.y);
var tx = x0 + y*(x1- x0);
var ty = y0 + y*(y1- y0);
return {"y":ty,"x":tx};
}
//////////////////////////////////////////////////////////////////////////////////////////////
function randomiseField()
{
noiseOf... | function drawParticleUpdate() | random_line_split | |
index3.js | 2.x = 200;
basepath.p2.y = 100;
pathobj = new QCurveObj(basepath, 10);
// pathobj.addToScene(scene);
// geometry
nInstances = 200000; // max number of instances that can be render in one go
bufferix = 0;
grid = new InstancedGrid();
grid.print();
var nx = 2; // keep this as 2
va... | {
particle.update(thickness);
} | conditional_block | |
push_error.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | {
/// This error occurs when an attempt is made to create a new push promise but
/// the allowed limit for concurrent promises has already been reached.
TooManyActiveStreams
}
| PushError | identifier_name |
push_error.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | } | random_line_split | |
activitybarPart.ts | ';
import errors = require('vs/base/common/errors');
import events = require('vs/base/common/events');
import {ActionsOrientation, ActionBar, IActionItem} from 'vs/base/browser/ui/actionbar/actionbar';
import {Scope, IActionBarRegistry, Extensions as ActionBarExtensions, prepareActions} from 'vs/workbench/browser/actio... |
private registerListeners(): void {
// Activate viewlet action on opening of a viewlet
this.toUnbind.push(this.eventService.addListener(EventType.COMPOSITE_OPENING, (e: CompositeEvent) => this.onCompositeOpening(e)));
// Deactivate viewlet action on close
this.toUnbind.push(this.eventService.addListener(Ev... | {
this.instantiationService = service;
} | identifier_body |
activitybarPart.ts | ';
import errors = require('vs/base/common/errors');
import events = require('vs/base/common/events');
import {ActionsOrientation, ActionBar, IActionItem} from 'vs/base/browser/ui/actionbar/actionbar';
import {Scope, IActionBarRegistry, Extensions as ActionBarExtensions, prepareActions} from 'vs/workbench/browser/actio... |
let actionItem = actionBarRegistry.getActionItemForContext(Scope.GLOBAL, CONTEXT, action);
if (!actionItem) {
actionItem = new ActivityActionItem(action, action.label, keybinding);
}
if (actionItem instanceof ActivityActionItem) {
(<ActivityActionItem> actionItem).keybinding = keybinding;
... | {
keybinding = keys[0];
} | conditional_block |
activitybarPart.ts | /actions';
import errors = require('vs/base/common/errors');
import events = require('vs/base/common/events');
import {ActionsOrientation, ActionBar, IActionItem} from 'vs/base/browser/ui/actionbar/actionbar';
import {Scope, IActionBarRegistry, Extensions as ActionBarExtensions, prepareActions} from 'vs/workbench/brows... | (viewletId: string): void {
this.showActivity(viewletId, null);
}
public createContentArea(parent: Builder): Builder {
let $el = $(parent);
let $result = $('.content').appendTo($el);
// Top Actionbar with action items for each viewlet action
this.createViewletSwitcher($result.clone());
// Bottom Toolba... | clearActivity | identifier_name |
activitybarPart.ts | /base/browser/ui/actionbar/actionbar';
import {Scope, IActionBarRegistry, Extensions as ActionBarExtensions, prepareActions} from 'vs/workbench/browser/actionBarRegistry';
import {CONTEXT, ToolBar} from 'vs/base/browser/ui/toolbar/toolbar';
import {Registry} from 'vs/platform/platform';
import {CompositeEvent, EventTyp... | this.viewlet = viewlet;
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.