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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
e21ca71d5bf19ec0feaab9dbf8caf25173152aec
|
projects/models.py
|
projects/models.py
|
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Разгледан и неодобрен на СИС'))
user = models.ForeignKey('members.User')
name = models.CharField(max_length=100)
flp = models.ForeignKey('members.User', related_name='flp')
team = models.ManyToManyField('members.User', related_name='team')
description = models.TextField()
targets = models.TextField()
tasks = models.TextField()
target_group = models.TextField()
schedule = models.TextField()
resources = models.TextField()
finance_description = models.TextField()
partners = models.TextField(blank=True, null=True)
files = models.ManyToManyField('attachments.Attachment')
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
date = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
|
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Разгледан и неодобрен на СИС'))
user = models.ForeignKey('members.User')
name = models.CharField(max_length=100)
flp = models.ForeignKey('members.User', related_name='flp')
team = models.ManyToManyField('members.User', related_name='team')
description = models.TextField()
targets = models.TextField()
tasks = models.TextField()
target_group = models.TextField()
schedule = models.TextField()
resources = models.TextField()
finance_description = models.TextField()
partners = models.TextField(blank=True, null=True)
files = models.ManyToManyField('attachments.Attachment')
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
discussed_at = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
|
Rename the date field related to the project status
|
Rename the date field related to the project status
|
Python
|
mit
|
Hackfmi/Diaphanum,Hackfmi/Diaphanum
|
python
|
## Code Before:
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Разгледан и неодобрен на СИС'))
user = models.ForeignKey('members.User')
name = models.CharField(max_length=100)
flp = models.ForeignKey('members.User', related_name='flp')
team = models.ManyToManyField('members.User', related_name='team')
description = models.TextField()
targets = models.TextField()
tasks = models.TextField()
target_group = models.TextField()
schedule = models.TextField()
resources = models.TextField()
finance_description = models.TextField()
partners = models.TextField(blank=True, null=True)
files = models.ManyToManyField('attachments.Attachment')
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
date = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
## Instruction:
Rename the date field related to the project status
## Code After:
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Разгледан и неодобрен на СИС'))
user = models.ForeignKey('members.User')
name = models.CharField(max_length=100)
flp = models.ForeignKey('members.User', related_name='flp')
team = models.ManyToManyField('members.User', related_name='team')
description = models.TextField()
targets = models.TextField()
tasks = models.TextField()
target_group = models.TextField()
schedule = models.TextField()
resources = models.TextField()
finance_description = models.TextField()
partners = models.TextField(blank=True, null=True)
files = models.ManyToManyField('attachments.Attachment')
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
discussed_at = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
|
...
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
discussed_at = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
...
|
cc754aeb16aa41f936d59a3b5746a3bec69489ef
|
sts/util/convenience.py
|
sts/util/convenience.py
|
import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
|
import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
|
Add little functions for checking if a list is sorted without sorting it
|
Add little functions for checking if a list is sorted without sorting it
|
Python
|
apache-2.0
|
ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts
|
python
|
## Code Before:
import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
## Instruction:
Add little functions for checking if a list is sorted without sorting it
## Code After:
import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
|
# ... existing code ...
import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
# ... rest of the code ...
|
6c1897af9f323a22cf53a195a12168e42985c62e
|
smallrl.c
|
smallrl.c
|
static void shutdown(void);
int main(int argc, char ** argv)
{
srand(time(NULL));
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
start_color();
init_pair(color_black, COLOR_BLACK, COLOR_BLACK);
init_pair(color_yellow, COLOR_YELLOW, COLOR_BLACK);
init_pair(color_blue, COLOR_BLUE, COLOR_BLACK);
init_pair(color_red, COLOR_RED, COLOR_BLACK);
init_pair(color_green, COLOR_GREEN, COLOR_BLACK);
init_pair(color_cyan, COLOR_CYAN, COLOR_BLACK);
init_pair(color_magenta, COLOR_MAGENTA, COLOR_BLACK);
if (LINES < 24 || COLS < 80)
{
shutdown();
printf("Terminal too small.");
exit(1);
}
do
{
erase();
new_game();
}
while (play());
shutdown();
return 0;
}
static void shutdown(void)
{
endwin();
return;
}
|
static void shutdown(void);
int main(int argc, char ** argv)
{
time_t random_seed = time(NULL);
printf("Random game #%ld\n", random_seed);
srand(random_seed);
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
start_color();
init_pair(color_black, COLOR_BLACK, COLOR_BLACK);
init_pair(color_yellow, COLOR_YELLOW, COLOR_BLACK);
init_pair(color_blue, COLOR_BLUE, COLOR_BLACK);
init_pair(color_red, COLOR_RED, COLOR_BLACK);
init_pair(color_green, COLOR_GREEN, COLOR_BLACK);
init_pair(color_cyan, COLOR_CYAN, COLOR_BLACK);
init_pair(color_magenta, COLOR_MAGENTA, COLOR_BLACK);
if (LINES < 24 || COLS < 80)
{
shutdown();
printf("Terminal too small.");
exit(1);
}
do
{
erase();
new_game();
}
while (play());
shutdown();
return 0;
}
static void shutdown(void)
{
endwin();
return;
}
|
Print random seed for sharing / debugging purposes
|
Print random seed for sharing / debugging purposes
|
C
|
bsd-2-clause
|
happyponyland/smallrl,happyponyland/smallrl,happyponyland/smallrl
|
c
|
## Code Before:
static void shutdown(void);
int main(int argc, char ** argv)
{
srand(time(NULL));
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
start_color();
init_pair(color_black, COLOR_BLACK, COLOR_BLACK);
init_pair(color_yellow, COLOR_YELLOW, COLOR_BLACK);
init_pair(color_blue, COLOR_BLUE, COLOR_BLACK);
init_pair(color_red, COLOR_RED, COLOR_BLACK);
init_pair(color_green, COLOR_GREEN, COLOR_BLACK);
init_pair(color_cyan, COLOR_CYAN, COLOR_BLACK);
init_pair(color_magenta, COLOR_MAGENTA, COLOR_BLACK);
if (LINES < 24 || COLS < 80)
{
shutdown();
printf("Terminal too small.");
exit(1);
}
do
{
erase();
new_game();
}
while (play());
shutdown();
return 0;
}
static void shutdown(void)
{
endwin();
return;
}
## Instruction:
Print random seed for sharing / debugging purposes
## Code After:
static void shutdown(void);
int main(int argc, char ** argv)
{
time_t random_seed = time(NULL);
printf("Random game #%ld\n", random_seed);
srand(random_seed);
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
start_color();
init_pair(color_black, COLOR_BLACK, COLOR_BLACK);
init_pair(color_yellow, COLOR_YELLOW, COLOR_BLACK);
init_pair(color_blue, COLOR_BLUE, COLOR_BLACK);
init_pair(color_red, COLOR_RED, COLOR_BLACK);
init_pair(color_green, COLOR_GREEN, COLOR_BLACK);
init_pair(color_cyan, COLOR_CYAN, COLOR_BLACK);
init_pair(color_magenta, COLOR_MAGENTA, COLOR_BLACK);
if (LINES < 24 || COLS < 80)
{
shutdown();
printf("Terminal too small.");
exit(1);
}
do
{
erase();
new_game();
}
while (play());
shutdown();
return 0;
}
static void shutdown(void)
{
endwin();
return;
}
|
# ... existing code ...
int main(int argc, char ** argv)
{
time_t random_seed = time(NULL);
printf("Random game #%ld\n", random_seed);
srand(random_seed);
initscr();
cbreak();
# ... rest of the code ...
|
aa8e8087a9b8de316b6f867c8073b9df6ecb471e
|
src/main/java/com/boundary/camel/component/ssh/SshxResult.java
|
src/main/java/com/boundary/camel/component/ssh/SshxResult.java
|
package com.boundary.camel.component.ssh;
import com.boundary.camel.component.common.ServiceInfo;
/**
*
* @author davidg
*
*/
public class SshxInfo extends ServiceInfo {
private String command;
private String expectedOutput;
public SshxInfo() {
// TODO Auto-generated constructor stub
}
public String getCommand() {
return command;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setCommand(String command) {
this.command = command;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
@Override
public String toString() {
return "SsshxInfo [expectedOutput=" + expectedOutput + "]";
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.boundary.camel.component.ssh;
import java.io.InputStream;
import com.boundary.camel.component.common.ServiceInfo;
public class SshxResult extends ServiceInfo {
/**
* The value of this header is a {@link InputStream} with the standard error
* stream of the executable.
*/
public static final String STDERR = "CamelSshStderr";
/**
* The value of this header is the exit value that is returned, after the
* execution. By convention a non-zero status exit value indicates abnormal
* termination. <br>
* <b>Note that the exit value is OS dependent.</b>
*/
public static final String EXIT_VALUE = "CamelSshExitValue";
private final String command;
private final int exitValue;
private final InputStream stdout;
private final InputStream stderr;
public SshxResult(String command, int exitValue, InputStream out, InputStream err) {
this.command = command;
this.exitValue = exitValue;
this.stdout = out;
this.stderr = err;
}
public String getCommand() {
return command;
}
public int getExitValue() {
return exitValue;
}
public InputStream getStdout() {
return stdout;
}
public InputStream getStderr() {
return stderr;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("exitValue=" + exitValue);
sb.append("command=" + command);
return sb.toString();
}
}
|
Use code from Camel distribution for results
|
Use code from Camel distribution for results
|
Java
|
apache-2.0
|
jdgwartney/camel-checkport,boundary/boundary-camel-components
|
java
|
## Code Before:
package com.boundary.camel.component.ssh;
import com.boundary.camel.component.common.ServiceInfo;
/**
*
* @author davidg
*
*/
public class SshxInfo extends ServiceInfo {
private String command;
private String expectedOutput;
public SshxInfo() {
// TODO Auto-generated constructor stub
}
public String getCommand() {
return command;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setCommand(String command) {
this.command = command;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
@Override
public String toString() {
return "SsshxInfo [expectedOutput=" + expectedOutput + "]";
}
}
## Instruction:
Use code from Camel distribution for results
## Code After:
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.boundary.camel.component.ssh;
import java.io.InputStream;
import com.boundary.camel.component.common.ServiceInfo;
public class SshxResult extends ServiceInfo {
/**
* The value of this header is a {@link InputStream} with the standard error
* stream of the executable.
*/
public static final String STDERR = "CamelSshStderr";
/**
* The value of this header is the exit value that is returned, after the
* execution. By convention a non-zero status exit value indicates abnormal
* termination. <br>
* <b>Note that the exit value is OS dependent.</b>
*/
public static final String EXIT_VALUE = "CamelSshExitValue";
private final String command;
private final int exitValue;
private final InputStream stdout;
private final InputStream stderr;
public SshxResult(String command, int exitValue, InputStream out, InputStream err) {
this.command = command;
this.exitValue = exitValue;
this.stdout = out;
this.stderr = err;
}
public String getCommand() {
return command;
}
public int getExitValue() {
return exitValue;
}
public InputStream getStdout() {
return stdout;
}
public InputStream getStderr() {
return stderr;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("exitValue=" + exitValue);
sb.append("command=" + command);
return sb.toString();
}
}
|
# ... existing code ...
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.boundary.camel.component.ssh;
import java.io.InputStream;
import com.boundary.camel.component.common.ServiceInfo;
public class SshxResult extends ServiceInfo {
/**
* The value of this header is a {@link InputStream} with the standard error
* stream of the executable.
*/
public static final String STDERR = "CamelSshStderr";
/**
* The value of this header is the exit value that is returned, after the
* execution. By convention a non-zero status exit value indicates abnormal
* termination. <br>
* <b>Note that the exit value is OS dependent.</b>
*/
public static final String EXIT_VALUE = "CamelSshExitValue";
private final String command;
private final int exitValue;
private final InputStream stdout;
private final InputStream stderr;
public SshxResult(String command, int exitValue, InputStream out, InputStream err) {
this.command = command;
this.exitValue = exitValue;
this.stdout = out;
this.stderr = err;
}
public String getCommand() {
return command;
}
public int getExitValue() {
return exitValue;
}
public InputStream getStdout() {
return stdout;
}
public InputStream getStderr() {
return stderr;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("exitValue=" + exitValue);
sb.append("command=" + command);
return sb.toString();
}
}
# ... rest of the code ...
|
7fb89e4dbe2cbed4ef37e13073d4fa3f2a650049
|
InvenTree/part/apps.py
|
InvenTree/part/apps.py
|
from __future__ import unicode_literals
from django.apps import AppConfig
class PartConfig(AppConfig):
name = 'part'
|
from __future__ import unicode_literals
import os
from django.db.utils import OperationalError, ProgrammingError
from django.apps import AppConfig
from django.conf import settings
class PartConfig(AppConfig):
name = 'part'
def ready(self):
"""
This function is called whenever the Part app is loaded.
"""
self.generate_part_thumbnails()
def generate_part_thumbnails(self):
from .models import Part
print("Checking Part image thumbnails")
try:
for part in Part.objects.all():
if part.image:
url = part.image.thumbnail.name
#if url.startswith('/'):
# url = url[1:]
loc = os.path.join(settings.MEDIA_ROOT, url)
if not os.path.exists(loc):
print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name))
part.image.render_variations(replace=False)
except (OperationalError, ProgrammingError):
print("Could not generate Part thumbnails")
|
Check for missing part thumbnails when the server first runs
|
Check for missing part thumbnails when the server first runs
|
Python
|
mit
|
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
|
python
|
## Code Before:
from __future__ import unicode_literals
from django.apps import AppConfig
class PartConfig(AppConfig):
name = 'part'
## Instruction:
Check for missing part thumbnails when the server first runs
## Code After:
from __future__ import unicode_literals
import os
from django.db.utils import OperationalError, ProgrammingError
from django.apps import AppConfig
from django.conf import settings
class PartConfig(AppConfig):
name = 'part'
def ready(self):
"""
This function is called whenever the Part app is loaded.
"""
self.generate_part_thumbnails()
def generate_part_thumbnails(self):
from .models import Part
print("Checking Part image thumbnails")
try:
for part in Part.objects.all():
if part.image:
url = part.image.thumbnail.name
#if url.startswith('/'):
# url = url[1:]
loc = os.path.join(settings.MEDIA_ROOT, url)
if not os.path.exists(loc):
print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name))
part.image.render_variations(replace=False)
except (OperationalError, ProgrammingError):
print("Could not generate Part thumbnails")
|
...
from __future__ import unicode_literals
import os
from django.db.utils import OperationalError, ProgrammingError
from django.apps import AppConfig
from django.conf import settings
class PartConfig(AppConfig):
name = 'part'
def ready(self):
"""
This function is called whenever the Part app is loaded.
"""
self.generate_part_thumbnails()
def generate_part_thumbnails(self):
from .models import Part
print("Checking Part image thumbnails")
try:
for part in Part.objects.all():
if part.image:
url = part.image.thumbnail.name
#if url.startswith('/'):
# url = url[1:]
loc = os.path.join(settings.MEDIA_ROOT, url)
if not os.path.exists(loc):
print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name))
part.image.render_variations(replace=False)
except (OperationalError, ProgrammingError):
print("Could not generate Part thumbnails")
...
|
566fa441f3864be4f813673dbaf8ffff87d28e17
|
setup.py
|
setup.py
|
from distutils.core import setup, Extension
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'[email protected]',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': [module1]
}
if __name__ == '__main__':
setup(**kwargs)
|
from distutils.core import setup, Extension
import os
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
def get_ex_mod():
if 'NO_PY_EXT' in os.environ:
return None
return [module1]
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'[email protected]',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': get_ex_mod()
}
if __name__ == '__main__':
setup(**kwargs)
|
Add NO_PY_EXT environment variable to disable compilation of the C module, which is not working very well in cross-compile mode.
|
Add NO_PY_EXT environment variable to disable compilation of
the C module, which is not working very well in cross-compile
mode.
|
Python
|
bsd-2-clause
|
sobomax/libelperiodic,sobomax/libelperiodic,sobomax/libelperiodic,sobomax/libelperiodic
|
python
|
## Code Before:
from distutils.core import setup, Extension
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'[email protected]',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': [module1]
}
if __name__ == '__main__':
setup(**kwargs)
## Instruction:
Add NO_PY_EXT environment variable to disable compilation of
the C module, which is not working very well in cross-compile
mode.
## Code After:
from distutils.core import setup, Extension
import os
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
def get_ex_mod():
if 'NO_PY_EXT' in os.environ:
return None
return [module1]
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'[email protected]',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': get_ex_mod()
}
if __name__ == '__main__':
setup(**kwargs)
|
# ... existing code ...
from distutils.core import setup, Extension
import os
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
# ... modified code ...
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
def get_ex_mod():
if 'NO_PY_EXT' in os.environ:
return None
return [module1]
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
...
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': get_ex_mod()
}
if __name__ == '__main__':
# ... rest of the code ...
|
057d7a95031ba8c51ae10ea1b742534fcb5e82a3
|
bidb/keys/tasks.py
|
bidb/keys/tasks.py
|
import celery
import subprocess
from bidb.utils.tempfile import TemporaryDirectory
from bidb.utils.subprocess import check_output2
from .models import Key
@celery.task(soft_time_limit=60)
def update_or_create_key(uid):
with TemporaryDirectory() as homedir:
try:
check_output2((
'gpg',
'--homedir', homedir,
'--keyserver', 'http://p80.pool.sks-keyservers.net/',
'--recv-keys', uid,
))
except subprocess.CalledProcessError as exc:
print "E: {}: {}".format(exc, exc.output)
return None, False
data = check_output2((
'gpg',
'--homedir', homedir,
'--with-colons',
'--fixed-list-mode',
'--fingerprint',
uid,
))
for line in data.splitlines():
if line.startswith('uid:'):
name = line.split(':')[9]
break
else:
raise ValueError("Could not parse name from key: {}".format(data))
return Key.objects.update_or_create(uid=uid, defaults={
'name': name,
})
@celery.task()
def refresh_all():
for x in Key.objects.all():
update_or_create_key.delay(x.uid)
|
import celery
import subprocess
from bidb.utils.tempfile import TemporaryDirectory
from bidb.utils.subprocess import check_output2
from .models import Key
@celery.task(soft_time_limit=60)
def update_or_create_key(uid):
with TemporaryDirectory() as homedir:
try:
check_output2((
'gpg',
'--homedir', homedir,
'--keyserver', 'pgpkeys.mit.edu',
'--recv-keys', uid,
))
except subprocess.CalledProcessError as exc:
print "E: {}: {}".format(exc, exc.output)
return None, False
data = check_output2((
'gpg',
'--homedir', homedir,
'--with-colons',
'--fixed-list-mode',
'--fingerprint',
uid,
))
for line in data.splitlines():
if line.startswith('uid:'):
name = line.split(':')[9]
break
else:
raise ValueError("Could not parse name from key: {}".format(data))
return Key.objects.update_or_create(uid=uid, defaults={
'name': name,
})
@celery.task()
def refresh_all():
for x in Key.objects.all():
update_or_create_key.delay(x.uid)
|
Use pgpkeys.mit.edu as our keyserver; seems to work.
|
Use pgpkeys.mit.edu as our keyserver; seems to work.
|
Python
|
agpl-3.0
|
lamby/buildinfo.debian.net,lamby/buildinfo.debian.net
|
python
|
## Code Before:
import celery
import subprocess
from bidb.utils.tempfile import TemporaryDirectory
from bidb.utils.subprocess import check_output2
from .models import Key
@celery.task(soft_time_limit=60)
def update_or_create_key(uid):
with TemporaryDirectory() as homedir:
try:
check_output2((
'gpg',
'--homedir', homedir,
'--keyserver', 'http://p80.pool.sks-keyservers.net/',
'--recv-keys', uid,
))
except subprocess.CalledProcessError as exc:
print "E: {}: {}".format(exc, exc.output)
return None, False
data = check_output2((
'gpg',
'--homedir', homedir,
'--with-colons',
'--fixed-list-mode',
'--fingerprint',
uid,
))
for line in data.splitlines():
if line.startswith('uid:'):
name = line.split(':')[9]
break
else:
raise ValueError("Could not parse name from key: {}".format(data))
return Key.objects.update_or_create(uid=uid, defaults={
'name': name,
})
@celery.task()
def refresh_all():
for x in Key.objects.all():
update_or_create_key.delay(x.uid)
## Instruction:
Use pgpkeys.mit.edu as our keyserver; seems to work.
## Code After:
import celery
import subprocess
from bidb.utils.tempfile import TemporaryDirectory
from bidb.utils.subprocess import check_output2
from .models import Key
@celery.task(soft_time_limit=60)
def update_or_create_key(uid):
with TemporaryDirectory() as homedir:
try:
check_output2((
'gpg',
'--homedir', homedir,
'--keyserver', 'pgpkeys.mit.edu',
'--recv-keys', uid,
))
except subprocess.CalledProcessError as exc:
print "E: {}: {}".format(exc, exc.output)
return None, False
data = check_output2((
'gpg',
'--homedir', homedir,
'--with-colons',
'--fixed-list-mode',
'--fingerprint',
uid,
))
for line in data.splitlines():
if line.startswith('uid:'):
name = line.split(':')[9]
break
else:
raise ValueError("Could not parse name from key: {}".format(data))
return Key.objects.update_or_create(uid=uid, defaults={
'name': name,
})
@celery.task()
def refresh_all():
for x in Key.objects.all():
update_or_create_key.delay(x.uid)
|
# ... existing code ...
check_output2((
'gpg',
'--homedir', homedir,
'--keyserver', 'pgpkeys.mit.edu',
'--recv-keys', uid,
))
except subprocess.CalledProcessError as exc:
# ... rest of the code ...
|
645265be1097f463e9d12f2be1a3a4de2b136f0c
|
tests/test_pooling.py
|
tests/test_pooling.py
|
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
# TODO Thread-mapped pool tests
|
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
class ThreadMappedPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ThreadMappedPool(self.mc)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
|
Add rudimentary testing for thread-mapped pools
|
Add rudimentary testing for thread-mapped pools
Refs #174
|
Python
|
bsd-3-clause
|
lericson/pylibmc,lericson/pylibmc,lericson/pylibmc
|
python
|
## Code Before:
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
# TODO Thread-mapped pool tests
## Instruction:
Add rudimentary testing for thread-mapped pools
Refs #174
## Code After:
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
class ThreadMappedPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ThreadMappedPool(self.mc)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
|
// ... existing code ...
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
class ThreadMappedPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ThreadMappedPool(self.mc)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
// ... rest of the code ...
|
d03603a903096eebfab0972a78e5038c41c75534
|
framework/JPetUser/JPetUser.h
|
framework/JPetUser/JPetUser.h
|
// JPet User - JPetUser.h
#ifndef JPET_USER_H
#define JPET_USER_H
#include "TNamed.h"
class JPetUser: public TNamed
{
protected:
int m_id;
std::string m_name;
std::string m_lastName;
std::string m_login;
std::string m_password;
bool m_isRoot;
std::string m_creationDate;
std::string m_lastLoginDate;
static bool m_isUserLogged;
inline void toggleUserLoggedStatus()
{
m_isUserLogged = (m_isUserLogged == true) ? false : true;
}
virtual std::string password(void) const;
public:
JPetUser(int p_id, std::string p_name, std::string p_lastName, std::string p_login, std::string p_password, bool p_isRoot);
virtual ~JPetUser(void);
static bool isUserLogged(void);
virtual bool logIn(void);
virtual bool logOut(void);
virtual bool changeLogin(void);
virtual bool changePassword(void);
virtual int id(void) const;
virtual std::string name(void) const;
virtual std::string lastName(void) const;
virtual std::string login(void) const;
virtual bool isRoot(void) const;
virtual std::string creationDate(void) const;
virtual std::string lastLoginDate(void) const;
private:
ClassDef(JPetUser, 1);
};
#endif // JPET_USER_H
|
// JPet User - JPetUser.h
#ifndef JPET_USER_H
#define JPET_USER_H
#include "TNamed.h"
class JPetUser: public TNamed
{
protected:
int m_id;
std::string m_name;
std::string m_lastName;
std::string m_login;
std::string m_password;
bool m_isRoot;
std::string m_creationDate;
std::string m_lastLoginDate;
static bool m_isUserLogged;
inline void toggleUserLoggedStatus()
{
m_isUserLogged = !m_isUserLogged;
}
virtual std::string password(void) const;
public:
JPetUser(int p_id, std::string p_name, std::string p_lastName, std::string p_login, std::string p_password, bool p_isRoot);
virtual ~JPetUser(void);
static bool isUserLogged(void);
virtual bool logIn(void);
virtual bool logOut(void);
virtual bool changeLogin(void);
virtual bool changePassword(void);
virtual int id(void) const;
virtual std::string name(void) const;
virtual std::string lastName(void) const;
virtual std::string login(void) const;
virtual bool isRoot(void) const;
virtual std::string creationDate(void) const;
virtual std::string lastLoginDate(void) const;
private:
ClassDef(JPetUser, 1);
};
#endif // JPET_USER_H
|
Change body of the toggleUserLoggedStatus method.
|
Change body of the toggleUserLoggedStatus method.
|
C
|
apache-2.0
|
kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework
|
c
|
## Code Before:
// JPet User - JPetUser.h
#ifndef JPET_USER_H
#define JPET_USER_H
#include "TNamed.h"
class JPetUser: public TNamed
{
protected:
int m_id;
std::string m_name;
std::string m_lastName;
std::string m_login;
std::string m_password;
bool m_isRoot;
std::string m_creationDate;
std::string m_lastLoginDate;
static bool m_isUserLogged;
inline void toggleUserLoggedStatus()
{
m_isUserLogged = (m_isUserLogged == true) ? false : true;
}
virtual std::string password(void) const;
public:
JPetUser(int p_id, std::string p_name, std::string p_lastName, std::string p_login, std::string p_password, bool p_isRoot);
virtual ~JPetUser(void);
static bool isUserLogged(void);
virtual bool logIn(void);
virtual bool logOut(void);
virtual bool changeLogin(void);
virtual bool changePassword(void);
virtual int id(void) const;
virtual std::string name(void) const;
virtual std::string lastName(void) const;
virtual std::string login(void) const;
virtual bool isRoot(void) const;
virtual std::string creationDate(void) const;
virtual std::string lastLoginDate(void) const;
private:
ClassDef(JPetUser, 1);
};
#endif // JPET_USER_H
## Instruction:
Change body of the toggleUserLoggedStatus method.
## Code After:
// JPet User - JPetUser.h
#ifndef JPET_USER_H
#define JPET_USER_H
#include "TNamed.h"
class JPetUser: public TNamed
{
protected:
int m_id;
std::string m_name;
std::string m_lastName;
std::string m_login;
std::string m_password;
bool m_isRoot;
std::string m_creationDate;
std::string m_lastLoginDate;
static bool m_isUserLogged;
inline void toggleUserLoggedStatus()
{
m_isUserLogged = !m_isUserLogged;
}
virtual std::string password(void) const;
public:
JPetUser(int p_id, std::string p_name, std::string p_lastName, std::string p_login, std::string p_password, bool p_isRoot);
virtual ~JPetUser(void);
static bool isUserLogged(void);
virtual bool logIn(void);
virtual bool logOut(void);
virtual bool changeLogin(void);
virtual bool changePassword(void);
virtual int id(void) const;
virtual std::string name(void) const;
virtual std::string lastName(void) const;
virtual std::string login(void) const;
virtual bool isRoot(void) const;
virtual std::string creationDate(void) const;
virtual std::string lastLoginDate(void) const;
private:
ClassDef(JPetUser, 1);
};
#endif // JPET_USER_H
|
// ... existing code ...
static bool m_isUserLogged;
inline void toggleUserLoggedStatus()
{
m_isUserLogged = !m_isUserLogged;
}
virtual std::string password(void) const;
// ... rest of the code ...
|
b39bf8ba3fc3d2037a293db7d5856d02ac047a31
|
nbt/__init__.py
|
nbt/__init__.py
|
from nbt import *
VERSION = (1, 1)
def _get_version():
return ".".join(VERSION)
|
__all__ = ["chunk", "region", "nbt"]
from . import *
VERSION = (1, 1)
def _get_version():
return ".".join(VERSION)
|
Use relative import (required for Python 3, supported in 2.6 or higher)
|
Use relative import (required for Python 3, supported in 2.6 or higher)
|
Python
|
mit
|
macfreek/NBT,twoolie/NBT,fwaggle/NBT,devmario/NBT,cburschka/NBT
|
python
|
## Code Before:
from nbt import *
VERSION = (1, 1)
def _get_version():
return ".".join(VERSION)
## Instruction:
Use relative import (required for Python 3, supported in 2.6 or higher)
## Code After:
__all__ = ["chunk", "region", "nbt"]
from . import *
VERSION = (1, 1)
def _get_version():
return ".".join(VERSION)
|
...
__all__ = ["chunk", "region", "nbt"]
from . import *
VERSION = (1, 1)
...
|
db648cdab35a2a72efa23bc4c417225f09e9d511
|
stm32f1-nrf24l01-transmitter/firmware/protocol_hk310.c
|
stm32f1-nrf24l01-transmitter/firmware/protocol_hk310.c
|
// ****************************************************************************
static void protocol_frame_callback(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
// ****************************************************************************
void init_protocol_hk310(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
|
typedef enum {
SEND_STICK1 = 0,
SEND_STICK2,
SEND_BIND_INFO,
SEND_PROGRAMBOX
} frame_state_t;
static frame_state_t frame_state;
// ****************************************************************************
static void send_stick_data(void)
{
}
// ****************************************************************************
static void send_binding_data(void)
{
}
// ****************************************************************************
static void send_programming_box_data(void)
{
}
// ****************************************************************************
static void nrf_transmit_done_callback(void)
{
switch (frame_state) {
case SEND_STICK1:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_STICK2:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_BIND_INFO:
send_binding_data();
frame_state = SEND_PROGRAMBOX;
break;
case SEND_PROGRAMBOX:
send_programming_box_data();
frame_state = SEND_STICK1;
break;
default:
break;
}
}
// ****************************************************************************
static void protocol_frame_callback(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
frame_state = SEND_STICK1;
nrf_transmit_done_callback();
}
// ****************************************************************************
void init_protocol_hk310(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
|
Build skeleton for nRF frames
|
Build skeleton for nRF frames
|
C
|
unlicense
|
laneboysrc/nrf24l01-rc,laneboysrc/nrf24l01-rc,laneboysrc/nrf24l01-rc
|
c
|
## Code Before:
// ****************************************************************************
static void protocol_frame_callback(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
// ****************************************************************************
void init_protocol_hk310(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
## Instruction:
Build skeleton for nRF frames
## Code After:
typedef enum {
SEND_STICK1 = 0,
SEND_STICK2,
SEND_BIND_INFO,
SEND_PROGRAMBOX
} frame_state_t;
static frame_state_t frame_state;
// ****************************************************************************
static void send_stick_data(void)
{
}
// ****************************************************************************
static void send_binding_data(void)
{
}
// ****************************************************************************
static void send_programming_box_data(void)
{
}
// ****************************************************************************
static void nrf_transmit_done_callback(void)
{
switch (frame_state) {
case SEND_STICK1:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_STICK2:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_BIND_INFO:
send_binding_data();
frame_state = SEND_PROGRAMBOX;
break;
case SEND_PROGRAMBOX:
send_programming_box_data();
frame_state = SEND_STICK1;
break;
default:
break;
}
}
// ****************************************************************************
static void protocol_frame_callback(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
frame_state = SEND_STICK1;
nrf_transmit_done_callback();
}
// ****************************************************************************
void init_protocol_hk310(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
}
|
# ... existing code ...
typedef enum {
SEND_STICK1 = 0,
SEND_STICK2,
SEND_BIND_INFO,
SEND_PROGRAMBOX
} frame_state_t;
static frame_state_t frame_state;
// ****************************************************************************
static void send_stick_data(void)
{
}
// ****************************************************************************
static void send_binding_data(void)
{
}
// ****************************************************************************
static void send_programming_box_data(void)
{
}
// ****************************************************************************
static void nrf_transmit_done_callback(void)
{
switch (frame_state) {
case SEND_STICK1:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_STICK2:
send_stick_data();
frame_state = SEND_BIND_INFO;
break;
case SEND_BIND_INFO:
send_binding_data();
frame_state = SEND_PROGRAMBOX;
break;
case SEND_PROGRAMBOX:
send_programming_box_data();
frame_state = SEND_STICK1;
break;
default:
break;
}
}
// ****************************************************************************
# ... modified code ...
static void protocol_frame_callback(void)
{
systick_set_callback(protocol_frame_callback, FRAME_TIME);
frame_state = SEND_STICK1;
nrf_transmit_done_callback();
}
...
}
# ... rest of the code ...
|
d371c92e999aa90df39887a33901fdaa58f648f1
|
test/gui/test_messages.py
|
test/gui/test_messages.py
|
import sys
from sequana.gui import messages
from PyQt5 import QtWidgets as QW
app = QW.QApplication(sys.argv)
def test_warning():
w = messages.WarningMessage("test")
def test_critical():
w = messages.CriticalMessage("test", details="test")
|
from sequana.gui import messages
def test_warning(qtbot):
w = messages.WarningMessage("test")
def test_critical(qtbot):
w = messages.CriticalMessage("test", details="test")
|
Fix test that caused a pytest hang
|
Fix test that caused a pytest hang
|
Python
|
bsd-3-clause
|
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
|
python
|
## Code Before:
import sys
from sequana.gui import messages
from PyQt5 import QtWidgets as QW
app = QW.QApplication(sys.argv)
def test_warning():
w = messages.WarningMessage("test")
def test_critical():
w = messages.CriticalMessage("test", details="test")
## Instruction:
Fix test that caused a pytest hang
## Code After:
from sequana.gui import messages
def test_warning(qtbot):
w = messages.WarningMessage("test")
def test_critical(qtbot):
w = messages.CriticalMessage("test", details="test")
|
// ... existing code ...
from sequana.gui import messages
def test_warning(qtbot):
w = messages.WarningMessage("test")
def test_critical(qtbot):
w = messages.CriticalMessage("test", details="test")
// ... rest of the code ...
|
d7ca978c696deb13c53fc3fdc9d227d0836b97f8
|
test/data/testCC.py
|
test/data/testCC.py
|
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirname(__file__))
class GenericCCTest(unittest.TestCase):
"""Generic coupled cluster unittest"""
def testsign(self):
"""Are the coupled cluster corrections negative?"""
corrections = self.data.ccenergies - self.data.scfenergies
self.assertTrue(numpy.alltrue(corrections < 0.0))
if __name__ == "__main__":
import sys
sys.path.insert(1, os.path.join(__filedir__, ".."))
from test_data import DataSuite
suite = DataSuite(['CC'])
suite.testall()
|
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirname(__file__))
class GenericCCTest(unittest.TestCase):
"""Generic coupled cluster unittest"""
def testsizeandshape(self):
"""Are the dimensions of ccenergies correct?"""
self.assertEqual(self.data.ccenergies.shape,
(len(self.data.scfenergies),))
def testsign(self):
"""Are the coupled cluster corrections negative?"""
corrections = self.data.ccenergies - self.data.scfenergies
self.assertTrue(numpy.alltrue(corrections < 0.0))
if __name__ == "__main__":
import sys
sys.path.insert(1, os.path.join(__filedir__, ".."))
from test_data import DataSuite
suite = DataSuite(['CC'])
suite.testall()
|
Test size and shape of ccenergies
|
Test size and shape of ccenergies
|
Python
|
bsd-3-clause
|
berquist/cclib,berquist/cclib,cclib/cclib,ATenderholt/cclib,ATenderholt/cclib,langner/cclib,cclib/cclib,berquist/cclib,cclib/cclib,langner/cclib,langner/cclib
|
python
|
## Code Before:
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirname(__file__))
class GenericCCTest(unittest.TestCase):
"""Generic coupled cluster unittest"""
def testsign(self):
"""Are the coupled cluster corrections negative?"""
corrections = self.data.ccenergies - self.data.scfenergies
self.assertTrue(numpy.alltrue(corrections < 0.0))
if __name__ == "__main__":
import sys
sys.path.insert(1, os.path.join(__filedir__, ".."))
from test_data import DataSuite
suite = DataSuite(['CC'])
suite.testall()
## Instruction:
Test size and shape of ccenergies
## Code After:
"""Test coupled cluster logfiles"""
import os
import unittest
import numpy
__filedir__ = os.path.realpath(os.path.dirname(__file__))
class GenericCCTest(unittest.TestCase):
"""Generic coupled cluster unittest"""
def testsizeandshape(self):
"""Are the dimensions of ccenergies correct?"""
self.assertEqual(self.data.ccenergies.shape,
(len(self.data.scfenergies),))
def testsign(self):
"""Are the coupled cluster corrections negative?"""
corrections = self.data.ccenergies - self.data.scfenergies
self.assertTrue(numpy.alltrue(corrections < 0.0))
if __name__ == "__main__":
import sys
sys.path.insert(1, os.path.join(__filedir__, ".."))
from test_data import DataSuite
suite = DataSuite(['CC'])
suite.testall()
|
...
class GenericCCTest(unittest.TestCase):
"""Generic coupled cluster unittest"""
def testsizeandshape(self):
"""Are the dimensions of ccenergies correct?"""
self.assertEqual(self.data.ccenergies.shape,
(len(self.data.scfenergies),))
def testsign(self):
"""Are the coupled cluster corrections negative?"""
...
|
992c29ed85019c7e05f137d2091ec59858820f9f
|
src/fitnesse/testutil/WaitFixture.java
|
src/fitnesse/testutil/WaitFixture.java
|
package fitnesse.testutil;
public class WaitFixture {
public WaitFixture() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package fitnesse.testutil;
public class WaitFixture {
public WaitFixture() throws InterruptedException {
Thread.sleep(2000);
}
}
|
Remove catch in wait fixture.
|
Remove catch in wait fixture.
|
Java
|
epl-1.0
|
jdufner/fitnesse,hansjoachim/fitnesse,rbevers/fitnesse,rbevers/fitnesse,amolenaar/fitnesse,rbevers/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,hansjoachim/fitnesse,hansjoachim/fitnesse
|
java
|
## Code Before:
package fitnesse.testutil;
public class WaitFixture {
public WaitFixture() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
## Instruction:
Remove catch in wait fixture.
## Code After:
package fitnesse.testutil;
public class WaitFixture {
public WaitFixture() throws InterruptedException {
Thread.sleep(2000);
}
}
|
// ... existing code ...
public class WaitFixture {
public WaitFixture() throws InterruptedException {
Thread.sleep(2000);
}
}
// ... rest of the code ...
|
08e5fdfa744071270523d9f23129255555fcbeea
|
data-model/src/main/java/org/pdxfinder/dao/PatientSnapshot.java
|
data-model/src/main/java/org/pdxfinder/dao/PatientSnapshot.java
|
package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
}
|
package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
}
|
Add getter and setter for Patient attribute
|
Add getter and setter for Patient attribute
|
Java
|
apache-2.0
|
PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder
|
java
|
## Code Before:
package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
}
## Instruction:
Add getter and setter for Patient attribute
## Code After:
package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
}
|
// ... existing code ...
}
this.samples.add(sample);
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
}
// ... rest of the code ...
|
b3790a607a9f48561ce7a3da9242927510974808
|
packs/rackspace/actions/lib/action.py
|
packs/rackspace/actions/lib/action.py
|
from st2actions.runners.pythonrunner import Action
import pyrax
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region']
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
|
import pyrax
from st2actions.runners.pythonrunner import Action
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region'].upper()
print 'xxx', region
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
|
Make sure region name is uppercase.
|
Make sure region name is uppercase.
|
Python
|
apache-2.0
|
jtopjian/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,armab/st2contrib,StackStorm/st2contrib,pinterb/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib,dennybaa/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,meirwah/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,jtopjian/st2contrib,armab/st2contrib,digideskio/st2contrib,StackStorm/st2contrib,psychopenguin/st2contrib,StackStorm/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,armab/st2contrib,digideskio/st2contrib,lmEshoo/st2contrib,pinterb/st2contrib,dennybaa/st2contrib
|
python
|
## Code Before:
from st2actions.runners.pythonrunner import Action
import pyrax
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region']
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
## Instruction:
Make sure region name is uppercase.
## Code After:
import pyrax
from st2actions.runners.pythonrunner import Action
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['username']
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region'].upper()
print 'xxx', region
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(username, api_key)
return pyrax
|
# ... existing code ...
import pyrax
from st2actions.runners.pythonrunner import Action
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
# ... modified code ...
api_key = self.config['api_key']
# Needs to be extracted to per-action
region = self.config['region'].upper()
print 'xxx', region
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
# ... rest of the code ...
|
6400e9b978be21b2cd81c308a9683137daad80cd
|
examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationFactory.java
|
examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationFactory.java
|
package org.keycloak.examples.federation.properties;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {
public static final String PROVIDER_NAME = "classpath-properties";
@Override
protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
return new ClasspathPropertiesFederationProvider(session, model, props);
}
protected InputStream getPropertiesFileStream(String path) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalStateException("Path not found for properties file");
}
return is;
}
@Override
public String getId() {
return PROVIDER_NAME;
}
}
|
package org.keycloak.examples.federation.properties;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {
public static final String PROVIDER_NAME = "classpath-properties";
@Override
protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
return new ClasspathPropertiesFederationProvider(session, model, props);
}
protected InputStream getPropertiesFileStream(String path) {
InputStream is = getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalStateException("Path not found for properties file");
}
return is;
}
@Override
public String getId() {
return PROVIDER_NAME;
}
}
|
Fix federation provider example to load users file from it's own ClassLoader instead of Thread CL
|
Fix federation provider example to load users file from it's own ClassLoader instead of Thread CL
|
Java
|
apache-2.0
|
thomasdarimont/keycloak,mhajas/keycloak,chameleon82/keycloak,lkubik/keycloak,lkubik/keycloak,ppolavar/keycloak,jean-merelis/keycloak,lennartj/keycloak,srose/keycloak,pfiled/keycloak,AOEpeople/keycloak,ssilvert/keycloak,arivanajoki/keycloak,gregjones60/keycloak,agolPL/keycloak,ahus1/keycloak,j-bore/keycloak,wildfly-security-incubator/keycloak,cmoulliard/keycloak,anaerobic/keycloak,mposolda/keycloak,amalalex/keycloak,raehalme/keycloak,dbarentine/keycloak,ssilvert/keycloak,pedroigor/keycloak,darranl/keycloak,stianst/keycloak,AOEpeople/keycloak,girirajsharma/keycloak,wildfly-security-incubator/keycloak,vmuzikar/keycloak,ahus1/keycloak,thomasdarimont/keycloak,manuel-palacio/keycloak,pedroigor/keycloak,eugene-chow/keycloak,ppolavar/keycloak,cmoulliard/keycloak,ppolavar/keycloak,girirajsharma/keycloak,thomasdarimont/keycloak,ssilvert/keycloak,AOEpeople/keycloak,almighty/keycloak,thomasdarimont/keycloak,grange74/keycloak,didiez/keycloak,jpkrohling/keycloak,stianst/keycloak,grange74/keycloak,chameleon82/keycloak,hmlnarik/keycloak,pfiled/keycloak,mposolda/keycloak,keycloak/keycloak,ahus1/keycloak,VihreatDeGrona/keycloak,didiez/keycloak,iperdomo/keycloak,abstractj/keycloak,mbaluch/keycloak,brat000012001/keycloak,ssilvert/keycloak,mhajas/keycloak,almighty/keycloak,jean-merelis/keycloak,raehalme/keycloak,manuel-palacio/keycloak,hmlnarik/keycloak,ahus1/keycloak,eugene-chow/keycloak,VihreatDeGrona/keycloak,cmoulliard/keycloak,arivanajoki/keycloak,j-bore/keycloak,gregjones60/keycloak,pedroigor/keycloak,didiez/keycloak,grange74/keycloak,eugene-chow/keycloak,cfsnyder/keycloak,anaerobic/keycloak,pfiled/keycloak,dylanplecki/keycloak,lkubik/keycloak,mbaluch/keycloak,cfsnyder/keycloak,abstractj/keycloak,ahus1/keycloak,matzew/keycloak,abstractj/keycloak,didiez/keycloak,manuel-palacio/keycloak,hmlnarik/keycloak,mposolda/keycloak,darranl/keycloak,mbaluch/keycloak,srose/keycloak,jpkrohling/keycloak,jean-merelis/keycloak,matzew/keycloak,jean-merelis/keycloak,VihreatDeGrona/keycloak,girirajsharma/keycloak,stianst/keycloak,thomasdarimont/keycloak,hmlnarik/keycloak,mposolda/keycloak,gregjones60/keycloak,anaerobic/keycloak,raehalme/keycloak,iperdomo/keycloak,lkubik/keycloak,anaerobic/keycloak,pedroigor/keycloak,chameleon82/keycloak,ssilvert/keycloak,iperdomo/keycloak,amalalex/keycloak,WebJustDevelopment/keycloak,pfiled/keycloak,jpkrohling/keycloak,iperdomo/keycloak,reneploetz/keycloak,brat000012001/keycloak,lennartj/keycloak,cmoulliard/keycloak,abstractj/keycloak,vmuzikar/keycloak,girirajsharma/keycloak,arivanajoki/keycloak,vmuzikar/keycloak,ewjmulder/keycloak,reneploetz/keycloak,srose/keycloak,keycloak/keycloak,almighty/keycloak,VihreatDeGrona/keycloak,darranl/keycloak,ewjmulder/keycloak,amalalex/keycloak,mbaluch/keycloak,raehalme/keycloak,brat000012001/keycloak,manuel-palacio/keycloak,lennartj/keycloak,abstractj/keycloak,wildfly-security-incubator/keycloak,vmuzikar/keycloak,reneploetz/keycloak,mhajas/keycloak,raehalme/keycloak,dylanplecki/keycloak,pedroigor/keycloak,dbarentine/keycloak,ewjmulder/keycloak,grange74/keycloak,eugene-chow/keycloak,j-bore/keycloak,vmuzikar/keycloak,chameleon82/keycloak,amalalex/keycloak,mhajas/keycloak,ahus1/keycloak,WebJustDevelopment/keycloak,stianst/keycloak,hmlnarik/keycloak,jpkrohling/keycloak,hmlnarik/keycloak,darranl/keycloak,vmuzikar/keycloak,matzew/keycloak,thomasdarimont/keycloak,dbarentine/keycloak,almighty/keycloak,mposolda/keycloak,raehalme/keycloak,srose/keycloak,ewjmulder/keycloak,agolPL/keycloak,mposolda/keycloak,srose/keycloak,arivanajoki/keycloak,matzew/keycloak,cfsnyder/keycloak,keycloak/keycloak,reneploetz/keycloak,dylanplecki/keycloak,brat000012001/keycloak,dbarentine/keycloak,WebJustDevelopment/keycloak,gregjones60/keycloak,keycloak/keycloak,agolPL/keycloak,reneploetz/keycloak,stianst/keycloak,keycloak/keycloak,cfsnyder/keycloak,lennartj/keycloak,agolPL/keycloak,WebJustDevelopment/keycloak,dylanplecki/keycloak,pedroigor/keycloak,jpkrohling/keycloak,ppolavar/keycloak,brat000012001/keycloak,j-bore/keycloak,AOEpeople/keycloak,wildfly-security-incubator/keycloak,mhajas/keycloak
|
java
|
## Code Before:
package org.keycloak.examples.federation.properties;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {
public static final String PROVIDER_NAME = "classpath-properties";
@Override
protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
return new ClasspathPropertiesFederationProvider(session, model, props);
}
protected InputStream getPropertiesFileStream(String path) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalStateException("Path not found for properties file");
}
return is;
}
@Override
public String getId() {
return PROVIDER_NAME;
}
}
## Instruction:
Fix federation provider example to load users file from it's own ClassLoader instead of Thread CL
## Code After:
package org.keycloak.examples.federation.properties;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {
public static final String PROVIDER_NAME = "classpath-properties";
@Override
protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
return new ClasspathPropertiesFederationProvider(session, model, props);
}
protected InputStream getPropertiesFileStream(String path) {
InputStream is = getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalStateException("Path not found for properties file");
}
return is;
}
@Override
public String getId() {
return PROVIDER_NAME;
}
}
|
...
}
protected InputStream getPropertiesFileStream(String path) {
InputStream is = getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalStateException("Path not found for properties file");
...
|
7b92f1c5d1b109b93eb5535e70573b708c3df305
|
setup.py
|
setup.py
|
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=['argparse'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
|
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
install_requires = []
if sys.version_info[:2] < (2, 6):
install_requires.append('argparse')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=install_requires,
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
|
Make the py2.6 dependency conditional
|
Make the py2.6 dependency conditional
|
Python
|
mit
|
mlen108/pipin
|
python
|
## Code Before:
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=['argparse'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
## Instruction:
Make the py2.6 dependency conditional
## Code After:
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import pipin
install_requires = []
if sys.version_info[:2] < (2, 6):
install_requires.append('argparse')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='pipin',
version=pipin.__version__,
description='',
author='Matt Lenc',
author_email='[email protected]',
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=install_requires,
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
extras_require={
'testing': ['pytest'],
},
entry_points={
'console_scripts': [
'pipin = pipin.pipin:lets_pipin',
]
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development",
"Topic :: Utilities",
]
)
|
# ... existing code ...
from setuptools.command.test import test as TestCommand
import pipin
install_requires = []
if sys.version_info[:2] < (2, 6):
install_requires.append('argparse')
class PyTest(TestCommand):
# ... modified code ...
url='http://github.com/mattack108/pipin',
license='LICENSE.txt',
packages=['pipin'],
install_requires=install_requires,
tests_require=['pytest'],
cmdclass={'test': PyTest},
test_suite='pipin.tests.test_pipin',
# ... rest of the code ...
|
27a33628310cbd68632f0e8b514de731a033f8e6
|
IPython/utils/tests/test_shimmodule.py
|
IPython/utils/tests/test_shimmodule.py
|
import sys
import warnings
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
import IPython.config
assert len(w) == 1
assert issubclass(w[-1].category, ShimWarning)
|
import pytest
import sys
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with pytest.warns(ShimWarning):
import IPython.config
|
Make test_shim_warning not fail on unrelated warnings
|
Make test_shim_warning not fail on unrelated warnings
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
python
|
## Code Before:
import sys
import warnings
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
import IPython.config
assert len(w) == 1
assert issubclass(w[-1].category, ShimWarning)
## Instruction:
Make test_shim_warning not fail on unrelated warnings
## Code After:
import pytest
import sys
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with pytest.warns(ShimWarning):
import IPython.config
|
// ... existing code ...
import pytest
import sys
from IPython.utils.shimmodule import ShimWarning
// ... modified code ...
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with pytest.warns(ShimWarning):
import IPython.config
// ... rest of the code ...
|
178b39611ec6bc32e4bb0ccd481660a0364872d7
|
src/tests/test_utils.py
|
src/tests/test_utils.py
|
import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = np.identity(size)
noise = np.random.rand(size, size) * 0.1
linear_structure += noise
linear_structure = filters.gaussian_filter(linear_structure, 1.5)
return linear_structure
|
import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = np.identity(size)
noise = np.random.rand(size, size) * 0.1
linear_structure += noise
linear_structure = filters.gaussian_filter(linear_structure, 1.5)
return linear_structure
def generate_blob():
""" Generate a blob by drawing from the normal distribution across two axes
and binning it to the required size
"""
mean = [0,0]
cov = [[1,1],[10,100]] # diagonal covariance, points lie on x or y-axis
x,y = np.random.multivariate_normal(mean,cov,5000).T
h, xedges, yedges = np.histogram2d(x,y, bins=100)
return h
|
Add testing function for blobs
|
Add testing function for blobs
|
Python
|
mit
|
samueljackson92/major-project,samueljackson92/major-project,samueljackson92/major-project,samueljackson92/major-project
|
python
|
## Code Before:
import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = np.identity(size)
noise = np.random.rand(size, size) * 0.1
linear_structure += noise
linear_structure = filters.gaussian_filter(linear_structure, 1.5)
return linear_structure
## Instruction:
Add testing function for blobs
## Code After:
import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = np.identity(size)
noise = np.random.rand(size, size) * 0.1
linear_structure += noise
linear_structure = filters.gaussian_filter(linear_structure, 1.5)
return linear_structure
def generate_blob():
""" Generate a blob by drawing from the normal distribution across two axes
and binning it to the required size
"""
mean = [0,0]
cov = [[1,1],[10,100]] # diagonal covariance, points lie on x or y-axis
x,y = np.random.multivariate_normal(mean,cov,5000).T
h, xedges, yedges = np.histogram2d(x,y, bins=100)
return h
|
// ... existing code ...
linear_structure = filters.gaussian_filter(linear_structure, 1.5)
return linear_structure
def generate_blob():
""" Generate a blob by drawing from the normal distribution across two axes
and binning it to the required size
"""
mean = [0,0]
cov = [[1,1],[10,100]] # diagonal covariance, points lie on x or y-axis
x,y = np.random.multivariate_normal(mean,cov,5000).T
h, xedges, yedges = np.histogram2d(x,y, bins=100)
return h
// ... rest of the code ...
|
57e4785123d830cfaa827474485596c9943cd2ae
|
test/CFrontend/2007-08-22-CTTZ.c
|
test/CFrontend/2007-08-22-CTTZ.c
|
// RUN: %llvmgcc -O2 -S -o - -emit-llvm %s | grep {llvm.cttz.i64} | count 1
// RUN: %llvmgcc -O2 -S -o - -emit-llvm %s | not grep {lshr}
int bork(unsigned long long x) {
return __builtin_ctzll(x);
}
|
// RUN: %llvmgcc -O2 -S -o - %s | grep {llvm.cttz.i64} | count 2
// RUN: %llvmgcc -O2 -S -o - %s | not grep {lshr}
int bork(unsigned long long x) {
return __builtin_ctzll(x);
}
|
Fix this testcase: there are two matches for llvm.cttz.i64 because of the declaration of the intrinsic. Also, emit-llvm is automatic and doesn't need to be specified.
|
Fix this testcase: there are two matches for
llvm.cttz.i64 because of the declaration of
the intrinsic. Also, emit-llvm is automatic
and doesn't need to be specified.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@41326 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
bsd-2-clause
|
dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
|
c
|
## Code Before:
// RUN: %llvmgcc -O2 -S -o - -emit-llvm %s | grep {llvm.cttz.i64} | count 1
// RUN: %llvmgcc -O2 -S -o - -emit-llvm %s | not grep {lshr}
int bork(unsigned long long x) {
return __builtin_ctzll(x);
}
## Instruction:
Fix this testcase: there are two matches for
llvm.cttz.i64 because of the declaration of
the intrinsic. Also, emit-llvm is automatic
and doesn't need to be specified.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@41326 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: %llvmgcc -O2 -S -o - %s | grep {llvm.cttz.i64} | count 2
// RUN: %llvmgcc -O2 -S -o - %s | not grep {lshr}
int bork(unsigned long long x) {
return __builtin_ctzll(x);
}
|
...
// RUN: %llvmgcc -O2 -S -o - %s | grep {llvm.cttz.i64} | count 2
// RUN: %llvmgcc -O2 -S -o - %s | not grep {lshr}
int bork(unsigned long long x) {
return __builtin_ctzll(x);
...
|
39c0dfd7821355c9d2ff2274f4dd6292e959ed87
|
pronto/__init__.py
|
pronto/__init__.py
|
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = '[email protected]'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .parser import Parser
except ImportError:
pass
|
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = '[email protected]'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
|
Remove Parser from __all__ (from pronto import *)
|
Remove Parser from __all__ (from pronto import *)
|
Python
|
mit
|
althonos/pronto
|
python
|
## Code Before:
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship", "Parser"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = '[email protected]'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .parser import Parser
except ImportError:
pass
## Instruction:
Remove Parser from __all__ (from pronto import *)
## Code After:
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = '[email protected]'
try:
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
|
...
from __future__ import absolute_import
__all__ = ["Ontology", "Term", "TermList", "Relationship"]
__version__='0.5.0'
__author__='Martin Larralde'
__author_email__ = '[email protected]'
...
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
except ImportError:
pass
...
|
1a5abf19878cf8430d932ff1c581f0f2184a594c
|
app/src/main/java/app/tivi/ui/widget/TintingToolbar.kt
|
app/src/main/java/app/tivi/ui/widget/TintingToolbar.kt
|
/*
* Copyright 2018 Google, Inc.
*
* 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 app.tivi.ui.widget
import android.content.Context
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor
class TintingToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
set(value) {
navigationIcon = navigationIcon?.let {
it.setTint(value)
it.mutate()
}
overflowIcon = overflowIcon?.let {
it.setTint(value)
it.mutate()
}
}
}
|
/*
* Copyright 2018 Google, Inc.
*
* 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 app.tivi.ui.widget
import android.content.Context
import android.support.annotation.Keep
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor
class TintingToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
@get:Keep
@set:Keep
var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
set(value) {
if (value != field) {
navigationIcon = navigationIcon?.let {
it.setTint(value)
it.mutate()
}
overflowIcon = overflowIcon?.let {
it.setTint(value)
it.mutate()
}
}
field = value
}
}
|
Fix Toolbar tinting animation on release build
|
Fix Toolbar tinting animation on release build
|
Kotlin
|
apache-2.0
|
chrisbanes/tivi,chrisbanes/tivi
|
kotlin
|
## Code Before:
/*
* Copyright 2018 Google, Inc.
*
* 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 app.tivi.ui.widget
import android.content.Context
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor
class TintingToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
set(value) {
navigationIcon = navigationIcon?.let {
it.setTint(value)
it.mutate()
}
overflowIcon = overflowIcon?.let {
it.setTint(value)
it.mutate()
}
}
}
## Instruction:
Fix Toolbar tinting animation on release build
## Code After:
/*
* Copyright 2018 Google, Inc.
*
* 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 app.tivi.ui.widget
import android.content.Context
import android.support.annotation.Keep
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor
class TintingToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
@get:Keep
@set:Keep
var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
set(value) {
if (value != field) {
navigationIcon = navigationIcon?.let {
it.setTint(value)
it.mutate()
}
overflowIcon = overflowIcon?.let {
it.setTint(value)
it.mutate()
}
}
field = value
}
}
|
// ... existing code ...
package app.tivi.ui.widget
import android.content.Context
import android.support.annotation.Keep
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
// ... modified code ...
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
@get:Keep
@set:Keep
var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
set(value) {
if (value != field) {
navigationIcon = navigationIcon?.let {
it.setTint(value)
it.mutate()
}
overflowIcon = overflowIcon?.let {
it.setTint(value)
it.mutate()
}
}
field = value
}
}
// ... rest of the code ...
|
e9ebbcf7a77e7a60fad3b1adf58856d4de273873
|
src/main/java/io/github/mikesaelim/poleposition/persistence/ArticlePersistenceRepository.java
|
src/main/java/io/github/mikesaelim/poleposition/persistence/ArticlePersistenceRepository.java
|
package io.github.mikesaelim.poleposition.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ArticlePersistenceRepository extends JpaRepository<ArticlePersistence, String> {
}
|
package io.github.mikesaelim.poleposition.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ArticlePersistenceRepository extends JpaRepository<ArticlePersistence, String> {
}
|
Make IntelliJ stop crying by adding unnecessary @Repository annotation
|
Make IntelliJ stop crying by adding unnecessary @Repository annotation
|
Java
|
mit
|
mikesaelim/poleposition
|
java
|
## Code Before:
package io.github.mikesaelim.poleposition.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ArticlePersistenceRepository extends JpaRepository<ArticlePersistence, String> {
}
## Instruction:
Make IntelliJ stop crying by adding unnecessary @Repository annotation
## Code After:
package io.github.mikesaelim.poleposition.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ArticlePersistenceRepository extends JpaRepository<ArticlePersistence, String> {
}
|
...
package io.github.mikesaelim.poleposition.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ArticlePersistenceRepository extends JpaRepository<ArticlePersistence, String> {
}
...
|
c581851a1839a63c4873ed632a62982d1c8bb6d0
|
src/helpers/number_helper.h
|
src/helpers/number_helper.h
|
/*
* *****************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* *****************************************************************************
*/
#ifndef NUMBER_HELPER_H
#define NUMBER_HELPER_H
#include <QString>
class NumberHelper
{
public:
static const uint64_t B;
static const uint64_t KB;
static const uint64_t MB;
static const uint64_t GB;
static const uint64_t TB;
static QString ToHumanSize(uint64_t bytes);
};
#endif
|
/*
* *****************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* *****************************************************************************
*/
#ifndef NUMBER_HELPER_H
#define NUMBER_HELPER_H
#include <stdint.h>
#include <QString>
class NumberHelper
{
public:
static const uint64_t B;
static const uint64_t KB;
static const uint64_t MB;
static const uint64_t GB;
static const uint64_t TB;
static QString ToHumanSize(uint64_t bytes);
};
#endif
|
Fix windows build by requiring stdint.h
|
Fix windows build by requiring stdint.h
|
C
|
apache-2.0
|
Klopsch/ds3_browser,Klopsch/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser,Klopsch/ds3_browser
|
c
|
## Code Before:
/*
* *****************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* *****************************************************************************
*/
#ifndef NUMBER_HELPER_H
#define NUMBER_HELPER_H
#include <QString>
class NumberHelper
{
public:
static const uint64_t B;
static const uint64_t KB;
static const uint64_t MB;
static const uint64_t GB;
static const uint64_t TB;
static QString ToHumanSize(uint64_t bytes);
};
#endif
## Instruction:
Fix windows build by requiring stdint.h
## Code After:
/*
* *****************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* *****************************************************************************
*/
#ifndef NUMBER_HELPER_H
#define NUMBER_HELPER_H
#include <stdint.h>
#include <QString>
class NumberHelper
{
public:
static const uint64_t B;
static const uint64_t KB;
static const uint64_t MB;
static const uint64_t GB;
static const uint64_t TB;
static QString ToHumanSize(uint64_t bytes);
};
#endif
|
// ... existing code ...
#ifndef NUMBER_HELPER_H
#define NUMBER_HELPER_H
#include <stdint.h>
#include <QString>
class NumberHelper
// ... rest of the code ...
|
0692cc324d3759703ee52e117ac19e75d82df6a6
|
tests/config/tests.py
|
tests/config/tests.py
|
from raven.conf import load
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:[email protected]/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
def test_path(self):
dsn = 'https://foo:[email protected]/app/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/app/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
|
import logging
import mock
from raven.conf import load, setup_logging
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:[email protected]/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
def test_path(self):
dsn = 'https://foo:[email protected]/app/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/app/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
class SetupLoggingTest(TestCase):
def test_basic_not_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
logger = getLogger()
logger.handlers = []
handler = mock.Mock()
result = setup_logging(handler)
self.assertTrue(result)
def test_basic_already_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
handler = mock.Mock()
logger = getLogger()
logger.handlers = [handler]
result = setup_logging(handler)
self.assertFalse(result)
|
Add basic coverage for the setup_logging method
|
Add basic coverage for the setup_logging method
|
Python
|
bsd-3-clause
|
inspirehep/raven-python,jmagnusson/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akalipetis/raven-python,inspirehep/raven-python,nikolas/raven-python,hzy/raven-python,smarkets/raven-python,beniwohli/apm-agent-python,icereval/raven-python,jmagnusson/raven-python,percipient/raven-python,dirtycoder/opbeat_python,someonehan/raven-python,johansteffner/raven-python,Photonomie/raven-python,recht/raven-python,lopter/raven-python-old,icereval/raven-python,arthurlogilab/raven-python,patrys/opbeat_python,getsentry/raven-python,alex/raven,jbarbuto/raven-python,lepture/raven-python,inspirehep/raven-python,jmagnusson/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,tarkatronic/opbeat_python,jmp0xf/raven-python,recht/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,smarkets/raven-python,jbarbuto/raven-python,lepture/raven-python,jbarbuto/raven-python,recht/raven-python,ronaldevers/raven-python,icereval/raven-python,daikeren/opbeat_python,ronaldevers/raven-python,nikolas/raven-python,beniwohli/apm-agent-python,someonehan/raven-python,getsentry/raven-python,beniwohli/apm-agent-python,percipient/raven-python,akalipetis/raven-python,smarkets/raven-python,patrys/opbeat_python,collective/mr.poe,inspirehep/raven-python,ticosax/opbeat_python,jmp0xf/raven-python,akalipetis/raven-python,patrys/opbeat_python,daikeren/opbeat_python,hzy/raven-python,danriti/raven-python,danriti/raven-python,jbarbuto/raven-python,ewdurbin/raven-python,ewdurbin/raven-python,daikeren/opbeat_python,tarkatronic/opbeat_python,nikolas/raven-python,Photonomie/raven-python,percipient/raven-python,openlabs/raven,lepture/raven-python,ticosax/opbeat_python,nikolas/raven-python,jmp0xf/raven-python,danriti/raven-python,akheron/raven-python,ewdurbin/raven-python,beniwohli/apm-agent-python,hzy/raven-python,smarkets/raven-python,someonehan/raven-python,icereval/raven-python,dirtycoder/opbeat_python,getsentry/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akheron/raven-python,dbravender/raven-python,tarkatronic/opbeat_python,Photonomie/raven-python,arthurlogilab/raven-python,ronaldevers/raven-python,dbravender/raven-python,johansteffner/raven-python,johansteffner/raven-python,ticosax/opbeat_python,arthurlogilab/raven-python,dbravender/raven-python,akheron/raven-python,patrys/opbeat_python,arthurlogilab/raven-python,dirtycoder/opbeat_python
|
python
|
## Code Before:
from raven.conf import load
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:[email protected]/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
def test_path(self):
dsn = 'https://foo:[email protected]/app/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/app/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
## Instruction:
Add basic coverage for the setup_logging method
## Code After:
import logging
import mock
from raven.conf import load, setup_logging
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:[email protected]/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
def test_path(self):
dsn = 'https://foo:[email protected]/app/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local/app/api/store/'],
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
class SetupLoggingTest(TestCase):
def test_basic_not_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
logger = getLogger()
logger.handlers = []
handler = mock.Mock()
result = setup_logging(handler)
self.assertTrue(result)
def test_basic_already_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
handler = mock.Mock()
logger = getLogger()
logger.handlers = [handler]
result = setup_logging(handler)
self.assertFalse(result)
|
...
import logging
import mock
from raven.conf import load, setup_logging
from unittest2 import TestCase
...
'SENTRY_PUBLIC_KEY': 'foo',
'SENTRY_SECRET_KEY': 'bar',
})
class SetupLoggingTest(TestCase):
def test_basic_not_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
logger = getLogger()
logger.handlers = []
handler = mock.Mock()
result = setup_logging(handler)
self.assertTrue(result)
def test_basic_already_configured(self):
with mock.patch('logging.getLogger', spec=logging.getLogger) as getLogger:
handler = mock.Mock()
logger = getLogger()
logger.handlers = [handler]
result = setup_logging(handler)
self.assertFalse(result)
...
|
696870bfaa390ca520afe760a68b2d99ac41a828
|
fruit/g4/FruitGenerator.java
|
fruit/g4/FruitGenerator.java
|
package fruit.g4;
public class FruitGenerator implements fruit.sim.FruitGenerator
{
private int[] dist;
public int[] generate(int nplayers, int bowlsize) {
int nfruits = nplayers * bowlsize;
dist = new int[12];
int distChoice = 2;
if(distChoice == 1)
uniform(nfruits);
else if(distChoice == 2)
halfFruits(nfruits);
return dist;
}
private void uniform(int nfruits) {
int unit = nfruits / 12;
dist[0] = nfruits - unit * 11;
for (int i = 1; i < 12; i++)
dist[i] = unit;
}
private void halfFruits(int nfruits) {
int r;
int subset[] = new int[6];
boolean filled = false;
for(int i=0; i < 6; i++) {
boolean unique;
do {
unique = true;
r = (int)(Math.random()*12);
for(int j=0; j < i; j++) {
if(subset[j] == r)
unique = false;
}
}while(!unique);
subset[i] = r;
}
while(nfruits > 0) {
r = (int)(Math.random()*subset.length);
dist[subset[r]]++ ;
nfruits--;
}
}
}
|
package fruit.g4;
public class FruitGenerator implements fruit.sim.FruitGenerator
{
private int[] dist;
public int[] generate(int nplayers, int bowlsize) {
int nfruits = nplayers * bowlsize;
dist = new int[12];
int distChoice = 2;
if(distChoice == 1)
uniform(nfruits);
else if(distChoice == 2)
halfFruits(nfruits);
return dist;
}
private void uniform(int nfruits) {
int unit = nfruits / 12;
dist[0] = nfruits - unit * 11;
for (int i = 1; i < 12; i++)
dist[i] = unit;
}
private void halfFruits(int nfruits) {
int r;
int subset[] = new int[6];
boolean filled = false;
for(int i=0; i < 6; i++) {
boolean unique;
do {
unique = true;
r = (int)(Math.random()*12);
for(int j=0; j < i; j++) {
if(subset[j] == r)
unique = false;
}
}while(!unique);
subset[i] = r;
}
while(nfruits > 0) {
r = (int)(Math.random()*subset.length);
dist[subset[r]]++ ;
nfruits--;
}
}
}
|
Clean up and switch distribution
|
Clean up and switch distribution
|
Java
|
mit
|
rymo4/fruitsalad
|
java
|
## Code Before:
package fruit.g4;
public class FruitGenerator implements fruit.sim.FruitGenerator
{
private int[] dist;
public int[] generate(int nplayers, int bowlsize) {
int nfruits = nplayers * bowlsize;
dist = new int[12];
int distChoice = 2;
if(distChoice == 1)
uniform(nfruits);
else if(distChoice == 2)
halfFruits(nfruits);
return dist;
}
private void uniform(int nfruits) {
int unit = nfruits / 12;
dist[0] = nfruits - unit * 11;
for (int i = 1; i < 12; i++)
dist[i] = unit;
}
private void halfFruits(int nfruits) {
int r;
int subset[] = new int[6];
boolean filled = false;
for(int i=0; i < 6; i++) {
boolean unique;
do {
unique = true;
r = (int)(Math.random()*12);
for(int j=0; j < i; j++) {
if(subset[j] == r)
unique = false;
}
}while(!unique);
subset[i] = r;
}
while(nfruits > 0) {
r = (int)(Math.random()*subset.length);
dist[subset[r]]++ ;
nfruits--;
}
}
}
## Instruction:
Clean up and switch distribution
## Code After:
package fruit.g4;
public class FruitGenerator implements fruit.sim.FruitGenerator
{
private int[] dist;
public int[] generate(int nplayers, int bowlsize) {
int nfruits = nplayers * bowlsize;
dist = new int[12];
int distChoice = 2;
if(distChoice == 1)
uniform(nfruits);
else if(distChoice == 2)
halfFruits(nfruits);
return dist;
}
private void uniform(int nfruits) {
int unit = nfruits / 12;
dist[0] = nfruits - unit * 11;
for (int i = 1; i < 12; i++)
dist[i] = unit;
}
private void halfFruits(int nfruits) {
int r;
int subset[] = new int[6];
boolean filled = false;
for(int i=0; i < 6; i++) {
boolean unique;
do {
unique = true;
r = (int)(Math.random()*12);
for(int j=0; j < i; j++) {
if(subset[j] == r)
unique = false;
}
}while(!unique);
subset[i] = r;
}
while(nfruits > 0) {
r = (int)(Math.random()*subset.length);
dist[subset[r]]++ ;
nfruits--;
}
}
}
|
...
public class FruitGenerator implements fruit.sim.FruitGenerator
{
private int[] dist;
public int[] generate(int nplayers, int bowlsize) {
int nfruits = nplayers * bowlsize;
dist = new int[12];
int distChoice = 2;
if(distChoice == 1)
uniform(nfruits);
else if(distChoice == 2)
halfFruits(nfruits);
return dist;
}
private void uniform(int nfruits) {
int unit = nfruits / 12;
...
for (int i = 1; i < 12; i++)
dist[i] = unit;
}
private void halfFruits(int nfruits) {
int r;
int subset[] = new int[6];
boolean filled = false;
for(int i=0; i < 6; i++) {
boolean unique;
do {
unique = true;
r = (int)(Math.random()*12);
for(int j=0; j < i; j++) {
if(subset[j] == r)
unique = false;
}
}while(!unique);
subset[i] = r;
}
while(nfruits > 0) {
r = (int)(Math.random()*subset.length);
dist[subset[r]]++ ;
nfruits--;
}
}
}
...
|
e3df58bba5f78dea87fd6a0bbbc8645e4d294bc9
|
kite-apps-crunch/src/main/java/org/kitesdk/apps/crunch/AbstractCrunchJob.java
|
kite-apps-crunch/src/main/java/org/kitesdk/apps/crunch/AbstractCrunchJob.java
|
package org.kitesdk.apps.crunch;
import org.kitesdk.apps.scheduled.AbstractSchedulableJob;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
/**
* Abstract base class for Crunch-based jobs.
*/
public abstract class AbstractCrunchJob extends AbstractSchedulableJob {
protected Pipeline getPipeline() {
return new MRPipeline(AbstractCrunchJob.class, getConf());
}
}
|
package org.kitesdk.apps.crunch;
import org.kitesdk.apps.scheduled.AbstractSchedulableJob;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
/**
* Abstract base class for Crunch-based jobs.
*/
public abstract class AbstractCrunchJob extends AbstractSchedulableJob {
protected Pipeline getPipeline() {
return new MRPipeline(AbstractCrunchJob.class, getName(), getConf());
}
}
|
Support naming the Crunch pipelines.
|
Support naming the Crunch pipelines.
|
Java
|
apache-2.0
|
mkwhitacre/kite-apps,rbrush/kite-apps,mkwhitacre/kite-apps,rbrush/kite-apps
|
java
|
## Code Before:
package org.kitesdk.apps.crunch;
import org.kitesdk.apps.scheduled.AbstractSchedulableJob;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
/**
* Abstract base class for Crunch-based jobs.
*/
public abstract class AbstractCrunchJob extends AbstractSchedulableJob {
protected Pipeline getPipeline() {
return new MRPipeline(AbstractCrunchJob.class, getConf());
}
}
## Instruction:
Support naming the Crunch pipelines.
## Code After:
package org.kitesdk.apps.crunch;
import org.kitesdk.apps.scheduled.AbstractSchedulableJob;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
/**
* Abstract base class for Crunch-based jobs.
*/
public abstract class AbstractCrunchJob extends AbstractSchedulableJob {
protected Pipeline getPipeline() {
return new MRPipeline(AbstractCrunchJob.class, getName(), getConf());
}
}
|
// ... existing code ...
public abstract class AbstractCrunchJob extends AbstractSchedulableJob {
protected Pipeline getPipeline() {
return new MRPipeline(AbstractCrunchJob.class, getName(), getConf());
}
}
// ... rest of the code ...
|
17c24de2f87e8f7140098c5d74c376295956eb6c
|
java_src/foam/lib/json/FObjectParser.java
|
java_src/foam/lib/json/FObjectParser.java
|
package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
public FObjectParser() {
super(new Seq1(7,
new Whitespace(),
new Literal("{"),
new Whitespace(),
new KeyParser("class"),
new Whitespace(),
new Literal(":"),
new Whitespace(),
new Parser() {
private Parser delegate = new StringParser();
public PStream parse(PStream ps, ParserContext x) {
ps = delegate.parse(ps, x);
if ( ps == null ) return null;
Class c;
try {
c = Class.forName(ps.value().toString());
} catch(ClassNotFoundException e) {
throw new RuntimeException(e);
}
ParserContext subx = x.sub();
try {
subx.set("obj", c.newInstance());
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
System.out.println("Parsing: " + c.getName());
ps = ModelParserFactory.getInstance(c).parse(ps, subx);
if ( ps != null ) {
return ps.setValue(subx.get("obj"));
}
return null;
}
},
new Whitespace(),
new Literal("}")));
}
}
|
package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
public FObjectParser() {
super(new Seq1(7,
new Whitespace(),
new Literal("{"),
new Whitespace(),
new KeyParser("class"),
new Whitespace(),
new Literal(":"),
new Whitespace(),
new Parser() {
private Parser delegate = new StringParser();
public PStream parse(PStream ps, ParserContext x) {
ps = delegate.parse(ps, x);
if ( ps == null ) return null;
Class c;
try {
c = Class.forName(ps.value().toString());
} catch(ClassNotFoundException e) {
throw new RuntimeException(e);
}
ParserContext subx = x.sub();
try {
subx.set("obj", c.newInstance());
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
ps = ModelParserFactory.getInstance(c).parse(ps, subx);
if ( ps != null ) {
return ps.setValue(subx.get("obj"));
}
return null;
}
},
new Whitespace(),
new Literal("}")));
}
}
|
Remove logging statment used for debugging.
|
Remove logging statment used for debugging.
|
Java
|
apache-2.0
|
foam-framework/foam2,TanayParikh/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,TanayParikh/foam2,TanayParikh/foam2,TanayParikh/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm
|
java
|
## Code Before:
package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
public FObjectParser() {
super(new Seq1(7,
new Whitespace(),
new Literal("{"),
new Whitespace(),
new KeyParser("class"),
new Whitespace(),
new Literal(":"),
new Whitespace(),
new Parser() {
private Parser delegate = new StringParser();
public PStream parse(PStream ps, ParserContext x) {
ps = delegate.parse(ps, x);
if ( ps == null ) return null;
Class c;
try {
c = Class.forName(ps.value().toString());
} catch(ClassNotFoundException e) {
throw new RuntimeException(e);
}
ParserContext subx = x.sub();
try {
subx.set("obj", c.newInstance());
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
System.out.println("Parsing: " + c.getName());
ps = ModelParserFactory.getInstance(c).parse(ps, subx);
if ( ps != null ) {
return ps.setValue(subx.get("obj"));
}
return null;
}
},
new Whitespace(),
new Literal("}")));
}
}
## Instruction:
Remove logging statment used for debugging.
## Code After:
package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
public FObjectParser() {
super(new Seq1(7,
new Whitespace(),
new Literal("{"),
new Whitespace(),
new KeyParser("class"),
new Whitespace(),
new Literal(":"),
new Whitespace(),
new Parser() {
private Parser delegate = new StringParser();
public PStream parse(PStream ps, ParserContext x) {
ps = delegate.parse(ps, x);
if ( ps == null ) return null;
Class c;
try {
c = Class.forName(ps.value().toString());
} catch(ClassNotFoundException e) {
throw new RuntimeException(e);
}
ParserContext subx = x.sub();
try {
subx.set("obj", c.newInstance());
} catch(InstantiationException e) {
throw new RuntimeException(e);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
ps = ModelParserFactory.getInstance(c).parse(ps, subx);
if ( ps != null ) {
return ps.setValue(subx.get("obj"));
}
return null;
}
},
new Whitespace(),
new Literal("}")));
}
}
|
...
throw new RuntimeException(e);
}
ps = ModelParserFactory.getInstance(c).parse(ps, subx);
if ( ps != null ) {
...
|
a05372ad910900ec2ef89bb10d4a0759c9bcd437
|
app.py
|
app.py
|
import os
from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
from charity import Charity
SECRET_KEY = os.environ['DONATION_SECRET_KEY']
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.values.get('From', None)
client = TwilioRestClient()
charity = Charity()
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the message!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Test sending a fresh message
|
Test sending a fresh message
|
Python
|
mit
|
DanielleSucher/Text-Donation
|
python
|
## Code Before:
import os
from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
from charity import Charity
SECRET_KEY = os.environ['DONATION_SECRET_KEY']
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.values.get('From', None)
client = TwilioRestClient()
charity = Charity()
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the message!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
## Instruction:
Test sending a fresh message
## Code After:
import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
# ... existing code ...
import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
# ... rest of the code ...
|
ac4f5451baaefd67392d9b908c9ccffc4083a9ad
|
fluidsynth/fluidsynth.py
|
fluidsynth/fluidsynth.py
|
from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
|
from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")
|
Change the LD search path
|
Change the LD search path
|
Python
|
mit
|
paultag/python-fluidsynth
|
python
|
## Code Before:
from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
## Instruction:
Change the LD search path
## Code After:
from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef struct _fluid_hashtable_t fluid_settings_t;
typedef struct _fluid_synth_t fluid_synth_t;
typedef struct _fluid_audio_driver_t fluid_audio_driver_t;
fluid_settings_t* new_fluid_settings(void);
fluid_synth_t* new_fluid_synth(fluid_settings_t* settings);
fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth);
int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets);
int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel);
int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key);
void delete_fluid_audio_driver(fluid_audio_driver_t* driver);
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")
|
...
int delete_fluid_synth(fluid_synth_t* synth);
void delete_fluid_settings(fluid_settings_t* settings);
""")
C = ffi.dlopen("libfluidsynth.so.1")
...
|
d7ed79ec53279f0fea0881703079a1c5b82bf938
|
_settings.py
|
_settings.py
|
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
|
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
|
Add comment regarding freetds config
|
Add comment regarding freetds config
|
Python
|
mit
|
cumc-dbmi/pmi_sprint_reporter
|
python
|
## Code Before:
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
## Instruction:
Add comment regarding freetds config
## Code After:
hpo_id = 'hpo_id'
# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'
# sprint number being validated against
sprint_num = 0
# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
|
// ... existing code ...
sprint_num = 0
# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
// ... rest of the code ...
|
5deb33c244242d36a16a8c08ff816368b345a8f3
|
qr_code/qrcode/image.py
|
qr_code/qrcode/image.py
|
import logging
from qrcode.image.svg import SvgPathImage as _SvgPathImage
logger = logging.getLogger('django')
try:
from qrcode.image.pil import PilImage as _PilImageOrFallback
except ImportError:
logger.info("Pillow is not installed. No support available for PNG format.")
from qrcode.image.svg import SvgPathImage as _PilImageOrFallback
SVG_FORMAT_NAME = 'svg'
PNG_FORMAT_NAME = 'png'
SvgPathImage = _SvgPathImage
PilImageOrFallback = _PilImageOrFallback
def has_png_support():
return PilImageOrFallback is not SvgPathImage
def get_supported_image_format(image_format):
image_format = image_format.lower()
if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]:
logger.warning('Unknown image format: %s' % image_format)
image_format = SVG_FORMAT_NAME
elif image_format == PNG_FORMAT_NAME and not has_png_support():
logger.warning("No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.")
image_format = SVG_FORMAT_NAME
return image_format
|
import logging
from qrcode.image.svg import SvgPathImage as _SvgPathImage
logger = logging.getLogger('django')
try:
from qrcode.image.pil import PilImage as _PilImageOrFallback
except ImportError: # pragma: no cover
logger.info("Pillow is not installed. No support available for PNG format.")
from qrcode.image.svg import SvgPathImage as _PilImageOrFallback
SVG_FORMAT_NAME = 'svg'
PNG_FORMAT_NAME = 'png'
SvgPathImage = _SvgPathImage
PilImageOrFallback = _PilImageOrFallback
def has_png_support():
return PilImageOrFallback is not SvgPathImage
def get_supported_image_format(image_format):
image_format = image_format.lower()
if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]:
logger.warning('Unknown image format: %s' % image_format)
image_format = SVG_FORMAT_NAME
elif image_format == PNG_FORMAT_NAME and not has_png_support():
logger.warning(
"No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.")
image_format = SVG_FORMAT_NAME
return image_format
|
Exclude handling of the situation where Pillow is not available from test coverage.
|
Exclude handling of the situation where Pillow is not available from test coverage.
|
Python
|
bsd-3-clause
|
dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code
|
python
|
## Code Before:
import logging
from qrcode.image.svg import SvgPathImage as _SvgPathImage
logger = logging.getLogger('django')
try:
from qrcode.image.pil import PilImage as _PilImageOrFallback
except ImportError:
logger.info("Pillow is not installed. No support available for PNG format.")
from qrcode.image.svg import SvgPathImage as _PilImageOrFallback
SVG_FORMAT_NAME = 'svg'
PNG_FORMAT_NAME = 'png'
SvgPathImage = _SvgPathImage
PilImageOrFallback = _PilImageOrFallback
def has_png_support():
return PilImageOrFallback is not SvgPathImage
def get_supported_image_format(image_format):
image_format = image_format.lower()
if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]:
logger.warning('Unknown image format: %s' % image_format)
image_format = SVG_FORMAT_NAME
elif image_format == PNG_FORMAT_NAME and not has_png_support():
logger.warning("No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.")
image_format = SVG_FORMAT_NAME
return image_format
## Instruction:
Exclude handling of the situation where Pillow is not available from test coverage.
## Code After:
import logging
from qrcode.image.svg import SvgPathImage as _SvgPathImage
logger = logging.getLogger('django')
try:
from qrcode.image.pil import PilImage as _PilImageOrFallback
except ImportError: # pragma: no cover
logger.info("Pillow is not installed. No support available for PNG format.")
from qrcode.image.svg import SvgPathImage as _PilImageOrFallback
SVG_FORMAT_NAME = 'svg'
PNG_FORMAT_NAME = 'png'
SvgPathImage = _SvgPathImage
PilImageOrFallback = _PilImageOrFallback
def has_png_support():
return PilImageOrFallback is not SvgPathImage
def get_supported_image_format(image_format):
image_format = image_format.lower()
if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]:
logger.warning('Unknown image format: %s' % image_format)
image_format = SVG_FORMAT_NAME
elif image_format == PNG_FORMAT_NAME and not has_png_support():
logger.warning(
"No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.")
image_format = SVG_FORMAT_NAME
return image_format
|
# ... existing code ...
import logging
from qrcode.image.svg import SvgPathImage as _SvgPathImage
logger = logging.getLogger('django')
try:
from qrcode.image.pil import PilImage as _PilImageOrFallback
except ImportError: # pragma: no cover
logger.info("Pillow is not installed. No support available for PNG format.")
from qrcode.image.svg import SvgPathImage as _PilImageOrFallback
# ... modified code ...
logger.warning('Unknown image format: %s' % image_format)
image_format = SVG_FORMAT_NAME
elif image_format == PNG_FORMAT_NAME and not has_png_support():
logger.warning(
"No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.")
image_format = SVG_FORMAT_NAME
return image_format
# ... rest of the code ...
|
20c69b4c3ba24c3b0a49783fe6cbde780eb52722
|
src/main/kotlin/com/lapismc/minecraft/versioning/OSRule.kt
|
src/main/kotlin/com/lapismc/minecraft/versioning/OSRule.kt
|
package com.lapismc.minecraft.versioning
/**
* Library inclusion rule for operating system checks.
* @param os Operating system this rule applies to.
* @param allowed Flag indicating whether the library should be included.
*/
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
override fun isApplicable(): Boolean = TODO()
}
|
package com.lapismc.minecraft.versioning
/**
* Library inclusion rule for operating system checks.
* @param os Operating system this rule applies to.
* @param allowed Flag indicating whether the library should be included.
*/
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
companion object {
/**
* Name of the current operating system.
*/
private val localOSName = System.getProperty("os.name").toLowerCase()
/**
* Checks whether the local system appears to be Windows.
* @return True if the local OS is Windows, false otherwise.
*/
fun isWindows() = localOSName.indexOf("win") >= 0
/**
* Checks whether the local system appears to be Mac OSX.
* @return True if the local OS is Mac OSX, false otherwise.
*/
fun isOSX() = localOSName.indexOf("mac") >= 0
/**
* Checks whether the local system appears to be Linux.
* @return True if the local OS is Linux, false otherwise.
*/
fun isLinux() = localOSName.indexOf("linux") >= 0
}
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
override fun isApplicable(): Boolean = when(os) {
OSType.WINDOWS -> isWindows()
OSType.OSX -> isOSX()
OSType.LINUX -> isLinux()
}
}
|
Add logic to detect OS
|
Add logic to detect OS
|
Kotlin
|
mit
|
lapis-mc/minecraft-versioning
|
kotlin
|
## Code Before:
package com.lapismc.minecraft.versioning
/**
* Library inclusion rule for operating system checks.
* @param os Operating system this rule applies to.
* @param allowed Flag indicating whether the library should be included.
*/
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
override fun isApplicable(): Boolean = TODO()
}
## Instruction:
Add logic to detect OS
## Code After:
package com.lapismc.minecraft.versioning
/**
* Library inclusion rule for operating system checks.
* @param os Operating system this rule applies to.
* @param allowed Flag indicating whether the library should be included.
*/
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
companion object {
/**
* Name of the current operating system.
*/
private val localOSName = System.getProperty("os.name").toLowerCase()
/**
* Checks whether the local system appears to be Windows.
* @return True if the local OS is Windows, false otherwise.
*/
fun isWindows() = localOSName.indexOf("win") >= 0
/**
* Checks whether the local system appears to be Mac OSX.
* @return True if the local OS is Mac OSX, false otherwise.
*/
fun isOSX() = localOSName.indexOf("mac") >= 0
/**
* Checks whether the local system appears to be Linux.
* @return True if the local OS is Linux, false otherwise.
*/
fun isLinux() = localOSName.indexOf("linux") >= 0
}
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
override fun isApplicable(): Boolean = when(os) {
OSType.WINDOWS -> isWindows()
OSType.OSX -> isOSX()
OSType.LINUX -> isLinux()
}
}
|
# ... existing code ...
* @param allowed Flag indicating whether the library should be included.
*/
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
companion object {
/**
* Name of the current operating system.
*/
private val localOSName = System.getProperty("os.name").toLowerCase()
/**
* Checks whether the local system appears to be Windows.
* @return True if the local OS is Windows, false otherwise.
*/
fun isWindows() = localOSName.indexOf("win") >= 0
/**
* Checks whether the local system appears to be Mac OSX.
* @return True if the local OS is Mac OSX, false otherwise.
*/
fun isOSX() = localOSName.indexOf("mac") >= 0
/**
* Checks whether the local system appears to be Linux.
* @return True if the local OS is Linux, false otherwise.
*/
fun isLinux() = localOSName.indexOf("linux") >= 0
}
/**
* Checks whether this rule applies to the current system.
* @return True if the rule should be considered, false otherwise.
*/
override fun isApplicable(): Boolean = when(os) {
OSType.WINDOWS -> isWindows()
OSType.OSX -> isOSX()
OSType.LINUX -> isLinux()
}
}
# ... rest of the code ...
|
24e65db624221d559f46ce74d88ad28ec970d754
|
profile_collection/startup/00-startup.py
|
profile_collection/startup/00-startup.py
|
import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
|
import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
import bluesky.qt_kicker
bluesky.qt_kicker.install_qt_kicker()
|
Update bluesky's API to the qt_kicker.
|
Update bluesky's API to the qt_kicker.
|
Python
|
bsd-2-clause
|
NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
|
python
|
## Code Before:
import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
## Instruction:
Update bluesky's API to the qt_kicker.
## Code After:
import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
import bluesky.qt_kicker
bluesky.qt_kicker.install_qt_kicker()
|
...
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
import bluesky.qt_kicker
bluesky.qt_kicker.install_qt_kicker()
...
|
4c3e9723f67448e93da65ff10142a98176cebe9b
|
publishconf.py
|
publishconf.py
|
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://pappasam.github.io'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False
DISQUS_SITENAME = "pappasam-github-io"
GOOGLE_ANALYTICS = "UA-117115805-1"
|
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://softwarejourneyman.com'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False
DISQUS_SITENAME = "pappasam-github-io"
GOOGLE_ANALYTICS = "UA-117115805-1"
|
Change publish site to softwarejourneyman.com
|
Change publish site to softwarejourneyman.com
|
Python
|
mit
|
pappasam/pappasam.github.io,pappasam/pappasam.github.io
|
python
|
## Code Before:
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://pappasam.github.io'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False
DISQUS_SITENAME = "pappasam-github-io"
GOOGLE_ANALYTICS = "UA-117115805-1"
## Instruction:
Change publish site to softwarejourneyman.com
## Code After:
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://softwarejourneyman.com'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False
DISQUS_SITENAME = "pappasam-github-io"
GOOGLE_ANALYTICS = "UA-117115805-1"
|
...
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'https://softwarejourneyman.com'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
...
|
3b9ae710816438e7cf20304c93e1b6e289bc4301
|
src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
|
src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
|
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(config: Config): List<Config.Entry<*>>
fun createStateEntries(config: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
|
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
fun createStateEntries(state: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
|
Improve plugin config method arg naming
|
Improve plugin config method arg naming
|
Kotlin
|
mit
|
BjoernPetersen/JMusicBot
|
kotlin
|
## Code Before:
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(config: Config): List<Config.Entry<*>>
fun createStateEntries(config: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
## Instruction:
Improve plugin config method arg naming
## Code After:
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
fun createStateEntries(state: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
|
// ... existing code ...
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
fun createStateEntries(state: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
// ... rest of the code ...
|
4e309e7f70760e400dc7150b34e7f86c4c5643b4
|
golddust/packages.py
|
golddust/packages.py
|
class Package:
"""A package managed by GoldDust"""
def __init__(self):
self.name = ""
self.version = ""
@property
def tarball(self):
"""The tarball file name for this package."""
return "{}-{}.tar.bz2".format(self.name, self.version)
@property
def sig_file(self):
"""The detached signature file name for this package."""
return "{}.sig".format(self.tarball)
class InstallScript:
"""Package pre/post install action script.
"""
def pre_install(self):
"""Called before any files are installed.
"""
pass
def post_install(self):
"""Called after files are installed.
"""
pass
|
class Package:
"""A package managed by GoldDust"""
def __init__(self):
self.name = ""
self.version = ""
@property
def tarball(self):
"""The tarball file name for this package."""
return "{}-{}.tar.bz2".format(self.name, self.version)
@property
def sig_file(self):
"""The detached signature file name for this package."""
return "{}.sig".format(self.tarball)
class InstallScript:
"""Package pre/post install action script.
These functions are used to perform extra work beyond extracting
files.
Note that JAR modification should only be done using the `munge_jar`
function. This lets GoldDust know that you're modifying the JAR so it
can properly handle other JAR mod packages as well.
"""
def pre_install(self):
"""Called before any files are installed.
"""
pass
def munge_jar(self, jar):
"""Modify the Minecraft JAR file.
"""
pass
def post_install(self):
"""Called after files are installed.
"""
pass
|
Add munge_jar stub for InstallScript
|
Add munge_jar stub for InstallScript
|
Python
|
apache-2.0
|
Packeteers/GoldDust
|
python
|
## Code Before:
class Package:
"""A package managed by GoldDust"""
def __init__(self):
self.name = ""
self.version = ""
@property
def tarball(self):
"""The tarball file name for this package."""
return "{}-{}.tar.bz2".format(self.name, self.version)
@property
def sig_file(self):
"""The detached signature file name for this package."""
return "{}.sig".format(self.tarball)
class InstallScript:
"""Package pre/post install action script.
"""
def pre_install(self):
"""Called before any files are installed.
"""
pass
def post_install(self):
"""Called after files are installed.
"""
pass
## Instruction:
Add munge_jar stub for InstallScript
## Code After:
class Package:
"""A package managed by GoldDust"""
def __init__(self):
self.name = ""
self.version = ""
@property
def tarball(self):
"""The tarball file name for this package."""
return "{}-{}.tar.bz2".format(self.name, self.version)
@property
def sig_file(self):
"""The detached signature file name for this package."""
return "{}.sig".format(self.tarball)
class InstallScript:
"""Package pre/post install action script.
These functions are used to perform extra work beyond extracting
files.
Note that JAR modification should only be done using the `munge_jar`
function. This lets GoldDust know that you're modifying the JAR so it
can properly handle other JAR mod packages as well.
"""
def pre_install(self):
"""Called before any files are installed.
"""
pass
def munge_jar(self, jar):
"""Modify the Minecraft JAR file.
"""
pass
def post_install(self):
"""Called after files are installed.
"""
pass
|
// ... existing code ...
class InstallScript:
"""Package pre/post install action script.
These functions are used to perform extra work beyond extracting
files.
Note that JAR modification should only be done using the `munge_jar`
function. This lets GoldDust know that you're modifying the JAR so it
can properly handle other JAR mod packages as well.
"""
def pre_install(self):
"""Called before any files are installed.
"""
pass
def munge_jar(self, jar):
"""Modify the Minecraft JAR file.
"""
pass
// ... rest of the code ...
|
3e66c6546eda367bfef4038a4bb512862a9dd01f
|
config.py
|
config.py
|
DOMAIN = 'studyindenmark-newscontrol.appspot.com'
MAIL_SENDER = "Per Thulin <[email protected]>"
|
DOMAIN = 'studyindenmark-newscontrol.appspot.com'
MAIL_SENDER = "Study in Denmark <[email protected]>"
|
Change email sender to [email protected]
|
Change email sender to [email protected]
|
Python
|
mit
|
studyindenmark/newscontrol,youtify/newscontrol,studyindenmark/newscontrol,youtify/newscontrol
|
python
|
## Code Before:
DOMAIN = 'studyindenmark-newscontrol.appspot.com'
MAIL_SENDER = "Per Thulin <[email protected]>"
## Instruction:
Change email sender to [email protected]
## Code After:
DOMAIN = 'studyindenmark-newscontrol.appspot.com'
MAIL_SENDER = "Study in Denmark <[email protected]>"
|
# ... existing code ...
DOMAIN = 'studyindenmark-newscontrol.appspot.com'
MAIL_SENDER = "Study in Denmark <[email protected]>"
# ... rest of the code ...
|
d239ac7241e61e35f8e9e7ce60a8a8735944028e
|
app/__init__.py
|
app/__init__.py
|
''' FAB CITY - VISUALIZAR 2016
--------------------------------------------
A web application powered by Flask and d3.js
to generate networks/datavisualisations
------------------------------------------
licence CC : BY - SA
---------------------------------------------
project by :
- FABLAB BARCELONA
- PING
developpers :
- Massimo M
- Mariana Q
- Julien P
with the support of :
MediaLab Prado - Visualizar 2016
---------------------------------------------
'''
from flask import Flask
import os
from .scripts.app_vars import static_dir ### custom static directory
app = Flask(__name__) ### default call
#app = Flask(__name__, static_path = static_dir ) ### change static directory adress to custom for Flask
from app import views
|
'''FAB CITY DASHBOARD - VISUALIZAR'16
--------------------------------------------
A dashboard for all the Fab Cities where citizens can understand the existing resilience of cities and how the Maker movement is having an impact on this.
------------------------------------------
license: AGPL 3.0
---------------------------------------------
A project by: IAAC | Fab Lab Barcelona - Fab City Research Lab from the Fab City Global discussions.
Proposed at Visualizar'16 at Medialab Prado: http://fablabbcn.org/news/2016/05/12/visualizar.html
Participants at Visualizar'16:
- Massimo Menichinelli (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Mariana Quintero (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Julien Paris (PING)
---------------------------------------------
'''
from flask import Flask
import os
from .scripts.app_vars import static_dir ### custom static directory
app = Flask(__name__) ### default call
#app = Flask(__name__, static_path = static_dir ) ### change static directory adress to custom for Flask
from app import views
|
Update info about the project
|
Update info about the project
|
Python
|
agpl-3.0
|
rubenlorenzo/fab-city-dashboard,rubenlorenzo/fab-city-dashboard,rubenlorenzo/fab-city-dashboard
|
python
|
## Code Before:
''' FAB CITY - VISUALIZAR 2016
--------------------------------------------
A web application powered by Flask and d3.js
to generate networks/datavisualisations
------------------------------------------
licence CC : BY - SA
---------------------------------------------
project by :
- FABLAB BARCELONA
- PING
developpers :
- Massimo M
- Mariana Q
- Julien P
with the support of :
MediaLab Prado - Visualizar 2016
---------------------------------------------
'''
from flask import Flask
import os
from .scripts.app_vars import static_dir ### custom static directory
app = Flask(__name__) ### default call
#app = Flask(__name__, static_path = static_dir ) ### change static directory adress to custom for Flask
from app import views
## Instruction:
Update info about the project
## Code After:
'''FAB CITY DASHBOARD - VISUALIZAR'16
--------------------------------------------
A dashboard for all the Fab Cities where citizens can understand the existing resilience of cities and how the Maker movement is having an impact on this.
------------------------------------------
license: AGPL 3.0
---------------------------------------------
A project by: IAAC | Fab Lab Barcelona - Fab City Research Lab from the Fab City Global discussions.
Proposed at Visualizar'16 at Medialab Prado: http://fablabbcn.org/news/2016/05/12/visualizar.html
Participants at Visualizar'16:
- Massimo Menichinelli (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Mariana Quintero (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Julien Paris (PING)
---------------------------------------------
'''
from flask import Flask
import os
from .scripts.app_vars import static_dir ### custom static directory
app = Flask(__name__) ### default call
#app = Flask(__name__, static_path = static_dir ) ### change static directory adress to custom for Flask
from app import views
|
...
'''FAB CITY DASHBOARD - VISUALIZAR'16
--------------------------------------------
A dashboard for all the Fab Cities where citizens can understand the existing resilience of cities and how the Maker movement is having an impact on this.
------------------------------------------
license: AGPL 3.0
---------------------------------------------
A project by: IAAC | Fab Lab Barcelona - Fab City Research Lab from the Fab City Global discussions.
Proposed at Visualizar'16 at Medialab Prado: http://fablabbcn.org/news/2016/05/12/visualizar.html
Participants at Visualizar'16:
- Massimo Menichinelli (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Mariana Quintero (IAAC | Fab Lab Barcelona - Fab City Research Lab)
- Julien Paris (PING)
---------------------------------------------
'''
...
from flask import Flask
import os
from .scripts.app_vars import static_dir ### custom static directory
app = Flask(__name__) ### default call
#app = Flask(__name__, static_path = static_dir ) ### change static directory adress to custom for Flask
from app import views
...
|
e526ebe84159bde0be325ec561cc728ab7c0daee
|
src/zeit/edit/testing.py
|
src/zeit/edit/testing.py
|
import gocept.lxml.interfaces
import gocept.selenium.ztk
import grokcore.component as grok
import zeit.cms.testing
import zeit.edit.container
import zeit.edit.interfaces
ZCML_LAYER = zeit.cms.testing.ZCMLLayer('ftesting.zcml')
SELENIUM_LAYER = gocept.selenium.ztk.Layer(ZCML_LAYER)
class FunctionalTestCase(zeit.cms.testing.FunctionalTestCase):
layer = ZCML_LAYER
class SeleniumTestCase(zeit.cms.testing.SeleniumTestCase):
layer = SELENIUM_LAYER
class IContainer(zeit.edit.interfaces.IArea,
zeit.edit.interfaces.IBlock):
pass
class IBlock(zeit.edit.interfaces.IBlock):
pass
class Container(zeit.edit.container.TypeOnAttributeContainer,
grok.MultiAdapter):
grok.implements(IContainer)
grok.provides(IContainer)
grok.adapts(
IContainer,
gocept.lxml.interfaces.IObjectified)
grok.name('container')
zeit.edit.block.register_element_factory(IContainer, 'container', 'Container')
class Block(zeit.edit.block.SimpleElement):
area = IContainer
grok.implements(IBlock)
type = 'block'
zeit.edit.block.register_element_factory(IContainer, 'block', 'Block')
|
import gocept.lxml.interfaces
import gocept.selenium.ztk
import grokcore.component as grok
import zeit.cms.testing
import zeit.edit.container
import zeit.edit.interfaces
ZCML_LAYER = zeit.cms.testing.ZCMLLayer('ftesting.zcml')
SELENIUM_LAYER = gocept.selenium.ztk.Layer(ZCML_LAYER)
class FunctionalTestCase(zeit.cms.testing.FunctionalTestCase):
layer = ZCML_LAYER
class SeleniumTestCase(zeit.cms.testing.SeleniumTestCase):
layer = SELENIUM_LAYER
skin = 'vivi'
class IContainer(zeit.edit.interfaces.IArea,
zeit.edit.interfaces.IBlock):
pass
class IBlock(zeit.edit.interfaces.IBlock):
pass
class Container(zeit.edit.container.TypeOnAttributeContainer,
grok.MultiAdapter):
grok.implements(IContainer)
grok.provides(IContainer)
grok.adapts(
IContainer,
gocept.lxml.interfaces.IObjectified)
grok.name('container')
zeit.edit.block.register_element_factory(IContainer, 'container', 'Container')
class Block(zeit.edit.block.SimpleElement):
area = IContainer
grok.implements(IBlock)
type = 'block'
zeit.edit.block.register_element_factory(IContainer, 'block', 'Block')
|
Use vivi-Layer since the editor resides on that
|
Use vivi-Layer since the editor resides on that
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.edit,ZeitOnline/zeit.edit,ZeitOnline/zeit.edit
|
python
|
## Code Before:
import gocept.lxml.interfaces
import gocept.selenium.ztk
import grokcore.component as grok
import zeit.cms.testing
import zeit.edit.container
import zeit.edit.interfaces
ZCML_LAYER = zeit.cms.testing.ZCMLLayer('ftesting.zcml')
SELENIUM_LAYER = gocept.selenium.ztk.Layer(ZCML_LAYER)
class FunctionalTestCase(zeit.cms.testing.FunctionalTestCase):
layer = ZCML_LAYER
class SeleniumTestCase(zeit.cms.testing.SeleniumTestCase):
layer = SELENIUM_LAYER
class IContainer(zeit.edit.interfaces.IArea,
zeit.edit.interfaces.IBlock):
pass
class IBlock(zeit.edit.interfaces.IBlock):
pass
class Container(zeit.edit.container.TypeOnAttributeContainer,
grok.MultiAdapter):
grok.implements(IContainer)
grok.provides(IContainer)
grok.adapts(
IContainer,
gocept.lxml.interfaces.IObjectified)
grok.name('container')
zeit.edit.block.register_element_factory(IContainer, 'container', 'Container')
class Block(zeit.edit.block.SimpleElement):
area = IContainer
grok.implements(IBlock)
type = 'block'
zeit.edit.block.register_element_factory(IContainer, 'block', 'Block')
## Instruction:
Use vivi-Layer since the editor resides on that
## Code After:
import gocept.lxml.interfaces
import gocept.selenium.ztk
import grokcore.component as grok
import zeit.cms.testing
import zeit.edit.container
import zeit.edit.interfaces
ZCML_LAYER = zeit.cms.testing.ZCMLLayer('ftesting.zcml')
SELENIUM_LAYER = gocept.selenium.ztk.Layer(ZCML_LAYER)
class FunctionalTestCase(zeit.cms.testing.FunctionalTestCase):
layer = ZCML_LAYER
class SeleniumTestCase(zeit.cms.testing.SeleniumTestCase):
layer = SELENIUM_LAYER
skin = 'vivi'
class IContainer(zeit.edit.interfaces.IArea,
zeit.edit.interfaces.IBlock):
pass
class IBlock(zeit.edit.interfaces.IBlock):
pass
class Container(zeit.edit.container.TypeOnAttributeContainer,
grok.MultiAdapter):
grok.implements(IContainer)
grok.provides(IContainer)
grok.adapts(
IContainer,
gocept.lxml.interfaces.IObjectified)
grok.name('container')
zeit.edit.block.register_element_factory(IContainer, 'container', 'Container')
class Block(zeit.edit.block.SimpleElement):
area = IContainer
grok.implements(IBlock)
type = 'block'
zeit.edit.block.register_element_factory(IContainer, 'block', 'Block')
|
// ... existing code ...
class SeleniumTestCase(zeit.cms.testing.SeleniumTestCase):
layer = SELENIUM_LAYER
skin = 'vivi'
class IContainer(zeit.edit.interfaces.IArea,
// ... rest of the code ...
|
31c921f0f88df5bc532db0f326ba9ef53318feb9
|
codejail/django_integration.py
|
codejail/django_integration.py
|
"""Django integration for codejail"""
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
import codejail.jail_code
class ConfigureCodeJailMiddleware(object):
"""Middleware to configure codejail on startup."""
def __init__(self):
python_bin = settings.CODE_JAIL.get('python_bin')
if python_bin:
user = settings.CODE_JAIL['user']
codejail.jail_code.configure("python", python_bin, user=user)
raise MiddlewareNotUsed
|
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
import codejail.jail_code
class ConfigureCodeJailMiddleware(object):
"""
Middleware to configure codejail on startup.
This is a Django idiom to have code run once on server startup: put the
code in the `__init__` of some middleware, and have it do the work, then
raise `MiddlewareNotUsed` to disable the middleware.
"""
def __init__(self):
python_bin = settings.CODE_JAIL.get('python_bin')
if python_bin:
user = settings.CODE_JAIL['user']
codejail.jail_code.configure("python", python_bin, user=user)
raise MiddlewareNotUsed
|
Add more detail in docstring
|
Add more detail in docstring
|
Python
|
agpl-3.0
|
StepicOrg/codejail,edx/codejail
|
python
|
## Code Before:
"""Django integration for codejail"""
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
import codejail.jail_code
class ConfigureCodeJailMiddleware(object):
"""Middleware to configure codejail on startup."""
def __init__(self):
python_bin = settings.CODE_JAIL.get('python_bin')
if python_bin:
user = settings.CODE_JAIL['user']
codejail.jail_code.configure("python", python_bin, user=user)
raise MiddlewareNotUsed
## Instruction:
Add more detail in docstring
## Code After:
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
import codejail.jail_code
class ConfigureCodeJailMiddleware(object):
"""
Middleware to configure codejail on startup.
This is a Django idiom to have code run once on server startup: put the
code in the `__init__` of some middleware, and have it do the work, then
raise `MiddlewareNotUsed` to disable the middleware.
"""
def __init__(self):
python_bin = settings.CODE_JAIL.get('python_bin')
if python_bin:
user = settings.CODE_JAIL['user']
codejail.jail_code.configure("python", python_bin, user=user)
raise MiddlewareNotUsed
|
...
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
...
class ConfigureCodeJailMiddleware(object):
"""
Middleware to configure codejail on startup.
This is a Django idiom to have code run once on server startup: put the
code in the `__init__` of some middleware, and have it do the work, then
raise `MiddlewareNotUsed` to disable the middleware.
"""
def __init__(self):
python_bin = settings.CODE_JAIL.get('python_bin')
if python_bin:
...
|
4b8de0203d2eec87c2d05c3521df8af3365f73a4
|
IPython/testing/nose_assert_methods.py
|
IPython/testing/nose_assert_methods.py
|
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
|
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
def assert_not_in(item, collection):
assert item not in collection, '%r in %r' % (item, collection)
if not hasattr(nt, 'assert_not_in'):
nt.assert_not_in = assert_not_in
|
Add assert_not_in method for Python2.6
|
Add assert_not_in method for Python2.6
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
python
|
## Code Before:
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
## Instruction:
Add assert_not_in method for Python2.6
## Code After:
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
def assert_not_in(item, collection):
assert item not in collection, '%r in %r' % (item, collection)
if not hasattr(nt, 'assert_not_in'):
nt.assert_not_in = assert_not_in
|
# ... existing code ...
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
def assert_not_in(item, collection):
assert item not in collection, '%r in %r' % (item, collection)
if not hasattr(nt, 'assert_not_in'):
nt.assert_not_in = assert_not_in
# ... rest of the code ...
|
efc857403d3c67589c1046d60e7f91132c844393
|
picdescbot/twitter.py
|
picdescbot/twitter.py
|
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
Add source links for tweets
|
Add source links for tweets
|
Python
|
mit
|
elad661/picdescbot
|
python
|
## Code Before:
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
## Instruction:
Add source links for tweets
## Code After:
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
# ... existing code ...
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
# ... rest of the code ...
|
e1e60f6c518274907d2331e7b6aadac7c7dbec3d
|
src/test/java/com/github/legioth/propertysource/rebind/StringTypeHandlerTest.java
|
src/test/java/com/github/legioth/propertysource/rebind/StringTypeHandlerTest.java
|
package com.github.legioth.propertysource.rebind;
import com.google.gwt.user.rebind.StringSourceWriter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class StringTypeHandlerTest
{
@DataProvider( name = "writeValues" )
public Object[][] actionDescriptions()
{
return new Object[][]{
new Object[]{ "hi", "\"hi\"" },
new Object[]{ "1\n2", "\"1\\n2\"" },
new Object[]{ "&", "\"&\"" },
new Object[]{ "Å", "\"Å\"" },
};
}
@Test( dataProvider = "writeValues" )
public void writeValues( final String input, final String output )
{
final StringSourceWriter writer = new StringSourceWriter();
StringTypeHandler.INSTANCE.writeValue( null, writer, input );
assertEquals( writer.toString(), output );
}
}
|
package com.github.legioth.propertysource.rebind;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.user.rebind.StringSourceWriter;
import java.util.Arrays;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class StringTypeHandlerTest
{
@DataProvider( name = "writeValues" )
public Object[][] actionDescriptions()
{
return new Object[][]{
new Object[]{ "hi", "\"hi\"" },
new Object[]{ "1\n2", "\"1\\n2\"" },
new Object[]{ "&", "\"&\"" },
new Object[]{ "Å", "\"Å\"" },
};
}
@Test( dataProvider = "writeValues" )
public void writeValues( final String input, final String output )
{
final StringSourceWriter writer = new StringSourceWriter();
StringTypeHandler.INSTANCE.writeValue( null, writer, input );
assertEquals( writer.toString(), output );
}
@Test
public void getStaticReturnValue()
throws Exception
{
final String result =
StringTypeHandler.INSTANCE.getStaticReturnValue( mock( TreeLogger.class ),
Arrays.asList( "A" ),
mock( JMethod.class ) );
assertEquals( result, "A" );
}
@Test
public void getStaticReturnValue_whenMultipleValues()
throws Exception
{
final TreeLogger logger = mock( TreeLogger.class );
try
{
StringTypeHandler.INSTANCE.getStaticReturnValue( logger,
Arrays.asList( "A", "B" ),
mock( JMethod.class ) );
fail( "Should have raised an exception" );
}
catch ( final UnableToCompleteException utce )
{
verify( logger ).log( Type.ERROR, "String only supported for properties with only one value" );
}
}
}
|
Add some more basic tests
|
Add some more basic tests
|
Java
|
apache-2.0
|
realityforge/gwt-property-source,realityforge/gwt-property-source
|
java
|
## Code Before:
package com.github.legioth.propertysource.rebind;
import com.google.gwt.user.rebind.StringSourceWriter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class StringTypeHandlerTest
{
@DataProvider( name = "writeValues" )
public Object[][] actionDescriptions()
{
return new Object[][]{
new Object[]{ "hi", "\"hi\"" },
new Object[]{ "1\n2", "\"1\\n2\"" },
new Object[]{ "&", "\"&\"" },
new Object[]{ "Å", "\"Å\"" },
};
}
@Test( dataProvider = "writeValues" )
public void writeValues( final String input, final String output )
{
final StringSourceWriter writer = new StringSourceWriter();
StringTypeHandler.INSTANCE.writeValue( null, writer, input );
assertEquals( writer.toString(), output );
}
}
## Instruction:
Add some more basic tests
## Code After:
package com.github.legioth.propertysource.rebind;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.user.rebind.StringSourceWriter;
import java.util.Arrays;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class StringTypeHandlerTest
{
@DataProvider( name = "writeValues" )
public Object[][] actionDescriptions()
{
return new Object[][]{
new Object[]{ "hi", "\"hi\"" },
new Object[]{ "1\n2", "\"1\\n2\"" },
new Object[]{ "&", "\"&\"" },
new Object[]{ "Å", "\"Å\"" },
};
}
@Test( dataProvider = "writeValues" )
public void writeValues( final String input, final String output )
{
final StringSourceWriter writer = new StringSourceWriter();
StringTypeHandler.INSTANCE.writeValue( null, writer, input );
assertEquals( writer.toString(), output );
}
@Test
public void getStaticReturnValue()
throws Exception
{
final String result =
StringTypeHandler.INSTANCE.getStaticReturnValue( mock( TreeLogger.class ),
Arrays.asList( "A" ),
mock( JMethod.class ) );
assertEquals( result, "A" );
}
@Test
public void getStaticReturnValue_whenMultipleValues()
throws Exception
{
final TreeLogger logger = mock( TreeLogger.class );
try
{
StringTypeHandler.INSTANCE.getStaticReturnValue( logger,
Arrays.asList( "A", "B" ),
mock( JMethod.class ) );
fail( "Should have raised an exception" );
}
catch ( final UnableToCompleteException utce )
{
verify( logger ).log( Type.ERROR, "String only supported for properties with only one value" );
}
}
}
|
...
package com.github.legioth.propertysource.rebind;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.user.rebind.StringSourceWriter;
import java.util.Arrays;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class StringTypeHandlerTest
...
StringTypeHandler.INSTANCE.writeValue( null, writer, input );
assertEquals( writer.toString(), output );
}
@Test
public void getStaticReturnValue()
throws Exception
{
final String result =
StringTypeHandler.INSTANCE.getStaticReturnValue( mock( TreeLogger.class ),
Arrays.asList( "A" ),
mock( JMethod.class ) );
assertEquals( result, "A" );
}
@Test
public void getStaticReturnValue_whenMultipleValues()
throws Exception
{
final TreeLogger logger = mock( TreeLogger.class );
try
{
StringTypeHandler.INSTANCE.getStaticReturnValue( logger,
Arrays.asList( "A", "B" ),
mock( JMethod.class ) );
fail( "Should have raised an exception" );
}
catch ( final UnableToCompleteException utce )
{
verify( logger ).log( Type.ERROR, "String only supported for properties with only one value" );
}
}
}
...
|
9d0e9af5844772c18ca24d4012642d4518b66dfc
|
tests/test_judicious.py
|
tests/test_judicious.py
|
"""Tests for `judicious` package."""
import pytest
import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
"""Tests for `judicious` package."""
import random
import pytest
import judicious
def test_seeding():
r1 = random.random()
r2 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r3 = random.random()
r4 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r5 = random.random()
r6 = random.random()
judicious.seed()
r7 = random.random()
r8 = random.random()
assert(r1 != r3)
assert(r2 != r4)
assert(r3 == r5)
assert(r4 == r6)
assert(r5 != r7)
assert(r6 != r8)
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
Add test of seeding PRNG
|
Add test of seeding PRNG
|
Python
|
mit
|
suchow/judicious,suchow/judicious,suchow/judicious
|
python
|
## Code Before:
"""Tests for `judicious` package."""
import pytest
import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
## Instruction:
Add test of seeding PRNG
## Code After:
"""Tests for `judicious` package."""
import random
import pytest
import judicious
def test_seeding():
r1 = random.random()
r2 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r3 = random.random()
r4 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r5 = random.random()
r6 = random.random()
judicious.seed()
r7 = random.random()
r8 = random.random()
assert(r1 != r3)
assert(r2 != r4)
assert(r3 == r5)
assert(r4 == r6)
assert(r5 != r7)
assert(r6 != r8)
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
// ... existing code ...
"""Tests for `judicious` package."""
import random
import pytest
import judicious
def test_seeding():
r1 = random.random()
r2 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r3 = random.random()
r4 = random.random()
judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff")
r5 = random.random()
r6 = random.random()
judicious.seed()
r7 = random.random()
r8 = random.random()
assert(r1 != r3)
assert(r2 != r4)
assert(r3 == r5)
assert(r4 == r6)
assert(r5 != r7)
assert(r6 != r8)
@pytest.fixture
// ... rest of the code ...
|
fefab5f18cdd166e9abab5d5652cdc7645f2d6ae
|
hbase/setup.py
|
hbase/setup.py
|
from setuptools import setup
setup(name='hbase',
version='0.0a1',
author='Thomas Bach')
|
from setuptools import setup
import sys
PY_VERSION = sys.version_info[:2]
tests_require = ['mock']
if PY_VERSION == (2, 6):
tests_require.append('unittest2')
setup(name='hbase',
version='0.0a1',
author='Thomas Bach',
tests_require=tests_require,
test_suite='hbase.tests')
|
Revert "don't know how to test these things"
|
Revert "don't know how to test these things"
This reverts commit a3e1d48b426000bc182265db336a907f3df4996d.
|
Python
|
bsd-3-clause
|
fuzzy-id/midas,fuzzy-id/midas,fuzzy-id/midas
|
python
|
## Code Before:
from setuptools import setup
setup(name='hbase',
version='0.0a1',
author='Thomas Bach')
## Instruction:
Revert "don't know how to test these things"
This reverts commit a3e1d48b426000bc182265db336a907f3df4996d.
## Code After:
from setuptools import setup
import sys
PY_VERSION = sys.version_info[:2]
tests_require = ['mock']
if PY_VERSION == (2, 6):
tests_require.append('unittest2')
setup(name='hbase',
version='0.0a1',
author='Thomas Bach',
tests_require=tests_require,
test_suite='hbase.tests')
|
...
from setuptools import setup
import sys
PY_VERSION = sys.version_info[:2]
tests_require = ['mock']
if PY_VERSION == (2, 6):
tests_require.append('unittest2')
setup(name='hbase',
version='0.0a1',
author='Thomas Bach',
tests_require=tests_require,
test_suite='hbase.tests')
...
|
9b18cc62dc0338a9dff6ae7dd448a4dca960c941
|
accounts/forms.py
|
accounts/forms.py
|
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
token = LoginTokenGenerator().make_token(email)
return '{}://{}/login/{}'.format(protocol, domain, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
|
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
url = reverse_lazy('login')
token = LoginTokenGenerator().make_token(email)
return '{}://{}{}?token={}'.format(protocol, domain, url, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
|
Add the token as a get parameter
|
Add the token as a get parameter
|
Python
|
mit
|
randomic/aniauth-tdd,randomic/aniauth-tdd
|
python
|
## Code Before:
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
token = LoginTokenGenerator().make_token(email)
return '{}://{}/login/{}'.format(protocol, domain, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
## Instruction:
Add the token as a get parameter
## Code After:
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
url = reverse_lazy('login')
token = LoginTokenGenerator().make_token(email)
return '{}://{}{}?token={}'.format(protocol, domain, url, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
|
// ... existing code ...
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
// ... modified code ...
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
url = reverse_lazy('login')
token = LoginTokenGenerator().make_token(email)
return '{}://{}{}?token={}'.format(protocol, domain, url, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
// ... rest of the code ...
|
5531f188c7bf3030cb9fc3b46d92a1db60817b7c
|
confirmation/views.py
|
confirmation/views.py
|
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
|
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
'key': confirmation_key,
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
|
Include confirmation key in context object.
|
Include confirmation key in context object.
This way our templates can reference the confirmation key later.
(imported from commit 4d57e1309386f2236829b6fdf4e4ad43c5b125c8)
|
Python
|
apache-2.0
|
schatt/zulip,deer-hope/zulip,PaulPetring/zulip,adnanh/zulip,jeffcao/zulip,hafeez3000/zulip,fw1121/zulip,KJin99/zulip,ufosky-server/zulip,mahim97/zulip,dhcrzf/zulip,dawran6/zulip,firstblade/zulip,akuseru/zulip,eastlhu/zulip,showell/zulip,dawran6/zulip,vikas-parashar/zulip,esander91/zulip,eastlhu/zulip,so0k/zulip,johnny9/zulip,amallia/zulip,sharmaeklavya2/zulip,mansilladev/zulip,krtkmj/zulip,dawran6/zulip,proliming/zulip,rht/zulip,jackrzhang/zulip,noroot/zulip,eastlhu/zulip,deer-hope/zulip,firstblade/zulip,wweiradio/zulip,jackrzhang/zulip,punchagan/zulip,peiwei/zulip,showell/zulip,Cheppers/zulip,guiquanz/zulip,seapasulli/zulip,hackerkid/zulip,jrowan/zulip,ipernet/zulip,dotcool/zulip,esander91/zulip,kou/zulip,Galexrt/zulip,nicholasbs/zulip,PhilSk/zulip,zwily/zulip,mdavid/zulip,amanharitsh123/zulip,Drooids/zulip,kokoar/zulip,karamcnair/zulip,stamhe/zulip,easyfmxu/zulip,PaulPetring/zulip,sharmaeklavya2/zulip,ahmadassaf/zulip,saitodisse/zulip,levixie/zulip,arpith/zulip,Drooids/zulip,zwily/zulip,gigawhitlocks/zulip,Drooids/zulip,dxq-git/zulip,swinghu/zulip,jonesgithub/zulip,thomasboyt/zulip,itnihao/zulip,dwrpayne/zulip,ashwinirudrappa/zulip,armooo/zulip,jimmy54/zulip,jessedhillon/zulip,LeeRisk/zulip,samatdav/zulip,zorojean/zulip,proliming/zulip,jerryge/zulip,fw1121/zulip,Suninus/zulip,ryanbackman/zulip,andersk/zulip,luyifan/zulip,pradiptad/zulip,joshisa/zulip,swinghu/zulip,armooo/zulip,grave-w-grave/zulip,Suninus/zulip,udxxabp/zulip,firstblade/zulip,akuseru/zulip,shubhamdhama/zulip,atomic-labs/zulip,bluesea/zulip,AZtheAsian/zulip,rht/zulip,hayderimran7/zulip,akuseru/zulip,peiwei/zulip,codeKonami/zulip,jerryge/zulip,fw1121/zulip,kou/zulip,shaunstanislaus/zulip,johnnygaddarr/zulip,kokoar/zulip,Frouk/zulip,samatdav/zulip,hackerkid/zulip,Frouk/zulip,saitodisse/zulip,hackerkid/zulip,lfranchi/zulip,ApsOps/zulip,sonali0901/zulip,voidException/zulip,atomic-labs/zulip,zachallaun/zulip,wdaher/zulip,noroot/zulip,zulip/zulip,xuxiao/zulip,gigawhitlocks/zulip,hackerkid/zulip,Vallher/zulip,susansls/zulip,reyha/zulip,paxapy/zulip,ryansnowboarder/zulip,xuxiao/zulip,ahmadassaf/zulip,dattatreya303/zulip,rht/zulip,shubhamdhama/zulip,jainayush975/zulip,noroot/zulip,TigorC/zulip,vabs22/zulip,luyifan/zulip,synicalsyntax/zulip,lfranchi/zulip,dwrpayne/zulip,kaiyuanheshang/zulip,dnmfarrell/zulip,kokoar/zulip,moria/zulip,jainayush975/zulip,thomasboyt/zulip,j831/zulip,wangdeshui/zulip,timabbott/zulip,levixie/zulip,vakila/zulip,akuseru/zulip,m1ssou/zulip,luyifan/zulip,bssrdf/zulip,johnnygaddarr/zulip,punchagan/zulip,vabs22/zulip,sharmaeklavya2/zulip,amallia/zulip,schatt/zulip,qq1012803704/zulip,wweiradio/zulip,showell/zulip,deer-hope/zulip,zachallaun/zulip,christi3k/zulip,Qgap/zulip,christi3k/zulip,zwily/zulip,schatt/zulip,MariaFaBella85/zulip,peguin40/zulip,ryanbackman/zulip,babbage/zulip,natanovia/zulip,wdaher/zulip,jeffcao/zulip,noroot/zulip,he15his/zulip,TigorC/zulip,babbage/zulip,tbutter/zulip,wavelets/zulip,developerfm/zulip,hj3938/zulip,sup95/zulip,wdaher/zulip,samatdav/zulip,mohsenSy/zulip,jerryge/zulip,huangkebo/zulip,adnanh/zulip,mansilladev/zulip,shaunstanislaus/zulip,Frouk/zulip,Juanvulcano/zulip,hj3938/zulip,Drooids/zulip,levixie/zulip,qq1012803704/zulip,ryanbackman/zulip,TigorC/zulip,Gabriel0402/zulip,johnnygaddarr/zulip,stamhe/zulip,m1ssou/zulip,mahim97/zulip,mdavid/zulip,blaze225/zulip,glovebx/zulip,bluesea/zulip,jphilipsen05/zulip,nicholasbs/zulip,brockwhittaker/zulip,showell/zulip,sonali0901/zulip,sonali0901/zulip,bastianh/zulip,johnnygaddarr/zulip,udxxabp/zulip,Cheppers/zulip,amanharitsh123/zulip,deer-hope/zulip,alliejones/zulip,JPJPJPOPOP/zulip,lfranchi/zulip,Suninus/zulip,ryansnowboarder/zulip,babbage/zulip,KingxBanana/zulip,bitemyapp/zulip,shrikrishnaholla/zulip,sup95/zulip,so0k/zulip,dnmfarrell/zulip,Suninus/zulip,ikasumiwt/zulip,bowlofstew/zulip,tommyip/zulip,ApsOps/zulip,suxinde2009/zulip,suxinde2009/zulip,vaidap/zulip,akuseru/zulip,seapasulli/zulip,jeffcao/zulip,themass/zulip,Batterfii/zulip,zulip/zulip,ericzhou2008/zulip,vakila/zulip,Vallher/zulip,arpith/zulip,EasonYi/zulip,ryansnowboarder/zulip,willingc/zulip,eeshangarg/zulip,deer-hope/zulip,showell/zulip,itnihao/zulip,hayderimran7/zulip,shrikrishnaholla/zulip,technicalpickles/zulip,PhilSk/zulip,Qgap/zulip,kokoar/zulip,Qgap/zulip,sup95/zulip,tiansiyuan/zulip,aps-sids/zulip,karamcnair/zulip,Batterfii/zulip,bastianh/zulip,pradiptad/zulip,codeKonami/zulip,punchagan/zulip,dxq-git/zulip,ashwinirudrappa/zulip,samatdav/zulip,hackerkid/zulip,levixie/zulip,alliejones/zulip,stamhe/zulip,bluesea/zulip,DazWorrall/zulip,zachallaun/zulip,AZtheAsian/zulip,aliceriot/zulip,yuvipanda/zulip,Juanvulcano/zulip,shrikrishnaholla/zulip,arpith/zulip,ApsOps/zulip,zofuthan/zulip,zulip/zulip,zulip/zulip,seapasulli/zulip,arpitpanwar/zulip,ericzhou2008/zulip,thomasboyt/zulip,amyliu345/zulip,hayderimran7/zulip,willingc/zulip,hafeez3000/zulip,ashwinirudrappa/zulip,aps-sids/zulip,MayB/zulip,yocome/zulip,mahim97/zulip,ikasumiwt/zulip,tbutter/zulip,samatdav/zulip,blaze225/zulip,kou/zulip,cosmicAsymmetry/zulip,ipernet/zulip,ericzhou2008/zulip,MariaFaBella85/zulip,KJin99/zulip,joshisa/zulip,ufosky-server/zulip,seapasulli/zulip,andersk/zulip,niftynei/zulip,JanzTam/zulip,Suninus/zulip,suxinde2009/zulip,eeshangarg/zulip,vabs22/zulip,rishig/zulip,tommyip/zulip,dwrpayne/zulip,seapasulli/zulip,tommyip/zulip,bowlofstew/zulip,souravbadami/zulip,synicalsyntax/zulip,saitodisse/zulip,ikasumiwt/zulip,aakash-cr7/zulip,verma-varsha/zulip,timabbott/zulip,eeshangarg/zulip,seapasulli/zulip,pradiptad/zulip,timabbott/zulip,DazWorrall/zulip,vaidap/zulip,zacps/zulip,deer-hope/zulip,Cheppers/zulip,Galexrt/zulip,eastlhu/zulip,timabbott/zulip,glovebx/zulip,adnanh/zulip,vikas-parashar/zulip,ryansnowboarder/zulip,lfranchi/zulip,willingc/zulip,AZtheAsian/zulip,swinghu/zulip,fw1121/zulip,KingxBanana/zulip,wangdeshui/zulip,bitemyapp/zulip,verma-varsha/zulip,shrikrishnaholla/zulip,TigorC/zulip,Qgap/zulip,peguin40/zulip,nicholasbs/zulip,moria/zulip,firstblade/zulip,krtkmj/zulip,Juanvulcano/zulip,zachallaun/zulip,yuvipanda/zulip,natanovia/zulip,Juanvulcano/zulip,adnanh/zulip,suxinde2009/zulip,punchagan/zulip,j831/zulip,huangkebo/zulip,jeffcao/zulip,zhaoweigg/zulip,shrikrishnaholla/zulip,jeffcao/zulip,adnanh/zulip,eastlhu/zulip,firstblade/zulip,tommyip/zulip,huangkebo/zulip,bastianh/zulip,susansls/zulip,kaiyuanheshang/zulip,aps-sids/zulip,brainwane/zulip,zorojean/zulip,suxinde2009/zulip,niftynei/zulip,LeeRisk/zulip,MariaFaBella85/zulip,jerryge/zulip,developerfm/zulip,karamcnair/zulip,themass/zulip,MayB/zulip,hafeez3000/zulip,jackrzhang/zulip,so0k/zulip,gkotian/zulip,hengqujushi/zulip,itnihao/zulip,johnnygaddarr/zulip,LAndreas/zulip,rishig/zulip,amallia/zulip,avastu/zulip,yocome/zulip,proliming/zulip,Galexrt/zulip,stamhe/zulip,firstblade/zulip,dxq-git/zulip,bluesea/zulip,dxq-git/zulip,praveenaki/zulip,bluesea/zulip,xuanhan863/zulip,Frouk/zulip,ipernet/zulip,voidException/zulip,aps-sids/zulip,natanovia/zulip,karamcnair/zulip,peguin40/zulip,wavelets/zulip,bastianh/zulip,joshisa/zulip,jrowan/zulip,eeshangarg/zulip,huangkebo/zulip,Qgap/zulip,ufosky-server/zulip,DazWorrall/zulip,dawran6/zulip,proliming/zulip,avastu/zulip,PaulPetring/zulip,umkay/zulip,hafeez3000/zulip,zulip/zulip,susansls/zulip,jphilipsen05/zulip,vaidap/zulip,Frouk/zulip,proliming/zulip,souravbadami/zulip,amyliu345/zulip,Cheppers/zulip,verma-varsha/zulip,arpith/zulip,EasonYi/zulip,ashwinirudrappa/zulip,zachallaun/zulip,dwrpayne/zulip,zacps/zulip,johnny9/zulip,jimmy54/zulip,wdaher/zulip,cosmicAsymmetry/zulip,fw1121/zulip,ryansnowboarder/zulip,jonesgithub/zulip,mdavid/zulip,yuvipanda/zulip,johnny9/zulip,Cheppers/zulip,zorojean/zulip,tbutter/zulip,sonali0901/zulip,Juanvulcano/zulip,hustlzp/zulip,reyha/zulip,m1ssou/zulip,wavelets/zulip,wangdeshui/zulip,eeshangarg/zulip,guiquanz/zulip,schatt/zulip,saitodisse/zulip,JanzTam/zulip,verma-varsha/zulip,Jianchun1/zulip,esander91/zulip,johnny9/zulip,hengqujushi/zulip,yocome/zulip,vaidap/zulip,KingxBanana/zulip,natanovia/zulip,ikasumiwt/zulip,PaulPetring/zulip,AZtheAsian/zulip,aakash-cr7/zulip,j831/zulip,yuvipanda/zulip,armooo/zulip,hafeez3000/zulip,rishig/zulip,mohsenSy/zulip,mahim97/zulip,christi3k/zulip,Diptanshu8/zulip,littledogboy/zulip,he15his/zulip,dxq-git/zulip,guiquanz/zulip,peguin40/zulip,noroot/zulip,SmartPeople/zulip,technicalpickles/zulip,KJin99/zulip,umkay/zulip,wweiradio/zulip,hengqujushi/zulip,LAndreas/zulip,zulip/zulip,tiansiyuan/zulip,babbage/zulip,themass/zulip,Drooids/zulip,LeeRisk/zulip,jainayush975/zulip,TigorC/zulip,ikasumiwt/zulip,LAndreas/zulip,Cheppers/zulip,Gabriel0402/zulip,cosmicAsymmetry/zulip,joyhchen/zulip,mahim97/zulip,paxapy/zulip,kou/zulip,SmartPeople/zulip,zofuthan/zulip,AZtheAsian/zulip,wweiradio/zulip,dnmfarrell/zulip,vaidap/zulip,rishig/zulip,krtkmj/zulip,technicalpickles/zulip,brainwane/zulip,schatt/zulip,tdr130/zulip,andersk/zulip,amyliu345/zulip,karamcnair/zulip,jonesgithub/zulip,Vallher/zulip,ryanbackman/zulip,arpitpanwar/zulip,PaulPetring/zulip,synicalsyntax/zulip,akuseru/zulip,Suninus/zulip,EasonYi/zulip,umkay/zulip,joyhchen/zulip,alliejones/zulip,pradiptad/zulip,so0k/zulip,timabbott/zulip,arpith/zulip,hustlzp/zulip,blaze225/zulip,Vallher/zulip,johnny9/zulip,umkay/zulip,armooo/zulip,hayderimran7/zulip,aakash-cr7/zulip,littledogboy/zulip,punchagan/zulip,avastu/zulip,codeKonami/zulip,verma-varsha/zulip,PhilSk/zulip,dotcool/zulip,dattatreya303/zulip,tommyip/zulip,luyifan/zulip,rht/zulip,zhaoweigg/zulip,zacps/zulip,rht/zulip,joshisa/zulip,he15his/zulip,voidException/zulip,willingc/zulip,EasonYi/zulip,voidException/zulip,zwily/zulip,lfranchi/zulip,sonali0901/zulip,esander91/zulip,joshisa/zulip,souravbadami/zulip,esander91/zulip,RobotCaleb/zulip,praveenaki/zulip,Gabriel0402/zulip,amyliu345/zulip,zachallaun/zulip,swinghu/zulip,wangdeshui/zulip,synicalsyntax/zulip,brainwane/zulip,peiwei/zulip,arpitpanwar/zulip,punchagan/zulip,souravbadami/zulip,zorojean/zulip,AZtheAsian/zulip,zofuthan/zulip,xuanhan863/zulip,KingxBanana/zulip,saitodisse/zulip,Vallher/zulip,sup95/zulip,armooo/zulip,blaze225/zulip,showell/zulip,kaiyuanheshang/zulip,jessedhillon/zulip,ryanbackman/zulip,huangkebo/zulip,dhcrzf/zulip,arpitpanwar/zulip,ipernet/zulip,joyhchen/zulip,guiquanz/zulip,atomic-labs/zulip,amyliu345/zulip,KingxBanana/zulip,reyha/zulip,krtkmj/zulip,KJin99/zulip,johnny9/zulip,Cheppers/zulip,MayB/zulip,easyfmxu/zulip,esander91/zulip,themass/zulip,Juanvulcano/zulip,dotcool/zulip,so0k/zulip,amallia/zulip,souravbadami/zulip,voidException/zulip,DazWorrall/zulip,saitodisse/zulip,so0k/zulip,ApsOps/zulip,zhaoweigg/zulip,rishig/zulip,kou/zulip,tbutter/zulip,schatt/zulip,brockwhittaker/zulip,joshisa/zulip,hj3938/zulip,developerfm/zulip,aakash-cr7/zulip,ufosky-server/zulip,dxq-git/zulip,zacps/zulip,Qgap/zulip,grave-w-grave/zulip,fw1121/zulip,PhilSk/zulip,j831/zulip,christi3k/zulip,gigawhitlocks/zulip,hayderimran7/zulip,udxxabp/zulip,synicalsyntax/zulip,JPJPJPOPOP/zulip,paxapy/zulip,hustlzp/zulip,xuanhan863/zulip,ipernet/zulip,paxapy/zulip,glovebx/zulip,cosmicAsymmetry/zulip,grave-w-grave/zulip,amallia/zulip,mansilladev/zulip,mohsenSy/zulip,RobotCaleb/zulip,aakash-cr7/zulip,shaunstanislaus/zulip,Galexrt/zulip,jonesgithub/zulip,rht/zulip,easyfmxu/zulip,wangdeshui/zulip,eeshangarg/zulip,praveenaki/zulip,rishig/zulip,dnmfarrell/zulip,noroot/zulip,ApsOps/zulip,dwrpayne/zulip,zofuthan/zulip,xuxiao/zulip,zofuthan/zulip,yocome/zulip,guiquanz/zulip,mansilladev/zulip,easyfmxu/zulip,vikas-parashar/zulip,seapasulli/zulip,johnny9/zulip,ApsOps/zulip,ipernet/zulip,glovebx/zulip,thomasboyt/zulip,LeeRisk/zulip,sup95/zulip,reyha/zulip,eastlhu/zulip,he15his/zulip,amallia/zulip,zorojean/zulip,wweiradio/zulip,MariaFaBella85/zulip,mdavid/zulip,ufosky-server/zulip,zwily/zulip,JanzTam/zulip,jackrzhang/zulip,shaunstanislaus/zulip,JPJPJPOPOP/zulip,jonesgithub/zulip,tdr130/zulip,paxapy/zulip,jainayush975/zulip,kou/zulip,tdr130/zulip,hengqujushi/zulip,hj3938/zulip,dnmfarrell/zulip,shubhamdhama/zulip,ashwinirudrappa/zulip,synicalsyntax/zulip,bitemyapp/zulip,Gabriel0402/zulip,jimmy54/zulip,lfranchi/zulip,bitemyapp/zulip,Frouk/zulip,MayB/zulip,bastianh/zulip,technicalpickles/zulip,dotcool/zulip,voidException/zulip,ufosky-server/zulip,technicalpickles/zulip,Batterfii/zulip,willingc/zulip,reyha/zulip,ahmadassaf/zulip,gkotian/zulip,LAndreas/zulip,jessedhillon/zulip,EasonYi/zulip,ipernet/zulip,jrowan/zulip,vakila/zulip,gkotian/zulip,isht3/zulip,moria/zulip,dnmfarrell/zulip,gigawhitlocks/zulip,developerfm/zulip,bitemyapp/zulip,peiwei/zulip,ryanbackman/zulip,gigawhitlocks/zulip,niftynei/zulip,praveenaki/zulip,wweiradio/zulip,tbutter/zulip,nicholasbs/zulip,bssrdf/zulip,qq1012803704/zulip,ericzhou2008/zulip,wavelets/zulip,brainwane/zulip,ahmadassaf/zulip,RobotCaleb/zulip,huangkebo/zulip,isht3/zulip,calvinleenyc/zulip,stamhe/zulip,dhcrzf/zulip,udxxabp/zulip,sharmaeklavya2/zulip,calvinleenyc/zulip,thomasboyt/zulip,aliceriot/zulip,vikas-parashar/zulip,verma-varsha/zulip,hackerkid/zulip,andersk/zulip,itnihao/zulip,krtkmj/zulip,natanovia/zulip,qq1012803704/zulip,dotcool/zulip,jerryge/zulip,pradiptad/zulip,levixie/zulip,RobotCaleb/zulip,easyfmxu/zulip,Vallher/zulip,he15his/zulip,so0k/zulip,avastu/zulip,bowlofstew/zulip,EasonYi/zulip,Batterfii/zulip,brockwhittaker/zulip,dnmfarrell/zulip,ashwinirudrappa/zulip,stamhe/zulip,peiwei/zulip,shubhamdhama/zulip,xuanhan863/zulip,brainwane/zulip,ericzhou2008/zulip,vikas-parashar/zulip,jphilipsen05/zulip,amallia/zulip,aliceriot/zulip,wangdeshui/zulip,DazWorrall/zulip,bluesea/zulip,karamcnair/zulip,zachallaun/zulip,andersk/zulip,ikasumiwt/zulip,thomasboyt/zulip,grave-w-grave/zulip,DazWorrall/zulip,littledogboy/zulip,he15his/zulip,peiwei/zulip,aakash-cr7/zulip,udxxabp/zulip,hustlzp/zulip,praveenaki/zulip,umkay/zulip,MayB/zulip,jrowan/zulip,niftynei/zulip,mansilladev/zulip,jimmy54/zulip,andersk/zulip,reyha/zulip,dwrpayne/zulip,m1ssou/zulip,kaiyuanheshang/zulip,krtkmj/zulip,mansilladev/zulip,Gabriel0402/zulip,gigawhitlocks/zulip,SmartPeople/zulip,LeeRisk/zulip,joshisa/zulip,themass/zulip,aps-sids/zulip,aliceriot/zulip,jeffcao/zulip,alliejones/zulip,hj3938/zulip,showell/zulip,Diptanshu8/zulip,bssrdf/zulip,stamhe/zulip,codeKonami/zulip,esander91/zulip,littledogboy/zulip,schatt/zulip,gkotian/zulip,KJin99/zulip,zwily/zulip,jackrzhang/zulip,armooo/zulip,mohsenSy/zulip,ApsOps/zulip,luyifan/zulip,vakila/zulip,JPJPJPOPOP/zulip,RobotCaleb/zulip,zhaoweigg/zulip,tiansiyuan/zulip,mdavid/zulip,calvinleenyc/zulip,joyhchen/zulip,developerfm/zulip,shaunstanislaus/zulip,hafeez3000/zulip,hayderimran7/zulip,isht3/zulip,bssrdf/zulip,jackrzhang/zulip,umkay/zulip,xuanhan863/zulip,themass/zulip,kokoar/zulip,cosmicAsymmetry/zulip,vakila/zulip,zacps/zulip,noroot/zulip,SmartPeople/zulip,MariaFaBella85/zulip,KingxBanana/zulip,dotcool/zulip,LAndreas/zulip,johnnygaddarr/zulip,hustlzp/zulip,proliming/zulip,jessedhillon/zulip,Diptanshu8/zulip,hayderimran7/zulip,developerfm/zulip,arpith/zulip,ahmadassaf/zulip,Vallher/zulip,RobotCaleb/zulip,bowlofstew/zulip,shubhamdhama/zulip,jonesgithub/zulip,Jianchun1/zulip,bastianh/zulip,tdr130/zulip,aps-sids/zulip,qq1012803704/zulip,praveenaki/zulip,xuanhan863/zulip,Frouk/zulip,Drooids/zulip,xuxiao/zulip,willingc/zulip,MariaFaBella85/zulip,moria/zulip,krtkmj/zulip,moria/zulip,dattatreya303/zulip,Drooids/zulip,PhilSk/zulip,jimmy54/zulip,shaunstanislaus/zulip,Gabriel0402/zulip,hustlzp/zulip,shaunstanislaus/zulip,amyliu345/zulip,Diptanshu8/zulip,pradiptad/zulip,dhcrzf/zulip,jainayush975/zulip,timabbott/zulip,dhcrzf/zulip,babbage/zulip,PaulPetring/zulip,ahmadassaf/zulip,zwily/zulip,brainwane/zulip,samatdav/zulip,he15his/zulip,shrikrishnaholla/zulip,qq1012803704/zulip,qq1012803704/zulip,tdr130/zulip,kaiyuanheshang/zulip,peguin40/zulip,MariaFaBella85/zulip,Gabriel0402/zulip,PaulPetring/zulip,hj3938/zulip,zorojean/zulip,kaiyuanheshang/zulip,dhcrzf/zulip,amanharitsh123/zulip,dotcool/zulip,adnanh/zulip,aliceriot/zulip,technicalpickles/zulip,sonali0901/zulip,brockwhittaker/zulip,JanzTam/zulip,KJin99/zulip,hengqujushi/zulip,udxxabp/zulip,codeKonami/zulip,timabbott/zulip,SmartPeople/zulip,susansls/zulip,vakila/zulip,xuxiao/zulip,blaze225/zulip,hengqujushi/zulip,natanovia/zulip,jrowan/zulip,peiwei/zulip,aliceriot/zulip,nicholasbs/zulip,rht/zulip,amanharitsh123/zulip,vabs22/zulip,adnanh/zulip,m1ssou/zulip,Batterfii/zulip,yocome/zulip,tommyip/zulip,mdavid/zulip,yuvipanda/zulip,LAndreas/zulip,atomic-labs/zulip,ryansnowboarder/zulip,Jianchun1/zulip,bowlofstew/zulip,shubhamdhama/zulip,isht3/zulip,Diptanshu8/zulip,jphilipsen05/zulip,luyifan/zulip,yocome/zulip,vabs22/zulip,tiansiyuan/zulip,dxq-git/zulip,vakila/zulip,atomic-labs/zulip,hafeez3000/zulip,Diptanshu8/zulip,eeshangarg/zulip,MayB/zulip,mdavid/zulip,tiansiyuan/zulip,SmartPeople/zulip,ikasumiwt/zulip,udxxabp/zulip,brockwhittaker/zulip,blaze225/zulip,bitemyapp/zulip,suxinde2009/zulip,tiansiyuan/zulip,wweiradio/zulip,j831/zulip,mansilladev/zulip,susansls/zulip,ashwinirudrappa/zulip,luyifan/zulip,PhilSk/zulip,voidException/zulip,jonesgithub/zulip,aliceriot/zulip,calvinleenyc/zulip,avastu/zulip,zulip/zulip,synicalsyntax/zulip,bowlofstew/zulip,m1ssou/zulip,Jianchun1/zulip,codeKonami/zulip,dwrpayne/zulip,lfranchi/zulip,jphilipsen05/zulip,suxinde2009/zulip,babbage/zulip,vikas-parashar/zulip,kaiyuanheshang/zulip,JanzTam/zulip,jackrzhang/zulip,mohsenSy/zulip,niftynei/zulip,firstblade/zulip,yocome/zulip,jessedhillon/zulip,grave-w-grave/zulip,LeeRisk/zulip,jerryge/zulip,Batterfii/zulip,punchagan/zulip,avastu/zulip,sharmaeklavya2/zulip,bowlofstew/zulip,ericzhou2008/zulip,amanharitsh123/zulip,hustlzp/zulip,jessedhillon/zulip,JanzTam/zulip,saitodisse/zulip,bssrdf/zulip,shrikrishnaholla/zulip,sup95/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,kokoar/zulip,tommyip/zulip,wdaher/zulip,brainwane/zulip,swinghu/zulip,xuanhan863/zulip,huangkebo/zulip,ufosky-server/zulip,brockwhittaker/zulip,atomic-labs/zulip,jimmy54/zulip,Suninus/zulip,zofuthan/zulip,jainayush975/zulip,littledogboy/zulip,wavelets/zulip,wavelets/zulip,yuvipanda/zulip,moria/zulip,alliejones/zulip,Batterfii/zulip,johnnygaddarr/zulip,TigorC/zulip,christi3k/zulip,glovebx/zulip,tiansiyuan/zulip,willingc/zulip,umkay/zulip,swinghu/zulip,jerryge/zulip,Galexrt/zulip,joyhchen/zulip,thomasboyt/zulip,Jianchun1/zulip,natanovia/zulip,DazWorrall/zulip,zorojean/zulip,nicholasbs/zulip,cosmicAsymmetry/zulip,gkotian/zulip,arpitpanwar/zulip,bssrdf/zulip,zofuthan/zulip,dawran6/zulip,itnihao/zulip,tdr130/zulip,mahim97/zulip,jeffcao/zulip,isht3/zulip,JPJPJPOPOP/zulip,bastianh/zulip,alliejones/zulip,m1ssou/zulip,vaidap/zulip,andersk/zulip,arpitpanwar/zulip,zhaoweigg/zulip,dattatreya303/zulip,littledogboy/zulip,calvinleenyc/zulip,xuxiao/zulip,akuseru/zulip,tdr130/zulip,isht3/zulip,dattatreya303/zulip,pradiptad/zulip,alliejones/zulip,themass/zulip,susansls/zulip,codeKonami/zulip,littledogboy/zulip,technicalpickles/zulip,dawran6/zulip,hengqujushi/zulip,developerfm/zulip,dhcrzf/zulip,hackerkid/zulip,kokoar/zulip,babbage/zulip,kou/zulip,itnihao/zulip,hj3938/zulip,vabs22/zulip,atomic-labs/zulip,fw1121/zulip,praveenaki/zulip,xuxiao/zulip,JPJPJPOPOP/zulip,rishig/zulip,moria/zulip,jphilipsen05/zulip,calvinleenyc/zulip,EasonYi/zulip,JanzTam/zulip,easyfmxu/zulip,zhaoweigg/zulip,grave-w-grave/zulip,swinghu/zulip,aps-sids/zulip,Jianchun1/zulip,joyhchen/zulip,Qgap/zulip,levixie/zulip,christi3k/zulip,wdaher/zulip,levixie/zulip,sharmaeklavya2/zulip,proliming/zulip,zacps/zulip,jessedhillon/zulip,tbutter/zulip,mohsenSy/zulip,ahmadassaf/zulip,bssrdf/zulip,arpitpanwar/zulip,wavelets/zulip,paxapy/zulip,bitemyapp/zulip,souravbadami/zulip,guiquanz/zulip,jimmy54/zulip,nicholasbs/zulip,bluesea/zulip,j831/zulip,jrowan/zulip,KJin99/zulip,Galexrt/zulip,gkotian/zulip,shubhamdhama/zulip,LAndreas/zulip,glovebx/zulip,easyfmxu/zulip,peguin40/zulip,dattatreya303/zulip,ericzhou2008/zulip,glovebx/zulip,deer-hope/zulip,wdaher/zulip,RobotCaleb/zulip,avastu/zulip,eastlhu/zulip,armooo/zulip,guiquanz/zulip,wangdeshui/zulip,MayB/zulip,gkotian/zulip,yuvipanda/zulip,zhaoweigg/zulip,LeeRisk/zulip,karamcnair/zulip,itnihao/zulip,tbutter/zulip,Galexrt/zulip,ryansnowboarder/zulip,niftynei/zulip
|
python
|
## Code Before:
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
## Instruction:
Include confirmation key in context object.
This way our templates can reference the confirmation key later.
(imported from commit 4d57e1309386f2236829b6fdf4e4ad43c5b125c8)
## Code After:
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
'key': confirmation_key,
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
|
// ... existing code ...
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
'key': confirmation_key,
}
templates = [
'confirmation/confirm.html',
// ... rest of the code ...
|
8b2c0ceba47b776f09c57c3fc8f1b3384cceedd0
|
src/org/bonsaimind/arbitrarylines/lines/LineStyle.java
|
src/org/bonsaimind/arbitrarylines/lines/LineStyle.java
|
/*
* Copyright (c) 2017 Robert 'Bobby' Zenz
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.bonsaimind.arbitrarylines.lines;
import org.eclipse.swt.SWT;
public enum LineStyle {
SOLID(SWT.LINE_SOLID), DASH(SWT.LINE_DASH), DOT(SWT.LINE_DOT), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT);
private static final String[] styleStrings = new String[DASHDOTDOT.ordinal() + 1];
private final int swtStyle;
static {
for (LineStyle type : LineStyle.values()) {
styleStrings[type.ordinal()] = type.toString();
}
}
private LineStyle(int swtEquivalent) {
swtStyle = swtEquivalent;
}
public static final String[] getStyleStrings() {
return styleStrings;
}
public int getSwtStyle() {
return swtStyle;
}
}
|
/*
* Copyright (c) 2017 Robert 'Bobby' Zenz
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.bonsaimind.arbitrarylines.lines;
import org.eclipse.swt.SWT;
public enum LineStyle {
DASH(SWT.LINE_DASH), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT), DOT(SWT.LINE_DOT), SOLID(SWT.LINE_SOLID);
private static final String[] styleStrings = new String[] { SOLID.toString(), DASH.toString(), DOT.toString(), DASHDOT.toString(), DASHDOTDOT.toString() };
private final int swtStyle;
private LineStyle(int swtEquivalent) {
swtStyle = swtEquivalent;
}
public static final String[] getStyleStrings() {
return styleStrings;
}
public int getSwtStyle() {
return swtStyle;
}
}
|
Modify so that sort order of literals doesn't matter.
|
Modify so that sort order of literals doesn't matter.
|
Java
|
epl-1.0
|
RobertZenz/ArbitraryLines
|
java
|
## Code Before:
/*
* Copyright (c) 2017 Robert 'Bobby' Zenz
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.bonsaimind.arbitrarylines.lines;
import org.eclipse.swt.SWT;
public enum LineStyle {
SOLID(SWT.LINE_SOLID), DASH(SWT.LINE_DASH), DOT(SWT.LINE_DOT), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT);
private static final String[] styleStrings = new String[DASHDOTDOT.ordinal() + 1];
private final int swtStyle;
static {
for (LineStyle type : LineStyle.values()) {
styleStrings[type.ordinal()] = type.toString();
}
}
private LineStyle(int swtEquivalent) {
swtStyle = swtEquivalent;
}
public static final String[] getStyleStrings() {
return styleStrings;
}
public int getSwtStyle() {
return swtStyle;
}
}
## Instruction:
Modify so that sort order of literals doesn't matter.
## Code After:
/*
* Copyright (c) 2017 Robert 'Bobby' Zenz
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.bonsaimind.arbitrarylines.lines;
import org.eclipse.swt.SWT;
public enum LineStyle {
DASH(SWT.LINE_DASH), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT), DOT(SWT.LINE_DOT), SOLID(SWT.LINE_SOLID);
private static final String[] styleStrings = new String[] { SOLID.toString(), DASH.toString(), DOT.toString(), DASHDOT.toString(), DASHDOTDOT.toString() };
private final int swtStyle;
private LineStyle(int swtEquivalent) {
swtStyle = swtEquivalent;
}
public static final String[] getStyleStrings() {
return styleStrings;
}
public int getSwtStyle() {
return swtStyle;
}
}
|
# ... existing code ...
import org.eclipse.swt.SWT;
public enum LineStyle {
DASH(SWT.LINE_DASH), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT), DOT(SWT.LINE_DOT), SOLID(SWT.LINE_SOLID);
private static final String[] styleStrings = new String[] { SOLID.toString(), DASH.toString(), DOT.toString(), DASHDOT.toString(), DASHDOTDOT.toString() };
private final int swtStyle;
private LineStyle(int swtEquivalent) {
swtStyle = swtEquivalent;
# ... rest of the code ...
|
6cbbeab123ef8f665e382ba1970c2efc31acf285
|
ObjScheme/ObSFileLoader.h
|
ObjScheme/ObSFileLoader.h
|
//
// ObSFileLoader.h
// GameChanger
//
// Created by Kiril Savino on Tuesday, April 16, 2013
// Copyright 2013 GameChanger. All rights reserved.
//
@class ObSInPort;
@protocol ObSFileLoader <NSObject>
- (ObSInPort*)findFile:(NSString*)filename;
- (NSString*)qualifyFileName:(NSString*)filename;
@end
@interface ObSBundleFileLoader : NSObject <ObSFileLoader>
@property (nonatomic, strong) NSBundle *bundle;
- (instancetype)initWithBundle:(NSBundle *)bundle;
@end
@interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> {
NSString* _directoryPath;
}
+ (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path;
@end
|
//
// ObSFileLoader.h
// GameChanger
//
// Created by Kiril Savino on Tuesday, April 16, 2013
// Copyright 2013 GameChanger. All rights reserved.
//
@class ObSInPort;
@protocol ObSFileLoader <NSObject>
- (ObSInPort*)findFile:(NSString*)filename;
- (NSString*)qualifyFileName:(NSString*)filename;
@end
@interface ObSBundleFileLoader : NSObject <ObSFileLoader>
@property (nonatomic, strong, readonly) NSBundle *bundle;
- (instancetype)initWithBundle:(NSBundle *)bundle;
@end
@interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> {
NSString* _directoryPath;
}
+ (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path;
@end
|
Make bundle property read only
|
Make bundle property read only
|
C
|
mit
|
gamechanger/objscheme,gamechanger/objscheme,gamechanger/objscheme
|
c
|
## Code Before:
//
// ObSFileLoader.h
// GameChanger
//
// Created by Kiril Savino on Tuesday, April 16, 2013
// Copyright 2013 GameChanger. All rights reserved.
//
@class ObSInPort;
@protocol ObSFileLoader <NSObject>
- (ObSInPort*)findFile:(NSString*)filename;
- (NSString*)qualifyFileName:(NSString*)filename;
@end
@interface ObSBundleFileLoader : NSObject <ObSFileLoader>
@property (nonatomic, strong) NSBundle *bundle;
- (instancetype)initWithBundle:(NSBundle *)bundle;
@end
@interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> {
NSString* _directoryPath;
}
+ (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path;
@end
## Instruction:
Make bundle property read only
## Code After:
//
// ObSFileLoader.h
// GameChanger
//
// Created by Kiril Savino on Tuesday, April 16, 2013
// Copyright 2013 GameChanger. All rights reserved.
//
@class ObSInPort;
@protocol ObSFileLoader <NSObject>
- (ObSInPort*)findFile:(NSString*)filename;
- (NSString*)qualifyFileName:(NSString*)filename;
@end
@interface ObSBundleFileLoader : NSObject <ObSFileLoader>
@property (nonatomic, strong, readonly) NSBundle *bundle;
- (instancetype)initWithBundle:(NSBundle *)bundle;
@end
@interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> {
NSString* _directoryPath;
}
+ (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path;
@end
|
// ... existing code ...
@interface ObSBundleFileLoader : NSObject <ObSFileLoader>
@property (nonatomic, strong, readonly) NSBundle *bundle;
- (instancetype)initWithBundle:(NSBundle *)bundle;
// ... rest of the code ...
|
7a1ad6ec07cd7134bc90b4a8c9caa2aa9a5c22c9
|
config-model-api/src/main/java/com/yahoo/config/model/api/Reindexing.java
|
config-model-api/src/main/java/com/yahoo/config/model/api/Reindexing.java
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;
import java.time.Instant;
import java.util.Map;
/**
* Status of reindexing for the documents of an application.
*
* @author jonmv
*/
public interface Reindexing {
/** Reindexing status for a given application, cluster and document type. */
default Status status(String cluster, String documentType) { return () -> Instant.MAX; }
/** Reindexing status of a given document type in a given cluster in a given application. */
interface Status {
/** The instant at which reindexing may begin. */
Instant ready();
}
}
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;
import java.time.Instant;
import java.util.Map;
/**
* Status of reindexing for the documents of an application.
*
* @author jonmv
*/
public interface Reindexing {
/** No reindexing should be done for this document type and cluster. */
Status NO_REINDEXING = () -> Instant.MAX;
/** Reindexing status for a given application, cluster and document type. */
default Status status(String cluster, String documentType) { return NO_REINDEXING; }
/** Reindexing status of a given document type in a given cluster in a given application. */
interface Status {
/** The instant at which reindexing may begin. */
Instant ready();
}
}
|
Use more explicit value when reindexing should not be done
|
Use more explicit value when reindexing should not be done
|
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:
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;
import java.time.Instant;
import java.util.Map;
/**
* Status of reindexing for the documents of an application.
*
* @author jonmv
*/
public interface Reindexing {
/** Reindexing status for a given application, cluster and document type. */
default Status status(String cluster, String documentType) { return () -> Instant.MAX; }
/** Reindexing status of a given document type in a given cluster in a given application. */
interface Status {
/** The instant at which reindexing may begin. */
Instant ready();
}
}
## Instruction:
Use more explicit value when reindexing should not be done
## Code After:
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;
import java.time.Instant;
import java.util.Map;
/**
* Status of reindexing for the documents of an application.
*
* @author jonmv
*/
public interface Reindexing {
/** No reindexing should be done for this document type and cluster. */
Status NO_REINDEXING = () -> Instant.MAX;
/** Reindexing status for a given application, cluster and document type. */
default Status status(String cluster, String documentType) { return NO_REINDEXING; }
/** Reindexing status of a given document type in a given cluster in a given application. */
interface Status {
/** The instant at which reindexing may begin. */
Instant ready();
}
}
|
// ... existing code ...
*/
public interface Reindexing {
/** No reindexing should be done for this document type and cluster. */
Status NO_REINDEXING = () -> Instant.MAX;
/** Reindexing status for a given application, cluster and document type. */
default Status status(String cluster, String documentType) { return NO_REINDEXING; }
/** Reindexing status of a given document type in a given cluster in a given application. */
interface Status {
// ... rest of the code ...
|
b704a92c919d7fa950a65ee0c569864c4549331f
|
glue/core/tests/util.py
|
glue/core/tests/util.py
|
from __future__ import absolute_import, division, print_function
import tempfile
from contextlib import contextmanager
import os
import zlib
from mock import MagicMock
from ... import core
from ...core.application_base import Application
@contextmanager
def make_file(contents, suffix, decompress=False):
"""Context manager to write data to a temporary file,
and delete on exit
:param contents: Data to write. string
:param suffix: File suffix. string
"""
if decompress:
contents = zlib.decompress(contents)
try:
_, fname = tempfile.mkstemp(suffix=suffix)
with open(fname, 'wb') as outfile:
outfile.write(contents)
yield fname
finally:
os.unlink(fname)
@contextmanager
def simple_catalog():
"""Context manager to create a temporary data file
:param suffix: File suffix. string
"""
with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result:
yield result
def simple_session():
collect = core.data_collection.DataCollection()
hub = core.hub.Hub()
result = core.Session(data_collection=collect, hub=hub,
application=MagicMock(Application),
command_stack=core.CommandStack())
result.command_stack.session = result
return result
|
from __future__ import absolute_import, division, print_function
import tempfile
from contextlib import contextmanager
import os
import zlib
from mock import MagicMock
from ... import core
from ...core.application_base import Application
@contextmanager
def make_file(contents, suffix, decompress=False):
"""Context manager to write data to a temporary file,
and delete on exit
:param contents: Data to write. string
:param suffix: File suffix. string
"""
if decompress:
contents = zlib.decompress(contents)
try:
_, fname = tempfile.mkstemp(suffix=suffix)
with open(fname, 'wb') as outfile:
outfile.write(contents)
yield fname
finally:
try:
os.unlink(fname)
except WindowsError: # on Windows the unlink can fail
pass
@contextmanager
def simple_catalog():
"""Context manager to create a temporary data file
:param suffix: File suffix. string
"""
with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result:
yield result
def simple_session():
collect = core.data_collection.DataCollection()
hub = core.hub.Hub()
result = core.Session(data_collection=collect, hub=hub,
application=MagicMock(Application),
command_stack=core.CommandStack())
result.command_stack.session = result
return result
|
Add workaround for failing unlink on Windows
|
Add workaround for failing unlink on Windows
|
Python
|
bsd-3-clause
|
saimn/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue,stscieisenhamer/glue
|
python
|
## Code Before:
from __future__ import absolute_import, division, print_function
import tempfile
from contextlib import contextmanager
import os
import zlib
from mock import MagicMock
from ... import core
from ...core.application_base import Application
@contextmanager
def make_file(contents, suffix, decompress=False):
"""Context manager to write data to a temporary file,
and delete on exit
:param contents: Data to write. string
:param suffix: File suffix. string
"""
if decompress:
contents = zlib.decompress(contents)
try:
_, fname = tempfile.mkstemp(suffix=suffix)
with open(fname, 'wb') as outfile:
outfile.write(contents)
yield fname
finally:
os.unlink(fname)
@contextmanager
def simple_catalog():
"""Context manager to create a temporary data file
:param suffix: File suffix. string
"""
with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result:
yield result
def simple_session():
collect = core.data_collection.DataCollection()
hub = core.hub.Hub()
result = core.Session(data_collection=collect, hub=hub,
application=MagicMock(Application),
command_stack=core.CommandStack())
result.command_stack.session = result
return result
## Instruction:
Add workaround for failing unlink on Windows
## Code After:
from __future__ import absolute_import, division, print_function
import tempfile
from contextlib import contextmanager
import os
import zlib
from mock import MagicMock
from ... import core
from ...core.application_base import Application
@contextmanager
def make_file(contents, suffix, decompress=False):
"""Context manager to write data to a temporary file,
and delete on exit
:param contents: Data to write. string
:param suffix: File suffix. string
"""
if decompress:
contents = zlib.decompress(contents)
try:
_, fname = tempfile.mkstemp(suffix=suffix)
with open(fname, 'wb') as outfile:
outfile.write(contents)
yield fname
finally:
try:
os.unlink(fname)
except WindowsError: # on Windows the unlink can fail
pass
@contextmanager
def simple_catalog():
"""Context manager to create a temporary data file
:param suffix: File suffix. string
"""
with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result:
yield result
def simple_session():
collect = core.data_collection.DataCollection()
hub = core.hub.Hub()
result = core.Session(data_collection=collect, hub=hub,
application=MagicMock(Application),
command_stack=core.CommandStack())
result.command_stack.session = result
return result
|
// ... existing code ...
outfile.write(contents)
yield fname
finally:
try:
os.unlink(fname)
except WindowsError: # on Windows the unlink can fail
pass
@contextmanager
// ... rest of the code ...
|
47b00f384dbee0fb3b82696406978669ae80a3c6
|
tests/test_config.py
|
tests/test_config.py
|
"""Unittest of configuration loading."""
import os
import unittest
from unittest import mock
from yanico import config
class TestUserPath(unittest.TestCase):
"""Test for yanico.config.user_path()."""
@mock.patch.dict(os.environ, {'HOME': 'spam'})
def test_path(self):
"""Expect filepath joinning '.yanico.conf' under $HOME."""
if os.sep == '\\':
expect = 'spam\\.yanico.conf'
elif os.sep == '/':
expect = 'spam/.yanico.conf'
result = config.user_path()
self.assertEqual(result, expect)
|
"""Unittest of configuration loading."""
import os
import unittest
from unittest import mock
from yanico import config
class TestUserPath(unittest.TestCase):
"""Test for yanico.config.user_path()."""
@mock.patch.dict(os.environ, {'HOME': 'spam'})
def test_path(self):
"""Expect filepath joinning '.yanico.conf' under $HOME."""
if os.sep == '\\':
expect = 'spam\\.yanico.conf'
elif os.sep == '/':
expect = 'spam/.yanico.conf'
result = config.user_path()
self.assertEqual(result, expect)
@mock.patch('yanico.config.CONFIG_FILENAME', new='ham.egg')
def test_dependence_constants(self):
"""Expect to depend filename by 'CONFIG_FILENAME' constants."""
result = config.user_path()
self.assertEqual(os.path.basename(result), 'ham.egg')
|
Add test case for dependence constants
|
Add test case for dependence constants
Expect to depend filename by 'CONFIG_FILENAME' constants.
|
Python
|
apache-2.0
|
ma8ma/yanico
|
python
|
## Code Before:
"""Unittest of configuration loading."""
import os
import unittest
from unittest import mock
from yanico import config
class TestUserPath(unittest.TestCase):
"""Test for yanico.config.user_path()."""
@mock.patch.dict(os.environ, {'HOME': 'spam'})
def test_path(self):
"""Expect filepath joinning '.yanico.conf' under $HOME."""
if os.sep == '\\':
expect = 'spam\\.yanico.conf'
elif os.sep == '/':
expect = 'spam/.yanico.conf'
result = config.user_path()
self.assertEqual(result, expect)
## Instruction:
Add test case for dependence constants
Expect to depend filename by 'CONFIG_FILENAME' constants.
## Code After:
"""Unittest of configuration loading."""
import os
import unittest
from unittest import mock
from yanico import config
class TestUserPath(unittest.TestCase):
"""Test for yanico.config.user_path()."""
@mock.patch.dict(os.environ, {'HOME': 'spam'})
def test_path(self):
"""Expect filepath joinning '.yanico.conf' under $HOME."""
if os.sep == '\\':
expect = 'spam\\.yanico.conf'
elif os.sep == '/':
expect = 'spam/.yanico.conf'
result = config.user_path()
self.assertEqual(result, expect)
@mock.patch('yanico.config.CONFIG_FILENAME', new='ham.egg')
def test_dependence_constants(self):
"""Expect to depend filename by 'CONFIG_FILENAME' constants."""
result = config.user_path()
self.assertEqual(os.path.basename(result), 'ham.egg')
|
...
expect = 'spam/.yanico.conf'
result = config.user_path()
self.assertEqual(result, expect)
@mock.patch('yanico.config.CONFIG_FILENAME', new='ham.egg')
def test_dependence_constants(self):
"""Expect to depend filename by 'CONFIG_FILENAME' constants."""
result = config.user_path()
self.assertEqual(os.path.basename(result), 'ham.egg')
...
|
dd6287903ccddf24edf600e3d30fba61efd9478f
|
distarray/core/tests/test_distributed_array_protocol.py
|
distarray/core/tests/test_distributed_array_protocol.py
|
import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
def setUp(self):
try:
comm = create_comm_of_size(4)
except InvalidCommSizeError:
raise unittest.SkipTest('Must run with comm size > 4.')
else:
self.larr = da.LocalArray((16,16),
grid_shape=(4,),
comm=comm, buf=None, offset=0)
def test_has_export(self):
self.assertTrue(hasattr(self.larr, '__distarray__'))
def test_export_keys(self):
required_keys = set(("buffer", "dimdata"))
export_data = self.larr.__distarray__()
exported_keys = set(export_data.keys())
self.assertEqual(required_keys, exported_keys)
def test_export_buffer(self):
"""See if we actually export a buffer."""
export_data = self.larr.__distarray__()
memoryview(export_data['buffer'])
def test_round_trip(self):
new_larr = da.localarray(self.larr)
self.assertEqual(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
|
import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
def setUp(self):
try:
comm = create_comm_of_size(4)
except InvalidCommSizeError:
raise unittest.SkipTest('Must run with comm size > 4.')
else:
self.larr = da.LocalArray((16,16),
grid_shape=(4,),
comm=comm, buf=None, offset=0)
def test_has_export(self):
self.assertTrue(hasattr(self.larr, '__distarray__'))
def test_export_keys(self):
required_keys = set(("buffer", "dimdata"))
export_data = self.larr.__distarray__()
exported_keys = set(export_data.keys())
self.assertEqual(required_keys, exported_keys)
def test_export_buffer(self):
"""See if we actually export a buffer."""
export_data = self.larr.__distarray__()
memoryview(export_data['buffer'])
@unittest.skip("Import not yet implemented.")
def test_round_trip(self):
new_larr = da.fromdap(self.larr)
self.assertIs(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
|
Modify round-trip test to use new function name.
|
Modify round-trip test to use new function name.
We've temporarily settled on `fromdap()` for importing from `__distarray__` interfaces.
|
Python
|
bsd-3-clause
|
RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray
|
python
|
## Code Before:
import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
def setUp(self):
try:
comm = create_comm_of_size(4)
except InvalidCommSizeError:
raise unittest.SkipTest('Must run with comm size > 4.')
else:
self.larr = da.LocalArray((16,16),
grid_shape=(4,),
comm=comm, buf=None, offset=0)
def test_has_export(self):
self.assertTrue(hasattr(self.larr, '__distarray__'))
def test_export_keys(self):
required_keys = set(("buffer", "dimdata"))
export_data = self.larr.__distarray__()
exported_keys = set(export_data.keys())
self.assertEqual(required_keys, exported_keys)
def test_export_buffer(self):
"""See if we actually export a buffer."""
export_data = self.larr.__distarray__()
memoryview(export_data['buffer'])
def test_round_trip(self):
new_larr = da.localarray(self.larr)
self.assertEqual(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
## Instruction:
Modify round-trip test to use new function name.
We've temporarily settled on `fromdap()` for importing from `__distarray__` interfaces.
## Code After:
import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
def setUp(self):
try:
comm = create_comm_of_size(4)
except InvalidCommSizeError:
raise unittest.SkipTest('Must run with comm size > 4.')
else:
self.larr = da.LocalArray((16,16),
grid_shape=(4,),
comm=comm, buf=None, offset=0)
def test_has_export(self):
self.assertTrue(hasattr(self.larr, '__distarray__'))
def test_export_keys(self):
required_keys = set(("buffer", "dimdata"))
export_data = self.larr.__distarray__()
exported_keys = set(export_data.keys())
self.assertEqual(required_keys, exported_keys)
def test_export_buffer(self):
"""See if we actually export a buffer."""
export_data = self.larr.__distarray__()
memoryview(export_data['buffer'])
@unittest.skip("Import not yet implemented.")
def test_round_trip(self):
new_larr = da.fromdap(self.larr)
self.assertIs(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
|
# ... existing code ...
export_data = self.larr.__distarray__()
memoryview(export_data['buffer'])
@unittest.skip("Import not yet implemented.")
def test_round_trip(self):
new_larr = da.fromdap(self.larr)
self.assertIs(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
# ... rest of the code ...
|
bae9390c345d9a5986672b35432dd6009c4e8415
|
src/main/java/org/oblodiff/token/BasicToken.java
|
src/main/java/org/oblodiff/token/BasicToken.java
|
package org.oblodiff.token;
import org.oblodiff.token.api.Token;
/**
* The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
*
* @param <T> the type of the content this token represents
* @author Christian Rösch <[email protected]>
*/
public abstract class BasicToken<T extends Object> implements Token {
/**
* the representation of the value/content of this token.
*/
private final T content;
public BasicToken(final T ct) {
super();
content = ct;
}
@Override
public final int hashCode() {
return content.hashCode();
}
@Override
public final boolean equals(Object obj) {
if (!(obj instanceof BasicToken)) {
return false;
}
return content.equals(((BasicToken) obj).content);
}
protected T getContent() {
return content;
}
@Override
public String toString() {
return super.toString() + " >" + content + "<";
}
}
|
package org.oblodiff.token;
import org.oblodiff.token.api.Token;
/**
* The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
*
* @param <T> the type of the content this token represents
* @author Christian Rösch <[email protected]>
*/
public abstract class BasicToken<T> implements Token {
/**
* the representation of the value/content of this token.
*/
private final T content;
/**
* @param ct the content this token represents.
* @see #getContent() for further details
*/
public BasicToken(final T ct) {
super();
content = ct;
}
@Override
public final int hashCode() {
return content.hashCode();
}
@Override
public final boolean equals(Object obj) {
return obj instanceof BasicToken && content.equals(((BasicToken) obj).content);
}
/**
* @return the content of this token. The content is used for generating the hash of this token.
*/
protected T getContent() {
return content;
}
@Override
public String toString() {
return super.toString() + " >" + content + "<";
}
}
|
Add JavaDoc and remove warnings.
|
Add JavaDoc and remove warnings.
|
Java
|
bsd-3-clause
|
croesch/oblodiff
|
java
|
## Code Before:
package org.oblodiff.token;
import org.oblodiff.token.api.Token;
/**
* The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
*
* @param <T> the type of the content this token represents
* @author Christian Rösch <[email protected]>
*/
public abstract class BasicToken<T extends Object> implements Token {
/**
* the representation of the value/content of this token.
*/
private final T content;
public BasicToken(final T ct) {
super();
content = ct;
}
@Override
public final int hashCode() {
return content.hashCode();
}
@Override
public final boolean equals(Object obj) {
if (!(obj instanceof BasicToken)) {
return false;
}
return content.equals(((BasicToken) obj).content);
}
protected T getContent() {
return content;
}
@Override
public String toString() {
return super.toString() + " >" + content + "<";
}
}
## Instruction:
Add JavaDoc and remove warnings.
## Code After:
package org.oblodiff.token;
import org.oblodiff.token.api.Token;
/**
* The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
*
* @param <T> the type of the content this token represents
* @author Christian Rösch <[email protected]>
*/
public abstract class BasicToken<T> implements Token {
/**
* the representation of the value/content of this token.
*/
private final T content;
/**
* @param ct the content this token represents.
* @see #getContent() for further details
*/
public BasicToken(final T ct) {
super();
content = ct;
}
@Override
public final int hashCode() {
return content.hashCode();
}
@Override
public final boolean equals(Object obj) {
return obj instanceof BasicToken && content.equals(((BasicToken) obj).content);
}
/**
* @return the content of this token. The content is used for generating the hash of this token.
*/
protected T getContent() {
return content;
}
@Override
public String toString() {
return super.toString() + " >" + content + "<";
}
}
|
// ... existing code ...
* @param <T> the type of the content this token represents
* @author Christian Rösch <[email protected]>
*/
public abstract class BasicToken<T> implements Token {
/**
* the representation of the value/content of this token.
// ... modified code ...
*/
private final T content;
/**
* @param ct the content this token represents.
* @see #getContent() for further details
*/
public BasicToken(final T ct) {
super();
content = ct;
...
@Override
public final boolean equals(Object obj) {
return obj instanceof BasicToken && content.equals(((BasicToken) obj).content);
}
/**
* @return the content of this token. The content is used for generating the hash of this token.
*/
protected T getContent() {
return content;
}
// ... rest of the code ...
|
4e0e29199ce01c7ac8f71af78013911da11a8dc0
|
LandPortalEntities/lpentities/interval.py
|
LandPortalEntities/lpentities/interval.py
|
'''
Created on 02/02/2014
@author: Miguel Otero
'''
from .time import Time
class Interval(Time):
'''
classdocs
'''
MONTHLY = "http://purl.org/linked-data/sdmx/2009/code#freq-M"
YEARLY = "http://purl.org/linked-data/sdmx/2009/code#freq-A"
def __init__(self, frequency = YEARLY, start_time=None, end_time=None):
'''
Constructor
'''
self.frequency = frequency
self.start_time = start_time
self.end_time = end_time
def get_time_string(self):
return str(self.start_time) + '-' + str(self.end_time)
|
'''
Created on 02/02/2014
@author: Miguel Otero
'''
from .time import Time
class Interval(Time):
'''
classdocs
'''
MONTHLY = "freq-M"
YEARLY = "freq-A"
def __init__(self, frequency=YEARLY, start_time=None, end_time=None):
'''
Constructor
'''
self.frequency = frequency
self.start_time = start_time
self.end_time = end_time
def get_time_string(self):
return str(self.start_time) + '-' + str(self.end_time)
|
Remove ontology reference in Interval frequency value
|
Remove ontology reference in Interval frequency value
|
Python
|
mit
|
weso/landportal-importers,landportal/landbook-importers,landportal/landbook-importers
|
python
|
## Code Before:
'''
Created on 02/02/2014
@author: Miguel Otero
'''
from .time import Time
class Interval(Time):
'''
classdocs
'''
MONTHLY = "http://purl.org/linked-data/sdmx/2009/code#freq-M"
YEARLY = "http://purl.org/linked-data/sdmx/2009/code#freq-A"
def __init__(self, frequency = YEARLY, start_time=None, end_time=None):
'''
Constructor
'''
self.frequency = frequency
self.start_time = start_time
self.end_time = end_time
def get_time_string(self):
return str(self.start_time) + '-' + str(self.end_time)
## Instruction:
Remove ontology reference in Interval frequency value
## Code After:
'''
Created on 02/02/2014
@author: Miguel Otero
'''
from .time import Time
class Interval(Time):
'''
classdocs
'''
MONTHLY = "freq-M"
YEARLY = "freq-A"
def __init__(self, frequency=YEARLY, start_time=None, end_time=None):
'''
Constructor
'''
self.frequency = frequency
self.start_time = start_time
self.end_time = end_time
def get_time_string(self):
return str(self.start_time) + '-' + str(self.end_time)
|
...
'''
classdocs
'''
MONTHLY = "freq-M"
YEARLY = "freq-A"
def __init__(self, frequency=YEARLY, start_time=None, end_time=None):
'''
Constructor
'''
...
|
5abfe2c2363d3c9f2597664edf3810a80017759f
|
test/Sema/complex-promotion.c
|
test/Sema/complex-promotion.c
|
// RUN: clang %s -verify -fsyntax-only
float a;
int b[__builtin_classify_type(a + 1i) == 9 ? 1 : -1];
int c[__builtin_classify_type(1i + a) == 9 ? 1 : -1];
double d;
__typeof__ (d + 1i) e;
int f[sizeof(e) == 2 * sizeof(double) ? 1 : -1];
|
// RUN: clang %s -verify -fsyntax-only
float a;
int b[__builtin_classify_type(a + 1i) == 9 ? 1 : -1];
int c[__builtin_classify_type(1i + a) == 9 ? 1 : -1];
double d;
__typeof__ (d + 1i) e;
int f[sizeof(e) == 2 * sizeof(double) ? 1 : -1];
int g;
int h[__builtin_classify_type(g + 1.0i) == 9 ? 1 : -1];
int i[__builtin_classify_type(1.0i + a) == 9 ? 1 : -1];
|
Add another complex promotion test.
|
Add another complex promotion test.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@60863 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/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,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang
|
c
|
## Code Before:
// RUN: clang %s -verify -fsyntax-only
float a;
int b[__builtin_classify_type(a + 1i) == 9 ? 1 : -1];
int c[__builtin_classify_type(1i + a) == 9 ? 1 : -1];
double d;
__typeof__ (d + 1i) e;
int f[sizeof(e) == 2 * sizeof(double) ? 1 : -1];
## Instruction:
Add another complex promotion test.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@60863 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: clang %s -verify -fsyntax-only
float a;
int b[__builtin_classify_type(a + 1i) == 9 ? 1 : -1];
int c[__builtin_classify_type(1i + a) == 9 ? 1 : -1];
double d;
__typeof__ (d + 1i) e;
int f[sizeof(e) == 2 * sizeof(double) ? 1 : -1];
int g;
int h[__builtin_classify_type(g + 1.0i) == 9 ? 1 : -1];
int i[__builtin_classify_type(1.0i + a) == 9 ? 1 : -1];
|
...
__typeof__ (d + 1i) e;
int f[sizeof(e) == 2 * sizeof(double) ? 1 : -1];
int g;
int h[__builtin_classify_type(g + 1.0i) == 9 ? 1 : -1];
int i[__builtin_classify_type(1.0i + a) == 9 ? 1 : -1];
...
|
f868b126b3bd81ec900f378ff1fa8bd29ab8ea4c
|
transformations/Transformations.py
|
transformations/Transformations.py
|
from transformations.BackTranslation import BackTranslation
from transformations.ButterFingersPerturbation import ButterFingersPerturbation
from transformations.ChangeNamedEntities import ChangeNamedEntities
from transformations.SentenceTransformation import SentenceTransformation
from transformations.WithoutPunctuation import WithoutPunctuation
class TransformationsList(SentenceTransformation):
def __init__(self):
transformations = []
transformations.append(ButterFingersPerturbation())
transformations.append(WithoutPunctuation())
transformations.append(ChangeNamedEntities())
transformations.append(BackTranslation())
self.transformations = transformations
def generate(self, sentence: str):
print(f"Original Input : {sentence}")
generations = {"Original": sentence}
for transformation in self.transformations:
generations[transformation.name()] = transformation.generate(sentence)
return generations
|
from transformations.BackTranslation import BackTranslation
from transformations.ButterFingersPerturbation import ButterFingersPerturbation
from transformations.ChangeNamedEntities import ChangeNamedEntities
from transformations.SentenceTransformation import SentenceTransformation
from transformations.WithoutPunctuation import WithoutPunctuation
class TransformationsList(SentenceTransformation):
def __init__(self):
transformations = [ButterFingersPerturbation(), WithoutPunctuation(), ChangeNamedEntities(), BackTranslation()]
self.transformations = transformations
def generate(self, sentence: str):
print(f"Original Input : {sentence}")
generations = {"Original": sentence}
for transformation in self.transformations:
generations[transformation.name()] = transformation.generate(sentence)
return generations
|
Add interface for source+label pertubation
|
Add interface for source+label pertubation
|
Python
|
mit
|
GEM-benchmark/NL-Augmenter
|
python
|
## Code Before:
from transformations.BackTranslation import BackTranslation
from transformations.ButterFingersPerturbation import ButterFingersPerturbation
from transformations.ChangeNamedEntities import ChangeNamedEntities
from transformations.SentenceTransformation import SentenceTransformation
from transformations.WithoutPunctuation import WithoutPunctuation
class TransformationsList(SentenceTransformation):
def __init__(self):
transformations = []
transformations.append(ButterFingersPerturbation())
transformations.append(WithoutPunctuation())
transformations.append(ChangeNamedEntities())
transformations.append(BackTranslation())
self.transformations = transformations
def generate(self, sentence: str):
print(f"Original Input : {sentence}")
generations = {"Original": sentence}
for transformation in self.transformations:
generations[transformation.name()] = transformation.generate(sentence)
return generations
## Instruction:
Add interface for source+label pertubation
## Code After:
from transformations.BackTranslation import BackTranslation
from transformations.ButterFingersPerturbation import ButterFingersPerturbation
from transformations.ChangeNamedEntities import ChangeNamedEntities
from transformations.SentenceTransformation import SentenceTransformation
from transformations.WithoutPunctuation import WithoutPunctuation
class TransformationsList(SentenceTransformation):
def __init__(self):
transformations = [ButterFingersPerturbation(), WithoutPunctuation(), ChangeNamedEntities(), BackTranslation()]
self.transformations = transformations
def generate(self, sentence: str):
print(f"Original Input : {sentence}")
generations = {"Original": sentence}
for transformation in self.transformations:
generations[transformation.name()] = transformation.generate(sentence)
return generations
|
# ... existing code ...
from transformations.BackTranslation import BackTranslation
from transformations.ButterFingersPerturbation import ButterFingersPerturbation
from transformations.ChangeNamedEntities import ChangeNamedEntities
# ... modified code ...
class TransformationsList(SentenceTransformation):
def __init__(self):
transformations = [ButterFingersPerturbation(), WithoutPunctuation(), ChangeNamedEntities(), BackTranslation()]
self.transformations = transformations
def generate(self, sentence: str):
# ... rest of the code ...
|
aa143e28b61118c0fc3e5d28f2330572213b501c
|
halaqat/urls.py
|
halaqat/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
Add students app url configuration
|
Add students app url configuration
|
Python
|
mit
|
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
|
python
|
## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^admin/', include(admin.site.urls)),
]
## Instruction:
Add students app url configuration
## Code After:
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
// ... existing code ...
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
// ... rest of the code ...
|
3f2bee235dff5ae0f092624491d791b9589c09cc
|
app/src/main/java/br/com/alura/agenda/tasks/InsereAlunoTask.java
|
app/src/main/java/br/com/alura/agenda/tasks/InsereAlunoTask.java
|
package br.com.alura.agenda.tasks;
import android.os.AsyncTask;
import br.com.alura.agenda.converter.AlunoConverter;
import br.com.alura.agenda.modelo.Aluno;
import br.com.alura.agenda.web.WebClient;
public class InsereAlunoTask extends AsyncTask {
private final Aluno aluno;
public InsereAlunoTask(Aluno aluno) {
this.aluno = aluno;
}
@Override
protected Object doInBackground(Object[] objects) {
new AlunoConverter().converteParaJSONCompleto(aluno);
//new WebClient().insere(json);
return null;
}
}
|
package br.com.alura.agenda.tasks;
import android.os.AsyncTask;
import br.com.alura.agenda.converter.AlunoConverter;
import br.com.alura.agenda.modelo.Aluno;
import br.com.alura.agenda.web.WebClient;
public class InsereAlunoTask extends AsyncTask {
private final Aluno aluno;
public InsereAlunoTask(Aluno aluno) {
this.aluno = aluno;
}
@Override
protected Object doInBackground(Object[] objects) {
String json = new AlunoConverter().converteParaJSONCompleto(aluno);
new WebClient().insere(json);
return null;
}
}
|
Add call to WebClient on insert student AsyncTask
|
Add call to WebClient on insert student AsyncTask
|
Java
|
mit
|
filipe1309/android-student-agenda
|
java
|
## Code Before:
package br.com.alura.agenda.tasks;
import android.os.AsyncTask;
import br.com.alura.agenda.converter.AlunoConverter;
import br.com.alura.agenda.modelo.Aluno;
import br.com.alura.agenda.web.WebClient;
public class InsereAlunoTask extends AsyncTask {
private final Aluno aluno;
public InsereAlunoTask(Aluno aluno) {
this.aluno = aluno;
}
@Override
protected Object doInBackground(Object[] objects) {
new AlunoConverter().converteParaJSONCompleto(aluno);
//new WebClient().insere(json);
return null;
}
}
## Instruction:
Add call to WebClient on insert student AsyncTask
## Code After:
package br.com.alura.agenda.tasks;
import android.os.AsyncTask;
import br.com.alura.agenda.converter.AlunoConverter;
import br.com.alura.agenda.modelo.Aluno;
import br.com.alura.agenda.web.WebClient;
public class InsereAlunoTask extends AsyncTask {
private final Aluno aluno;
public InsereAlunoTask(Aluno aluno) {
this.aluno = aluno;
}
@Override
protected Object doInBackground(Object[] objects) {
String json = new AlunoConverter().converteParaJSONCompleto(aluno);
new WebClient().insere(json);
return null;
}
}
|
...
@Override
protected Object doInBackground(Object[] objects) {
String json = new AlunoConverter().converteParaJSONCompleto(aluno);
new WebClient().insere(json);
return null;
}
}
...
|
d535cf76b3129c0e5b6908a720bdf3e3a804e41b
|
mopidy/mixers/gstreamer_software.py
|
mopidy/mixers/gstreamer_software.py
|
import multiprocessing
from mopidy.mixers import BaseMixer
from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
my_end, other_end = multiprocessing.Pipe()
self.backend.output_queue.put({
'command': 'get_volume',
'reply_to': pickle_connection(other_end),
})
my_end.poll(None)
return my_end.recv()
def _set_volume(self, volume):
self.backend.output_queue.put({
'command': 'set_volume',
'volume': volume,
})
|
from mopidy.mixers import BaseMixer
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
return self.backend.output.get_volume()
def _set_volume(self, volume):
self.backend.output.set_volume(volume)
|
Update GStreamer software mixer to use new output API
|
Update GStreamer software mixer to use new output API
|
Python
|
apache-2.0
|
SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,ali/mopidy,quartz55/mopidy,adamcik/mopidy,liamw9534/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,abarisain/mopidy,swak/mopidy,mopidy/mopidy,pacificIT/mopidy,swak/mopidy,diandiankan/mopidy,adamcik/mopidy,bencevans/mopidy,hkariti/mopidy,glogiotatidis/mopidy,vrs01/mopidy,ZenithDK/mopidy,diandiankan/mopidy,bencevans/mopidy,tkem/mopidy,mokieyue/mopidy,jodal/mopidy,ali/mopidy,priestd09/mopidy,quartz55/mopidy,mopidy/mopidy,rawdlite/mopidy,kingosticks/mopidy,woutervanwijk/mopidy,jmarsik/mopidy,ali/mopidy,kingosticks/mopidy,dbrgn/mopidy,vrs01/mopidy,bacontext/mopidy,mopidy/mopidy,bencevans/mopidy,ZenithDK/mopidy,pacificIT/mopidy,swak/mopidy,rawdlite/mopidy,tkem/mopidy,dbrgn/mopidy,priestd09/mopidy,jcass77/mopidy,jcass77/mopidy,abarisain/mopidy,quartz55/mopidy,mokieyue/mopidy,quartz55/mopidy,jcass77/mopidy,hkariti/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,vrs01/mopidy,kingosticks/mopidy,priestd09/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,tkem/mopidy,jmarsik/mopidy,rawdlite/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,jodal/mopidy,adamcik/mopidy,jmarsik/mopidy,vrs01/mopidy,rawdlite/mopidy,jodal/mopidy,ZenithDK/mopidy,mokieyue/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,bacontext/mopidy,hkariti/mopidy,pacificIT/mopidy,hkariti/mopidy,mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,pacificIT/mopidy,bencevans/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,tkem/mopidy
|
python
|
## Code Before:
import multiprocessing
from mopidy.mixers import BaseMixer
from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
my_end, other_end = multiprocessing.Pipe()
self.backend.output_queue.put({
'command': 'get_volume',
'reply_to': pickle_connection(other_end),
})
my_end.poll(None)
return my_end.recv()
def _set_volume(self, volume):
self.backend.output_queue.put({
'command': 'set_volume',
'volume': volume,
})
## Instruction:
Update GStreamer software mixer to use new output API
## Code After:
from mopidy.mixers import BaseMixer
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
return self.backend.output.get_volume()
def _set_volume(self, volume):
self.backend.output.set_volume(volume)
|
...
from mopidy.mixers import BaseMixer
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
...
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
return self.backend.output.get_volume()
def _set_volume(self, volume):
self.backend.output.set_volume(volume)
...
|
ec6da89080d8ff55026be38c51e1e98c5ae9a982
|
inventory-client/src/main/java/name/webdizz/fault/tolerance/inventory/client/command/TimeOutInventoryRequestCommand.java
|
inventory-client/src/main/java/name/webdizz/fault/tolerance/inventory/client/command/TimeOutInventoryRequestCommand.java
|
package name.webdizz.fault.tolerance.inventory.client.command;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> {
private final InventoryRequester inventoryRequester;
private final Store store;
private final Product product;
public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("InventoryRequest"))
.andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(true)
.withExecutionTimeoutInMilliseconds(timeoutInMillis))
);
this.inventoryRequester = inventoryRequester;
this.store = store;
this.product = product;
}
@Override
protected Inventory run() throws Exception {
return inventoryRequester.requestInventoryFor(store, product);
}
}
|
package name.webdizz.fault.tolerance.inventory.client.command;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> {
private final InventoryRequester inventoryRequester;
private final Store store;
private final Product product;
public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(true)
.withExecutionTimeoutInMilliseconds(timeoutInMillis))
);
this.inventoryRequester = inventoryRequester;
this.store = store;
this.product = product;
}
@Override
protected Inventory run() throws Exception {
return inventoryRequester.requestInventoryFor(store, product);
}
}
|
Set Hystrix group key to command class name
|
Set Hystrix group key to command class name
|
Java
|
apache-2.0
|
webdizz/fault-tolerance-talk
|
java
|
## Code Before:
package name.webdizz.fault.tolerance.inventory.client.command;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> {
private final InventoryRequester inventoryRequester;
private final Store store;
private final Product product;
public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("InventoryRequest"))
.andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(true)
.withExecutionTimeoutInMilliseconds(timeoutInMillis))
);
this.inventoryRequester = inventoryRequester;
this.store = store;
this.product = product;
}
@Override
protected Inventory run() throws Exception {
return inventoryRequester.requestInventoryFor(store, product);
}
}
## Instruction:
Set Hystrix group key to command class name
## Code After:
package name.webdizz.fault.tolerance.inventory.client.command;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> {
private final InventoryRequester inventoryRequester;
private final Store store;
private final Product product;
public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(true)
.withExecutionTimeoutInMilliseconds(timeoutInMillis))
);
this.inventoryRequester = inventoryRequester;
this.store = store;
this.product = product;
}
@Override
protected Inventory run() throws Exception {
return inventoryRequester.requestInventoryFor(store, product);
}
}
|
// ... existing code ...
public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerForceClosed(true)
// ... rest of the code ...
|
57015bec555ca2a3f2e5893158d00f2dd2ca441c
|
errs.py
|
errs.py
|
import sys
class ConfigError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ParseError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
|
import sys
class GenericException(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ConfigError(GenericException):
pass
class ParseError(GenericException):
pass
|
Make errors a bit easier to copy
|
Make errors a bit easier to copy
|
Python
|
agpl-3.0
|
OpenTechStrategies/anvil
|
python
|
## Code Before:
import sys
class ConfigError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ParseError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
## Instruction:
Make errors a bit easier to copy
## Code After:
import sys
class GenericException(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ConfigError(GenericException):
pass
class ParseError(GenericException):
pass
|
// ... existing code ...
import sys
class GenericException(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ConfigError(GenericException):
pass
class ParseError(GenericException):
pass
// ... rest of the code ...
|
0dd6a55210fe1f8ab9daa3db524cac9becaa382e
|
lotte/src/main/java/com/airbnb/lotte/layers/RootLotteAnimatableLayer.java
|
lotte/src/main/java/com/airbnb/lotte/layers/RootLotteAnimatableLayer.java
|
package com.airbnb.lotte.layers;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import com.airbnb.lotte.utils.LotteTransform3D;
import com.airbnb.lotte.utils.Observable;
public class RootLotteAnimatableLayer extends LotteAnimatableLayer {
public RootLotteAnimatableLayer(Drawable.Callback callback) {
super(0, callback);
}
@Override
public void draw(@NonNull Canvas canvas) {
setTransform(new Observable<>(new LotteTransform3D()));
super.draw(canvas);
canvas.clipRect(getBounds());
}
}
|
package com.airbnb.lotte.layers;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
public class RootLotteAnimatableLayer extends LotteAnimatableLayer {
public RootLotteAnimatableLayer(Drawable.Callback callback) {
super(0, callback);
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
canvas.clipRect(getBounds());
}
}
|
Remove transform from root layer
|
Remove transform from root layer
|
Java
|
apache-2.0
|
airbnb/lottie-android,airbnb/lottie-android,airbnb/lottie-android,sudaoblinnnk/donghua,airbnb/lottie-android
|
java
|
## Code Before:
package com.airbnb.lotte.layers;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import com.airbnb.lotte.utils.LotteTransform3D;
import com.airbnb.lotte.utils.Observable;
public class RootLotteAnimatableLayer extends LotteAnimatableLayer {
public RootLotteAnimatableLayer(Drawable.Callback callback) {
super(0, callback);
}
@Override
public void draw(@NonNull Canvas canvas) {
setTransform(new Observable<>(new LotteTransform3D()));
super.draw(canvas);
canvas.clipRect(getBounds());
}
}
## Instruction:
Remove transform from root layer
## Code After:
package com.airbnb.lotte.layers;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
public class RootLotteAnimatableLayer extends LotteAnimatableLayer {
public RootLotteAnimatableLayer(Drawable.Callback callback) {
super(0, callback);
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
canvas.clipRect(getBounds());
}
}
|
# ... existing code ...
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
public class RootLotteAnimatableLayer extends LotteAnimatableLayer {
public RootLotteAnimatableLayer(Drawable.Callback callback) {
# ... modified code ...
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
canvas.clipRect(getBounds());
}
# ... rest of the code ...
|
58e3caf75a50a64d485b82d12d2353985413401f
|
src/util/bitwise.h
|
src/util/bitwise.h
|
namespace bitwise {
inline u16 compose_bytes(const u8 high, const u8 low) {
return static_cast<u16>((high << 8) + low);
}
inline bool check_bit(const u8 value, const u8 bit) {
return (value & (1 << bit)) != 0;
}
inline u8 set_bit(const u8 value, const u8 bit) {
auto value_set = value | (1 << bit);
return static_cast<u8>(value_set);
}
inline u8 clear_bit(const u8 value, const u8 bit) {
auto value_cleared = value & ~(1 << bit);
return static_cast<u8>(value_cleared);
}
inline u8 set_bit_to(const u8 value, const u8 bit, bool bit_on) {
return bit_on ? set_bit(value, bit) : clear_bit(value, bit);
}
} // namespace bitwise
|
namespace bitwise {
inline u16 compose_bytes(const u8 high, const u8 low) {
return static_cast<u16>((high << 8) + low);
}
inline bool check_bit(const u8 value, const u8 bit) {
return (value & (1 << bit)) != 0;
}
inline u8 bit_value(const u8 value, const u8 bit) {
return (value >> bit) & 1;
}
inline u8 set_bit(const u8 value, const u8 bit) {
auto value_set = value | (1 << bit);
return static_cast<u8>(value_set);
}
inline u8 clear_bit(const u8 value, const u8 bit) {
auto value_cleared = value & ~(1 << bit);
return static_cast<u8>(value_cleared);
}
inline u8 set_bit_to(const u8 value, const u8 bit, bool bit_on) {
return bit_on ? set_bit(value, bit) : clear_bit(value, bit);
}
} // namespace bitwise
|
Add a bit_value function for the numeric value of a single bit
|
Add a bit_value function for the numeric value of a single bit
|
C
|
bsd-3-clause
|
jgilchrist/emulator,jgilchrist/emulator,jgilchrist/emulator
|
c
|
## Code Before:
namespace bitwise {
inline u16 compose_bytes(const u8 high, const u8 low) {
return static_cast<u16>((high << 8) + low);
}
inline bool check_bit(const u8 value, const u8 bit) {
return (value & (1 << bit)) != 0;
}
inline u8 set_bit(const u8 value, const u8 bit) {
auto value_set = value | (1 << bit);
return static_cast<u8>(value_set);
}
inline u8 clear_bit(const u8 value, const u8 bit) {
auto value_cleared = value & ~(1 << bit);
return static_cast<u8>(value_cleared);
}
inline u8 set_bit_to(const u8 value, const u8 bit, bool bit_on) {
return bit_on ? set_bit(value, bit) : clear_bit(value, bit);
}
} // namespace bitwise
## Instruction:
Add a bit_value function for the numeric value of a single bit
## Code After:
namespace bitwise {
inline u16 compose_bytes(const u8 high, const u8 low) {
return static_cast<u16>((high << 8) + low);
}
inline bool check_bit(const u8 value, const u8 bit) {
return (value & (1 << bit)) != 0;
}
inline u8 bit_value(const u8 value, const u8 bit) {
return (value >> bit) & 1;
}
inline u8 set_bit(const u8 value, const u8 bit) {
auto value_set = value | (1 << bit);
return static_cast<u8>(value_set);
}
inline u8 clear_bit(const u8 value, const u8 bit) {
auto value_cleared = value & ~(1 << bit);
return static_cast<u8>(value_cleared);
}
inline u8 set_bit_to(const u8 value, const u8 bit, bool bit_on) {
return bit_on ? set_bit(value, bit) : clear_bit(value, bit);
}
} // namespace bitwise
|
...
inline bool check_bit(const u8 value, const u8 bit) {
return (value & (1 << bit)) != 0;
}
inline u8 bit_value(const u8 value, const u8 bit) {
return (value >> bit) & 1;
}
inline u8 set_bit(const u8 value, const u8 bit) {
...
|
a0ee7a9ac7cb8410f8ac2db5f4ac3cf1f9b9d932
|
app/src/main/java/com/example/mwismer/mobproto_finalproject/MyFragment.java
|
app/src/main/java/com/example/mwismer/mobproto_finalproject/MyFragment.java
|
package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
}
|
package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
}
|
Remove unused imports from MyActivity
|
Remove unused imports from MyActivity
|
Java
|
mit
|
MattWis/MobProto-FinalProject
|
java
|
## Code Before:
package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
}
## Instruction:
Remove unused imports from MyActivity
## Code After:
package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by mwismer on 10/23/14.
*/
public class MyFragment extends Fragment {
private String TAG = "MyFragment";
public MyFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
new BLEScanner(getActivity()).scanBLE();
return rootView;
}
}
|
# ... existing code ...
package com.example.mwismer.mobproto_finalproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by mwismer on 10/23/14.
# ... rest of the code ...
|
e88c22d817b2688f22daf996e15e686be7d17f6c
|
com.trollworks.gcs/src/com/trollworks/gcs/expression/function/Roll.java
|
com.trollworks.gcs/src/com/trollworks/gcs/expression/function/Roll.java
|
/*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 2.0. If a copy of the MPL was not distributed with
* this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
|
/*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 2.0. If a copy of the MPL was not distributed with
* this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments.contains("(") ? new Evaluator(evaluator).evaluate(arguments).toString() : arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
|
Allow expressions like roll(dice(1, 4, 1)) to work
|
Allow expressions like roll(dice(1, 4, 1)) to work
|
Java
|
mpl-2.0
|
richardwilkes/gcs,richardwilkes/gcs
|
java
|
## Code Before:
/*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 2.0. If a copy of the MPL was not distributed with
* this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
## Instruction:
Allow expressions like roll(dice(1, 4, 1)) to work
## Code After:
/*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 2.0. If a copy of the MPL was not distributed with
* this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments.contains("(") ? new Evaluator(evaluator).evaluate(arguments).toString() : arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
|
...
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments.contains("(") ? new Evaluator(evaluator).evaluate(arguments).toString() : arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
...
|
8a4a8cc351ae7fecd53932d0fb6ca0a7f9a83fbc
|
falcom/api/test/test_uris.py
|
falcom/api/test/test_uris.py
|
from hamcrest import *
import unittest
from .hamcrest import ComposedAssertion
from ..uri import URI
# There are three URIs that I need to use:
#
# http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json
# http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml
# http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50
class URITest (unittest.TestCase):
def test_null_uri_yields_empty_string (self):
uri = URI(None)
assert_that(uri(), is_(equal_to("")))
def test_empty_uri_yields_empty_string (self):
uri = URI("")
assert_that(uri(), is_(equal_to("")))
def test_simple_uri_yields_itself (self):
uri = URI("hello")
assert_that(uri(), is_(equal_to("hello")))
|
from hamcrest import *
import unittest
from .hamcrest import ComposedAssertion
from ..uri import URI
# There are three URIs that I need to use:
#
# http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json
# http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml
# http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50
class URITest (unittest.TestCase):
def test_null_uri_yields_empty_string (self):
uri = URI(None)
assert_that(uri(), is_(equal_to("")))
def test_simple_uri_yields_itself (self):
uri = URI("hello")
assert_that(uri(), is_(equal_to("hello")))
class GivenEmptyStrURI (unittest.TestCase):
def setUp (self):
self.uri = URI("")
def test_when_called_without_args_yields_empty_str (self):
assert_that(self.uri(), is_(equal_to("")))
|
Refactor a test into its own "given" test class
|
Refactor a test into its own "given" test class
|
Python
|
bsd-3-clause
|
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
|
python
|
## Code Before:
from hamcrest import *
import unittest
from .hamcrest import ComposedAssertion
from ..uri import URI
# There are three URIs that I need to use:
#
# http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json
# http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml
# http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50
class URITest (unittest.TestCase):
def test_null_uri_yields_empty_string (self):
uri = URI(None)
assert_that(uri(), is_(equal_to("")))
def test_empty_uri_yields_empty_string (self):
uri = URI("")
assert_that(uri(), is_(equal_to("")))
def test_simple_uri_yields_itself (self):
uri = URI("hello")
assert_that(uri(), is_(equal_to("hello")))
## Instruction:
Refactor a test into its own "given" test class
## Code After:
from hamcrest import *
import unittest
from .hamcrest import ComposedAssertion
from ..uri import URI
# There are three URIs that I need to use:
#
# http://catalog.hathitrust.org/api/volumes/brief/oclc/[OCLC].json
# http://mirlyn-aleph.lib.umich.edu/cgi-bin/bc2meta?id=[BARCODE]&type=bc&schema=marcxml
# http://www.worldcat.org/webservices/catalog/content/libraries/[OCLC]?wskey=[WC_KEY]&format=json&maximumLibraries=50
class URITest (unittest.TestCase):
def test_null_uri_yields_empty_string (self):
uri = URI(None)
assert_that(uri(), is_(equal_to("")))
def test_simple_uri_yields_itself (self):
uri = URI("hello")
assert_that(uri(), is_(equal_to("hello")))
class GivenEmptyStrURI (unittest.TestCase):
def setUp (self):
self.uri = URI("")
def test_when_called_without_args_yields_empty_str (self):
assert_that(self.uri(), is_(equal_to("")))
|
...
uri = URI(None)
assert_that(uri(), is_(equal_to("")))
def test_simple_uri_yields_itself (self):
uri = URI("hello")
assert_that(uri(), is_(equal_to("hello")))
class GivenEmptyStrURI (unittest.TestCase):
def setUp (self):
self.uri = URI("")
def test_when_called_without_args_yields_empty_str (self):
assert_that(self.uri(), is_(equal_to("")))
...
|
5733c800c10a7546228ec4562e40b2bd06c77c7e
|
models.py
|
models.py
|
from django.db import models
# Create your models here.
|
from django.db import models
from django.utils import timezone
import datetime
class Poll(models.Model):
question = models.CharField(max_length=255)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=255)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
|
Improve database model and apperance for admin site
|
Improve database model and apperance for admin site
|
Python
|
mit
|
egel/polls
|
python
|
## Code Before:
from django.db import models
# Create your models here.
## Instruction:
Improve database model and apperance for admin site
## Code After:
from django.db import models
from django.utils import timezone
import datetime
class Poll(models.Model):
question = models.CharField(max_length=255)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=255)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
|
// ... existing code ...
from django.db import models
from django.utils import timezone
import datetime
class Poll(models.Model):
question = models.CharField(max_length=255)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=255)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
// ... rest of the code ...
|
eccda634d3233cd4f8aaeea372735731fd674c29
|
pysis/labels/__init__.py
|
pysis/labels/__init__.py
|
import io
import functools
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated as a filename
"""
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return LabelDecoder().decode(fp)
return LabelDecoder().decode(stream)
def loads(data, encoding='utf-8'):
"""Parse an isis label from a string.
:param data: an isis label as a string
:returns: a dictionary representation of the given isis label
"""
if not isinstance(data, bytes):
data = data.encode(encoding)
return LabelDecoder().decode(data)
def dump(label, stream):
LabelEncoder().encode(label, stream)
def dumps(label):
stream = io.BytesIO()
LabelEncoder().encode(label, stream)
return stream.getvalue()
@functools.wraps(load)
def parse_file_label(stream):
warnings.warn('parse_file_label is deprecated. use load instead.')
return load(stream)
@functools.wraps(loads)
def parse_label(data, encoding='utf-8'):
warnings.warn('parse_label is deprecated. use load instead.')
return loads(data, encoding='utf-8')
|
import io
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated as a filename
"""
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return LabelDecoder().decode(fp)
return LabelDecoder().decode(stream)
def loads(data, encoding='utf-8'):
"""Parse an isis label from a string.
:param data: an isis label as a string
:returns: a dictionary representation of the given isis label
"""
if not isinstance(data, bytes):
data = data.encode(encoding)
return LabelDecoder().decode(data)
def dump(label, stream):
LabelEncoder().encode(label, stream)
def dumps(label):
stream = io.BytesIO()
LabelEncoder().encode(label, stream)
return stream.getvalue()
def parse_file_label(stream):
load.__doc__ + """
deprecated:: 0.4.0
Use load instead.
"""
warnings.warn('parse_file_label is deprecated. use load instead.')
return load(stream)
def parse_label(data, encoding='utf-8'):
loads.__doc__ + """
deprecated:: 0.4.0
Use loads instead.
"""
warnings.warn('parse_label is deprecated. use loads instead.')
return loads(data, encoding='utf-8')
|
Add depreciation messages to old parse_label methods.
|
Add depreciation messages to old parse_label methods.
|
Python
|
bsd-3-clause
|
michaelaye/Pysis,wtolson/pysis,wtolson/pysis,michaelaye/Pysis
|
python
|
## Code Before:
import io
import functools
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated as a filename
"""
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return LabelDecoder().decode(fp)
return LabelDecoder().decode(stream)
def loads(data, encoding='utf-8'):
"""Parse an isis label from a string.
:param data: an isis label as a string
:returns: a dictionary representation of the given isis label
"""
if not isinstance(data, bytes):
data = data.encode(encoding)
return LabelDecoder().decode(data)
def dump(label, stream):
LabelEncoder().encode(label, stream)
def dumps(label):
stream = io.BytesIO()
LabelEncoder().encode(label, stream)
return stream.getvalue()
@functools.wraps(load)
def parse_file_label(stream):
warnings.warn('parse_file_label is deprecated. use load instead.')
return load(stream)
@functools.wraps(loads)
def parse_label(data, encoding='utf-8'):
warnings.warn('parse_label is deprecated. use load instead.')
return loads(data, encoding='utf-8')
## Instruction:
Add depreciation messages to old parse_label methods.
## Code After:
import io
import warnings
import six
from .decoder import LabelDecoder
from .encoder import LabelEncoder
def load(stream):
"""Parse an isis label from a stream.
:param stream: a ``.read()``-supporting file-like object containing a label.
if ``stream`` is a string it will be treated as a filename
"""
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return LabelDecoder().decode(fp)
return LabelDecoder().decode(stream)
def loads(data, encoding='utf-8'):
"""Parse an isis label from a string.
:param data: an isis label as a string
:returns: a dictionary representation of the given isis label
"""
if not isinstance(data, bytes):
data = data.encode(encoding)
return LabelDecoder().decode(data)
def dump(label, stream):
LabelEncoder().encode(label, stream)
def dumps(label):
stream = io.BytesIO()
LabelEncoder().encode(label, stream)
return stream.getvalue()
def parse_file_label(stream):
load.__doc__ + """
deprecated:: 0.4.0
Use load instead.
"""
warnings.warn('parse_file_label is deprecated. use load instead.')
return load(stream)
def parse_label(data, encoding='utf-8'):
loads.__doc__ + """
deprecated:: 0.4.0
Use loads instead.
"""
warnings.warn('parse_label is deprecated. use loads instead.')
return loads(data, encoding='utf-8')
|
...
import io
import warnings
import six
...
return stream.getvalue()
def parse_file_label(stream):
load.__doc__ + """
deprecated:: 0.4.0
Use load instead.
"""
warnings.warn('parse_file_label is deprecated. use load instead.')
return load(stream)
def parse_label(data, encoding='utf-8'):
loads.__doc__ + """
deprecated:: 0.4.0
Use loads instead.
"""
warnings.warn('parse_label is deprecated. use loads instead.')
return loads(data, encoding='utf-8')
...
|
2a63eef748fa1910eddb0b772eb24344e6705fdc
|
net/socket/ssl_client_socket.h
|
net/socket/ssl_client_socket.h
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Next Protocol Negotiation (NPN), if successful, results in agreement on an
// application-level string that specifies the application level protocol to
// use over the TLS connection. NextProto enumerates the application level
// protocols that we recognise.
enum NextProto {
kProtoUnknown = 0,
kProtoHTTP11 = 1,
kProtoSPDY = 2,
};
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
static NextProto NextProtoFromString(const std::string& proto_string) {
if (proto_string == "http1.1") {
return kProtoHTTP11;
} else if (proto_string == "spdy") {
return kProtoSPDY;
} else {
return kProtoUnknown;
}
}
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
|
Add static function to convert NPN strings to an enum.
|
Add static function to convert NPN strings to an enum.
http://codereview.chromium.org/487012
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@34287 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
c
|
## Code Before:
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
## Instruction:
Add static function to convert NPN strings to an enum.
http://codereview.chromium.org/487012
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@34287 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
## Code After:
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include "net/socket/client_socket.h"
namespace net {
class SSLCertRequestInfo;
class SSLInfo;
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class SSLClientSocket : public ClientSocket {
public:
// Next Protocol Negotiation (NPN), if successful, results in agreement on an
// application-level string that specifies the application level protocol to
// use over the TLS connection. NextProto enumerates the application level
// protocols that we recognise.
enum NextProto {
kProtoUnknown = 0,
kProtoHTTP11 = 1,
kProtoSPDY = 2,
};
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// Gets the SSL CertificateRequest info of the socket after Connect failed
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
static NextProto NextProtoFromString(const std::string& proto_string) {
if (proto_string == "http1.1") {
return kProtoHTTP11;
} else if (proto_string == "spdy") {
return kProtoSPDY;
} else {
return kProtoUnknown;
}
}
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
|
// ... existing code ...
//
class SSLClientSocket : public ClientSocket {
public:
// Next Protocol Negotiation (NPN), if successful, results in agreement on an
// application-level string that specifies the application level protocol to
// use over the TLS connection. NextProto enumerates the application level
// protocols that we recognise.
enum NextProto {
kProtoUnknown = 0,
kProtoHTTP11 = 1,
kProtoSPDY = 2,
};
// Gets the SSL connection information of the socket.
virtual void GetSSLInfo(SSLInfo* ssl_info) = 0;
// ... modified code ...
// with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
virtual void GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) = 0;
static NextProto NextProtoFromString(const std::string& proto_string) {
if (proto_string == "http1.1") {
return kProtoHTTP11;
} else if (proto_string == "spdy") {
return kProtoSPDY;
} else {
return kProtoUnknown;
}
}
};
} // namespace net
// ... rest of the code ...
|
ac8dbe8f70061906035ea24ae6bae91f0432dca8
|
astropy/utils/setup_package.py
|
astropy/utils/setup_package.py
|
from distutils.core import Extension
from os.path import dirname, join
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[join(ROOT, 'src', 'compiler.c')])
]
|
from distutils.core import Extension
from os.path import dirname, join, relpath
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[relpath(join(ROOT, 'src', 'compiler.c'))])
]
|
Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes can make for long path names.)
|
Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes can make for long path names.)
|
Python
|
bsd-3-clause
|
MSeifert04/astropy,pllim/astropy,funbaker/astropy,stargaser/astropy,lpsinger/astropy,DougBurke/astropy,larrybradley/astropy,AustereCuriosity/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,tbabej/astropy,DougBurke/astropy,kelle/astropy,AustereCuriosity/astropy,saimn/astropy,mhvk/astropy,bsipocz/astropy,funbaker/astropy,astropy/astropy,stargaser/astropy,joergdietrich/astropy,StuartLittlefair/astropy,stargaser/astropy,aleksandr-bakanov/astropy,tbabej/astropy,AustereCuriosity/astropy,saimn/astropy,larrybradley/astropy,astropy/astropy,kelle/astropy,MSeifert04/astropy,larrybradley/astropy,StuartLittlefair/astropy,lpsinger/astropy,funbaker/astropy,dhomeier/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,larrybradley/astropy,tbabej/astropy,AustereCuriosity/astropy,tbabej/astropy,pllim/astropy,tbabej/astropy,pllim/astropy,saimn/astropy,DougBurke/astropy,lpsinger/astropy,astropy/astropy,joergdietrich/astropy,lpsinger/astropy,bsipocz/astropy,MSeifert04/astropy,pllim/astropy,joergdietrich/astropy,lpsinger/astropy,kelle/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,pllim/astropy,dhomeier/astropy,mhvk/astropy,larrybradley/astropy,astropy/astropy,StuartLittlefair/astropy,bsipocz/astropy,MSeifert04/astropy,kelle/astropy,bsipocz/astropy,astropy/astropy,stargaser/astropy,funbaker/astropy,kelle/astropy,dhomeier/astropy,DougBurke/astropy,mhvk/astropy,saimn/astropy,joergdietrich/astropy,StuartLittlefair/astropy,mhvk/astropy
|
python
|
## Code Before:
from distutils.core import Extension
from os.path import dirname, join
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[join(ROOT, 'src', 'compiler.c')])
]
## Instruction:
Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes can make for long path names.)
## Code After:
from distutils.core import Extension
from os.path import dirname, join, relpath
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[relpath(join(ROOT, 'src', 'compiler.c'))])
]
|
...
from distutils.core import Extension
from os.path import dirname, join, relpath
def get_extensions():
...
return [
Extension('astropy.utils._compiler',
[relpath(join(ROOT, 'src', 'compiler.c'))])
]
...
|
92317d3b7d6f1f7640e0a71c039c5f79f75b8517
|
src/com/samovich/java/basics/concepts/classes/MyClass.java
|
src/com/samovich/java/basics/concepts/classes/MyClass.java
|
/**
* @file MyClass.java
* @author Valery Samovich
* @version 1
* @date 2014/01/09
*
* Example of Class Declaration
*/
package com.samovich.java.basics.concepts.classes;
/*
* Class declaration
*/
public class MyClass {
// Field(s), Constructor, and Method declarations
}
|
/**
* @file MyClass.java
* @author Valery Samovich
* @version 1
* @date 2014/01/09
*
* Example of Class Declaration
* 1. Modifiers such as public, private, and a number of others that you will
* encounter later.
* 2. The class name, with the initial letter capitalized by convention.
* 3. The name of the class's parent (superclass), if any, preceded by the
* keyword extends. A class can only extend (subclass) one parent.
* 4. A comma-separated list of interfaces implemented by the class, if any,
* preceded by the keyword implements. A class can implement more than one
* interface.
The class body, surrounded by braces, {}.
*/
package com.samovich.java.basics.concepts.classes;
/*
* Class declaration
*/
public class MyClass {
// Field(s), Constructor, and Method declarations
}
|
Add Javadoc for Class Declaration.
|
Add Javadoc for Class Declaration.
|
Java
|
unknown
|
vsamov/java-technologies,valerysamovich/java-technologies,vsamov/java-technologies
|
java
|
## Code Before:
/**
* @file MyClass.java
* @author Valery Samovich
* @version 1
* @date 2014/01/09
*
* Example of Class Declaration
*/
package com.samovich.java.basics.concepts.classes;
/*
* Class declaration
*/
public class MyClass {
// Field(s), Constructor, and Method declarations
}
## Instruction:
Add Javadoc for Class Declaration.
## Code After:
/**
* @file MyClass.java
* @author Valery Samovich
* @version 1
* @date 2014/01/09
*
* Example of Class Declaration
* 1. Modifiers such as public, private, and a number of others that you will
* encounter later.
* 2. The class name, with the initial letter capitalized by convention.
* 3. The name of the class's parent (superclass), if any, preceded by the
* keyword extends. A class can only extend (subclass) one parent.
* 4. A comma-separated list of interfaces implemented by the class, if any,
* preceded by the keyword implements. A class can implement more than one
* interface.
The class body, surrounded by braces, {}.
*/
package com.samovich.java.basics.concepts.classes;
/*
* Class declaration
*/
public class MyClass {
// Field(s), Constructor, and Method declarations
}
|
// ... existing code ...
* @date 2014/01/09
*
* Example of Class Declaration
* 1. Modifiers such as public, private, and a number of others that you will
* encounter later.
* 2. The class name, with the initial letter capitalized by convention.
* 3. The name of the class's parent (superclass), if any, preceded by the
* keyword extends. A class can only extend (subclass) one parent.
* 4. A comma-separated list of interfaces implemented by the class, if any,
* preceded by the keyword implements. A class can implement more than one
* interface.
The class body, surrounded by braces, {}.
*/
package com.samovich.java.basics.concepts.classes;
// ... rest of the code ...
|
392db70fa268f52058018bc3b4fe672576e384e5
|
ReactiveCocoaFramework/ReactiveCocoa/NSUserDefaults+RACSupport.h
|
ReactiveCocoaFramework/ReactiveCocoa/NSUserDefaults+RACSupport.h
|
//
// NSUserDefaults+RACSupport.h
// ReactiveCocoa
//
// Created by Matt Diephouse on 12/19/13.
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class RACChannelTerminal;
@interface NSUserDefaults (RACSupport)
// Creates and returns a terminal for binding the user defaults key.
//
// key - The user defaults key to create the channel terminal for.
//
// This makes it easy to bind a property to a default by assigning to
// `RACChannelTo`.
//
// The terminal will send the value of the user defaults key upon subscription.
//
// Returns a channel terminal.
- (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key;
@end
|
//
// NSUserDefaults+RACSupport.h
// ReactiveCocoa
//
// Created by Matt Diephouse on 12/19/13.
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class RACChannelTerminal;
@interface NSUserDefaults (RACSupport)
/// Creates and returns a terminal for binding the user defaults key.
///
/// key - The user defaults key to create the channel terminal for.
///
/// This makes it easy to bind a property to a default by assigning to
/// `RACChannelTo`.
///
/// The terminal will send the value of the user defaults key upon subscription.
///
/// Returns a channel terminal.
- (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key;
@end
|
Add a third slash for Xcode
|
Add a third slash for Xcode
|
C
|
mit
|
dachaoisme/ReactiveCocoa,almassapargali/ReactiveCocoa,on99/ReactiveCocoa,itschaitanya/ReactiveCocoa,brightcove/ReactiveCocoa,tonyarnold/ReactiveCocoa,chao95957/ReactiveCocoa,zhiwen1024/ReactiveCocoa,Khan/ReactiveCocoa,cnbin/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,bencochran/ReactiveCocoa,jeelun/ReactiveCocoa,leelili/ReactiveCocoa,wpstarnice/ReactiveCocoa,mtxs007/ReactiveCocoa,xiaobing2007/ReactiveCocoa,DreamHill/ReactiveCocoa,beni55/ReactiveCocoa,hbucius/ReactiveCocoa,zhukaixy/ReactiveCocoa,nikita-leonov/ReactiveCocoa,emodeqidao/ReactiveCocoa,dachaoisme/ReactiveCocoa,ohwutup/ReactiveCocoa,hj3938/ReactiveCocoa,FelixYin66/ReactiveCocoa,tonyarnold/ReactiveCocoa,sdhzwm/ReactiveCocoa,Pikdays/ReactiveCocoa,koamac/ReactiveCocoa,Eveian/ReactiveCocoa,gabemdev/ReactiveCocoa,yizzuide/ReactiveCocoa,kevin-zqw/ReactiveCocoa,windgo/ReactiveCocoa,yoichitgy/ReactiveCocoa,ailyanlu/ReactiveCocoa,Farteen/ReactiveCocoa,rpowelll/ReactiveCocoa,yoichitgy/ReactiveCocoa,lixar/ReactiveCocoa,nikita-leonov/ReactiveCocoa,tzongw/ReactiveCocoa,tiger8888/ReactiveCocoa,200895045/ReactiveCocoa,sandyway/ReactiveCocoa,ShawnLeee/ReactiveCocoa,gengjf/ReactiveCocoa,hoanganh6491/ReactiveCocoa,jeelun/ReactiveCocoa,esttorhe/ReactiveCocoa,calebd/ReactiveCocoa,valleyman86/ReactiveCocoa,kevin-zqw/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,andersio/ReactiveCocoa,jaylib/ReactiveCocoa,yonekawa/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,eyu1988/ReactiveCocoa,xiaoliyang/ReactiveCocoa,cstars135/ReactiveCocoa,KuPai32G/ReactiveCocoa,JohnJin007/ReactiveCocoa,wangqi211/ReactiveCocoa,Pikdays/ReactiveCocoa,SuPair/ReactiveCocoa,bensonday/ReactiveCocoa,wangqi211/ReactiveCocoa,Remitly/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,jackywpy/ReactiveCocoa,tipbit/ReactiveCocoa,mxxiv/ReactiveCocoa,valleyman86/ReactiveCocoa,WEIBP/ReactiveCocoa,richeterre/ReactiveCocoa,zhigang1992/ReactiveCocoa,nickcheng/ReactiveCocoa,Adlai-Holler/ReactiveCocoa,LHDsimon/ReactiveCocoa,ailyanlu/ReactiveCocoa,victorlin/ReactiveCocoa,buildo/ReactiveCocoa,ohwutup/ReactiveCocoa,richeterre/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,335g/ReactiveCocoa,koamac/ReactiveCocoa,j364960953/ReactiveCocoa,alvinvarghese/ReactiveCocoa,xiaoliyang/ReactiveCocoa,eyu1988/ReactiveCocoa,ceekayel/ReactiveCocoa,natestedman/ReactiveCocoa,stupidfive/ReactiveCocoa,Pingco/ReactiveCocoa,sugar2010/ReactiveCocoa,huiping192/ReactiveCocoa,zhiwen1024/ReactiveCocoa,chieryw/ReactiveCocoa,howandhao/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,liufeigit/ReactiveCocoa,isghe/ReactiveCocoa,kaylio/ReactiveCocoa,tornade0913/ReactiveCocoa,CQXfly/ReactiveCocoa,kaylio/ReactiveCocoa,jaylib/ReactiveCocoa,ShawnLeee/ReactiveCocoa,esttorhe/ReactiveCocoa,brightcove/ReactiveCocoa,tornade0913/ReactiveCocoa,monkeydbobo/ReactiveCocoa,zzzworm/ReactiveCocoa,isghe/ReactiveCocoa,tzongw/ReactiveCocoa,mattpetters/ReactiveCocoa,tornade0913/ReactiveCocoa,jrmiddle/ReactiveCocoa,OneSmallTree/ReactiveCocoa,terry408911/ReactiveCocoa,KuPai32G/ReactiveCocoa,fhchina/ReactiveCocoa,jsslai/ReactiveCocoa,sujeking/ReactiveCocoa,bscarano/ReactiveCocoa,BrooksWon/ReactiveCocoa,DreamHill/ReactiveCocoa,ericzhou2008/ReactiveCocoa,Rupert-RR/ReactiveCocoa,gabemdev/ReactiveCocoa,BlessNeo/ReactiveCocoa,libiao88/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,loupman/ReactiveCocoa,zzzworm/ReactiveCocoa,loupman/ReactiveCocoa,Ray0218/ReactiveCocoa,stupidfive/ReactiveCocoa,stevielu/ReactiveCocoa,ohwutup/ReactiveCocoa,tipbit/ReactiveCocoa,goodheart/ReactiveCocoa,KJin99/ReactiveCocoa,calebd/ReactiveCocoa,yizzuide/ReactiveCocoa,tonyli508/ReactiveCocoa,kevin-zqw/ReactiveCocoa,sujeking/ReactiveCocoa,llb1119/test,yonekawa/ReactiveCocoa,jianwoo/ReactiveCocoa,zhenlove/ReactiveCocoa,bensonday/ReactiveCocoa,bencochran/ReactiveCocoa,JohnJin007/ReactiveCocoa,goodheart/ReactiveCocoa,jianwoo/ReactiveCocoa,Liquidsoul/ReactiveCocoa,JohnJin007/ReactiveCocoa,icepy/ReactiveCocoa,ericzhou2008/ReactiveCocoa,terry408911/ReactiveCocoa,ShawnLeee/ReactiveCocoa,tiger8888/ReactiveCocoa,takeshineshiro/ReactiveCocoa,dachaoisme/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,CQXfly/ReactiveCocoa,CQXfly/ReactiveCocoa,dskatz22/ReactiveCocoa,victorlin/ReactiveCocoa,natestedman/ReactiveCocoa,Rupert-RR/ReactiveCocoa,yytong/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,pzw224/ReactiveCocoa,Ricowere/ReactiveCocoa,loupman/ReactiveCocoa,dz1111/ReactiveCocoa,hilllinux/ReactiveCocoa,AlanJN/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,fanghao085/ReactiveCocoa,wangqi211/ReactiveCocoa,ReactiveCocoa/ReactiveSwift,fanghao085/ReactiveCocoa,on99/ReactiveCocoa,ztchena/ReactiveCocoa,ioshger0125/ReactiveCocoa,jrmiddle/ReactiveCocoa,huiping192/ReactiveCocoa,zzzworm/ReactiveCocoa,add715/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,fhchina/ReactiveCocoa,esttorhe/ReactiveCocoa,cogddo/ReactiveCocoa,rpowelll/ReactiveCocoa,tonyli508/ReactiveCocoa,natan/ReactiveCocoa,pzw224/ReactiveCocoa,gengjf/ReactiveCocoa,zhigang1992/ReactiveCocoa,bencochran/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,howandhao/ReactiveCocoa,ikesyo/ReactiveCocoa,ailyanlu/ReactiveCocoa,eyu1988/ReactiveCocoa,cstars135/ReactiveCocoa,jackywpy/ReactiveCocoa,gengjf/ReactiveCocoa,imkerberos/ReactiveCocoa,DreamHill/ReactiveCocoa,mtxs007/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,200895045/ReactiveCocoa,kiurentu/ReactiveCocoa,chao95957/ReactiveCocoa,SmartEncounter/ReactiveCocoa,hbucius/ReactiveCocoa,yoichitgy/ReactiveCocoa,OneSmallTree/ReactiveCocoa,pzw224/ReactiveCocoa,j364960953/ReactiveCocoa,stevielu/ReactiveCocoa,eliperkins/ReactiveCocoa,longv2go/ReactiveCocoa,Juraldinio/ReactiveCocoa,KuPai32G/ReactiveCocoa,brasbug/ReactiveCocoa,lixar/ReactiveCocoa,Juraldinio/ReactiveCocoa,libiao88/ReactiveCocoa,dz1111/ReactiveCocoa,smilypeda/ReactiveCocoa,luerhouhou/ReactiveCocoa,zzqiltw/ReactiveCocoa,ddc391565320/ReactiveCocoa,leichunfeng/ReactiveCocoa,huiping192/ReactiveCocoa,paulyoung/ReactiveCocoa,BlessNeo/ReactiveCocoa,sandyway/ReactiveCocoa,xumaolin/ReactiveCocoa,sandyway/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,leelili/ReactiveCocoa,AllanChen/ReactiveCocoa,jrmiddle/ReactiveCocoa,mattpetters/ReactiveCocoa,jsslai/ReactiveCocoa,jianwoo/ReactiveCocoa,andersio/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,BrooksWon/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,Ray0218/ReactiveCocoa,esttorhe/ReactiveCocoa,towik/ReactiveCocoa,libiao88/ReactiveCocoa,Rupert-RR/ReactiveCocoa,Eveian/ReactiveCocoa,taylormoonxu/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,qq644531343/ReactiveCocoa,ddc391565320/ReactiveCocoa,j364960953/ReactiveCocoa,sdhzwm/ReactiveCocoa,clg0118/ReactiveCocoa,AlanJN/ReactiveCocoa,dullgrass/ReactiveCocoa,dskatz22/ReactiveCocoa,JackLian/ReactiveCocoa,FelixYin66/ReactiveCocoa,mxxiv/ReactiveCocoa,walkingsmarts/ReactiveCocoa,takeshineshiro/ReactiveCocoa,koamac/ReactiveCocoa,bensonday/ReactiveCocoa,zhukaixy/ReactiveCocoa,calebd/ReactiveCocoa,ceekayel/ReactiveCocoa,huiping192/ReactiveCocoa,zxq3220122/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,WEIBP/ReactiveCocoa,hoanganh6491/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,zhaoguohui/ReactiveCocoa,335g/ReactiveCocoa,on99/ReactiveCocoa,isghe/ReactiveCocoa,tiger8888/ReactiveCocoa,dz1111/ReactiveCocoa,brasbug/ReactiveCocoa,windgo/ReactiveCocoa,ztchena/ReactiveCocoa,JackLian/ReactiveCocoa,Ethan89/ReactiveCocoa,SanChain/ReactiveCocoa,towik/ReactiveCocoa,buildo/ReactiveCocoa,AlanJN/ReactiveCocoa,jackywpy/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,BrooksWon/ReactiveCocoa,335g/ReactiveCocoa,leichunfeng/ReactiveCocoa,dullgrass/ReactiveCocoa,hj3938/ReactiveCocoa,hilllinux/ReactiveCocoa,longv2go/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,xulibao/ReactiveCocoa,AllanChen/ReactiveCocoa,stupidfive/ReactiveCocoa,liufeigit/ReactiveCocoa,200895045/ReactiveCocoa,Ethan89/ReactiveCocoa,mxxiv/ReactiveCocoa,emodeqidao/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,bscarano/ReactiveCocoa,add715/ReactiveCocoa,jam891/ReactiveCocoa,ikesyo/ReactiveCocoa,nickcheng/ReactiveCocoa,Liquidsoul/ReactiveCocoa,eliperkins/ReactiveCocoa,Remitly/ReactiveCocoa,Eveian/ReactiveCocoa,dskatz22/ReactiveCocoa,richeterre/ReactiveCocoa,KJin99/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,ioshger0125/ReactiveCocoa,SanChain/ReactiveCocoa,icepy/ReactiveCocoa,windgo/ReactiveCocoa,xiaobing2007/ReactiveCocoa,ceekayel/ReactiveCocoa,Carthage/ReactiveCocoa,smilypeda/ReactiveCocoa,Ray0218/ReactiveCocoa,itschaitanya/ReactiveCocoa,luerhouhou/ReactiveCocoa,CCOOOOLL/ReactiveCocoa,cnbin/ReactiveCocoa,stevielu/ReactiveCocoa,towik/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,luerhouhou/ReactiveCocoa,beni55/ReactiveCocoa,shuxiashusheng/ReactiveCocoa,xumaolin/ReactiveCocoa,xulibao/ReactiveCocoa,Khan/ReactiveCocoa,sugar2010/ReactiveCocoa,zzqiltw/ReactiveCocoa,vincentiss/ReactiveCocoa,leichunfeng/ReactiveCocoa,SmartEncounter/ReactiveCocoa,longv2go/ReactiveCocoa,PSPDFKit-labs/ReactiveCocoa,zhiwen1024/ReactiveCocoa,hj3938/ReactiveCocoa,fanghao085/ReactiveCocoa,dullgrass/ReactiveCocoa,ddc391565320/ReactiveCocoa,tonyarnold/ReactiveCocoa,imkerberos/ReactiveCocoa,zhaoguohui/ReactiveCocoa,GuitarPlayer-Ma/ReactiveCocoa,almassapargali/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,leelili/ReactiveCocoa,imkerberos/ReactiveCocoa,OneSmallTree/ReactiveCocoa,yizzuide/ReactiveCocoa,terry408911/ReactiveCocoa,walkingsmarts/ReactiveCocoa,Pikdays/ReactiveCocoa,taylormoonxu/ReactiveCocoa,chao95957/ReactiveCocoa,kiurentu/ReactiveCocoa,msdgwzhy6/ReactiveCocoa,icepy/ReactiveCocoa,almassapargali/ReactiveCocoa,Remitly/ReactiveCocoa,chieryw/ReactiveCocoa,RuiAAPeres/ReactiveCocoa,lixar/ReactiveCocoa,paulyoung/ReactiveCocoa,monkeydbobo/ReactiveCocoa,shaohung001/ReactiveCocoa,bscarano/ReactiveCocoa,BlessNeo/ReactiveCocoa,beni55/ReactiveCocoa,zhigang1992/ReactiveCocoa,zhenlove/ReactiveCocoa,qq644531343/ReactiveCocoa,taylormoonxu/ReactiveCocoa,mtxs007/ReactiveCocoa,FelixYin66/ReactiveCocoa,jeelun/ReactiveCocoa,Farteen/ReactiveCocoa,brasbug/ReactiveCocoa,takeshineshiro/ReactiveCocoa,jaylib/ReactiveCocoa,alvinvarghese/ReactiveCocoa,jam891/ReactiveCocoa,yytong/ReactiveCocoa,zhenlove/ReactiveCocoa,jam891/ReactiveCocoa,zhaoguohui/ReactiveCocoa,paulyoung/ReactiveCocoa,victorlin/ReactiveCocoa,wpstarnice/ReactiveCocoa,xulibao/ReactiveCocoa,xiaoliyang/ReactiveCocoa,sugar2010/ReactiveCocoa,cstars135/ReactiveCocoa,clg0118/ReactiveCocoa,goodheart/ReactiveCocoa,tonyli508/ReactiveCocoa,xumaolin/ReactiveCocoa,natan/ReactiveCocoa,natan/ReactiveCocoa,Adlai-Holler/ReactiveCocoa,nikita-leonov/ReactiveCocoa,JackLian/ReactiveCocoa,Ricowere/ReactiveCocoa,ztchena/ReactiveCocoa,yytong/ReactiveCocoa,AndyZhaoHe/ReactiveCocoa,monkeydbobo/ReactiveCocoa,ericzhou2008/ReactiveCocoa,kaylio/ReactiveCocoa,WEIBP/ReactiveCocoa,sdhzwm/ReactiveCocoa,jsslai/ReactiveCocoa,Farteen/ReactiveCocoa,zhukaixy/ReactiveCocoa,DongDongDongDong/ReactiveCocoa,kiurentu/ReactiveCocoa,cnbin/ReactiveCocoa,shaohung001/ReactiveCocoa,add715/ReactiveCocoa,brightcove/ReactiveCocoa,Adlai-Holler/ReactiveCocoa,valleyman86/ReactiveCocoa,zxq3220122/ReactiveCocoa,natestedman/ReactiveCocoa,cogddo/ReactiveCocoa,nickcheng/ReactiveCocoa,smilypeda/ReactiveCocoa,vincentiss/ReactiveCocoa,KJin99/ReactiveCocoa,tzongw/ReactiveCocoa,wpstarnice/ReactiveCocoa,Carthage/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,jaylib/ReactiveCocoa,hilllinux/ReactiveCocoa,SuPair/ReactiveCocoa,itschaitanya/ReactiveCocoa,fhchina/ReactiveCocoa,cogddo/ReactiveCocoa,OnTheWay1988/ReactiveCocoa,yaoxiaoyong/ReactiveCocoa,Ricowere/ReactiveCocoa,Ricowere/ReactiveCocoa,clg0118/ReactiveCocoa,buildo/ReactiveCocoa,qq644531343/ReactiveCocoa,hbucius/ReactiveCocoa,vincentiss/ReactiveCocoa,juliangrosshauser/ReactiveCocoa,xiaobing2007/ReactiveCocoa,liufeigit/ReactiveCocoa,Juraldinio/ReactiveCocoa,rpowelll/ReactiveCocoa,andersio/ReactiveCocoa,sujeking/ReactiveCocoa,llb1119/test,SuPair/ReactiveCocoa,nickcheng/ReactiveCocoa,Pingco/ReactiveCocoa,hoanganh6491/ReactiveCocoa,yangshengchaoios/ReactiveCocoa,zzqiltw/ReactiveCocoa,ioshger0125/ReactiveCocoa,Liquidsoul/ReactiveCocoa,chieryw/ReactiveCocoa,howandhao/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,Carthage/ReactiveCocoa,llb1119/test,eliperkins/ReactiveCocoa,Khan/ReactiveCocoa,walkingsmarts/ReactiveCocoa,yangyangluoluo/ReactiveCocoa,LHDsimon/ReactiveCocoa,alvinvarghese/ReactiveCocoa,zxq3220122/ReactiveCocoa,mattpetters/ReactiveCocoa,Ethan89/ReactiveCocoa,shaohung001/ReactiveCocoa,yonekawa/ReactiveCocoa,LHDsimon/ReactiveCocoa,SanChain/ReactiveCocoa,Pingco/ReactiveCocoa,emodeqidao/ReactiveCocoa
|
c
|
## Code Before:
//
// NSUserDefaults+RACSupport.h
// ReactiveCocoa
//
// Created by Matt Diephouse on 12/19/13.
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class RACChannelTerminal;
@interface NSUserDefaults (RACSupport)
// Creates and returns a terminal for binding the user defaults key.
//
// key - The user defaults key to create the channel terminal for.
//
// This makes it easy to bind a property to a default by assigning to
// `RACChannelTo`.
//
// The terminal will send the value of the user defaults key upon subscription.
//
// Returns a channel terminal.
- (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key;
@end
## Instruction:
Add a third slash for Xcode
## Code After:
//
// NSUserDefaults+RACSupport.h
// ReactiveCocoa
//
// Created by Matt Diephouse on 12/19/13.
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class RACChannelTerminal;
@interface NSUserDefaults (RACSupport)
/// Creates and returns a terminal for binding the user defaults key.
///
/// key - The user defaults key to create the channel terminal for.
///
/// This makes it easy to bind a property to a default by assigning to
/// `RACChannelTo`.
///
/// The terminal will send the value of the user defaults key upon subscription.
///
/// Returns a channel terminal.
- (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key;
@end
|
...
@interface NSUserDefaults (RACSupport)
/// Creates and returns a terminal for binding the user defaults key.
///
/// key - The user defaults key to create the channel terminal for.
///
/// This makes it easy to bind a property to a default by assigning to
/// `RACChannelTo`.
///
/// The terminal will send the value of the user defaults key upon subscription.
///
/// Returns a channel terminal.
- (RACChannelTerminal *)rac_channelTerminalForKey:(NSString *)key;
@end
...
|
668440b16916651b85b4a4a507214cee721906a8
|
scanpointgenerator/__init__.py
|
scanpointgenerator/__init__.py
|
from point import Point # noqa
from generator import Generator # noqa
from arraygenerator import ArrayGenerator # noqa
from compoundgenerator import CompoundGenerator # noqa
from linegenerator import LineGenerator # noqa
from lissajousgenerator import LissajousGenerator # noqa
from randomoffsetgenerator import RandomOffsetGenerator # noqa
from spiralgenerator import SpiralGenerator # noqa
from plotgenerator import plot_generator # noqa
|
from scanpointgenerator.point import Point # noqa
from scanpointgenerator.generator import Generator # noqa
from scanpointgenerator.arraygenerator import ArrayGenerator # noqa
from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa
from scanpointgenerator.linegenerator import LineGenerator # noqa
from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa
from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa
from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa
from scanpointgenerator.plotgenerator import plot_generator # noqa
|
Add absolute imports in init
|
Add absolute imports in init
|
Python
|
apache-2.0
|
dls-controls/scanpointgenerator
|
python
|
## Code Before:
from point import Point # noqa
from generator import Generator # noqa
from arraygenerator import ArrayGenerator # noqa
from compoundgenerator import CompoundGenerator # noqa
from linegenerator import LineGenerator # noqa
from lissajousgenerator import LissajousGenerator # noqa
from randomoffsetgenerator import RandomOffsetGenerator # noqa
from spiralgenerator import SpiralGenerator # noqa
from plotgenerator import plot_generator # noqa
## Instruction:
Add absolute imports in init
## Code After:
from scanpointgenerator.point import Point # noqa
from scanpointgenerator.generator import Generator # noqa
from scanpointgenerator.arraygenerator import ArrayGenerator # noqa
from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa
from scanpointgenerator.linegenerator import LineGenerator # noqa
from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa
from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa
from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa
from scanpointgenerator.plotgenerator import plot_generator # noqa
|
# ... existing code ...
from scanpointgenerator.point import Point # noqa
from scanpointgenerator.generator import Generator # noqa
from scanpointgenerator.arraygenerator import ArrayGenerator # noqa
from scanpointgenerator.compoundgenerator import CompoundGenerator # noqa
from scanpointgenerator.linegenerator import LineGenerator # noqa
from scanpointgenerator.lissajousgenerator import LissajousGenerator # noqa
from scanpointgenerator.randomoffsetgenerator import RandomOffsetGenerator # noqa
from scanpointgenerator.spiralgenerator import SpiralGenerator # noqa
from scanpointgenerator.plotgenerator import plot_generator # noqa
# ... rest of the code ...
|
57617193daeecc6ec6adf1057dbd687464558259
|
demo1/src/demo/object/itickable.h
|
demo1/src/demo/object/itickable.h
|
// itickable.h
//
// Interface definition of an object that is updated during the tick cycle.
//
#ifndef DEMO_ITICKABLE_H
#define DEMO_ITICKABLE_H
namespace demo
{
namespace obj
{
class ITickable
{
public:
// CONSTRUCTORS
~ITickable();
// MEMBER FUNCTIONS
/**
* Prepare for the next tick cycle.
*/
virtual void preTick() = 0;
/**
* Update the object.
* @param dt The elapsed time.
*/
virtual void tick( float dt ) = 0;
/**
* Clean up after the tick cycle.
*/
virtual void postTick() = 0;
};
// CONSTRUCTORS
ITickable::~ITickable()
{
}
} // End nspc obj
} // End nspc demo
#endif // DEMO_ITICKABLE_H
|
// itickable.h
//
// Interface definition of an object that is updated during the tick cycle.
//
#ifndef DEMO_ITICKABLE_H
#define DEMO_ITICKABLE_H
namespace demo
{
namespace obj
{
class ITickable
{
public:
// CONSTRUCTORS
/**
* Destruct the tickable.
*/
~ITickable();
// MEMBER FUNCTIONS
/**
* Prepare for the next tick cycle.
*/
virtual void preTick() = 0;
/**
* Update the object.
* @param dt The elapsed time in seconds.
*/
virtual void tick( float dt ) = 0;
/**
* Clean up after the tick cycle.
*/
virtual void postTick() = 0;
};
// CONSTRUCTORS
inline
ITickable::~ITickable()
{
}
} // End nspc obj
} // End nspc demo
#endif // DEMO_ITICKABLE_H
|
Clean up the tickable definition.
|
Clean up the tickable definition.
|
C
|
mit
|
invaderjon/demo,invaderjon/demo
|
c
|
## Code Before:
// itickable.h
//
// Interface definition of an object that is updated during the tick cycle.
//
#ifndef DEMO_ITICKABLE_H
#define DEMO_ITICKABLE_H
namespace demo
{
namespace obj
{
class ITickable
{
public:
// CONSTRUCTORS
~ITickable();
// MEMBER FUNCTIONS
/**
* Prepare for the next tick cycle.
*/
virtual void preTick() = 0;
/**
* Update the object.
* @param dt The elapsed time.
*/
virtual void tick( float dt ) = 0;
/**
* Clean up after the tick cycle.
*/
virtual void postTick() = 0;
};
// CONSTRUCTORS
ITickable::~ITickable()
{
}
} // End nspc obj
} // End nspc demo
#endif // DEMO_ITICKABLE_H
## Instruction:
Clean up the tickable definition.
## Code After:
// itickable.h
//
// Interface definition of an object that is updated during the tick cycle.
//
#ifndef DEMO_ITICKABLE_H
#define DEMO_ITICKABLE_H
namespace demo
{
namespace obj
{
class ITickable
{
public:
// CONSTRUCTORS
/**
* Destruct the tickable.
*/
~ITickable();
// MEMBER FUNCTIONS
/**
* Prepare for the next tick cycle.
*/
virtual void preTick() = 0;
/**
* Update the object.
* @param dt The elapsed time in seconds.
*/
virtual void tick( float dt ) = 0;
/**
* Clean up after the tick cycle.
*/
virtual void postTick() = 0;
};
// CONSTRUCTORS
inline
ITickable::~ITickable()
{
}
} // End nspc obj
} // End nspc demo
#endif // DEMO_ITICKABLE_H
|
# ... existing code ...
{
public:
// CONSTRUCTORS
/**
* Destruct the tickable.
*/
~ITickable();
// MEMBER FUNCTIONS
# ... modified code ...
/**
* Update the object.
* @param dt The elapsed time in seconds.
*/
virtual void tick( float dt ) = 0;
...
};
// CONSTRUCTORS
inline
ITickable::~ITickable()
{
}
# ... rest of the code ...
|
a555737e2d594a67078a15be9d5eb3c8524d0698
|
app/models.py
|
app/models.py
|
from . import db
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
age = db.Column(db.Date())
def __repr__(self):
return '<User {} {}>'.format(self.id, self.email)
|
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
password_hash = db.Column(db.String(128))
birth_date = db.Column(db.Date())
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User {} {}>'.format(self.id, self.email)
|
Add password hash to Monkey model
|
Add password hash to Monkey model
|
Python
|
mit
|
timzdevz/fm-flask-app
|
python
|
## Code Before:
from . import db
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
age = db.Column(db.Date())
def __repr__(self):
return '<User {} {}>'.format(self.id, self.email)
## Instruction:
Add password hash to Monkey model
## Code After:
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
class Monkey(db.Model):
__tablename__ = 'monkeys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
password_hash = db.Column(db.String(128))
birth_date = db.Column(db.Date())
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User {} {}>'.format(self.id, self.email)
|
...
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
class Monkey(db.Model):
__tablename__ = 'monkeys'
...
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64), unique=True)
password_hash = db.Column(db.String(128))
birth_date = db.Column(db.Date())
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User {} {}>'.format(self.id, self.email)
...
|
6336e8e13c01b6a81b8586499e7a3e8fc8b532a8
|
launch_control/commands/interface.py
|
launch_control/commands/interface.py
|
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return cls.__doc__
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
|
import inspect
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return inspect.getdoc(cls)
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
|
Use inspect.getdoc() instead of plain __doc__
|
Use inspect.getdoc() instead of plain __doc__
|
Python
|
agpl-3.0
|
Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server
|
python
|
## Code Before:
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return cls.__doc__
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
## Instruction:
Use inspect.getdoc() instead of plain __doc__
## Code After:
import inspect
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return inspect.getdoc(cls)
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
|
# ... existing code ...
import inspect
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
# ... modified code ...
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return inspect.getdoc(cls)
@classmethod
def register_arguments(cls, parser):
# ... rest of the code ...
|
abff14b5804bf43bc2bffeac6418259580bdbae5
|
makecard.py
|
makecard.py
|
import svgwrite
def main():
print 'test'
if __name__ == '__main__':
main()
|
import sys
import svgwrite
def main():
drawing = svgwrite.Drawing(size=('1000', '1400'))
img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
drawing.add(img)
sys.stdout.write(drawing.tostring())
if __name__ == '__main__':
main()
|
Include the first bullet svg
|
Include the first bullet svg
|
Python
|
apache-2.0
|
nanaze/xmascard
|
python
|
## Code Before:
import svgwrite
def main():
print 'test'
if __name__ == '__main__':
main()
## Instruction:
Include the first bullet svg
## Code After:
import sys
import svgwrite
def main():
drawing = svgwrite.Drawing(size=('1000', '1400'))
img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
drawing.add(img)
sys.stdout.write(drawing.tostring())
if __name__ == '__main__':
main()
|
...
import sys
import svgwrite
def main():
drawing = svgwrite.Drawing(size=('1000', '1400'))
img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100))
drawing.add(img)
sys.stdout.write(drawing.tostring())
if __name__ == '__main__':
main()
...
|
9cbfed00905fb8b360b60cce1afc293b71a2aced
|
check_access.py
|
check_access.py
|
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
exit
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.getuid()
if can_access(path, perm):
print "PASS: UID {} has {} access to {}".format(uid, perm, path)
exit(0)
else:
print "ERROR: UID {} has no {} access to {}".format(uid, perm, path)
exit(1)
|
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "USAGE: {} <docker volume spec>".format(sys.argv[0])
print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0])
exit(1)
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.getuid()
if can_access(path, perm):
print "PASS: UID {} has {} access to {}".format(uid, perm, path)
exit(0)
else:
print "ERROR: UID {} has no {} access to {}".format(uid, perm, path)
exit(1)
|
Print usage if not enough args
|
Print usage if not enough args
|
Python
|
mit
|
Duke-GCB/docker-wrapper,Duke-GCB/docker-wrapper
|
python
|
## Code Before:
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
exit
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.getuid()
if can_access(path, perm):
print "PASS: UID {} has {} access to {}".format(uid, perm, path)
exit(0)
else:
print "ERROR: UID {} has no {} access to {}".format(uid, perm, path)
exit(1)
## Instruction:
Print usage if not enough args
## Code After:
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "USAGE: {} <docker volume spec>".format(sys.argv[0])
print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0])
exit(1)
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.getuid()
if can_access(path, perm):
print "PASS: UID {} has {} access to {}".format(uid, perm, path)
exit(0)
else:
print "ERROR: UID {} has no {} access to {}".format(uid, perm, path)
exit(1)
|
// ... existing code ...
if __name__ == '__main__':
if len(sys.argv) < 2:
print "USAGE: {} <docker volume spec>".format(sys.argv[0])
print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0])
exit(1)
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.getuid()
// ... rest of the code ...
|
f5fd283497afb5030632108ce692e8acde526188
|
datalake_ingester/reporter.py
|
datalake_ingester/reporter.py
|
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
raise InsufficientConfiguration('Please configure a report_key')
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
|
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
return None
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
|
Allow the ingester to work without a report key
|
Allow the ingester to work without a report key
|
Python
|
apache-2.0
|
planetlabs/datalake-ingester,planetlabs/atl,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake
|
python
|
## Code Before:
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
raise InsufficientConfiguration('Please configure a report_key')
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
## Instruction:
Allow the ingester to work without a report key
## Code After:
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
return None
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
|
...
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
...
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
return None
return cls(report_key)
@property
...
|
893540d492b731b93a31f3c5158c99f4db9fc3e4
|
tasks.py
|
tasks.py
|
import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
|
import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
count += 1
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
|
Increase the count so we don't spin forever
|
Increase the count so we don't spin forever
|
Python
|
bsd-3-clause
|
pydotorg/pypi,pydotorg/pypi,pydotorg/pypi,pydotorg/pypi
|
python
|
## Code Before:
import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
## Instruction:
Increase the count so we don't spin forever
## Code After:
import urlparse
import requests
def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25):
session = requests.session()
headers = {"X-Fastly-Key": api_key, "Accept": "application/json"}
all_tags = set(tags)
purges = {}
count = 0
while all_tags and not count > max_tries:
count += 1
try:
for tag in set(all_tags):
# Build the URL
url_path = "/service/%s/purge/%s" % (service_id, tag)
url = urlparse.urljoin(domain, url_path)
# Issue the Purge
resp = session.post(url, headers=headers)
resp.raise_for_status()
# Store the Purge ID so we can track it later
purges[tag] = resp.json()["id"]
# for tag, purge_id in purges.iteritems():
# # Ensure that the purge completed successfully
# url = urlparse.urljoin(domain, "/purge")
# status = session.get(url, params={"id": purge_id})
# status.raise_for_status()
# # If the purge completely successfully remove the tag from
# # our list.
# if status.json().get("results", {}).get("complete", None):
# all_tags.remove(tag)
except Exception:
if count > max_tries:
raise
|
// ... existing code ...
count = 0
while all_tags and not count > max_tries:
count += 1
try:
for tag in set(all_tags):
# Build the URL
// ... rest of the code ...
|
e9f3efcc1d9a3372e97e396160ea2ecbdee778c6
|
rfmodbuslib/__init__.py
|
rfmodbuslib/__init__.py
|
__append_version__ = '-alpha'
__lib_version__ = '0.1' + __append_version__
__lib_name__ = 'rfmodbuslib'
__lib_copyright__ = 'Copyright 2015 Legrand Group'
|
__append_version__ = '-alpha'
__lib_version__ = '0.1' + __append_version__
__lib_name__ = 'rfmodbuslib'
__lib_copyright__ = 'Copyright 2015 Legrand Group'
__version__ = __lib_version__
|
Add a .__version__ attribute to package
|
Add a .__version__ attribute to package
|
Python
|
apache-2.0
|
Legrandgroup/robotframework-modbuslibrary
|
python
|
## Code Before:
__append_version__ = '-alpha'
__lib_version__ = '0.1' + __append_version__
__lib_name__ = 'rfmodbuslib'
__lib_copyright__ = 'Copyright 2015 Legrand Group'
## Instruction:
Add a .__version__ attribute to package
## Code After:
__append_version__ = '-alpha'
__lib_version__ = '0.1' + __append_version__
__lib_name__ = 'rfmodbuslib'
__lib_copyright__ = 'Copyright 2015 Legrand Group'
__version__ = __lib_version__
|
// ... existing code ...
__lib_version__ = '0.1' + __append_version__
__lib_name__ = 'rfmodbuslib'
__lib_copyright__ = 'Copyright 2015 Legrand Group'
__version__ = __lib_version__
// ... rest of the code ...
|
0c9cd65c1d995b22abb2944cf22b6b63791ff079
|
euler/java/src/test/java/com/ejpm/euler/math/prime/PrimeNumberTest.java
|
euler/java/src/test/java/com/ejpm/euler/math/prime/PrimeNumberTest.java
|
package com.ejpm.euler.math.prime;
import com.ejpm.euler.math.prime.PrimeNumber;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
|
package com.ejpm.euler.math.prime;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
|
Remove comment from package change
|
Remove comment from package change
|
Java
|
mit
|
edmathew/playground,edmathew/playground
|
java
|
## Code Before:
package com.ejpm.euler.math.prime;
import com.ejpm.euler.math.prime.PrimeNumber;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
## Instruction:
Remove comment from package change
## Code After:
package com.ejpm.euler.math.prime;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
|
// ... existing code ...
package com.ejpm.euler.math.prime;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
// ... rest of the code ...
|
3fa0dd1c2183fd00f8ec7162936dfdf63a34f858
|
data-service/src/main/java/org/ihtsdo/buildcloud/service/build/transform/RepeatableRelationshipUUIDTransform.java
|
data-service/src/main/java/org/ihtsdo/buildcloud/service/build/transform/RepeatableRelationshipUUIDTransform.java
|
package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
|
package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0] == null || columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
|
Allow SCTID in relationship file to be actually null, not just "null"
|
Allow SCTID in relationship file to be actually null, not just "null"
|
Java
|
apache-2.0
|
IHTSDO/snomed-release-service,IHTSDO/snomed-release-service
|
java
|
## Code Before:
package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
## Instruction:
Allow SCTID in relationship file to be actually null, not just "null"
## Code After:
package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0] == null || columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
|
// ... existing code ...
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0] == null || columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
// ... rest of the code ...
|
a112be00ddaaf775808250aece8ff18478831c9b
|
src/test/java/uk/gov/verifiablelog/merkletree/TestUtil.java
|
src/test/java/uk/gov/verifiablelog/merkletree/TestUtil.java
|
package uk.gov.verifiablelog.merkletree;
import javax.xml.bind.DatatypeConverter;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
class MerkleTreeTestUnit {
public MerkleTree merkleTree;
public List<byte[]> leaves;
public MerkleTreeTestUnit(MerkleTree merkleTree, List<byte[]> leaves) {
this.merkleTree = merkleTree;
this.leaves = leaves;
}
}
public class TestUtil {
public static MerkleTree makeMerkleTree(List<byte[]> entries) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
}
public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
}
public static MerkleTreeTestUnit makeMerkleTreeTestUnit(MemoizationStore memoizationStore) {
List<byte[]> leafValues = new ArrayList<>();
return new MerkleTreeTestUnit(makeMerkleTree(leafValues, memoizationStore), leafValues);
}
public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
}
public static String bytesToString(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}
public static byte[] stringToBytes(String input) {
return DatatypeConverter.parseHexBinary(input);
}
}
|
package uk.gov.verifiablelog.merkletree;
import javax.xml.bind.DatatypeConverter;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class TestUtil {
public static MerkleTree makeMerkleTree(List<byte[]> entries) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
}
public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
}
public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
}
public static String bytesToString(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}
public static byte[] stringToBytes(String input) {
return DatatypeConverter.parseHexBinary(input);
}
}
|
Remove unused utils and legacy dto test item class
|
Remove unused utils and legacy dto test item class
|
Java
|
mit
|
openregister/verifiable-log
|
java
|
## Code Before:
package uk.gov.verifiablelog.merkletree;
import javax.xml.bind.DatatypeConverter;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
class MerkleTreeTestUnit {
public MerkleTree merkleTree;
public List<byte[]> leaves;
public MerkleTreeTestUnit(MerkleTree merkleTree, List<byte[]> leaves) {
this.merkleTree = merkleTree;
this.leaves = leaves;
}
}
public class TestUtil {
public static MerkleTree makeMerkleTree(List<byte[]> entries) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
}
public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
}
public static MerkleTreeTestUnit makeMerkleTreeTestUnit(MemoizationStore memoizationStore) {
List<byte[]> leafValues = new ArrayList<>();
return new MerkleTreeTestUnit(makeMerkleTree(leafValues, memoizationStore), leafValues);
}
public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
}
public static String bytesToString(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}
public static byte[] stringToBytes(String input) {
return DatatypeConverter.parseHexBinary(input);
}
}
## Instruction:
Remove unused utils and legacy dto test item class
## Code After:
package uk.gov.verifiablelog.merkletree;
import javax.xml.bind.DatatypeConverter;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class TestUtil {
public static MerkleTree makeMerkleTree(List<byte[]> entries) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size);
}
public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
}
public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
return listOfByteArrays.stream().map(TestUtil::bytesToString).collect(toList());
}
public static String bytesToString(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}
public static byte[] stringToBytes(String input) {
return DatatypeConverter.parseHexBinary(input);
}
}
|
// ... existing code ...
package uk.gov.verifiablelog.merkletree;
import javax.xml.bind.DatatypeConverter;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class TestUtil {
public static MerkleTree makeMerkleTree(List<byte[]> entries) {
// ... modified code ...
public static MerkleTree makeMerkleTree(List<byte[]> entries, MemoizationStore memoizationStore) {
return new MerkleTree(Util.sha256Instance(), entries::get, entries::size, memoizationStore);
}
public static List<String> bytesToString(List<byte[]> listOfByteArrays) {
// ... rest of the code ...
|
2a3e9218e331362b7df25283dbad22140c3bc228
|
aQute.libg/src/aQute/lib/exceptions/Exceptions.java
|
aQute.libg/src/aQute/lib/exceptions/Exceptions.java
|
package aQute.lib.exceptions;
public class Exceptions {
static RuntimeException singleton = new RuntimeException();
public static RuntimeException duck(Throwable t) {
Exceptions.<RuntimeException> asUncheckedException0(t);
return singleton;
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> E asUncheckedException0(Throwable throwable) throws E {
return (E) throwable;
}
public static Runnable wrap(final RunnableWithException run) {
return new Runnable() {
@Override
public void run() {
try {
run.run();
} catch (Exception e) {
duck(e);
}
}
};
}
public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) {
return new org.osgi.util.function.Function<T,R>() {
@Override
public R apply(T value) {
try {
return run.apply(value);
} catch (Exception e) {
duck(e);
return null; // will never happen
}
}
};
}
}
|
package aQute.lib.exceptions;
public class Exceptions {
private Exceptions() {}
public static RuntimeException duck(Throwable t) {
Exceptions.<RuntimeException> throwsUnchecked(t);
throw new AssertionError("unreachable");
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwsUnchecked(Throwable throwable) throws E {
throw (E) throwable;
}
public static Runnable wrap(final RunnableWithException run) {
return new Runnable() {
@Override
public void run() {
try {
run.run();
} catch (Exception e) {
throw duck(e);
}
}
};
}
public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) {
return new org.osgi.util.function.Function<T,R>() {
@Override
public R apply(T value) {
try {
return run.apply(value);
} catch (Exception e) {
throw duck(e);
}
}
};
}
}
|
Fix so it actually throws the ducked exception
|
duck: Fix so it actually throws the ducked exception
Signed-off-by: BJ Hargrave <[email protected]>
|
Java
|
apache-2.0
|
lostiniceland/bnd,psoreide/bnd,mcculls/bnd,mcculls/bnd,magnet/bnd,psoreide/bnd,psoreide/bnd,lostiniceland/bnd,magnet/bnd,magnet/bnd,mcculls/bnd,lostiniceland/bnd
|
java
|
## Code Before:
package aQute.lib.exceptions;
public class Exceptions {
static RuntimeException singleton = new RuntimeException();
public static RuntimeException duck(Throwable t) {
Exceptions.<RuntimeException> asUncheckedException0(t);
return singleton;
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> E asUncheckedException0(Throwable throwable) throws E {
return (E) throwable;
}
public static Runnable wrap(final RunnableWithException run) {
return new Runnable() {
@Override
public void run() {
try {
run.run();
} catch (Exception e) {
duck(e);
}
}
};
}
public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) {
return new org.osgi.util.function.Function<T,R>() {
@Override
public R apply(T value) {
try {
return run.apply(value);
} catch (Exception e) {
duck(e);
return null; // will never happen
}
}
};
}
}
## Instruction:
duck: Fix so it actually throws the ducked exception
Signed-off-by: BJ Hargrave <[email protected]>
## Code After:
package aQute.lib.exceptions;
public class Exceptions {
private Exceptions() {}
public static RuntimeException duck(Throwable t) {
Exceptions.<RuntimeException> throwsUnchecked(t);
throw new AssertionError("unreachable");
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwsUnchecked(Throwable throwable) throws E {
throw (E) throwable;
}
public static Runnable wrap(final RunnableWithException run) {
return new Runnable() {
@Override
public void run() {
try {
run.run();
} catch (Exception e) {
throw duck(e);
}
}
};
}
public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) {
return new org.osgi.util.function.Function<T,R>() {
@Override
public R apply(T value) {
try {
return run.apply(value);
} catch (Exception e) {
throw duck(e);
}
}
};
}
}
|
// ... existing code ...
package aQute.lib.exceptions;
public class Exceptions {
private Exceptions() {}
public static RuntimeException duck(Throwable t) {
Exceptions.<RuntimeException> throwsUnchecked(t);
throw new AssertionError("unreachable");
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwsUnchecked(Throwable throwable) throws E {
throw (E) throwable;
}
public static Runnable wrap(final RunnableWithException run) {
// ... modified code ...
try {
run.run();
} catch (Exception e) {
throw duck(e);
}
}
...
try {
return run.apply(value);
} catch (Exception e) {
throw duck(e);
}
}
};
// ... rest of the code ...
|
61e4b4fe80a2d89de5bb30310d65e08e45548208
|
tests/test_read_user_choice.py
|
tests/test_read_user_choice.py
|
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
|
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
Implement a test checking that options needs to be a non empty list
|
Implement a test checking that options needs to be a non empty list
|
Python
|
bsd-3-clause
|
pjbull/cookiecutter,benthomasson/cookiecutter,dajose/cookiecutter,atlassian/cookiecutter,dajose/cookiecutter,nhomar/cookiecutter,ionelmc/cookiecutter,christabor/cookiecutter,sp1rs/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,lgp171188/cookiecutter,Springerle/cookiecutter,agconti/cookiecutter,lucius-feng/cookiecutter,lgp171188/cookiecutter,stevepiercy/cookiecutter,venumech/cookiecutter,tylerdave/cookiecutter,lucius-feng/cookiecutter,ionelmc/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,audreyr/cookiecutter,kkujawinski/cookiecutter,audreyr/cookiecutter,foodszhang/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,janusnic/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,drgarcia1986/cookiecutter,foodszhang/cookiecutter,Vauxoo/cookiecutter,nhomar/cookiecutter,moi65/cookiecutter,pjbull/cookiecutter,willingc/cookiecutter,willingc/cookiecutter,moi65/cookiecutter,benthomasson/cookiecutter,takeflight/cookiecutter,kkujawinski/cookiecutter,drgarcia1986/cookiecutter,takeflight/cookiecutter,venumech/cookiecutter,michaeljoseph/cookiecutter,ramiroluz/cookiecutter,sp1rs/cookiecutter,agconti/cookiecutter,christabor/cookiecutter,michaeljoseph/cookiecutter,Vauxoo/cookiecutter,vintasoftware/cookiecutter,janusnic/cookiecutter,stevepiercy/cookiecutter,vintasoftware/cookiecutter,terryjbates/cookiecutter
|
python
|
## Code Before:
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
## Instruction:
Implement a test checking that options needs to be a non empty list
## Code After:
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
// ... existing code ...
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
// ... rest of the code ...
|
8c5edbf6d928ab937128b783782726c06592cc9f
|
rosetta/signals.py
|
rosetta/signals.py
|
from django import dispatch
entry_changed = dispatch.Signal()
post_save = dispatch.Signal()
|
from django import dispatch
# providing_args=["user", "old_msgstr", "old_fuzzy", "pofile", "language_code"]
entry_changed = dispatch.Signal()
# providing_args=["language_code", "request"]
post_save = dispatch.Signal()
|
Add providing_args as a comment
|
Add providing_args as a comment
|
Python
|
mit
|
mbi/django-rosetta,mbi/django-rosetta,mbi/django-rosetta,mbi/django-rosetta
|
python
|
## Code Before:
from django import dispatch
entry_changed = dispatch.Signal()
post_save = dispatch.Signal()
## Instruction:
Add providing_args as a comment
## Code After:
from django import dispatch
# providing_args=["user", "old_msgstr", "old_fuzzy", "pofile", "language_code"]
entry_changed = dispatch.Signal()
# providing_args=["language_code", "request"]
post_save = dispatch.Signal()
|
...
from django import dispatch
# providing_args=["user", "old_msgstr", "old_fuzzy", "pofile", "language_code"]
entry_changed = dispatch.Signal()
# providing_args=["language_code", "request"]
post_save = dispatch.Signal()
...
|
4bd930b8bc6410a9966327c8e73e0b1849c71157
|
sympy/conftest.py
|
sympy/conftest.py
|
import sys
sys._running_pytest = True
from sympy.core.cache import clear_cache
def pytest_terminal_summary(terminalreporter):
if (terminalreporter.stats.get('error', None) or
terminalreporter.stats.get('failed', None)):
terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True)
def pytest_runtest_teardown():
clear_cache()
|
import sys
sys._running_pytest = True
from sympy.core.cache import clear_cache
def pytest_report_header(config):
from sympy.utilities.misc import ARCH
s = "architecture: %s\n" % ARCH
from sympy.core.cache import USE_CACHE
s += "cache: %s\n" % USE_CACHE
from sympy.polys.domains import GROUND_TYPES
s += "ground types: %s\n" % GROUND_TYPES
return s
def pytest_terminal_summary(terminalreporter):
if (terminalreporter.stats.get('error', None) or
terminalreporter.stats.get('failed', None)):
terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True)
def pytest_runtest_teardown():
clear_cache()
|
Add more info to pytest header
|
Add more info to pytest header
|
Python
|
bsd-3-clause
|
moble/sympy,ahhda/sympy,chaffra/sympy,saurabhjn76/sympy,saurabhjn76/sympy,ga7g08/sympy,AkademieOlympia/sympy,sampadsaha5/sympy,hrashk/sympy,jbbskinny/sympy,chaffra/sympy,yukoba/sympy,Designist/sympy,abhiii5459/sympy,atsao72/sympy,pandeyadarsh/sympy,kevalds51/sympy,postvakje/sympy,sahmed95/sympy,beni55/sympy,Vishluck/sympy,asm666/sympy,rahuldan/sympy,garvitr/sympy,AunShiLord/sympy,MechCoder/sympy,shipci/sympy,bukzor/sympy,ga7g08/sympy,chaffra/sympy,ga7g08/sympy,sahilshekhawat/sympy,Gadal/sympy,emon10005/sympy,madan96/sympy,MechCoder/sympy,jaimahajan1997/sympy,MridulS/sympy,kaushik94/sympy,bukzor/sympy,oliverlee/sympy,lidavidm/sympy,Shaswat27/sympy,drufat/sympy,Gadal/sympy,Designist/sympy,cccfran/sympy,hargup/sympy,souravsingh/sympy,atsao72/sympy,diofant/diofant,dqnykamp/sympy,farhaanbukhsh/sympy,hrashk/sympy,abloomston/sympy,Titan-C/sympy,abhiii5459/sympy,farhaanbukhsh/sympy,mafiya69/sympy,lidavidm/sympy,pbrady/sympy,jamesblunt/sympy,iamutkarshtiwari/sympy,yashsharan/sympy,Titan-C/sympy,drufat/sympy,pandeyadarsh/sympy,dqnykamp/sympy,maniteja123/sympy,sunny94/temp,debugger22/sympy,meghana1995/sympy,ahhda/sympy,cswiercz/sympy,meghana1995/sympy,AkademieOlympia/sympy,jbbskinny/sympy,hargup/sympy,toolforger/sympy,kaushik94/sympy,mcdaniel67/sympy,Vishluck/sympy,kaichogami/sympy,wyom/sympy,lindsayad/sympy,Shaswat27/sympy,atsao72/sympy,srjoglekar246/sympy,Davidjohnwilson/sympy,sahilshekhawat/sympy,Davidjohnwilson/sympy,dqnykamp/sympy,sahmed95/sympy,moble/sympy,farhaanbukhsh/sympy,rahuldan/sympy,ChristinaZografou/sympy,skidzo/sympy,MridulS/sympy,kevalds51/sympy,shipci/sympy,jamesblunt/sympy,VaibhavAgarwalVA/sympy,beni55/sympy,hrashk/sympy,ChristinaZografou/sympy,pbrady/sympy,MechCoder/sympy,sampadsaha5/sympy,Designist/sympy,Curious72/sympy,souravsingh/sympy,wyom/sympy,lidavidm/sympy,abhiii5459/sympy,moble/sympy,wyom/sympy,Mitchkoens/sympy,Mitchkoens/sympy,liangjiaxing/sympy,Arafatk/sympy,hargup/sympy,yukoba/sympy,jbbskinny/sympy,postvakje/sympy,garvitr/sympy,grevutiu-gabriel/sympy,MridulS/sympy,mcdaniel67/sympy,Titan-C/sympy,cccfran/sympy,shipci/sympy,amitjamadagni/sympy,Curious72/sympy,cswiercz/sympy,toolforger/sympy,Arafatk/sympy,kmacinnis/sympy,asm666/sympy,iamutkarshtiwari/sympy,atreyv/sympy,kumarkrishna/sympy,atreyv/sympy,debugger22/sympy,wanglongqi/sympy,VaibhavAgarwalVA/sympy,saurabhjn76/sympy,pandeyadarsh/sympy,Gadal/sympy,aktech/sympy,shikil/sympy,amitjamadagni/sympy,VaibhavAgarwalVA/sympy,madan96/sympy,Mitchkoens/sympy,kumarkrishna/sympy,drufat/sympy,skidzo/sympy,maniteja123/sympy,kmacinnis/sympy,wanglongqi/sympy,kmacinnis/sympy,toolforger/sympy,skirpichev/omg,jerli/sympy,liangjiaxing/sympy,cswiercz/sympy,lindsayad/sympy,mafiya69/sympy,beni55/sympy,atreyv/sympy,abloomston/sympy,yukoba/sympy,cccfran/sympy,rahuldan/sympy,postvakje/sympy,shikil/sympy,shikil/sympy,Sumith1896/sympy,lindsayad/sympy,sunny94/temp,yashsharan/sympy,ahhda/sympy,asm666/sympy,AunShiLord/sympy,jamesblunt/sympy,grevutiu-gabriel/sympy,madan96/sympy,jaimahajan1997/sympy,sunny94/temp,liangjiaxing/sympy,jerli/sympy,emon10005/sympy,Vishluck/sympy,yashsharan/sympy,kaichogami/sympy,skidzo/sympy,kevalds51/sympy,mafiya69/sympy,AunShiLord/sympy,vipulroxx/sympy,vipulroxx/sympy,kumarkrishna/sympy,oliverlee/sympy,debugger22/sympy,grevutiu-gabriel/sympy,Davidjohnwilson/sympy,sampadsaha5/sympy,sahilshekhawat/sympy,Shaswat27/sympy,maniteja123/sympy,pbrady/sympy,emon10005/sympy,aktech/sympy,ChristinaZografou/sympy,bukzor/sympy,flacjacket/sympy,Curious72/sympy,mcdaniel67/sympy,oliverlee/sympy,Arafatk/sympy,sahmed95/sympy,souravsingh/sympy,Sumith1896/sympy,garvitr/sympy,abloomston/sympy,meghana1995/sympy,kaushik94/sympy,Sumith1896/sympy,AkademieOlympia/sympy,kaichogami/sympy,aktech/sympy,wanglongqi/sympy,iamutkarshtiwari/sympy,jerli/sympy,vipulroxx/sympy,jaimahajan1997/sympy
|
python
|
## Code Before:
import sys
sys._running_pytest = True
from sympy.core.cache import clear_cache
def pytest_terminal_summary(terminalreporter):
if (terminalreporter.stats.get('error', None) or
terminalreporter.stats.get('failed', None)):
terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True)
def pytest_runtest_teardown():
clear_cache()
## Instruction:
Add more info to pytest header
## Code After:
import sys
sys._running_pytest = True
from sympy.core.cache import clear_cache
def pytest_report_header(config):
from sympy.utilities.misc import ARCH
s = "architecture: %s\n" % ARCH
from sympy.core.cache import USE_CACHE
s += "cache: %s\n" % USE_CACHE
from sympy.polys.domains import GROUND_TYPES
s += "ground types: %s\n" % GROUND_TYPES
return s
def pytest_terminal_summary(terminalreporter):
if (terminalreporter.stats.get('error', None) or
terminalreporter.stats.get('failed', None)):
terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True)
def pytest_runtest_teardown():
clear_cache()
|
# ... existing code ...
sys._running_pytest = True
from sympy.core.cache import clear_cache
def pytest_report_header(config):
from sympy.utilities.misc import ARCH
s = "architecture: %s\n" % ARCH
from sympy.core.cache import USE_CACHE
s += "cache: %s\n" % USE_CACHE
from sympy.polys.domains import GROUND_TYPES
s += "ground types: %s\n" % GROUND_TYPES
return s
def pytest_terminal_summary(terminalreporter):
if (terminalreporter.stats.get('error', None) or
# ... rest of the code ...
|
364cb2307021cc11de5a31f577e12a5f3e1f6bf6
|
openpathsampling/engines/toy/snapshot.py
|
openpathsampling/engines/toy/snapshot.py
|
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
import openpathsampling.engines.features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
|
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
|
Fix for bad merge decision
|
Fix for bad merge decision
|
Python
|
mit
|
openpathsampling/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,openpathsampling/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling
|
python
|
## Code Before:
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
import openpathsampling.engines.features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
## Instruction:
Fix for bad merge decision
## Code After:
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
|
# ... existing code ...
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
# ... rest of the code ...
|
3617ea84c0920554ce4debdf0278e52b116df542
|
library/src/main/java/com/m039/estimoto/util/EstimotoServiceUtil.java
|
library/src/main/java/com/m039/estimoto/util/EstimotoServiceUtil.java
|
/** EstimotoServiceUtil.java ---
*
* Copyright (C) 2014 Dmitry Mozgin
*
* Author: Dmitry Mozgin <[email protected]>
*
*
*/
package com.m039.estimoto.util;
import android.content.Context;
import android.content.Intent;
import com.m039.estimoto.service.EstimotoService;
/**
*
*
* Created: 03/22/14
*
* @author Dmitry Mozgin
* @version
* @since
*/
public class EstimotoServiceUtil {
public static void turnOn(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
ctx.startService(intent);
}
public static void turnOff(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
ctx.startService(intent);
}
private static Intent newEstimotoIntent(Context ctx, String action) {
Intent intent = new Intent(ctx, EstimotoService.class);
intent.setAction(action);
return intent;
}
} // EstimotoServiceUtil
|
/** EstimotoServiceUtil.java ---
*
* Copyright (C) 2014 Dmitry Mozgin
*
* Author: Dmitry Mozgin <[email protected]>
*
*
*/
package com.m039.estimoto.util;
import android.content.Context;
import android.content.Intent;
import com.m039.estimoto.service.EstimotoService;
/**
*
*
* Created: 03/22/14
*
* @author Dmitry Mozgin
* @version
* @since
*/
public class EstimotoServiceUtil {
public static void turnOn(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
ctx.startService(intent);
}
public static void turnOff(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
ctx.startService(intent);
ctx.stopService(intent); // hack
}
private static Intent newEstimotoIntent(Context ctx, String action) {
Intent intent = new Intent(ctx, EstimotoService.class);
intent.setAction(action);
return intent;
}
} // EstimotoServiceUtil
|
Add hack to stop service
|
Add hack to stop service
|
Java
|
apache-2.0
|
m039/beacon-keeper
|
java
|
## Code Before:
/** EstimotoServiceUtil.java ---
*
* Copyright (C) 2014 Dmitry Mozgin
*
* Author: Dmitry Mozgin <[email protected]>
*
*
*/
package com.m039.estimoto.util;
import android.content.Context;
import android.content.Intent;
import com.m039.estimoto.service.EstimotoService;
/**
*
*
* Created: 03/22/14
*
* @author Dmitry Mozgin
* @version
* @since
*/
public class EstimotoServiceUtil {
public static void turnOn(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
ctx.startService(intent);
}
public static void turnOff(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
ctx.startService(intent);
}
private static Intent newEstimotoIntent(Context ctx, String action) {
Intent intent = new Intent(ctx, EstimotoService.class);
intent.setAction(action);
return intent;
}
} // EstimotoServiceUtil
## Instruction:
Add hack to stop service
## Code After:
/** EstimotoServiceUtil.java ---
*
* Copyright (C) 2014 Dmitry Mozgin
*
* Author: Dmitry Mozgin <[email protected]>
*
*
*/
package com.m039.estimoto.util;
import android.content.Context;
import android.content.Intent;
import com.m039.estimoto.service.EstimotoService;
/**
*
*
* Created: 03/22/14
*
* @author Dmitry Mozgin
* @version
* @since
*/
public class EstimotoServiceUtil {
public static void turnOn(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
ctx.startService(intent);
}
public static void turnOff(Context ctx) {
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
ctx.startService(intent);
ctx.stopService(intent); // hack
}
private static Intent newEstimotoIntent(Context ctx, String action) {
Intent intent = new Intent(ctx, EstimotoService.class);
intent.setAction(action);
return intent;
}
} // EstimotoServiceUtil
|
// ... existing code ...
Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
ctx.startService(intent);
ctx.stopService(intent); // hack
}
private static Intent newEstimotoIntent(Context ctx, String action) {
// ... rest of the code ...
|
d46d908f5cfafcb6962207c45f923d3afb7f35a7
|
pyrobus/__init__.py
|
pyrobus/__init__.py
|
from .robot import Robot
from .modules import *
|
import logging
from .robot import Robot
from .modules import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
|
Add null handler as default for logging.
|
Add null handler as default for logging.
|
Python
|
mit
|
pollen/pyrobus
|
python
|
## Code Before:
from .robot import Robot
from .modules import *
## Instruction:
Add null handler as default for logging.
## Code After:
import logging
from .robot import Robot
from .modules import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
|
...
import logging
from .robot import Robot
from .modules import *
nh = logging.NullHandler()
logging.getLogger(__name__).addHandler(nh)
...
|
aac0f52fa97f75ca6ec5a2744cd1c0942a57c283
|
src/pybel/struct/utils.py
|
src/pybel/struct/utils.py
|
from collections import defaultdict
def hash_dict(d):
"""Hashes a dictionary
:param dict d: A dictionary to recursively hash
:return: the hash value of the dictionary
:rtype: int
"""
h = 0
for k, v in sorted(d.items()):
h += hash(k)
if isinstance(v, (set, list)):
h += hash(tuple(sorted(v)))
if isinstance(v, dict):
h += hash_dict(v)
if isinstance(v, (bool, int, tuple, str)):
h += hash(v)
return hash(h)
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_dict(d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
|
from collections import defaultdict
from ..utils import hash_edge
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
|
Cut out old hash function
|
Cut out old hash function
|
Python
|
mit
|
pybel/pybel,pybel/pybel,pybel/pybel
|
python
|
## Code Before:
from collections import defaultdict
def hash_dict(d):
"""Hashes a dictionary
:param dict d: A dictionary to recursively hash
:return: the hash value of the dictionary
:rtype: int
"""
h = 0
for k, v in sorted(d.items()):
h += hash(k)
if isinstance(v, (set, list)):
h += hash(tuple(sorted(v)))
if isinstance(v, dict):
h += hash_dict(v)
if isinstance(v, (bool, int, tuple, str)):
h += hash(v)
return hash(h)
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_dict(d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
## Instruction:
Cut out old hash function
## Code After:
from collections import defaultdict
from ..utils import hash_edge
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
|
...
from collections import defaultdict
from ..utils import hash_edge
def stratify_hash_edges(graph):
...
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
...
|
09052d05c27921bc87b0c968de02b244b4e5a56b
|
cryptchat/test/test_networkhandler.py
|
cryptchat/test/test_networkhandler.py
|
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
def setUp(self):
alice = DiffieHellman()
bob = DiffieHellman()
a = alice.gensessionkey(bob.publickey)
b = bob.gensessionkey(alice.publickey)
aes1 = AESCipher(a)
aes2 = AESCipher(b)
self.server = NetworkHandler("localhost", 8090, True, alice, aes1)
self.client = NetworkHandler("localhost", 8090, False, bob, aes2)
def test_sendmessage(self):
self.server.start()
self.client.start()
m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö"
self.client.send(m)
m2 = self.server.getinmessage()
self.assertEqual(m, m2)
def tearDown(self):
self.server.stop()
self.client.stop()
def main():
unittest.main()
if __name__ == '__main__':
main()
|
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
@classmethod
def setUpClass(self):
alice = DiffieHellman()
bob = DiffieHellman()
a = alice.gensessionkey(bob.publickey)
b = bob.gensessionkey(alice.publickey)
aes1 = AESCipher(a)
aes2 = AESCipher(b)
self.server = NetworkHandler("localhost", 8090, True, alice, aes1)
self.client = NetworkHandler("localhost", 8090, False, bob, aes2)
def test_sendmessage(self):
self.server.start()
self.client.start()
m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö"
self.client.send(m)
m2 = self.server.getinmessage()
self.assertEqual(m, m2)
def main():
unittest.main()
if __name__ == '__main__':
main()
|
Set up server/client once for the netcode test
|
Set up server/client once for the netcode test
|
Python
|
mit
|
djohsson/Cryptchat
|
python
|
## Code Before:
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
def setUp(self):
alice = DiffieHellman()
bob = DiffieHellman()
a = alice.gensessionkey(bob.publickey)
b = bob.gensessionkey(alice.publickey)
aes1 = AESCipher(a)
aes2 = AESCipher(b)
self.server = NetworkHandler("localhost", 8090, True, alice, aes1)
self.client = NetworkHandler("localhost", 8090, False, bob, aes2)
def test_sendmessage(self):
self.server.start()
self.client.start()
m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö"
self.client.send(m)
m2 = self.server.getinmessage()
self.assertEqual(m, m2)
def tearDown(self):
self.server.stop()
self.client.stop()
def main():
unittest.main()
if __name__ == '__main__':
main()
## Instruction:
Set up server/client once for the netcode test
## Code After:
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
@classmethod
def setUpClass(self):
alice = DiffieHellman()
bob = DiffieHellman()
a = alice.gensessionkey(bob.publickey)
b = bob.gensessionkey(alice.publickey)
aes1 = AESCipher(a)
aes2 = AESCipher(b)
self.server = NetworkHandler("localhost", 8090, True, alice, aes1)
self.client = NetworkHandler("localhost", 8090, False, bob, aes2)
def test_sendmessage(self):
self.server.start()
self.client.start()
m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö"
self.client.send(m)
m2 = self.server.getinmessage()
self.assertEqual(m, m2)
def main():
unittest.main()
if __name__ == '__main__':
main()
|
...
class testNetworkHandler(unittest.TestCase):
@classmethod
def setUpClass(self):
alice = DiffieHellman()
bob = DiffieHellman()
a = alice.gensessionkey(bob.publickey)
...
m2 = self.server.getinmessage()
self.assertEqual(m, m2)
def main():
unittest.main()
...
|
0180aead701820d2de140791c3e271b4b8a7d231
|
tests/__init__.py
|
tests/__init__.py
|
import os
def fixture_response(path):
return open(os.path.join(
os.path.dirname(__file__),
'fixtures',
path)).read()
|
import os
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
|
Fix file handlers being left open for fixtures
|
Fix file handlers being left open for fixtures
|
Python
|
mit
|
accepton/accepton-python
|
python
|
## Code Before:
import os
def fixture_response(path):
return open(os.path.join(
os.path.dirname(__file__),
'fixtures',
path)).read()
## Instruction:
Fix file handlers being left open for fixtures
## Code After:
import os
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
|
...
def fixture_response(path):
with open(os.path.join(os.path.dirname(__file__),
'fixtures',
path)) as fixture:
return fixture.read()
...
|
d1d0576b94ce000a77e08bd8353f5c1c10b0839f
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = '[email protected]',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
)
|
from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode','audioTranscode.encoders','audioTranscode.decoders'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = '[email protected]',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
)
|
Include .encoders and .decoders packages with the distribution
|
Include .encoders and .decoders packages with the distribution
|
Python
|
isc
|
jeffayle/Transcode
|
python
|
## Code Before:
from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = '[email protected]',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
)
## Instruction:
Include .encoders and .decoders packages with the distribution
## Code After:
from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode','audioTranscode.encoders','audioTranscode.decoders'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = '[email protected]',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
)
|
...
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode','audioTranscode.encoders','audioTranscode.decoders'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = '[email protected]',
...
|
e8537feff53310913047d06d95f4dd8e9dace1da
|
flow_workflow/historian/handler.py
|
flow_workflow/historian/handler.py
|
from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError
from twisted.internet import defer
import flow.interfaces
import logging
import os
LOG = logging.getLogger(__name__)
@inject(storage=flow.interfaces.IStorage,
queue_name=setting('workflow.historian.queue'))
class WorkflowHistorianMessageHandler(Handler):
message_class = UpdateMessage
def _handle_message(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
return defer.succeed(None)
except (ResourceClosedError, TimeoutError, DisconnectionError):
LOG.exception("This historian cannot handle messages anymore, "
"because it lost access to Oracle... exiting.")
exit_process(exit_codes.EXECUTE_FAILURE)
|
from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError
from twisted.internet import defer
import flow.interfaces
import logging
import os
LOG = logging.getLogger(__name__)
@inject(storage=flow.interfaces.IStorage,
queue_name=setting('workflow.historian.queue'))
class WorkflowHistorianMessageHandler(Handler):
message_class = UpdateMessage
def _handle_message(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
return defer.succeed(None)
except (ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError):
LOG.exception("This historian cannot handle messages anymore, "
"because it lost access to Oracle... exiting.")
exit_process(exit_codes.EXECUTE_FAILURE)
|
Add DatabaseError to list of errors that kill a historian
|
Add DatabaseError to list of errors that kill a historian
|
Python
|
agpl-3.0
|
genome/flow-workflow,genome/flow-workflow,genome/flow-workflow
|
python
|
## Code Before:
from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError
from twisted.internet import defer
import flow.interfaces
import logging
import os
LOG = logging.getLogger(__name__)
@inject(storage=flow.interfaces.IStorage,
queue_name=setting('workflow.historian.queue'))
class WorkflowHistorianMessageHandler(Handler):
message_class = UpdateMessage
def _handle_message(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
return defer.succeed(None)
except (ResourceClosedError, TimeoutError, DisconnectionError):
LOG.exception("This historian cannot handle messages anymore, "
"because it lost access to Oracle... exiting.")
exit_process(exit_codes.EXECUTE_FAILURE)
## Instruction:
Add DatabaseError to list of errors that kill a historian
## Code After:
from flow import exit_codes
from flow.configuration.settings.injector import setting
from flow.handler import Handler
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError
from twisted.internet import defer
import flow.interfaces
import logging
import os
LOG = logging.getLogger(__name__)
@inject(storage=flow.interfaces.IStorage,
queue_name=setting('workflow.historian.queue'))
class WorkflowHistorianMessageHandler(Handler):
message_class = UpdateMessage
def _handle_message(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
return defer.succeed(None)
except (ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError):
LOG.exception("This historian cannot handle messages anymore, "
"because it lost access to Oracle... exiting.")
exit_process(exit_codes.EXECUTE_FAILURE)
|
...
from flow.util.exit import exit_process
from flow_workflow.historian.messages import UpdateMessage
from injector import inject
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError
from twisted.internet import defer
import flow.interfaces
...
try:
self.storage.update(message_dict)
return defer.succeed(None)
except (ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError):
LOG.exception("This historian cannot handle messages anymore, "
"because it lost access to Oracle... exiting.")
exit_process(exit_codes.EXECUTE_FAILURE)
...
|
46bcad1e20e57f66498e7a70b8f3be929115bde6
|
incunafein/module/page/extensions/prepared_date.py
|
incunafein/module/page/extensions/prepared_date.py
|
from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
|
from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter():
if not cls._prepared_date:
try:
return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull=False)[0]._prepared_date
except IndexError:
return None
return cls._prepared_date
def setter(value):
cls._prepared_date = value
cls.prepared_date = property(getter, setter)
if admin_cls and admin_cls.fieldsets:
admin_cls.fieldsets[2][1]['fields'].append('_prepared_date')
|
Return parent date if there isn't one on the current object
|
Return parent date if there isn't one on the current object
Look for a prepared date in the ancestors of the current object and use
that if it exists
|
Python
|
bsd-2-clause
|
incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms
|
python
|
## Code Before:
from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
## Instruction:
Return parent date if there isn't one on the current object
Look for a prepared date in the ancestors of the current object and use
that if it exists
## Code After:
from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter():
if not cls._prepared_date:
try:
return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull=False)[0]._prepared_date
except IndexError:
return None
return cls._prepared_date
def setter(value):
cls._prepared_date = value
cls.prepared_date = property(getter, setter)
if admin_cls and admin_cls.fieldsets:
admin_cls.fieldsets[2][1]['fields'].append('_prepared_date')
|
// ... existing code ...
from django.db import models
def register(cls, admin_cls):
cls.add_to_class('_prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
def getter():
if not cls._prepared_date:
try:
return cls.get_ancestors(ascending=True).filter(_prepared_date__isnull=False)[0]._prepared_date
except IndexError:
return None
return cls._prepared_date
def setter(value):
cls._prepared_date = value
cls.prepared_date = property(getter, setter)
if admin_cls and admin_cls.fieldsets:
admin_cls.fieldsets[2][1]['fields'].append('_prepared_date')
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.