prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
<|fim_middle|>
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | deltas = [] |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
<|fim_middle|>
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | cli() |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def <|fim_middle|>(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | is_quantile |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def <|fim_middle|>(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | is_stat |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def <|fim_middle|>():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | get_args |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def <|fim_middle|>(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | compute |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def <|fim_middle|>(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | analyze |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def <|fim_middle|>(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | write_result |
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|>"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def <|fim_middle|>():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
<|fim▁end|> | cli |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def test_merge_Zmap():<|fim▁hole|> reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
pytest.main()<|fim▁end|> | |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
<|fim_middle|>
def test_merge_Zmap():
reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
pytest.main()
<|fim▁end|> | reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___') |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def test_merge_Zmap():
<|fim_middle|>
if __name__ == '__main__':
pytest.main()
<|fim▁end|> | reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2) |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def test_merge_Zmap():
reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | pytest.main() |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def <|fim_middle|>():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def test_merge_Zmap():
reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
pytest.main()
<|fim▁end|> | test_read_seq |
<|file_name|>test_seqreader.py<|end_file_name|><|fim▁begin|>import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def <|fim_middle|>():
reader = SeqReader()
reader.read_seq(resource('seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
pytest.main()
<|fim▁end|> | test_merge_Zmap |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Stefano Palazzo <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
hello
Usage:
hello (--help | --version)
<|fim▁hole|>
'''
import sys
import docopt
import hello
def main(argv=sys.argv[1:]):
try:
docopt.docopt(__doc__, argv=argv, version=hello.__version__)
except docopt.DocoptExit as e:
print(str(e), file=sys.stderr)
return 2
except SystemExit as e:
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())<|fim▁end|> | Options:
--help -h display this help message and exit
--version print version information and exit |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Stefano Palazzo <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
hello
Usage:
hello (--help | --version)
Options:
--help -h display this help message and exit
--version print version information and exit
'''
import sys
import docopt
import hello
def main(argv=sys.argv[1:]):
<|fim_middle|>
if __name__ == "__main__": # pragma: no cover
sys.exit(main())
<|fim▁end|> | try:
docopt.docopt(__doc__, argv=argv, version=hello.__version__)
except docopt.DocoptExit as e:
print(str(e), file=sys.stderr)
return 2
except SystemExit as e:
return 0 |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Stefano Palazzo <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
hello
Usage:
hello (--help | --version)
Options:
--help -h display this help message and exit
--version print version information and exit
'''
import sys
import docopt
import hello
def main(argv=sys.argv[1:]):
try:
docopt.docopt(__doc__, argv=argv, version=hello.__version__)
except docopt.DocoptExit as e:
print(str(e), file=sys.stderr)
return 2
except SystemExit as e:
return 0
if __name__ == "__main__": # pragma: no cover
<|fim_middle|>
<|fim▁end|> | sys.exit(main()) |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Stefano Palazzo <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
hello
Usage:
hello (--help | --version)
Options:
--help -h display this help message and exit
--version print version information and exit
'''
import sys
import docopt
import hello
def <|fim_middle|>(argv=sys.argv[1:]):
try:
docopt.docopt(__doc__, argv=argv, version=hello.__version__)
except docopt.DocoptExit as e:
print(str(e), file=sys.stderr)
return 2
except SystemExit as e:
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())
<|fim▁end|> | main |
<|file_name|>max_tiff.py<|end_file_name|><|fim▁begin|>from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1')
fig1 = plt.figure(1)
img1.seek(0)
# for i in range(250):
# pixA11 = img1.getpixel((1,i))
# print(pixA11)
f1 = list(img1.getdata())
print(f1[1000])
plt.imshow(img1)
fig1.show()
input()
# Plots eleventh frame
# print('Frame 11')
# fig2 = plt.figure(2)
# img1.seek(10)
# # for i in range(250):
# # pixB11 = img1.getpixel((1,i))
# # print(pixB11)
# f2 = list(img1.getdata())
# print(f2[10000])
# plt.imshow(img1)
# fig2.show()
# input()
# Create a new image
fig3 = plt.figure(3)
imgAvg = Image.new(img1.mode, img1.size)
print(img1.mode)
print(img1.size)
fAvg = list()
pix = imgAvg.load()
for i in range(512):
for j in range(512):
pixVal = (f1[i*512+j] + f1[i*512+j]) / 2
# fAvg.append(pixVal)
fAvg.insert(i*512+j,pixVal)
imgAvg.putdata(fAvg)
imgAvg.save('avg.tiff')
plt.imshow(imgAvg)
fig3.show()
print('Average')
# The following is necessary to keep the above figures 'alive'
input()
<|fim▁hole|># data = random.random((256, 256))
# img1 = Image.fromarray(data)
# img1.save('test.tiff')<|fim▁end|> | |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#<|fim▁hole|>#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)<|fim▁end|> | # Copyright (C) 2009-2012 HDE, Inc. |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
<|fim_middle|>
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | @auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path) |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
<|fim_middle|>
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | (host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path) |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: <|fim_middle|>
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | return web.notfound() |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
<|fim_middle|>
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | return web.badrequest("Request data is invalid.") |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
<|fim_middle|>
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.") |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: <|fim_middle|>
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | return web.notfound() |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
<|fim_middle|>
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound() |
<|file_name|>guestby1currentsnapshot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def <|fim_middle|>(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
<|fim▁end|> | _PUT |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):<|fim▁hole|> Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()<|fim▁end|> | """ |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
<|fim_middle|>
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | return bool(float_match(string)) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
<|fim_middle|>
<|fim▁end|> | """
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close() |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
<|fim_middle|>
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
<|fim_middle|>
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed" |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
<|fim_middle|>
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
<|fim_middle|>
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
<|fim_middle|>
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
<|fim_middle|>
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
<|fim_middle|>
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close() |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
<|fim_middle|>
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | return bool(float_match(string)) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
<|fim_middle|>
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | """
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
""" |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
<|fim_middle|>
<|fim▁end|> | sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close() |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
<|fim_middle|>
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | self.db.close()
print "MySQL Connection Closed" |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
<|fim_middle|>
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " * " |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
<|fim_middle|>
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma! |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
<|fim_middle|>
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " JOIN %s " % kwargs.get('join') |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
<|fim_middle|>
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " WHERE %s " % kwargs.get('where') |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
<|fim_middle|>
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " LIMIT %s " % kwargs.get('limit') |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
<|fim_middle|>
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | results = self.convert_to_named_tuples(cursor) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
<|fim_middle|>
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | results = cursor.fetchall() |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
<|fim_middle|>
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
<|fim_middle|>
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
<|fim_middle|>
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " AND `%s`.`%s` %s" % (table, where, term) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
<|fim_middle|>
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values) |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
<|fim_middle|>
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | values += "%s, " % value |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
<|fim_middle|>
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | values += "5S, " % value |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
<|fim_middle|>
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
<|fim_middle|>
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += "%s, " % value |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
<|fim_middle|>
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += "'%s', " % value |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
<|fim_middle|>
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | sql_str += " WHERE %s" % where |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def <|fim_middle|>(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | is_number |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def <|fim_middle|>(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | __init__ |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def <|fim_middle|>(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | __del__ |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def <|fim_middle|>(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | get_available_tables |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def <|fim_middle|>(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | convert_to_named_tuples |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def <|fim_middle|>(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | get_columns_for_table |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def <|fim_middle|>(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | select |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def <|fim_middle|>(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | delete |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def <|fim_middle|>(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | is_number |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def <|fim_middle|>(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | insert |
<|file_name|>mysql.py<|end_file_name|><|fim▁begin|>import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def <|fim_middle|>(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
<|fim▁end|> | update |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software<|fim▁hole|>"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config<|fim▁end|> | # 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. |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
<|fim_middle|>
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
<|fim_middle|>
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | """A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
<|fim_middle|>
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | self._masked_tokens = masked_tokens or []
super().__init__(name, dtype) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
<|fim_middle|>
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
<|fim_middle|>
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
<|fim_middle|>
<|fim▁end|> | """An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
<|fim_middle|>
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
<|fim_middle|>
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
<|fim_middle|>
<|fim▁end|> | config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
<|fim_middle|>
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | sample_weight = tf.ones_like(y_true, dtype) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
<|fim_middle|>
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | sample_weight = tf.cast(sample_weight, dtype) |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def <|fim_middle|>(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | _apply_mask |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def <|fim_middle|>(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | __init__ |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def <|fim_middle|>(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | update_state |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def <|fim_middle|>(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | get_config |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def <|fim_middle|>(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | __init__ |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def <|fim_middle|>(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | update_state |
<|file_name|>keras_metrics.py<|end_file_name|><|fim▁begin|># Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_true, token), dtype)
sample_weight = sample_weight * mask
return sample_weight
class NumTokensCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""
def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(sample_weight)
def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that masks some tokens."""
def __init__(self, masked_tokens=None, name='accuracy', dtype=None):
self._masked_tokens = masked_tokens or []
super().__init__(name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens,
self._dtype)
num_classes = tf.shape(y_pred)[-1]
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1, num_classes])
sample_weight = tf.reshape(sample_weight, [-1])
super().update_state(y_true, y_pred, sample_weight)
def <|fim_middle|>(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config
<|fim▁end|> | get_config |
<|file_name|>media.py<|end_file_name|><|fim▁begin|>class movie:
"""Stores movie metadata"""
# The constructor takes
# - The Title
# - The youtube trailer
# - The poster image URL
def __init__(self, title, youtube_trailer, poster_url):
self.title = title<|fim▁hole|><|fim▁end|> | self.trailer_youtube_url = youtube_trailer
self.poster_image_url = poster_url |
<|file_name|>media.py<|end_file_name|><|fim▁begin|>class movie:
<|fim_middle|>
<|fim▁end|> | """Stores movie metadata"""
# The constructor takes
# - The Title
# - The youtube trailer
# - The poster image URL
def __init__(self, title, youtube_trailer, poster_url):
self.title = title
self.trailer_youtube_url = youtube_trailer
self.poster_image_url = poster_url |
<|file_name|>media.py<|end_file_name|><|fim▁begin|>class movie:
"""Stores movie metadata"""
# The constructor takes
# - The Title
# - The youtube trailer
# - The poster image URL
def __init__(self, title, youtube_trailer, poster_url):
<|fim_middle|>
<|fim▁end|> | self.title = title
self.trailer_youtube_url = youtube_trailer
self.poster_image_url = poster_url |
<|file_name|>media.py<|end_file_name|><|fim▁begin|>class movie:
"""Stores movie metadata"""
# The constructor takes
# - The Title
# - The youtube trailer
# - The poster image URL
def <|fim_middle|>(self, title, youtube_trailer, poster_url):
self.title = title
self.trailer_youtube_url = youtube_trailer
self.poster_image_url = poster_url
<|fim▁end|> | __init__ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""<|fim▁hole|> ~~~~~~~
Get popular cat/dog/superhero/supervillain names.
:copyright: (c) 2015 by lord63.
:license: MIT, see LICENSE for more details.
"""
from getname.main import random_name
__title__ = "getname"
__version__ = '0.1.1'
__author__ = "lord63"
__license__ = "MIT"
__copyright__ = "Copyright 2015 lord63"<|fim▁end|> | getname |
<|file_name|>331.py<|end_file_name|><|fim▁begin|>class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()<|fim▁hole|> stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False<|fim▁end|> | if len(stack) < 1:
return False |
<|file_name|>331.py<|end_file_name|><|fim▁begin|>class Solution:
<|fim_middle|>
<|fim▁end|> | def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
if len(stack) < 1:
return False
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False |
<|file_name|>331.py<|end_file_name|><|fim▁begin|>class Solution:
def isValidSerialization(self, preorder):
<|fim_middle|>
<|fim▁end|> | """
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
if len(stack) < 1:
return False
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False |
<|file_name|>331.py<|end_file_name|><|fim▁begin|>class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
if len(stack) < 1:
<|fim_middle|>
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False
<|fim▁end|> | return False |
<|file_name|>331.py<|end_file_name|><|fim▁begin|>class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
if len(stack) < 1:
return False
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
<|fim_middle|>
return False
<|fim▁end|> | return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.