I have 80k+ Entries in table Calendar. When I run either of the following 2 methods, the filter or get is taking too long to execute and due to which server is getting crashed after sometime and no new entries are getting added. I want to know if there are any more methods from which I can solve this issue.
Method 1:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()
for j in date_list:
for i in profiles:
try:
Calendar.objects.get(date=j,emp_id = i.emp_id)
except Calendar.DoesNotExist:
e = Calander()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
e.save()
Method 2:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()
for j in date_list:
for i in profiles:
cal = Calander.objects.filter(date=j,emp_id = i.emp_id).count()
if cal < 1:
e = Calander()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
e.save()
Try this:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
for j in date_list:
profiles = Profile.objects.exclude(emp_id__in=Calendar.objects.filter(date=j).values('emp_id'))
calendars = []
for i in profiles:
e = Calendar()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
calendars.append(e)
Calendar.objects.bulk_create(calendars)
Related
Following this post Google Sheets QUERY with WHERE on multiple columns I build up my formula to select specific values from more columns but when I had a condition data start to be confused and not equal to what I selected. I started from this query which works perfectly on one column for each IF:
=QUERY(Concerti!A1:AL; "SELECT * WHERE 1=1" &IF(A2="TUTTI";"";" AND E = '"&A2&"' ") &IF(E2="TUTTI";"";" AND H = '"&E2&"' ") &IF(F2="TUTTI";"";" AND B = "&F2&" "); 1)
Then I wrote this query to select (and filter) the content in A4, E4 and F4 but it doesn't work correctly i.e. it keeps some data which doesn't exactly match with the values on A4, E4 and F4.
=QUERY(Concerti!A1:AL; "SELECT * WHERE 1=1" &IF(A2="TUTTI";"";" AND E = '"&A2&"' ") &IF(E2="TUTTI";"";" AND H = '"&E2&"' ") &IF(F2="TUTTI";"";" AND B = "&F2&" ") &IF(A4="TUTTI";"";" AND I = ('"&A$4&"') OR (K='"&A$4&"' OR M='"&A$4&"' OR O='"&A$4&"' OR Q='"&A$4&"' OR S='"&A$4&"') ") &IF(E4="TUTTI";"";" AND J = ('"&E$4&"') OR (L='"&E$4&"' OR N='"&E$4&"' OR P='"&E$4&"' OR R='"&E$4&"' OR T='"&E$4&"') ") &IF(F4="TUTTI";"";" AND Y = ('"&F$4&"') OR (AA='"&F$4&"' OR AC='"&F$4&"' OR AE='"&F$4&"' OR AG='"&F$4&"' OR AI='"&E$4&"') "); 1)
Where is my mistake? Thank you so much in advance!!! I post a screenshot of the project:
[![Filtering mask](https://i.stack.imgur.com/cRFLv.png)](https://i.stack.imgur.com/cRFLv.png)
try:
=QUERY(Concerti!A1:AL; "where 1=1"&
IF(A2="TUTTI";;" and E = '"&A2&"'")&
IF(E2="TUTTI";;" and H = '"&E2&"'")&
IF(F2="TUTTI";;" and B = "&F2&" ")&
IF(A4="TUTTI";;" and (I = '"&A$4&"'
or K = '"&A$4&"'
or M = '"&A$4&"'
or O = '"&A$4&"'
or Q = '"&A$4&"'
or S = '"&A$4&"')")&
IF(E4="TUTTI";;" and (J = '"&E$4&"'
or L = '"&E$4&"'
or N = '"&E$4&"'
or P = '"&E$4&"'
or R = '"&E$4&"'
or T = '"&E$4&"')")&
IF(F4="TUTTI";;" and (Y = '"&F$4&"'
or AA= '"&F$4&"'
or AC= '"&F$4&"'
or AE= '"&F$4&"'
or AG= '"&F$4&"'
or AI= '"&E$4&"')"); 1)
I'm new to TF and ML.
Details about data: Features(x) - (70 x 70 x 70) tensor for each sample, y - a float for each sample.
TFRecords created with the following code:
def convert_to_tf_records():
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float64_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
tfrecords_filename = 'A-100-h2-h2o.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename)
# Get data from db for now.
db = connect('results-60-70.db')
data = db.select(selection='Ti')
i = 0
for row in data:
desc = np.array(json.loads(row.descriptor), dtype=np.float32)
print(desc.shape)
be = float(row.binding_energy) * 23 # Convert to Kcal/mol ?
desc = desc.flatten()
desc = desc.tostring()
example = tf.train.Example(features=tf.train.Features(feature={'voxel_grid': _bytes_feature(desc), 'binding_energy': _float64_feature(be)}))
writer.write(example.SerializeToString())
i += 1
if i >= 10:
break
Input function:
def my_input_function(fname, perform_shuffle=False, repeat_count=None):
def _parse_elements(example):
features = tf.parse_single_example(example, features={'voxel_grid': tf.FixedLenFeature([], tf.string), 'binding_energy': tf.FixedLenFeature([], tf.float32)})
vg = tf.decode_raw(features['voxel_grid'], tf.float32)
vg = tf.reshape(vg, [70, 70, 70])
vg = tf.convert_to_tensor(vg, dtype=tf.float32)
vg = {'voxel_grid': vg}
e = tf.cast(features['binding_energy'], tf.float32)
return vg, e
def input_function():
dataset = tf.data.TFRecordDataset(fname).map(_parse_elements)
dataset = dataset.repeat(repeat_count)
dataset = dataset.batch(5)
dataset = dataset.prefetch(1)
if perform_shuffle:
dataset.shuffle(20)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
return input_function
Model function:
def my_model_function(features, labels, mode):
if mode == tf.estimator.ModeKeys.PREDICT:
tf.logging.info("my_model_fn: PREDICT, {}".format(mode))
elif mode == tf.estimator.ModeKeys.EVAL:
tf.logging.info("my_model_fn: EVAL, {}".format(mode))
elif mode == tf.estimator.ModeKeys.TRAIN:
tf.logging.info("my_model_fn: TRAIN, {}".format(mode))
feature_columns = [tf.feature_column.numeric_column('voxel_grid', shape=(70, 70, 70), dtype=tf.float32)]
# Create the layer of input
input_layer = tf.feature_column.input_layer(features, feature_columns)
input_layer = tf.reshape(input_layer, [-1, 70, 70, 70, 1])
# Convolution layers
conv1 = tf.layers.conv3d(inputs=input_layer, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
conv2 = tf.layers.conv3d(inputs=conv1, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
pool3 = tf.layers.max_pooling3d(inputs=conv2, pool_size=[2, 2, 2], strides=2)
flat = tf.layers.flatten(pool3)
dense1 = tf.layers.dense(inputs=flat, units=10, activation=tf.nn.relu)
dense2 = tf.layers.dense(inputs=dense1, units=10, activation=tf.nn.relu)
output = tf.layers.dense(inputs=dense2, units=1)
predictions = {'binding_energy': output}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
# Add evaluation metrics
eval_metric_ops = {"mse": tf.metrics.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])}
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
When calling model.train using
model = tf.estimator.Estimator(model_fn=my_model_function, model_dir='./model_dir')
model.train(input_fn=my_input_function('A-100-h2-h2o.tfrecords'), steps=100)
I get the following error.
TypeError: Failed to convert object of type to Tensor.
Found it!
changing
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
to
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])
solves the issue.
This way actually worked. But are there any simplified answer.
dayname(Num,Name) :-
member([Num,Name],
[[1,'Monday'],[2,'Tuesday'],[3,'Wednesday'],[4,'Thursday'],
[5,'Friday'],[6,'Saturday'],[7,'Sunday'],[8,'Monday'],
[9,'Tuesday'],[10,'Wednesday'],[11,'Thursday'],[12,'Friday'],
[13,'Saturday'],[14,'Sunday'],[15,'Monday'],[16,'Tuesday'],
[17,'Wednesday'],[18,'Thursday'],[19,'Friday'],[20,'Saturday'],
[21,'Sunday'],[22,'Monday'],[23,'Tuesday'],[24,'Wednesday'],
[25,'Thursday'],[26,'Friday'],[27,'Saturday'],[28,'Sunday'],
[29,'Monday'],[30,'Tuesday'],[31,'Monday']]).
Yes. First of all you do not need to use member/2 for facts. You can list these as facts:
dayname(1,'Monday').
dayname(2,'Tuesday').
dayname(3,'Wednesday').
dayname(4,'Thursday').
dayname(5,'Friday').
dayname(6,'Saturday').
dayname(7,'Sunday').
But now we have of course no way to obtain 'Monday' for 8. Probably the most declarative way to do this is the following clause:
:- use_module(library(clpfd)).
dayname(I,D) :-
I in 8..31,
J #= I-7,
dayname(J,D).
Putting this all together, we get:
:- use_module(library(clpfd)).
dayname(1,'Monday').
dayname(2,'Tuesday').
dayname(3,'Wednesday').
dayname(4,'Thursday').
dayname(5,'Friday').
dayname(6,'Saturday').
dayname(7,'Sunday').
dayname(I,D) :-
I in 8..31,
J #= I-7,
dayname(J,D).
We then query it in all possible ways:
?- dayname(I,D).
I = 1,
D = 'Monday' ;
I = 2,
D = 'Tuesday' ;
I = 3,
D = 'Wednesday' ;
I = 4,
D = 'Thursday' ;
I = 5,
D = 'Friday' ;
I = 6,
D = 'Saturday' ;
I = 7,
D = 'Sunday' ;
I = 8,
D = 'Monday' ;
I = 9,
D = 'Tuesday' ;
I = 10,
D = 'Wednesday' ;
I = 11,
D = 'Thursday' ;
I = 12,
D = 'Friday' ;
I = 13,
D = 'Saturday' ;
I = 14,
D = 'Sunday' ;
I = 15,
D = 'Monday' ;
I = 16,
D = 'Tuesday' ;
I = 17,
D = 'Wednesday' ;
I = 18,
D = 'Thursday' ;
I = 19,
D = 'Friday' ;
I = 20,
D = 'Saturday' ;
I = 21,
D = 'Sunday' ;
I = 22,
D = 'Monday' ;
I = 23,
D = 'Tuesday' ;
I = 24,
D = 'Wednesday' ;
I = 25,
D = 'Thursday' ;
I = 26,
D = 'Friday' ;
I = 27,
D = 'Saturday' ;
I = 28,
D = 'Sunday' ;
I = 29,
D = 'Monday' ;
I = 30,
D = 'Tuesday' ;
I = 31,
D = 'Wednesday' ;
false.
?- dayname(15,D).
D = 'Monday' ;
false.
?- dayname(I,'Thursday').
I = 4 ;
I = 11 ;
I = 18 ;
I = 25 ;
false.
?- dayname(12,'Thursday').
false.
?- dayname(11,'Thursday').
true ;
false.
My problem at the moment is I am trying to change a label(label 16) to the first value of entry_values[0] which isn't working I have tried passing it in as a variable and many other things, after about an hour of research I couldn't find a solution.I think the main problem is that it sets the label before the code with the entry is run so that it wont change. when I set it to a textvariable it produces an empty string (I think) but when I use just text it puts in a 0 where I expect my number.
def sub_menu(root):
global subpage
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: save_entries())
button5.grid(row = 1, column = 6, sticky = E)
button6 = Button(subpage, text="Return To Main Page",
command = lambda: switch_page("main"))
button6.grid(row = 0, column = 6, sticky = W)
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Population (Thousands)")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
birth_rate_label5 = Label(subpage,text="Birth Rate")
number_of_gens_label6 = Label(subpage,text="Number of Generations")
disease_trigger_label7 = Label(subpage,text="Disease Trigger Point")
global entry0
entry0 = Entry(subpage)
global entry1
entry1 = Entry(subpage)
global entry2
entry2 = Entry(subpage)
global entry3
entry3 = Entry(subpage)
global entry4
entry4 = Entry(subpage)
global entry5
entry5 = Entry(subpage)
global entry6
entry6 = Entry(subpage)
global entry7
entry7 = Entry(subpage)
global entry8
entry8 = Entry(subpage)
juveniles_label0.grid(row = 0, column = 1)
adults_label1.grid(row = 0, column = 2)
seniles_label2.grid(row = 0, column = 3)
population_label3.grid(row = 1, column = 0)
survival_rate_label4.grid(row = 2, column = 0)
birth_rate_label5.grid(row = 3, column = 0)
number_of_gens_label6.grid(row = 3, column = 2)
disease_trigger_label7.grid(row = 4, column = 0)
entry0.grid(row = 1, column = 1)
entry1.grid(row = 1, column = 2)
entry2.grid(row = 1, column = 3)
entry3.grid(row = 2, column = 1)
entry4.grid(row = 2, column = 2)
entry5.grid(row = 2, column = 3)
entry6.grid(row = 3, column = 1)
entry7.grid(row = 3, column = 3)
entry8.grid(row = 4, column = 1)
return subpage
def save_entries(): #entry recieve point
save_page = Frame(root)
""" if e0 < 0:
make a check to check if value is < 0 dont accept and if a value is inputed or not using if type(string_name) == str """
e0 = entry0.get()
if e0 >= 0:
entry_values[0] = (e0)
e1 = entry1.get()
if e0 >= 0:
entry_values[1] = (e1)
e2 = entry2.get()
if e0 >= 0:
entry_values[2] = (e2)
e3 = entry3.get()
if e0 >= 0:
entry_values[3] = (e3)
e4 = entry4.get()
if e0 >= 0:
entry_values[4] = (e4)
e5 = entry5.get()
if e0 >= 0:
entry_values[5] = (e5)
e6 = entry6.get()
if e0 >= 0:
entry_values[6] = (e6)
e7 = entry7.get()
if e0 >= 0:
entry_values[7] = (e7)
e8 = entry8.get()
if e0 >= 0:
entry_values[8] = (e8)
print entry_values
return save_page
def display_values(root):
sub2 = Frame(root)
global entry_values
label8 = Label(sub2, text = "Juveniles")
label9 = Label(sub2, text = "Adults")
label10 = Label(sub2, text = "Seniles")
label11 = Label(sub2, text = "Population(Thousands)")
label12 = Label(sub2, text = "Survival Rate(Between 1 and 0)")
label13 = Label(sub2, text = "Birth Rate")
label14 = Label(sub2, text = "Number of Generations")
label15 = Label(sub2, text = "Disase Trigger Point")
label16 = Label(sub2, text = entry_values[0])
label17 = Label(sub2, textvariable = entry_values[1])
label18 = Label(sub2, textvariable = "")
label19 = Label(sub2, textvariable = "")
label20 = Label(sub2, textvariable = "")
label21 = Label(sub2, textvariable = "")
label22 = Label(sub2, textvariable = "")
label23 = Label(sub2, textvariable = "")
label24 = Label(sub2, textvariable = "")
button7 = Button(sub2, text="Return To Main Page",
command = lambda: switch_page("main"))
label8.grid(row = 0, column = 1)
label9.grid(row = 0, column = 2)
label10.grid(row = 0, column = 3)
label11.grid(row = 1, column = 0)
label12.grid(row = 2, column = 0)
label13.grid(row = 3, column = 0)
label14.grid(row = 3, column = 3)
label15.grid(row = 4, column = 0)
label16.grid(row = 1, column = 1)
label17.grid(row = 1, column = 2)
label18.grid(row = 1, column = 3)
label19.grid(row = 2, column = 1)
label20.grid(row = 2, column = 2)
label21.grid(row = 2, column = 3)
label22.grid(row = 3, column = 1)
label23.grid(row = 3, column = 3)
label24.grid(row = 4, column = 1)
button7.grid(row = 0, column = 0)
return sub2
In order to change the text of a label you can do:
label["text"] = textVar
or
label.config(text=textVar)
So in your above code, when the entry changes, reconfigure the label using one of the above options.
I am getting the error need more than 1 value to unpack i am using defaultDict to make my list to dictionary.
def getTabsCols(request):
proj_name = request.GET.get('projname')
cursor = connection.cursor()
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
result = cursor.fetchall()
tab_list = []
tab_col_list = []
prd = {}
res = []
for row in result:
tabs = collections.OrderedDict()
schema_name = row[1]
table_name = row[3]
tab = (schema_name + '.' + table_name).encode('utf8')
tabs[tab] = row[5].encode('utf8')
tab_list.append(tabs)
d = collections.defaultdict(set)
for k, v in tab_list:
d1[k].append(v)
d = dict((k, tuple(v)) for k, v in d1.iteritems())
return HttpResponse(d, content_type="text/html")