commit
stringlengths
40
40
old_file
stringlengths
4
234
new_file
stringlengths
4
234
old_contents
stringlengths
10
3.01k
new_contents
stringlengths
19
3.38k
subject
stringlengths
16
736
message
stringlengths
17
2.63k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
82.6k
config
stringclasses
4 values
content
stringlengths
134
4.41k
fuzzy_diff
stringlengths
29
3.44k
0c70c6e5ea5541a613d39c5e052ed2b3feb0ca6d
src/kernel/thread/sched_none.c
src/kernel/thread/sched_none.c
/** * @file * * @date Mar 21, 2013 * @author: Anton Bondarev */ struct sleepq; struct event; void sched_wake_all(struct sleepq *sq) { } int sched_sleep_ms(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_ms(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_ns(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_us(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_us(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_ns(struct sleepq *sq, unsigned long timeout) { return 0; }
/** * @file * * @date Mar 21, 2013 * @author: Anton Bondarev */ struct sleepq; struct event; void sched_wake_all(struct sleepq *sq) { } int sched_sleep(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked(struct sleepq *sq, unsigned long timeout) { return 0; }
Fix MIPS template in master
Fix MIPS template in master
C
bsd-2-clause
embox/embox,Kefir0192/embox,vrxfile/embox-trik,abusalimov/embox,mike2390/embox,gzoom13/embox,gzoom13/embox,vrxfile/embox-trik,Kakadu/embox,Kakadu/embox,Kefir0192/embox,Kefir0192/embox,Kakadu/embox,mike2390/embox,embox/embox,mike2390/embox,vrxfile/embox-trik,Kakadu/embox,vrxfile/embox-trik,embox/embox,Kefir0192/embox,mike2390/embox,gzoom13/embox,abusalimov/embox,embox/embox,gzoom13/embox,Kakadu/embox,vrxfile/embox-trik,embox/embox,mike2390/embox,Kefir0192/embox,Kakadu/embox,vrxfile/embox-trik,abusalimov/embox,Kefir0192/embox,Kakadu/embox,mike2390/embox,abusalimov/embox,vrxfile/embox-trik,Kefir0192/embox,gzoom13/embox,gzoom13/embox,gzoom13/embox,embox/embox,abusalimov/embox,abusalimov/embox,mike2390/embox
c
## Code Before: /** * @file * * @date Mar 21, 2013 * @author: Anton Bondarev */ struct sleepq; struct event; void sched_wake_all(struct sleepq *sq) { } int sched_sleep_ms(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_ms(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_ns(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_us(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_us(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked_ns(struct sleepq *sq, unsigned long timeout) { return 0; } ## Instruction: Fix MIPS template in master ## Code After: /** * @file * * @date Mar 21, 2013 * @author: Anton Bondarev */ struct sleepq; struct event; void sched_wake_all(struct sleepq *sq) { } int sched_sleep(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked(struct sleepq *sq, unsigned long timeout) { return 0; }
# ... existing code ... } int sched_sleep(struct sleepq *sq, unsigned long timeout) { return 0; } int sched_sleep_locked(struct sleepq *sq, unsigned long timeout) { return 0; } # ... rest of the code ...
b2e0a123631d326f06192a01758ebe581284dbdf
src/pip/_internal/operations/generate_metadata.py
src/pip/_internal/operations/generate_metadata.py
def get_metadata_generator(install_req): if install_req.use_pep517: return install_req.prepare_pep517_metadata else: return install_req.run_egg_info
def get_metadata_generator(install_req): if not install_req.use_pep517: return install_req.run_egg_info return install_req.prepare_pep517_metadata
Return early for legacy processes
Return early for legacy processes
Python
mit
xavfernandez/pip,pfmoore/pip,rouge8/pip,rouge8/pip,pradyunsg/pip,rouge8/pip,pfmoore/pip,sbidoul/pip,xavfernandez/pip,pypa/pip,pradyunsg/pip,xavfernandez/pip,pypa/pip,sbidoul/pip
python
## Code Before: def get_metadata_generator(install_req): if install_req.use_pep517: return install_req.prepare_pep517_metadata else: return install_req.run_egg_info ## Instruction: Return early for legacy processes ## Code After: def get_metadata_generator(install_req): if not install_req.use_pep517: return install_req.run_egg_info return install_req.prepare_pep517_metadata
// ... existing code ... def get_metadata_generator(install_req): if not install_req.use_pep517: return install_req.run_egg_info return install_req.prepare_pep517_metadata // ... rest of the code ...
5737f701d59c229d62f25734260fccb23722a67d
setup.py
setup.py
from distutils.core import setup try: from setuptools import setup except: pass setup( name = "pyjaco", version = "1.0.0", author = "Pyjaco development team", author_email = "[email protected]", description = ("Python to JavaScript translator"), url = "http://pyjaco.org", keywords = "python javascript translator compiler", packages=["pyjaco", "pyjaco.compiler"], )
from distutils.core import setup try: from setuptools import setup except: pass setup( name = "pyjaco", version = "1.0.0", author = "Pyjaco development team", author_email = "[email protected]", description = ("Python to JavaScript translator"), scripts = ["pyjs.py"], url = "http://pyjaco.org", keywords = "python javascript translator compiler", packages=["pyjaco", "pyjaco.compiler"], )
Include the pyjs compiler script in pypi distribution.
Include the pyjs compiler script in pypi distribution. I tested this in a virtualenv and it worked.
Python
mit
buchuki/pyjaco,chrivers/pyjaco,buchuki/pyjaco,chrivers/pyjaco,chrivers/pyjaco,buchuki/pyjaco
python
## Code Before: from distutils.core import setup try: from setuptools import setup except: pass setup( name = "pyjaco", version = "1.0.0", author = "Pyjaco development team", author_email = "[email protected]", description = ("Python to JavaScript translator"), url = "http://pyjaco.org", keywords = "python javascript translator compiler", packages=["pyjaco", "pyjaco.compiler"], ) ## Instruction: Include the pyjs compiler script in pypi distribution. I tested this in a virtualenv and it worked. ## Code After: from distutils.core import setup try: from setuptools import setup except: pass setup( name = "pyjaco", version = "1.0.0", author = "Pyjaco development team", author_email = "[email protected]", description = ("Python to JavaScript translator"), scripts = ["pyjs.py"], url = "http://pyjaco.org", keywords = "python javascript translator compiler", packages=["pyjaco", "pyjaco.compiler"], )
// ... existing code ... author = "Pyjaco development team", author_email = "[email protected]", description = ("Python to JavaScript translator"), scripts = ["pyjs.py"], url = "http://pyjaco.org", keywords = "python javascript translator compiler", packages=["pyjaco", "pyjaco.compiler"], // ... rest of the code ...
a561ae4e09a6651c68b0971706829b277bf427ce
src/com/sudoku/data/model/Comment.java
src/com/sudoku/data/model/Comment.java
package com.sudoku.data.model; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @author jonathan */ public class Comment { /** * Champs de la classe Comment * * */ private User author; private String pseudo; private String comment; private Integer grade; /** * Méthode de la classe Comment */ public Comment(String comment, Integer grade, User u) { this.comment = comment; this.grade = grade; this.author = u; this.pseudo = u.getPseudo(); } public static Comment buildFromAvroComment( com.sudoku.comm.generated.Comment comment) { return new Comment(comment.getComment(), comment.getGrade(), User.buildFromAvroUser(comment.getAuthor())); } public User getAuthor() { return author; } public String getPseudo() { return pseudo; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } }
package com.sudoku.data.model; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @author jonathan */ public class Comment { /** * Champs de la classe Comment * * */ private final User author; private final String pseudo; private final String userSalt; // We use the salt as an UUID to identify the poster private String comment; private Integer grade; /** * Méthode de la classe Comment * @param comment * @param grade * @param u */ public Comment(String comment, Integer grade, User u) { this.comment = comment; this.grade = grade; this.author = u; this.pseudo = u.getPseudo(); this.userSalt = u.getSalt(); } public static Comment buildFromAvroComment( com.sudoku.comm.generated.Comment comment) { return new Comment(comment.getComment(), comment.getGrade(), User.buildFromAvroUser(comment.getAuthor())); } public User getAuthor() { return author; } public String getPseudo() { return pseudo; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } }
Add final and add salt as an UUID
Add final and add salt as an UUID
Java
mit
BenFradet/LO23
java
## Code Before: package com.sudoku.data.model; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @author jonathan */ public class Comment { /** * Champs de la classe Comment * * */ private User author; private String pseudo; private String comment; private Integer grade; /** * Méthode de la classe Comment */ public Comment(String comment, Integer grade, User u) { this.comment = comment; this.grade = grade; this.author = u; this.pseudo = u.getPseudo(); } public static Comment buildFromAvroComment( com.sudoku.comm.generated.Comment comment) { return new Comment(comment.getComment(), comment.getGrade(), User.buildFromAvroUser(comment.getAuthor())); } public User getAuthor() { return author; } public String getPseudo() { return pseudo; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } } ## Instruction: Add final and add salt as an UUID ## Code After: package com.sudoku.data.model; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @author jonathan */ public class Comment { /** * Champs de la classe Comment * * */ private final User author; private final String pseudo; private final String userSalt; // We use the salt as an UUID to identify the poster private String comment; private Integer grade; /** * Méthode de la classe Comment * @param comment * @param grade * @param u */ public Comment(String comment, Integer grade, User u) { this.comment = comment; this.grade = grade; this.author = u; this.pseudo = u.getPseudo(); this.userSalt = u.getSalt(); } public static Comment buildFromAvroComment( com.sudoku.comm.generated.Comment comment) { return new Comment(comment.getComment(), comment.getGrade(), User.buildFromAvroUser(comment.getAuthor())); } public User getAuthor() { return author; } public String getPseudo() { return pseudo; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } }
... * Champs de la classe Comment * * */ private final User author; private final String pseudo; private final String userSalt; // We use the salt as an UUID to identify the poster private String comment; private Integer grade; /** * Méthode de la classe Comment * @param comment * @param grade * @param u */ public Comment(String comment, Integer grade, User u) { this.comment = comment; ... this.grade = grade; this.author = u; this.pseudo = u.getPseudo(); this.userSalt = u.getSalt(); } public static Comment buildFromAvroComment( ...
070b0e11e6c3d32a693792b157c7b334ec3cbd19
common/src/main/java/com/khorn/terraincontrol/configuration/settingType/StringListSetting.java
common/src/main/java/com/khorn/terraincontrol/configuration/settingType/StringListSetting.java
package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { String[] split = StringHelper.readCommaSeperatedString(string); for (int i = 0; i < split.length; i++) { // Trimming the values allows "Value1, Value2" instead of // "Value1,Value2" split[i] = split[i]; } return Arrays.asList(split); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } }
package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { return Arrays.asList(StringHelper.readCommaSeperatedString(string)); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } }
Remove some unneeded code, as StringHelper.readCommaSeperatedString already trims values
Remove some unneeded code, as StringHelper.readCommaSeperatedString already trims values
Java
mit
whichonespink44/TerrainControl,PG85/OpenTerrainGenerator,LinkBR/TerrainControl,Ezoteric/TerrainControl,MCTCP/TerrainControl
java
## Code Before: package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { String[] split = StringHelper.readCommaSeperatedString(string); for (int i = 0; i < split.length; i++) { // Trimming the values allows "Value1, Value2" instead of // "Value1,Value2" split[i] = split[i]; } return Arrays.asList(split); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } } ## Instruction: Remove some unneeded code, as StringHelper.readCommaSeperatedString already trims values ## Code After: package com.khorn.terraincontrol.configuration.settingType; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.helpers.StringHelper; import java.util.Arrays; import java.util.List; /** * Reads and writes a list of strings. Strings are read using * {@link StringHelper#readCommaSeperatedString(String)}, and written with a * ", " between each string. * */ class StringListSetting extends Setting<List<String>> { private String[] defaultValue; StringListSetting(String name, String... defaultValue) { super(name); this.defaultValue = defaultValue; } @Override public List<String> getDefaultValue() { return Arrays.asList(defaultValue); } @Override public List<String> read(String string) throws InvalidConfigException { return Arrays.asList(StringHelper.readCommaSeperatedString(string)); } @Override public String write(List<String> value) { return StringHelper.join(value, ", "); } }
// ... existing code ... @Override public List<String> read(String string) throws InvalidConfigException { return Arrays.asList(StringHelper.readCommaSeperatedString(string)); } @Override // ... rest of the code ...
372e5fdc0a5c630b2d196a782540606192b4cbfe
src/polyglot/ast/NumLit_c.java
src/polyglot/ast/NumLit_c.java
package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; /** * An integer literal: longs, ints, shorts, bytes, and chars. */ public abstract class NumLit_c extends Lit_c implements NumLit { protected long value; public NumLit_c(Position pos, long value) { super(pos); this.value = value; } /** Get the value of the expression. */ public long longValue() { return this.value; } /** Get the value of the expression, as an object. */ public Object objValue() { return new Long(this.value); } }
package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; /** * An integer literal: longs, ints, shorts, bytes, and chars. */ public abstract class NumLit_c extends Lit_c implements NumLit { protected long value; public NumLit_c(Position pos, long value) { super(pos); this.value = value; } /** Get the value of the expression. */ public long longValue() { return this.value; } /** Get the value of the expression, as an object. */ public Object objValue() { return new Long(this.value); } public void dump(CodeWriter w) { super.dump(w); w.allowBreak(4, " "); w.begin(0); w.write("(value " + value + ")"); w.end(); } }
Include value of numerical literals in AST dumps.
Include value of numerical literals in AST dumps.
Java
lgpl-2.1
liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,xcv58/polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,xcv58/polyglot
java
## Code Before: package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; /** * An integer literal: longs, ints, shorts, bytes, and chars. */ public abstract class NumLit_c extends Lit_c implements NumLit { protected long value; public NumLit_c(Position pos, long value) { super(pos); this.value = value; } /** Get the value of the expression. */ public long longValue() { return this.value; } /** Get the value of the expression, as an object. */ public Object objValue() { return new Long(this.value); } } ## Instruction: Include value of numerical literals in AST dumps. ## Code After: package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; /** * An integer literal: longs, ints, shorts, bytes, and chars. */ public abstract class NumLit_c extends Lit_c implements NumLit { protected long value; public NumLit_c(Position pos, long value) { super(pos); this.value = value; } /** Get the value of the expression. */ public long longValue() { return this.value; } /** Get the value of the expression, as an object. */ public Object objValue() { return new Long(this.value); } public void dump(CodeWriter w) { super.dump(w); w.allowBreak(4, " "); w.begin(0); w.write("(value " + value + ")"); w.end(); } }
# ... existing code ... public Object objValue() { return new Long(this.value); } public void dump(CodeWriter w) { super.dump(w); w.allowBreak(4, " "); w.begin(0); w.write("(value " + value + ")"); w.end(); } } # ... rest of the code ...
9c9a33869747223952b4a999a5a14354ffb3e540
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output)
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
Throw exception instead of returning false.
Throw exception instead of returning false.
Python
apache-2.0
StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2
python
## Code Before: from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) ## Instruction: Throw exception instead of returning false. ## Code After: from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
... repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output) ...
702a4596ce58b1f6f55340c7b37c007510ad2843
src/org/cryptonit/IOBuffer.java
src/org/cryptonit/IOBuffer.java
package org.cryptonit; import javacard.framework.JCSystem; public class IOBuffer { private FileIndex index = null; private byte [] buffer = null; private short [] shorts = null; private boolean [] bools = null; final private byte isLOADED = 0x0; final private byte isFILE = 0x1; public IOBuffer(FileIndex index) { this.index = index; this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT); this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT); this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT); } }
package org.cryptonit; import javacard.framework.JCSystem; public class IOBuffer { private FileIndex index = null; private byte [] buffer = null; private short [] shorts = null; final private byte SIZE = 0x0; final private byte PATH = 0x1; final private byte OFFSET = 0x2; private boolean [] bools = null; final private byte isLOADED = 0x0; final private byte isFILE = 0x1; public IOBuffer(FileIndex index) { this.index = index; this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT); this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT); this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT); } }
Define integer metadata array index constants
Define integer metadata array index constants
Java
agpl-3.0
mbrossard/cryptonit-applet
java
## Code Before: package org.cryptonit; import javacard.framework.JCSystem; public class IOBuffer { private FileIndex index = null; private byte [] buffer = null; private short [] shorts = null; private boolean [] bools = null; final private byte isLOADED = 0x0; final private byte isFILE = 0x1; public IOBuffer(FileIndex index) { this.index = index; this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT); this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT); this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT); } } ## Instruction: Define integer metadata array index constants ## Code After: package org.cryptonit; import javacard.framework.JCSystem; public class IOBuffer { private FileIndex index = null; private byte [] buffer = null; private short [] shorts = null; final private byte SIZE = 0x0; final private byte PATH = 0x1; final private byte OFFSET = 0x2; private boolean [] bools = null; final private byte isLOADED = 0x0; final private byte isFILE = 0x1; public IOBuffer(FileIndex index) { this.index = index; this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT); this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT); this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT); } }
// ... existing code ... private byte [] buffer = null; private short [] shorts = null; final private byte SIZE = 0x0; final private byte PATH = 0x1; final private byte OFFSET = 0x2; private boolean [] bools = null; final private byte isLOADED = 0x0; final private byte isFILE = 0x1; // ... rest of the code ...
4a214d4328de514574535cc43a1ce09699b96279
java/src/main/java/hwo/kurjatturskat/core/message/gameinit/TrackPieces.java
java/src/main/java/hwo/kurjatturskat/core/message/gameinit/TrackPieces.java
package hwo.kurjatturskat.core.message.gameinit; public class TrackPieces { public final Double length; public final Double radius; public final Double angle; public TrackPieces(Double length, Double radius, Double angle) { this.length = length; this.radius = radius; this.angle = angle; } public boolean isCurve() { return this.angle != null; } }
package hwo.kurjatturskat.core.message.gameinit; import com.google.gson.annotations.SerializedName; public class TrackPieces { public final Double length; public final Double radius; public final Double angle; @SerializedName("switch") public final boolean isSwitch; public TrackPieces(Double length, Double radius, Double angle, boolean isSwitch) { this.length = length; this.radius = radius; this.angle = angle; this.isSwitch = isSwitch; } public boolean isCurve() { return this.angle != null; } }
Add missing switch data field
Add missing switch data field
Java
apache-2.0
Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129,Arch-vile/hwo2014-team-129
java
## Code Before: package hwo.kurjatturskat.core.message.gameinit; public class TrackPieces { public final Double length; public final Double radius; public final Double angle; public TrackPieces(Double length, Double radius, Double angle) { this.length = length; this.radius = radius; this.angle = angle; } public boolean isCurve() { return this.angle != null; } } ## Instruction: Add missing switch data field ## Code After: package hwo.kurjatturskat.core.message.gameinit; import com.google.gson.annotations.SerializedName; public class TrackPieces { public final Double length; public final Double radius; public final Double angle; @SerializedName("switch") public final boolean isSwitch; public TrackPieces(Double length, Double radius, Double angle, boolean isSwitch) { this.length = length; this.radius = radius; this.angle = angle; this.isSwitch = isSwitch; } public boolean isCurve() { return this.angle != null; } }
... package hwo.kurjatturskat.core.message.gameinit; import com.google.gson.annotations.SerializedName; public class TrackPieces { public final Double length; ... public final Double radius; public final Double angle; @SerializedName("switch") public final boolean isSwitch; public TrackPieces(Double length, Double radius, Double angle, boolean isSwitch) { this.length = length; this.radius = radius; this.angle = angle; this.isSwitch = isSwitch; } public boolean isCurve() { ...
ae655d0979816892f4cb0a4f8a9b3cbe910d7248
stock_request_direction/models/stock_request_order.py
stock_request_direction/models/stock_request_order.py
from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
Add warehouse_id to existing onchange.
[IMP] Add warehouse_id to existing onchange.
Python
agpl-3.0
OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse
python
## Code Before: from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction ## Instruction: [IMP] Add warehouse_id to existing onchange. ## Code After: from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
// ... existing code ... readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers // ... modified code ... else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False // ... rest of the code ...
298f58e073b2782bd264edea969769b7b5e7cf41
libc/sysdeps/linux/arm/bits/arm_asm.h
libc/sysdeps/linux/arm/bits/arm_asm.h
/* Various definitons used the the ARM uClibc assembly code. */ #ifndef _ARM_ASM_H #define _ARM_ASM_H #ifdef __thumb2__ # ifdef __ASSEMBLER__ .thumb .syntax unified # endif /* __ASSEMBLER__ */ #define IT(t, cond) i##t cond #else /* XXX: This can be removed if/when we require an assembler that supports unified assembly syntax. */ #define IT(t, cond) /* Code to return from a thumb function stub. */ #ifdef __ARM_ARCH_4T__ #define POP_RET pop {r2, pc} #else #define POP_RET pop {r2, r3}; bx r3 #endif #endif #if defined(__ARM_ARCH_6M__) /* Force arm mode to flush out errors on M profile cores. */ #undef IT #define THUMB1_ONLY 1 #endif #endif /* _ARM_ASM_H */
/* Various definitons used the the ARM uClibc assembly code. */ #ifndef _ARM_ASM_H #define _ARM_ASM_H #ifdef __thumb2__ # ifdef __ASSEMBLER__ .thumb .syntax unified # endif /* __ASSEMBLER__ */ #define IT(t, cond) i##t cond #else /* XXX: This can be removed if/when we require an assembler that supports unified assembly syntax. */ #define IT(t, cond) /* Code to return from a thumb function stub. */ # if defined __ARM_ARCH_4T__ && defined __THUMB_INTERWORK__ # define POP_RET pop {r2, r3}; bx r3 # else # define POP_RET pop {r2, pc} # endif #endif /* __thumb2__ */ #if defined(__ARM_ARCH_6M__) /* Force arm mode to flush out errors on M profile cores. */ #undef IT #define THUMB1_ONLY 1 #endif #endif /* _ARM_ASM_H */
Fix POP_RET for armv4t && interworking
arm: Fix POP_RET for armv4t && interworking It seems the condition was reversed which lead to e.g. arm-920t being confused Signed-off-by: Bernhard Reutner-Fischer <[email protected]>
C
lgpl-2.1
kraj/uClibc,foss-for-synopsys-dwc-arc-processors/uClibc,brgl/uclibc-ng,kraj/uclibc-ng,wbx-github/uclibc-ng,majek/uclibc-vx32,brgl/uclibc-ng,kraj/uClibc,brgl/uclibc-ng,foss-for-synopsys-dwc-arc-processors/uClibc,foss-for-synopsys-dwc-arc-processors/uClibc,wbx-github/uclibc-ng,majek/uclibc-vx32,kraj/uClibc,kraj/uclibc-ng,brgl/uclibc-ng,kraj/uclibc-ng,foss-for-synopsys-dwc-arc-processors/uClibc,kraj/uclibc-ng,wbx-github/uclibc-ng,wbx-github/uclibc-ng,majek/uclibc-vx32,majek/uclibc-vx32,kraj/uClibc
c
## Code Before: /* Various definitons used the the ARM uClibc assembly code. */ #ifndef _ARM_ASM_H #define _ARM_ASM_H #ifdef __thumb2__ # ifdef __ASSEMBLER__ .thumb .syntax unified # endif /* __ASSEMBLER__ */ #define IT(t, cond) i##t cond #else /* XXX: This can be removed if/when we require an assembler that supports unified assembly syntax. */ #define IT(t, cond) /* Code to return from a thumb function stub. */ #ifdef __ARM_ARCH_4T__ #define POP_RET pop {r2, pc} #else #define POP_RET pop {r2, r3}; bx r3 #endif #endif #if defined(__ARM_ARCH_6M__) /* Force arm mode to flush out errors on M profile cores. */ #undef IT #define THUMB1_ONLY 1 #endif #endif /* _ARM_ASM_H */ ## Instruction: arm: Fix POP_RET for armv4t && interworking It seems the condition was reversed which lead to e.g. arm-920t being confused Signed-off-by: Bernhard Reutner-Fischer <[email protected]> ## Code After: /* Various definitons used the the ARM uClibc assembly code. */ #ifndef _ARM_ASM_H #define _ARM_ASM_H #ifdef __thumb2__ # ifdef __ASSEMBLER__ .thumb .syntax unified # endif /* __ASSEMBLER__ */ #define IT(t, cond) i##t cond #else /* XXX: This can be removed if/when we require an assembler that supports unified assembly syntax. */ #define IT(t, cond) /* Code to return from a thumb function stub. */ # if defined __ARM_ARCH_4T__ && defined __THUMB_INTERWORK__ # define POP_RET pop {r2, r3}; bx r3 # else # define POP_RET pop {r2, pc} # endif #endif /* __thumb2__ */ #if defined(__ARM_ARCH_6M__) /* Force arm mode to flush out errors on M profile cores. */ #undef IT #define THUMB1_ONLY 1 #endif #endif /* _ARM_ASM_H */
# ... existing code ... unified assembly syntax. */ #define IT(t, cond) /* Code to return from a thumb function stub. */ # if defined __ARM_ARCH_4T__ && defined __THUMB_INTERWORK__ # define POP_RET pop {r2, r3}; bx r3 # else # define POP_RET pop {r2, pc} # endif #endif /* __thumb2__ */ #if defined(__ARM_ARCH_6M__) /* Force arm mode to flush out errors on M profile cores. */ # ... rest of the code ...
01847c64869298a436980eb17c549d49f09d6a91
src/nodeconductor_openstack/openstack_tenant/perms.py
src/nodeconductor_openstack/openstack_tenant/perms.py
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), )
from nodeconductor.core.permissions import StaffPermissionLogic from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), ('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)), )
Add permissions to service properties
Add permissions to service properties - wal-94
Python
mit
opennode/nodeconductor-openstack
python
## Code Before: from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), ) ## Instruction: Add permissions to service properties - wal-94 ## Code After: from nodeconductor.core.permissions import StaffPermissionLogic from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), ('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)), )
// ... existing code ... from nodeconductor.core.permissions import StaffPermissionLogic from nodeconductor.structure import perms as structure_perms // ... modified code ... PERMISSION_LOGICS = ( ('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic), ('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic), ('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)), ('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)), ) // ... rest of the code ...
75afa4e0a18601ef3578ed3c3bfa880aeafd8881
ruffy-spi/src/main/java/de/jotomo/ruffy/spi/BasalProfile.java
ruffy-spi/src/main/java/de/jotomo/ruffy/spi/BasalProfile.java
package de.jotomo.ruffy.spi; public class BasalProfile { public final int number; public final double[] hourlyRates; public BasalProfile(int number, double[] hourlyRates) { this.number = number; if (hourlyRates.length != 24) throw new IllegalArgumentException("Profile must have 24 hourly rates"); this.hourlyRates = hourlyRates; } }
package de.jotomo.ruffy.spi; public class BasalProfile { public final double[] hourlyRates; public BasalProfile( double[] hourlyRates) { this.hourlyRates = hourlyRates; } }
Remove basal rate profile number, only using one.
Remove basal rate profile number, only using one.
Java
agpl-3.0
jotomo/AndroidAPS,MilosKozak/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS,Heiner1/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,PoweRGbg/AndroidAPS,MilosKozak/AndroidAPS
java
## Code Before: package de.jotomo.ruffy.spi; public class BasalProfile { public final int number; public final double[] hourlyRates; public BasalProfile(int number, double[] hourlyRates) { this.number = number; if (hourlyRates.length != 24) throw new IllegalArgumentException("Profile must have 24 hourly rates"); this.hourlyRates = hourlyRates; } } ## Instruction: Remove basal rate profile number, only using one. ## Code After: package de.jotomo.ruffy.spi; public class BasalProfile { public final double[] hourlyRates; public BasalProfile( double[] hourlyRates) { this.hourlyRates = hourlyRates; } }
# ... existing code ... package de.jotomo.ruffy.spi; public class BasalProfile { public final double[] hourlyRates; public BasalProfile( double[] hourlyRates) { this.hourlyRates = hourlyRates; } } # ... rest of the code ...
53a1c2ccbd43a8fcb90d8d9b7814c8ed129c0635
thumbor_botornado/s3_http_loader.py
thumbor_botornado/s3_http_loader.py
from botornado.s3.bucket import AsyncBucket from botornado.s3.connection import AsyncS3Connection from botornado.s3.key import AsyncKey from thumbor_botornado.s3_loader import S3Loader from thumbor.loaders.http_loader import HttpLoader def load(context, url, callback): p = re.compile('/^https?:/i') m = p.match(url) if m: HttpLoader.load(context, url, callback) else: S3Loader.load(context, url, callback)
import thumbor_botornado.s3_loader as S3Loader import thumbor.loaders.http_loader as HttpLoader import re def load(context, url, callback): if re.match('https?:', url, re.IGNORECASE): HttpLoader.load(context, url, callback) else: S3Loader.load(context, url, callback)
Add s3-http loader which delegates based on the uri
Add s3-http loader which delegates based on the uri
Python
mit
99designs/thumbor_botornado,Jimdo/thumbor_botornado,99designs/thumbor_botornado,Jimdo/thumbor_botornado
python
## Code Before: from botornado.s3.bucket import AsyncBucket from botornado.s3.connection import AsyncS3Connection from botornado.s3.key import AsyncKey from thumbor_botornado.s3_loader import S3Loader from thumbor.loaders.http_loader import HttpLoader def load(context, url, callback): p = re.compile('/^https?:/i') m = p.match(url) if m: HttpLoader.load(context, url, callback) else: S3Loader.load(context, url, callback) ## Instruction: Add s3-http loader which delegates based on the uri ## Code After: import thumbor_botornado.s3_loader as S3Loader import thumbor.loaders.http_loader as HttpLoader import re def load(context, url, callback): if re.match('https?:', url, re.IGNORECASE): HttpLoader.load(context, url, callback) else: S3Loader.load(context, url, callback)
// ... existing code ... import thumbor_botornado.s3_loader as S3Loader import thumbor.loaders.http_loader as HttpLoader import re def load(context, url, callback): if re.match('https?:', url, re.IGNORECASE): HttpLoader.load(context, url, callback) else: S3Loader.load(context, url, callback) // ... rest of the code ...
2f152c5036d32a780741edd8fb6ce75684728824
singleuser/user-config.py
singleuser/user-config.py
import os mylang = 'test' family = 'wikipedia' # Not defining any extra variables here at all since that causes pywikibot # to issue a warning about potential misspellings if os.path.exists(os.path.expanduser('~/user-config.py')): with open(os.path.expanduser('~/user-config.py'), 'r') as f: exec( compile(f.read(), os.path.expanduser('~/user-config.py'), 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['JPY_USER']
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['JPY_USER']
Revert "Do not introduce extra variables"
Revert "Do not introduce extra variables" Since the 'f' is considered an extra variable and introduces a warning anyway :( Let's fix this the right way This reverts commit a03de68fb772d859098327d0e54a219fe4507072.
Python
mit
yuvipanda/paws,yuvipanda/paws
python
## Code Before: import os mylang = 'test' family = 'wikipedia' # Not defining any extra variables here at all since that causes pywikibot # to issue a warning about potential misspellings if os.path.exists(os.path.expanduser('~/user-config.py')): with open(os.path.expanduser('~/user-config.py'), 'r') as f: exec( compile(f.read(), os.path.expanduser('~/user-config.py'), 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['JPY_USER'] ## Instruction: Revert "Do not introduce extra variables" Since the 'f' is considered an extra variable and introduces a warning anyway :( Let's fix this the right way This reverts commit a03de68fb772d859098327d0e54a219fe4507072. ## Code After: import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['JPY_USER']
... family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['JPY_USER'] ...
f89c60e6ff2c846aacd39db8488de1300b156a71
src/membership/web/views.py
src/membership/web/views.py
from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) m.update(self.request.form) if (not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({'ok': True}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id})
from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) if (not self.try_update_model(m) or not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id})
Use try_update_model in sign in handler instead of dict update.
Use try_update_model in sign in handler instead of dict update.
Python
mit
akornatskyy/sample-blog-api,akornatskyy/sample-blog-api
python
## Code Before: from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) m.update(self.request.form) if (not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({'ok': True}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id}) ## Instruction: Use try_update_model in sign in handler instead of dict update. ## Code After: from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) if (not self.try_update_model(m) or not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id})
... def post(self): m = attrdict(username=u(''), password=u('')) if (not self.try_update_model(m) or not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) ... def get(self): del self.principal return self.json_response({}) class UserHandler(APIHandler): ...
a99d8443c0671c5c879c7e7688db2fe8ff4428cf
xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-repositories/xwiki-platform-extension-repository-xwiki/xwiki-platform-extension-repository-xwiki-api/src/main/java/org/xwiki/extension/repository/xwiki/Resources.java
xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-repositories/xwiki-platform-extension-repository-xwiki/xwiki-platform-extension-repository-xwiki-api/src/main/java/org/xwiki/extension/repository/xwiki/Resources.java
package org.xwiki.extension.repository.xwiki; /** * Resources to use to access Extension Manager REST service. * <p> * Resources producing list of result support the following arguments: * <ul> * <li>start: offset where the search start to return results</li> * <li>number: maximum number of results</li> * </ul> * <p> * Resources producing extensions descriptor support the following arguments: * <ul> * <li>language: language used to resolve the descriptor values</li> * </ul> * * @version $Id$ */ public class Resources { // Entry point public final static String ENTRYPOINT = "/extensions"; // Extensions /** * ?start={offset}&number={number} */ public final static String EXTENSION_ID = ENTRYPOINT + "/ids/{extensionId}"; public final static String EXTENSION = EXTENSION_ID + "/versions/{extensionVersion}"; public final static String EXTENSIONFILE = EXTENSION + "/file"; // Search /** * ?q={keywords} */ public final static String SEARCH = ENTRYPOINT + "/search"; /** * ?q={keywords} */ public final static String SEARCH_FROM_ID = EXTENSION_ID + "/search"; // Index public final static String EXTENSION_INDEX = ENTRYPOINT + "/index"; }
package org.xwiki.extension.repository.xwiki; /** * Resources to use to access Extension Manager REST service. * <p> * Resources producing list of result support the following arguments: * <ul> * <li>start: offset where the search start to return results</li> * <li>number: maximum number of results</li> * </ul> * <p> * Resources producing extensions descriptor support the following arguments: * <ul> * <li>language: language used to resolve the descriptor values</li> * </ul> * * @version $Id$ */ public class Resources { // Entry point public final static String ENTRYPOINT = "/repository"; // Extensions /** * ?start={offset}&number={number} */ public final static String EXTENSIONS = ENTRYPOINT + "/extensions"; public final static String EXTENSIONS_ID = EXTENSIONS + "/{extensionId}"; public final static String EXTENSIONSVERSIONS = EXTENSIONS_ID + "/versions"; public final static String EXTENSIONSVERSIONS_VERSION = EXTENSIONSVERSIONS + "/{extensionVersion}"; public final static String EXTENSIONFILE = EXTENSIONSVERSIONS + "/file"; // Search /** * ?q={keywords} */ public final static String SEARCH = ENTRYPOINT + "/search"; /** * ?q={keywords} */ public final static String SEARCH_FROM_ID = EXTENSIONS_ID + "/search"; }
Make XWiki Repository protocol more restfull
XWIKI-6871: Make XWiki Repository protocol more restfull
Java
lgpl-2.1
xwiki/xwiki-commons,xwiki/xwiki-commons
java
## Code Before: package org.xwiki.extension.repository.xwiki; /** * Resources to use to access Extension Manager REST service. * <p> * Resources producing list of result support the following arguments: * <ul> * <li>start: offset where the search start to return results</li> * <li>number: maximum number of results</li> * </ul> * <p> * Resources producing extensions descriptor support the following arguments: * <ul> * <li>language: language used to resolve the descriptor values</li> * </ul> * * @version $Id$ */ public class Resources { // Entry point public final static String ENTRYPOINT = "/extensions"; // Extensions /** * ?start={offset}&number={number} */ public final static String EXTENSION_ID = ENTRYPOINT + "/ids/{extensionId}"; public final static String EXTENSION = EXTENSION_ID + "/versions/{extensionVersion}"; public final static String EXTENSIONFILE = EXTENSION + "/file"; // Search /** * ?q={keywords} */ public final static String SEARCH = ENTRYPOINT + "/search"; /** * ?q={keywords} */ public final static String SEARCH_FROM_ID = EXTENSION_ID + "/search"; // Index public final static String EXTENSION_INDEX = ENTRYPOINT + "/index"; } ## Instruction: XWIKI-6871: Make XWiki Repository protocol more restfull ## Code After: package org.xwiki.extension.repository.xwiki; /** * Resources to use to access Extension Manager REST service. * <p> * Resources producing list of result support the following arguments: * <ul> * <li>start: offset where the search start to return results</li> * <li>number: maximum number of results</li> * </ul> * <p> * Resources producing extensions descriptor support the following arguments: * <ul> * <li>language: language used to resolve the descriptor values</li> * </ul> * * @version $Id$ */ public class Resources { // Entry point public final static String ENTRYPOINT = "/repository"; // Extensions /** * ?start={offset}&number={number} */ public final static String EXTENSIONS = ENTRYPOINT + "/extensions"; public final static String EXTENSIONS_ID = EXTENSIONS + "/{extensionId}"; public final static String EXTENSIONSVERSIONS = EXTENSIONS_ID + "/versions"; public final static String EXTENSIONSVERSIONS_VERSION = EXTENSIONSVERSIONS + "/{extensionVersion}"; public final static String EXTENSIONFILE = EXTENSIONSVERSIONS + "/file"; // Search /** * ?q={keywords} */ public final static String SEARCH = ENTRYPOINT + "/search"; /** * ?q={keywords} */ public final static String SEARCH_FROM_ID = EXTENSIONS_ID + "/search"; }
// ... existing code ... { // Entry point public final static String ENTRYPOINT = "/repository"; // Extensions // ... modified code ... /** * ?start={offset}&number={number} */ public final static String EXTENSIONS = ENTRYPOINT + "/extensions"; public final static String EXTENSIONS_ID = EXTENSIONS + "/{extensionId}"; public final static String EXTENSIONSVERSIONS = EXTENSIONS_ID + "/versions"; public final static String EXTENSIONSVERSIONS_VERSION = EXTENSIONSVERSIONS + "/{extensionVersion}"; public final static String EXTENSIONFILE = EXTENSIONSVERSIONS + "/file"; // Search ... /** * ?q={keywords} */ public final static String SEARCH_FROM_ID = EXTENSIONS_ID + "/search"; } // ... rest of the code ...
0eb20c8025a838d93a5854442640550d5bf05b0b
settings.py
settings.py
# Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' ANDROID_CLIENT_ID = 'replace with Android client ID' IOS_CLIENT_ID = 'replace with iOS client ID' ANDROID_AUDIENCE = WEB_CLIENT_ID
# Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' ANDROID_CLIENT_ID = '757224007118-dpqfa375ra8rgbpslig7beh4jb6qd03s.apps.googleusercontent.com' IOS_CLIENT_ID = '757224007118-nfgr65ic7dpiv5inbvta8a2b4j2h7d09.apps.googleusercontent.com' ANDROID_AUDIENCE = WEB_CLIENT_ID
Add android and ios client IDs
Add android and ios client IDs
Python
apache-2.0
elbernante/conference-central,elbernante/conference-central,elbernante/conference-central
python
## Code Before: # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' ANDROID_CLIENT_ID = 'replace with Android client ID' IOS_CLIENT_ID = 'replace with iOS client ID' ANDROID_AUDIENCE = WEB_CLIENT_ID ## Instruction: Add android and ios client IDs ## Code After: # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' ANDROID_CLIENT_ID = '757224007118-dpqfa375ra8rgbpslig7beh4jb6qd03s.apps.googleusercontent.com' IOS_CLIENT_ID = '757224007118-nfgr65ic7dpiv5inbvta8a2b4j2h7d09.apps.googleusercontent.com' ANDROID_AUDIENCE = WEB_CLIENT_ID
// ... existing code ... # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com' ANDROID_CLIENT_ID = '757224007118-dpqfa375ra8rgbpslig7beh4jb6qd03s.apps.googleusercontent.com' IOS_CLIENT_ID = '757224007118-nfgr65ic7dpiv5inbvta8a2b4j2h7d09.apps.googleusercontent.com' ANDROID_AUDIENCE = WEB_CLIENT_ID // ... rest of the code ...
d6d656ae00418edab0a1f86b46997b3cce316731
moho-api/src/main/java/com/voxeo/moho/media/input/SignalGrammar.java
moho-api/src/main/java/com/voxeo/moho/media/input/SignalGrammar.java
package com.voxeo.moho.media.input; public class SignalGrammar extends Grammar { public enum Signal { FAX_CED, FAX_CNG, BEEP, RING, SIT, MODEM, OFFHOOK; public static Signal parse(String value) { if ("beep".equalsIgnoreCase(value)) { return BEEP; } if ("modem".equalsIgnoreCase(value)) { return MODEM; } if ("sit".equalsIgnoreCase(value)) { return SIT; } if ("fax".equalsIgnoreCase(value)) { return FAX_CED; } if ("fax-cng".equalsIgnoreCase(value)) { return FAX_CNG; } if ("ring".equalsIgnoreCase(value)) { return RING; } if ("offhook".equalsIgnoreCase(value)) { return OFFHOOK; } return null; } } protected final Signal _signal; public SignalGrammar(final Signal signal, final boolean terminating) { super(null, null, terminating); _signal = signal; } public Signal getSignal() { return _signal; } }
package com.voxeo.moho.media.input; public class SignalGrammar extends Grammar { public enum Signal { FAX_CED, FAX_CNG, BEEP, RING, SIT, MODEM, OFFHOOK; public static Signal parse(String value) { if ("beep".equalsIgnoreCase(value)) { return BEEP; } if ("modem".equalsIgnoreCase(value)) { return MODEM; } if ("sit".equalsIgnoreCase(value)) { return SIT; } if ("fax".equalsIgnoreCase(value)) { return FAX_CED; } if ("fax-cng".equalsIgnoreCase(value)) { return FAX_CNG; } if ("ring".equalsIgnoreCase(value)) { return RING; } if ("offhook".equalsIgnoreCase(value)) { return OFFHOOK; } return null; } @Override public String toString() { if (this == FAX_CED) { return "fax"; } if (this == FAX_CNG) { return "fax-cng"; } return super.toString(); } } protected final Signal _signal; public SignalGrammar(final Signal signal, final boolean terminating) { super(null, null, terminating); _signal = signal; } public Signal getSignal() { return _signal; } }
Fix the werid parse by overriding toString method
MOHO-15: Fix the werid parse by overriding toString method
Java
apache-2.0
voxeolabs/moho,voxeolabs/moho
java
## Code Before: package com.voxeo.moho.media.input; public class SignalGrammar extends Grammar { public enum Signal { FAX_CED, FAX_CNG, BEEP, RING, SIT, MODEM, OFFHOOK; public static Signal parse(String value) { if ("beep".equalsIgnoreCase(value)) { return BEEP; } if ("modem".equalsIgnoreCase(value)) { return MODEM; } if ("sit".equalsIgnoreCase(value)) { return SIT; } if ("fax".equalsIgnoreCase(value)) { return FAX_CED; } if ("fax-cng".equalsIgnoreCase(value)) { return FAX_CNG; } if ("ring".equalsIgnoreCase(value)) { return RING; } if ("offhook".equalsIgnoreCase(value)) { return OFFHOOK; } return null; } } protected final Signal _signal; public SignalGrammar(final Signal signal, final boolean terminating) { super(null, null, terminating); _signal = signal; } public Signal getSignal() { return _signal; } } ## Instruction: MOHO-15: Fix the werid parse by overriding toString method ## Code After: package com.voxeo.moho.media.input; public class SignalGrammar extends Grammar { public enum Signal { FAX_CED, FAX_CNG, BEEP, RING, SIT, MODEM, OFFHOOK; public static Signal parse(String value) { if ("beep".equalsIgnoreCase(value)) { return BEEP; } if ("modem".equalsIgnoreCase(value)) { return MODEM; } if ("sit".equalsIgnoreCase(value)) { return SIT; } if ("fax".equalsIgnoreCase(value)) { return FAX_CED; } if ("fax-cng".equalsIgnoreCase(value)) { return FAX_CNG; } if ("ring".equalsIgnoreCase(value)) { return RING; } if ("offhook".equalsIgnoreCase(value)) { return OFFHOOK; } return null; } @Override public String toString() { if (this == FAX_CED) { return "fax"; } if (this == FAX_CNG) { return "fax-cng"; } return super.toString(); } } protected final Signal _signal; public SignalGrammar(final Signal signal, final boolean terminating) { super(null, null, terminating); _signal = signal; } public Signal getSignal() { return _signal; } }
... } return null; } @Override public String toString() { if (this == FAX_CED) { return "fax"; } if (this == FAX_CNG) { return "fax-cng"; } return super.toString(); } } protected final Signal _signal; ...
8aeee881bb32935718e767114256179f9c9bf216
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "email": user.email, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
Remove email from User API Test
Remove email from User API Test
Python
bsd-3-clause
ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django
python
## Code Before: import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "email": user.email, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", } ## Instruction: Remove email from User API Test ## Code After: import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
# ... existing code ... assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", } # ... rest of the code ...
8723611817a982907f3f0a98ed4678d587597002
src/appleseed.python/test/runtests.py
src/appleseed.python/test/runtests.py
import unittest from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
import unittest from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
Add new unit tests to collection
Add new unit tests to collection
Python
mit
pjessesco/appleseed,dictoon/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,glebmish/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,dictoon/appleseed,luisbarrancos/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,dictoon/appleseed,aiivashchenko/appleseed,gospodnetic/appleseed,gospodnetic/appleseed,Biart95/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,Biart95/appleseed,dictoon/appleseed,aiivashchenko/appleseed,aiivashchenko/appleseed,Aakash1312/appleseed,Biart95/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,dictoon/appleseed,appleseedhq/appleseed,Aakash1312/appleseed,aytekaman/appleseed,pjessesco/appleseed,est77/appleseed,pjessesco/appleseed,glebmish/appleseed,aiivashchenko/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,aytekaman/appleseed,est77/appleseed,est77/appleseed,gospodnetic/appleseed,Biart95/appleseed,glebmish/appleseed,glebmish/appleseed,est77/appleseed,appleseedhq/appleseed
python
## Code Before: import unittest from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner()) ## Instruction: Add new unit tests to collection ## Code After: import unittest from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import * unittest.TestProgram(testRunner = unittest.TextTestRunner())
# ... existing code ... import unittest from testbasis import * from testdict2dict import * from testentitymap import * from testentityvector import * # ... rest of the code ...
7c47a2960d644b34ce3ff569042fb5e965270e8c
netsecus/task.py
netsecus/task.py
from __future__ import unicode_literals class Task(object): def __init__(self, taskID, sheetID, name, description, maxPoints, reachedPoints=0): self.id = taskID self.sheetID = sheetID self.name = name self.description = description self.maxPoints = maxPoints self.reachedPoints = reachedPoints
from __future__ import unicode_literals class Task(object): def __init__(self, taskID, sheetID, name, description, maxPoints): self.id = taskID self.sheetID = sheetID self.name = name self.description = description self.maxPoints = maxPoints
Remove unneeded 'reachedPoints' variable from Task class
Remove unneeded 'reachedPoints' variable from Task class
Python
mit
hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem
python
## Code Before: from __future__ import unicode_literals class Task(object): def __init__(self, taskID, sheetID, name, description, maxPoints, reachedPoints=0): self.id = taskID self.sheetID = sheetID self.name = name self.description = description self.maxPoints = maxPoints self.reachedPoints = reachedPoints ## Instruction: Remove unneeded 'reachedPoints' variable from Task class ## Code After: from __future__ import unicode_literals class Task(object): def __init__(self, taskID, sheetID, name, description, maxPoints): self.id = taskID self.sheetID = sheetID self.name = name self.description = description self.maxPoints = maxPoints
# ... existing code ... class Task(object): def __init__(self, taskID, sheetID, name, description, maxPoints): self.id = taskID self.sheetID = sheetID self.name = name self.description = description self.maxPoints = maxPoints # ... rest of the code ...
c3745e7017c1788f4633d09ef4d29a37018b53d3
populus/cli/main.py
populus/cli/main.py
import click @click.group() def main(): """ Populus """ pass
import click CONTEXT_SETTINGS = dict( # Support -h as a shortcut for --help help_option_names=['-h', '--help'], ) @click.group(context_settings=CONTEXT_SETTINGS) def main(): """ Populus """ pass
Support -h as a shortcut for --help
CLI: Support -h as a shortcut for --help
Python
mit
pipermerriam/populus,euri10/populus,euri10/populus,pipermerriam/populus,euri10/populus
python
## Code Before: import click @click.group() def main(): """ Populus """ pass ## Instruction: CLI: Support -h as a shortcut for --help ## Code After: import click CONTEXT_SETTINGS = dict( # Support -h as a shortcut for --help help_option_names=['-h', '--help'], ) @click.group(context_settings=CONTEXT_SETTINGS) def main(): """ Populus """ pass
# ... existing code ... import click CONTEXT_SETTINGS = dict( # Support -h as a shortcut for --help help_option_names=['-h', '--help'], ) @click.group(context_settings=CONTEXT_SETTINGS) def main(): """ Populus # ... rest of the code ...
4158e2b5d2d7524f4d8e66b9ee021c1f63e11b25
blanc_basic_events/events/templatetags/events_tags.py
blanc_basic_events/events/templatetags/events_tags.py
from django import template from blanc_basic_events.events.models import Event register = template.Library() @register.assignment_tag def get_events(): return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
from django import template from blanc_basic_events.events.models import Category, Event register = template.Library() @register.assignment_tag def get_events_categories(): return Category.objects.all() @register.assignment_tag def get_events(): return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
Tag to get all categories
Tag to get all categories
Python
bsd-3-clause
blancltd/blanc-basic-events
python
## Code Before: from django import template from blanc_basic_events.events.models import Event register = template.Library() @register.assignment_tag def get_events(): return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set') ## Instruction: Tag to get all categories ## Code After: from django import template from blanc_basic_events.events.models import Category, Event register = template.Library() @register.assignment_tag def get_events_categories(): return Category.objects.all() @register.assignment_tag def get_events(): return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
... from django import template from blanc_basic_events.events.models import Category, Event register = template.Library() @register.assignment_tag def get_events_categories(): return Category.objects.all() @register.assignment_tag def get_events(): return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set') ...
cdbaf22e9897597d142a4bf7fc59defff022a799
web/src/main/java/org/cbioportal/web/parameter/ResultPageSettings.java
web/src/main/java/org/cbioportal/web/parameter/ResultPageSettings.java
package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } class ClinicalTrackConfig { public String stableId; public String sortOrder; public boolean gapOn; }
package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.ALWAYS) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } @JsonInclude(Include.ALWAYS) class ClinicalTrackConfig { public String stableId; public String sortOrder; public Boolean gapOn; }
Store clinical track fields with null values in session
Store clinical track fields with null values in session
Java
agpl-3.0
cBioPortal/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,onursumer/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal
java
## Code Before: package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } class ClinicalTrackConfig { public String stableId; public String sortOrder; public boolean gapOn; } ## Instruction: Store clinical track fields with null values in session ## Code After: package org.cbioportal.web.parameter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.ALWAYS) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); public List<ClinicalTrackConfig> getClinicallist() { return clinicallist; } public void setClinicallist(List<ClinicalTrackConfig> clinicallist) { this.clinicallist = clinicallist; } } @JsonInclude(Include.ALWAYS) class ClinicalTrackConfig { public String stableId; public String sortOrder; public Boolean gapOn; }
# ... existing code ... import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.ALWAYS) public class ResultPageSettings extends PageSettingsData implements Serializable { private List<ClinicalTrackConfig> clinicallist = new ArrayList<>(); # ... modified code ... } } @JsonInclude(Include.ALWAYS) class ClinicalTrackConfig { public String stableId; public String sortOrder; public Boolean gapOn; } # ... rest of the code ...
65529690d8fecbf81087c6f43316f054288785ec
twenty3.py
twenty3.py
from pync import Notifier from time import sleep import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--min', type=int, help="Minutes before break", default="20") args = parser.parse_args() if not args.min: raise ValueError("Invalid minutes") while True: sleep(args.min*60) Notifier.notify('Time for a break.', title="Reminder") if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
from pync import Notifier from time import sleep import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--min', type=int, help="Timeout before sending alert (minutes)", default="20") parser.add_argument('--duration', type=int, help="Duration of break (seconds)", default="20") args = parser.parse_args() if not (args.min and args.duration): raise ValueError("Invalid arguments") while True: # sleep for n minutes sleep(args.min*60) # break time Notifier.notify( 'Take a break for %d secs' % args.duration, title="Break reminder" ) # on break sleep(args.duration) # back to work Notifier.notify("Back to work", Title="Break reminder") if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
Add break duration argument and sleep timeout. Add notification when it is time to get back to work
Add break duration argument and sleep timeout. Add notification when it is time to get back to work
Python
mit
mgalang/twenty3
python
## Code Before: from pync import Notifier from time import sleep import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--min', type=int, help="Minutes before break", default="20") args = parser.parse_args() if not args.min: raise ValueError("Invalid minutes") while True: sleep(args.min*60) Notifier.notify('Time for a break.', title="Reminder") if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ## Instruction: Add break duration argument and sleep timeout. Add notification when it is time to get back to work ## Code After: from pync import Notifier from time import sleep import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--min', type=int, help="Timeout before sending alert (minutes)", default="20") parser.add_argument('--duration', type=int, help="Duration of break (seconds)", default="20") args = parser.parse_args() if not (args.min and args.duration): raise ValueError("Invalid arguments") while True: # sleep for n minutes sleep(args.min*60) # break time Notifier.notify( 'Take a break for %d secs' % args.duration, title="Break reminder" ) # on break sleep(args.duration) # back to work Notifier.notify("Back to work", Title="Break reminder") if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
// ... existing code ... def main(): parser = argparse.ArgumentParser() parser.add_argument('--min', type=int, help="Timeout before sending alert (minutes)", default="20") parser.add_argument('--duration', type=int, help="Duration of break (seconds)", default="20") args = parser.parse_args() if not (args.min and args.duration): raise ValueError("Invalid arguments") while True: # sleep for n minutes sleep(args.min*60) # break time Notifier.notify( 'Take a break for %d secs' % args.duration, title="Break reminder" ) # on break sleep(args.duration) # back to work Notifier.notify("Back to work", Title="Break reminder") if __name__ == '__main__': try: // ... rest of the code ...
acba9a027eafb1877f0b6208613206674ba5d55d
tmc/models/employee.py
tmc/models/employee.py
from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3, required=True ) docket_number = fields.Integer( required=True ) bank_account_number = fields.Char() bank_branch = fields.Integer( size=2 ) admission_date = fields.Date() email = fields.Char() active = fields.Boolean( default=True ) employee_title_ids = fields.Many2many( comodel_name='tmc.hr.employee_title' ) employee_job_id = fields.Many2one( comodel_name='tmc.hr.employee_job' ) office_id = fields.Many2one( comodel_name='tmc.hr.office' ) _sql_constraints = [ ('number_uniq', 'unique(docket_number, bank_account_number)', 'Number must be unique!'), ]
from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3 ) docket_number = fields.Integer() bank_account_number = fields.Char() bank_branch = fields.Integer( size=2 ) admission_date = fields.Date() email = fields.Char() active = fields.Boolean( default=True ) employee_title_ids = fields.Many2many( comodel_name='tmc.hr.employee_title' ) employee_job_id = fields.Many2one( comodel_name='tmc.hr.employee_job' ) office_id = fields.Many2one( comodel_name='tmc.hr.office' ) _sql_constraints = [ ('number_uniq', 'unique(docket_number, bank_account_number)', 'Number must be unique!'), ]
Remove required property on some fields
[DEL] Remove required property on some fields
Python
agpl-3.0
tmcrosario/odoo-tmc
python
## Code Before: from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3, required=True ) docket_number = fields.Integer( required=True ) bank_account_number = fields.Char() bank_branch = fields.Integer( size=2 ) admission_date = fields.Date() email = fields.Char() active = fields.Boolean( default=True ) employee_title_ids = fields.Many2many( comodel_name='tmc.hr.employee_title' ) employee_job_id = fields.Many2one( comodel_name='tmc.hr.employee_job' ) office_id = fields.Many2one( comodel_name='tmc.hr.office' ) _sql_constraints = [ ('number_uniq', 'unique(docket_number, bank_account_number)', 'Number must be unique!'), ] ## Instruction: [DEL] Remove required property on some fields ## Code After: from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3 ) docket_number = fields.Integer() bank_account_number = fields.Char() bank_branch = fields.Integer( size=2 ) admission_date = fields.Date() email = fields.Char() active = fields.Boolean( default=True ) employee_title_ids = fields.Many2many( comodel_name='tmc.hr.employee_title' ) employee_job_id = fields.Many2one( comodel_name='tmc.hr.employee_job' ) office_id = fields.Many2one( comodel_name='tmc.hr.office' ) _sql_constraints = [ ('number_uniq', 'unique(docket_number, bank_account_number)', 'Number must be unique!'), ]
# ... existing code ... name = fields.Char() internal_number = fields.Char( size=3 ) docket_number = fields.Integer() bank_account_number = fields.Char() # ... rest of the code ...
4319688dfb39444d9edcc384e4c56977967cda4b
src/includes/kernel/util.h
src/includes/kernel/util.h
/** arm-016-util.h */ #ifndef RPI_UTIL_H #define RPI_UTIL_H #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define SCREEN_DEPTH 24 /* 16 or 32-bit */ #define COLOUR_DELTA 0.05 /* Float from 0 to 1 incremented by this amount */ #include <math.h> typedef struct { float r; float g; float b; float a; } colour_t; extern void setColor(volatile unsigned char* fb, colour_t pixel, long x, long y, long pitch); int * getCoordinates(); double scale_to_x_origin(int); int scale_to_y_pixel(double); #endif
/** arm-016-util.h */ #ifndef RPI_UTIL_H #define RPI_UTIL_H #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define SCREEN_DEPTH 24 /* 16 or 32-bit */ #define COLOUR_DELTA 0.05 /* Float from 0 to 1 incremented by this amount */ #include <math.h> #include <stdlib.h> typedef struct { float r; float g; float b; float a; } colour_t; extern void setColor(volatile unsigned char* fb, colour_t pixel, long x, long y, long pitch); extern int * getCoordinates(); extern double scale_to_x_origin(int); extern int scale_to_y_pixel(double); #endif
Include stdlib.h and changed function declaration to extern
Include stdlib.h and changed function declaration to extern
C
mit
Neo-Desktop/bare-metal-pi,Neo-Desktop/bare-metal-pi
c
## Code Before: /** arm-016-util.h */ #ifndef RPI_UTIL_H #define RPI_UTIL_H #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define SCREEN_DEPTH 24 /* 16 or 32-bit */ #define COLOUR_DELTA 0.05 /* Float from 0 to 1 incremented by this amount */ #include <math.h> typedef struct { float r; float g; float b; float a; } colour_t; extern void setColor(volatile unsigned char* fb, colour_t pixel, long x, long y, long pitch); int * getCoordinates(); double scale_to_x_origin(int); int scale_to_y_pixel(double); #endif ## Instruction: Include stdlib.h and changed function declaration to extern ## Code After: /** arm-016-util.h */ #ifndef RPI_UTIL_H #define RPI_UTIL_H #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define SCREEN_DEPTH 24 /* 16 or 32-bit */ #define COLOUR_DELTA 0.05 /* Float from 0 to 1 incremented by this amount */ #include <math.h> #include <stdlib.h> typedef struct { float r; float g; float b; float a; } colour_t; extern void setColor(volatile unsigned char* fb, colour_t pixel, long x, long y, long pitch); extern int * getCoordinates(); extern double scale_to_x_origin(int); extern int scale_to_y_pixel(double); #endif
... #define COLOUR_DELTA 0.05 /* Float from 0 to 1 incremented by this amount */ #include <math.h> #include <stdlib.h> typedef struct { float r; ... extern void setColor(volatile unsigned char* fb, colour_t pixel, long x, long y, long pitch); extern int * getCoordinates(); extern double scale_to_x_origin(int); extern int scale_to_y_pixel(double); #endif ...
eb6f229e66a6d86499b00a806297a8610620f9cb
tests/check-gibber-xmpp-node.c
tests/check-gibber-xmpp-node.c
START_TEST (test_instantiation) { GibberXmppNode *node; node = gibber_xmpp_node_new ("test"); fail_unless (node != NULL); } END_TEST TCase * make_gibber_xmpp_node_tcase (void) { TCase *tc = tcase_create ("XMPP Node"); tcase_add_test (tc, test_instantiation); return tc; }
START_TEST (test_instantiation) { GibberXmppNode *node; node = gibber_xmpp_node_new ("test"); fail_unless (node != NULL); node = gibber_xmpp_node_new (NULL); fail_unless (node != NULL); } END_TEST START_TEST (test_language) { GibberXmppNode *node; const gchar *lang; node = gibber_xmpp_node_new ("test"); lang = gibber_xmpp_node_get_language (node); fail_unless (lang == NULL); gibber_xmpp_node_set_language (node, "us"); lang = gibber_xmpp_node_get_language (node); fail_unless (strcmp(lang, "us") == 0); } END_TEST TCase * make_gibber_xmpp_node_tcase (void) { TCase *tc = tcase_create ("XMPP Node"); tcase_add_test (tc, test_instantiation); tcase_add_test (tc, test_language); return tc; }
Test gibber_xmpp_node_[gs]et_language() and node creation with a NULL name
Test gibber_xmpp_node_[gs]et_language() and node creation with a NULL name 20070609084741-f974e-602d6f3a4ba28432895c80518d5ea7daa5c85389.gz
C
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut,freedesktop-unofficial-mirror/telepathy__telepathy-salut
c
## Code Before: START_TEST (test_instantiation) { GibberXmppNode *node; node = gibber_xmpp_node_new ("test"); fail_unless (node != NULL); } END_TEST TCase * make_gibber_xmpp_node_tcase (void) { TCase *tc = tcase_create ("XMPP Node"); tcase_add_test (tc, test_instantiation); return tc; } ## Instruction: Test gibber_xmpp_node_[gs]et_language() and node creation with a NULL name 20070609084741-f974e-602d6f3a4ba28432895c80518d5ea7daa5c85389.gz ## Code After: START_TEST (test_instantiation) { GibberXmppNode *node; node = gibber_xmpp_node_new ("test"); fail_unless (node != NULL); node = gibber_xmpp_node_new (NULL); fail_unless (node != NULL); } END_TEST START_TEST (test_language) { GibberXmppNode *node; const gchar *lang; node = gibber_xmpp_node_new ("test"); lang = gibber_xmpp_node_get_language (node); fail_unless (lang == NULL); gibber_xmpp_node_set_language (node, "us"); lang = gibber_xmpp_node_get_language (node); fail_unless (strcmp(lang, "us") == 0); } END_TEST TCase * make_gibber_xmpp_node_tcase (void) { TCase *tc = tcase_create ("XMPP Node"); tcase_add_test (tc, test_instantiation); tcase_add_test (tc, test_language); return tc; }
# ... existing code ... GibberXmppNode *node; node = gibber_xmpp_node_new ("test"); fail_unless (node != NULL); node = gibber_xmpp_node_new (NULL); fail_unless (node != NULL); } END_TEST START_TEST (test_language) { GibberXmppNode *node; const gchar *lang; node = gibber_xmpp_node_new ("test"); lang = gibber_xmpp_node_get_language (node); fail_unless (lang == NULL); gibber_xmpp_node_set_language (node, "us"); lang = gibber_xmpp_node_get_language (node); fail_unless (strcmp(lang, "us") == 0); } END_TEST # ... modified code ... { TCase *tc = tcase_create ("XMPP Node"); tcase_add_test (tc, test_instantiation); tcase_add_test (tc, test_language); return tc; } # ... rest of the code ...
aa7dae2a6dbcac076ed2fc5416c65e2ac7f04f4b
plugins/changeReminder/src/com/jetbrains/changeReminder/plugin/UserSettings.kt
plugins/changeReminder/src/com/jetbrains/changeReminder/plugin/UserSettings.kt
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminderUserStorage", storages = [Storage(file = "changeReminder.user.storage.xml")]) class UserSettings : PersistentStateComponent<UserSettings.Companion.State> { companion object { data class State(var isPluginEnabled: Boolean = true) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) private var currentState = State() var isPluginEnabled: Boolean get() = currentState.isPluginEnabled set(value) { currentState.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } override fun loadState(state: State) { currentState = state } override fun getState(): State = currentState fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")]) internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) { private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) var isPluginEnabled: Boolean get() = state.isPluginEnabled set(value) { state.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } } internal class UserSettingsState : BaseState() { var isPluginEnabled: Boolean by property(true) }
Use PersistentStateComponent in proper way
[change-reminder] Use PersistentStateComponent in proper way * PersistentComponent should be internal and should extend SimplePersistentStateComponent. * State name should be in CamelCase. * State class should extend BaseState GitOrigin-RevId: 8c574c8a0e2923da13555b3dd24398c8a22d5f86
Kotlin
apache-2.0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
kotlin
## Code Before: // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminderUserStorage", storages = [Storage(file = "changeReminder.user.storage.xml")]) class UserSettings : PersistentStateComponent<UserSettings.Companion.State> { companion object { data class State(var isPluginEnabled: Boolean = true) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) private var currentState = State() var isPluginEnabled: Boolean get() = currentState.isPluginEnabled set(value) { currentState.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } override fun loadState(state: State) { currentState = state } override fun getState(): State = currentState fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } } ## Instruction: [change-reminder] Use PersistentStateComponent in proper way * PersistentComponent should be internal and should extend SimplePersistentStateComponent. * State name should be in CamelCase. * State class should extend BaseState GitOrigin-RevId: 8c574c8a0e2923da13555b3dd24398c8a22d5f86 ## Code After: // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")]) internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) { private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) var isPluginEnabled: Boolean get() = state.isPluginEnabled set(value) { state.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } } internal class UserSettingsState : BaseState() { var isPluginEnabled: Boolean by property(true) }
... // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")]) internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) { private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) var isPluginEnabled: Boolean get() = state.isPluginEnabled set(value) { state.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } } internal class UserSettingsState : BaseState() { var isPluginEnabled: Boolean by property(true) } ...
3f062342003fcb096efc01312a41739a9ea226ee
src/test/java/spark/InitExceptionHandlerTest.java
src/test/java/spark/InitExceptionHandlerTest.java
package spark; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Assert; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { @Test public void testInitExceptionHandler() throws Exception { ExecutorService executorService = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = new CompletableFuture<>(); executorService.submit(() -> { Service service1 = ignite().port(1122); service1.init(); nap(); Service service2 = ignite().port(1122); service2.initExceptionHandler((e) -> future.complete("Custom init error")); service2.init(); service1.stop(); service2.stop(); }); Assert.assertEquals("Custom init error", future.get()); } private void nap() { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } }
package spark; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { private static Service service1; private static Service service2; private static String errorMessage = ""; @BeforeClass public static void setUpClass() throws Exception { service1 = ignite(); service1.port(1122); service1.init(); service1.awaitInitialization(); service2 = ignite(); service2.port(1122); service2.initExceptionHandler((e) -> errorMessage = "Custom init error"); service2.init(); service2.awaitInitialization(); } @Test public void testGetPort_withRandomPort() throws Exception { Assert.assertEquals("Custom init error", errorMessage); } @AfterClass public static void tearDown() throws Exception { service1.stop(); service2.stop(); } }
Rewrite initExceptionTest to be less stupid
Rewrite initExceptionTest to be less stupid
Java
apache-2.0
perwendel/spark,stylismo/spark,rokusr/spark,MouettE-SC/spark,stylismo/spark,MouettE-SC/spark,rokusr/spark,stylismo/spark,rokusr/spark,gimlet2/spark,MouettE-SC/spark,gimlet2/spark,stylismo/spark,gimlet2/spark,arekkw/spark,arekkw/spark,perwendel/spark,perwendel/spark,gimlet2/spark
java
## Code Before: package spark; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Assert; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { @Test public void testInitExceptionHandler() throws Exception { ExecutorService executorService = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = new CompletableFuture<>(); executorService.submit(() -> { Service service1 = ignite().port(1122); service1.init(); nap(); Service service2 = ignite().port(1122); service2.initExceptionHandler((e) -> future.complete("Custom init error")); service2.init(); service1.stop(); service2.stop(); }); Assert.assertEquals("Custom init error", future.get()); } private void nap() { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } ## Instruction: Rewrite initExceptionTest to be less stupid ## Code After: package spark; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import static spark.Service.ignite; public class InitExceptionHandlerTest { private static Service service1; private static Service service2; private static String errorMessage = ""; @BeforeClass public static void setUpClass() throws Exception { service1 = ignite(); service1.port(1122); service1.init(); service1.awaitInitialization(); service2 = ignite(); service2.port(1122); service2.initExceptionHandler((e) -> errorMessage = "Custom init error"); service2.init(); service2.awaitInitialization(); } @Test public void testGetPort_withRandomPort() throws Exception { Assert.assertEquals("Custom init error", errorMessage); } @AfterClass public static void tearDown() throws Exception { service1.stop(); service2.stop(); } }
// ... existing code ... package spark; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import static spark.Service.ignite; // ... modified code ... public class InitExceptionHandlerTest { private static Service service1; private static Service service2; private static String errorMessage = ""; @BeforeClass public static void setUpClass() throws Exception { service1 = ignite(); service1.port(1122); service1.init(); service1.awaitInitialization(); service2 = ignite(); service2.port(1122); service2.initExceptionHandler((e) -> errorMessage = "Custom init error"); service2.init(); service2.awaitInitialization(); } @Test public void testGetPort_withRandomPort() throws Exception { Assert.assertEquals("Custom init error", errorMessage); } @AfterClass public static void tearDown() throws Exception { service1.stop(); service2.stop(); } } // ... rest of the code ...
413d9304b5ff0a45e70512dadc4527843eee7b68
setup.py
setup.py
import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='[email protected]', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ], )
import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='[email protected]', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ],classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Communications', ], )
Add classifiers with py ver info
Add classifiers with py ver info
Python
mit
ferringb/raygun4py,MindscapeHQ/raygun4py,Osmose/raygun4py
python
## Code Before: import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='[email protected]', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ], ) ## Instruction: Add classifiers with py ver info ## Code After: import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='[email protected]', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ],classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Communications', ], )
// ... existing code ... long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ],classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Communications', ], ) // ... rest of the code ...
f2139cad673ee50f027164bda80d86979d5ce7a0
passenger_wsgi.py
passenger_wsgi.py
import os import sys try: from flask import Flask, render_template, send_file, Response import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!"
import os import sys try: from flask import Flask import flask_login from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!"
Add more imports for further functionality
Add more imports for further functionality `flask_login`, `flask_restless`, `flask_sqlalchemy`
Python
mit
GregBrimble/boilerplate-web-service,GregBrimble/boilerplate-web-service
python
## Code Before: import os import sys try: from flask import Flask, render_template, send_file, Response import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!" ## Instruction: Add more imports for further functionality `flask_login`, `flask_restless`, `flask_sqlalchemy` ## Code After: import os import sys try: from flask import Flask import flask_login from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!"
// ... existing code ... import sys try: from flask import Flask import flask_login from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy import requests except ImportError: INTERP = "venv/bin/python" // ... rest of the code ...
8d46e411b2e7091fc54c676665905da8ec6906f3
controllers/dotd.py
controllers/dotd.py
def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False form = SQLFORM(db.raw_log, showid=False, formstyle='divs').process() if form.accepted: redirect(URL('dotd', 'parsed', args=db.raw_log.uuid.default)) return dict(form=form) def parsed(): if request.args: uuid = request.args[0] rows = db(db.raw_log.uuid==uuid).select() if len(rows) == 0: redirect(URL('form')) for row in rows: experience, obtained_items, proc_items, found_items, log_file, max_hit, hit_list=parser(row.data) # hit_list=parser(row.data) return locals() else: redirect(URL('form'))
def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False if form.accepted: redirect(URL('dotd', 'parsed', args=db.raw_log.uuid.default)) return dict(form=form) def parsed(): if request.args: uuid = request.args[0] rows = db(db.raw_log.uuid==uuid).select() if len(rows) == 0: redirect(URL('form')) for row in rows: experience, obtained_items, proc_items, found_items, log_file, max_hit, hit_list=parser(row.data) # hit_list=parser(row.data) return locals() else: redirect(URL('form'))
Remove selection of all raw_log rows, since it was used for debugging purposes only
Remove selection of all raw_log rows, since it was used for debugging purposes only
Python
mit
tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser,tsunam/dotd_parser
python
## Code Before: def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False form = SQLFORM(db.raw_log, showid=False, formstyle='divs').process() if form.accepted: redirect(URL('dotd', 'parsed', args=db.raw_log.uuid.default)) return dict(form=form) def parsed(): if request.args: uuid = request.args[0] rows = db(db.raw_log.uuid==uuid).select() if len(rows) == 0: redirect(URL('form')) for row in rows: experience, obtained_items, proc_items, found_items, log_file, max_hit, hit_list=parser(row.data) # hit_list=parser(row.data) return locals() else: redirect(URL('form')) ## Instruction: Remove selection of all raw_log rows, since it was used for debugging purposes only ## Code After: def form(): db.raw_log.uuid.default = uuid_generator() db.raw_log.date.default = dbdate() #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False if form.accepted: redirect(URL('dotd', 'parsed', args=db.raw_log.uuid.default)) return dict(form=form) def parsed(): if request.args: uuid = request.args[0] rows = db(db.raw_log.uuid==uuid).select() if len(rows) == 0: redirect(URL('form')) for row in rows: experience, obtained_items, proc_items, found_items, log_file, max_hit, hit_list=parser(row.data) # hit_list=parser(row.data) return locals() else: redirect(URL('form'))
# ... existing code ... #don't display form items that are part of table, but not facing end user db.raw_log.uuid.readable = db.raw_log.uuid.writable = False db.raw_log.date.readable = db.raw_log.date.writable = False if form.accepted: redirect(URL('dotd', 'parsed', args=db.raw_log.uuid.default)) return dict(form=form) # ... rest of the code ...
cddcc7e5735022c7a4faeee5331e7b80a6349406
src/functions.py
src/functions.py
def getTableColumnLabel(c): label = '' while True: label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] if c <= 26: break c = int(c/26) return label def parseTableColumnLabel(label): ret = 0 for c in map(ord, reversed(label)): if 0x41 <= c <= 0x5A: ret = ret*26 + (c-0x41) else: raise ValueError('Invalid label: %s' % label) return ret
def getTableColumnLabel(c): label = '' while True: label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label if c < 26: break c = c//26-1 return label def parseTableColumnLabel(label): if not label: raise ValueError('Invalid label: %s' % label) ret = -1 for c in map(ord, label): if 0x41 <= c <= 0x5A: ret = (ret+1)*26 + (c-0x41) else: raise ValueError('Invalid label: %s' % label) return ret
Fix (parse|generate) table header label function
Fix (parse|generate) table header label function
Python
mit
takumak/tuna,takumak/tuna
python
## Code Before: def getTableColumnLabel(c): label = '' while True: label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] if c <= 26: break c = int(c/26) return label def parseTableColumnLabel(label): ret = 0 for c in map(ord, reversed(label)): if 0x41 <= c <= 0x5A: ret = ret*26 + (c-0x41) else: raise ValueError('Invalid label: %s' % label) return ret ## Instruction: Fix (parse|generate) table header label function ## Code After: def getTableColumnLabel(c): label = '' while True: label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label if c < 26: break c = c//26-1 return label def parseTableColumnLabel(label): if not label: raise ValueError('Invalid label: %s' % label) ret = -1 for c in map(ord, label): if 0x41 <= c <= 0x5A: ret = (ret+1)*26 + (c-0x41) else: raise ValueError('Invalid label: %s' % label) return ret
# ... existing code ... def getTableColumnLabel(c): label = '' while True: label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label if c < 26: break c = c//26-1 return label def parseTableColumnLabel(label): if not label: raise ValueError('Invalid label: %s' % label) ret = -1 for c in map(ord, label): if 0x41 <= c <= 0x5A: ret = (ret+1)*26 + (c-0x41) else: raise ValueError('Invalid label: %s' % label) return ret # ... rest of the code ...
63abcc1a7a806e0665ce9382ff9a0ec480cd9576
hipstore/src/test/java/tech/lab23/hipstore/EntityStorageTest.kt
hipstore/src/test/java/tech/lab23/hipstore/EntityStorageTest.kt
package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } @Test fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } }
package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test @Throws(Exception::class) fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } @Test @Throws(Exception::class) fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } }
Implement unit tests for EntityStorage
Implement unit tests for EntityStorage
Kotlin
apache-2.0
samiuelson/Hipstore,samiuelson/Hipstore
kotlin
## Code Before: package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } @Test fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } } ## Instruction: Implement unit tests for EntityStorage ## Code After: package tech.lab23.hipstore import android.content.SharedPreferences import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before fun init() { prefs.edit().clear().apply() } @Test @Throws(Exception::class) fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) EntitiesStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() storage.put(bob) // when storage.remove(bob) // then Assert.assertFalse(storage.get() != null) } @Test @Throws(Exception::class) fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } }
... import android.preference.PreferenceManager import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner ... import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class EntityStorageTest { var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) @Before ... } @Test @Throws(Exception::class) fun remove() { // given storage with Bob inside val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) ... Assert.assertFalse(storage.get() != null) } @Test @Throws(Exception::class) fun put() { // given empty storage val storage: EntityStorage<TestMocks.Person> = EntityStorage<TestMocks.Person>(prefs, TestMocks.Person::class.java) val bob = TestMocks.MocksProvider.provideBob() Assert.assertTrue(storage.get() == null) // when storage.put(bob) // then Assert.assertTrue(storage.get() != null) } } ...
f9dedee2f091dd14a8da268399c34c00b6d37695
Game.h
Game.h
class Game { public: // Objects declared static are allocated storage in static storage area, and have scope till the end of the program. static void Start(); private: static bool IsExiting(); static void GameLoop(); enum GameState { Uninitialized, ShowingSplash, Paused, ShowingMenu, Playing, Exiting }; // Represents the various states the game can be in. An enum is a user-defined type consisting of a set of named constants called enumerators. static GameState _gameState; static sf::RenderWindow _mainWindow; };
class Game { public: // Objects declared static are allocated storage in static storage area, and have scope till the end of the program. static void start(); private: static bool is_exiting(); static void game_loop(); enum game_state { Uninitialized, ShowingSplash, Paused, ShowingMenu, Playing, Exiting }; // Represents the various states the game can be in. An enum is a user-defined type consisting of a set of named constants called enumerators. static game_state s_game_state; static sf::RenderWindow s_main_window; }; #endif
Change styling convention of the variable names
Change styling convention of the variable names
C
mit
jessicaphuong/pong-clone
c
## Code Before: class Game { public: // Objects declared static are allocated storage in static storage area, and have scope till the end of the program. static void Start(); private: static bool IsExiting(); static void GameLoop(); enum GameState { Uninitialized, ShowingSplash, Paused, ShowingMenu, Playing, Exiting }; // Represents the various states the game can be in. An enum is a user-defined type consisting of a set of named constants called enumerators. static GameState _gameState; static sf::RenderWindow _mainWindow; }; ## Instruction: Change styling convention of the variable names ## Code After: class Game { public: // Objects declared static are allocated storage in static storage area, and have scope till the end of the program. static void start(); private: static bool is_exiting(); static void game_loop(); enum game_state { Uninitialized, ShowingSplash, Paused, ShowingMenu, Playing, Exiting }; // Represents the various states the game can be in. An enum is a user-defined type consisting of a set of named constants called enumerators. static game_state s_game_state; static sf::RenderWindow s_main_window; }; #endif
# ... existing code ... class Game { public: // Objects declared static are allocated storage in static storage area, and have scope till the end of the program. static void start(); private: static bool is_exiting(); static void game_loop(); enum game_state { Uninitialized, ShowingSplash, Paused, ShowingMenu, Playing, Exiting }; // Represents the various states the game can be in. An enum is a user-defined type consisting of a set of named constants called enumerators. static game_state s_game_state; static sf::RenderWindow s_main_window; }; #endif # ... rest of the code ...
1c91cc95ea51c8fb404ebe8cc1a783c31c30ca01
src/main/java/nl/tudelft/dnainator/ui/DNAinator.java
src/main/java/nl/tudelft/dnainator/ui/DNAinator.java
package nl.tudelft.dnainator.ui; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * DNAinator's main window, from which all interaction will occur. * <p> * The {@link #start(Stage) start} method will automatically load * the required fxml files, which in turn instantiates all controllers. * </p> */ public class DNAinator extends Application { private static final String DNAINATOR = "DNAinator"; private static final String FXML = "/ui/fxml/dnainator.fxml"; private static final String ICON = "/ui/icons/dnainator.png"; @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); primaryStage.setMaximized(true); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); } }
package nl.tudelft.dnainator.ui; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * DNAinator's main window, from which all interaction will occur. * <p> * The {@link #start(Stage) start} method will automatically load * the required fxml files, which in turn instantiates all controllers. * </p> */ public class DNAinator extends Application { private static final String DNAINATOR = "DNAinator"; private static final String FXML = "/ui/fxml/dnainator.fxml"; private static final String ICON = "/ui/icons/dnainator.png"; private static final int MIN_WIDTH = 300; private static final int MIN_HEIGHT = 150; @Override public void start(Stage primaryStage) throws Exception { primaryStage.setMinHeight(MIN_HEIGHT); primaryStage.setMinWidth(MIN_WIDTH); primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); primaryStage.setMaximized(true); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); } }
Add minimum size to the Application window
Add minimum size to the Application window
Java
bsd-3-clause
AbeelLab/dnainator
java
## Code Before: package nl.tudelft.dnainator.ui; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * DNAinator's main window, from which all interaction will occur. * <p> * The {@link #start(Stage) start} method will automatically load * the required fxml files, which in turn instantiates all controllers. * </p> */ public class DNAinator extends Application { private static final String DNAINATOR = "DNAinator"; private static final String FXML = "/ui/fxml/dnainator.fxml"; private static final String ICON = "/ui/icons/dnainator.png"; @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); primaryStage.setMaximized(true); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); } } ## Instruction: Add minimum size to the Application window ## Code After: package nl.tudelft.dnainator.ui; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * DNAinator's main window, from which all interaction will occur. * <p> * The {@link #start(Stage) start} method will automatically load * the required fxml files, which in turn instantiates all controllers. * </p> */ public class DNAinator extends Application { private static final String DNAINATOR = "DNAinator"; private static final String FXML = "/ui/fxml/dnainator.fxml"; private static final String ICON = "/ui/icons/dnainator.png"; private static final int MIN_WIDTH = 300; private static final int MIN_HEIGHT = 150; @Override public void start(Stage primaryStage) throws Exception { primaryStage.setMinHeight(MIN_HEIGHT); primaryStage.setMinWidth(MIN_WIDTH); primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); primaryStage.setMaximized(true); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); } }
# ... existing code ... private static final String FXML = "/ui/fxml/dnainator.fxml"; private static final String ICON = "/ui/icons/dnainator.png"; private static final int MIN_WIDTH = 300; private static final int MIN_HEIGHT = 150; @Override public void start(Stage primaryStage) throws Exception { primaryStage.setMinHeight(MIN_HEIGHT); primaryStage.setMinWidth(MIN_WIDTH); primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); primaryStage.setMaximized(true); # ... rest of the code ...
49898caae2c1209de839bc8d1361c93eed3e8dac
setup.py
setup.py
import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email='[email protected]', url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="[email protected]", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
Update to new e-mail adress.
Update to new e-mail adress.
Python
mit
EmilStenstrom/conllu
python
## Code Before: import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email='[email protected]', url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], ) ## Instruction: Update to new e-mail adress. ## Code After: import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="[email protected]", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
# ... existing code ... long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="[email protected]", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ # ... rest of the code ...
a8bce6d99e94738fd6abf3429de078208d5221a0
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/MockEnclaveAccessService.java
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/MockEnclaveAccessService.java
package com.yahoo.vespa.hosted.controller.api.integration.aws; import com.yahoo.config.provision.CloudAccount; import java.util.Set; import java.util.TreeSet; /** * @author jonmv */ public class MockEnclaveAccessService implements EnclaveAccessService { private volatile Set<CloudAccount> currentAccounts; public Set<CloudAccount> currentAccounts() { return currentAccounts; } @Override public void allowAccessFor(Set<CloudAccount> accounts) { currentAccounts = new TreeSet<>(accounts); } }
package com.yahoo.vespa.hosted.controller.api.integration.aws; import com.yahoo.config.provision.CloudAccount; import java.util.Set; import java.util.TreeSet; /** * @author jonmv */ public class MockEnclaveAccessService implements EnclaveAccessService { private volatile Set<CloudAccount> currentAccounts = new TreeSet<>(); public Set<CloudAccount> currentAccounts() { return currentAccounts; } @Override public void allowAccessFor(Set<CloudAccount> accounts) { currentAccounts = new TreeSet<>(accounts); } }
Fix test even more :'(
Fix test even more :'(
Java
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
java
## Code Before: package com.yahoo.vespa.hosted.controller.api.integration.aws; import com.yahoo.config.provision.CloudAccount; import java.util.Set; import java.util.TreeSet; /** * @author jonmv */ public class MockEnclaveAccessService implements EnclaveAccessService { private volatile Set<CloudAccount> currentAccounts; public Set<CloudAccount> currentAccounts() { return currentAccounts; } @Override public void allowAccessFor(Set<CloudAccount> accounts) { currentAccounts = new TreeSet<>(accounts); } } ## Instruction: Fix test even more :'( ## Code After: package com.yahoo.vespa.hosted.controller.api.integration.aws; import com.yahoo.config.provision.CloudAccount; import java.util.Set; import java.util.TreeSet; /** * @author jonmv */ public class MockEnclaveAccessService implements EnclaveAccessService { private volatile Set<CloudAccount> currentAccounts = new TreeSet<>(); public Set<CloudAccount> currentAccounts() { return currentAccounts; } @Override public void allowAccessFor(Set<CloudAccount> accounts) { currentAccounts = new TreeSet<>(accounts); } }
# ... existing code ... */ public class MockEnclaveAccessService implements EnclaveAccessService { private volatile Set<CloudAccount> currentAccounts = new TreeSet<>(); public Set<CloudAccount> currentAccounts() { return currentAccounts; } # ... rest of the code ...
93081d423a73a6b16e5adfb94247ffec23ef667c
api/base/authentication/backends.py
api/base/authentication/backends.py
from osf.models.user import OSFUser from framework.auth.core import get_user from django.contrib.auth.backends import ModelBackend # https://docs.djangoproject.com/en/1.8/topics/auth/customizing/ class ODMBackend(ModelBackend): def authenticate(self, username=None, password=None): return get_user(email=username, password=password) or None def get_user(self, user_id): try: user = OSFUser.objects.get(id=user_id) except OSFUser.DoesNotExist: user = OSFUser.load(user_id) return user
from osf.models.user import OSFUser from framework.auth.core import get_user from django.contrib.auth.backends import ModelBackend # https://docs.djangoproject.com/en/3.2/topics/auth/customizing/ class ODMBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): return get_user(email=username, password=password) or None def get_user(self, user_id): try: user = OSFUser.objects.get(id=user_id) except OSFUser.DoesNotExist: user = OSFUser.load(user_id) return user
Fix admin login failure for django upgrade
Fix admin login failure for django upgrade
Python
apache-2.0
Johnetordoff/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io
python
## Code Before: from osf.models.user import OSFUser from framework.auth.core import get_user from django.contrib.auth.backends import ModelBackend # https://docs.djangoproject.com/en/1.8/topics/auth/customizing/ class ODMBackend(ModelBackend): def authenticate(self, username=None, password=None): return get_user(email=username, password=password) or None def get_user(self, user_id): try: user = OSFUser.objects.get(id=user_id) except OSFUser.DoesNotExist: user = OSFUser.load(user_id) return user ## Instruction: Fix admin login failure for django upgrade ## Code After: from osf.models.user import OSFUser from framework.auth.core import get_user from django.contrib.auth.backends import ModelBackend # https://docs.djangoproject.com/en/3.2/topics/auth/customizing/ class ODMBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): return get_user(email=username, password=password) or None def get_user(self, user_id): try: user = OSFUser.objects.get(id=user_id) except OSFUser.DoesNotExist: user = OSFUser.load(user_id) return user
# ... existing code ... from framework.auth.core import get_user from django.contrib.auth.backends import ModelBackend # https://docs.djangoproject.com/en/3.2/topics/auth/customizing/ class ODMBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): return get_user(email=username, password=password) or None def get_user(self, user_id): # ... rest of the code ...
1d36d56766ab6ced877ba0f03e971e44cb92fbab
src/test/java/com/google/sps/AuthInfoTest.java
src/test/java/com/google/sps/AuthInfoTest.java
package com.google.sps.tests; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class AuthInfoTest { @Test public void example() { // placeholder test to show that tests are evaluated Assert.assertEquals(1 + 1, 2); Assert.assertEquals(2 * 2, 4); Assert.assertEquals(1337, 1500 - 163); } }
package com.google.sps; import com.google.sps.data.AuthInfo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class AuthInfoTest { @Test public void testDefaultBuilderValues() { AuthInfo uninitializedAuthInfo = AuthInfo.builder().setIsLoggedIn(false).build(); Assert.assertEquals("", uninitializedAuthInfo.email()); Assert.assertEquals("", uninitializedAuthInfo.loginUrl()); Assert.assertEquals("", uninitializedAuthInfo.logoutUrl()); } @Test public void testBuilderLoggedInFields() { AuthInfo loggedInAuthInfo = AuthInfo.builder() .setIsLoggedIn(true) .setEmail("[email protected]") .setLogoutUrl("https://google.com") .build(); Assert.assertEquals(true, loggedInAuthInfo.isLoggedIn()); Assert.assertEquals("[email protected]", loggedInAuthInfo.email()); Assert.assertEquals("https://google.com", loggedInAuthInfo.logoutUrl()); Assert.assertEquals("", loggedInAuthInfo.loginUrl()); } }
Add tests for AuthInfo value class
Add tests for AuthInfo value class
Java
apache-2.0
googleinterns/step27-2020,googleinterns/step27-2020,googleinterns/step27-2020
java
## Code Before: package com.google.sps.tests; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class AuthInfoTest { @Test public void example() { // placeholder test to show that tests are evaluated Assert.assertEquals(1 + 1, 2); Assert.assertEquals(2 * 2, 4); Assert.assertEquals(1337, 1500 - 163); } } ## Instruction: Add tests for AuthInfo value class ## Code After: package com.google.sps; import com.google.sps.data.AuthInfo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class AuthInfoTest { @Test public void testDefaultBuilderValues() { AuthInfo uninitializedAuthInfo = AuthInfo.builder().setIsLoggedIn(false).build(); Assert.assertEquals("", uninitializedAuthInfo.email()); Assert.assertEquals("", uninitializedAuthInfo.loginUrl()); Assert.assertEquals("", uninitializedAuthInfo.logoutUrl()); } @Test public void testBuilderLoggedInFields() { AuthInfo loggedInAuthInfo = AuthInfo.builder() .setIsLoggedIn(true) .setEmail("[email protected]") .setLogoutUrl("https://google.com") .build(); Assert.assertEquals(true, loggedInAuthInfo.isLoggedIn()); Assert.assertEquals("[email protected]", loggedInAuthInfo.email()); Assert.assertEquals("https://google.com", loggedInAuthInfo.logoutUrl()); Assert.assertEquals("", loggedInAuthInfo.loginUrl()); } }
// ... existing code ... package com.google.sps; import com.google.sps.data.AuthInfo; import org.junit.Assert; import org.junit.Test; // ... modified code ... @RunWith(JUnit4.class) public final class AuthInfoTest { @Test public void testDefaultBuilderValues() { AuthInfo uninitializedAuthInfo = AuthInfo.builder().setIsLoggedIn(false).build(); Assert.assertEquals("", uninitializedAuthInfo.email()); Assert.assertEquals("", uninitializedAuthInfo.loginUrl()); Assert.assertEquals("", uninitializedAuthInfo.logoutUrl()); } @Test public void testBuilderLoggedInFields() { AuthInfo loggedInAuthInfo = AuthInfo.builder() .setIsLoggedIn(true) .setEmail("[email protected]") .setLogoutUrl("https://google.com") .build(); Assert.assertEquals(true, loggedInAuthInfo.isLoggedIn()); Assert.assertEquals("[email protected]", loggedInAuthInfo.email()); Assert.assertEquals("https://google.com", loggedInAuthInfo.logoutUrl()); Assert.assertEquals("", loggedInAuthInfo.loginUrl()); } } // ... rest of the code ...
7bea8f5cb6f958225ce61a9f7ce439e9a80036ea
tests/unit/utils/cache_test.py
tests/unit/utils/cache_test.py
''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) assert isinstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict assert 'foo' not in cd cd['foo'] = 'bar' assert cd['foo'] == 'bar' del cd['foo'] assert 'foo' not in cd def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' assert 'foo' in cd assert cd['foo'] == 'bar' time.sleep(0.1) assert 'foo' not in cd # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
Change python asserts to unittest asserts
Change python asserts to unittest asserts
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: ''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) assert isinstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict assert 'foo' not in cd cd['foo'] = 'bar' assert cd['foo'] == 'bar' del cd['foo'] assert 'foo' not in cd def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' assert 'foo' in cd assert cd['foo'] == 'bar' time.sleep(0.1) assert 'foo' not in cd # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False) ## Instruction: Change python asserts to unittest asserts ## Code After: ''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
// ... existing code ... Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') // ... rest of the code ...
ddbef13134b9609f8833e2118dcd88387c9ce581
addressbook-web-tests/src/test/java/ru/stqua/pft/addressbook/tests/ContactModificationTests.java
addressbook-web-tests/src/test/java/ru/stqua/pft/addressbook/tests/ContactModificationTests.java
package ru.stqua.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.ContactData; /** * Created by Alexander Gorny on 1/29/2017. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification(){ app.getNavigationHelper().gotoHomePage(); if (! app.getContactHelper().isThereAContact()){ // create new contact app.getContactHelper().createContact(new ContactData("Alex", "Gorny", "Cool Woker", "Mr", "GE", "New Orleans", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", "test1"), true); app.getNavigationHelper().gotoHomePage(); // modify created contact app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); app.getNavigationHelper().gotoHomePage(); // delete previously created contact app.getContactHelper().selectContactFromTheList(1); app.getContactHelper().deleteSelectedContant(); } else { app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); } app.getNavigationHelper().gotoHomePage(); } }
package ru.stqua.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.ContactData; /** * Created by Alexander Gorny on 1/29/2017. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification(){ app.getNavigationHelper().gotoHomePage(); if (! app.getContactHelper().isThereAContact()){ // create new contact app.getContactHelper().createContact(new ContactData("Alex", "Gorny", "Cool Woker", "Mr", "GE", "New Orleans", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", "test1"), true); app.getNavigationHelper().gotoHomePage(); } app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); app.getNavigationHelper().gotoHomePage(); } }
Remove Contact Deletion from ContactModification
Remove Contact Deletion from ContactModification
Java
apache-2.0
GornyAlex/pdt_37,GornyAlex/pdt_37
java
## Code Before: package ru.stqua.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.ContactData; /** * Created by Alexander Gorny on 1/29/2017. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification(){ app.getNavigationHelper().gotoHomePage(); if (! app.getContactHelper().isThereAContact()){ // create new contact app.getContactHelper().createContact(new ContactData("Alex", "Gorny", "Cool Woker", "Mr", "GE", "New Orleans", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", "test1"), true); app.getNavigationHelper().gotoHomePage(); // modify created contact app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); app.getNavigationHelper().gotoHomePage(); // delete previously created contact app.getContactHelper().selectContactFromTheList(1); app.getContactHelper().deleteSelectedContant(); } else { app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); } app.getNavigationHelper().gotoHomePage(); } } ## Instruction: Remove Contact Deletion from ContactModification ## Code After: package ru.stqua.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.ContactData; /** * Created by Alexander Gorny on 1/29/2017. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification(){ app.getNavigationHelper().gotoHomePage(); if (! app.getContactHelper().isThereAContact()){ // create new contact app.getContactHelper().createContact(new ContactData("Alex", "Gorny", "Cool Woker", "Mr", "GE", "New Orleans", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", "test1"), true); app.getNavigationHelper().gotoHomePage(); } app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); app.getNavigationHelper().gotoHomePage(); } }
... // create new contact app.getContactHelper().createContact(new ContactData("Alex", "Gorny", "Cool Woker", "Mr", "GE", "New Orleans", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", "test1"), true); app.getNavigationHelper().gotoHomePage(); } app.getContactHelper().modifyContact(new ContactData("Chuck", "Norris", "Walker", "Mr", "Texas Ranger", "Ryan", "444-555-6666", "[email protected]", "[email protected]", "www.homepage.com", null), 1); app.getNavigationHelper().gotoHomePage(); } ...
e3ae701be163ccff7e2f64721752b0374dffdfc1
rosie/chamber_of_deputies/tests/test_dataset.py
rosie/chamber_of_deputies/tests/test_dataset.py
import os.path from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies import settings from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): temp_path = mkdtemp() copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz', os.path.join(temp_path, settings.COMPANIES_DATASET)) copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path) self.subject = Adapter(temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch): dataset = self.subject.dataset() self.assertEqual(5, len(dataset)) self.assertEqual(1, dataset['legal_entity'].isnull().sum())
import shutil import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): self.temp_path = mkdtemp() fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') copies = ( ('companies.xz', Adapter.COMPANIES_DATASET), ('reimbursements.xz', 'reimbursements.xz') ) for source, target in copies: copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) self.subject = Adapter(self.temp_path) def tearDown(self): shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): self.assertEqual(5, len(self.subject.dataset)) self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
Fix companies path in Chamber of Deputies dataset test
Fix companies path in Chamber of Deputies dataset test
Python
mit
marcusrehm/serenata-de-amor,datasciencebr/rosie,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor
python
## Code Before: import os.path from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies import settings from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): temp_path = mkdtemp() copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz', os.path.join(temp_path, settings.COMPANIES_DATASET)) copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path) self.subject = Adapter(temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch): dataset = self.subject.dataset() self.assertEqual(5, len(dataset)) self.assertEqual(1, dataset['legal_entity'].isnull().sum()) ## Instruction: Fix companies path in Chamber of Deputies dataset test ## Code After: import shutil import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): self.temp_path = mkdtemp() fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') copies = ( ('companies.xz', Adapter.COMPANIES_DATASET), ('reimbursements.xz', 'reimbursements.xz') ) for source, target in copies: copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) self.subject = Adapter(self.temp_path) def tearDown(self): shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): self.assertEqual(5, len(self.subject.dataset)) self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
... import shutil import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies.adapter import Adapter ... class TestDataset(TestCase): def setUp(self): self.temp_path = mkdtemp() fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') copies = ( ('companies.xz', Adapter.COMPANIES_DATASET), ('reimbursements.xz', 'reimbursements.xz') ) for source, target in copies: copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) self.subject = Adapter(self.temp_path) def tearDown(self): shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): self.assertEqual(5, len(self.subject.dataset)) self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum()) ...
6e80bcef30b6b4485fa5e3f269f13fc62380c422
tests/test_evaluate.py
tests/test_evaluate.py
import numpy as np from numpy.testing import assert_equal from gala import evaluate as ev def test_contingency_table(): seg = np.array([0, 1, 1, 1, 2, 2, 2, 3]) gt = np.array([1, 1, 1, 2, 2, 2, 2, 0]) ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[]) ct0 = ev.contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0]) ctd = ct.todense() assert_equal(ctd, np.array([[0. , 0.125, 0. ], [0. , 0.25 , 0.125], [0. , 0. , 0.375], [0.125, 0. , 0. ]])) assert ct.shape == ct0.shape def test_vi(): seg = np.array([1, 2, 3, 4]) gt = np.array([1, 1, 8, 8]) assert_equal(ev.vi(seg, gt), 1) def test_are(): seg = np.eye(3) gt = np.eye(3) seg[1][1] = 0 assert seg.shape == gt.shape
import numpy as np from numpy.testing import assert_equal from gala import evaluate as ev def test_contingency_table(): seg = np.array([0, 1, 1, 1, 2, 2, 2, 3]) gt = np.array([1, 1, 1, 2, 2, 2, 2, 0]) ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[]) ct0 = ev.contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0]) ctd = ct.todense() assert_equal(ctd, np.array([[0. , 0.125, 0. ], [0. , 0.25 , 0.125], [0. , 0. , 0.375], [0.125, 0. , 0. ]])) assert ct.shape == ct0.shape def test_vi(): seg = np.array([1, 2, 3, 4]) gt = np.array([1, 1, 8, 8]) assert_equal(ev.vi(seg, gt), 1) def test_are(): seg = np.array([[0,1], [1,0]]) gt = np.array([[1,2],[0,1]]) assert_almost_equal(ev.adapted_rand_error(seg,gt),0.081) assert seg.shape == gt.shape
Add in test for ARE
Add in test for ARE
Python
bsd-3-clause
jni/gala,janelia-flyem/gala
python
## Code Before: import numpy as np from numpy.testing import assert_equal from gala import evaluate as ev def test_contingency_table(): seg = np.array([0, 1, 1, 1, 2, 2, 2, 3]) gt = np.array([1, 1, 1, 2, 2, 2, 2, 0]) ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[]) ct0 = ev.contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0]) ctd = ct.todense() assert_equal(ctd, np.array([[0. , 0.125, 0. ], [0. , 0.25 , 0.125], [0. , 0. , 0.375], [0.125, 0. , 0. ]])) assert ct.shape == ct0.shape def test_vi(): seg = np.array([1, 2, 3, 4]) gt = np.array([1, 1, 8, 8]) assert_equal(ev.vi(seg, gt), 1) def test_are(): seg = np.eye(3) gt = np.eye(3) seg[1][1] = 0 assert seg.shape == gt.shape ## Instruction: Add in test for ARE ## Code After: import numpy as np from numpy.testing import assert_equal from gala import evaluate as ev def test_contingency_table(): seg = np.array([0, 1, 1, 1, 2, 2, 2, 3]) gt = np.array([1, 1, 1, 2, 2, 2, 2, 0]) ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[]) ct0 = ev.contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0]) ctd = ct.todense() assert_equal(ctd, np.array([[0. , 0.125, 0. ], [0. , 0.25 , 0.125], [0. , 0. , 0.375], [0.125, 0. , 0. ]])) assert ct.shape == ct0.shape def test_vi(): seg = np.array([1, 2, 3, 4]) gt = np.array([1, 1, 8, 8]) assert_equal(ev.vi(seg, gt), 1) def test_are(): seg = np.array([[0,1], [1,0]]) gt = np.array([[1,2],[0,1]]) assert_almost_equal(ev.adapted_rand_error(seg,gt),0.081) assert seg.shape == gt.shape
... assert_equal(ev.vi(seg, gt), 1) def test_are(): seg = np.array([[0,1], [1,0]]) gt = np.array([[1,2],[0,1]]) assert_almost_equal(ev.adapted_rand_error(seg,gt),0.081) assert seg.shape == gt.shape ...
a412de216896ddf5b1c2156927d39bade75b10d8
setup.py
setup.py
import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='[email protected]', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main']}, zip_safe=False )
import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='[email protected]', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main', 'dusty = dusty.client:main']}, zip_safe=False )
Add entrypoint for Dusty client
Add entrypoint for Dusty client
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
python
## Code Before: import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='[email protected]', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main']}, zip_safe=False ) ## Instruction: Add entrypoint for Dusty client ## Code After: import os import sys import imp from setuptools import find_packages try: from restricted_pkg import setup except: # allow falling back to setuptools only if # we are not trying to upload if 'upload' in sys.argv: raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg') from setuptools import setup requirements = imp.load_source('requirements', os.path.realpath('requirements.py')) setup( name='dusty', version='0.0.1', description='Docker-based development environment manager', url='https://github.com/gamechanger/dusty', private_repository='gamechanger', author='GameChanger', author_email='[email protected]', packages=find_packages(), install_requires=requirements.install_requires, tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main', 'dusty = dusty.client:main']}, zip_safe=False )
... tests_require=requirements.test_requires, test_suite="nose.collector", entry_points={'console_scripts': ['dustyd = dusty.daemon:main', 'dusty = dusty.client:main']}, zip_safe=False ) ...
5b66a57257807adf527fcb1de4c750013e532f25
newsletter/utils.py
newsletter/utils.py
import logging logger = logging.getLogger(__name__) import random from django.utils.hashcompat import sha_constructor from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha_constructor(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha_constructor(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()]
import logging logger = logging.getLogger(__name__) import random try: from hashlib import sha1 except ImportError: from django.utils.hashcompat import sha_constructor as sha1 from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha1(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha1(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()]
Fix deprecation warnings with Django 1.5
Fix deprecation warnings with Django 1.5 django/utils/hashcompat.py:9: DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead
Python
agpl-3.0
dsanders11/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter
python
## Code Before: import logging logger = logging.getLogger(__name__) import random from django.utils.hashcompat import sha_constructor from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha_constructor(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha_constructor(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()] ## Instruction: Fix deprecation warnings with Django 1.5 django/utils/hashcompat.py:9: DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead ## Code After: import logging logger = logging.getLogger(__name__) import random try: from hashlib import sha1 except ImportError: from django.utils.hashcompat import sha_constructor as sha1 from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha1(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha1(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()]
... import random try: from hashlib import sha1 except ImportError: from django.utils.hashcompat import sha_constructor as sha1 from django.contrib.sites.models import Site from datetime import datetime ... def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha1(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha1(combined_string).hexdigest() def get_default_sites(): ...
5785323d0a83c1f8b3b4e1cd17a22ff5222114fe
mistraldashboard/test/tests/error_handle.py
mistraldashboard/test/tests/error_handle.py
from mistraldashboard.handle_errors import handle_errors from mistraldashboard.test import helpers as test class ErrorHandleTests(test.TestCase): class CommonException(Exception): pass def test_args_request_view_error_handle(self): @handle_errors('Error message') def common_view(request): raise self.CommonException() self.assertRaises(self.CommonException, common_view, {}) def test_kwargs_request_view_error_handle(self): @handle_errors('Error message') def common_view(slf, request, context=None): raise self.CommonException() with self.assertRaises(self.CommonException): common_view(slf=None, request={})
from mistraldashboard.test import helpers as test class ErrorHandleTests(test.TestCase): class CommonException(Exception): pass
Remove the test cases for handle_errors to fix the py27 gate issue
Remove the test cases for handle_errors to fix the py27 gate issue As we just change the exceptions handle method in horizon, now the test cases have some issues, so disable them first to fix all py27 gate fails. Change-Id: Ic369434a40ff209b06de9481884637d46ee588f7
Python
apache-2.0
openstack/mistral-dashboard,openstack/mistral-dashboard,openstack/mistral-dashboard
python
## Code Before: from mistraldashboard.handle_errors import handle_errors from mistraldashboard.test import helpers as test class ErrorHandleTests(test.TestCase): class CommonException(Exception): pass def test_args_request_view_error_handle(self): @handle_errors('Error message') def common_view(request): raise self.CommonException() self.assertRaises(self.CommonException, common_view, {}) def test_kwargs_request_view_error_handle(self): @handle_errors('Error message') def common_view(slf, request, context=None): raise self.CommonException() with self.assertRaises(self.CommonException): common_view(slf=None, request={}) ## Instruction: Remove the test cases for handle_errors to fix the py27 gate issue As we just change the exceptions handle method in horizon, now the test cases have some issues, so disable them first to fix all py27 gate fails. Change-Id: Ic369434a40ff209b06de9481884637d46ee588f7 ## Code After: from mistraldashboard.test import helpers as test class ErrorHandleTests(test.TestCase): class CommonException(Exception): pass
# ... existing code ... from mistraldashboard.test import helpers as test # ... modified code ... class CommonException(Exception): pass # ... rest of the code ...
45501645e06743bd6341cfd6d2573f6c5f36d094
netmiko/ubiquiti/__init__.py
netmiko/ubiquiti/__init__.py
from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UnifiSwitchSSH", "UbiquitiUnifiSwitchSSH", ]
from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UbiquitiUnifiSwitchSSH", ]
Fix __all__ import for ubiquiti
Fix __all__ import for ubiquiti
Python
mit
ktbyers/netmiko,ktbyers/netmiko
python
## Code Before: from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UnifiSwitchSSH", "UbiquitiUnifiSwitchSSH", ] ## Instruction: Fix __all__ import for ubiquiti ## Code After: from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UbiquitiUnifiSwitchSSH", ]
... __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UbiquitiUnifiSwitchSSH", ] ...
0b1d2a43e4f9858bcb9d9bf9edf3dfae417f133d
satchless/util/__init__.py
satchless/util/__init__.py
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): def handle_decimal(self, o): if isinstance(o, Decimal): return float(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type)
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): class UndercoverDecimal(float): ''' A horrible hack that lets us encode Decimals as numbers. Do not do this at home. ''' def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def handle_decimal(self, o): if isinstance(o, Decimal): return self.UndercoverDecimal(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type)
Add a huge hack to treat Decimals like floats
Add a huge hack to treat Decimals like floats This commit provided to you by highly trained professional stuntmen, do not try to reproduce any of this at home!
Python
bsd-3-clause
taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless
python
## Code Before: from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): def handle_decimal(self, o): if isinstance(o, Decimal): return float(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type) ## Instruction: Add a huge hack to treat Decimals like floats This commit provided to you by highly trained professional stuntmen, do not try to reproduce any of this at home! ## Code After: from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): class UndercoverDecimal(float): ''' A horrible hack that lets us encode Decimals as numbers. Do not do this at home. ''' def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def handle_decimal(self, o): if isinstance(o, Decimal): return self.UndercoverDecimal(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type)
// ... existing code ... return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): class UndercoverDecimal(float): ''' A horrible hack that lets us encode Decimals as numbers. Do not do this at home. ''' def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def handle_decimal(self, o): if isinstance(o, Decimal): return self.UndercoverDecimal(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, // ... rest of the code ...
82fc0cb7883747942326d6d6ca1333b27bd647f0
test/Preprocessor/optimize.c
test/Preprocessor/optimize.c
// RUN: clang-cc -Eonly optimize.c -DOPT_O2 -O2 -verify && #ifdef OPT_O2 #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly optimize.c -DOPT_O0 -O0 -verify && #ifdef OPT_O0 #ifdef __OPTIMIZE__ #error "__OPTIMIZE__ defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly optimize.c -DOPT_OS -Os -verify #ifdef OPT_OS #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifndef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ not defined" #endif #endif
// RUN: clang-cc -Eonly %s -DOPT_O2 -O2 -verify && #ifdef OPT_O2 #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly %s -DOPT_O0 -O0 -verify && #ifdef OPT_O0 #ifdef __OPTIMIZE__ #error "__OPTIMIZE__ defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly %s -DOPT_OS -Os -verify #ifdef OPT_OS #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifndef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ not defined" #endif #endif
Use %s in test, not hard coded name.
Use %s in test, not hard coded name. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@68521 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
c
## Code Before: // RUN: clang-cc -Eonly optimize.c -DOPT_O2 -O2 -verify && #ifdef OPT_O2 #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly optimize.c -DOPT_O0 -O0 -verify && #ifdef OPT_O0 #ifdef __OPTIMIZE__ #error "__OPTIMIZE__ defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly optimize.c -DOPT_OS -Os -verify #ifdef OPT_OS #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifndef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ not defined" #endif #endif ## Instruction: Use %s in test, not hard coded name. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@68521 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: clang-cc -Eonly %s -DOPT_O2 -O2 -verify && #ifdef OPT_O2 #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly %s -DOPT_O0 -O0 -verify && #ifdef OPT_O0 #ifdef __OPTIMIZE__ #error "__OPTIMIZE__ defined" #endif #ifdef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ defined" #endif #endif // RUN: clang-cc -Eonly %s -DOPT_OS -Os -verify #ifdef OPT_OS #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" #endif #ifndef __OPTIMIZE_SIZE #error "__OPTIMIZE_SIZE__ not defined" #endif #endif
// ... existing code ... // RUN: clang-cc -Eonly %s -DOPT_O2 -O2 -verify && #ifdef OPT_O2 #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" // ... modified code ... #endif #endif // RUN: clang-cc -Eonly %s -DOPT_O0 -O0 -verify && #ifdef OPT_O0 #ifdef __OPTIMIZE__ #error "__OPTIMIZE__ defined" ... #endif #endif // RUN: clang-cc -Eonly %s -DOPT_OS -Os -verify #ifdef OPT_OS #ifndef __OPTIMIZE__ #error "__OPTIMIZE__ not defined" // ... rest of the code ...
dbba9e403538fb3bfd29763b8741e07dad3db1b1
src/main/python/cfn_sphere/resolver/file.py
src/main/python/cfn_sphere/resolver/file.py
class FileResolver(object): def read(self, path): with open(path, 'r') as file: return file.read()
class FileResolver(object): def read(self, path): try: with open(path, 'r') as f: return f.read() except IOError as e: raise CfnSphereException("Cannot read file " + path, e)
Throw CfnSphereException on IOErrors. Fix landmark issue.
Throw CfnSphereException on IOErrors. Fix landmark issue.
Python
apache-2.0
cfn-sphere/cfn-sphere,cfn-sphere/cfn-sphere,ImmobilienScout24/cfn-sphere,cfn-sphere/cfn-sphere,marco-hoyer/cfn-sphere
python
## Code Before: class FileResolver(object): def read(self, path): with open(path, 'r') as file: return file.read() ## Instruction: Throw CfnSphereException on IOErrors. Fix landmark issue. ## Code After: class FileResolver(object): def read(self, path): try: with open(path, 'r') as f: return f.read() except IOError as e: raise CfnSphereException("Cannot read file " + path, e)
... class FileResolver(object): def read(self, path): try: with open(path, 'r') as f: return f.read() except IOError as e: raise CfnSphereException("Cannot read file " + path, e) ...
4ce674ea3a672c2819112b5237319000e33f22c5
marten/__init__.py
marten/__init__.py
"""Stupid simple Python configuration environments""" from __future__ import absolute_import import os as _os __version__ = '0.6.0' _os.environ.setdefault('MARTEN_ENV', 'default') try: from .util import get_config_from_env as _get_config except ImportError: config = None else: config = _get_config()
"""Stupid simple Python configuration environments""" from __future__ import absolute_import from marten import loaded_configs import os as _os __version__ = '0.6.1' _os.environ.setdefault('MARTEN_ENV', 'default') try: from .util import get_config_from_env as _get_config except ImportError: config = None else: config = _get_config()
Add explicit import for loaded_configs namespace to fix RuntimeWarning
Add explicit import for loaded_configs namespace to fix RuntimeWarning
Python
mit
nick-allen/marten
python
## Code Before: """Stupid simple Python configuration environments""" from __future__ import absolute_import import os as _os __version__ = '0.6.0' _os.environ.setdefault('MARTEN_ENV', 'default') try: from .util import get_config_from_env as _get_config except ImportError: config = None else: config = _get_config() ## Instruction: Add explicit import for loaded_configs namespace to fix RuntimeWarning ## Code After: """Stupid simple Python configuration environments""" from __future__ import absolute_import from marten import loaded_configs import os as _os __version__ = '0.6.1' _os.environ.setdefault('MARTEN_ENV', 'default') try: from .util import get_config_from_env as _get_config except ImportError: config = None else: config = _get_config()
... from __future__ import absolute_import from marten import loaded_configs import os as _os __version__ = '0.6.1' ...
5c8780c1f4ba914f20f0dc022cc26becb381f2f1
markymark/fields.py
markymark/fields.py
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
Revert "Allow widget overwriting on form field"
Revert "Allow widget overwriting on form field" This reverts commit 23a9aaae78cc4d9228f8d0705647fbcadcaf7975.
Python
mit
moccu/django-markymark,moccu/django-markymark,moccu/django-markymark
python
## Code Before: from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', MarkdownTextarea) super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs) ## Instruction: Revert "Allow widget overwriting on form field" This reverts commit 23a9aaae78cc4d9228f8d0705647fbcadcaf7975. ## Code After: from django import forms from django.db import models from .widgets import MarkdownTextarea class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) class MarkdownField(models.TextField): def formfield(self, form_class=MarkdownFormField, **kwargs): return super(MarkdownField, self).formfield( form_class=form_class, **kwargs)
# ... existing code ... class MarkdownFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): kwargs['widget'] = MarkdownTextarea super(MarkdownFormField, self).__init__(*args, **kwargs) # ... rest of the code ...
af8e53a6a1f592c6d3e4ce1bf100ec7b927ef679
CefSharp.Core/SchemeHandlerFactoryWrapper.h
CefSharp.Core/SchemeHandlerFactoryWrapper.h
// Copyright 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "include/cef_scheme.h" #include "Internals/AutoLock.h" using namespace System; using namespace System::IO; using namespace System::Collections::Specialized; namespace CefSharp { private class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory { gcroot<ISchemeHandlerFactory^> _factory; public: SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) : _factory(factory) {} ~SchemeHandlerFactoryWrapper() { _factory = nullptr; } virtual CefRefPtr<CefResourceHandler> SchemeHandlerFactoryWrapper::Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { auto handler = _factory->Create(); CefRefPtr<ResourceHandlerWrapper> wrapper = new ResourceHandlerWrapper(handler); return static_cast<CefRefPtr<CefResourceHandler>>(wrapper); } IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); }; }
// Copyright 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "include/cef_scheme.h" #include "Internals/AutoLock.h" using namespace System; using namespace System::IO; using namespace System::Collections::Specialized; namespace CefSharp { private class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory { gcroot<ISchemeHandlerFactory^> _factory; public: SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) : _factory(factory) {} ~SchemeHandlerFactoryWrapper() { _factory = nullptr; } virtual CefRefPtr<CefResourceHandler> Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { auto handler = _factory->Create(); CefRefPtr<ResourceHandlerWrapper> wrapper = new ResourceHandlerWrapper(handler); return static_cast<CefRefPtr<CefResourceHandler>>(wrapper); } IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); }; }
Remove redundant method prefix (cpp)
Remove redundant method prefix (cpp)
C
bsd-3-clause
rlmcneary2/CefSharp,illfang/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,joshvera/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,dga711/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,illfang/CefSharp,windygu/CefSharp,windygu/CefSharp,illfang/CefSharp,twxstar/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,joshvera/CefSharp,VioletLife/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,Livit/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,NumbersInternational/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,rlmcneary2/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,joshvera/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,battewr/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,NumbersInternational/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,ITGlobal/CefSharp,windygu/CefSharp,AJDev77/CefSharp,wangzheng888520/CefSharp,ruisebastiao/CefSharp,VioletLife/CefSharp
c
## Code Before: // Copyright 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "include/cef_scheme.h" #include "Internals/AutoLock.h" using namespace System; using namespace System::IO; using namespace System::Collections::Specialized; namespace CefSharp { private class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory { gcroot<ISchemeHandlerFactory^> _factory; public: SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) : _factory(factory) {} ~SchemeHandlerFactoryWrapper() { _factory = nullptr; } virtual CefRefPtr<CefResourceHandler> SchemeHandlerFactoryWrapper::Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { auto handler = _factory->Create(); CefRefPtr<ResourceHandlerWrapper> wrapper = new ResourceHandlerWrapper(handler); return static_cast<CefRefPtr<CefResourceHandler>>(wrapper); } IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); }; } ## Instruction: Remove redundant method prefix (cpp) ## Code After: // Copyright 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "include/cef_scheme.h" #include "Internals/AutoLock.h" using namespace System; using namespace System::IO; using namespace System::Collections::Specialized; namespace CefSharp { private class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory { gcroot<ISchemeHandlerFactory^> _factory; public: SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) : _factory(factory) {} ~SchemeHandlerFactoryWrapper() { _factory = nullptr; } virtual CefRefPtr<CefResourceHandler> Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { auto handler = _factory->Create(); CefRefPtr<ResourceHandlerWrapper> wrapper = new ResourceHandlerWrapper(handler); return static_cast<CefRefPtr<CefResourceHandler>>(wrapper); } IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); }; }
// ... existing code ... _factory = nullptr; } virtual CefRefPtr<CefResourceHandler> Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request) OVERRIDE { auto handler = _factory->Create(); CefRefPtr<ResourceHandlerWrapper> wrapper = new ResourceHandlerWrapper(handler); // ... rest of the code ...
291da4afa9f359dc4cfda6a683afdcead39d557b
simiki/conf_templates/fabfile.py
simiki/conf_templates/fabfile.py
from __future__ import absolute_import import os import os.path from fabric.api import env, local, run from fabric.colors import blue import fabric.contrib.project as project # Remote host and username env.hosts = [] env.user = "" env.colorize_errors = True # Local output path env.local_output = os.path.join( os.path.abspath(os.path.dirname(__file__)), "output/") # Remote path to deploy output env.remote_output = "" def update_simiki(): print(blue("Old Version: ")) run("simiki -V") run("pip install -U simiki") print(blue("New Version: ")) run("simiki -V") def deploy(): project.rsync_project( local_dir = env.local_output, remote_dir = env.remote_output.rstrip("/") + "/", delete =True ) def g(): local("simiki generate") def p(): local("simiki preview") def gp(): g() p()
from __future__ import absolute_import import os import os.path from sys import exit from fabric.api import env, local, run from fabric.colors import blue, red import fabric.contrib.project as project # Remote host and username env.hosts = [] env.user = "" env.colorize_errors = True # Local output path env.local_output = os.path.join( os.path.abspath(os.path.dirname(__file__)), "output/") # Remote path to deploy output env.remote_output = "" # Other options env.rsync_delete = False def update_simiki(): print(blue("Old Version: ")) run("simiki -V") run("pip install -U simiki") print(blue("New Version: ")) run("simiki -V") def deploy(): if not env.remote_output: if env.rsync_delete: print(red("You can't enable env.rsync_delete option " "if env.remote_output is not set!!!")) print(blue("Exit")) exit() print(red("Warning: env.remote_output directory is not set!\n" "This will cause some problems!!!")) ans = raw_input(red("Do you want to continue? (y/N) ")) if ans != "y": print(blue("Exit")) exit() project.rsync_project( local_dir = env.local_output, remote_dir = env.remote_output.rstrip("/") + "/", delete = env.rsync_delete ) def g(): local("simiki generate") def p(): local("simiki preview") def gp(): g() p()
Fix serious problem using rsync
Fix serious problem using rsync If env.remote_output not set, use rsync --delete option will empty the whole remote system, this is a very serious problem!
Python
mit
tankywoo/simiki,tankywoo/simiki,9p0le/simiki,9p0le/simiki,9p0le/simiki,zhaochunqi/simiki,tankywoo/simiki,zhaochunqi/simiki,zhaochunqi/simiki
python
## Code Before: from __future__ import absolute_import import os import os.path from fabric.api import env, local, run from fabric.colors import blue import fabric.contrib.project as project # Remote host and username env.hosts = [] env.user = "" env.colorize_errors = True # Local output path env.local_output = os.path.join( os.path.abspath(os.path.dirname(__file__)), "output/") # Remote path to deploy output env.remote_output = "" def update_simiki(): print(blue("Old Version: ")) run("simiki -V") run("pip install -U simiki") print(blue("New Version: ")) run("simiki -V") def deploy(): project.rsync_project( local_dir = env.local_output, remote_dir = env.remote_output.rstrip("/") + "/", delete =True ) def g(): local("simiki generate") def p(): local("simiki preview") def gp(): g() p() ## Instruction: Fix serious problem using rsync If env.remote_output not set, use rsync --delete option will empty the whole remote system, this is a very serious problem! ## Code After: from __future__ import absolute_import import os import os.path from sys import exit from fabric.api import env, local, run from fabric.colors import blue, red import fabric.contrib.project as project # Remote host and username env.hosts = [] env.user = "" env.colorize_errors = True # Local output path env.local_output = os.path.join( os.path.abspath(os.path.dirname(__file__)), "output/") # Remote path to deploy output env.remote_output = "" # Other options env.rsync_delete = False def update_simiki(): print(blue("Old Version: ")) run("simiki -V") run("pip install -U simiki") print(blue("New Version: ")) run("simiki -V") def deploy(): if not env.remote_output: if env.rsync_delete: print(red("You can't enable env.rsync_delete option " "if env.remote_output is not set!!!")) print(blue("Exit")) exit() print(red("Warning: env.remote_output directory is not set!\n" "This will cause some problems!!!")) ans = raw_input(red("Do you want to continue? (y/N) ")) if ans != "y": print(blue("Exit")) exit() project.rsync_project( local_dir = env.local_output, remote_dir = env.remote_output.rstrip("/") + "/", delete = env.rsync_delete ) def g(): local("simiki generate") def p(): local("simiki preview") def gp(): g() p()
// ... existing code ... import os import os.path from sys import exit from fabric.api import env, local, run from fabric.colors import blue, red import fabric.contrib.project as project # Remote host and username // ... modified code ... # Remote path to deploy output env.remote_output = "" # Other options env.rsync_delete = False def update_simiki(): print(blue("Old Version: ")) ... run("simiki -V") def deploy(): if not env.remote_output: if env.rsync_delete: print(red("You can't enable env.rsync_delete option " "if env.remote_output is not set!!!")) print(blue("Exit")) exit() print(red("Warning: env.remote_output directory is not set!\n" "This will cause some problems!!!")) ans = raw_input(red("Do you want to continue? (y/N) ")) if ans != "y": print(blue("Exit")) exit() project.rsync_project( local_dir = env.local_output, remote_dir = env.remote_output.rstrip("/") + "/", delete = env.rsync_delete ) def g(): // ... rest of the code ...
960fb81025643c1122c2d4913ca5130a231527e8
src/main/java/bj/pranie/util/TimeUtil.java
src/main/java/bj/pranie/util/TimeUtil.java
package bj.pranie.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Created by noon on 03.02.17. */ public class TimeUtil { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm"); private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw"); private static Calendar calendar = Calendar.getInstance(timeZone); public static String getTime() { return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE); } public static Calendar getCalendar(){ return (Calendar) calendar.clone(); } public static boolean isPast(String time, String date) { Calendar now = TimeUtil.getCalendar(); now.setTime(new Date()); Calendar calendar = TimeUtil.getCalendar(); try { calendar.setTime(format.parse(date + " " + time)); } catch (ParseException e) { e.printStackTrace(); return false; } if (now.before(calendar)) { return false; } else { return true; } } }
package bj.pranie.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Created by noon on 03.02.17. */ public class TimeUtil { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm"); private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw"); private static Calendar calendar = Calendar.getInstance(timeZone); public static String getTime() { return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE); } public static Calendar getCalendar(){ return (Calendar) calendar.clone(); } public static boolean isPast(String time, String date) { Calendar now = TimeUtil.getCalendar(); Calendar calendar = TimeUtil.getCalendar(); try { calendar.setTime(format.parse(date + " " + time)); } catch (ParseException e) { e.printStackTrace(); return false; } if (now.before(calendar)) { return false; } else { return true; } } }
Remove unnecessary set time to calendar.
Remove unnecessary set time to calendar.
Java
apache-2.0
sebastiansokolowski/ReservationSystem-BJ,sebastiansokolowski/ReservationSystem-BJ
java
## Code Before: package bj.pranie.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Created by noon on 03.02.17. */ public class TimeUtil { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm"); private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw"); private static Calendar calendar = Calendar.getInstance(timeZone); public static String getTime() { return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE); } public static Calendar getCalendar(){ return (Calendar) calendar.clone(); } public static boolean isPast(String time, String date) { Calendar now = TimeUtil.getCalendar(); now.setTime(new Date()); Calendar calendar = TimeUtil.getCalendar(); try { calendar.setTime(format.parse(date + " " + time)); } catch (ParseException e) { e.printStackTrace(); return false; } if (now.before(calendar)) { return false; } else { return true; } } } ## Instruction: Remove unnecessary set time to calendar. ## Code After: package bj.pranie.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Created by noon on 03.02.17. */ public class TimeUtil { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm"); private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw"); private static Calendar calendar = Calendar.getInstance(timeZone); public static String getTime() { return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE); } public static Calendar getCalendar(){ return (Calendar) calendar.clone(); } public static boolean isPast(String time, String date) { Calendar now = TimeUtil.getCalendar(); Calendar calendar = TimeUtil.getCalendar(); try { calendar.setTime(format.parse(date + " " + time)); } catch (ParseException e) { e.printStackTrace(); return false; } if (now.before(calendar)) { return false; } else { return true; } } }
# ... existing code ... public static boolean isPast(String time, String date) { Calendar now = TimeUtil.getCalendar(); Calendar calendar = TimeUtil.getCalendar(); try { # ... rest of the code ...
72d0ca4e2f4be7969498b226af4243315f2dff0c
tests/test_colors.py
tests/test_colors.py
"""Test imagemagick functions.""" import unittest from pywal import colors class TestGenColors(unittest.TestCase): """Test the gen_colors functions.""" def test_gen_colors(self): """> Generate a colorscheme.""" result = colors.get("tests/test_files/test.jpg") self.assertEqual(result["colors"]["color0"], "#0D191B") if __name__ == "__main__": unittest.main()
"""Test imagemagick functions.""" import unittest from pywal import colors class TestGenColors(unittest.TestCase): """Test the gen_colors functions.""" def test_gen_colors(self): """> Generate a colorscheme.""" result = colors.get("tests/test_files/test.jpg") self.assertEqual(len(result["colors"]["color0"]), 7) if __name__ == "__main__": unittest.main()
Check color length instead of value since the tests will fail on other versions of imageamgick
tests: Check color length instead of value since the tests will fail on other versions of imageamgick
Python
mit
dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal
python
## Code Before: """Test imagemagick functions.""" import unittest from pywal import colors class TestGenColors(unittest.TestCase): """Test the gen_colors functions.""" def test_gen_colors(self): """> Generate a colorscheme.""" result = colors.get("tests/test_files/test.jpg") self.assertEqual(result["colors"]["color0"], "#0D191B") if __name__ == "__main__": unittest.main() ## Instruction: tests: Check color length instead of value since the tests will fail on other versions of imageamgick ## Code After: """Test imagemagick functions.""" import unittest from pywal import colors class TestGenColors(unittest.TestCase): """Test the gen_colors functions.""" def test_gen_colors(self): """> Generate a colorscheme.""" result = colors.get("tests/test_files/test.jpg") self.assertEqual(len(result["colors"]["color0"]), 7) if __name__ == "__main__": unittest.main()
... def test_gen_colors(self): """> Generate a colorscheme.""" result = colors.get("tests/test_files/test.jpg") self.assertEqual(len(result["colors"]["color0"]), 7) if __name__ == "__main__": ...
198cc2829c109bef95d2b4608cc4ee1460ada804
src/main/java/com/imsweb/seerapi/client/cs/CsSchema.java
src/main/java/com/imsweb/seerapi/client/cs/CsSchema.java
/* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } }
/* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<CsSiteSpecificFactor>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } }
Maintain Java 6 compatibility for now
Maintain Java 6 compatibility for now
Java
mit
imsweb/seerapi-client-java
java
## Code Before: /* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } } ## Instruction: Maintain Java 6 compatibility for now ## Code After: /* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<CsSiteSpecificFactor>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } }
# ... existing code ... @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<CsSiteSpecificFactor>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") # ... rest of the code ...
797815f0927078072fe16ac4f54571ee3884f35b
beaform-core/src/test/java/beaform/utilities/SystemTimeTest.java
beaform-core/src/test/java/beaform/utilities/SystemTimeTest.java
package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.Test; public class SystemTimeTest { @Test public void testDefaultTimeSource() { final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertBetween("The tested value is not between the given arguments", start, end, tested); } private void assertBetween(String message, long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } assertTrue(message, (lower <= tested) && (tested <= upper)); } }
package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.Test; public class SystemTimeTest { @Test public void testDefaultTimeSource() { final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } return (lower <= tested) && (tested <= upper); } }
Move the actual assertion to the test
Move the actual assertion to the test
Java
mit
stevenpost/beaform
java
## Code Before: package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.Test; public class SystemTimeTest { @Test public void testDefaultTimeSource() { final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertBetween("The tested value is not between the given arguments", start, end, tested); } private void assertBetween(String message, long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } assertTrue(message, (lower <= tested) && (tested <= upper)); } } ## Instruction: Move the actual assertion to the test ## Code After: package beaform.utilities; import static org.junit.Assert.assertTrue; import org.junit.Test; public class SystemTimeTest { @Test public void testDefaultTimeSource() { final long start = System.currentTimeMillis(); final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { lower = boundary1; upper = boundary2; } else { lower = boundary2; upper = boundary1; } return (lower <= tested) && (tested <= upper); } }
... final long tested = SystemTime.getAsLong(); final long end = System.currentTimeMillis(); assertTrue("The tested value is not between the given arguments", isBetween(start, end, tested)); } private boolean isBetween(long boundary1, long boundary2, long tested) { long upper, lower; if (boundary1 <= boundary2) { ... upper = boundary1; } return (lower <= tested) && (tested <= upper); } } ...
693ce5f8b1344f072e1f116ebf3ad79ffaad42b6
fungui.py
fungui.py
# Import modules from PyQt4 import QtGui, QtCore
# Import modules from PyQt4 import QtGui, QtCore import sys # Global variables FRAME_WIDTH = 1020 FRAME_HEIGHT = 480 class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) # create stuff self.wdg = Widget() self.setCentralWidget(self.wdg) self.createActions() self.createMenus() #self.createStatusBar() # format the main window self.resize(FRAME_WIDTH, FRAME_HEIGHT) self.center() self.setWindowTitle('Fungui') # show windows self.show() self.wdg.show() def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def about(self): QtGui.QMessageBox.about(self, self.tr("About fungui"), self.tr("fungui...")) def createActions(self): self.exitAct = QtGui.QAction(self.tr("E&xit"), self) self.exitAct.setShortcut(self.tr("Ctrl+Q")) self.exitAct.setStatusTip(self.tr("Exit the application")) self.exitAct.triggered.connect(self.close) self.aboutAct = QtGui.QAction(self.tr("&About"), self) self.aboutAct.setStatusTip(self.tr("Show the application's About box")) self.aboutAct.triggered.connect(self.about) self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self) self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box")) self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu(self.tr("&File")) self.fileMenu.addAction(self.exitAct) self.helpMenu = self.menuBar().addMenu(self.tr("&Help")) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) class Widget(QtGui.QWidget): def __init__(self): super(Widget, self).__init__() # set font for tips QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) self.create_frame() def create_frame(self): """The frame""" self.main_frame = QtGui.QWidget() def main(): app = QtGui.QApplication(sys.argv) mw = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main()
Create a frame with a menu bar.
Create a frame with a menu bar. The software will have several buttons, but the idea of the menu bar is to have redundancy on the commands and to inform the user of the shortcuts.
Python
bsd-3-clause
leouieda/funghi
python
## Code Before: # Import modules from PyQt4 import QtGui, QtCore ## Instruction: Create a frame with a menu bar. The software will have several buttons, but the idea of the menu bar is to have redundancy on the commands and to inform the user of the shortcuts. ## Code After: # Import modules from PyQt4 import QtGui, QtCore import sys # Global variables FRAME_WIDTH = 1020 FRAME_HEIGHT = 480 class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) # create stuff self.wdg = Widget() self.setCentralWidget(self.wdg) self.createActions() self.createMenus() #self.createStatusBar() # format the main window self.resize(FRAME_WIDTH, FRAME_HEIGHT) self.center() self.setWindowTitle('Fungui') # show windows self.show() self.wdg.show() def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def about(self): QtGui.QMessageBox.about(self, self.tr("About fungui"), self.tr("fungui...")) def createActions(self): self.exitAct = QtGui.QAction(self.tr("E&xit"), self) self.exitAct.setShortcut(self.tr("Ctrl+Q")) self.exitAct.setStatusTip(self.tr("Exit the application")) self.exitAct.triggered.connect(self.close) self.aboutAct = QtGui.QAction(self.tr("&About"), self) self.aboutAct.setStatusTip(self.tr("Show the application's About box")) self.aboutAct.triggered.connect(self.about) self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self) self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box")) self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu(self.tr("&File")) self.fileMenu.addAction(self.exitAct) self.helpMenu = self.menuBar().addMenu(self.tr("&Help")) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) class Widget(QtGui.QWidget): def __init__(self): super(Widget, self).__init__() # set font for tips QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) self.create_frame() def create_frame(self): """The frame""" self.main_frame = QtGui.QWidget() def main(): app = QtGui.QApplication(sys.argv) mw = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main()
... # Import modules from PyQt4 import QtGui, QtCore import sys # Global variables FRAME_WIDTH = 1020 FRAME_HEIGHT = 480 class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) # create stuff self.wdg = Widget() self.setCentralWidget(self.wdg) self.createActions() self.createMenus() #self.createStatusBar() # format the main window self.resize(FRAME_WIDTH, FRAME_HEIGHT) self.center() self.setWindowTitle('Fungui') # show windows self.show() self.wdg.show() def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def about(self): QtGui.QMessageBox.about(self, self.tr("About fungui"), self.tr("fungui...")) def createActions(self): self.exitAct = QtGui.QAction(self.tr("E&xit"), self) self.exitAct.setShortcut(self.tr("Ctrl+Q")) self.exitAct.setStatusTip(self.tr("Exit the application")) self.exitAct.triggered.connect(self.close) self.aboutAct = QtGui.QAction(self.tr("&About"), self) self.aboutAct.setStatusTip(self.tr("Show the application's About box")) self.aboutAct.triggered.connect(self.about) self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self) self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box")) self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu(self.tr("&File")) self.fileMenu.addAction(self.exitAct) self.helpMenu = self.menuBar().addMenu(self.tr("&Help")) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) class Widget(QtGui.QWidget): def __init__(self): super(Widget, self).__init__() # set font for tips QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) self.create_frame() def create_frame(self): """The frame""" self.main_frame = QtGui.QWidget() def main(): app = QtGui.QApplication(sys.argv) mw = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() ...
eac7026af8a003ed4bdbb76fd6c9baab2e33461b
src/main/java/me/august/lumen/common/Modifier.java
src/main/java/me/august/lumen/common/Modifier.java
package me.august.lumen.common; import java.util.ArrayList; import java.util.List; public enum Modifier { PUBLIC(0x0001), PRIVATE(0x0002), PROTECTED(0x004), PACKAGE_PRIVATE(0x0000), FINAL(0x0010), STATIC(0x0008), ABSTRACT(0x0400), VOLATILE(0x0040), SYNCHRONIZED(0x0020), NATIVE(0x0100); private int value; Modifier(int value) { this.value = value; } public int getValue() { return value; } public static int compose(Modifier... mods) { int res = 0; for (Modifier m : mods) { res |= m.value; } return res; } public static Modifier[] fromAccess(int access) { List<Modifier> modifiers = new ArrayList<>(); for (Modifier mod : values()) { if ((access & mod.getValue()) == mod.getValue()) { modifiers.add(mod); } } return modifiers.toArray(new Modifier[modifiers.size()]); } }
package me.august.lumen.common; import java.util.ArrayList; import java.util.List; public enum Modifier { PUBLIC(0x0001), PRIVATE(0x0002), PROTECTED(0x004), PACKAGE_PRIVATE(0x0000), FINAL(0x0010), STATIC(0x0008), ABSTRACT(0x0400), VOLATILE(0x0040), SYNCHRONIZED(0x0020), NATIVE(0x0100); private int value; Modifier(int value) { this.value = value; } public int getValue() { return value; } public static int compose(Modifier... mods) { int res = 0; for (Modifier m : mods) { res |= m.value; } return res; } public static Modifier[] fromAccess(int access) { List<Modifier> modifiers = new ArrayList<>(); for (Modifier mod : values()) { if ((access & mod.getValue()) == mod.getValue()) { modifiers.add(mod); } } if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED)) { modifiers.remove(PACKAGE_PRIVATE); } return modifiers.toArray(new Modifier[modifiers.size()]); } }
Fix package private modifier presence
Fix package private modifier presence
Java
mit
augustt198/lumen
java
## Code Before: package me.august.lumen.common; import java.util.ArrayList; import java.util.List; public enum Modifier { PUBLIC(0x0001), PRIVATE(0x0002), PROTECTED(0x004), PACKAGE_PRIVATE(0x0000), FINAL(0x0010), STATIC(0x0008), ABSTRACT(0x0400), VOLATILE(0x0040), SYNCHRONIZED(0x0020), NATIVE(0x0100); private int value; Modifier(int value) { this.value = value; } public int getValue() { return value; } public static int compose(Modifier... mods) { int res = 0; for (Modifier m : mods) { res |= m.value; } return res; } public static Modifier[] fromAccess(int access) { List<Modifier> modifiers = new ArrayList<>(); for (Modifier mod : values()) { if ((access & mod.getValue()) == mod.getValue()) { modifiers.add(mod); } } return modifiers.toArray(new Modifier[modifiers.size()]); } } ## Instruction: Fix package private modifier presence ## Code After: package me.august.lumen.common; import java.util.ArrayList; import java.util.List; public enum Modifier { PUBLIC(0x0001), PRIVATE(0x0002), PROTECTED(0x004), PACKAGE_PRIVATE(0x0000), FINAL(0x0010), STATIC(0x0008), ABSTRACT(0x0400), VOLATILE(0x0040), SYNCHRONIZED(0x0020), NATIVE(0x0100); private int value; Modifier(int value) { this.value = value; } public int getValue() { return value; } public static int compose(Modifier... mods) { int res = 0; for (Modifier m : mods) { res |= m.value; } return res; } public static Modifier[] fromAccess(int access) { List<Modifier> modifiers = new ArrayList<>(); for (Modifier mod : values()) { if ((access & mod.getValue()) == mod.getValue()) { modifiers.add(mod); } } if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED)) { modifiers.remove(PACKAGE_PRIVATE); } return modifiers.toArray(new Modifier[modifiers.size()]); } }
// ... existing code ... modifiers.add(mod); } } if (modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED)) { modifiers.remove(PACKAGE_PRIVATE); } return modifiers.toArray(new Modifier[modifiers.size()]); } } // ... rest of the code ...
48b2460c718af88e8140b108d4a9acd9258ade8c
gargoyle/__init__.py
gargoyle/__init__.py
try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
__import__('pkg_resources').declare_namespace(__name__)
Change to vanilla namespace package
Change to vanilla namespace package
Python
apache-2.0
disqus/gutter,disqus/gutter,kalail/gutter,kalail/gutter,kalail/gutter
python
## Code Before: try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) ## Instruction: Change to vanilla namespace package ## Code After: __import__('pkg_resources').declare_namespace(__name__)
// ... existing code ... __import__('pkg_resources').declare_namespace(__name__) // ... rest of the code ...
0182fa2e384034fbbe1326fa887bb537c05d4525
test/FrontendC/2010-05-18-asmsched.c
test/FrontendC/2010-05-18-asmsched.c
// RUN: %llvmgcc %s -c -O3 -m64 -emit-llvm -o - | llc -march=x86-64 -mtriple=x86_64-apple-darwin | FileCheck %s // XFAIL: * // XTARGET: x86,i386,i686 // r9 used to be clobbered before its value was moved to r10. 7993104. void foo(int x, int y) { // CHECK: bar // CHECK: movq %r9, %r10 // CHECK: movq %rdi, %r9 // CHECK: bar register int lr9 asm("r9") = x; register int lr10 asm("r10") = y; int foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); foo = lr9; lr9 = x; lr10 = foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); }
// RUN: %llvmgcc %s -c -O3 -m64 -emit-llvm -o - | llc -march=x86-64 -mtriple=x86_64-apple-darwin | FileCheck %s // r9 used to be clobbered before its value was moved to r10. 7993104. void foo(int x, int y) { // CHECK: bar // CHECK: movq %r9, %r10 // CHECK: movq %rdi, %r9 // CHECK: bar register int lr9 asm("r9") = x; register int lr10 asm("r10") = y; int foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); foo = lr9; lr9 = x; lr10 = foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); }
Test passed on ppc, to my surprise; if it worked there it may work everywhere...
Test passed on ppc, to my surprise; if it worked there it may work everywhere... git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@104053 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm
c
## Code Before: // RUN: %llvmgcc %s -c -O3 -m64 -emit-llvm -o - | llc -march=x86-64 -mtriple=x86_64-apple-darwin | FileCheck %s // XFAIL: * // XTARGET: x86,i386,i686 // r9 used to be clobbered before its value was moved to r10. 7993104. void foo(int x, int y) { // CHECK: bar // CHECK: movq %r9, %r10 // CHECK: movq %rdi, %r9 // CHECK: bar register int lr9 asm("r9") = x; register int lr10 asm("r10") = y; int foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); foo = lr9; lr9 = x; lr10 = foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); } ## Instruction: Test passed on ppc, to my surprise; if it worked there it may work everywhere... git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@104053 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %llvmgcc %s -c -O3 -m64 -emit-llvm -o - | llc -march=x86-64 -mtriple=x86_64-apple-darwin | FileCheck %s // r9 used to be clobbered before its value was moved to r10. 7993104. void foo(int x, int y) { // CHECK: bar // CHECK: movq %r9, %r10 // CHECK: movq %rdi, %r9 // CHECK: bar register int lr9 asm("r9") = x; register int lr10 asm("r10") = y; int foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); foo = lr9; lr9 = x; lr10 = foo; asm volatile("bar" : "=r"(lr9) : "r"(lr9), "r"(lr10)); }
# ... existing code ... // RUN: %llvmgcc %s -c -O3 -m64 -emit-llvm -o - | llc -march=x86-64 -mtriple=x86_64-apple-darwin | FileCheck %s // r9 used to be clobbered before its value was moved to r10. 7993104. void foo(int x, int y) { # ... rest of the code ...
9c7ec15d6347d915cd0285927ed651d4ae6508c1
amen/time.py
amen/time.py
import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time, self.duration return '<TimeSlice, start:{0:.2f}, duration:{1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice)
import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time.delta / 1000000000.0, self.duration.delta / 1000000000.0 return '<TimeSlice, start: {0:.2f}, duration: {1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice)
Fix formatting bug in repr
Fix formatting bug in repr
Python
bsd-2-clause
algorithmic-music-exploration/amen,algorithmic-music-exploration/amen
python
## Code Before: import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time, self.duration return '<TimeSlice, start:{0:.2f}, duration:{1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice) ## Instruction: Fix formatting bug in repr ## Code After: import six import numpy as np import pandas as pd class TimeSlice(object): """ A slice of time: has a start time, a duration, and a reference to an Audio object. """ def __init__(self, time, duration, audio, unit='s'): self.time = pd.to_timedelta(time, unit=unit) self.duration = pd.to_timedelta(duration, unit=unit) self.audio = audio def __repr__(self): args = self.time.delta / 1000000000.0, self.duration.delta / 1000000000.0 return '<TimeSlice, start: {0:.2f}, duration: {1:.2f}'.format(*args) class TimingList(list): """ A list of TimeSlices. """ def __init__(self, name, timings, audio, unit='s'): # This assumes that we're going to get a list of tuples (start, duration) from librosa, # which may or may not be true. self.name = name for (start, duration) in timings: slice = TimeSlice(start, duration, audio, unit=unit) self.append(slice)
... self.audio = audio def __repr__(self): args = self.time.delta / 1000000000.0, self.duration.delta / 1000000000.0 return '<TimeSlice, start: {0:.2f}, duration: {1:.2f}'.format(*args) class TimingList(list): """ ...
38b4af0b3c1c6105d68ff453d86107758ef9d751
preconditions.py
preconditions.py
class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format(p)) i = -len(spec.defaults) appargs, closureargs = spec.args[:i], spec.args[i:] precinfo.append( (appargs, closureargs, p) ) def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Python
mit
nejucomo/preconditions
python
## Code Before: class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate ## Instruction: Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function. ## Code After: import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format(p)) i = -len(spec.defaults) appargs, closureargs = spec.args[:i], spec.args[i:] precinfo.append( (appargs, closureargs, p) ) def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
// ... existing code ... import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format(p)) i = -len(spec.defaults) appargs, closureargs = spec.args[:i], spec.args[i:] precinfo.append( (appargs, closureargs, p) ) def decorate(f): def g(*a, **kw): return f(*a, **kw) // ... rest of the code ...
4c9654096e1e6d9cb1bf4574432a992ecdc24117
src/registers.h
src/registers.h
/* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */
/* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ /* * Set with each arithmetic/logical operation (OPL). * ZF: was the result 0? * SF: was the result < 0? * OF: did the result overflow? (2's complement) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */
Add descriptions of the CC's
Add descriptions of the CC's
C
isc
sbennett1990/YESS,sbennett1990/YESS,sbennett1990/YESS
c
## Code Before: /* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */ ## Instruction: Add descriptions of the CC's ## Code After: /* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ /* * Set with each arithmetic/logical operation (OPL). * ZF: was the result 0? * SF: was the result < 0? * OF: did the result overflow? (2's complement) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */
// ... existing code ... #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ /* * Set with each arithmetic/logical operation (OPL). * ZF: was the result 0? * SF: was the result < 0? * OF: did the result overflow? (2's complement) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ // ... rest of the code ...
5168a28ff8a268b5e01c336fa162730c4ac9bafb
AndroidRequestLoaders/src/main/java/ru/nixan/android/requestloaders/IRequest.java
AndroidRequestLoaders/src/main/java/ru/nixan/android/requestloaders/IRequest.java
package ru.nixan.android.requestloaders; import android.content.Context; /** * Created by nixan on 11/26/13. */ public interface IRequest { /** * Executes the request. In case of any error in implemented protocol or actual implementation * of network stack please throw an exception. */ public void execute(Context context); /** * Cancel the executing request */ public void cancel(); /** * @return if the instance of this request class have already been executed */ public boolean wasExecuted(); /** * Set the result of the request */ public void setException(Exception exception); /** * @return the exception that occured during excecution. */ public Exception getException(); /** * @return if the request was succesfull */ public boolean isSuccesfull(); }
package ru.nixan.android.requestloaders; import android.content.Context; /** * Created by nixan on 11/26/13. */ public interface IRequest { /** * Executes the request. */ public void execute(Context context); /** * Cancel the executing request */ public void cancel(); /** * @return if the instance of this request class have already been executed */ public boolean wasExecuted(); /** * Set the result of the request */ public void setException(Exception exception); /** * @return the exception that occured during excecution. */ public Exception getException(); /** * @return if the request was succesfull */ public boolean isSuccesfull(); }
Change comment about Exceptions in execute
Change comment about Exceptions in execute
Java
mit
qiwi/java-android-network-request-loader
java
## Code Before: package ru.nixan.android.requestloaders; import android.content.Context; /** * Created by nixan on 11/26/13. */ public interface IRequest { /** * Executes the request. In case of any error in implemented protocol or actual implementation * of network stack please throw an exception. */ public void execute(Context context); /** * Cancel the executing request */ public void cancel(); /** * @return if the instance of this request class have already been executed */ public boolean wasExecuted(); /** * Set the result of the request */ public void setException(Exception exception); /** * @return the exception that occured during excecution. */ public Exception getException(); /** * @return if the request was succesfull */ public boolean isSuccesfull(); } ## Instruction: Change comment about Exceptions in execute ## Code After: package ru.nixan.android.requestloaders; import android.content.Context; /** * Created by nixan on 11/26/13. */ public interface IRequest { /** * Executes the request. */ public void execute(Context context); /** * Cancel the executing request */ public void cancel(); /** * @return if the instance of this request class have already been executed */ public boolean wasExecuted(); /** * Set the result of the request */ public void setException(Exception exception); /** * @return the exception that occured during excecution. */ public Exception getException(); /** * @return if the request was succesfull */ public boolean isSuccesfull(); }
// ... existing code ... public interface IRequest { /** * Executes the request. */ public void execute(Context context); // ... rest of the code ...
c763ce6d152597312f2b40d40311a85bf156af60
src/test/java/ml/shifu/shifu/core/ConvergeJudgerTest.java
src/test/java/ml/shifu/shifu/core/ConvergeJudgerTest.java
package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.Test; public class ConvergeJudgerTest { @Test public void testJudge() { ConvergeJudger judger = new ConvergeJudger(); Assert.assertTrue(judger.judge(1.0, 2.0)); Assert.assertTrue(judger.judge(1.0, 1.0)); Assert.assertFalse(judger.judge(1.0, 0.1)); } }
package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConvergeJudgerTest { private ConvergeJudger judger; @BeforeClass public void setUp() { this.judger = new ConvergeJudger(); } @Test public void testJudge() { Assert.assertTrue(judger.judge(1.0, 2.0)); Assert.assertTrue(judger.judge(1.0, 1.0)); Assert.assertFalse(judger.judge(1.0, 0.1)); } }
Use setup to initialize judger instance.
Use setup to initialize judger instance.
Java
apache-2.0
ShifuML/shifu,ShifuML/shifu,ShifuML/shifu
java
## Code Before: package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.Test; public class ConvergeJudgerTest { @Test public void testJudge() { ConvergeJudger judger = new ConvergeJudger(); Assert.assertTrue(judger.judge(1.0, 2.0)); Assert.assertTrue(judger.judge(1.0, 1.0)); Assert.assertFalse(judger.judge(1.0, 0.1)); } } ## Instruction: Use setup to initialize judger instance. ## Code After: package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConvergeJudgerTest { private ConvergeJudger judger; @BeforeClass public void setUp() { this.judger = new ConvergeJudger(); } @Test public void testJudge() { Assert.assertTrue(judger.judge(1.0, 2.0)); Assert.assertTrue(judger.judge(1.0, 1.0)); Assert.assertFalse(judger.judge(1.0, 0.1)); } }
# ... existing code ... package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConvergeJudgerTest { private ConvergeJudger judger; @BeforeClass public void setUp() { this.judger = new ConvergeJudger(); } @Test public void testJudge() { Assert.assertTrue(judger.judge(1.0, 2.0)); Assert.assertTrue(judger.judge(1.0, 1.0)); Assert.assertFalse(judger.judge(1.0, 0.1)); } } # ... rest of the code ...
24acb5ee218e20c7e7af477bcbe8d3b339ab63fe
std/stack.c
std/stack.c
struct Stack { NodeT *list; AtomPoolT *pool; }; StackT *NewStack(AtomPoolT *pool) { StackT *stack = NEW_S(StackT); stack->list = NewList(); stack->pool = pool; StackPushNew(stack); return stack; } void DeleteStack(StackT *stack) { if (stack) { DeleteList(stack->list); DeleteAtomPool(stack->pool); DELETE(stack); } } void StackReset(StackT *stack) { ResetList(stack->list); ResetAtomPool(stack->pool); } void StackRemove(StackT *stack) { AtomFree(stack->pool, ListPopFront(stack->list)); } PtrT StackPeek(StackT *stack, size_t index) { return ListGetNth(stack->list, index); } PtrT StackTop(StackT *stack) { return ListGetNth(stack->list, 0); } PtrT StackPushNew(StackT *stack) { PtrT item = AtomNew0(stack->pool); ListPushFront(stack->list, item); return item; } size_t StackSize(StackT *stack) { return ListSize(stack->list); }
struct Stack { ListT *list; AtomPoolT *pool; }; StackT *NewStack(AtomPoolT *pool) { StackT *stack = NEW_S(StackT); stack->list = NewList(); stack->pool = pool; StackPushNew(stack); return stack; } void DeleteStack(StackT *stack) { if (stack) { DeleteList(stack->list); DeleteAtomPool(stack->pool); DELETE(stack); } } void StackReset(StackT *stack) { ResetList(stack->list); ResetAtomPool(stack->pool); } void StackRemove(StackT *stack) { AtomFree(stack->pool, ListPopFront(stack->list)); } PtrT StackPeek(StackT *stack, size_t index) { return ListGet(stack->list, index); } PtrT StackTop(StackT *stack) { return ListGet(stack->list, 0); } PtrT StackPushNew(StackT *stack) { PtrT item = AtomNew0(stack->pool); ListPushFront(stack->list, item); return item; } size_t StackSize(StackT *stack) { return ListSize(stack->list); }
Correct after list API changes.
Correct after list API changes.
C
artistic-2.0
cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene
c
## Code Before: struct Stack { NodeT *list; AtomPoolT *pool; }; StackT *NewStack(AtomPoolT *pool) { StackT *stack = NEW_S(StackT); stack->list = NewList(); stack->pool = pool; StackPushNew(stack); return stack; } void DeleteStack(StackT *stack) { if (stack) { DeleteList(stack->list); DeleteAtomPool(stack->pool); DELETE(stack); } } void StackReset(StackT *stack) { ResetList(stack->list); ResetAtomPool(stack->pool); } void StackRemove(StackT *stack) { AtomFree(stack->pool, ListPopFront(stack->list)); } PtrT StackPeek(StackT *stack, size_t index) { return ListGetNth(stack->list, index); } PtrT StackTop(StackT *stack) { return ListGetNth(stack->list, 0); } PtrT StackPushNew(StackT *stack) { PtrT item = AtomNew0(stack->pool); ListPushFront(stack->list, item); return item; } size_t StackSize(StackT *stack) { return ListSize(stack->list); } ## Instruction: Correct after list API changes. ## Code After: struct Stack { ListT *list; AtomPoolT *pool; }; StackT *NewStack(AtomPoolT *pool) { StackT *stack = NEW_S(StackT); stack->list = NewList(); stack->pool = pool; StackPushNew(stack); return stack; } void DeleteStack(StackT *stack) { if (stack) { DeleteList(stack->list); DeleteAtomPool(stack->pool); DELETE(stack); } } void StackReset(StackT *stack) { ResetList(stack->list); ResetAtomPool(stack->pool); } void StackRemove(StackT *stack) { AtomFree(stack->pool, ListPopFront(stack->list)); } PtrT StackPeek(StackT *stack, size_t index) { return ListGet(stack->list, index); } PtrT StackTop(StackT *stack) { return ListGet(stack->list, 0); } PtrT StackPushNew(StackT *stack) { PtrT item = AtomNew0(stack->pool); ListPushFront(stack->list, item); return item; } size_t StackSize(StackT *stack) { return ListSize(stack->list); }
... struct Stack { ListT *list; AtomPoolT *pool; }; ... } PtrT StackPeek(StackT *stack, size_t index) { return ListGet(stack->list, index); } PtrT StackTop(StackT *stack) { return ListGet(stack->list, 0); } PtrT StackPushNew(StackT *stack) { ...
2ceb4f7195220d52ce92156da9332b50369fb746
bluesnap/exceptions.py
bluesnap/exceptions.py
class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
Return formatted messages in APIError
Return formatted messages in APIError
Python
mit
justyoyo/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python,kowito/bluesnap-python
python
## Code Before: class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass ## Instruction: Return formatted messages in APIError ## Code After: class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
# ... existing code ... class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): # ... rest of the code ...
35a9087ae23b9e8bd1b8b811fce8619fa05d74ce
src/main/java/com/ao/adrestia/controller/HomeController.java
src/main/java/com/ao/adrestia/controller/HomeController.java
/* Apache2 License Notice Copyright 2017 Alex Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ao.adrestia.controller; import java.security.Principal; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @SuppressWarnings("unused") @Controller public class HomeController { private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController"); @RequestMapping(value = "/portal/home", method = RequestMethod.GET) protected String home(final Map<String, Object> model, final Principal principal) { logger.info("Home page"); if (principal == null) { logger.warn("No Principal Detected"); return "redirect:/logout"; } model.put("userId", principal); return "home"; } }
/* Apache2 License Notice Copyright 2017 Alex Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ao.adrestia.controller; import java.security.Principal; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @SuppressWarnings("unused") @Controller public class HomeController { @Value(value = "${server.auth.active}") private boolean authActive; private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController"); @RequestMapping(value = "/portal/home", method = RequestMethod.GET) protected String home(final Map<String, Object> model, final Principal principal) { logger.info("Home page"); if (principal == null && authActive) { logger.warn("No Principal Detected"); return "redirect:/logout"; } model.put("userId", principal); return "home"; } }
Allow access to the homepage if authorization is inactive
Allow access to the homepage if authorization is inactive
Java
apache-2.0
AO-StreetArt/Adrestia,AO-StreetArt/Adrestia,AO-StreetArt/Adrestia
java
## Code Before: /* Apache2 License Notice Copyright 2017 Alex Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ao.adrestia.controller; import java.security.Principal; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @SuppressWarnings("unused") @Controller public class HomeController { private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController"); @RequestMapping(value = "/portal/home", method = RequestMethod.GET) protected String home(final Map<String, Object> model, final Principal principal) { logger.info("Home page"); if (principal == null) { logger.warn("No Principal Detected"); return "redirect:/logout"; } model.put("userId", principal); return "home"; } } ## Instruction: Allow access to the homepage if authorization is inactive ## Code After: /* Apache2 License Notice Copyright 2017 Alex Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ao.adrestia.controller; import java.security.Principal; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @SuppressWarnings("unused") @Controller public class HomeController { @Value(value = "${server.auth.active}") private boolean authActive; private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController"); @RequestMapping(value = "/portal/home", method = RequestMethod.GET) protected String home(final Map<String, Object> model, final Principal principal) { logger.info("Home page"); if (principal == null && authActive) { logger.warn("No Principal Detected"); return "redirect:/logout"; } model.put("userId", principal); return "home"; } }
# ... existing code ... import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; # ... modified code ... @Controller public class HomeController { @Value(value = "${server.auth.active}") private boolean authActive; private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController"); @RequestMapping(value = "/portal/home", method = RequestMethod.GET) protected String home(final Map<String, Object> model, final Principal principal) { logger.info("Home page"); if (principal == null && authActive) { logger.warn("No Principal Detected"); return "redirect:/logout"; } # ... rest of the code ...
7d24695c7e94e787b5d66854db7cc6dc1abcbf10
polyaxon/tracker/publish_tracker.py
polyaxon/tracker/publish_tracker.py
import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): if not self.cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( self.get_cluster_id(), event.serialize(dumps=False), ) self.analytics.track( self.get_cluster_id(), event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id()
import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): cluster_id = self.get_cluster_id() if not cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( cluster_id, event.serialize(dumps=False), ) self.analytics.track( cluster_id, event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id()
Update check on cluster id
Update check on cluster id
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
python
## Code Before: import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): if not self.cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( self.get_cluster_id(), event.serialize(dumps=False), ) self.analytics.track( self.get_cluster_id(), event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id() ## Instruction: Update check on cluster id ## Code After: import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): cluster_id = self.get_cluster_id() if not cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( cluster_id, event.serialize(dumps=False), ) self.analytics.track( cluster_id, event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id()
... return self.cluster_id def record_event(self, event): cluster_id = self.get_cluster_id() if not cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( cluster_id, event.serialize(dumps=False), ) self.analytics.track( cluster_id, event.event_type, event.serialize(dumps=False), ) ...
1ba4d84fb72a343cdf288d905d2029f1d2fbee12
wagtail/api/v2/pagination.py
wagtail/api/v2/pagination.py
from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) assert offset >= 0 except (ValueError, AssertionError): raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit_max and limit > limit_max: raise BadRequestError("limit cannot be higher than %d" % limit_max) assert limit >= 0 except (ValueError, AssertionError): raise BadRequestError("limit must be a positive integer") start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
Remove assert from WagtailPagination.paginate_queryset method
Remove assert from WagtailPagination.paginate_queryset method
Python
bsd-3-clause
mikedingjan/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,jnns/wagtail,mixxorz/wagtail,wagtail/wagtail,mixxorz/wagtail,FlipperPA/wagtail,wagtail/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,mikedingjan/wagtail,timorieber/wagtail,zerolab/wagtail,gasman/wagtail,jnns/wagtail,zerolab/wagtail,kaedroho/wagtail,thenewguy/wagtail,FlipperPA/wagtail,nimasmi/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,mikedingjan/wagtail,mixxorz/wagtail,rsalmaso/wagtail,kaedroho/wagtail,nealtodd/wagtail,takeflight/wagtail,mixxorz/wagtail,nimasmi/wagtail,torchbox/wagtail,kaedroho/wagtail,jnns/wagtail,mikedingjan/wagtail,timorieber/wagtail,nealtodd/wagtail,wagtail/wagtail,nealtodd/wagtail,thenewguy/wagtail,thenewguy/wagtail,thenewguy/wagtail,FlipperPA/wagtail,takeflight/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,takeflight/wagtail,nimasmi/wagtail,FlipperPA/wagtail,wagtail/wagtail,zerolab/wagtail,jnns/wagtail,rsalmaso/wagtail,nimasmi/wagtail,timorieber/wagtail,takeflight/wagtail,gasman/wagtail,kaedroho/wagtail,rsalmaso/wagtail,gasman/wagtail,timorieber/wagtail,wagtail/wagtail,kaedroho/wagtail,nealtodd/wagtail
python
## Code Before: from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) assert offset >= 0 except (ValueError, AssertionError): raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit_max and limit > limit_max: raise BadRequestError("limit cannot be higher than %d" % limit_max) assert limit >= 0 except (ValueError, AssertionError): raise BadRequestError("limit must be a positive integer") start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data) ## Instruction: Remove assert from WagtailPagination.paginate_queryset method ## Code After: from collections import OrderedDict from django.conf import settings from rest_framework.pagination import BasePagination from rest_framework.response import Response from .utils import BadRequestError class WagtailPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20) try: offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) start = offset stop = offset + limit self.view = view self.total_count = queryset.count() return queryset[start:stop] def get_paginated_response(self, data): data = OrderedDict([ ('meta', OrderedDict([ ('total_count', self.total_count), ])), ('items', data), ]) return Response(data)
// ... existing code ... try: offset = int(request.GET.get('offset', 0)) if offset < 0: raise ValueError() except ValueError: raise BadRequestError("offset must be a positive integer") try: limit_default = 20 if not limit_max else min(20, limit_max) limit = int(request.GET.get('limit', limit_default)) if limit < 0: raise ValueError() except ValueError: raise BadRequestError("limit must be a positive integer") if limit_max and limit > limit_max: raise BadRequestError( "limit cannot be higher than %d" % limit_max) start = offset stop = offset + limit // ... rest of the code ...
bc15058cc95916788250d660d5560b69a82e0b89
warehouse/__main__.py
warehouse/__main__.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from warehouse import script def main(): script.run() if __name__ == "__main__": main()
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import sys from flask.ext.script import InvalidCommand # pylint: disable=E0611,F0401 from warehouse import script def main(): # This is copied over from script.run and modified for Warehouse try: try: command = sys.argv[1] except IndexError: raise InvalidCommand("Please provide a command:") return script.handle("warehouse", command, sys.argv[2:]) except InvalidCommand as exc: print exc script.print_usage() return 1 if __name__ == "__main__": sys.exit(main())
Customize the command runner for cleaner output
Customize the command runner for cleaner output
Python
bsd-2-clause
davidfischer/warehouse
python
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from warehouse import script def main(): script.run() if __name__ == "__main__": main() ## Instruction: Customize the command runner for cleaner output ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import sys from flask.ext.script import InvalidCommand # pylint: disable=E0611,F0401 from warehouse import script def main(): # This is copied over from script.run and modified for Warehouse try: try: command = sys.argv[1] except IndexError: raise InvalidCommand("Please provide a command:") return script.handle("warehouse", command, sys.argv[2:]) except InvalidCommand as exc: print exc script.print_usage() return 1 if __name__ == "__main__": sys.exit(main())
# ... existing code ... from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import sys from flask.ext.script import InvalidCommand # pylint: disable=E0611,F0401 from warehouse import script def main(): # This is copied over from script.run and modified for Warehouse try: try: command = sys.argv[1] except IndexError: raise InvalidCommand("Please provide a command:") return script.handle("warehouse", command, sys.argv[2:]) except InvalidCommand as exc: print exc script.print_usage() return 1 if __name__ == "__main__": sys.exit(main()) # ... rest of the code ...
c889ffd1f86a445f2e5ba157fc81cbb64e92dc12
voctocore/lib/sources/videoloopsource.py
voctocore/lib/sources/videoloopsource.py
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): def __init__(self, name): super().__init__('VideoLoopSource', name, False, True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc name=videoloop-{name} location={location} loop=true ! decodebin ! videoconvert ! videoscale name=videoloop """.format( name=self.name, location=self.location ) def build_videoport(self): return 'videoloop.' def build_audioport(self, audiostream): return 'audioloop.'
import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): timer_resolution = 0.5 def __init__(self, name, has_audio=True, has_video=True, force_num_streams=None): super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc location={location} loop=true ! decodebin name=videoloop-{name} """.format( name=self.name, location=self.location ) def build_videoport(self): return """ videoloop-{name}. ! videoconvert ! videoscale """.format(name=self.name) def build_audioport(self): return """ videoloop-{name}. ! audioconvert ! audioresample """.format(name=self.name)
Modify videoloop to allow for audio
Modify videoloop to allow for audio
Python
mit
voc/voctomix,voc/voctomix
python
## Code Before: import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): def __init__(self, name): super().__init__('VideoLoopSource', name, False, True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc name=videoloop-{name} location={location} loop=true ! decodebin ! videoconvert ! videoscale name=videoloop """.format( name=self.name, location=self.location ) def build_videoport(self): return 'videoloop.' def build_audioport(self, audiostream): return 'audioloop.' ## Instruction: Modify videoloop to allow for audio ## Code After: import logging import re from gi.repository import Gst from lib.config import Config from lib.sources.avsource import AVSource class VideoLoopSource(AVSource): timer_resolution = 0.5 def __init__(self, name, has_audio=True, has_video=True, force_num_streams=None): super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() def __str__(self): return 'VideoLoopSource[{name}] displaying {location}'.format( name=self.name, location=self.location ) def port(self): m = re.search('.*/([^/]*)', self.location) return self.location def num_connections(self): return 1 def video_channels(self): return 1 def build_source(self): return """ multifilesrc location={location} loop=true ! decodebin name=videoloop-{name} """.format( name=self.name, location=self.location ) def build_videoport(self): return """ videoloop-{name}. ! videoconvert ! videoscale """.format(name=self.name) def build_audioport(self): return """ videoloop-{name}. ! audioconvert ! audioresample """.format(name=self.name)
... class VideoLoopSource(AVSource): timer_resolution = 0.5 def __init__(self, name, has_audio=True, has_video=True, force_num_streams=None): super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True) self.location = Config.getLocation(name) self.build_pipeline() ... def build_source(self): return """ multifilesrc location={location} loop=true ! decodebin name=videoloop-{name} """.format( name=self.name, location=self.location ... ) def build_videoport(self): return """ videoloop-{name}. ! videoconvert ! videoscale """.format(name=self.name) def build_audioport(self): return """ videoloop-{name}. ! audioconvert ! audioresample """.format(name=self.name) ...
8ca4437691459b8d743bc02b99ade3b37cbb324d
biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignParameters.java
biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignParameters.java
package org.biojava.nbio.structure.align.quaternary; /** * The parameter bean for the {@link QsAlign} algorithm. * * @author Aleix Lafita * @since 5.0.0 * */ public class QsAlignParameters { private double dCutoff = 10.0; /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @return dCutoff */ public double getdCutoff() { return dCutoff; } /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @param dCutoff */ public void setdCutoff(double dCutoff) { this.dCutoff = dCutoff; } }
package org.biojava.nbio.structure.align.quaternary; /** * The parameter bean for the {@link QsAlign} algorithm. * * @author Aleix Lafita * @since 5.0.0 * */ public class QsAlignParameters { private double dCutoff = 10.0; private double maxRmsd = 7.0; private double minOrientationMetric = Math.PI / 8; // 45 degree /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @return dCutoff */ public double getdCutoff() { return dCutoff; } /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @param dCutoff */ public void setdCutoff(double dCutoff) { this.dCutoff = dCutoff; } public double getMaxRmsd() { return maxRmsd; } public void setMaxRmsd(double maxRmsd) { this.maxRmsd = maxRmsd; } public double getMinOrientationMetric() { return minOrientationMetric; } public void setMinOrientationMetric(double minOrientationMetric) { this.minOrientationMetric = minOrientationMetric; } }
Add more parameters for QsAlign
Add more parameters for QsAlign
Java
lgpl-2.1
lafita/biojava,emckee2006/biojava,pwrose/biojava,lafita/biojava,heuermh/biojava,lafita/biojava,andreasprlic/biojava,biojava/biojava,biojava/biojava,pwrose/biojava,andreasprlic/biojava,heuermh/biojava,andreasprlic/biojava,sbliven/biojava-sbliven,sbliven/biojava-sbliven,heuermh/biojava,sbliven/biojava-sbliven,biojava/biojava,emckee2006/biojava,andreasprlic/biojava,pwrose/biojava,emckee2006/biojava
java
## Code Before: package org.biojava.nbio.structure.align.quaternary; /** * The parameter bean for the {@link QsAlign} algorithm. * * @author Aleix Lafita * @since 5.0.0 * */ public class QsAlignParameters { private double dCutoff = 10.0; /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @return dCutoff */ public double getdCutoff() { return dCutoff; } /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @param dCutoff */ public void setdCutoff(double dCutoff) { this.dCutoff = dCutoff; } } ## Instruction: Add more parameters for QsAlign ## Code After: package org.biojava.nbio.structure.align.quaternary; /** * The parameter bean for the {@link QsAlign} algorithm. * * @author Aleix Lafita * @since 5.0.0 * */ public class QsAlignParameters { private double dCutoff = 10.0; private double maxRmsd = 7.0; private double minOrientationMetric = Math.PI / 8; // 45 degree /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @return dCutoff */ public double getdCutoff() { return dCutoff; } /** * The maximum allowed distance between the centroids of two equivalent * Subunits, in A. * * @param dCutoff */ public void setdCutoff(double dCutoff) { this.dCutoff = dCutoff; } public double getMaxRmsd() { return maxRmsd; } public void setMaxRmsd(double maxRmsd) { this.maxRmsd = maxRmsd; } public double getMinOrientationMetric() { return minOrientationMetric; } public void setMinOrientationMetric(double minOrientationMetric) { this.minOrientationMetric = minOrientationMetric; } }
// ... existing code ... public class QsAlignParameters { private double dCutoff = 10.0; private double maxRmsd = 7.0; private double minOrientationMetric = Math.PI / 8; // 45 degree /** * The maximum allowed distance between the centroids of two equivalent // ... modified code ... this.dCutoff = dCutoff; } public double getMaxRmsd() { return maxRmsd; } public void setMaxRmsd(double maxRmsd) { this.maxRmsd = maxRmsd; } public double getMinOrientationMetric() { return minOrientationMetric; } public void setMinOrientationMetric(double minOrientationMetric) { this.minOrientationMetric = minOrientationMetric; } } // ... rest of the code ...
ab46b3a31f69f778cd1fc1312dee3db4d0aa23a0
data-model-db/src/main/java/org/mousephenotype/cda/db/repositories/ParameterRepository.java
data-model-db/src/main/java/org/mousephenotype/cda/db/repositories/ParameterRepository.java
/******************************************************************************* * Copyright © 2019 EMBL - European Bioinformatics Institute * <p/> * 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 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package org.mousephenotype.cda.db.repositories; import org.mousephenotype.cda.db.pojo.Parameter; import org.springframework.data.repository.CrudRepository; public interface ParameterRepository extends CrudRepository<Parameter, Long> { Parameter getByStableId(String stableId); }
/******************************************************************************* * Copyright © 2019 EMBL - European Bioinformatics Institute * <p/> * 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 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package org.mousephenotype.cda.db.repositories; import org.mousephenotype.cda.db.pojo.Parameter; import org.springframework.data.repository.CrudRepository; public interface ParameterRepository extends CrudRepository<Parameter, Long> { Parameter getByStableId(String stableId); Parameter getFirstByStableId(String stableId); }
Add method to find first by parameter stable id
Add method to find first by parameter stable id
Java
apache-2.0
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
java
## Code Before: /******************************************************************************* * Copyright © 2019 EMBL - European Bioinformatics Institute * <p/> * 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 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package org.mousephenotype.cda.db.repositories; import org.mousephenotype.cda.db.pojo.Parameter; import org.springframework.data.repository.CrudRepository; public interface ParameterRepository extends CrudRepository<Parameter, Long> { Parameter getByStableId(String stableId); } ## Instruction: Add method to find first by parameter stable id ## Code After: /******************************************************************************* * Copyright © 2019 EMBL - European Bioinformatics Institute * <p/> * 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 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package org.mousephenotype.cda.db.repositories; import org.mousephenotype.cda.db.pojo.Parameter; import org.springframework.data.repository.CrudRepository; public interface ParameterRepository extends CrudRepository<Parameter, Long> { Parameter getByStableId(String stableId); Parameter getFirstByStableId(String stableId); }
# ... existing code ... public interface ParameterRepository extends CrudRepository<Parameter, Long> { Parameter getByStableId(String stableId); Parameter getFirstByStableId(String stableId); } # ... rest of the code ...
8cee7d5478cde2b188da4dc93f844073be729a48
src/gerobak/apps/profile/models.py
src/gerobak/apps/profile/models.py
from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.db.models.signals import post_save from gerobak import utils class Profile(models.Model): pid = models.CharField(max_length=8) user = models.ForeignKey(User) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) desc = models.CharField(max_length=250, null=True, blank=True) arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS, default=settings.GEROBAK_DEFAULT_ARCH) repo_updated = models.DateTimeField(null=True, default=None) sources_updated = models.DateTimeField(null=True, default=None) sources_total = models.IntegerField(null=True, default=None) status_updated = models.DateTimeField(null=True, default=None) status_hash = models.CharField(max_length=32, null=True, default=None) status_size = models.IntegerField(default=0) def is_ready(self): return self.repo_updated is not None and \ self.status_updated is not None def generate_pid(self): import uuid return str(uuid.uuid4()).split('-')[0]
from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.db.models.signals import post_save from gerobak import utils class Profile(models.Model): pid = models.CharField(max_length=8) user = models.ForeignKey(User) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) desc = models.CharField(max_length=250, null=True, blank=True) arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS, default=settings.GEROBAK_DEFAULT_ARCH) repo_updated = models.DateTimeField(null=True, default=None) sources_updated = models.DateTimeField(null=True, default=None) sources_total = models.IntegerField(null=True, default=None) status_updated = models.DateTimeField(null=True, default=None) status_hash = models.CharField(max_length=32, null=True, default=None) status_size = models.IntegerField(default=0) tid_update = models.CharField(max_length=36, null=True, default=None) tid_install = models.CharField(max_length=36, null=True, default=None) tid_upgrade = models.CharField(max_length=36, null=True, default=None) def is_ready(self): return self.repo_updated is not None and \ self.status_updated is not None def generate_pid(self): import uuid return str(uuid.uuid4()).split('-')[0]
Store task_id for update, install, and upgrade processes in the database.
Store task_id for update, install, and upgrade processes in the database.
Python
agpl-3.0
fajran/gerobak,fajran/gerobak
python
## Code Before: from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.db.models.signals import post_save from gerobak import utils class Profile(models.Model): pid = models.CharField(max_length=8) user = models.ForeignKey(User) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) desc = models.CharField(max_length=250, null=True, blank=True) arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS, default=settings.GEROBAK_DEFAULT_ARCH) repo_updated = models.DateTimeField(null=True, default=None) sources_updated = models.DateTimeField(null=True, default=None) sources_total = models.IntegerField(null=True, default=None) status_updated = models.DateTimeField(null=True, default=None) status_hash = models.CharField(max_length=32, null=True, default=None) status_size = models.IntegerField(default=0) def is_ready(self): return self.repo_updated is not None and \ self.status_updated is not None def generate_pid(self): import uuid return str(uuid.uuid4()).split('-')[0] ## Instruction: Store task_id for update, install, and upgrade processes in the database. ## Code After: from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.db.models.signals import post_save from gerobak import utils class Profile(models.Model): pid = models.CharField(max_length=8) user = models.ForeignKey(User) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) desc = models.CharField(max_length=250, null=True, blank=True) arch = models.CharField(max_length=10, choices=settings.GEROBAK_ARCHS, default=settings.GEROBAK_DEFAULT_ARCH) repo_updated = models.DateTimeField(null=True, default=None) sources_updated = models.DateTimeField(null=True, default=None) sources_total = models.IntegerField(null=True, default=None) status_updated = models.DateTimeField(null=True, default=None) status_hash = models.CharField(max_length=32, null=True, default=None) status_size = models.IntegerField(default=0) tid_update = models.CharField(max_length=36, null=True, default=None) tid_install = models.CharField(max_length=36, null=True, default=None) tid_upgrade = models.CharField(max_length=36, null=True, default=None) def is_ready(self): return self.repo_updated is not None and \ self.status_updated is not None def generate_pid(self): import uuid return str(uuid.uuid4()).split('-')[0]
# ... existing code ... status_hash = models.CharField(max_length=32, null=True, default=None) status_size = models.IntegerField(default=0) tid_update = models.CharField(max_length=36, null=True, default=None) tid_install = models.CharField(max_length=36, null=True, default=None) tid_upgrade = models.CharField(max_length=36, null=True, default=None) def is_ready(self): return self.repo_updated is not None and \ self.status_updated is not None # ... rest of the code ...
0911322da92ca9d3db2abcedb811c97357b07f8e
BaragonAgentService/src/main/java/com/hubspot/baragon/agent/resources/RenderedConfigsResource.java
BaragonAgentService/src/main/java/com/hubspot/baragon/agent/resources/RenderedConfigsResource.java
package com.hubspot.baragon.agent.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hubspot.baragon.agent.managers.AgentRequestManager; @Path("/renderedConfigs") @Produces(MediaType.APPLICATION_JSON) public class RenderedConfigsResource { private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class); private final AgentRequestManager agentRequestManager; @Inject public RenderedConfigsResource( AgentRequestManager agentRequestManager) { this.agentRequestManager = agentRequestManager; } @GET @Path("/{serviceId}") public Response getServiceId(@PathParam("serviceId") String serviceId) { LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId); return agentRequestManager.getRenderedConfigs(serviceId); } }
package com.hubspot.baragon.agent.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hubspot.baragon.agent.managers.AgentRequestManager; import com.hubspot.baragon.auth.NoAuth; @Path("/renderedConfigs") @Produces(MediaType.APPLICATION_JSON) public class RenderedConfigsResource { private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class); private final AgentRequestManager agentRequestManager; @Inject public RenderedConfigsResource( AgentRequestManager agentRequestManager) { this.agentRequestManager = agentRequestManager; } @GET @NoAuth @Path("/{serviceId}") public Response getServiceId(@PathParam("serviceId") String serviceId) { LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId); return agentRequestManager.getRenderedConfigs(serviceId); } }
Make GET to /renderedConfigs/{serviceId} at the Agent level not require authentication
Make GET to /renderedConfigs/{serviceId} at the Agent level not require authentication
Java
apache-2.0
HubSpot/Baragon,HubSpot/Baragon,HubSpot/Baragon
java
## Code Before: package com.hubspot.baragon.agent.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hubspot.baragon.agent.managers.AgentRequestManager; @Path("/renderedConfigs") @Produces(MediaType.APPLICATION_JSON) public class RenderedConfigsResource { private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class); private final AgentRequestManager agentRequestManager; @Inject public RenderedConfigsResource( AgentRequestManager agentRequestManager) { this.agentRequestManager = agentRequestManager; } @GET @Path("/{serviceId}") public Response getServiceId(@PathParam("serviceId") String serviceId) { LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId); return agentRequestManager.getRenderedConfigs(serviceId); } } ## Instruction: Make GET to /renderedConfigs/{serviceId} at the Agent level not require authentication ## Code After: package com.hubspot.baragon.agent.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hubspot.baragon.agent.managers.AgentRequestManager; import com.hubspot.baragon.auth.NoAuth; @Path("/renderedConfigs") @Produces(MediaType.APPLICATION_JSON) public class RenderedConfigsResource { private static final Logger LOG = LoggerFactory.getLogger(RenderedConfigsResource.class); private final AgentRequestManager agentRequestManager; @Inject public RenderedConfigsResource( AgentRequestManager agentRequestManager) { this.agentRequestManager = agentRequestManager; } @GET @NoAuth @Path("/{serviceId}") public Response getServiceId(@PathParam("serviceId") String serviceId) { LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId); return agentRequestManager.getRenderedConfigs(serviceId); } }
# ... existing code ... import com.google.inject.Inject; import com.hubspot.baragon.agent.managers.AgentRequestManager; import com.hubspot.baragon.auth.NoAuth; @Path("/renderedConfigs") @Produces(MediaType.APPLICATION_JSON) # ... modified code ... } @GET @NoAuth @Path("/{serviceId}") public Response getServiceId(@PathParam("serviceId") String serviceId) { LOG.info("Received request to view the renderedConfig of serviceId={}", serviceId); # ... rest of the code ...
7e080edea2139c5cce907f4d752320943b044ac7
game.py
game.py
people = '123456' room = 'abcdef' # murder configuration # who was where # who is the murderer # current configuration # who was where # player location
import random people = '123456' room = 'abcdef' # murder configuration # who was where # who is the murderer # current configuration # who was where # player location murder_config_people = list(people) random.shuffle(murder_config_people) murder_location = random.choice(room) murderer = people[room.find(murder_location)] current_config_people = list(people) random.shuffle(current_config_people) current_location = random.choice(room) print( current_config_people) print( current_location)
Add random people and rooms
Add random people and rooms
Python
mit
tomviner/dojo-adventure-game
python
## Code Before: people = '123456' room = 'abcdef' # murder configuration # who was where # who is the murderer # current configuration # who was where # player location ## Instruction: Add random people and rooms ## Code After: import random people = '123456' room = 'abcdef' # murder configuration # who was where # who is the murderer # current configuration # who was where # player location murder_config_people = list(people) random.shuffle(murder_config_people) murder_location = random.choice(room) murderer = people[room.find(murder_location)] current_config_people = list(people) random.shuffle(current_config_people) current_location = random.choice(room) print( current_config_people) print( current_location)
... import random people = '123456' room = 'abcdef' ... # who was where # player location murder_config_people = list(people) random.shuffle(murder_config_people) murder_location = random.choice(room) murderer = people[room.find(murder_location)] current_config_people = list(people) random.shuffle(current_config_people) current_location = random.choice(room) print( current_config_people) print( current_location) ...
77cf51c33f8819fee7329285bfe09292e1a7c2d3
src/main/java/io/github/trevornelson/Constants.java
src/main/java/io/github/trevornelson/Constants.java
package io.github.trevornelson; /** * Contains the client IDs and scopes for allowed clients consuming the helloworld API. */ public class Constants { public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com"; public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; }
package io.github.trevornelson; public class Constants { public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com"; public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; public static final String ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly"; }
Add ANALYTICS_SCOPE constant to constants file
Add ANALYTICS_SCOPE constant to constants file
Java
apache-2.0
trevornelson/java-analytics-dashboard,trevornelson/java-analytics-dashboard,trevornelson/java-analytics-dashboard
java
## Code Before: package io.github.trevornelson; /** * Contains the client IDs and scopes for allowed clients consuming the helloworld API. */ public class Constants { public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com"; public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; } ## Instruction: Add ANALYTICS_SCOPE constant to constants file ## Code After: package io.github.trevornelson; public class Constants { public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com"; public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; public static final String ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly"; }
// ... existing code ... package io.github.trevornelson; public class Constants { public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com"; public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; // ... modified code ... public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; public static final String ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly"; } // ... rest of the code ...
318cbaabb289034584cdfb82639c84ed91fc6e2e
tests/test_io.py
tests/test_io.py
import pytest from pikepdf import Pdf from io import BytesIO @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf')
import pytest from pikepdf import Pdf from pikepdf._cpphelpers import fspath from io import BytesIO from shutil import copy import sys @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf') @pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil') def test_overwrite_input(resources, outdir): copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf') p = Pdf.open(outdir / 'sandwich.pdf') with pytest.raises(ValueError, match=r'overwrite input file'): p.save(outdir / 'sandwich.pdf')
Add test to check that we do not overwrite input file
Add test to check that we do not overwrite input file
Python
mpl-2.0
pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf
python
## Code Before: import pytest from pikepdf import Pdf from io import BytesIO @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf') ## Instruction: Add test to check that we do not overwrite input file ## Code After: import pytest from pikepdf import Pdf from pikepdf._cpphelpers import fspath from io import BytesIO from shutil import copy import sys @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf') @pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil') def test_overwrite_input(resources, outdir): copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf') p = Pdf.open(outdir / 'sandwich.pdf') with pytest.raises(ValueError, match=r'overwrite input file'): p.save(outdir / 'sandwich.pdf')
... import pytest from pikepdf import Pdf from pikepdf._cpphelpers import fspath from io import BytesIO from shutil import copy import sys @pytest.fixture ... (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf') @pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil') def test_overwrite_input(resources, outdir): copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf') p = Pdf.open(outdir / 'sandwich.pdf') with pytest.raises(ValueError, match=r'overwrite input file'): p.save(outdir / 'sandwich.pdf') ...
253c6b1a470f10d936119306264d4acfc62b51de
src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java
src/main/java/com/enderio/core/api/common/enchant/IAdvancedEnchant.java
package com.enderio.core.api.common.enchant; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.EnderCore; import com.google.common.base.Predicate; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; /** * Allows your enchants to have some flavor or description text underneath them */ public interface IAdvancedEnchant { public static final EnumEnchantmentType ALL = EnumHelper.addEnchantmentType("EC_REALLY_ALL", new Predicate<Item>() { @Override public boolean apply(@Nullable Item input) { return true; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } }); /** * Get the detail for this itemstack * * @param stack * @return a list of <code>String</code>s to be bulleted under the enchantment */ default @Nonnull String[] getTooltipDetails(@Nonnull ItemStack stack) { return EnderCore.lang.splitList(EnderCore.lang.localizeExact("description." + ((Enchantment) this).getName())); } }
package com.enderio.core.api.common.enchant; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.EnderCore; import com.google.common.base.Predicate; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; /** * Allows your enchants to have some flavor or description text underneath them */ public interface IAdvancedEnchant { public static final EnumEnchantmentType ALL = EnumHelper.addEnchantmentType("EC_REALLY_ALL", new Predicate<Item>() { @Override public boolean apply(@Nullable Item input) { return true; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } }); /** * Get the detail for this itemstack * * @param stack * @return a list of <code>String</code>s to be bulleted under the enchantment */ default @Nonnull String[] getTooltipDetails(@Nonnull ItemStack stack) { final String unloc = "description." + ((Enchantment) this).getName(); final String loc = EnderCore.lang.localizeExact(unloc); return unloc.equals(loc) ? new String[0] : EnderCore.lang.splitList(loc); } }
Fix enchantment default tooltips not checking translation keys for existance
Fix enchantment default tooltips not checking translation keys for existance
Java
cc0-1.0
SleepyTrousers/EnderCore
java
## Code Before: package com.enderio.core.api.common.enchant; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.EnderCore; import com.google.common.base.Predicate; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; /** * Allows your enchants to have some flavor or description text underneath them */ public interface IAdvancedEnchant { public static final EnumEnchantmentType ALL = EnumHelper.addEnchantmentType("EC_REALLY_ALL", new Predicate<Item>() { @Override public boolean apply(@Nullable Item input) { return true; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } }); /** * Get the detail for this itemstack * * @param stack * @return a list of <code>String</code>s to be bulleted under the enchantment */ default @Nonnull String[] getTooltipDetails(@Nonnull ItemStack stack) { return EnderCore.lang.splitList(EnderCore.lang.localizeExact("description." + ((Enchantment) this).getName())); } } ## Instruction: Fix enchantment default tooltips not checking translation keys for existance ## Code After: package com.enderio.core.api.common.enchant; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.EnderCore; import com.google.common.base.Predicate; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; /** * Allows your enchants to have some flavor or description text underneath them */ public interface IAdvancedEnchant { public static final EnumEnchantmentType ALL = EnumHelper.addEnchantmentType("EC_REALLY_ALL", new Predicate<Item>() { @Override public boolean apply(@Nullable Item input) { return true; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj); } }); /** * Get the detail for this itemstack * * @param stack * @return a list of <code>String</code>s to be bulleted under the enchantment */ default @Nonnull String[] getTooltipDetails(@Nonnull ItemStack stack) { final String unloc = "description." + ((Enchantment) this).getName(); final String loc = EnderCore.lang.localizeExact(unloc); return unloc.equals(loc) ? new String[0] : EnderCore.lang.splitList(loc); } }
... * @return a list of <code>String</code>s to be bulleted under the enchantment */ default @Nonnull String[] getTooltipDetails(@Nonnull ItemStack stack) { final String unloc = "description." + ((Enchantment) this).getName(); final String loc = EnderCore.lang.localizeExact(unloc); return unloc.equals(loc) ? new String[0] : EnderCore.lang.splitList(loc); } } ...
1c7af58f9fabb5edfc559660d742825d3fbdefb0
chaoswg/forms.py
chaoswg/forms.py
from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField from wtforms.validators import InputRequired, NumberRange, Optional class LoginForm(FlaskForm): name = StringField(u'Username', validators=[InputRequired()]) password = PasswordField(u'Password', validators=[InputRequired()]) submit = SubmitField(u'Login') class CreateTaskForm(FlaskForm): task = StringField(u'Task', validators=[InputRequired()]) base_points = IntegerField(u'Base Points', validators=[NumberRange(1, 13, 'Value must be between 1 and 13')]) time_factor = FloatField(u'Time Factor', validators=[NumberRange(0.0, 3.0, 'Value must be between 0.0 and 3.0')]) schedule_days = IntegerField(u'Schedule every X days (optional)', validators=[Optional(), NumberRange(1, 365, 'Value must be between 1 and 365')]) submit = SubmitField(u'Create Task') class CustomTaskForm(FlaskForm): task = StringField(u'Custom Task', validators=[InputRequired()]) points = IntegerField(u'Points', validators=[NumberRange(1, 13, 'Value must be between 1 and 13')]) submit = SubmitField(u'Do Task now')
from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField from wtforms.validators import InputRequired, NumberRange, Optional class LoginForm(FlaskForm): name = StringField(u'Username', validators=[InputRequired()]) password = PasswordField(u'Password', validators=[InputRequired()]) submit = SubmitField(u'Login') class CreateTaskForm(FlaskForm): task = StringField(u'Task', validators=[InputRequired()]) base_points = IntegerField(u'Base Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) time_factor = FloatField(u'Time Factor', validators=[InputRequired(), NumberRange(0.0, 3.0, 'Value must be between 0.0 and 3.0')], default=0.0) schedule_days = IntegerField(u'Schedule every X days (optional)', validators=[Optional(), NumberRange(1, 365, 'Value must be between 1 and 365')]) submit = SubmitField(u'Create Task') class CustomTaskForm(FlaskForm): task = StringField(u'Custom Task', validators=[InputRequired()]) points = IntegerField(u'Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) submit = SubmitField(u'Do Task now')
Add some defaults for form input
Add some defaults for form input
Python
agpl-3.0
Obihoernchen/ChaosWG-Manager,Obihoernchen/ChaosWG-Manager,Obihoernchen/ChaosWG-Manager
python
## Code Before: from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField from wtforms.validators import InputRequired, NumberRange, Optional class LoginForm(FlaskForm): name = StringField(u'Username', validators=[InputRequired()]) password = PasswordField(u'Password', validators=[InputRequired()]) submit = SubmitField(u'Login') class CreateTaskForm(FlaskForm): task = StringField(u'Task', validators=[InputRequired()]) base_points = IntegerField(u'Base Points', validators=[NumberRange(1, 13, 'Value must be between 1 and 13')]) time_factor = FloatField(u'Time Factor', validators=[NumberRange(0.0, 3.0, 'Value must be between 0.0 and 3.0')]) schedule_days = IntegerField(u'Schedule every X days (optional)', validators=[Optional(), NumberRange(1, 365, 'Value must be between 1 and 365')]) submit = SubmitField(u'Create Task') class CustomTaskForm(FlaskForm): task = StringField(u'Custom Task', validators=[InputRequired()]) points = IntegerField(u'Points', validators=[NumberRange(1, 13, 'Value must be between 1 and 13')]) submit = SubmitField(u'Do Task now') ## Instruction: Add some defaults for form input ## Code After: from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField from wtforms.validators import InputRequired, NumberRange, Optional class LoginForm(FlaskForm): name = StringField(u'Username', validators=[InputRequired()]) password = PasswordField(u'Password', validators=[InputRequired()]) submit = SubmitField(u'Login') class CreateTaskForm(FlaskForm): task = StringField(u'Task', validators=[InputRequired()]) base_points = IntegerField(u'Base Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) time_factor = FloatField(u'Time Factor', validators=[InputRequired(), NumberRange(0.0, 3.0, 'Value must be between 0.0 and 3.0')], default=0.0) schedule_days = IntegerField(u'Schedule every X days (optional)', validators=[Optional(), NumberRange(1, 365, 'Value must be between 1 and 365')]) submit = SubmitField(u'Create Task') class CustomTaskForm(FlaskForm): task = StringField(u'Custom Task', validators=[InputRequired()]) points = IntegerField(u'Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) submit = SubmitField(u'Do Task now')
... class CreateTaskForm(FlaskForm): task = StringField(u'Task', validators=[InputRequired()]) base_points = IntegerField(u'Base Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) time_factor = FloatField(u'Time Factor', validators=[InputRequired(), NumberRange(0.0, 3.0, 'Value must be between 0.0 and 3.0')], default=0.0) schedule_days = IntegerField(u'Schedule every X days (optional)', validators=[Optional(), NumberRange(1, 365, 'Value must be between 1 and 365')]) ... class CustomTaskForm(FlaskForm): task = StringField(u'Custom Task', validators=[InputRequired()]) points = IntegerField(u'Points', validators=[InputRequired(), NumberRange(1, 13, 'Value must be between 1 and 13')], default=1) submit = SubmitField(u'Do Task now') ...
0b28fe44514969470db926c6f38615a8a5478bf6
smoke_signal/__init__.py
smoke_signal/__init__.py
from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
Remove the no-JS version from the app
Remove the no-JS version from the app I haven't looked into it for a long while.
Python
mit
flacerdk/smoke-signal,flacerdk/smoke-signal,flacerdk/smoke-signal
python
## Code Before: from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close() ## Instruction: Remove the no-JS version from the app I haven't looked into it for a long while. ## Code After: from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
// ... existing code ... from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker // ... modified code ... app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request // ... rest of the code ...
52f585aa3aaaa4f645b61575d6ca307555247bcc
appengine/models/product_group.py
appengine/models/product_group.py
from google.appengine.ext import ndb from endpoints_proto_datastore.ndb import EndpointsModel from endpoints_proto_datastore.ndb import EndpointsAliasProperty from protorpc import messages class ProductGroup(EndpointsModel): _message_fields_schema = ('id', 'tag', 'description', 'url', 'image') _api_key = None # Hashtag to be used for the product group tag = ndb.StringProperty() # Description of the Activity Type / to be displayed in the Front End description = ndb.StringProperty() # URL of the Google Developers site for this product url = ndb.StringProperty() # Badge-image for this product image = ndb.StringProperty() def ApiKeySet(self, value): self._api_key = value @EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField) def api_key(self): return self._api_key def IdSet(self, value): if not isinstance(value, basestring): raise TypeError('ID must be a string.') self.UpdateFromKey(ndb.Key(ProductGroup, value)) @EndpointsAliasProperty(setter=IdSet, required=True) def id(self): if self.key is not None: return self.key.string_id() @classmethod def all_tags(cls): return [entity.tag for entity in cls.query()]
from google.appengine.ext import ndb from endpoints_proto_datastore.ndb import EndpointsModel from endpoints_proto_datastore.ndb import EndpointsAliasProperty from protorpc import messages class ProductGroup(EndpointsModel): _message_fields_schema = ( 'id', 'tag', 'description', 'url', 'image', 'so_tags') _api_key = None # Hashtag to be used for the product group tag = ndb.StringProperty() # Description of the Activity Type / to be displayed in the Front End description = ndb.StringProperty() # URL of the Google Developers site for this product url = ndb.StringProperty() # Badge-image for this product image = ndb.StringProperty() # Stack Overflow tags of interest : issue #211 on github so_tags = ndb.StringProperty(repeated=True) def ApiKeySet(self, value): self._api_key = value @EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField) def api_key(self): return self._api_key def IdSet(self, value): if not isinstance(value, basestring): raise TypeError('ID must be a string.') self.UpdateFromKey(ndb.Key(ProductGroup, value)) @EndpointsAliasProperty(setter=IdSet, required=True) def id(self): if self.key is not None: return self.key.string_id() @classmethod def all_tags(cls): return [entity.tag for entity in cls.query()]
Add so tags to ProductGroup entity
Add so tags to ProductGroup entity
Python
apache-2.0
GoogleDeveloperExperts/experts-app-backend
python
## Code Before: from google.appengine.ext import ndb from endpoints_proto_datastore.ndb import EndpointsModel from endpoints_proto_datastore.ndb import EndpointsAliasProperty from protorpc import messages class ProductGroup(EndpointsModel): _message_fields_schema = ('id', 'tag', 'description', 'url', 'image') _api_key = None # Hashtag to be used for the product group tag = ndb.StringProperty() # Description of the Activity Type / to be displayed in the Front End description = ndb.StringProperty() # URL of the Google Developers site for this product url = ndb.StringProperty() # Badge-image for this product image = ndb.StringProperty() def ApiKeySet(self, value): self._api_key = value @EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField) def api_key(self): return self._api_key def IdSet(self, value): if not isinstance(value, basestring): raise TypeError('ID must be a string.') self.UpdateFromKey(ndb.Key(ProductGroup, value)) @EndpointsAliasProperty(setter=IdSet, required=True) def id(self): if self.key is not None: return self.key.string_id() @classmethod def all_tags(cls): return [entity.tag for entity in cls.query()] ## Instruction: Add so tags to ProductGroup entity ## Code After: from google.appengine.ext import ndb from endpoints_proto_datastore.ndb import EndpointsModel from endpoints_proto_datastore.ndb import EndpointsAliasProperty from protorpc import messages class ProductGroup(EndpointsModel): _message_fields_schema = ( 'id', 'tag', 'description', 'url', 'image', 'so_tags') _api_key = None # Hashtag to be used for the product group tag = ndb.StringProperty() # Description of the Activity Type / to be displayed in the Front End description = ndb.StringProperty() # URL of the Google Developers site for this product url = ndb.StringProperty() # Badge-image for this product image = ndb.StringProperty() # Stack Overflow tags of interest : issue #211 on github so_tags = ndb.StringProperty(repeated=True) def ApiKeySet(self, value): self._api_key = value @EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField) def api_key(self): return self._api_key def IdSet(self, value): if not isinstance(value, basestring): raise TypeError('ID must be a string.') self.UpdateFromKey(ndb.Key(ProductGroup, value)) @EndpointsAliasProperty(setter=IdSet, required=True) def id(self): if self.key is not None: return self.key.string_id() @classmethod def all_tags(cls): return [entity.tag for entity in cls.query()]
// ... existing code ... class ProductGroup(EndpointsModel): _message_fields_schema = ( 'id', 'tag', 'description', 'url', 'image', 'so_tags') _api_key = None // ... modified code ... # Badge-image for this product image = ndb.StringProperty() # Stack Overflow tags of interest : issue #211 on github so_tags = ndb.StringProperty(repeated=True) def ApiKeySet(self, value): self._api_key = value // ... rest of the code ...
eba27be700a564cc412a67dcdd8841850dda22da
src/main/java/leetcode/Problem315.java
src/main/java/leetcode/Problem315.java
package leetcode; import java.util.ArrayList; import java.util.List; /** * https://leetcode.com/problems/count-of-smaller-numbers-after-self/ */ public class Problem315 { public List<Integer> countSmaller(int[] nums) { List<Integer> result = new ArrayList<>(); // TODO: return result; } public static void main(String[] args) { Problem315 prob = new Problem315(); System.out.println(prob.countSmaller(new int[]{5, 2, 6, 1})); // [2, 1, 1, 0] } }
package leetcode; import java.util.Arrays; import java.util.List; /** * https://leetcode.com/problems/count-of-smaller-numbers-after-self/ */ public class Problem315 { public List<Integer> countSmaller(int[] nums) { int[] tmp = nums.clone(); Arrays.sort(tmp); for (int i = 0; i < nums.length; i++) { nums[i] = Arrays.binarySearch(tmp, nums[i]) + 1; } int[] bit = new int[nums.length + 1]; Integer[] ans = new Integer[nums.length]; for (int i = nums.length - 1; i >= 0; i--) { ans[i] = query(bit, nums[i] - 1); add(bit, nums[i], 1); } return Arrays.asList(ans); } private void add(int[] bit, int i, int val) { for (; i < bit.length; i += i & -i) { bit[i] += val; } } private int query(int[] bit, int i) { int ans = 0; for (; i > 0; i -= i & -i) { ans += bit[i]; } return ans; } }
Put solution for problem 315
Put solution for problem 315
Java
mit
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
java
## Code Before: package leetcode; import java.util.ArrayList; import java.util.List; /** * https://leetcode.com/problems/count-of-smaller-numbers-after-self/ */ public class Problem315 { public List<Integer> countSmaller(int[] nums) { List<Integer> result = new ArrayList<>(); // TODO: return result; } public static void main(String[] args) { Problem315 prob = new Problem315(); System.out.println(prob.countSmaller(new int[]{5, 2, 6, 1})); // [2, 1, 1, 0] } } ## Instruction: Put solution for problem 315 ## Code After: package leetcode; import java.util.Arrays; import java.util.List; /** * https://leetcode.com/problems/count-of-smaller-numbers-after-self/ */ public class Problem315 { public List<Integer> countSmaller(int[] nums) { int[] tmp = nums.clone(); Arrays.sort(tmp); for (int i = 0; i < nums.length; i++) { nums[i] = Arrays.binarySearch(tmp, nums[i]) + 1; } int[] bit = new int[nums.length + 1]; Integer[] ans = new Integer[nums.length]; for (int i = nums.length - 1; i >= 0; i--) { ans[i] = query(bit, nums[i] - 1); add(bit, nums[i], 1); } return Arrays.asList(ans); } private void add(int[] bit, int i, int val) { for (; i < bit.length; i += i & -i) { bit[i] += val; } } private int query(int[] bit, int i) { int ans = 0; for (; i > 0; i -= i & -i) { ans += bit[i]; } return ans; } }
# ... existing code ... package leetcode; import java.util.Arrays; import java.util.List; /** # ... modified code ... */ public class Problem315 { public List<Integer> countSmaller(int[] nums) { int[] tmp = nums.clone(); Arrays.sort(tmp); for (int i = 0; i < nums.length; i++) { nums[i] = Arrays.binarySearch(tmp, nums[i]) + 1; } int[] bit = new int[nums.length + 1]; Integer[] ans = new Integer[nums.length]; for (int i = nums.length - 1; i >= 0; i--) { ans[i] = query(bit, nums[i] - 1); add(bit, nums[i], 1); } return Arrays.asList(ans); } private void add(int[] bit, int i, int val) { for (; i < bit.length; i += i & -i) { bit[i] += val; } } private int query(int[] bit, int i) { int ans = 0; for (; i > 0; i -= i & -i) { ans += bit[i]; } return ans; } } # ... rest of the code ...
8b3780d502712fa55a0881ea53d5d3d394a31e7c
java/upparse/corpus/UnlabeledBracket.java
java/upparse/corpus/UnlabeledBracket.java
package upparse.corpus; /** * Data structure representing a bracket, not including a category label * @author [email protected] (Elias Ponvert) */ public class UnlabeledBracket implements Comparable<UnlabeledBracket> { private final int first, last; public UnlabeledBracket(final int _first, final int _last) { first = _first; last = _last; } @Override public boolean equals(Object obj) { final UnlabeledBracket b = (UnlabeledBracket) obj; return first == b.first && last == b.last; } @Override public int hashCode() { return 37 * first + last; } public int getFirst() { return first; } public int getLast() { return last; } public int len() { return last - first; } @Override public int compareTo(UnlabeledBracket o) { if (o == null) throw new NullPointerException(); else if (last < o.first) return -1; else if (o.last < first) return 1; else if (o.first <= first && last <= o.last) return -1; else return 0; } public boolean contains(UnlabeledBracket b) { return first <= b.first && b.last <= last; } @Override public String toString() { return String.format("[%d,%d]", first, last); } }
package upparse.corpus; /** * Data structure representing a bracket, not including a category label * @author [email protected] (Elias Ponvert) */ public class UnlabeledBracket implements Comparable<UnlabeledBracket> { private final int first, last; public UnlabeledBracket(final int _first, final int _last) { first = _first; last = _last; } @Override public boolean equals(Object obj) { final UnlabeledBracket b = (UnlabeledBracket) obj; return first == b.first && last == b.last; } @Override public int hashCode() { return 37 * first + last; } public int getFirst() { return first; } public int getLast() { return last; } public int len() { return last - first; } @Override public int compareTo(UnlabeledBracket o) { if (o == null) throw new NullPointerException(); else if (last < o.first) return -1; else if (o.last < first) return 1; else if (o.first == first && last == o.last) return 0; else if (o.first <= first && last <= o.last) return -1; else if (first <= o.first && o.last <= last) return 1; else return 0; } public boolean contains(UnlabeledBracket b) { return first <= b.first && b.last <= last; } @Override public String toString() { return String.format("[%d,%d]", first, last); } }
Fix to bracket ordering in tree representation
Fix to bracket ordering in tree representation
Java
apache-2.0
eponvert/upparse,eponvert/upparse,eponvert/upparse
java
## Code Before: package upparse.corpus; /** * Data structure representing a bracket, not including a category label * @author [email protected] (Elias Ponvert) */ public class UnlabeledBracket implements Comparable<UnlabeledBracket> { private final int first, last; public UnlabeledBracket(final int _first, final int _last) { first = _first; last = _last; } @Override public boolean equals(Object obj) { final UnlabeledBracket b = (UnlabeledBracket) obj; return first == b.first && last == b.last; } @Override public int hashCode() { return 37 * first + last; } public int getFirst() { return first; } public int getLast() { return last; } public int len() { return last - first; } @Override public int compareTo(UnlabeledBracket o) { if (o == null) throw new NullPointerException(); else if (last < o.first) return -1; else if (o.last < first) return 1; else if (o.first <= first && last <= o.last) return -1; else return 0; } public boolean contains(UnlabeledBracket b) { return first <= b.first && b.last <= last; } @Override public String toString() { return String.format("[%d,%d]", first, last); } } ## Instruction: Fix to bracket ordering in tree representation ## Code After: package upparse.corpus; /** * Data structure representing a bracket, not including a category label * @author [email protected] (Elias Ponvert) */ public class UnlabeledBracket implements Comparable<UnlabeledBracket> { private final int first, last; public UnlabeledBracket(final int _first, final int _last) { first = _first; last = _last; } @Override public boolean equals(Object obj) { final UnlabeledBracket b = (UnlabeledBracket) obj; return first == b.first && last == b.last; } @Override public int hashCode() { return 37 * first + last; } public int getFirst() { return first; } public int getLast() { return last; } public int len() { return last - first; } @Override public int compareTo(UnlabeledBracket o) { if (o == null) throw new NullPointerException(); else if (last < o.first) return -1; else if (o.last < first) return 1; else if (o.first == first && last == o.last) return 0; else if (o.first <= first && last <= o.last) return -1; else if (first <= o.first && o.last <= last) return 1; else return 0; } public boolean contains(UnlabeledBracket b) { return first <= b.first && b.last <= last; } @Override public String toString() { return String.format("[%d,%d]", first, last); } }
... if (o == null) throw new NullPointerException(); else if (last < o.first) return -1; else if (o.last < first) return 1; else if (o.first == first && last == o.last) return 0; else if (o.first <= first && last <= o.last) return -1; else if (first <= o.first && o.last <= last) return 1; else return 0; } ...
9c1728416cf6773e510fc8c8843055189e1b03a4
public/java/test/org/broadinstitute/sting/gatk/walkers/CNV/SymbolicAllelesIntegrationTest.java
public/java/test/org/broadinstitute/sting/gatk/walkers/CNV/SymbolicAllelesIntegrationTest.java
package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("3008d6f5044bc14801e5c58d985dec72")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } }
package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("6645babc8c7d46be0da223477c7b1291")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } }
Revert "Updating md5 for fixed file" because this was fixed properly in unstable (but will break SnpEff if put into Stable).
Revert "Updating md5 for fixed file" because this was fixed properly in unstable (but will break SnpEff if put into Stable). This reverts commit 6b4182c6ab3e214da4c73bc6f3687ac6d1c0b72c.
Java
mit
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
java
## Code Before: package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("3008d6f5044bc14801e5c58d985dec72")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } } ## Instruction: Revert "Updating md5 for fixed file" because this was fixed properly in unstable (but will break SnpEff if put into Stable). This reverts commit 6b4182c6ab3e214da4c73bc6f3687ac6d1c0b72c. ## Code After: package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("6645babc8c7d46be0da223477c7b1291")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } }
// ... existing code ... WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("6645babc8c7d46be0da223477c7b1291")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } } // ... rest of the code ...
9089cca24db36608825598e1cd32451a8e20bb2f
src/libaacs/aacs.h
src/libaacs/aacs.h
/* * libaacs by Doom9 ppl 2009, 2010 */ #ifndef AACS_H_ #define AACS_H_ #include <stdint.h> #include "../file/configfile.h" #define LIBAACS_VERSION "1.0" typedef struct aacs AACS; struct aacs { uint8_t pk[16], mk[16], vuk[16], vid[16]; uint8_t *uks; /* unit key array (size = 16 * num_uks, each key is * at 16-byte offset) */ uint16_t num_uks; /* number of unit keys */ uint8_t iv[16]; CONFIGFILE *kf; }; AACS *aacs_open(const char *path, const char *keyfile_path); void aacs_close(AACS *aacs); int aacs_decrypt_unit(AACS *aacs, uint8_t *buf, uint32_t len, uint64_t offset); uint8_t *aacs_get_vid(AACS *aacs); #endif /* AACS_H_ */
/* * libaacs by Doom9 ppl 2009, 2010 */ #ifndef AACS_H_ #define AACS_H_ #include "../file/configfile.h" #include <stdint.h> #define LIBAACS_VERSION "1.0" typedef struct aacs AACS; struct aacs { uint8_t pk[16], mk[16], vuk[16], vid[16]; uint8_t *uks; /* unit key array (size = 16 * num_uks, each key is * at 16-byte offset) */ uint16_t num_uks; /* number of unit keys */ uint8_t iv[16]; CONFIGFILE *kf; }; AACS *aacs_open(const char *path, const char *keyfile_path); void aacs_close(AACS *aacs); int aacs_decrypt_unit(AACS *aacs, uint8_t *buf, uint32_t len, uint64_t offset); uint8_t *aacs_get_vid(AACS *aacs); #endif /* AACS_H_ */
Move inclusion of internal headers before system headers
Move inclusion of internal headers before system headers
C
lgpl-2.1
rraptorr/libaacs,zxlooong/libaacs,zxlooong/libaacs,ShiftMediaProject/libaacs,mwgoldsmith/aacs,rraptorr/libaacs,ShiftMediaProject/libaacs,mwgoldsmith/aacs
c
## Code Before: /* * libaacs by Doom9 ppl 2009, 2010 */ #ifndef AACS_H_ #define AACS_H_ #include <stdint.h> #include "../file/configfile.h" #define LIBAACS_VERSION "1.0" typedef struct aacs AACS; struct aacs { uint8_t pk[16], mk[16], vuk[16], vid[16]; uint8_t *uks; /* unit key array (size = 16 * num_uks, each key is * at 16-byte offset) */ uint16_t num_uks; /* number of unit keys */ uint8_t iv[16]; CONFIGFILE *kf; }; AACS *aacs_open(const char *path, const char *keyfile_path); void aacs_close(AACS *aacs); int aacs_decrypt_unit(AACS *aacs, uint8_t *buf, uint32_t len, uint64_t offset); uint8_t *aacs_get_vid(AACS *aacs); #endif /* AACS_H_ */ ## Instruction: Move inclusion of internal headers before system headers ## Code After: /* * libaacs by Doom9 ppl 2009, 2010 */ #ifndef AACS_H_ #define AACS_H_ #include "../file/configfile.h" #include <stdint.h> #define LIBAACS_VERSION "1.0" typedef struct aacs AACS; struct aacs { uint8_t pk[16], mk[16], vuk[16], vid[16]; uint8_t *uks; /* unit key array (size = 16 * num_uks, each key is * at 16-byte offset) */ uint16_t num_uks; /* number of unit keys */ uint8_t iv[16]; CONFIGFILE *kf; }; AACS *aacs_open(const char *path, const char *keyfile_path); void aacs_close(AACS *aacs); int aacs_decrypt_unit(AACS *aacs, uint8_t *buf, uint32_t len, uint64_t offset); uint8_t *aacs_get_vid(AACS *aacs); #endif /* AACS_H_ */
// ... existing code ... #ifndef AACS_H_ #define AACS_H_ #include "../file/configfile.h" #include <stdint.h> #define LIBAACS_VERSION "1.0" // ... rest of the code ...
ea7200bc9774f69562b37f177ad18ca606998dfa
perfrunner/utils/debug.py
perfrunner/utils/debug.py
import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if __name__ == '__main__': main()
import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main()
Archive logs from the tools
Archive logs from the tools Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864 Reviewed-on: http://review.couchbase.org/76571 Tested-by: Build Bot <[email protected]> Reviewed-by: Pavel Paulau <[email protected]>
Python
apache-2.0
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner
python
## Code Before: import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if __name__ == '__main__': main() ## Instruction: Archive logs from the tools Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864 Reviewed-on: http://review.couchbase.org/76571 Tested-by: Build Bot <[email protected]> Reviewed-by: Pavel Paulau <[email protected]> ## Code After: import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main()
# ... existing code ... import glob import os.path import shutil from optparse import OptionParser # ... modified code ... for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main() # ... rest of the code ...
72e5b32a0306ad608b32eaaa4817b0e5b5ef3c8d
project/asylum/utils.py
project/asylum/utils.py
import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret
import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
Add helper for iterating over months and move date proxy here
Add helper for iterating over months and move date proxy here the proxy is now needed by two commands
Python
mit
rambo/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,rambo/asylum,hacklab-fi/asylum,hacklab-fi/asylum,jautero/asylum,rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
python
## Code Before: import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret ## Instruction: Add helper for iterating over months and move date proxy here the proxy is now needed by two commands ## Code After: import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
# ... existing code ... import calendar import datetime import importlib import random # ... modified code ... random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat() # ... rest of the code ...
84e33048fa548c4d740266b5438440e3d6c0610c
core/src/com/pqbyte/coherence/CollisionListener.java
core/src/com/pqbyte/coherence/CollisionListener.java
package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && actorB instanceof Map) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && actorA instanceof Map) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }
package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && (actorB instanceof Map || actorB instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && (actorA instanceof Map || actorA instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }
Add collision detection for Obstacle
Add collision detection for Obstacle
Java
apache-2.0
pqbyte/coherence
java
## Code Before: package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && actorB instanceof Map) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && actorA instanceof Map) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } } ## Instruction: Add collision detection for Obstacle ## Code After: package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && (actorB instanceof Map || actorB instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && (actorA instanceof Map || actorA instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }
// ... existing code ... Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && (actorB instanceof Map || actorB instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && (actorA instanceof Map || actorA instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorB); } } // ... rest of the code ...
720102873c40b56b03acabc5a4a161d8df9029bb
src/main/java/org/ndexbio/model/object/network/Namespace.java
src/main/java/org/ndexbio/model/object/network/Namespace.java
package org.ndexbio.model.object.network; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Namespace extends NetworkElement { private String _prefix; private String _uri; /************************************************************************** * Default constructor. **************************************************************************/ public Namespace() { super(); _type = this.getClass().getSimpleName(); } public String getPrefix() { return _prefix; } public void setPrefix(String prefix) //throws Exception { // if ( prefix == null ) throw new Exception("Prefix for Namespace can't be null."); _prefix = prefix; } public String getUri() { return _uri; } public void setUri(String uri) { _uri = uri; } }
package org.ndexbio.model.object.network; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Namespace extends PropertiedNetworkElement { private String _prefix; private String _uri; /************************************************************************** * Default constructor. **************************************************************************/ public Namespace() { super(); _type = this.getClass().getSimpleName(); } public String getPrefix() { return _prefix; } public void setPrefix(String prefix) //throws Exception { // if ( prefix == null ) throw new Exception("Prefix for Namespace can't be null."); _prefix = prefix; } public String getUri() { return _uri; } public void setUri(String uri) { _uri = uri; } }
Extend namespace class from PropertiedNetworkElement.
Extend namespace class from PropertiedNetworkElement.
Java
bsd-3-clause
ndexbio/ndex-object-model
java
## Code Before: package org.ndexbio.model.object.network; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Namespace extends NetworkElement { private String _prefix; private String _uri; /************************************************************************** * Default constructor. **************************************************************************/ public Namespace() { super(); _type = this.getClass().getSimpleName(); } public String getPrefix() { return _prefix; } public void setPrefix(String prefix) //throws Exception { // if ( prefix == null ) throw new Exception("Prefix for Namespace can't be null."); _prefix = prefix; } public String getUri() { return _uri; } public void setUri(String uri) { _uri = uri; } } ## Instruction: Extend namespace class from PropertiedNetworkElement. ## Code After: package org.ndexbio.model.object.network; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Namespace extends PropertiedNetworkElement { private String _prefix; private String _uri; /************************************************************************** * Default constructor. **************************************************************************/ public Namespace() { super(); _type = this.getClass().getSimpleName(); } public String getPrefix() { return _prefix; } public void setPrefix(String prefix) //throws Exception { // if ( prefix == null ) throw new Exception("Prefix for Namespace can't be null."); _prefix = prefix; } public String getUri() { return _uri; } public void setUri(String uri) { _uri = uri; } }
# ... existing code ... import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Namespace extends PropertiedNetworkElement { private String _prefix; private String _uri; # ... rest of the code ...
6fe06b2a2b504c28bc35ef2f429d72dc8082efca
cmsplugin_zinnia/placeholder.py
cmsplugin_zinnia/placeholder.py
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) class Meta(EntryAbstractClass.Meta): """EntryPlaceholder's Meta""" abstract = True
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) class Meta(AbstractEntry.Meta): """EntryPlaceholder's Meta""" abstract = True
Use AbstractEntry instead of EntryAbstractClass
Use AbstractEntry instead of EntryAbstractClass
Python
bsd-3-clause
bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia
python
## Code Before: """Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) class Meta(EntryAbstractClass.Meta): """EntryPlaceholder's Meta""" abstract = True ## Instruction: Use AbstractEntry instead of EntryAbstractClass ## Code After: """Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) class Meta(AbstractEntry.Meta): """EntryPlaceholder's Meta""" abstract = True
... from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') ... context = self.acquire_context() return render_placeholder(self.content_placeholder, context) class Meta(AbstractEntry.Meta): """EntryPlaceholder's Meta""" abstract = True ...
4e3351486b88a8cec60279ff3182565921caec0d
website_portal_v10/__openerp__.py
website_portal_v10/__openerp__.py
{ 'name': 'Website Portal', 'category': 'Website', 'summary': 'Account Management Frontend for your Customers', 'version': '1.0', 'description': """ Allows your customers to manage their account from a beautiful web interface. """, 'website': 'https://www.odoo.com/', 'depends': [ 'website', ], 'data': [ 'views/templates.xml', ], 'installable': True, }
{ 'name': 'Website Portal', 'category': 'Website', 'summary': 'Account Management Frontend for your Customers', 'version': '1.0', 'description': """ Allows your customers to manage their account from a beautiful web interface. """, 'depends': [ 'website', ], 'data': [ 'views/templates.xml', ], 'installable': True, }
Remove 'author' and 'website' on odoo modules' manisfest
[IMP] Remove 'author' and 'website' on odoo modules' manisfest And use the default values : - author : 'Odoo S.A.' - website: https://www.odoo.com/
Python
agpl-3.0
Tecnativa/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,JayVora-SerpentCS/website,JayVora-SerpentCS/website,nicolas-petit/website,RoelAdriaans-B-informed/website,khaeusler/website,khaeusler/website,Tecnativa/website,RoelAdriaans-B-informed/website,nicolas-petit/website,khaeusler/website,nicolas-petit/website,Tecnativa/website,RoelAdriaans-B-informed/website
python
## Code Before: { 'name': 'Website Portal', 'category': 'Website', 'summary': 'Account Management Frontend for your Customers', 'version': '1.0', 'description': """ Allows your customers to manage their account from a beautiful web interface. """, 'website': 'https://www.odoo.com/', 'depends': [ 'website', ], 'data': [ 'views/templates.xml', ], 'installable': True, } ## Instruction: [IMP] Remove 'author' and 'website' on odoo modules' manisfest And use the default values : - author : 'Odoo S.A.' - website: https://www.odoo.com/ ## Code After: { 'name': 'Website Portal', 'category': 'Website', 'summary': 'Account Management Frontend for your Customers', 'version': '1.0', 'description': """ Allows your customers to manage their account from a beautiful web interface. """, 'depends': [ 'website', ], 'data': [ 'views/templates.xml', ], 'installable': True, }
// ... existing code ... 'description': """ Allows your customers to manage their account from a beautiful web interface. """, 'depends': [ 'website', ], // ... rest of the code ...
39256f49c952dbd5802d5321c8a74b2c41934e38
timedelta/__init__.py
timedelta/__init__.py
import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) except ImportError: pass
import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: import django from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) except (ImportError, django.core.exceptions.ImproperlyConfigured): pass
Fix running on unconfigured virtualenv.
Fix running on unconfigured virtualenv.
Python
bsd-3-clause
sookasa/django-timedelta-field
python
## Code Before: import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) except ImportError: pass ## Instruction: Fix running on unconfigured virtualenv. ## Code After: import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: import django from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) except (ImportError, django.core.exceptions.ImproperlyConfigured): pass
// ... existing code ... __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: import django from fields import TimedeltaField from helpers import ( divide, multiply, modulo, // ... modified code ... percentage, decimal_percentage, total_seconds ) except (ImportError, django.core.exceptions.ImproperlyConfigured): pass // ... rest of the code ...
75d710dfd28c91608377587a8cf358e241d394b5
SingularityExecutor/src/main/java/com/hubspot/singularity/executor/shells/SingularityExecutorShellCommandDescriptor.java
SingularityExecutor/src/main/java/com/hubspot/singularity/executor/shells/SingularityExecutorShellCommandDescriptor.java
package com.hubspot.singularity.executor.shells; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SingularityExecutorShellCommandDescriptor { @JsonProperty @NotNull private String name; @JsonProperty @NotNull // Options are : {PID} private List<String> command; @JsonProperty @NotNull private List<SingularityExecutorShellCommandOptionDescriptor> options = Collections.emptyList(); @JsonProperty private boolean skipCommandPrefix = false; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; } public void setOptions(List<SingularityExecutorShellCommandOptionDescriptor> options) { this.options = options; } public void setName(String name) { this.name = name; } public void setCommand(List<String> command) { this.command = command; } public String getName() { return name; } public List<String> getCommand() { return command; } public boolean isSkipCommandPrefix() { return skipCommandPrefix; } public void setSkipCommandPrefix(boolean skipCommandPrefix) { this.skipCommandPrefix = skipCommandPrefix; } }
package com.hubspot.singularity.executor.shells; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SingularityExecutorShellCommandDescriptor { @JsonProperty @NotNull private String name; @JsonProperty @NotNull // Options are : {PID} private List<String> command; @JsonProperty @NotNull private List<SingularityExecutorShellCommandOptionDescriptor> options = Collections.emptyList(); @JsonProperty private boolean skipCommandPrefix = false; @JsonProperty private boolean skipCommandPrefixDockerOnly = false; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; } public void setOptions(List<SingularityExecutorShellCommandOptionDescriptor> options) { this.options = options; } public void setName(String name) { this.name = name; } public void setCommand(List<String> command) { this.command = command; } public String getName() { return name; } public List<String> getCommand() { return command; } public boolean isSkipCommandPrefix() { return skipCommandPrefix; } public void setSkipCommandPrefix(boolean skipCommandPrefix) { this.skipCommandPrefix = skipCommandPrefix; } public boolean isSkipCommandPrefixDockerOnly() { return skipCommandPrefixDockerOnly; } public void setSkipCommandPrefixDockerOnly(boolean skipCommandPrefixDockerOnly) { this.skipCommandPrefixDockerOnly = skipCommandPrefixDockerOnly; } }
Add config for skipping the shell command prefix for Docker tasks only.
Add config for skipping the shell command prefix for Docker tasks only.
Java
apache-2.0
hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity
java
## Code Before: package com.hubspot.singularity.executor.shells; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SingularityExecutorShellCommandDescriptor { @JsonProperty @NotNull private String name; @JsonProperty @NotNull // Options are : {PID} private List<String> command; @JsonProperty @NotNull private List<SingularityExecutorShellCommandOptionDescriptor> options = Collections.emptyList(); @JsonProperty private boolean skipCommandPrefix = false; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; } public void setOptions(List<SingularityExecutorShellCommandOptionDescriptor> options) { this.options = options; } public void setName(String name) { this.name = name; } public void setCommand(List<String> command) { this.command = command; } public String getName() { return name; } public List<String> getCommand() { return command; } public boolean isSkipCommandPrefix() { return skipCommandPrefix; } public void setSkipCommandPrefix(boolean skipCommandPrefix) { this.skipCommandPrefix = skipCommandPrefix; } } ## Instruction: Add config for skipping the shell command prefix for Docker tasks only. ## Code After: package com.hubspot.singularity.executor.shells; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SingularityExecutorShellCommandDescriptor { @JsonProperty @NotNull private String name; @JsonProperty @NotNull // Options are : {PID} private List<String> command; @JsonProperty @NotNull private List<SingularityExecutorShellCommandOptionDescriptor> options = Collections.emptyList(); @JsonProperty private boolean skipCommandPrefix = false; @JsonProperty private boolean skipCommandPrefixDockerOnly = false; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; } public void setOptions(List<SingularityExecutorShellCommandOptionDescriptor> options) { this.options = options; } public void setName(String name) { this.name = name; } public void setCommand(List<String> command) { this.command = command; } public String getName() { return name; } public List<String> getCommand() { return command; } public boolean isSkipCommandPrefix() { return skipCommandPrefix; } public void setSkipCommandPrefix(boolean skipCommandPrefix) { this.skipCommandPrefix = skipCommandPrefix; } public boolean isSkipCommandPrefixDockerOnly() { return skipCommandPrefixDockerOnly; } public void setSkipCommandPrefixDockerOnly(boolean skipCommandPrefixDockerOnly) { this.skipCommandPrefixDockerOnly = skipCommandPrefixDockerOnly; } }
... @JsonProperty private boolean skipCommandPrefix = false; @JsonProperty private boolean skipCommandPrefixDockerOnly = false; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; ... public void setSkipCommandPrefix(boolean skipCommandPrefix) { this.skipCommandPrefix = skipCommandPrefix; } public boolean isSkipCommandPrefixDockerOnly() { return skipCommandPrefixDockerOnly; } public void setSkipCommandPrefixDockerOnly(boolean skipCommandPrefixDockerOnly) { this.skipCommandPrefixDockerOnly = skipCommandPrefixDockerOnly; } } ...