content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
sequence | answers_scores
sequence | non_answers
sequence | non_answers_scores
sequence | tags
sequence | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
tf vesion problem. Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution
This is the code that create problem.
def cost_func(x=None, y=None):
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
tf.compat.v1.disable_eager_execution()
y = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
# two local minima near (0, 0)
# z = __f1(x, y)
# 3rd local minimum at (-0.5, -0.8)
z = -1 * __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.35, y_sig=0.35)
# one steep gaussian trench at (0, 0)
# z -= __f2(x, y, x_mean=0, y_mean=0, x_sig=0.2, y_sig=0.2)
# three steep gaussian trenches
z -= __f2(x, y, x_mean=1.0, y_mean=-0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-1.0, y_mean=0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.2, y_sig=0.2)
return x, y, z
My goal is:
For visualizing contour plot, call f() and collect placeholder nodes for fast GPU calc.
To incorporate variables to optimize, pass them in as argument to attach as x and y.
Args:
x: None if placeholder tensor is used as input. Specify x to use x as input tensor.
y: None if placeholder tensor is used as input. Specify y to use y as input tensor.
Returns:
Tuple (x, y, z) where x and y are input tensors and z is output tensor.
The error is:
using a tf.Tensor as a Python bool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
The fully code is:
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
# cost function
def cost_func(x=None, y=None):
'''Cost function.
For visualizing contour plot, call f() and collect placeholder nodes for fast GPU calc.
To incorporate variables to optimize, pass them in as argument to attach as x and y.
Args:
x: None if placeholder tensor is used as input. Specify x to use x as input tensor.
y: None if placeholder tensor is used as input. Specify y to use y as input tensor.
Returns:
Tuple (x, y, z) where x and y are input tensors and z is output tensor.
'''
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
tf.compat.v1.disable_eager_execution()
y = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
# two local minima near (0, 0)
# z = __f1(x, y)
# 3rd local minimum at (-0.5, -0.8)
z = -1 * __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.35, y_sig=0.35)
# one steep gaussian trench at (0, 0)
# z -= __f2(x, y, x_mean=0, y_mean=0, x_sig=0.2, y_sig=0.2)
# three steep gaussian trenches
z -= __f2(x, y, x_mean=1.0, y_mean=-0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-1.0, y_mean=0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.2, y_sig=0.2)
return x, y, z
# noisy hills of the cost function
def __f1(x, y):
return -1 * tf.sin(x * x) * tf.cos(3 * y * y) * tf.exp(-(x * y) * (x * y)) - tf.exp(-(x + y) * (x + y))
# bivar gaussian hills of the cost function
def __f2(x, y, x_mean, y_mean, x_sig, y_sig):
normalizing = 1 / (2 * np.pi * x_sig * y_sig)
x_exp = (-1 * tf.square(x - x_mean)) / (2 * tf.square(x_sig))
y_exp = (-1 * tf.square(y - y_mean)) / (2 * tf.square(y_sig))
return normalizing * tf.exp(x_exp + y_exp)
# pyplot settings
plt.ion()
fig = plt.figure(figsize=(3, 2), dpi=300)
ax = fig.add_subplot(111, projection='3d')
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
params = {'legend.fontsize': 3,
'legend.handlelength': 3}
plt.rcParams.update(params)
plt.axis('off')
# input (x, y) and output (z) nodes of cost-function graph
x, y, z = cost_func()
# visualize cost function as a contour plot
x_val = y_val = np.arange(-1.5, 1.5, 0.005, dtype=np.float32)
x_val_mesh, y_val_mesh = np.meshgrid(x_val, y_val)
x_val_mesh_flat = x_val_mesh.reshape([-1, 1])
y_val_mesh_flat = y_val_mesh.reshape([-1, 1])
with tf.compat.v1.Session() as sess:
z_val_mesh_flat = sess.run(z, feed_dict={x: x_val_mesh_flat, y: y_val_mesh_flat})
z_val_mesh = z_val_mesh_flat.reshape(x_val_mesh.shape)
levels = np.arange(-10, 1, 0.05)
# ax.contour(x_val_mesh, y_val_mesh, z_val_mesh, levels, alpha=.7, linewidths=0.4)
# ax.plot_wireframe(x_val_mesh, y_val_mesh, z_val_mesh, alpha=.5, linewidths=0.4, antialiased=True)
ax.plot_surface(x_val_mesh, y_val_mesh, z_val_mesh, alpha=.4, cmap=cm.coolwarm)
plt.draw()
# starting location for variables
x_i = 0.75
y_i = 1.0
# create variable pair (x, y) for each optimizer
x_var, y_var = [], []
for i in range(7):
x_var.append(tf.Variable(x_i, [1], dtype=tf.float32))
y_var.append(tf.Variable(y_i, [1], dtype=tf.float32))
# create separate graph for each variable pairs
cost = []
for i in range(7):
cost.append(cost_func(x_var[i], y_var[i])[2])
# define method of gradient descent for each graph
# optimizer label name, learning rate, color
ops_param = np.array([['Adadelta', 50.0, 'b'],
['Adagrad', 0.10, 'g'],
['Adam', 0.05, 'r'],
['Ftrl', 0.5, 'c'],
['GD', 0.05, 'm'],
['Momentum', 0.01, 'y'],
['RMSProp', 0.02, 'k']])
ops = []
ops.append(tf.compat.v1.train.AdadeltaOptimizer(float(ops_param[0, 1])).minimize(cost[0]))
ops.append(tf.compat.v1.train.AdagradOptimizer(float(ops_param[1, 1])).minimize(cost[1]))
ops.append(tf.compat.v1.train.AdamOptimizer(float(ops_param[2, 1])).minimize(cost[2]))
ops.append(tf.compat.v1.train.FtrlOptimizer(float(ops_param[3, 1])).minimize(cost[3]))
ops.append(tf.compat.v1.train.GradientDescentOptimizer(float(ops_param[4, 1])).minimize(cost[4]))
ops.append(tf.compat.v1.train.MomentumOptimizer(float(ops_param[5, 1]), momentum=0.95).minimize(cost[5]))
ops.append(tf.compat.v1.train.RMSPropOptimizer(float(ops_param[6, 1])).minimize(cost[6]))
# 3d plot camera zoom, angle
xlm = ax.get_xlim3d()
ylm = ax.get_ylim3d()
zlm = ax.get_zlim3d()
ax.set_xlim3d(xlm[0] * 0.5, xlm[1] * 0.5)
ax.set_ylim3d(ylm[0] * 0.5, ylm[1] * 0.5)
ax.set_zlim3d(zlm[0] * 0.5, zlm[1] * 0.5)
azm = ax.azim
ele = ax.elev + 40
ax.view_init(elev=ele, azim=azm)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# use last location to draw a line to the current location
last_x, last_y, last_z = [], [], []
plot_cache = [None for _ in range(len(ops))]
# loop each step of the optimization algorithm
steps = 1000
for iter in range(steps):
for i, op in enumerate(ops):
# run a step of optimization and collect new x and y variable values
_, x_val, y_val, z_val = sess.run([op, x_var[i], y_var[i], cost[i]])
# move dot to the current value
if plot_cache[i]:
plot_cache[i].remove()
plot_cache[i] = ax.scatter(x_val, y_val, z_val, s=3, depthshade=True, label=ops_param[i, 0],
color=ops_param[i, 2])
# draw a line from the previous value
if iter == 0:
last_z.append(z_val)
last_x.append(x_i)
last_y.append(y_i)
ax.plot([last_x[i], x_val], [last_y[i], y_val], [last_z[i], z_val], linewidth=0.5, color=ops_param[i, 2])
last_x[i] = x_val
last_y[i] = y_val
last_z[i] = z_val
if iter == 0:
legend = np.vstack((ops_param[:, 0], ops_param[:, 1])).transpose()
plt.legend(plot_cache, legend)
plt.savefig('figures/' + str(iter) + '.png')
print('iteration: {}'.format(iter))
plt.pause(0.0001)
print("done")
If x and y are placeholder tensor and they are used as input, output None. I have tried converting x and y to other types (such as string) if they are placeholder tensors, and then outputting them directly if they are not placeholder tensors. But I found that this didn't work. Then I tried not using keyword arguments, but making the determination within the function, and I found that that didn't work either.
As I understand, I will solve this problem if I use tensorflow v1, but I want to use tensorflow v2. Please help me!!!!
A:
To resolve this error, you can either use eager execution or decorate the function using @tf.function. Eager execution is enabled by default, so if you're using versions of TensorFlow older than 1.10.0, you may need to explicitly enable it in your code. To enable it, you can add the following line of code:
tf.enable_eager_execution()
The @tf.function decorator allows for the conversion of a Python function into a TensorFlow graph. It accepts parameters, such as input signature and autograph, that can be used to control how the graph is generated. For more information, you can refer to the official TensorFlow documentation
| tf vesion problem. Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution | This is the code that create problem.
def cost_func(x=None, y=None):
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
tf.compat.v1.disable_eager_execution()
y = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
# two local minima near (0, 0)
# z = __f1(x, y)
# 3rd local minimum at (-0.5, -0.8)
z = -1 * __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.35, y_sig=0.35)
# one steep gaussian trench at (0, 0)
# z -= __f2(x, y, x_mean=0, y_mean=0, x_sig=0.2, y_sig=0.2)
# three steep gaussian trenches
z -= __f2(x, y, x_mean=1.0, y_mean=-0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-1.0, y_mean=0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.2, y_sig=0.2)
return x, y, z
My goal is:
For visualizing contour plot, call f() and collect placeholder nodes for fast GPU calc.
To incorporate variables to optimize, pass them in as argument to attach as x and y.
Args:
x: None if placeholder tensor is used as input. Specify x to use x as input tensor.
y: None if placeholder tensor is used as input. Specify y to use y as input tensor.
Returns:
Tuple (x, y, z) where x and y are input tensors and z is output tensor.
The error is:
using a tf.Tensor as a Python bool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
The fully code is:
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
# cost function
def cost_func(x=None, y=None):
'''Cost function.
For visualizing contour plot, call f() and collect placeholder nodes for fast GPU calc.
To incorporate variables to optimize, pass them in as argument to attach as x and y.
Args:
x: None if placeholder tensor is used as input. Specify x to use x as input tensor.
y: None if placeholder tensor is used as input. Specify y to use y as input tensor.
Returns:
Tuple (x, y, z) where x and y are input tensors and z is output tensor.
'''
if not x:
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
if not y:
tf.compat.v1.disable_eager_execution()
y = tf.compat.v1.placeholder(tf.float32, shape=[None, 1])
# two local minima near (0, 0)
# z = __f1(x, y)
# 3rd local minimum at (-0.5, -0.8)
z = -1 * __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.35, y_sig=0.35)
# one steep gaussian trench at (0, 0)
# z -= __f2(x, y, x_mean=0, y_mean=0, x_sig=0.2, y_sig=0.2)
# three steep gaussian trenches
z -= __f2(x, y, x_mean=1.0, y_mean=-0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-1.0, y_mean=0.5, x_sig=0.2, y_sig=0.2)
z -= __f2(x, y, x_mean=-0.5, y_mean=-0.8, x_sig=0.2, y_sig=0.2)
return x, y, z
# noisy hills of the cost function
def __f1(x, y):
return -1 * tf.sin(x * x) * tf.cos(3 * y * y) * tf.exp(-(x * y) * (x * y)) - tf.exp(-(x + y) * (x + y))
# bivar gaussian hills of the cost function
def __f2(x, y, x_mean, y_mean, x_sig, y_sig):
normalizing = 1 / (2 * np.pi * x_sig * y_sig)
x_exp = (-1 * tf.square(x - x_mean)) / (2 * tf.square(x_sig))
y_exp = (-1 * tf.square(y - y_mean)) / (2 * tf.square(y_sig))
return normalizing * tf.exp(x_exp + y_exp)
# pyplot settings
plt.ion()
fig = plt.figure(figsize=(3, 2), dpi=300)
ax = fig.add_subplot(111, projection='3d')
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
params = {'legend.fontsize': 3,
'legend.handlelength': 3}
plt.rcParams.update(params)
plt.axis('off')
# input (x, y) and output (z) nodes of cost-function graph
x, y, z = cost_func()
# visualize cost function as a contour plot
x_val = y_val = np.arange(-1.5, 1.5, 0.005, dtype=np.float32)
x_val_mesh, y_val_mesh = np.meshgrid(x_val, y_val)
x_val_mesh_flat = x_val_mesh.reshape([-1, 1])
y_val_mesh_flat = y_val_mesh.reshape([-1, 1])
with tf.compat.v1.Session() as sess:
z_val_mesh_flat = sess.run(z, feed_dict={x: x_val_mesh_flat, y: y_val_mesh_flat})
z_val_mesh = z_val_mesh_flat.reshape(x_val_mesh.shape)
levels = np.arange(-10, 1, 0.05)
# ax.contour(x_val_mesh, y_val_mesh, z_val_mesh, levels, alpha=.7, linewidths=0.4)
# ax.plot_wireframe(x_val_mesh, y_val_mesh, z_val_mesh, alpha=.5, linewidths=0.4, antialiased=True)
ax.plot_surface(x_val_mesh, y_val_mesh, z_val_mesh, alpha=.4, cmap=cm.coolwarm)
plt.draw()
# starting location for variables
x_i = 0.75
y_i = 1.0
# create variable pair (x, y) for each optimizer
x_var, y_var = [], []
for i in range(7):
x_var.append(tf.Variable(x_i, [1], dtype=tf.float32))
y_var.append(tf.Variable(y_i, [1], dtype=tf.float32))
# create separate graph for each variable pairs
cost = []
for i in range(7):
cost.append(cost_func(x_var[i], y_var[i])[2])
# define method of gradient descent for each graph
# optimizer label name, learning rate, color
ops_param = np.array([['Adadelta', 50.0, 'b'],
['Adagrad', 0.10, 'g'],
['Adam', 0.05, 'r'],
['Ftrl', 0.5, 'c'],
['GD', 0.05, 'm'],
['Momentum', 0.01, 'y'],
['RMSProp', 0.02, 'k']])
ops = []
ops.append(tf.compat.v1.train.AdadeltaOptimizer(float(ops_param[0, 1])).minimize(cost[0]))
ops.append(tf.compat.v1.train.AdagradOptimizer(float(ops_param[1, 1])).minimize(cost[1]))
ops.append(tf.compat.v1.train.AdamOptimizer(float(ops_param[2, 1])).minimize(cost[2]))
ops.append(tf.compat.v1.train.FtrlOptimizer(float(ops_param[3, 1])).minimize(cost[3]))
ops.append(tf.compat.v1.train.GradientDescentOptimizer(float(ops_param[4, 1])).minimize(cost[4]))
ops.append(tf.compat.v1.train.MomentumOptimizer(float(ops_param[5, 1]), momentum=0.95).minimize(cost[5]))
ops.append(tf.compat.v1.train.RMSPropOptimizer(float(ops_param[6, 1])).minimize(cost[6]))
# 3d plot camera zoom, angle
xlm = ax.get_xlim3d()
ylm = ax.get_ylim3d()
zlm = ax.get_zlim3d()
ax.set_xlim3d(xlm[0] * 0.5, xlm[1] * 0.5)
ax.set_ylim3d(ylm[0] * 0.5, ylm[1] * 0.5)
ax.set_zlim3d(zlm[0] * 0.5, zlm[1] * 0.5)
azm = ax.azim
ele = ax.elev + 40
ax.view_init(elev=ele, azim=azm)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# use last location to draw a line to the current location
last_x, last_y, last_z = [], [], []
plot_cache = [None for _ in range(len(ops))]
# loop each step of the optimization algorithm
steps = 1000
for iter in range(steps):
for i, op in enumerate(ops):
# run a step of optimization and collect new x and y variable values
_, x_val, y_val, z_val = sess.run([op, x_var[i], y_var[i], cost[i]])
# move dot to the current value
if plot_cache[i]:
plot_cache[i].remove()
plot_cache[i] = ax.scatter(x_val, y_val, z_val, s=3, depthshade=True, label=ops_param[i, 0],
color=ops_param[i, 2])
# draw a line from the previous value
if iter == 0:
last_z.append(z_val)
last_x.append(x_i)
last_y.append(y_i)
ax.plot([last_x[i], x_val], [last_y[i], y_val], [last_z[i], z_val], linewidth=0.5, color=ops_param[i, 2])
last_x[i] = x_val
last_y[i] = y_val
last_z[i] = z_val
if iter == 0:
legend = np.vstack((ops_param[:, 0], ops_param[:, 1])).transpose()
plt.legend(plot_cache, legend)
plt.savefig('figures/' + str(iter) + '.png')
print('iteration: {}'.format(iter))
plt.pause(0.0001)
print("done")
If x and y are placeholder tensor and they are used as input, output None. I have tried converting x and y to other types (such as string) if they are placeholder tensors, and then outputting them directly if they are not placeholder tensors. But I found that this didn't work. Then I tried not using keyword arguments, but making the determination within the function, and I found that that didn't work either.
As I understand, I will solve this problem if I use tensorflow v1, but I want to use tensorflow v2. Please help me!!!!
| [
"To resolve this error, you can either use eager execution or decorate the function using @tf.function. Eager execution is enabled by default, so if you're using versions of TensorFlow older than 1.10.0, you may need to explicitly enable it in your code. To enable it, you can add the following line of code:\ntf.enable_eager_execution()\nThe @tf.function decorator allows for the conversion of a Python function into a TensorFlow graph. It accepts parameters, such as input signature and autograph, that can be used to control how the graph is generated. For more information, you can refer to the official TensorFlow documentation\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074675427_python_tensorflow.txt |
Q:
Laravel nested relationship automatically to model
I wonder if I can do dynamic relationship from pivot table. I'm using mariadb and I have structure tables like this below
table user_has_profiles as pivot model App\Models\PivotProfile
user_id
profile_id
profile_type
uuid-1
uuid-up
App\Models\UserProfile
uuid-1
uuid-tp
App\Models\TeacherProfile
table user_profiles as model App\Models\UserProfile
id
gender
birthday
uuid-up
male
2022-01-01
table teacher_profilesas model App\Models\TeacherProfile
id
teacher_number
country
uuid-tp
TC-001
France
if I query with model Pivotprofile::get() how can I get result like this
[
0 => [
"user_id" => "uuid-1",
"profile_id" => "uuid-up",
"profile_type" => "App\Models\UserProfile",
"profile" => [
"id" => "uuid-up",
"gender" => "male",
"birthday" => "2022-01-01"
]
],
1 => [
"user_id" => "uuid-1",
"profile_id" => "uuid-tp",
"profile_type" => "App\Models\TeacherProfile",
"profile" => [
"id" => "uuid-tp",
"teacher_number" => "TC-001",
"country" => "France"
]
],
]
So PivotProfile automatically have relation according to profile_type. Or maybe you have better option in structure table if users have multiple profile table.
Thank you
A:
One option to achieve this would be to create a polymorphic relationship in the PivotProfile model.
First, define the relationship in the PivotProfile model:
public function profile()
{
return $this->morphTo();
}
Then, you can use the morphTo() method in your query to retrieve the related profile model:
$profiles = PivotProfile::with('profile')->get();
This will return a collection of PivotProfile objects with a "profile" property that contains the related profile model, according to the "profile_type" field in the pivot table.
You can then iterate over the collection and access the profile data for each pivot profile:
foreach ($profiles as $profile) {
$profileData = $profile->profile;
// access profile data here, e.g. $profileData->gender
}
Note that this solution assumes that you have defined the correct morph classes in the profile_type field of the pivot table. For example, if the profile_type is "App\Models\UserProfile", then the UserProfile model should have a $morphClass property set to "App\Models\UserProfile".
Hope this helps! Let me know if you have any further questions.
| Laravel nested relationship automatically to model | I wonder if I can do dynamic relationship from pivot table. I'm using mariadb and I have structure tables like this below
table user_has_profiles as pivot model App\Models\PivotProfile
user_id
profile_id
profile_type
uuid-1
uuid-up
App\Models\UserProfile
uuid-1
uuid-tp
App\Models\TeacherProfile
table user_profiles as model App\Models\UserProfile
id
gender
birthday
uuid-up
male
2022-01-01
table teacher_profilesas model App\Models\TeacherProfile
id
teacher_number
country
uuid-tp
TC-001
France
if I query with model Pivotprofile::get() how can I get result like this
[
0 => [
"user_id" => "uuid-1",
"profile_id" => "uuid-up",
"profile_type" => "App\Models\UserProfile",
"profile" => [
"id" => "uuid-up",
"gender" => "male",
"birthday" => "2022-01-01"
]
],
1 => [
"user_id" => "uuid-1",
"profile_id" => "uuid-tp",
"profile_type" => "App\Models\TeacherProfile",
"profile" => [
"id" => "uuid-tp",
"teacher_number" => "TC-001",
"country" => "France"
]
],
]
So PivotProfile automatically have relation according to profile_type. Or maybe you have better option in structure table if users have multiple profile table.
Thank you
| [
"One option to achieve this would be to create a polymorphic relationship in the PivotProfile model.\nFirst, define the relationship in the PivotProfile model:\npublic function profile()\n{\n return $this->morphTo();\n}\n\nThen, you can use the morphTo() method in your query to retrieve the related profile model:\n$profiles = PivotProfile::with('profile')->get();\n\nThis will return a collection of PivotProfile objects with a \"profile\" property that contains the related profile model, according to the \"profile_type\" field in the pivot table.\nYou can then iterate over the collection and access the profile data for each pivot profile:\nforeach ($profiles as $profile) {\n $profileData = $profile->profile;\n\n // access profile data here, e.g. $profileData->gender\n}\n\nNote that this solution assumes that you have defined the correct morph classes in the profile_type field of the pivot table. For example, if the profile_type is \"App\\Models\\UserProfile\", then the UserProfile model should have a $morphClass property set to \"App\\Models\\UserProfile\".\nHope this helps! Let me know if you have any further questions.\n"
] | [
1
] | [] | [] | [
"laravel"
] | stackoverflow_0074675410_laravel.txt |
Q:
Next JS Rewrites for Sanity CMS giving 404 page after login
I'm currently hosting a Next JS site on Netlify with a Sanity CMS backend for content editing. I've got it configured to run on the single domain IE - examplesite.com has the front-end website, where examplesite.com/sanity opens the Sanity Studio editor.
This works as intended if the editor has a log-in cookie already (from previous login, etc), but if the editor has to login, after going through the login process the site is redirected to /sanity/desk and Next displays a 404 page. The editor then has to visit /sanity to access the CMS, where it redirects successfully to /sanity/desk (no 404).
Following the official Sanity setup guide, I have the following rewrite applied in the Next config.
const SANITY_REWRITE = {
source: "/sanity/:path*",
destination:
process.env.NODE_ENV === "development"
? "http://localhost:3333/sanity/:path*"
: "/sanity/index.html",
};
const DESK_REWRITE = {
source: "/sanity/desk",
destination: "/sanity/index.html",
};
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withBundleAnalyzer({
reactStrictMode: true,
async rewrites() {
return {
beforeFiles: [SANITY_REWRITE, DESK_REWRITE],
};
},
images: {
domains: ["cdn.sanity.io"],
},
});
For completeness, here is my sanity.json as well:
{
"root": true,
"project": {
"name": "main-site",
"basePath": "/sanity"
},
"api": {
"projectId": "ga8f69l8",
"dataset": "production"
},
"plugins": [
"@sanity/base",
"@sanity/components",
"@sanity/default-layout",
"@sanity/default-login",
"@sanity/desk-tool",
"@sanity/dashboard",
"dashboard-widget-netlify"
],
"env": {
"development": {
"plugins": ["@sanity/vision"]
}
},
"parts": [
{
"name": "part:@sanity/base/schema",
"path": "./schemas/schema"
},
{
"name": "part:@sanity/desk-tool/structure",
"path": "./structures/deskStructure.js"
},
{
"implements": "part:@sanity/dashboard/config",
"path": "src/dashboardConfig.js"
}
]
}
My assumption was that any path after /sanity would be redirected to the sanity/index.html file output by the build command (build command below), but it doesn't seem to be functioning correctly for any path except just /sanity.
Build command (in package.json):
{
"scripts": {
...
"prebuild": "echo 'Building Sanity to public/sanity' && cd sanity && yarn && npx @sanity/cli build ../public/sanity -y && echo 'Done'",
...
},
Any help greatly appreciated!
A:
Dont know if you managed to sort this, but this is what works for me.
/next.config.js
/** @type {import('next').NextConfig} */
const STUDIO_REWRITE = {
source: "/studio/:path*",
destination: process.env.NODE_ENV === "development" ?
"http://localhost:3333/studio/:path*" : "/studio/index.html",
};
const nextConfig = {
i18n: {
locales: ["en"],
defaultLocale: "en",
},
rewrites: async () => [STUDIO_REWRITE],
reactStrictMode: true,
images: {
domains: ['cdn.sanity.io'],
},
}
module.exports = nextConfig
/netlify.toml
[[redirects]]
from = "/studio/*"
to = "/studio/index.html"
status = 200
force = false
| Next JS Rewrites for Sanity CMS giving 404 page after login | I'm currently hosting a Next JS site on Netlify with a Sanity CMS backend for content editing. I've got it configured to run on the single domain IE - examplesite.com has the front-end website, where examplesite.com/sanity opens the Sanity Studio editor.
This works as intended if the editor has a log-in cookie already (from previous login, etc), but if the editor has to login, after going through the login process the site is redirected to /sanity/desk and Next displays a 404 page. The editor then has to visit /sanity to access the CMS, where it redirects successfully to /sanity/desk (no 404).
Following the official Sanity setup guide, I have the following rewrite applied in the Next config.
const SANITY_REWRITE = {
source: "/sanity/:path*",
destination:
process.env.NODE_ENV === "development"
? "http://localhost:3333/sanity/:path*"
: "/sanity/index.html",
};
const DESK_REWRITE = {
source: "/sanity/desk",
destination: "/sanity/index.html",
};
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withBundleAnalyzer({
reactStrictMode: true,
async rewrites() {
return {
beforeFiles: [SANITY_REWRITE, DESK_REWRITE],
};
},
images: {
domains: ["cdn.sanity.io"],
},
});
For completeness, here is my sanity.json as well:
{
"root": true,
"project": {
"name": "main-site",
"basePath": "/sanity"
},
"api": {
"projectId": "ga8f69l8",
"dataset": "production"
},
"plugins": [
"@sanity/base",
"@sanity/components",
"@sanity/default-layout",
"@sanity/default-login",
"@sanity/desk-tool",
"@sanity/dashboard",
"dashboard-widget-netlify"
],
"env": {
"development": {
"plugins": ["@sanity/vision"]
}
},
"parts": [
{
"name": "part:@sanity/base/schema",
"path": "./schemas/schema"
},
{
"name": "part:@sanity/desk-tool/structure",
"path": "./structures/deskStructure.js"
},
{
"implements": "part:@sanity/dashboard/config",
"path": "src/dashboardConfig.js"
}
]
}
My assumption was that any path after /sanity would be redirected to the sanity/index.html file output by the build command (build command below), but it doesn't seem to be functioning correctly for any path except just /sanity.
Build command (in package.json):
{
"scripts": {
...
"prebuild": "echo 'Building Sanity to public/sanity' && cd sanity && yarn && npx @sanity/cli build ../public/sanity -y && echo 'Done'",
...
},
Any help greatly appreciated!
| [
"Dont know if you managed to sort this, but this is what works for me.\n/next.config.js\n/** @type {import('next').NextConfig} */\n\nconst STUDIO_REWRITE = {\n source: \"/studio/:path*\",\n destination: process.env.NODE_ENV === \"development\" ? \n \"http://localhost:3333/studio/:path*\" : \"/studio/index.html\",\n};\n\nconst nextConfig = {\n i18n: {\n locales: [\"en\"],\n defaultLocale: \"en\",\n },\n rewrites: async () => [STUDIO_REWRITE],\n reactStrictMode: true,\n images: {\n domains: ['cdn.sanity.io'],\n },\n}\n\nmodule.exports = nextConfig\n\n/netlify.toml\n[[redirects]]\nfrom = \"/studio/*\"\nto = \"/studio/index.html\"\nstatus = 200\nforce = false\n\n"
] | [
0
] | [] | [] | [
"javascript",
"netlify",
"next.js",
"sanity"
] | stackoverflow_0071355932_javascript_netlify_next.js_sanity.txt |
Q:
Cannot find module 'prompt-sync'
I'm making Tic Tac Toe game in JavaScript needed prompt-sync to get user inputs. After I installed prompt-sync module using npm I was getting this error whenever I tried to run this file. Did a quick google search to find that it requires npm install -g to activate it globally. Despite doing this I'm still getting the same Error. If anyone could please tell what's going wrong here!
Error:
$ node main.js
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'prompt-sync'
Require stack:
- B:\JavaScript Projects\Tic Tac Toe\main.js
β[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)β[39m
β[90m at Function.Module._load (internal/modules/cjs/loader.js:725:27)β[39m
β[90m at Module.require (internal/modules/cjs/loader.js:952:19)β[39m
β[90m at require (internal/modules/cjs/helpers.js:88:18)β[39m
at Object.<anonymous> (B:\JavaScript Projects\Tic Tac Toe\main.js:5:16)
β[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)β[39m
β[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)β[39m
β[90m at Module.load (internal/modules/cjs/loader.js:928:32)β[39m
β[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)β[39m
β[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)β[39m {
code: β[32m'MODULE_NOT_FOUND'β[39m,
requireStack: [ β[32m'B:\\JavaScript Projects\\Tic Tac Toe\\main.js'β[39m ]
}
The Code
/*
This project implements multiplayer Tic Tac Toe
*/
const prompt = require('prompt-sync')({sigint: true});
const clear_ouput = () => {
for (let i = 1; i < 201; i++) {
console.log();
}
}
const display_board = board => {
clear_ouput();
console.log(' | | ');
console.log(' ' + board[7] + ' | ' + board[8] +' | ' + board[9] + ' ');
console.log(' | | ');
console.log('-----------');
console.log(' | | ');
console.log(' ' + board[4] + ' | ' + board[5] +' | ' + board[6] + ' ');
console.log(' | | ');
console.log('-----------');
console.log(' | | ');
console.log(' ' + board[1] + ' | ' + board[2] +' | ' + board[3] + ' ');
console.log(' | | ');
}
const create_board = char => {
let board = [];
for (let i = 0; i < 11; i++) {
board.push(char);
}
return board;
}
// let game_board = create_board('X');
// display_board(game_board);
const decide_markers = () => {
let marker;
while ( ['X', 'O'].includes(marker) ) {
marker = prompt('Player 1, enter your marker (X - O): ');
if ( !(['X', 'O'].includes(marker)) ) {
console.log(`Sorry but ${marker} is not a valid marker.\nChoose from 'X' or 'O'.\n`);
};
}
if (marker === 'X') {
return ['X', 'O'];
}
return ['O', 'X'];
}
player_markers = decide_markers();
The path of the file is /b/Javascript Projects/Tic Tac Toe
command used to install prompt-synce npm install -g prompt-sync
I've tried restarting VS Code several times but it's still the same.
A:
Not sure if you still need it, but for anyone who does:
Try using npm install prompt-sync.
A:
1.Make sure you have Node and NPM installed
2.Run npm install prompt-sync in the terminal
A:
Use this instead in the command prompt (I wrote it while in the same folder as the .js file but that might not be necessary)
npm i prompt-sync
Source: https://www.npmjs.com/package/prompt-sync
| Cannot find module 'prompt-sync' | I'm making Tic Tac Toe game in JavaScript needed prompt-sync to get user inputs. After I installed prompt-sync module using npm I was getting this error whenever I tried to run this file. Did a quick google search to find that it requires npm install -g to activate it globally. Despite doing this I'm still getting the same Error. If anyone could please tell what's going wrong here!
Error:
$ node main.js
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'prompt-sync'
Require stack:
- B:\JavaScript Projects\Tic Tac Toe\main.js
β[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)β[39m
β[90m at Function.Module._load (internal/modules/cjs/loader.js:725:27)β[39m
β[90m at Module.require (internal/modules/cjs/loader.js:952:19)β[39m
β[90m at require (internal/modules/cjs/helpers.js:88:18)β[39m
at Object.<anonymous> (B:\JavaScript Projects\Tic Tac Toe\main.js:5:16)
β[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)β[39m
β[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)β[39m
β[90m at Module.load (internal/modules/cjs/loader.js:928:32)β[39m
β[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)β[39m
β[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)β[39m {
code: β[32m'MODULE_NOT_FOUND'β[39m,
requireStack: [ β[32m'B:\\JavaScript Projects\\Tic Tac Toe\\main.js'β[39m ]
}
The Code
/*
This project implements multiplayer Tic Tac Toe
*/
const prompt = require('prompt-sync')({sigint: true});
const clear_ouput = () => {
for (let i = 1; i < 201; i++) {
console.log();
}
}
const display_board = board => {
clear_ouput();
console.log(' | | ');
console.log(' ' + board[7] + ' | ' + board[8] +' | ' + board[9] + ' ');
console.log(' | | ');
console.log('-----------');
console.log(' | | ');
console.log(' ' + board[4] + ' | ' + board[5] +' | ' + board[6] + ' ');
console.log(' | | ');
console.log('-----------');
console.log(' | | ');
console.log(' ' + board[1] + ' | ' + board[2] +' | ' + board[3] + ' ');
console.log(' | | ');
}
const create_board = char => {
let board = [];
for (let i = 0; i < 11; i++) {
board.push(char);
}
return board;
}
// let game_board = create_board('X');
// display_board(game_board);
const decide_markers = () => {
let marker;
while ( ['X', 'O'].includes(marker) ) {
marker = prompt('Player 1, enter your marker (X - O): ');
if ( !(['X', 'O'].includes(marker)) ) {
console.log(`Sorry but ${marker} is not a valid marker.\nChoose from 'X' or 'O'.\n`);
};
}
if (marker === 'X') {
return ['X', 'O'];
}
return ['O', 'X'];
}
player_markers = decide_markers();
The path of the file is /b/Javascript Projects/Tic Tac Toe
command used to install prompt-synce npm install -g prompt-sync
I've tried restarting VS Code several times but it's still the same.
| [
"Not sure if you still need it, but for anyone who does:\nTry using npm install prompt-sync.\n",
"1.Make sure you have Node and NPM installed\n2.Run npm install prompt-sync in the terminal\n",
"Use this instead in the command prompt (I wrote it while in the same folder as the .js file but that might not be necessary)\nnpm i prompt-sync\nSource: https://www.npmjs.com/package/prompt-sync\n"
] | [
1,
0,
0
] | [] | [] | [
"javascript",
"node.js"
] | stackoverflow_0065680193_javascript_node.js.txt |
Q:
How do I install an Ansible Galaxy role from a tar.gz file?
I have seen a number of sites that explain how to install a role from a tar.gz file using ansible-galaxy, and they all seem to say the same thing.
In my case I have downloaded the following role file from ansible galaxy :
dsglaser-cis_security-1.2.0.tar.gz
Then I tried to install the role:
ansible-galaxy collection install dsglaser-cis_security-1.2.0.tar.gz
which gives me the warning :
[WARNING]: - collection was NOT installed successfully: Failed to get data from the API server (https://galaxy.ansible.com/api/): Failed to connect to galaxy.ansible.com at port 443: [Errno 104] Connection reset by peer
This is correct, because this machine is not, and never will be connected to the internet.
Another attempt :
ansible-galaxy install dsglaser-cis_security-1.2.0.tar.gz
results in another warning:
[WARNING]: - dsglaser-cis_security-1.2.0.tar.gz was NOT installed successfully: the specified roles path exists and is not a directory.
Also tried using the -p option to indicate where I want the role to be installed, with and without the directory present, but every attempt resulted in the last warning.
I'm not doing this as root...
Ansible version is 2.8.13
Just discovered that the command
ansible-galaxy install dsglaser-cis_security-1.2.0.tar.gz -p ./bla
does work, but only as root. And that's not what I want...
What am I doing wrong ?
A:
I have been banging my head against the wall on this one for a while. I found that the collections I am trying to install have dependencies, that are not included in the tar.gz file.
This makes galaxy go out to download the files not found.
The way to get around this is by using another machine with ansible (2.10+) and transferring the files over.
Once you have ansible installed on a machine with internet use the following command
ansible-galaxy collection download {{ name of collection, if multiple use space as a separator }}
i.e.
ansible-galaxy collection download cisco.ios cisco.asa
This will create a folder in your current working directory with a tar.gz of the collection and its dependencies, as well as a requirements.yml file.
Note: with the requirements.yml file, if you re-run the download command, it will overwrite this, so if you have multiple collections use the single line command above.
Then it's just a matter of copying that folder over to the offline ansible server (2.9+), cd to that directory, and run:
ansible-galaxy collection install -r requirements.yml
Bobs your uncle.
I hope this saves someone time.
Thanks goes to this reddit post on the same topic
https://www.reddit.com/r/ansible/comments/lh1do0/ansible_newbie_trying_to_install_an_ansible/
A:
AFAIK, installation from archives was never support for roles but was supported for collections.
For roles you are stuck with installation from git URLs.
This alone is a good-enough reason for me to avoid using old standalone roles, especially as support for them in galaxy is minimal, no new features being added (like install from tar archives).
| How do I install an Ansible Galaxy role from a tar.gz file? | I have seen a number of sites that explain how to install a role from a tar.gz file using ansible-galaxy, and they all seem to say the same thing.
In my case I have downloaded the following role file from ansible galaxy :
dsglaser-cis_security-1.2.0.tar.gz
Then I tried to install the role:
ansible-galaxy collection install dsglaser-cis_security-1.2.0.tar.gz
which gives me the warning :
[WARNING]: - collection was NOT installed successfully: Failed to get data from the API server (https://galaxy.ansible.com/api/): Failed to connect to galaxy.ansible.com at port 443: [Errno 104] Connection reset by peer
This is correct, because this machine is not, and never will be connected to the internet.
Another attempt :
ansible-galaxy install dsglaser-cis_security-1.2.0.tar.gz
results in another warning:
[WARNING]: - dsglaser-cis_security-1.2.0.tar.gz was NOT installed successfully: the specified roles path exists and is not a directory.
Also tried using the -p option to indicate where I want the role to be installed, with and without the directory present, but every attempt resulted in the last warning.
I'm not doing this as root...
Ansible version is 2.8.13
Just discovered that the command
ansible-galaxy install dsglaser-cis_security-1.2.0.tar.gz -p ./bla
does work, but only as root. And that's not what I want...
What am I doing wrong ?
| [
"I have been banging my head against the wall on this one for a while. I found that the collections I am trying to install have dependencies, that are not included in the tar.gz file.\nThis makes galaxy go out to download the files not found.\nThe way to get around this is by using another machine with ansible (2.10+) and transferring the files over.\nOnce you have ansible installed on a machine with internet use the following command\nansible-galaxy collection download {{ name of collection, if multiple use space as a separator }}\ni.e.\nansible-galaxy collection download cisco.ios cisco.asa\n\nThis will create a folder in your current working directory with a tar.gz of the collection and its dependencies, as well as a requirements.yml file.\nNote: with the requirements.yml file, if you re-run the download command, it will overwrite this, so if you have multiple collections use the single line command above.\nThen it's just a matter of copying that folder over to the offline ansible server (2.9+), cd to that directory, and run:\nansible-galaxy collection install -r requirements.yml\n\nBobs your uncle.\nI hope this saves someone time.\nThanks goes to this reddit post on the same topic\nhttps://www.reddit.com/r/ansible/comments/lh1do0/ansible_newbie_trying_to_install_an_ansible/\n",
"AFAIK, installation from archives was never support for roles but was supported for collections.\nFor roles you are stuck with installation from git URLs.\nThis alone is a good-enough reason for me to avoid using old standalone roles, especially as support for them in galaxy is minimal, no new features being added (like install from tar archives).\n"
] | [
0,
0
] | [] | [] | [
"ansible"
] | stackoverflow_0063413114_ansible.txt |
Q:
Create .PEM key using openssl
I have public key, and I want to create .PEM key using this public key. I am using openssl tool.
I didn't tried any steps. Could you please suggest any steps to be followed to create .PEM key?
A:
try this one :
openssl genrsa -out private_key.pem 2048
where private key is the name of the file and 2048 is the length of the private key ( install openssl with home-brew on Mac )!
| Create .PEM key using openssl | I have public key, and I want to create .PEM key using this public key. I am using openssl tool.
I didn't tried any steps. Could you please suggest any steps to be followed to create .PEM key?
| [
"try this one :\nopenssl genrsa -out private_key.pem 2048\nwhere private key is the name of the file and 2048 is the length of the private key ( install openssl with home-brew on Mac )!\n"
] | [
0
] | [] | [] | [
"openssl"
] | stackoverflow_0074404045_openssl.txt |
Q:
Django call function to save file cannot work
I am create Django project and create function for download file, But my project cannot work, File not response to save
view.py
from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
def index(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'my_file.json'
filepath = BASE_DIR + '/filedownload/' + filename
download(request,filepath)
return HttpResponse('Download File')
def download(request, path):
file_path = path
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/x-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
How can I solve this?
A:
Your download() returns response to your index() and your index() returns its own response(not a response of download()). If you returns response of download() like below, it will works.
import os
from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
def index(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'my_file.json'
filepath = BASE_DIR + '/filedownload/' + filename
return download(request,filepath)
def download(request, path):
file_path = path
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/x-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
| Django call function to save file cannot work | I am create Django project and create function for download file, But my project cannot work, File not response to save
view.py
from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
def index(request):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'my_file.json'
filepath = BASE_DIR + '/filedownload/' + filename
download(request,filepath)
return HttpResponse('Download File')
def download(request, path):
file_path = path
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/x-download")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
How can I solve this?
| [
"Your download() returns response to your index() and your index() returns its own response(not a response of download()). If you returns response of download() like below, it will works.\nimport os\nfrom django.http.response import HttpResponse\nfrom django.conf import settings\nfrom django.http import HttpResponse, Http404\n\ndef index(request):\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n filename = 'my_file.json'\n filepath = BASE_DIR + '/filedownload/' + filename\n return download(request,filepath)\n\ndef download(request, path):\n file_path = path\n if os.path.exists(file_path):\n with open(file_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/x-download\")\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)\n return response\n raise Http404\n\n"
] | [
0
] | [] | [] | [
"django",
"fileresponse"
] | stackoverflow_0074674231_django_fileresponse.txt |
Q:
The named parameter 'semesters' is required, but there's no corresponding argument
main.dart
`
void main() {
runApp(
Provider(
create: (_) => LoginService(),
child: MaterialApp(
theme: ThemeData(fontFamily: 'Roboto'),
debugShowCheckedModeBanner: false,
routes: {
'/': (context) => SplashPage(goToPage: WelcomePage(), duration: 3),
'/welcomepage' : (context) => WelcomePage(),
'/categorylistpage' : (context) => CategoryListPage(),
'/selectedcategorypage' : (context) => SelectedCategoryPage(),
}
),
)
);
}
`
selectedcategorypage.dart
`
class SelectedCategoryPage extends StatelessWidget {
final MyCategory? selectedCategory;
final List<MySemester> semesters;
const SelectedCategoryPage({
Key? key,
this.selectedCategory,
required this.semesters,
}) : super(key: key);
`
I tried to make the routs but for selectedcategory I have required this.semesters which I don't need a required to but without it I get this error: The parameter 'semesters' can't have a value of 'null' because of its type, but the implicit default value is 'null'. I don't know how to get around it
A:
If the parameter 'semesters' is not required, then just remove the 'required' tag
and make the variable nullable. Like:
final List<MySemester>? semesters;
Full code:
class SelectedCategoryPage extends StatelessWidget {
final MyCategory? selectedCategory;
final List<MySemester>? semesters;
const SelectedCategoryPage({
Key? key,
this.selectedCategory,
this.semesters,
}) : super(key: key);
| The named parameter 'semesters' is required, but there's no corresponding argument | main.dart
`
void main() {
runApp(
Provider(
create: (_) => LoginService(),
child: MaterialApp(
theme: ThemeData(fontFamily: 'Roboto'),
debugShowCheckedModeBanner: false,
routes: {
'/': (context) => SplashPage(goToPage: WelcomePage(), duration: 3),
'/welcomepage' : (context) => WelcomePage(),
'/categorylistpage' : (context) => CategoryListPage(),
'/selectedcategorypage' : (context) => SelectedCategoryPage(),
}
),
)
);
}
`
selectedcategorypage.dart
`
class SelectedCategoryPage extends StatelessWidget {
final MyCategory? selectedCategory;
final List<MySemester> semesters;
const SelectedCategoryPage({
Key? key,
this.selectedCategory,
required this.semesters,
}) : super(key: key);
`
I tried to make the routs but for selectedcategory I have required this.semesters which I don't need a required to but without it I get this error: The parameter 'semesters' can't have a value of 'null' because of its type, but the implicit default value is 'null'. I don't know how to get around it
| [
"If the parameter 'semesters' is not required, then just remove the 'required' tag\nand make the variable nullable. Like:\n final List<MySemester>? semesters;\n\nFull code:\nclass SelectedCategoryPage extends StatelessWidget {\n final MyCategory? selectedCategory;\n final List<MySemester>? semesters;\n const SelectedCategoryPage({\n Key? key,\n this.selectedCategory,\n this.semesters,\n }) : super(key: key);\n\n"
] | [
0
] | [] | [] | [
"flutter"
] | stackoverflow_0074675052_flutter.txt |
Q:
Is there a way to apply a random spread to Physics.Raycast?
I'm working on an FPS and am attempting to implement a bullet spread mechanic using Physics.Raycast with the following code:
if( Physics.Raycast(playercam.transform.position, playercam.transform.forward, out hit) )
I figured it would work by doing something as follows, but even trying to get this to function returns no good results.
if( Physics.Raycast(playercam.transform.position, playercam.transform.forward + new Vector3(*random numbers*), out hit) )
Is it just my implementation, or is there a better way?
A:
To add spread to the above code, you can generate a random direction vector within a cone centred around the camera's forward direction and then use that direction vector as the direction for the raycast.
#region Serialized Fields
[SerializeField] [Range(0, 20)] private float spreadAngle = 10.0f;
#endregion
private Camera _playerCamera;
private Vector3 _randomDirection;
#region Event Functions
private void Awake()
{
_playerCamera = Camera.main;
}
private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;
// Draw the spread cone and the resulting raycast direction
var cameraTransform = _playerCamera.transform;
var cameraPosition = cameraTransform.position;
Gizmos.color = Color.red;
Gizmos.DrawLine(cameraPosition,
cameraPosition + cameraTransform.forward * 100.0f);
Gizmos.color = Color.green;
Gizmos.DrawLine(cameraPosition, cameraPosition + _randomDirection * 100.0f);
}
#endregion
public void Shoot()
{
_randomDirection = Random.insideUnitSphere;
_randomDirection = Vector3.Slerp(_playerCamera.transform.forward, _randomDirection, spreadAngle / 180.0f);
if (Physics.Raycast(_playerCamera.transform.position, _randomDirection, out var hit))
Debug.Log(hit.collider.name);
}
The above code generates a random direction vector within a cone centred around the camera's forward direction, using the Random.insideUnitSphere property and the Vector3.Slerp() method. The maximum spread angle is defined by the spreadAngle variable and is used to control the size of the spread cone. You could extend this to use Unity's ScriptableObjects, so you have a unique spreadAngle per weapon!
I've also added an OnDrawGizmosSelected, which will show you the camera's forward direction (denoted in red) and the spread of your last fired raycast (denoted in green).
| Is there a way to apply a random spread to Physics.Raycast? | I'm working on an FPS and am attempting to implement a bullet spread mechanic using Physics.Raycast with the following code:
if( Physics.Raycast(playercam.transform.position, playercam.transform.forward, out hit) )
I figured it would work by doing something as follows, but even trying to get this to function returns no good results.
if( Physics.Raycast(playercam.transform.position, playercam.transform.forward + new Vector3(*random numbers*), out hit) )
Is it just my implementation, or is there a better way?
| [
"To add spread to the above code, you can generate a random direction vector within a cone centred around the camera's forward direction and then use that direction vector as the direction for the raycast.\n#region Serialized Fields\n\n[SerializeField] [Range(0, 20)] private float spreadAngle = 10.0f;\n\n#endregion\n\nprivate Camera _playerCamera;\nprivate Vector3 _randomDirection;\n\n#region Event Functions\n\nprivate void Awake()\n{\n _playerCamera = Camera.main;\n}\n\nprivate void OnDrawGizmosSelected()\n{\n if (!Application.isPlaying) return;\n\n // Draw the spread cone and the resulting raycast direction\n var cameraTransform = _playerCamera.transform;\n var cameraPosition = cameraTransform.position;\n\n Gizmos.color = Color.red;\n Gizmos.DrawLine(cameraPosition,\n cameraPosition + cameraTransform.forward * 100.0f);\n Gizmos.color = Color.green;\n Gizmos.DrawLine(cameraPosition, cameraPosition + _randomDirection * 100.0f);\n}\n\n#endregion\n\npublic void Shoot()\n{\n _randomDirection = Random.insideUnitSphere;\n _randomDirection = Vector3.Slerp(_playerCamera.transform.forward, _randomDirection, spreadAngle / 180.0f);\n\n if (Physics.Raycast(_playerCamera.transform.position, _randomDirection, out var hit))\n Debug.Log(hit.collider.name);\n}\n\nThe above code generates a random direction vector within a cone centred around the camera's forward direction, using the Random.insideUnitSphere property and the Vector3.Slerp() method. The maximum spread angle is defined by the spreadAngle variable and is used to control the size of the spread cone. You could extend this to use Unity's ScriptableObjects, so you have a unique spreadAngle per weapon!\nI've also added an OnDrawGizmosSelected, which will show you the camera's forward direction (denoted in red) and the spread of your last fired raycast (denoted in green).\n\n"
] | [
1
] | [] | [] | [
"c#",
"unity3d"
] | stackoverflow_0074671980_c#_unity3d.txt |
Q:
Sync API table to SQL Database
I'm exploring options on how to one-way sync from a table available via API to an SQL database. Does anyone have any suggestions on how to achieve this?
The data from the "Source" is often updated and should be copied to the "Destination" as the changes happen (live).
Source
Read Only table from an ERP available via an API. Webhooks on the source are not possible. Entries to this table may be created, updated or deleted. There would be approximately 150,000 entries in the table with about 1000 changes per day.
Destination
Azure MS SQL database which I have full control over.
I'm looking for best practice or any ideas on how to achieve this. There seems to be very few articles that I can find with anything helpful.
I'm open to using any tool on Azure including Logic Apps and Azure Functions but want to stay away from using 3rd party tools.
A:
If you are trying to achieving this through logic apps, Below is the flow that you can follow.
Note: Make sure you preprocess the data before sending the data to SQL database using appropriate actions based on the type of data that you are receiving.
| Sync API table to SQL Database | I'm exploring options on how to one-way sync from a table available via API to an SQL database. Does anyone have any suggestions on how to achieve this?
The data from the "Source" is often updated and should be copied to the "Destination" as the changes happen (live).
Source
Read Only table from an ERP available via an API. Webhooks on the source are not possible. Entries to this table may be created, updated or deleted. There would be approximately 150,000 entries in the table with about 1000 changes per day.
Destination
Azure MS SQL database which I have full control over.
I'm looking for best practice or any ideas on how to achieve this. There seems to be very few articles that I can find with anything helpful.
I'm open to using any tool on Azure including Logic Apps and Azure Functions but want to stay away from using 3rd party tools.
| [
"If you are trying to achieving this through logic apps, Below is the flow that you can follow.\nNote: Make sure you preprocess the data before sending the data to SQL database using appropriate actions based on the type of data that you are receiving.\n\n"
] | [
0
] | [] | [] | [
"azure",
"azure_logic_apps",
"database",
"erp",
"integration"
] | stackoverflow_0074457703_azure_azure_logic_apps_database_erp_integration.txt |
Q:
Error when trying to install app with mysql2 gem
Im trying to install an open source rails 3.2.21 application that uses the mysql2 gem, but when i try and run the bundle commant I get the following error:
Fetching: mysql2-0.3.18.gem (100%)
Building native extensions. This could take a while...
p
ERROR: Error installing mysql2:
ERROR: Failed to build gem native extension.
/Users/my_username/.rvm/rubies/ruby-2.1.2/bin/ruby -r ./siteconf20150614-72129-orqsb7.rb extconf.rb
checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
-----
Using mysql_config at /usr/local/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for mysqld_error.h... yes
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /usr/local/Cellar/mysql/5.6.25/lib
-----
creating Makefile
make "DESTDIR=" clean
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
linking shared-object mysql2/mysql2.bundle
ld: warning: directory not found for option '-L/Users/travis/.sm/pkg/active/lib'
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1
make failed, exit code 2
Gem files will remain installed in /Users/my_username/.rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/gems/mysql2-0.3.18 for inspection.
Results logged to /Users/my_username/.rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/extensions/x86
I tried uninstalling every version of mysql I installed via homebrew and reinstalling them, like so:
brew uninstall --force mysql && brew install mysql
Then running:
sudo gem install mysql2
As suggested by a number of similar questions asked on here, but it still results in the same error as above.
Please could someone offer guidance on how to get this up and running?
A:
For anybody still experiencing the issue:
When you install openssl via brew, you should get the following message:
Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries
Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:
LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include
PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig
You can set these build flags (for the local application) by running the following:
bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include"
This worked for me.
See bundler's documentation for more information.
A:
The error log says:
ld: library not found for -lssl
So, you need to install libssl:
brew install openssl
As it was pointed out in comments, there might be a need to export the path to the library.
export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/
A:
Try this:
gem install mysql2 -v '0.5.2' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
(Update version as appropriate)
A:
The solution for me was to install the Xcode Command Line Tools.
I had recently updated Xcode through the Mac App Store, and every time I do that, I've found that I have to reinstall the Command Line Tools again.
xcode-select --install
A:
Based on the solution here
brew install openssl
export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/
solved the problem.
A:
After Homebrew update ([email protected]) there is a new path for libs, so may use:
bundle config build.mysql2 --with-opt-dir=$(brew --prefix openssl)
bundle install
It will fix ld: library not found for -lssl error
A:
Thanks @mudasobwa for pointing me in the right direction. It turns out the error was caused by an unlinked openssl file, so running:
brew reinstall openssl && brew link openssl --force
Solved the problem. I found the solution here: OpenSSL, RVM, Brew, conflicting error
A:
On MacBook air M1(macOS) it worked for me.
Install zstd
brew install zstd
Install mysql2
gem install mysql2 -v '0.5.3' -- --with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib
A:
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
From here:
https://gorails.com/setup/osx/10.14-mojave
A:
The combination of commands solved it me. I am on Mojave.
brew reinstall openssl && brew link openssl --force
and then
gem install mysql2 -v '0.4.10' -- \
--with-ldflags=-L/usr/local/opt/openssl/lib \
--with-cppflags=-I/usr/local/opt/openssl/include
A:
Steps for me on Monterey M1 Mac
brew install openssl@3
brew install zstd
gem install mysql2 -v '0.5.3' -- --with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib
bundle config --local build.mysql2 "--with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib"
bundle install
A:
Seems that you miss the main files needed to build mysql2 gem
sudo apt-get install libsqlite3-dev libmysqlclient-dev -y
libsqlite3-dev is not mandatory but install it since it's the default rails DB.
A:
Mac Catalina using Homebrew fix:
gem install mysql2 -- --with-opt-dir="$(brew --prefix openssl)"
A:
the following command works for my Mac os 12.1 MacOs Monterey
gem install mysql2 -v '0.5.3' -- \
--with-mysql-lib=/opt/homebrew/Cellar/mysql/8.0.28/lib \
--with-mysql-dir=/opt/homebrew/Cellar/mysql/8.0.28 \
--with-mysql-config=/opt/homebrew/Cellar/mysql/8.0.28/bin/mysql_config \
--with-mysql-include=/opt/homebrew/Cellar/mysql/8.0.28/include
Please refer this link for more details
https://github.com/brianmario/mysql2/issues/1175
A:
This finally worked for me on macOS Monterey 12.3 (M1 Pro):
gem install mysql2 -- --with-mysql-dir=/opt/homebrew/Cellar/mysql/8.0.28_1
Make sure you read the installation instructions. Notable points for me were:
Make sure MySQL is installed (brew install mysql)
Make sure XCode select tools are installed (xcode-select --install)
Set the with-mysql-dir option to wherever mysql was installed (check with brew info mysql)
A:
Combining the answers given by Aleksei Matiushkin and Alexey Mozorov fixed the problem for me.
But I also updated the openssl before adding the path.
Thanks!
A:
I've been coding with mysql2 gem for years and have encountered with this issue time to time.
Today I found that this magic option -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include no longer worked on my Mac. Indeed, it looks like the default location where brew installs openssl has changed:
$ brew reinstall openssl
...
If you need to have openssl@3 first in your PATH, run:
echo 'export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"' >> ~/.zshrc
For compilers to find openssl@3 you may need to set:
export LDFLAGS="-L/opt/homebrew/opt/openssl@3/lib"
export CPPFLAGS="-I/opt/homebrew/opt/openssl@3/include"
So following the message, I had to make a few changes to the command and got it work finally:
$ gem install mysql2 -v '0.5.3' -- --with-ldflags=-L/opt/homebrew/opt/openssl@3/lib --with-cppflags=-I/opt/homebrew/opt/openssl@3/include
Hope this will help someone!
| Error when trying to install app with mysql2 gem | Im trying to install an open source rails 3.2.21 application that uses the mysql2 gem, but when i try and run the bundle commant I get the following error:
Fetching: mysql2-0.3.18.gem (100%)
Building native extensions. This could take a while...
p
ERROR: Error installing mysql2:
ERROR: Failed to build gem native extension.
/Users/my_username/.rvm/rubies/ruby-2.1.2/bin/ruby -r ./siteconf20150614-72129-orqsb7.rb extconf.rb
checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
-----
Using mysql_config at /usr/local/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for mysqld_error.h... yes
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /usr/local/Cellar/mysql/5.6.25/lib
-----
creating Makefile
make "DESTDIR=" clean
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
linking shared-object mysql2/mysql2.bundle
ld: warning: directory not found for option '-L/Users/travis/.sm/pkg/active/lib'
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1
make failed, exit code 2
Gem files will remain installed in /Users/my_username/.rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/gems/mysql2-0.3.18 for inspection.
Results logged to /Users/my_username/.rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/extensions/x86
I tried uninstalling every version of mysql I installed via homebrew and reinstalling them, like so:
brew uninstall --force mysql && brew install mysql
Then running:
sudo gem install mysql2
As suggested by a number of similar questions asked on here, but it still results in the same error as above.
Please could someone offer guidance on how to get this up and running?
| [
"For anybody still experiencing the issue:\nWhen you install openssl via brew, you should get the following message:\n\nApple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries\nGenerally there are no consequences of this for you. If you build your\n own software and it requires this formula, you'll need to add to your\n build variables:\nLDFLAGS: -L/usr/local/opt/openssl/lib\n CPPFLAGS: -I/usr/local/opt/openssl/include\n PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig \n\nYou can set these build flags (for the local application) by running the following:\nbundle config --local build.mysql2 \"--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include\"\n\nThis worked for me.\nSee bundler's documentation for more information.\n",
"The error log says:\nld: library not found for -lssl\n\nSo, you need to install libssl:\nbrew install openssl\n\n\nAs it was pointed out in comments, there might be a need to export the path to the library.\nexport LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/\n\n",
"Try this:\ngem install mysql2 -v '0.5.2' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include\n\n(Update version as appropriate)\n",
"The solution for me was to install the Xcode Command Line Tools.\nI had recently updated Xcode through the Mac App Store, and every time I do that, I've found that I have to reinstall the Command Line Tools again.\nxcode-select --install\n\n",
"Based on the solution here\nbrew install openssl\n\nexport LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/\n\nsolved the problem.\n",
"After Homebrew update ([email protected]) there is a new path for libs, so may use:\nbundle config build.mysql2 --with-opt-dir=$(brew --prefix openssl)\nbundle install\n\nIt will fix ld: library not found for -lssl error\n",
"Thanks @mudasobwa for pointing me in the right direction. It turns out the error was caused by an unlinked openssl file, so running:\nbrew reinstall openssl && brew link openssl --force \n\nSolved the problem. I found the solution here: OpenSSL, RVM, Brew, conflicting error\n",
"On MacBook air M1(macOS) it worked for me.\nInstall zstd\n\nbrew install zstd\n\nInstall mysql2\n\ngem install mysql2 -v '0.5.3' -- --with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib\n\n",
"sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /\n\nFrom here:\nhttps://gorails.com/setup/osx/10.14-mojave\n",
"The combination of commands solved it me. I am on Mojave.\nbrew reinstall openssl && brew link openssl --force\nand then \ngem install mysql2 -v '0.4.10' -- \\\n --with-ldflags=-L/usr/local/opt/openssl/lib \\\n --with-cppflags=-I/usr/local/opt/openssl/include\n\n",
"Steps for me on Monterey M1 Mac\nbrew install openssl@3\n\nbrew install zstd\n\ngem install mysql2 -v '0.5.3' -- --with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib\n\nbundle config --local build.mysql2 \"--with-opt-dir=$(brew --prefix openssl) --with-ldflags=-L/opt/homebrew/Cellar/zstd/1.5.0/lib\"\n\nbundle install\n\n",
"Seems that you miss the main files needed to build mysql2 gem\nsudo apt-get install libsqlite3-dev libmysqlclient-dev -y\n\nlibsqlite3-dev is not mandatory but install it since it's the default rails DB. \n",
"Mac Catalina using Homebrew fix:\ngem install mysql2 -- --with-opt-dir=\"$(brew --prefix openssl)\"\n",
"the following command works for my Mac os 12.1 MacOs Monterey\n gem install mysql2 -v '0.5.3' -- \\\n --with-mysql-lib=/opt/homebrew/Cellar/mysql/8.0.28/lib \\\n --with-mysql-dir=/opt/homebrew/Cellar/mysql/8.0.28 \\\n --with-mysql-config=/opt/homebrew/Cellar/mysql/8.0.28/bin/mysql_config \\\n --with-mysql-include=/opt/homebrew/Cellar/mysql/8.0.28/include \n\nPlease refer this link for more details\nhttps://github.com/brianmario/mysql2/issues/1175\n",
"This finally worked for me on macOS Monterey 12.3 (M1 Pro):\n gem install mysql2 -- --with-mysql-dir=/opt/homebrew/Cellar/mysql/8.0.28_1\n\nMake sure you read the installation instructions. Notable points for me were:\n\nMake sure MySQL is installed (brew install mysql)\nMake sure XCode select tools are installed (xcode-select --install)\nSet the with-mysql-dir option to wherever mysql was installed (check with brew info mysql)\n\n",
"Combining the answers given by Aleksei Matiushkin and Alexey Mozorov fixed the problem for me.\nBut I also updated the openssl before adding the path.\nThanks!\n",
"I've been coding with mysql2 gem for years and have encountered with this issue time to time.\nToday I found that this magic option -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include no longer worked on my Mac. Indeed, it looks like the default location where brew installs openssl has changed:\n$ brew reinstall openssl\n\n...\n\nIf you need to have openssl@3 first in your PATH, run:\n echo 'export PATH=\"/opt/homebrew/opt/openssl@3/bin:$PATH\"' >> ~/.zshrc\n\nFor compilers to find openssl@3 you may need to set:\n export LDFLAGS=\"-L/opt/homebrew/opt/openssl@3/lib\"\n export CPPFLAGS=\"-I/opt/homebrew/opt/openssl@3/include\"\n\nSo following the message, I had to make a few changes to the command and got it work finally:\n$ gem install mysql2 -v '0.5.3' -- --with-ldflags=-L/opt/homebrew/opt/openssl@3/lib --with-cppflags=-I/opt/homebrew/opt/openssl@3/include\n\nHope this will help someone!\n"
] | [
176,
75,
47,
36,
33,
16,
11,
9,
3,
2,
2,
1,
1,
1,
1,
0,
0
] | [
"I found that I had to use --with-opt-dir=/usr/local/opt.\nSpecifically, I added the following to my ~/.bundle/config file:\nBUNDLE_BUILD__MYSQL2: \"--with-opt-dir=/usr/local/opt\"\n\n"
] | [
-1
] | [
"mysql",
"mysql2",
"ruby",
"ruby_on_rails",
"ruby_on_rails_4"
] | stackoverflow_0030834421_mysql_mysql2_ruby_ruby_on_rails_ruby_on_rails_4.txt |
Q:
count number specific value within columns for each row in pandas
Hello I have a dataframe such as :
Species COL1 COL2 COL3 COL4 COL5
SP1 0 0 0 1-2 0-1-2
SP2 1-2 2 0 1 0
SP3 0-1 1 2 0 1-2
and I would like to add new columns to count for each row the number of specific unique values such as :
Species COL1 COL2 COL3 COL4 COL5 count_0 count_1-2 count_0-1-2 count_1 count_2
SP1 0 0 0 1-2 0-1-2 3 1 1 0 0
SP2 1-2 2 0 1 0 2 1 0 1 1
SP3 0-1 1 2 0 1-2 1 1 0 2 1
Does someone have na idea please ?
A:
You can use the value_counts() method in the pandas library to count the number of occurrences of each unique value in each row of your dataframe.
# Loop through each row of the dataframe
for index, row in df.iterrows():
# Create a series object for the current row
series = pd.Series(row)
# Count the number of occurrences of each unique value in the row
counts = series.value_counts()
# Add the count values to the current row of the dataframe
df.loc[index, 'count_0'] = counts[0] if 0 in counts else 0
df.loc[index, 'count_1-2'] = counts['1-2'] if '1-2' in counts else 0
df.loc[index, 'count_0-1-2'] = counts['0-1-2'] if '0-1-2' in counts else 0
df.loc[index, 'count_1'] = counts[1] if 1 in counts else 0
df.loc[index, 'count_2'] = counts[2] if 2 in counts else 0
A:
Example
data = {'Species': {0: 'SP1', 1: 'SP2', 2: 'SP3'},
'COL1': {0: '0', 1: '1-2', 2: '0-1'},
'COL2': {0: '0', 1: '2', 2: '1'},
'COL3': {0: '0', 1: '0', 2: '2'},
'COL4': {0: '1-2', 1: '1', 2: '0'},
'COL5': {0: '0-1-2', 1: '0', 2: '1-2'}}
df = pd.DataFrame(data)
Code
df1 = (df.set_index('Species').apply(lambda x: x.value_counts(), axis=1)
.add_prefix('count_').fillna(0).astype('int'))
df1
count_0 count_0-1 count_0-1-2 count_1 count_1-2 count_2
Species
SP1 3 0 1 0 1 0
SP2 2 0 0 1 1 1
SP3 1 1 0 1 1 1
make desired output
concat df & df1
pd.concat([df.set_index('Species'), df1], axis=1)
| count number specific value within columns for each row in pandas | Hello I have a dataframe such as :
Species COL1 COL2 COL3 COL4 COL5
SP1 0 0 0 1-2 0-1-2
SP2 1-2 2 0 1 0
SP3 0-1 1 2 0 1-2
and I would like to add new columns to count for each row the number of specific unique values such as :
Species COL1 COL2 COL3 COL4 COL5 count_0 count_1-2 count_0-1-2 count_1 count_2
SP1 0 0 0 1-2 0-1-2 3 1 1 0 0
SP2 1-2 2 0 1 0 2 1 0 1 1
SP3 0-1 1 2 0 1-2 1 1 0 2 1
Does someone have na idea please ?
| [
"You can use the value_counts() method in the pandas library to count the number of occurrences of each unique value in each row of your dataframe.\n# Loop through each row of the dataframe\nfor index, row in df.iterrows():\n # Create a series object for the current row\n series = pd.Series(row)\n\n # Count the number of occurrences of each unique value in the row\n counts = series.value_counts()\n\n # Add the count values to the current row of the dataframe\n df.loc[index, 'count_0'] = counts[0] if 0 in counts else 0\n df.loc[index, 'count_1-2'] = counts['1-2'] if '1-2' in counts else 0\n df.loc[index, 'count_0-1-2'] = counts['0-1-2'] if '0-1-2' in counts else 0\n df.loc[index, 'count_1'] = counts[1] if 1 in counts else 0\n df.loc[index, 'count_2'] = counts[2] if 2 in counts else 0\n\n",
"Example\ndata = {'Species': {0: 'SP1', 1: 'SP2', 2: 'SP3'},\n 'COL1': {0: '0', 1: '1-2', 2: '0-1'},\n 'COL2': {0: '0', 1: '2', 2: '1'},\n 'COL3': {0: '0', 1: '0', 2: '2'},\n 'COL4': {0: '1-2', 1: '1', 2: '0'},\n 'COL5': {0: '0-1-2', 1: '0', 2: '1-2'}}\ndf = pd.DataFrame(data)\n\nCode\ndf1 = (df.set_index('Species').apply(lambda x: x.value_counts(), axis=1)\n .add_prefix('count_').fillna(0).astype('int'))\n\ndf1\n count_0 count_0-1 count_0-1-2 count_1 count_1-2 count_2\nSpecies \nSP1 3 0 1 0 1 0\nSP2 2 0 0 1 1 1\nSP3 1 1 0 1 1 1\n\nmake desired output\nconcat df & df1\npd.concat([df.set_index('Species'), df1], axis=1)\n\n"
] | [
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074675276_pandas_python_python_3.x.txt |
Q:
Countifs alternative in PowerQuery for MS PowerBI
I have a bit complicated PowerQuery query which has many steps. Within these steps I have a date, team and conditions as below (not actual data)
So the challenge is that I want to count the Pass number for each team for each day and then create another count for Pass and Fail and then it will be used in so many calculations which I can handle later.
I have tried many options, like for example grouping, but it was so confusing because as I mentioned before, the query has so many columns and calculations now. I could successfully solve the issue by creating DAX measure, but the issue here that I need to calculate the average outcome which is not possible to because I couldn't also average the measure of the outcome. So I have no other option but to make the countif though PowerQuery.
Appreciate your help and ideas.
Raw data as text is here in google sheets
A:
I am assuming that your dates showing the year 0203 is a typo and should be 2023
Not sure exactly what you want for output, but you should be able to adapt the below.
The solution seems to be a simple grouping with a count of the number of passes and/or fails.
The below code generates a separate column for passes and fails per team and date.
It is not sorted in the original order, but that could be added if necessary.
#"Grouped Rows" = Table.Group(#"Previous Step", {"Date", "Team"}, {
{"Pass", (t)=>List.Count(List.Select(t[#"PASS/FAIL"], each _ = "Pass")), Int64.Type},
{"Fail", (t)=>List.Count(List.Select(t[#"PASS/FAIL"], each _ = "Fail")), Int64.Type}
})
Using your data table from the Google sheet (after correcting the year):
let
Source = Excel.CurrentWorkbook(){[Name="Table12"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type date}, {"Team", type text}, {"PASS/FAIL", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Date", "Team"}, {
{"Pass", (t)=>List.Count(List.Select(t[#"PASS/FAIL"], each _ = "Pass")), Int64.Type},
{"Fail", (t)=>List.Count(List.Select(t[#"PASS/FAIL"], each _ = "Fail")), Int64.Type}
})
in
#"Grouped Rows"
A:
If you need the zeroes in your final output, you'll need to do a cross join to bring in combinations not present in the original.
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMtQ31DcyMDJW0lFyDAISAYnFxUqxOigSrn44JFxcgYRbYmYOuoSfD7KEkb4RilEkSeA0Cr8E3LlIEmDnEpYw1jfWNzAywDSKIgmcduCUQI0PJAnU+CDGKNSwotwOiFGxAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t, Team = _t, #"PASS/FAIL" = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type text}, {"Team", type text}, {"PASS/FAIL", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Date", "Team"}, {{"Count", each Table.RowCount(_), Int64.Type}}),
Custom1 = List.Distinct( #"Grouped Rows"[Date]),
#"Converted to Table" = Table.FromList(Custom1, Splitter.SplitByNothing(), {"Date"}, null, ExtraValues.Error),
#"Added Custom" = Table.AddColumn(#"Converted to Table", "Team", each List.Distinct( #"Grouped Rows"[Team])),
#"Expanded Team" = Table.ExpandListColumn(#"Added Custom", "Team"),
#"Merged Queries" = Table.NestedJoin(#"Expanded Team", {"Date", "Team"}, #"Grouped Rows", {"Date", "Team"}, "Expanded Team", JoinKind.LeftOuter),
#"Expanded Expanded Team" = Table.ExpandTableColumn(#"Merged Queries", "Expanded Team", {"Count"}, {"Count"}),
#"Replaced Value" = Table.ReplaceValue(#"Expanded Expanded Team",null,0,Replacer.ReplaceValue,{"Count"})
in
#"Replaced Value"
Stepping through the code:
Group by date and team and create a count:
Get a distinct list of dates
Convert to table
Add column for a cross join with all teams (to get zero values later)
Expand
Merge back to the grouped step to pull in the previous grouped values.
Replace nulls with 0
You can amend this for your other question by simply filtering for pass before you do the grouping.
| Countifs alternative in PowerQuery for MS PowerBI | I have a bit complicated PowerQuery query which has many steps. Within these steps I have a date, team and conditions as below (not actual data)
So the challenge is that I want to count the Pass number for each team for each day and then create another count for Pass and Fail and then it will be used in so many calculations which I can handle later.
I have tried many options, like for example grouping, but it was so confusing because as I mentioned before, the query has so many columns and calculations now. I could successfully solve the issue by creating DAX measure, but the issue here that I need to calculate the average outcome which is not possible to because I couldn't also average the measure of the outcome. So I have no other option but to make the countif though PowerQuery.
Appreciate your help and ideas.
Raw data as text is here in google sheets
| [
"I am assuming that your dates showing the year 0203 is a typo and should be 2023\nNot sure exactly what you want for output, but you should be able to adapt the below.\nThe solution seems to be a simple grouping with a count of the number of passes and/or fails.\nThe below code generates a separate column for passes and fails per team and date.\nIt is not sorted in the original order, but that could be added if necessary.\n #\"Grouped Rows\" = Table.Group(#\"Previous Step\", {\"Date\", \"Team\"}, {\n {\"Pass\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Pass\")), Int64.Type},\n {\"Fail\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Fail\")), Int64.Type}\n })\n\nUsing your data table from the Google sheet (after correcting the year):\nlet\n Source = Excel.CurrentWorkbook(){[Name=\"Table12\"]}[Content],\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Date\", type date}, {\"Team\", type text}, {\"PASS/FAIL\", type text}}),\n #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Date\", \"Team\"}, {\n {\"Pass\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Pass\")), Int64.Type},\n {\"Fail\", (t)=>List.Count(List.Select(t[#\"PASS/FAIL\"], each _ = \"Fail\")), Int64.Type}\n })\nin\n #\"Grouped Rows\"\n\n\n",
"If you need the zeroes in your final output, you'll need to do a cross join to bring in combinations not present in the original.\n\nlet\n Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText(\"i45WMtQ31DcyMDJW0lFyDAISAYnFxUqxOigSrn44JFxcgYRbYmYOuoSfD7KEkb4RilEkSeA0Cr8E3LlIEmDnEpYw1jfWNzAywDSKIgmcduCUQI0PJAnU+CDGKNSwotwOiFGxAA==\", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t, Team = _t, #\"PASS/FAIL\" = _t]),\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Date\", type text}, {\"Team\", type text}, {\"PASS/FAIL\", type text}}),\n #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Date\", \"Team\"}, {{\"Count\", each Table.RowCount(_), Int64.Type}}),\n Custom1 = List.Distinct( #\"Grouped Rows\"[Date]),\n #\"Converted to Table\" = Table.FromList(Custom1, Splitter.SplitByNothing(), {\"Date\"}, null, ExtraValues.Error),\n #\"Added Custom\" = Table.AddColumn(#\"Converted to Table\", \"Team\", each List.Distinct( #\"Grouped Rows\"[Team])),\n #\"Expanded Team\" = Table.ExpandListColumn(#\"Added Custom\", \"Team\"),\n #\"Merged Queries\" = Table.NestedJoin(#\"Expanded Team\", {\"Date\", \"Team\"}, #\"Grouped Rows\", {\"Date\", \"Team\"}, \"Expanded Team\", JoinKind.LeftOuter),\n #\"Expanded Expanded Team\" = Table.ExpandTableColumn(#\"Merged Queries\", \"Expanded Team\", {\"Count\"}, {\"Count\"}),\n #\"Replaced Value\" = Table.ReplaceValue(#\"Expanded Expanded Team\",null,0,Replacer.ReplaceValue,{\"Count\"})\nin\n #\"Replaced Value\"\n\nStepping through the code:\n\nGroup by date and team and create a count:\n\n\n\nGet a distinct list of dates\nConvert to table\nAdd column for a cross join with all teams (to get zero values later)\nExpand\nMerge back to the grouped step to pull in the previous grouped values.\nReplace nulls with 0\n\nYou can amend this for your other question by simply filtering for pass before you do the grouping.\n"
] | [
1,
0
] | [] | [] | [
"powerbi",
"powerbi_desktop",
"powerquery"
] | stackoverflow_0074674025_powerbi_powerbi_desktop_powerquery.txt |
Q:
Error url with parameters (read key from web.config) mvc c# visual studio 2013
I have the following code :
Β
publicΒ ActionResultΒ Signin()
{
var state = Guid.NewGuid(); // work for application state if required then we can use it.
var oAuthUrl = $"{ConfigurationManager.AppSettings["AuthorizationEndpoint"]}?response_type=code&redirect_uri={ConfigurationManager.AppSettings["RedirectUri"]}&client_id={ConfigurationManager.AppSettings["ClientId"]}&env={ConfigurationManager.AppSettings["Environment"]}&state={state}";
Β Β Β Β returnΒ Redirect(oAuthUrl);
}
there is a error in syntax of oAuthUrl. Please, i need your help
A:
I'm assuming you might need to install NuGet package System.Configuration.ConfigurationManager. What is the .Net version you are targetting?
I am asking it here since my reputation is not enough to comment on the original question.
public ActionResult Signin()
{
var state = Guid.NewGuid(); // work for application state if required then we can use it.
var oAuthUrl = $"{ConfigurationManager.AppSettings["AuthorizationEndpoint"]}?response_type=code&redirect_uri={ConfigurationManager.AppSettings["RedirectUri"]}&client_id={ConfigurationManager.AppSettings["ClientId"]}&env={ConfigurationManager.AppSettings["Environment"]}&state={state}";
return Redirect(oAuthUrl);
}
| Error url with parameters (read key from web.config) mvc c# visual studio 2013 | I have the following code :
Β
publicΒ ActionResultΒ Signin()
{
var state = Guid.NewGuid(); // work for application state if required then we can use it.
var oAuthUrl = $"{ConfigurationManager.AppSettings["AuthorizationEndpoint"]}?response_type=code&redirect_uri={ConfigurationManager.AppSettings["RedirectUri"]}&client_id={ConfigurationManager.AppSettings["ClientId"]}&env={ConfigurationManager.AppSettings["Environment"]}&state={state}";
Β Β Β Β returnΒ Redirect(oAuthUrl);
}
there is a error in syntax of oAuthUrl. Please, i need your help
| [
"I'm assuming you might need to install NuGet package System.Configuration.ConfigurationManager. What is the .Net version you are targetting?\nI am asking it here since my reputation is not enough to comment on the original question.\npublic ActionResult Signin()\n {\n var state = Guid.NewGuid(); // work for application state if required then we can use it.\n var oAuthUrl = $\"{ConfigurationManager.AppSettings[\"AuthorizationEndpoint\"]}?response_type=code&redirect_uri={ConfigurationManager.AppSettings[\"RedirectUri\"]}&client_id={ConfigurationManager.AppSettings[\"ClientId\"]}&env={ConfigurationManager.AppSettings[\"Environment\"]}&state={state}\";\n return Redirect(oAuthUrl);\n }\n\n\n"
] | [
0
] | [] | [] | [
"c#",
"model_view_controller",
"url",
"visual_studio_2013",
"web_config"
] | stackoverflow_0074675307_c#_model_view_controller_url_visual_studio_2013_web_config.txt |
Q:
Cmake build error on Fedora 37 ; cannot find UDev library
I was trying to make some games in SFML, download the source code on github but i have some dependencies issues while trying to build the code.
enter image description here
I'm working on Fedora 37.
Anyone know how to solve it ?
The library exit on /usr/lib/udev so i guess it's a path issues but i already try to export it on the $PATH but didn't work either.
A:
There is no reason to build SFML on Fedora since it is in the repos. Just do
dnf install SFML SFML-devel
| Cmake build error on Fedora 37 ; cannot find UDev library | I was trying to make some games in SFML, download the source code on github but i have some dependencies issues while trying to build the code.
enter image description here
I'm working on Fedora 37.
Anyone know how to solve it ?
The library exit on /usr/lib/udev so i guess it's a path issues but i already try to export it on the $PATH but didn't work either.
| [
"There is no reason to build SFML on Fedora since it is in the repos. Just do\ndnf install SFML SFML-devel\n\n"
] | [
0
] | [] | [] | [
"c++",
"cmake",
"linux",
"sfml"
] | stackoverflow_0074675119_c++_cmake_linux_sfml.txt |
Q:
w-screen and h-screen of tailwind are breaking the responsiveness
I am trying to make a 404 page with Nextjs and typescript. Here are the screenshots:
As you see, I have the scrollbar on both the right and bottom sides and they are breaking the responsiveness.
I gave the background color to make this noticeable.
Here's my code...
import Link from "next/link";
import { useRouter } from "next/router";
import React from "react";
interface Props {}
const ErrorPage: React.FC<Props> = ({}) => {
const router = useRouter();
return (
<>
<div className="bg-gray-900 h-screen w-screen flex justify-center items-center absolute z-0">
<svg
className="p-6 lg:p-48 fill-current text-gray-300"
viewBox="0 0 445 202"
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke="currentColor"
// viewBox="0 0 24 24"
>
<path
d="M137.587 154.953h-22.102V197h-37.6v-42.047H.53v-33.557L72.36 2.803h43.125V124.9h22.102v30.053zM77.886 124.9V40.537L28.966 124.9h48.92zm116.707-23.718c0 22.46 1.842 39.643 5.525 51.547 3.684 11.905 11.23 17.857 22.64 17.857 11.411 0 18.89-5.952 22.44-17.857 3.548-11.904 5.323-29.086 5.323-51.547 0-23.54-1.775-40.97-5.324-52.29s-11.028-16.98-22.438-16.98c-11.41 0-18.957 5.66-22.64 16.98-3.684 11.32-5.526 28.75-5.526 52.29zM222.759.242c24.887 0 42.339 8.76 52.356 26.28 10.018 17.52 15.027 42.406 15.027 74.66s-5.01 57.095-15.027 74.525c-10.017 17.43-27.47 26.145-52.356 26.145-24.887 0-42.339-8.715-52.357-26.145-10.017-17.43-15.026-42.271-15.026-74.525 0-32.254 5.009-57.14 15.026-74.66C180.42 9.001 197.872.241 222.76.241zm221.824 154.711h-22.102V197h-37.6v-42.047h-77.355v-33.557l71.83-118.593h43.125V124.9h22.102v30.053zM384.882 124.9V40.537l-48.92 84.363h48.92z"
fillRule="nonzero"
/>
</svg>
</div>
<div className="h-screen w-screen flex justify-center items-center relative z-10">
<div className="p-6 text-center">
<h2 className="uppercase text-xl lg:text-5xl font-black">
We are sorry, Page not found!
</h2>
<p className="mt-3 uppercase text-sm lg:text-base font-semibold text-gray-900">
The page you are looking for might have been removed had its name
changed or is temporarily unavailable.
</p>
<div className="text-center">
<Link href="/">
<a
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/3 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Back To Homepage
</a>
</Link>
<button
onClick={() => router.back()}
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/4 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Go Back
</button>
</div>
</div>
</div>
</>
);
};
export default ErrorPage;
Is this happening because of h-screen and w-screen or is something wrong with flex? But if I don't use them, I don't make it to work as I am expecting which is placing one div above the other (absolute). I am probably looking at this code for too long and I am lost in space.
So, what am I doing wrong here? Thanks.
A:
I would suggest to have a parent relative div
<div class="h-screen w-screen relative">
<!-- 404 -->
<div class="bg-gray-900 flex justify-center items-center absolute inset-0 z-0"> // inset-0 is important
<svg></svg>
</div>
<!-- content -->
<div class="flex justify-center items-center absolute inset-0 z-10">
</div>
</div>
A:
I replicated your design.
I would recommend changing h-screen to min-h-screen.
You can check out an example using your code in the following link.
https://play.tailwindcss.com/eD7VEDN5AR
A:
"width: 100vw" is breaking the page layout. There's a horizontal scrollbar appearing on the page.
That's because the w-screen property means "width: 100vw" (the element with such a property is supposed to consume the whole available device screen space horizontally).
As you have a vertical scrollbar on the page body () (as the body is probably bigger in height than the screen height (= 100vh)), you'll always have less gorizontal space than 100vw, as the horizontal space is also consumed by the vertical scrollbar.
It's not a TailwindCSS-related issue, but rather a CSS-related bug.
The vertical scrollbar's width is usually ~12 px, but it differs between OS'es and screen sizes.
What I think would be better is if CSS would count the available screen width for the 100vw property considering the scrollbar width, like 100vw = real screen width - (vertical scrollbar's width, if one is present).
"(height: 100vh // max-height: 100vh)" is breaking the page layout. There's a vertical scrollbar appearing
That's because the w-screen property means "width: 100vw" (the element with such a property is supposed to consume the whole available device screen space horizontally).
As you have a vertical scrollbar on the page body () (as the body is probably bigger in width than the screen width (= 100vw)), you'll always have less vertical space than 100vh, as the vertical space is also consumed by the horizontal scrollbar.
The horizontal scrollbar's width is usually ~12 px, but it differs between OS'es and screen sizes.
For this case CSS could count the property for the 100vh value like 100vh = real screen height - (horizontal scrollbar's height, if one is present).
What can be done now:
You better use width: 100% and height: 100% properties instead of width: 100vw and height: 100vh
It's always risky to use the vh and vw values. Why would you need that? Semantically, the child should always be smaller than the parent.
This is the same ugly workaround as hiding the problems with overflowing with "overflow-x: hidden".
So your code should look like:
import Link from "next/link";
import { useRouter } from "next/router";
import React from "react";
interface Props {}
const ErrorPage: React.FC<Props> = ({}) => {
const router = useRouter();
return (
<>
<div className="bg-gray-900 h-full w-full flex justify-center items-center absolute z-0">
<svg
className="p-6 lg:p-48 fill-current text-gray-300"
viewBox="0 0 445 202"
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke="currentColor"
// viewBox="0 0 24 24"
>
<path
d="M137.587 154.953h-22.102V197h-37.6v-42.047H.53v-33.557L72.36 2.803h43.125V124.9h22.102v30.053zM77.886 124.9V40.537L28.966 124.9h48.92zm116.707-23.718c0 22.46 1.842 39.643 5.525 51.547 3.684 11.905 11.23 17.857 22.64 17.857 11.411 0 18.89-5.952 22.44-17.857 3.548-11.904 5.323-29.086 5.323-51.547 0-23.54-1.775-40.97-5.324-52.29s-11.028-16.98-22.438-16.98c-11.41 0-18.957 5.66-22.64 16.98-3.684 11.32-5.526 28.75-5.526 52.29zM222.759.242c24.887 0 42.339 8.76 52.356 26.28 10.018 17.52 15.027 42.406 15.027 74.66s-5.01 57.095-15.027 74.525c-10.017 17.43-27.47 26.145-52.356 26.145-24.887 0-42.339-8.715-52.357-26.145-10.017-17.43-15.026-42.271-15.026-74.525 0-32.254 5.009-57.14 15.026-74.66C180.42 9.001 197.872.241 222.76.241zm221.824 154.711h-22.102V197h-37.6v-42.047h-77.355v-33.557l71.83-118.593h43.125V124.9h22.102v30.053zM384.882 124.9V40.537l-48.92 84.363h48.92z"
fillRule="nonzero"
/>
</svg>
</div>
<div className="h-full w-full flex justify-center items-center relative z-10">
<div className="p-6 text-center">
<h2 className="uppercase text-xl lg:text-5xl font-black">
We are sorry, Page not found!
</h2>
<p className="mt-3 uppercase text-sm lg:text-base font-semibold text-gray-900">
The page you are looking for might have been removed had its name
changed or is temporarily unavailable.
</p>
<div className="text-center">
<Link href="/">
<a
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/3 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Back To Homepage
</a>
</Link>
<button
onClick={() => router.back()}
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/4 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Go Back
</button>
</div>
</div>
</div>
</>
);
};
export default ErrorPage;
In the case of TailwindCSS, you should use h-full and w-full instead of h-screen and w-screen.
Also, in your specific case it's this line that was breaking everything, most likely:
<div className="h-screen w-screen flex justify-center items-center relative z-10">
As you already have this applied to the parent element:
<div className="bg-gray-900 h-screen w-screen flex justify-center items-center absolute z-0">
It's all wrong semantically in your code. This is ugly work-arounding.
You haven't provided the tailwind.config.js, so some of the colors in the demo are missing due to missing custom TailwidnCSS class names values.
But this is basically the same code with an exception of eplacing all -screen properties with -full and also removing the bottom padding of the svg, as on most of the screens, the svg has too much spacing and then consumes >100vh space of the screen and is not positioned at the center vertically, but rather has starneg white space at the bottom of the page.
https://dpd0jl.sse.codesandbox.io/
| w-screen and h-screen of tailwind are breaking the responsiveness | I am trying to make a 404 page with Nextjs and typescript. Here are the screenshots:
As you see, I have the scrollbar on both the right and bottom sides and they are breaking the responsiveness.
I gave the background color to make this noticeable.
Here's my code...
import Link from "next/link";
import { useRouter } from "next/router";
import React from "react";
interface Props {}
const ErrorPage: React.FC<Props> = ({}) => {
const router = useRouter();
return (
<>
<div className="bg-gray-900 h-screen w-screen flex justify-center items-center absolute z-0">
<svg
className="p-6 lg:p-48 fill-current text-gray-300"
viewBox="0 0 445 202"
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke="currentColor"
// viewBox="0 0 24 24"
>
<path
d="M137.587 154.953h-22.102V197h-37.6v-42.047H.53v-33.557L72.36 2.803h43.125V124.9h22.102v30.053zM77.886 124.9V40.537L28.966 124.9h48.92zm116.707-23.718c0 22.46 1.842 39.643 5.525 51.547 3.684 11.905 11.23 17.857 22.64 17.857 11.411 0 18.89-5.952 22.44-17.857 3.548-11.904 5.323-29.086 5.323-51.547 0-23.54-1.775-40.97-5.324-52.29s-11.028-16.98-22.438-16.98c-11.41 0-18.957 5.66-22.64 16.98-3.684 11.32-5.526 28.75-5.526 52.29zM222.759.242c24.887 0 42.339 8.76 52.356 26.28 10.018 17.52 15.027 42.406 15.027 74.66s-5.01 57.095-15.027 74.525c-10.017 17.43-27.47 26.145-52.356 26.145-24.887 0-42.339-8.715-52.357-26.145-10.017-17.43-15.026-42.271-15.026-74.525 0-32.254 5.009-57.14 15.026-74.66C180.42 9.001 197.872.241 222.76.241zm221.824 154.711h-22.102V197h-37.6v-42.047h-77.355v-33.557l71.83-118.593h43.125V124.9h22.102v30.053zM384.882 124.9V40.537l-48.92 84.363h48.92z"
fillRule="nonzero"
/>
</svg>
</div>
<div className="h-screen w-screen flex justify-center items-center relative z-10">
<div className="p-6 text-center">
<h2 className="uppercase text-xl lg:text-5xl font-black">
We are sorry, Page not found!
</h2>
<p className="mt-3 uppercase text-sm lg:text-base font-semibold text-gray-900">
The page you are looking for might have been removed had its name
changed or is temporarily unavailable.
</p>
<div className="text-center">
<Link href="/">
<a
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/3 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Back To Homepage
</a>
</Link>
<button
onClick={() => router.back()}
className="mt-6 m-auto bg-primary text-white py-4 px-6 w-1/4 block rounded-full tracking-wide
font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent
shadow-lg transition-css"
>
Go Back
</button>
</div>
</div>
</div>
</>
);
};
export default ErrorPage;
Is this happening because of h-screen and w-screen or is something wrong with flex? But if I don't use them, I don't make it to work as I am expecting which is placing one div above the other (absolute). I am probably looking at this code for too long and I am lost in space.
So, what am I doing wrong here? Thanks.
| [
"I would suggest to have a parent relative div\n<div class=\"h-screen w-screen relative\">\n\n <!-- 404 -->\n <div class=\"bg-gray-900 flex justify-center items-center absolute inset-0 z-0\"> // inset-0 is important\n <svg></svg>\n </div>\n \n <!-- content -->\n <div class=\"flex justify-center items-center absolute inset-0 z-10\">\n </div>\n\n</div>\n\n",
"I replicated your design.\nI would recommend changing h-screen to min-h-screen.\nYou can check out an example using your code in the following link.\nhttps://play.tailwindcss.com/eD7VEDN5AR\n",
"\"width: 100vw\" is breaking the page layout. There's a horizontal scrollbar appearing on the page.\nThat's because the w-screen property means \"width: 100vw\" (the element with such a property is supposed to consume the whole available device screen space horizontally).\nAs you have a vertical scrollbar on the page body () (as the body is probably bigger in height than the screen height (= 100vh)), you'll always have less gorizontal space than 100vw, as the horizontal space is also consumed by the vertical scrollbar.\nIt's not a TailwindCSS-related issue, but rather a CSS-related bug.\nThe vertical scrollbar's width is usually ~12 px, but it differs between OS'es and screen sizes.\nWhat I think would be better is if CSS would count the available screen width for the 100vw property considering the scrollbar width, like 100vw = real screen width - (vertical scrollbar's width, if one is present).\n\n\"(height: 100vh // max-height: 100vh)\" is breaking the page layout. There's a vertical scrollbar appearing\nThat's because the w-screen property means \"width: 100vw\" (the element with such a property is supposed to consume the whole available device screen space horizontally).\nAs you have a vertical scrollbar on the page body () (as the body is probably bigger in width than the screen width (= 100vw)), you'll always have less vertical space than 100vh, as the vertical space is also consumed by the horizontal scrollbar.\nThe horizontal scrollbar's width is usually ~12 px, but it differs between OS'es and screen sizes.\nFor this case CSS could count the property for the 100vh value like 100vh = real screen height - (horizontal scrollbar's height, if one is present).\nWhat can be done now:\nYou better use width: 100% and height: 100% properties instead of width: 100vw and height: 100vh\nIt's always risky to use the vh and vw values. Why would you need that? Semantically, the child should always be smaller than the parent.\nThis is the same ugly workaround as hiding the problems with overflowing with \"overflow-x: hidden\".\nSo your code should look like:\nimport Link from \"next/link\";\nimport { useRouter } from \"next/router\";\nimport React from \"react\";\n\ninterface Props {}\n\nconst ErrorPage: React.FC<Props> = ({}) => {\n const router = useRouter();\n return (\n <>\n <div className=\"bg-gray-900 h-full w-full flex justify-center items-center absolute z-0\">\n <svg\n className=\"p-6 lg:p-48 fill-current text-gray-300\"\n viewBox=\"0 0 445 202\"\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n stroke=\"currentColor\"\n // viewBox=\"0 0 24 24\"\n >\n <path\n d=\"M137.587 154.953h-22.102V197h-37.6v-42.047H.53v-33.557L72.36 2.803h43.125V124.9h22.102v30.053zM77.886 124.9V40.537L28.966 124.9h48.92zm116.707-23.718c0 22.46 1.842 39.643 5.525 51.547 3.684 11.905 11.23 17.857 22.64 17.857 11.411 0 18.89-5.952 22.44-17.857 3.548-11.904 5.323-29.086 5.323-51.547 0-23.54-1.775-40.97-5.324-52.29s-11.028-16.98-22.438-16.98c-11.41 0-18.957 5.66-22.64 16.98-3.684 11.32-5.526 28.75-5.526 52.29zM222.759.242c24.887 0 42.339 8.76 52.356 26.28 10.018 17.52 15.027 42.406 15.027 74.66s-5.01 57.095-15.027 74.525c-10.017 17.43-27.47 26.145-52.356 26.145-24.887 0-42.339-8.715-52.357-26.145-10.017-17.43-15.026-42.271-15.026-74.525 0-32.254 5.009-57.14 15.026-74.66C180.42 9.001 197.872.241 222.76.241zm221.824 154.711h-22.102V197h-37.6v-42.047h-77.355v-33.557l71.83-118.593h43.125V124.9h22.102v30.053zM384.882 124.9V40.537l-48.92 84.363h48.92z\"\n fillRule=\"nonzero\"\n />\n </svg>\n </div>\n <div className=\"h-full w-full flex justify-center items-center relative z-10\">\n <div className=\"p-6 text-center\">\n <h2 className=\"uppercase text-xl lg:text-5xl font-black\">\n We are sorry, Page not found!\n </h2>\n <p className=\"mt-3 uppercase text-sm lg:text-base font-semibold text-gray-900\">\n The page you are looking for might have been removed had its name\n changed or is temporarily unavailable.\n </p>\n <div className=\"text-center\">\n <Link href=\"/\">\n <a\n className=\"mt-6 m-auto bg-primary text-white py-4 px-6 w-1/3 block rounded-full tracking-wide\n font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent\n shadow-lg transition-css\"\n >\n Back To Homepage\n </a>\n </Link>\n\n <button\n onClick={() => router.back()}\n className=\"mt-6 m-auto bg-primary text-white py-4 px-6 w-1/4 block rounded-full tracking-wide\n font-semibold font-display focus:outline-none focus:shadow-outline hover:bg-primaryAccent\n shadow-lg transition-css\"\n >\n Go Back\n </button>\n </div>\n </div>\n </div>\n </>\n );\n};\n\nexport default ErrorPage;\n\nIn the case of TailwindCSS, you should use h-full and w-full instead of h-screen and w-screen.\nAlso, in your specific case it's this line that was breaking everything, most likely:\n<div className=\"h-screen w-screen flex justify-center items-center relative z-10\">\n\nAs you already have this applied to the parent element:\n<div className=\"bg-gray-900 h-screen w-screen flex justify-center items-center absolute z-0\">\n\nIt's all wrong semantically in your code. This is ugly work-arounding.\nYou haven't provided the tailwind.config.js, so some of the colors in the demo are missing due to missing custom TailwidnCSS class names values.\nBut this is basically the same code with an exception of eplacing all -screen properties with -full and also removing the bottom padding of the svg, as on most of the screens, the svg has too much spacing and then consumes >100vh space of the screen and is not positioned at the center vertically, but rather has starneg white space at the bottom of the page.\nhttps://dpd0jl.sse.codesandbox.io/\n"
] | [
0,
0,
0
] | [] | [] | [
"css",
"flexbox",
"next.js",
"tailwind_css"
] | stackoverflow_0066121961_css_flexbox_next.js_tailwind_css.txt |
Q:
Quicksort Algorithm: Need to know the time complexity of the following code and if it is optimized or not
I was practicing Quicksort algorithm and I suddenly came up with this solution, I need to know the time complexity of this algorithm and space complexity, and whether it is optimized or not.
def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot_index = 0
swap_index = 0
for i in range(1, len(arr)):
if arr[pivot_index] > arr[i]:
swap_index += 1
if not swap_index == i:
arr[i], arr[swap_index] = arr[swap_index], arr[i]
arr[pivot_index], arr[swap_index] = arr[swap_index], arr[pivot_index]
return quickSort(arr[:swap_index]) + [arr[swap_index]] + quickSort(arr[swap_index + 1:])
print(quickSort([1,3,3,3]))
| Quicksort Algorithm: Need to know the time complexity of the following code and if it is optimized or not | I was practicing Quicksort algorithm and I suddenly came up with this solution, I need to know the time complexity of this algorithm and space complexity, and whether it is optimized or not.
def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot_index = 0
swap_index = 0
for i in range(1, len(arr)):
if arr[pivot_index] > arr[i]:
swap_index += 1
if not swap_index == i:
arr[i], arr[swap_index] = arr[swap_index], arr[i]
arr[pivot_index], arr[swap_index] = arr[swap_index], arr[pivot_index]
return quickSort(arr[:swap_index]) + [arr[swap_index]] + quickSort(arr[swap_index + 1:])
print(quickSort([1,3,3,3]))
| [] | [] | [
"These pages explain it pretty good. Also with some graph plotting of your time and space measurement of your sort function, you would be able to analyse it by yourself.\nhttps://www.geeksforgeeks.org/time-complexity-and-space-complexity/\nhttps://iq.opengenus.org/time-and-space-complexity-of-quick-sort/\n"
] | [
-1
] | [
"python",
"quicksort"
] | stackoverflow_0074675096_python_quicksort.txt |
Q:
how do i fill colors selectively?
i want output like this where it feels circles back to back leave another two and then refill
`
for y in range(5,screensizE,scale):
for x in range(5,screensizE,scale):
centre = Point(x,y)
if doX == True:
drawcircle(win,centre,radius,colour[0])
else:
drawcircle(win,centre,radius,colour[1])
output = ''
enter image description here
`
A:
You can achieve the desired output by adding a counter variable that tracks the current position in the circle drawing sequence. The counter variable should be incremented every time a circle is drawn, and it should be reset to 0 when it reaches a certain value (e.g. 2 in the example you provided). Here is an example of how this can be implemented in your code:
# Initialize the counter variable
counter = 0
# Loop through the y-coordinates
for y in range(5, screensizE, scale):
# Loop through the x-coordinates
for x in range(5, screensizE, scale):
# Increment the counter
counter += 1
# Draw the circle
centre = Point(x, y)
if doX == True:
drawcircle(win, centre, radius, colour[0])
else:
drawcircle(win, centre, radius, colour[1])
# Check if the counter has reached its minimum value
if counter == 0:
# Reset the counter to 2
counter = 2
# Skip the next two positions by incrementing the loop indices
x += 2 * scale
y += 2 * scale
This should produce the desired output, with the circles being drawn back to back and leaving two empty positions in between each group of circles.
| how do i fill colors selectively? | i want output like this where it feels circles back to back leave another two and then refill
`
for y in range(5,screensizE,scale):
for x in range(5,screensizE,scale):
centre = Point(x,y)
if doX == True:
drawcircle(win,centre,radius,colour[0])
else:
drawcircle(win,centre,radius,colour[1])
output = ''
enter image description here
`
| [
"You can achieve the desired output by adding a counter variable that tracks the current position in the circle drawing sequence. The counter variable should be incremented every time a circle is drawn, and it should be reset to 0 when it reaches a certain value (e.g. 2 in the example you provided). Here is an example of how this can be implemented in your code:\n# Initialize the counter variable\ncounter = 0\n\n# Loop through the y-coordinates\nfor y in range(5, screensizE, scale):\n\n # Loop through the x-coordinates\n for x in range(5, screensizE, scale):\n\n # Increment the counter\n counter += 1\n\n # Draw the circle\n centre = Point(x, y)\n if doX == True:\n drawcircle(win, centre, radius, colour[0])\n else:\n drawcircle(win, centre, radius, colour[1])\n\n # Check if the counter has reached its minimum value\n if counter == 0:\n # Reset the counter to 2\n counter = 2\n\n # Skip the next two positions by incrementing the loop indices\n x += 2 * scale\n y += 2 * scale\n\nThis should produce the desired output, with the circles being drawn back to back and leaving two empty positions in between each group of circles.\n"
] | [
0
] | [] | [] | [
"graphics",
"python_3.x"
] | stackoverflow_0074675445_graphics_python_3.x.txt |
Q:
Bottom overflow by 30px
I face a problem by wrapping TextField with new Expanded(). When try to search something in textfield its show me bottom overflow by 30px. Below is my code:
Widget build(BuildContext context) {
return new Scaffold(
body:
Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {
setState(() {
});
}),
new Flexible(
child: new TextField(
onChanged: (String value) {
onchange(value);
},
maxLines: 1,
autocorrect: true,
// decoration: const InputDecoration(helperText: "Search"),
style: new TextStyle(fontSize: 10.0, color: Colors.black),
),
),
_text != null ? IconButton(
icon: Icon(Icons.close), onPressed: (){
}) : new Container(),
IconButton(icon: Icon(Icons.bookmark_border), onPressed: () {}),
],
),
new Expanded(
child: FilstList(searchtext: _text,)
),
],
),
);
}
}
A:
There are two solutions to this problem.
Add resizeToAvoidBottomPadding: false to your Scaffold
Scaffold(
resizeToAvoidBottomPadding: false,
body: ...)
Put your FilstList(searchtext: _text,) inside a scrollableView (like SingleChildScrollView or ListView)
A:
Use Scaffold property "resizeToAvoidBottomPadding: false"
and "SingleChildScrollView" as parent of Scaffold body:
home: Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text("Registration Page"),
),
body: SingleChildScrollView(
child: RegisterUser(),
)),
this will solve issue.
A:
You should use resizeToAvoidBottomInset
Scaffold(
resizeToAvoidBottomInset: false, // set it to false
...
)
If you're having issues with overflow error, use SingleChildScrollView with it.
Scaffold(
resizeToAvoidBottomInset: false, // set it to false
body: SingleChildScrollView(child: YourBody()),
)
A:
I faced a similar problem and fixed it in the following way:
You can wrap it with SingleChildScrollView or with a ListView.
Scaffold(
body: Container(
height: MediaQuery.of(context).size.height * .50,
child: SingleChildScrollView(
child: Column(
....
)
)
)
);
A:
put resizeToAvoidBottomPadding as false in Scaffold:
Scaffold(
resizeToAvoidBottomPadding: false,
update
it is better solution:
remove Column and put instead it ListView
because if you run this app on smaller device bottom items will disappear and hide from the show screen and that will be bad for App users.
A:
Use of resizeToAvoidBottomInset: false in your Scaffold is the best solution to that.
A:
Do two way
NO1.
Scaffold(
resizeToAvoidBottomPadding: false, )
The problem is when you do this body content never gone top when you select input box..
Best practice
SingleChildScrollView widget
A:
Use CustomScrollView with SliverToBoxAdapter:
body: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Form(....)
),
]
)
| Bottom overflow by 30px | I face a problem by wrapping TextField with new Expanded(). When try to search something in textfield its show me bottom overflow by 30px. Below is my code:
Widget build(BuildContext context) {
return new Scaffold(
body:
Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {
setState(() {
});
}),
new Flexible(
child: new TextField(
onChanged: (String value) {
onchange(value);
},
maxLines: 1,
autocorrect: true,
// decoration: const InputDecoration(helperText: "Search"),
style: new TextStyle(fontSize: 10.0, color: Colors.black),
),
),
_text != null ? IconButton(
icon: Icon(Icons.close), onPressed: (){
}) : new Container(),
IconButton(icon: Icon(Icons.bookmark_border), onPressed: () {}),
],
),
new Expanded(
child: FilstList(searchtext: _text,)
),
],
),
);
}
}
| [
"There are two solutions to this problem.\n\nAdd resizeToAvoidBottomPadding: false to your Scaffold\nScaffold(\n resizeToAvoidBottomPadding: false,\n body: ...)\n\nPut your FilstList(searchtext: _text,) inside a scrollableView (like SingleChildScrollView or ListView)\n\n",
"Use Scaffold property \"resizeToAvoidBottomPadding: false\" \nand \"SingleChildScrollView\" as parent of Scaffold body:\n home: Scaffold(\n resizeToAvoidBottomPadding: false,\n appBar: AppBar(\n title: Text(\"Registration Page\"),\n ),\n body: SingleChildScrollView(\n child: RegisterUser(),\n )),\n\nthis will solve issue.\n",
"You should use resizeToAvoidBottomInset\nScaffold(\n resizeToAvoidBottomInset: false, // set it to false\n ... \n)\n\n\nIf you're having issues with overflow error, use SingleChildScrollView with it. \nScaffold(\n resizeToAvoidBottomInset: false, // set it to false\n body: SingleChildScrollView(child: YourBody()),\n)\n\n",
"I faced a similar problem and fixed it in the following way:\nYou can wrap it with SingleChildScrollView or with a ListView.\nScaffold(\n body: Container(\n height: MediaQuery.of(context).size.height * .50,\n child: SingleChildScrollView(\n child: Column( \n ....\n )\n )\n )\n );\n\n",
"put resizeToAvoidBottomPadding as false in Scaffold:\n Scaffold(\n resizeToAvoidBottomPadding: false, \n\nupdate\nit is better solution:\nremove Column and put instead it ListView\nbecause if you run this app on smaller device bottom items will disappear and hide from the show screen and that will be bad for App users.\n",
"Use of resizeToAvoidBottomInset: false in your Scaffold is the best solution to that.\n",
"Do two way\nNO1.\nScaffold(\n resizeToAvoidBottomPadding: false, )\n\nThe problem is when you do this body content never gone top when you select input box..\nBest practice\nSingleChildScrollView widget\n",
"Use CustomScrollView with SliverToBoxAdapter:\nbody: CustomScrollView( \n slivers: [\n SliverToBoxAdapter(\n child: Form(....)\n ),\n ]\n)\n\n"
] | [
92,
10,
8,
4,
3,
3,
0,
0
] | [
"Used SigleChildScrollView\nsample code\nScaffold(\n appBar: //AppBar\n body: SingleChildScrollView(\n padding: EdgeInsets.symmetric(horizontal: 5.0, vertical: 3.0),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n\n"
] | [
-1
] | [
"flutter",
"flutter_layout"
] | stackoverflow_0051972371_flutter_flutter_layout.txt |
Q:
Example of why downcast is not allowed and if it's done then why it's unsafe
#include <iostream>
class A{
public:
virtual void display(){
std::cout<<"A Class"<<std::endl;
}
};
class B: public A{
public:
void show(){
std::cout<<"B Class"<<std::endl;
}
};
int main()
{
A *ob = new B();
ob->display();//A Class
B *ob1 = (B*)(ob);
ob1->show();//B Class
A *obj = new A();
B *obj1 = (B*)obj;
obj1->display();//A Class
obj1->show();//B Class
return 0;
}
Above is the example for upcasting and downcasting.
My questions are -
Why downcasting is not allowed and if its done why explicitly need to be done.
Why downcasting is unsafe and its considered as a bad design.
I have read over internet every answer but, didn't get any proper answer with example.
So, can anyone explain about the same with some easy example ?
A:
I have changed your example a bit so that error get more obvious:
#include <iostream>
class A{
public:
virtual void display(){
std::cout<<"A Class"<<std::endl;
}
};
class B: public A{
int* s=new int;
public:
void show(){
std::cout<<"B Class"<<*s<<std::endl;
}
};
int main()
{
A *ob = new B();
ob->display();//A Class
B *ob1 = (B*)(ob);
ob1->show();//B Class
A *obj = new A();
B *obj1 = (B*)obj;
obj1->display();//A Class
obj1->show();//B Class
return 0;
}
The change I did is adding a member variable to B and print its value. So when you create an object of type A and downcast it to B, where do you think that that member has been initialized?
And the answer ist that it was never initialised and that not even some memory was reserved for it.
| Example of why downcast is not allowed and if it's done then why it's unsafe | #include <iostream>
class A{
public:
virtual void display(){
std::cout<<"A Class"<<std::endl;
}
};
class B: public A{
public:
void show(){
std::cout<<"B Class"<<std::endl;
}
};
int main()
{
A *ob = new B();
ob->display();//A Class
B *ob1 = (B*)(ob);
ob1->show();//B Class
A *obj = new A();
B *obj1 = (B*)obj;
obj1->display();//A Class
obj1->show();//B Class
return 0;
}
Above is the example for upcasting and downcasting.
My questions are -
Why downcasting is not allowed and if its done why explicitly need to be done.
Why downcasting is unsafe and its considered as a bad design.
I have read over internet every answer but, didn't get any proper answer with example.
So, can anyone explain about the same with some easy example ?
| [
"I have changed your example a bit so that error get more obvious:\n#include <iostream>\n\nclass A{\n public:\n virtual void display(){\n std::cout<<\"A Class\"<<std::endl;\n }\n};\n\nclass B: public A{\n int* s=new int;\n public:\n void show(){\n std::cout<<\"B Class\"<<*s<<std::endl;\n }\n};\n\nint main() \n{\n A *ob = new B();\n ob->display();//A Class\n B *ob1 = (B*)(ob);\n ob1->show();//B Class\n\n A *obj = new A();\n B *obj1 = (B*)obj;\n obj1->display();//A Class\n obj1->show();//B Class\n \n return 0;\n}\n\nThe change I did is adding a member variable to B and print its value. So when you create an object of type A and downcast it to B, where do you think that that member has been initialized?\nAnd the answer ist that it was never initialised and that not even some memory was reserved for it.\n"
] | [
0
] | [] | [] | [
"c++"
] | stackoverflow_0074675169_c++.txt |
Q:
How to handle sessions securely in SvelteKit
I'm fairly new to SvelteKit and I'm wondering how to properly handle sessions. From what I understand a unique session ID is typically stored in the browser as a cookie and this is linked to the currently signed in user backend. I'm used to PHP where all this is taken care of for you but that doesn't seem to be the case with SvelteKit.
This is what I've got so far:
/src/hooks.ts:
import cookie from 'cookie';
import { v4 as uuid } from '@lukeed/uuid';
import type { Handle } from '@sveltejs/kit';
import { getOrCreateSession } from '$lib/Authentication';
export const handle: Handle = async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
event.locals.userid = cookies.userid || uuid();
const response = await resolve(event);
if (!cookies.userid) {
// if this is the first time the user has visited this app,
// set a cookie so that we recognise them when they return
response.headers.set(
'set-cookie',
cookie.serialize('userid', event.locals.userid, {
path: '/',
httpOnly: true
})
);
}
return response;
};
export async function getSession(event) : Promise<App.Session> {
return getOrCreateSession(event.locals.userid);
}
/src/app.d.ts:
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#the-app-namespace
// for information about these interfaces
declare namespace App {
interface Locals {
userid: string;
}
// interface Platform {}
interface Session {
id: string;
userId?: number;
}
// interface Stuff {}
}
/src/lib/Authentication.ts:
export let sessions: App.Session[] = [];
export async function getOrCreateSession(id: string) {
let session = sessions.find(x => x.id === id);
if(!session) {
session = {
id: id,
};
sessions.push(session);
}
return session;
}
/src/routes/setSession.svelte:
<script lang="ts" context="module">
export async function load({ session }) {
session.userId = 1;
return {}
}
</script>
/src/routes/getSession.svelte:
<script lang="ts" context="module">
export async function load({ fetch, session }) {
return {
props: {
session: session,
}
}
}
</script>
<script lang="ts">
export let session: App.Session;
</script>
{JSON.stringify(session)}
Visiting /setSession will set userId and it'll be retrieved when visiting /getSession.
Is this the proper way to do this?
Other than sessions not persisting on server restart, is there any other drawback storing the sessions in a variable instead of a database?
Over time sessions will become quite large. To have an expiry date that's extended on each request would probably be a good idea but where would be a good place to put the code that remove all expired sessions?
A:
I am also new to sveltekit and I believe that sveltekit server side is typically stateless so that it can be deployed on edge functions.
One way to manage sessions, would be to store all session data in an HTTP only cookie (not only the session ID). This is the idea of svelte-kit-cookie-session
Of course, you can also use a database to store session data.
To manage expiration:
If you store session data in a cookie, then set the expires parameter on the creation
If you store session data in a database, depending on the database, you might use a Time To Live policy...
| How to handle sessions securely in SvelteKit | I'm fairly new to SvelteKit and I'm wondering how to properly handle sessions. From what I understand a unique session ID is typically stored in the browser as a cookie and this is linked to the currently signed in user backend. I'm used to PHP where all this is taken care of for you but that doesn't seem to be the case with SvelteKit.
This is what I've got so far:
/src/hooks.ts:
import cookie from 'cookie';
import { v4 as uuid } from '@lukeed/uuid';
import type { Handle } from '@sveltejs/kit';
import { getOrCreateSession } from '$lib/Authentication';
export const handle: Handle = async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
event.locals.userid = cookies.userid || uuid();
const response = await resolve(event);
if (!cookies.userid) {
// if this is the first time the user has visited this app,
// set a cookie so that we recognise them when they return
response.headers.set(
'set-cookie',
cookie.serialize('userid', event.locals.userid, {
path: '/',
httpOnly: true
})
);
}
return response;
};
export async function getSession(event) : Promise<App.Session> {
return getOrCreateSession(event.locals.userid);
}
/src/app.d.ts:
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#the-app-namespace
// for information about these interfaces
declare namespace App {
interface Locals {
userid: string;
}
// interface Platform {}
interface Session {
id: string;
userId?: number;
}
// interface Stuff {}
}
/src/lib/Authentication.ts:
export let sessions: App.Session[] = [];
export async function getOrCreateSession(id: string) {
let session = sessions.find(x => x.id === id);
if(!session) {
session = {
id: id,
};
sessions.push(session);
}
return session;
}
/src/routes/setSession.svelte:
<script lang="ts" context="module">
export async function load({ session }) {
session.userId = 1;
return {}
}
</script>
/src/routes/getSession.svelte:
<script lang="ts" context="module">
export async function load({ fetch, session }) {
return {
props: {
session: session,
}
}
}
</script>
<script lang="ts">
export let session: App.Session;
</script>
{JSON.stringify(session)}
Visiting /setSession will set userId and it'll be retrieved when visiting /getSession.
Is this the proper way to do this?
Other than sessions not persisting on server restart, is there any other drawback storing the sessions in a variable instead of a database?
Over time sessions will become quite large. To have an expiry date that's extended on each request would probably be a good idea but where would be a good place to put the code that remove all expired sessions?
| [
"I am also new to sveltekit and I believe that sveltekit server side is typically stateless so that it can be deployed on edge functions.\nOne way to manage sessions, would be to store all session data in an HTTP only cookie (not only the session ID). This is the idea of svelte-kit-cookie-session\nOf course, you can also use a database to store session data.\nTo manage expiration:\n\nIf you store session data in a cookie, then set the expires parameter on the creation\nIf you store session data in a database, depending on the database, you might use a Time To Live policy...\n\n"
] | [
0
] | [] | [] | [
"sveltekit"
] | stackoverflow_0072230390_sveltekit.txt |
Q:
Woocommerce - displays price with tax, but charging without tax
I have a problem with wocommerce shop. I'm manually adding product to cart by below code:
WC()->cart->add_to_cart( $product_id, 1, 0, array(), array( 'misha_custom_price' => $my_custom_price ) );
In my functions.php I have added below code:
add_action( 'woocommerce_before_calculate_totals', 'rudr_custom_price_refresh' );
function rudr_custom_price_refresh( $cart_object ) {
foreach ( $cart_object->get_cart() as $item ) {
if( array_key_exists( 'misha_custom_price', $item ) ) {
$item[ 'data' ]->set_price( $item[ 'misha_custom_price' ] );
}
}
}
On my checkout page, price is shown correctly, eg. 123$ (including 23$ as 23% VAT).
But when I go to pay, I see price without tax (100$).
Please help me. Thanks.
A:
I found a solution. I was using a plugin to manage checkout fields. I have hidden the "Coutry" field on the checkout page. This field must be visible for the tax to work properly.
| Woocommerce - displays price with tax, but charging without tax | I have a problem with wocommerce shop. I'm manually adding product to cart by below code:
WC()->cart->add_to_cart( $product_id, 1, 0, array(), array( 'misha_custom_price' => $my_custom_price ) );
In my functions.php I have added below code:
add_action( 'woocommerce_before_calculate_totals', 'rudr_custom_price_refresh' );
function rudr_custom_price_refresh( $cart_object ) {
foreach ( $cart_object->get_cart() as $item ) {
if( array_key_exists( 'misha_custom_price', $item ) ) {
$item[ 'data' ]->set_price( $item[ 'misha_custom_price' ] );
}
}
}
On my checkout page, price is shown correctly, eg. 123$ (including 23$ as 23% VAT).
But when I go to pay, I see price without tax (100$).
Please help me. Thanks.
| [
"I found a solution. I was using a plugin to manage checkout fields. I have hidden the \"Coutry\" field on the checkout page. This field must be visible for the tax to work properly.\n"
] | [
0
] | [] | [] | [
"php",
"woocommerce",
"wordpress"
] | stackoverflow_0074644794_php_woocommerce_wordpress.txt |
Q:
Find the flag from a RSA encryption written in C with no modulus
So I'm doing a practice Capture The Flag problem, The problem reads:
I was trying to implement RSA in C but I forgot the modulus. But I think this might be good enough already?
And then there is this code written in C attached to the question:
#include <stdio.h>
int main()
{
unsigned long long int flag1 = <redacted>;
flag1++;
unsigned long long int flag2 = <redacted>;
unsigned long long int ct1 = 1;
unsigned long long int ct2 = 1;
for (int i = 0; i<65537; i++)
{
ct1 = ct1 * flag1;
ct2 = ct2 * flag2;
}
printf("%llu\n",ct1);
printf("%llu\n",ct2);
}
/*OUTPUT:
7904812928421683021
16220282676865089917
*/
I want to get the flag, that is I want to find the values of flag1 and flag2 which outputted ct1(7904812928421683021) and ct2(16220282676865089917) after running in the program. Therefore I want to get the values of flag1 and flag 2 which is indicated by 'redacted' in the program.
I've done some research and found that 65537 is the public key exponent also in the question it states that they forgot the modulus. I've been sitting at this problem for hours now and still couldn't find anything particularly useful. I'm a beginner at cryptography so any help would be greatly appreciated.
If anyone of you could help it would mean a lot.
Thank you.
A:
By appearances, unsigned long long int is 64 bits in the C implementation being used, so the arithmetic is performed modulo 264.
The loop that multiplies by flag1 or flag2 65537 times computes flag165537 modulo 264 and flag265537 modulo 264. We are given the results 7904812928421683021 and 16220282676865089917. To find flag1 and flag2 prior to the loop, we want to compute the inverse function.
By a generalization of Fermatβs little theorem, a(n) β‘ 1 mod n, where is Eulerβs totient function. This means that exponentiating modulo n by (n) is the same as exponentiating modulo n by 0, which means that exponentiation modulo n works modulo (n) in the exponent. In other words, ab β‘ ac mod n if b β‘ c mod (n).
The way this is useful to us is that when we have ab mod n, if we can find a c such that bc β‘ 1 mod (n), then we can compute (ab)c mod n = abc mod n = a1 mod n = a mod n.
The Wikipedia page for Eulerβs totient function tells us (n) = nβ’product(1β1/p for prime p|n). (That product is the multiplication of 1β1/p for each prime p that divides n.) Since our n is 264, the only prime that divides it is 2, for which 1β1/2 = Β½, so (264) = 264β’Β½ = 263.
Then we need to find the c such that bc β‘ 1 mod (n) for b = 65537 and (n) = 263. This can be done with the extended Euclidean algorithm. However, since we only need to do it once, and the numbers involved are large enough to be awkward to do in common C implementations, we can simply ask Wolfram Alpha for 65537^-1 mod 2^64, for which it tells us 9,223,090,566,172,966,913.
Next, we need to be able to raise a number to the power of 9,223,090,566,172,966,913. As this would take too long to do by simple iterative multiplication, we can instead use the algorithm below:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
/* This routine computes x**e modulo 2^64 by multiplying a running product by
each x**p such that p is a power of two whose corresponding bit is set in
e. Thus, if e is 19, which is 10011 in binary, the powers of two
represented in it are 2^16, 2^1, and 2^0, so we multiply the running
product by x^(2^0), x^(2^1), and x^(2^16), yielding x^(2^0 + 2^1 + 2^16) =
x^19.
*/
static uint64_t pow_u64(uint64_t x, uint64_t e)
{
uint64_t y = 1; // Initialize running product to 1.
while (e) // Continue while bits remain in exponent.
{
if (e & 1) // If current bit is set, multiply by power of x.
y *= x;
x *= x; // Update to next x to a power-of-two.
e >>= 1; // Update e to move next bit into low position.
}
return y;
}
static void Do(uint64_t y)
{
uint64_t c = 9223090566172966913u;
printf("%" PRIu64 " ^ %" PRIu64 " = %" PRIu64 ".\n", y, c, pow_u64(y, c));
}
int main(void)
{
Do(7904812928421683021u);
Do(16220282676865089917u);
}
This produces the output:
7904812928421683021 ^ 9223090566172966913 = 7380380986431332173.
16220282676865089917 ^ 9223090566172966913 = 5716833052698820989.
from which we see the values of flag1 and flag2 before the loop are 7,380,380,986,431,332,173 and 5,716,833,052,698,820,989.
Since flag1 was incremented with ++ after it was initialized by <redacted>, we subtract 1 to get the initial value, 7,380,380,986,431,332,172. flag2 was directly initialized with 5,716,833,052,698,820,989.
| Find the flag from a RSA encryption written in C with no modulus | So I'm doing a practice Capture The Flag problem, The problem reads:
I was trying to implement RSA in C but I forgot the modulus. But I think this might be good enough already?
And then there is this code written in C attached to the question:
#include <stdio.h>
int main()
{
unsigned long long int flag1 = <redacted>;
flag1++;
unsigned long long int flag2 = <redacted>;
unsigned long long int ct1 = 1;
unsigned long long int ct2 = 1;
for (int i = 0; i<65537; i++)
{
ct1 = ct1 * flag1;
ct2 = ct2 * flag2;
}
printf("%llu\n",ct1);
printf("%llu\n",ct2);
}
/*OUTPUT:
7904812928421683021
16220282676865089917
*/
I want to get the flag, that is I want to find the values of flag1 and flag2 which outputted ct1(7904812928421683021) and ct2(16220282676865089917) after running in the program. Therefore I want to get the values of flag1 and flag 2 which is indicated by 'redacted' in the program.
I've done some research and found that 65537 is the public key exponent also in the question it states that they forgot the modulus. I've been sitting at this problem for hours now and still couldn't find anything particularly useful. I'm a beginner at cryptography so any help would be greatly appreciated.
If anyone of you could help it would mean a lot.
Thank you.
| [
"By appearances, unsigned long long int is 64 bits in the C implementation being used, so the arithmetic is performed modulo 264.\nThe loop that multiplies by flag1 or flag2 65537 times computes flag165537 modulo 264 and flag265537 modulo 264. We are given the results 7904812928421683021 and 16220282676865089917. To find flag1 and flag2 prior to the loop, we want to compute the inverse function.\nBy a generalization of Fermatβs little theorem, a(n) β‘ 1 mod n, where is Eulerβs totient function. This means that exponentiating modulo n by (n) is the same as exponentiating modulo n by 0, which means that exponentiation modulo n works modulo (n) in the exponent. In other words, ab β‘ ac mod n if b β‘ c mod (n).\nThe way this is useful to us is that when we have ab mod n, if we can find a c such that bc β‘ 1 mod (n), then we can compute (ab)c mod n = abc mod n = a1 mod n = a mod n.\nThe Wikipedia page for Eulerβs totient function tells us (n) = nβ’product(1β1/p for prime p|n). (That product is the multiplication of 1β1/p for each prime p that divides n.) Since our n is 264, the only prime that divides it is 2, for which 1β1/2 = Β½, so (264) = 264β’Β½ = 263.\nThen we need to find the c such that bc β‘ 1 mod (n) for b = 65537 and (n) = 263. This can be done with the extended Euclidean algorithm. However, since we only need to do it once, and the numbers involved are large enough to be awkward to do in common C implementations, we can simply ask Wolfram Alpha for 65537^-1 mod 2^64, for which it tells us 9,223,090,566,172,966,913.\nNext, we need to be able to raise a number to the power of 9,223,090,566,172,966,913. As this would take too long to do by simple iterative multiplication, we can instead use the algorithm below:\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdio.h>\n\n\n/* This routine computes x**e modulo 2^64 by multiplying a running product by\n each x**p such that p is a power of two whose corresponding bit is set in\n e. Thus, if e is 19, which is 10011 in binary, the powers of two\n represented in it are 2^16, 2^1, and 2^0, so we multiply the running\n product by x^(2^0), x^(2^1), and x^(2^16), yielding x^(2^0 + 2^1 + 2^16) =\n x^19.\n*/\nstatic uint64_t pow_u64(uint64_t x, uint64_t e)\n{\n uint64_t y = 1; // Initialize running product to 1.\n while (e) // Continue while bits remain in exponent.\n {\n if (e & 1) // If current bit is set, multiply by power of x.\n y *= x;\n x *= x; // Update to next x to a power-of-two.\n e >>= 1; // Update e to move next bit into low position.\n }\n return y;\n}\n\n\nstatic void Do(uint64_t y)\n{\n uint64_t c = 9223090566172966913u;\n printf(\"%\" PRIu64 \" ^ %\" PRIu64 \" = %\" PRIu64 \".\\n\", y, c, pow_u64(y, c));\n}\n\n\nint main(void)\n{\n Do(7904812928421683021u);\n Do(16220282676865089917u);\n}\n\nThis produces the output:\n\n7904812928421683021 ^ 9223090566172966913 = 7380380986431332173.\n16220282676865089917 ^ 9223090566172966913 = 5716833052698820989.\n\nfrom which we see the values of flag1 and flag2 before the loop are 7,380,380,986,431,332,173 and 5,716,833,052,698,820,989.\nSince flag1 was incremented with ++ after it was initialized by <redacted>, we subtract 1 to get the initial value, 7,380,380,986,431,332,172. flag2 was directly initialized with 5,716,833,052,698,820,989.\n"
] | [
1
] | [] | [] | [
"c",
"cryptography",
"encryption",
"reverse_engineering",
"rsa"
] | stackoverflow_0074672930_c_cryptography_encryption_reverse_engineering_rsa.txt |
Q:
Python Executable Crashes in Conda Environment
Let's say I have two files we'll call test1.py and test2.py, and I want to run both of these files as executables. I'm familiar with the standard procedure of adding a shebang followed by the path to the desired python interpreter and then running chmod u="rwx" file.py.
I also know that when using conda, each environment gets its own unique interpreter with which to run scripts. So naturally, I activate my environment, run which python and add that command's output to my script like so...
test1.py
#!/home/my_name/anaconda3/envs/env_name/bin/python
print("foo")
Which when I run it as ./test1.py gives me the following error...
./test1.py: line 2: syntax error near unexpected token `"foo"'
./test1.py: line 2: `print("foo")'
However simply running python test1.py gives...
foo
Now let's say I return to my base environment and following the same procedure as above, I create the following script...
test2.py
#!/home/my_name/anaconda3/bin/python
print("foo")
This script runs without error and gives the correct output regardless of whether or not I run it as an executable.
What do I need to do in order to run my python scripts without these errors?
EDIT
Running which python in env_name gives
/home/my_name/anaconda3/envs/env_name/bin/python
Whereas running the same command in base gives
/home/my_name/anaconda3/bin/python
A:
I had the same issue when line 1 was empty, and the interpreter was set in line 2. This results in bash assuming that it's a bash script, and as a result, you get a "syntax error" from trying to execute python commands in bash.
| Python Executable Crashes in Conda Environment | Let's say I have two files we'll call test1.py and test2.py, and I want to run both of these files as executables. I'm familiar with the standard procedure of adding a shebang followed by the path to the desired python interpreter and then running chmod u="rwx" file.py.
I also know that when using conda, each environment gets its own unique interpreter with which to run scripts. So naturally, I activate my environment, run which python and add that command's output to my script like so...
test1.py
#!/home/my_name/anaconda3/envs/env_name/bin/python
print("foo")
Which when I run it as ./test1.py gives me the following error...
./test1.py: line 2: syntax error near unexpected token `"foo"'
./test1.py: line 2: `print("foo")'
However simply running python test1.py gives...
foo
Now let's say I return to my base environment and following the same procedure as above, I create the following script...
test2.py
#!/home/my_name/anaconda3/bin/python
print("foo")
This script runs without error and gives the correct output regardless of whether or not I run it as an executable.
What do I need to do in order to run my python scripts without these errors?
EDIT
Running which python in env_name gives
/home/my_name/anaconda3/envs/env_name/bin/python
Whereas running the same command in base gives
/home/my_name/anaconda3/bin/python
| [
"I had the same issue when line 1 was empty, and the interpreter was set in line 2. This results in bash assuming that it's a bash script, and as a result, you get a \"syntax error\" from trying to execute python commands in bash.\n"
] | [
0
] | [] | [] | [
"conda",
"executable",
"python"
] | stackoverflow_0071374828_conda_executable_python.txt |
Q:
Converting an RGB color tuple to a hexidecimal string
I need to convert (0, 128, 64) to something like this "#008040". I'm not sure what to call the latter, making searching difficult.
A:
Use the format operator %:
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
Note that it won't check bounds...
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
A:
def clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
This uses the preferred method of string formatting, as described in PEP 3101. It also uses min() and max to ensure that 0 <= {r,g,b} <= 255.
Update added the clamp function as suggested below.
Update From the title of the question and the context given, it should be obvious that this expects 3 ints in [0,255] and will always return a color when passed 3 such ints. However, from the comments, this may not be obvious to everyone, so let it be explicitly stated:
Provided three int values, this will return a valid hex triplet representing a color. If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.
A:
I have created a full python program for it the following functions can convert rgb to hex and vice versa.
def rgb2hex(r,g,b):
return "#{:02x}{:02x}{:02x}".format(r,g,b)
def hex2rgb(hexcode):
return tuple(map(ord,hexcode[1:].decode('hex')))
You can see the full code and tutorial at the following link : RGB to Hex and Hex to RGB conversion using Python
A:
This is an old question but for information, I developed a package with some utilities related to colors and colormaps and contains the rgb2hex function you were looking to convert triplet into hexa value (which can be found in many other packages, e.g. matplotlib). It's on pypi
pip install colormap
and then
>>> from colormap import rgb2hex
>>> rgb2hex(0, 128, 64)
'##008040'
Validity of the inputs is checked (values must be between 0 and 255).
A:
I'm truly surprised no one suggested this approach:
For Python 2 and 3:
'#' + ''.join('{:02X}'.format(i) for i in colortuple)
Python 3.6+:
'#' + ''.join(f'{i:02X}' for i in colortuple)
As a function:
def hextriplet(colortuple):
return '#' + ''.join(f'{i:02X}' for i in colortuple)
color = (0, 128, 64)
print(hextriplet(color))
#008040
A:
triplet = (0, 128, 64)
print '#'+''.join(map(chr, triplet)).encode('hex')
or
from struct import pack
print '#'+pack("BBB",*triplet).encode('hex')
python3 is slightly different
from base64 import b16encode
print(b'#'+b16encode(bytes(triplet)))
A:
you can use lambda and f-strings(available in python 3.6+)
rgb2hex = lambda r,g,b: f"#{r:02x}{g:02x}{b:02x}"
hex2rgb = lambda hx: (int(hx[0:2],16),int(hx[2:4],16),int(hx[4:6],16))
usage
rgb2hex(r,g,b) #output = #hexcolor
hex2rgb("#hex") #output = (r,g,b) hexcolor must be in #hex format
A:
In Python 3.6, you can use f-strings to make this cleaner:
rgb = (0,128, 64)
f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'
Of course you can put that into a function, and as a bonus, values get rounded and converted to int:
def rgb2hex(r,g,b):
return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'
rgb2hex(*rgb)
A:
Here is a more complete function for handling situations in which you may have RGB values in the range [0,1] or the range [0,255].
def RGBtoHex(vals, rgbtype=1):
"""Converts RGB values in a variety of formats to Hex values.
@param vals An RGB/RGBA tuple
@param rgbtype Valid valus are:
1 - Inputs are in the range 0 to 1
256 - Inputs are in the range 0 to 255
@return A hex string in the form '#RRGGBB' or '#RRGGBBAA'
"""
if len(vals)!=3 and len(vals)!=4:
raise Exception("RGB or RGBA inputs to RGBtoHex must have three or four elements!")
if rgbtype!=1 and rgbtype!=256:
raise Exception("rgbtype must be 1 or 256!")
#Convert from 0-1 RGB/RGBA to 0-255 RGB/RGBA
if rgbtype==1:
vals = [255*x for x in vals]
#Ensure values are rounded integers, convert to hex, and concatenate
return '#' + ''.join(['{:02X}'.format(int(round(x))) for x in vals])
print(RGBtoHex((0.1,0.3, 1)))
print(RGBtoHex((0.8,0.5, 0)))
print(RGBtoHex(( 3, 20,147), rgbtype=256))
print(RGBtoHex(( 3, 20,147,43), rgbtype=256))
A:
Note that this only works with python3.6 and above.
def rgb2hex(color):
"""Converts a list or tuple of color to an RGB string
Args:
color (list|tuple): the list or tuple of integers (e.g. (127, 127, 127))
Returns:
str: the rgb string
"""
return f"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in color)}"
The above is the equivalent of:
def rgb2hex(color):
string = '#'
for value in color:
hex_string = hex(value) # e.g. 0x7f
reduced_hex_string = hex_string[2:] # e.g. 7f
capitalized_hex_string = reduced_hex_string.upper() # e.g. 7F
string += capitalized_hex_string # e.g. #7F7F7F
return string
A:
You can also use bit wise operators which is pretty efficient, even though I doubt you'd be worried about efficiency with something like this. It's also relatively clean. Note it doesn't clamp or check bounds. This has been supported since at least Python 2.7.17.
hex(r << 16 | g << 8 | b)
And to change it so it starts with a # you can do:
"#" + hex(243 << 16 | 103 << 8 | 67)[2:]
A:
def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)
background = RGB(0, 128, 64)
I know one-liners in Python aren't necessarily looked upon kindly. But there are times where I can't resist taking advantage of what the Python parser does allow. It's the same answer as Dietrich Epp's solution (the best), but wrapped up in a single line function. So, thank you Dietrich!
I'm using it now with tkinter :-)
A:
There is a package called webcolors. https://github.com/ubernostrum/webcolors
It has a method webcolors.rgb_to_hex
>>> import webcolors
>>> webcolors.rgb_to_hex((12,232,23))
'#0ce817'
A:
''.join('%02x'%i for i in input)
can be used for hex conversion from int number
A:
If typing the formatting string three times seems a bit verbose...
The combination of bit shifts and an f-string will do the job nicely:
# Example setup.
>>> r, g, b = 0, 0, 195
# Create the hex string.
>>> f'#{r << 16 | g << 8 | b:06x}'
'#0000c3'
This also illustrates a method by which 'leading' zero bits are not dropped, if either the red or green channels are zero.
A:
Use this line
'#%02X%02X%02X' % (r,g,b)
A:
#My course task required doing this without using for loops and other stuff,so here is my bizarre solution lol.
color1 = int(input())
color2 = int(input())
color3 = int(input())
color1 = hex(color1).upper()
color2 = hex(color2).upper()
color3 = hex(color3).upper()
print('#'+ color1[2:].zfill(2)+color2[2:].zfill(2)+color3[2:].zfill(2))
| Converting an RGB color tuple to a hexidecimal string | I need to convert (0, 128, 64) to something like this "#008040". I'm not sure what to call the latter, making searching difficult.
| [
"Use the format operator %:\n>>> '#%02x%02x%02x' % (0, 128, 64)\n'#008040'\n\nNote that it won't check bounds...\n>>> '#%02x%02x%02x' % (0, -1, 9999)\n'#00-1270f'\n\n",
"def clamp(x): \n return max(0, min(x, 255))\n\n\"#{0:02x}{1:02x}{2:02x}\".format(clamp(r), clamp(g), clamp(b))\n\nThis uses the preferred method of string formatting, as described in PEP 3101. It also uses min() and max to ensure that 0 <= {r,g,b} <= 255.\nUpdate added the clamp function as suggested below.\nUpdate From the title of the question and the context given, it should be obvious that this expects 3 ints in [0,255] and will always return a color when passed 3 such ints. However, from the comments, this may not be obvious to everyone, so let it be explicitly stated: \n\nProvided three int values, this will return a valid hex triplet representing a color. If those values are between [0,255], then it will treat those as RGB values and return the color corresponding to those values.\n\n",
"I have created a full python program for it the following functions can convert rgb to hex and vice versa.\ndef rgb2hex(r,g,b):\n return \"#{:02x}{:02x}{:02x}\".format(r,g,b)\n\ndef hex2rgb(hexcode):\n return tuple(map(ord,hexcode[1:].decode('hex')))\n\nYou can see the full code and tutorial at the following link : RGB to Hex and Hex to RGB conversion using Python\n",
"This is an old question but for information, I developed a package with some utilities related to colors and colormaps and contains the rgb2hex function you were looking to convert triplet into hexa value (which can be found in many other packages, e.g. matplotlib). It's on pypi\npip install colormap\n\nand then\n>>> from colormap import rgb2hex\n>>> rgb2hex(0, 128, 64)\n'##008040'\n\nValidity of the inputs is checked (values must be between 0 and 255).\n",
"I'm truly surprised no one suggested this approach:\nFor Python 2 and 3:\n'#' + ''.join('{:02X}'.format(i) for i in colortuple)\n\nPython 3.6+:\n'#' + ''.join(f'{i:02X}' for i in colortuple)\n\nAs a function:\ndef hextriplet(colortuple):\n return '#' + ''.join(f'{i:02X}' for i in colortuple)\n\ncolor = (0, 128, 64)\nprint(hextriplet(color))\n\n#008040\n\n",
"triplet = (0, 128, 64)\nprint '#'+''.join(map(chr, triplet)).encode('hex')\n\nor\nfrom struct import pack\nprint '#'+pack(\"BBB\",*triplet).encode('hex')\n\npython3 is slightly different\nfrom base64 import b16encode\nprint(b'#'+b16encode(bytes(triplet)))\n\n",
"you can use lambda and f-strings(available in python 3.6+)\nrgb2hex = lambda r,g,b: f\"#{r:02x}{g:02x}{b:02x}\"\nhex2rgb = lambda hx: (int(hx[0:2],16),int(hx[2:4],16),int(hx[4:6],16))\n\nusage\nrgb2hex(r,g,b) #output = #hexcolor\n hex2rgb(\"#hex\") #output = (r,g,b) hexcolor must be in #hex format\n",
"In Python 3.6, you can use f-strings to make this cleaner:\nrgb = (0,128, 64)\nf'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}'\n\n\nOf course you can put that into a function, and as a bonus, values get rounded and converted to int: \ndef rgb2hex(r,g,b):\n return f'#{int(round(r)):02x}{int(round(g)):02x}{int(round(b)):02x}'\n\nrgb2hex(*rgb)\n\n",
"Here is a more complete function for handling situations in which you may have RGB values in the range [0,1] or the range [0,255].\ndef RGBtoHex(vals, rgbtype=1):\n \"\"\"Converts RGB values in a variety of formats to Hex values.\n\n @param vals An RGB/RGBA tuple\n @param rgbtype Valid valus are:\n 1 - Inputs are in the range 0 to 1\n 256 - Inputs are in the range 0 to 255\n\n @return A hex string in the form '#RRGGBB' or '#RRGGBBAA'\n\"\"\"\n\n if len(vals)!=3 and len(vals)!=4:\n raise Exception(\"RGB or RGBA inputs to RGBtoHex must have three or four elements!\")\n if rgbtype!=1 and rgbtype!=256:\n raise Exception(\"rgbtype must be 1 or 256!\")\n\n #Convert from 0-1 RGB/RGBA to 0-255 RGB/RGBA\n if rgbtype==1:\n vals = [255*x for x in vals]\n\n #Ensure values are rounded integers, convert to hex, and concatenate\n return '#' + ''.join(['{:02X}'.format(int(round(x))) for x in vals])\n\nprint(RGBtoHex((0.1,0.3, 1)))\nprint(RGBtoHex((0.8,0.5, 0)))\nprint(RGBtoHex(( 3, 20,147), rgbtype=256))\nprint(RGBtoHex(( 3, 20,147,43), rgbtype=256))\n\n",
"Note that this only works with python3.6 and above.\ndef rgb2hex(color):\n \"\"\"Converts a list or tuple of color to an RGB string\n\n Args:\n color (list|tuple): the list or tuple of integers (e.g. (127, 127, 127))\n\n Returns:\n str: the rgb string\n \"\"\"\n return f\"#{''.join(f'{hex(c)[2:].upper():0>2}' for c in color)}\"\n\nThe above is the equivalent of:\ndef rgb2hex(color):\n string = '#'\n for value in color:\n hex_string = hex(value) # e.g. 0x7f\n reduced_hex_string = hex_string[2:] # e.g. 7f\n capitalized_hex_string = reduced_hex_string.upper() # e.g. 7F\n string += capitalized_hex_string # e.g. #7F7F7F\n return string\n\n",
"You can also use bit wise operators which is pretty efficient, even though I doubt you'd be worried about efficiency with something like this. It's also relatively clean. Note it doesn't clamp or check bounds. This has been supported since at least Python 2.7.17.\nhex(r << 16 | g << 8 | b)\n\nAnd to change it so it starts with a # you can do:\n\"#\" + hex(243 << 16 | 103 << 8 | 67)[2:]\n\n",
"def RGB(red,green,blue): return '#%02x%02x%02x' % (red,green,blue)\n\nbackground = RGB(0, 128, 64)\n\nI know one-liners in Python aren't necessarily looked upon kindly. But there are times where I can't resist taking advantage of what the Python parser does allow. It's the same answer as Dietrich Epp's solution (the best), but wrapped up in a single line function. So, thank you Dietrich!\nI'm using it now with tkinter :-)\n",
"There is a package called webcolors. https://github.com/ubernostrum/webcolors\nIt has a method webcolors.rgb_to_hex\n>>> import webcolors\n>>> webcolors.rgb_to_hex((12,232,23))\n'#0ce817'\n\n",
"''.join('%02x'%i for i in input)\n\ncan be used for hex conversion from int number\n",
"If typing the formatting string three times seems a bit verbose...\nThe combination of bit shifts and an f-string will do the job nicely:\n# Example setup.\n>>> r, g, b = 0, 0, 195\n\n# Create the hex string.\n>>> f'#{r << 16 | g << 8 | b:06x}'\n'#0000c3'\n\nThis also illustrates a method by which 'leading' zero bits are not dropped, if either the red or green channels are zero.\n",
"Use this line\n'#%02X%02X%02X' % (r,g,b)\n",
"#My course task required doing this without using for loops and other stuff,so here is my bizarre solution lol.\ncolor1 = int(input())\ncolor2 = int(input())\ncolor3 = int(input())\n\ncolor1 = hex(color1).upper()\ncolor2 = hex(color2).upper()\ncolor3 = hex(color3).upper()\n\n\nprint('#'+ color1[2:].zfill(2)+color2[2:].zfill(2)+color3[2:].zfill(2))\n\n"
] | [
257,
67,
24,
23,
12,
10,
6,
5,
4,
4,
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"colors",
"hex",
"python",
"rgb"
] | stackoverflow_0003380726_colors_hex_python_rgb.txt |
Q:
Asp,net Core Controller Action body timeout
So I am receiving a Shopify webhook request to my asp.net application. I keep getting the following error.
'((Microsoft.AspNetCore.Http.DefaultHttpRequest)this.Request).Form' threw an exception of type 'System.InvalidOperationException'
If I put Request.Body it says item timed out. I am not sure how to read the stream that is getting sent to my action.
I can post any extra details you request I am not sure what to post here.
A:
This we because I needed to read the incoming stream.
| Asp,net Core Controller Action body timeout | So I am receiving a Shopify webhook request to my asp.net application. I keep getting the following error.
'((Microsoft.AspNetCore.Http.DefaultHttpRequest)this.Request).Form' threw an exception of type 'System.InvalidOperationException'
If I put Request.Body it says item timed out. I am not sure how to read the stream that is getting sent to my action.
I can post any extra details you request I am not sure what to post here.
| [
"This we because I needed to read the incoming stream.\n"
] | [
0
] | [] | [] | [
"asp.net",
"shopify_app"
] | stackoverflow_0074158949_asp.net_shopify_app.txt |
Q:
AWS VPN client on Windows 10: can't add VPN configuration file because of invalid path to the sertificate
I want to add a new profile in AWS VPN client having three files:
vpn.ovpn
vpn.companyName.com.crt
vpn.companyName.com.key
When I try to add vpn.ovpn I'm getting the error:
"File path: ~/ssh.vpn.companyName.com.crt is in invalid format. It may be a path to a remote server, which is not allowed for security reasons. Only absolute paths are accepted"
A:
For me the issue was in the file vpn.ovpn the path for both files
vpn.companyName.com.crt
vpn.companyName.com.key
were incorect.
Solution:
open vpn.ovpn file and scroll to bottom and edit your path to correct location
| AWS VPN client on Windows 10: can't add VPN configuration file because of invalid path to the sertificate | I want to add a new profile in AWS VPN client having three files:
vpn.ovpn
vpn.companyName.com.crt
vpn.companyName.com.key
When I try to add vpn.ovpn I'm getting the error:
"File path: ~/ssh.vpn.companyName.com.crt is in invalid format. It may be a path to a remote server, which is not allowed for security reasons. Only absolute paths are accepted"
| [
"For me the issue was in the file vpn.ovpn the path for both files\n\nvpn.companyName.com.crt\nvpn.companyName.com.key\n\nwere incorect.\nSolution:\nopen vpn.ovpn file and scroll to bottom and edit your path to correct location\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"client",
"vpn"
] | stackoverflow_0072614756_amazon_web_services_client_vpn.txt |
Q:
Atomic data in asynchroneous context
Is there a way to use atomic types in an asynchroneous context instead of an asynchronous Mutex or RwLock ?
Can standard atomics be used as is in an asynchronous context?
Or, for example, is there an asynchroneous equivalent of std::sync::atomic::AtomicUsize with load / store methods, which could replace something like tokio::sync::RwLock<usize> with read().await / write().await methods?
A:
Yes, using Atomics in an async context is no problem.
Most of them are lock-free (=can't even block).
Even if you would block, it is still recommended to use normal, blocking synchronization primitives over async ones, unless you hold that lock during an await.
For more info I quote the respective chapter of the tokio tutorial:
On using std::sync::Mutex
Note, std::sync::Mutex and not tokio::sync::Mutex is used to guard the HashMap. A common error is to unconditionally use tokio::sync::Mutex from within async code. An async mutex is a mutex that is locked across calls to .await.
A synchronous mutex will block the current thread when waiting to acquire the lock. This, in turn, will block other tasks from processing. However, switching to tokio::sync::Mutex usually does not help as the asynchronous mutex uses a synchronous mutex internally.
As a rule of thumb, using a synchronous mutex from within asynchronous code is fine as long as contention remains low and the lock is not held across calls to .await. Additionally, consider using parking_lot::Mutex as a faster alternative to std::sync::Mutex.
| Atomic data in asynchroneous context | Is there a way to use atomic types in an asynchroneous context instead of an asynchronous Mutex or RwLock ?
Can standard atomics be used as is in an asynchronous context?
Or, for example, is there an asynchroneous equivalent of std::sync::atomic::AtomicUsize with load / store methods, which could replace something like tokio::sync::RwLock<usize> with read().await / write().await methods?
| [
"Yes, using Atomics in an async context is no problem.\nMost of them are lock-free (=can't even block).\nEven if you would block, it is still recommended to use normal, blocking synchronization primitives over async ones, unless you hold that lock during an await.\nFor more info I quote the respective chapter of the tokio tutorial:\n\nOn using std::sync::Mutex\nNote, std::sync::Mutex and not tokio::sync::Mutex is used to guard the HashMap. A common error is to unconditionally use tokio::sync::Mutex from within async code. An async mutex is a mutex that is locked across calls to .await.\nA synchronous mutex will block the current thread when waiting to acquire the lock. This, in turn, will block other tasks from processing. However, switching to tokio::sync::Mutex usually does not help as the asynchronous mutex uses a synchronous mutex internally.\nAs a rule of thumb, using a synchronous mutex from within asynchronous code is fine as long as contention remains low and the lock is not held across calls to .await. Additionally, consider using parking_lot::Mutex as a faster alternative to std::sync::Mutex.\n\n"
] | [
1
] | [] | [] | [
"asynchronous",
"atomic",
"mutex",
"rust",
"rwlock"
] | stackoverflow_0074658169_asynchronous_atomic_mutex_rust_rwlock.txt |
Q:
How to get Text from certain Area in a PDF-Document in Android Studio?
I want to get data from a certain Position in a PDF-Document.
I tried to get Text from a certain Area in a PDF with the pdfbox library.
But the addRegion method expects a Rectangle2D. Android only has the Rect class which is not a Rectangle2D.
Because of that I get an error on:
stripper.addRegion("class1", rect);
What can I do to overcome this?
Is there any other way to extract data
from a certain Position in a PDF-Document with the Android SDK? Any other Library that works for this? Because I don't think there is a Library for Android Studio for Rectangle2D.
PDDocument document = PDDocument.load(new File("/Users/osman/Desktop/test.pdf"));
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
Rect rect = new Rect(0, 0, 0, 0);
stripper.addRegion("class1", rect);
stripper.extractRegions(document.getPage(1));
System.out.println(stripper.getTextForRegion("class1"));
Error Message
A:
I found a Solution to my own Question:
There is a PDFBox Library for Android on GitHub. https://github.com/TomRoush/PdfBox-Android
Add this to Android.Manifest dependencies
dependencies {
implementation 'com.tom-roush:pdfbox-android:2.0.25.0'
}
The Code to extract Data is:
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "Test.pdf");
PDDocument document = PDDocument.load(new File(file.getAbsolutePath()));
PDFBoxResourceLoader.init(getApplicationContext());
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
RectF rect = new RectF(100, 100, 300, 300);
stripper.addRegion("class1", rect);
stripper.extractRegions(document.getPage(0));
System.out.println(stripper.getTextForRegion("class1"));
| How to get Text from certain Area in a PDF-Document in Android Studio? | I want to get data from a certain Position in a PDF-Document.
I tried to get Text from a certain Area in a PDF with the pdfbox library.
But the addRegion method expects a Rectangle2D. Android only has the Rect class which is not a Rectangle2D.
Because of that I get an error on:
stripper.addRegion("class1", rect);
What can I do to overcome this?
Is there any other way to extract data
from a certain Position in a PDF-Document with the Android SDK? Any other Library that works for this? Because I don't think there is a Library for Android Studio for Rectangle2D.
PDDocument document = PDDocument.load(new File("/Users/osman/Desktop/test.pdf"));
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
Rect rect = new Rect(0, 0, 0, 0);
stripper.addRegion("class1", rect);
stripper.extractRegions(document.getPage(1));
System.out.println(stripper.getTextForRegion("class1"));
Error Message
| [
"I found a Solution to my own Question:\nThere is a PDFBox Library for Android on GitHub. https://github.com/TomRoush/PdfBox-Android\nAdd this to Android.Manifest dependencies\ndependencies {\n implementation 'com.tom-roush:pdfbox-android:2.0.25.0'\n}\n\nThe Code to extract Data is:\n File path = Environment.getExternalStoragePublicDirectory(\n Environment.DIRECTORY_DOWNLOADS);\n File file = new File(path, \"Test.pdf\");\n PDDocument document = PDDocument.load(new File(file.getAbsolutePath()));\n PDFBoxResourceLoader.init(getApplicationContext());\n PDFTextStripperByArea stripper = new PDFTextStripperByArea();\n stripper.setSortByPosition(true);\n RectF rect = new RectF(100, 100, 300, 300);\n stripper.addRegion(\"class1\", rect);\n stripper.extractRegions(document.getPage(0));\n System.out.println(stripper.getTextForRegion(\"class1\"));\n\n"
] | [
0
] | [] | [] | [
"android",
"android_studio",
"java",
"pdf_reader",
"pdfbox"
] | stackoverflow_0074665040_android_android_studio_java_pdf_reader_pdfbox.txt |
Q:
Getting ORA-01858 in Program but working in SQL Developer
We have a program that ERRORS out with ORA-01858: a non-numeric character was found where a numeric was expected
DECLARE
l_prev_purchase_batch_id xx_rep_status.reporting_status_id%type;
l_tax_calendar_period xx_rep_status.tax_calendar_period%type := 'JAN-06';
BEGIN
SELECT status.reporting_status_id
INTO l_prev_purchase_batch_id
FROM xx_rep_status status
WHERE status.vat_reporting_entity_id = 300100097478219
AND TO_CHAR(TO_DATE(status.tax_calendar_period, 'MM/YY'), 'MM/YY') = TO_CHAR(ADD_MONTHS(TO_DATE(l_tax_calendar_period, 'MM/YY'), -1), 'MM/YY')
AND status.source NOT IN ('GL', 'AR', 'AP')
AND status.source = 'P2P';
END;
But when we run it directly from SQL Developer on the same database, it works fine.
I checked the NLS_DATE_FORMAT and NLS_DATE_LANGUAGE from the database session and the Program session, and they match:
select VALUE, 'SESSION_NLS_DATE_FORMAT' parameter
from nls_session_parameters
where parameter = 'NLS_DATE_FORMAT'
UNION ALL
select VALUE, 'DB_NLS_DATE_FORMAT'
from nls_database_parameters
where parameter = 'NLS_DATE_FORMAT'
UNION ALL
select VALUE, 'SESSION_NLS_DATE_LANGUAGE'
from nls_session_parameters
where parameter = 'NLS_DATE_LANGUAGE'
UNION ALL
select VALUE, 'DB_NLS_DATE_LANGUAGE'
from nls_database_parameters
where parameter = 'NLS_DATE_LANGUAGE';
SQL Developer
VALUE PARAMETER
------------- -------------------------
DD-MON-RR SESSION_NLS_DATE_FORMAT
DD-MON-RR DB_NLS_DATE_FORMAT
AMERICAN SESSION_NLS_DATE_LANGUAGE
AMERICAN DB_NLS_DATE_LANGUAGE
Application
VALUE PARAMETER
--------------------------- -------------------------
YYYY-MM-DD SESSION_NLS_DATE_FORMAT
DD-MON-RR DB_NLS_DATE_FORMAT
NUMERIC DATE LANGUAGE SESSION_NLS_DATE_LANGUAGE
AMERICAN DB_NLS_DATE_LANGUAGE
I have tried passing the value of l_tax_calendar_period to another variable but it's still having issues.
The value of l_tax_calendar_period changes such as '01-01' OR 'JAN-01', depending on the setup.
I have been stuck on this for quite some time, any ideas?
Thank you.
A:
You don't appear to be doing any implicit conversion or relying on the session NLS_DATE_FORMAT setting. But when you use month abbreviations you are relying on NLS_DATE_LANGUAGE.
If you have value like JAN-01 then Oracle's 'helpful' default behaviour of loose interpretation of the format models means that it will be converted correctly to 2006-01-01, but only if the session recognised the JAN as a valid month abbreviation (or name) in its language.
select to_date('Jan-06', 'MM/YY') from dual
TO_DATE('JAN-06','MM/YY')
01-JAN-06
With a session in a different language that might not work, and can give the error you are seeing:
alter session set nls_date_language = French
select to_date('Jan-06', 'MM/YY') from dual
ORA-01858: a non-numeric character was found where a numeric was expected
or with the 'numeric' date language your application is actually using:
alter session set nls_date_language = 'numeric date language'
select to_date('Jan-06', 'MM/YY') from dual
ORA-01858: a non-numeric character was found where a numeric was expected
Assuming all the data in your table is in a single language - which may not be the case if it's as free-form as it looks - then you can override the session setting in the to_date() call:
select to_date('Jan-06', 'MM/YY', 'nls_date_language=English') from dual
TO_DATE('JAN-06','MM/YY','NLS_DATE_LANGUAGE=ENGLISH')
01-01-06
fiddle
If the values might be in multiple languages then your program would have to identify them and pass the correct language into your DB code; or convert to a date itself.
It would probably still be preferable to only use month numbers, and constrain the column to only allow valid values; or only use English names, also constrained; or store a nominal date instead of any MM/YY pattern. I suspect that's out of your control though...
| Getting ORA-01858 in Program but working in SQL Developer | We have a program that ERRORS out with ORA-01858: a non-numeric character was found where a numeric was expected
DECLARE
l_prev_purchase_batch_id xx_rep_status.reporting_status_id%type;
l_tax_calendar_period xx_rep_status.tax_calendar_period%type := 'JAN-06';
BEGIN
SELECT status.reporting_status_id
INTO l_prev_purchase_batch_id
FROM xx_rep_status status
WHERE status.vat_reporting_entity_id = 300100097478219
AND TO_CHAR(TO_DATE(status.tax_calendar_period, 'MM/YY'), 'MM/YY') = TO_CHAR(ADD_MONTHS(TO_DATE(l_tax_calendar_period, 'MM/YY'), -1), 'MM/YY')
AND status.source NOT IN ('GL', 'AR', 'AP')
AND status.source = 'P2P';
END;
But when we run it directly from SQL Developer on the same database, it works fine.
I checked the NLS_DATE_FORMAT and NLS_DATE_LANGUAGE from the database session and the Program session, and they match:
select VALUE, 'SESSION_NLS_DATE_FORMAT' parameter
from nls_session_parameters
where parameter = 'NLS_DATE_FORMAT'
UNION ALL
select VALUE, 'DB_NLS_DATE_FORMAT'
from nls_database_parameters
where parameter = 'NLS_DATE_FORMAT'
UNION ALL
select VALUE, 'SESSION_NLS_DATE_LANGUAGE'
from nls_session_parameters
where parameter = 'NLS_DATE_LANGUAGE'
UNION ALL
select VALUE, 'DB_NLS_DATE_LANGUAGE'
from nls_database_parameters
where parameter = 'NLS_DATE_LANGUAGE';
SQL Developer
VALUE PARAMETER
------------- -------------------------
DD-MON-RR SESSION_NLS_DATE_FORMAT
DD-MON-RR DB_NLS_DATE_FORMAT
AMERICAN SESSION_NLS_DATE_LANGUAGE
AMERICAN DB_NLS_DATE_LANGUAGE
Application
VALUE PARAMETER
--------------------------- -------------------------
YYYY-MM-DD SESSION_NLS_DATE_FORMAT
DD-MON-RR DB_NLS_DATE_FORMAT
NUMERIC DATE LANGUAGE SESSION_NLS_DATE_LANGUAGE
AMERICAN DB_NLS_DATE_LANGUAGE
I have tried passing the value of l_tax_calendar_period to another variable but it's still having issues.
The value of l_tax_calendar_period changes such as '01-01' OR 'JAN-01', depending on the setup.
I have been stuck on this for quite some time, any ideas?
Thank you.
| [
"You don't appear to be doing any implicit conversion or relying on the session NLS_DATE_FORMAT setting. But when you use month abbreviations you are relying on NLS_DATE_LANGUAGE.\nIf you have value like JAN-01 then Oracle's 'helpful' default behaviour of loose interpretation of the format models means that it will be converted correctly to 2006-01-01, but only if the session recognised the JAN as a valid month abbreviation (or name) in its language.\nselect to_date('Jan-06', 'MM/YY') from dual\n\n\n\n\n\nTO_DATE('JAN-06','MM/YY')\n\n\n\n\n01-JAN-06\n\n\n\n\nWith a session in a different language that might not work, and can give the error you are seeing:\nalter session set nls_date_language = French\n\nselect to_date('Jan-06', 'MM/YY') from dual\n\nORA-01858: a non-numeric character was found where a numeric was expected\n\nor with the 'numeric' date language your application is actually using:\nalter session set nls_date_language = 'numeric date language'\n\nselect to_date('Jan-06', 'MM/YY') from dual\n\nORA-01858: a non-numeric character was found where a numeric was expected\n\nAssuming all the data in your table is in a single language - which may not be the case if it's as free-form as it looks - then you can override the session setting in the to_date() call:\nselect to_date('Jan-06', 'MM/YY', 'nls_date_language=English') from dual\n\n\n\n\n\nTO_DATE('JAN-06','MM/YY','NLS_DATE_LANGUAGE=ENGLISH')\n\n\n\n\n01-01-06\n\n\n\n\nfiddle\nIf the values might be in multiple languages then your program would have to identify them and pass the correct language into your DB code; or convert to a date itself.\nIt would probably still be preferable to only use month numbers, and constrain the column to only allow valid values; or only use English names, also constrained; or store a nominal date instead of any MM/YY pattern. I suspect that's out of your control though...\n"
] | [
3
] | [] | [] | [
"ora_01858",
"oracle",
"oracle_sqldeveloper",
"sql"
] | stackoverflow_0074675140_ora_01858_oracle_oracle_sqldeveloper_sql.txt |
Q:
length of the longest substring of given string so that rearrangement of its characters form PALINDROME
Only lower case string as input.
Only words as input
Invalid if characters like "@","#"... are present
Find the length of the longest substring of given string so that the characters in it can be rearranged to form a palindrome.
Output the length
I am unable to put it in terms of programming in python.
please help.
My line of thinking was to keep an initial counter as 1(as even a word with completely different letters will have 1 by default)
then add 2 for every 1 match in letters
Sample input: "letter"
Sample output: 5 #(1(by default + 2(for 2"t"s) + 2(for 2"e"s))
A:
You can use this code to figure out the length of the longest substring which can be rearranged to form a palindrome:
def longestSubstring(s: str):
# To keep track of the last
# index of each xor
n = len(s)
index = dict()
# Initialize answer with 0
answer = 0
mask = 0
index[mask] = -1
# Now iterate through each character
# of the string
for i in range(n):
# Convert the character from
# [a, z] to [0, 25]
temp = ord(s[i]) - 97
# Turn the temp-th bit on if
# character occurs odd number
# of times and turn off the temp-th
# bit off if the character occurs
# even number of times
mask ^= (1 << temp)
# If a mask is present in the index
# Therefore a palindrome is
# found from index[mask] to i
if mask in index.keys():
answer = max(answer,
i - index[mask])
# If x is not found then add its
# position in the index dict.
else:
index[mask] = i
# Check for the palindrome of
# odd length
for j in range(26):
# We cancel the occurrence
# of a character if it occurs
# odd number times
mask2 = mask ^ (1 << j)
if mask2 in index.keys():
answer = max(answer,
i - index[mask2])
return answer
This algorithm is basically O(N*26). XOR basically checks if the amount of a certain character is even or odd. For every character in your string there is a certain XOR sequence of every character up to that point which tells you which characters have appeared an odd number of time and which characters have appeared an even number of times. If the same sequence has already been encountered in the past then you know that you have found a palindrome, because you have become back to where you started in the XOR sequence aka there are an even number of every character which appears between this point and the start point. If there is an even number of every character which appear between two points in the string, then you can form a palindrome out of them. The odd length check is just a special case to check for palindromes which are of odd length. It works by just pretending sequentially if a character appears an odd number of times, that it just assumes it to occur an even number of times to handle the special case of the character in the middle of an odd length palindrome.
Edit: here is the link to the original code and explanation.
| length of the longest substring of given string so that rearrangement of its characters form PALINDROME |
Only lower case string as input.
Only words as input
Invalid if characters like "@","#"... are present
Find the length of the longest substring of given string so that the characters in it can be rearranged to form a palindrome.
Output the length
I am unable to put it in terms of programming in python.
please help.
My line of thinking was to keep an initial counter as 1(as even a word with completely different letters will have 1 by default)
then add 2 for every 1 match in letters
Sample input: "letter"
Sample output: 5 #(1(by default + 2(for 2"t"s) + 2(for 2"e"s))
| [
"You can use this code to figure out the length of the longest substring which can be rearranged to form a palindrome:\ndef longestSubstring(s: str):\n \n # To keep track of the last\n # index of each xor\n n = len(s)\n index = dict()\n \n # Initialize answer with 0\n answer = 0\n \n mask = 0\n index[mask] = -1\n \n # Now iterate through each character\n # of the string\n for i in range(n):\n \n # Convert the character from\n # [a, z] to [0, 25]\n temp = ord(s[i]) - 97\n \n # Turn the temp-th bit on if\n # character occurs odd number\n # of times and turn off the temp-th\n # bit off if the character occurs\n # even number of times\n mask ^= (1 << temp)\n \n # If a mask is present in the index\n # Therefore a palindrome is\n # found from index[mask] to i\n if mask in index.keys():\n answer = max(answer,\n i - index[mask])\n \n # If x is not found then add its\n # position in the index dict.\n else:\n index[mask] = i\n \n # Check for the palindrome of\n # odd length\n for j in range(26):\n \n # We cancel the occurrence\n # of a character if it occurs\n # odd number times\n mask2 = mask ^ (1 << j)\n if mask2 in index.keys():\n \n answer = max(answer,\n i - index[mask2])\n \n return answer\n\nThis algorithm is basically O(N*26). XOR basically checks if the amount of a certain character is even or odd. For every character in your string there is a certain XOR sequence of every character up to that point which tells you which characters have appeared an odd number of time and which characters have appeared an even number of times. If the same sequence has already been encountered in the past then you know that you have found a palindrome, because you have become back to where you started in the XOR sequence aka there are an even number of every character which appears between this point and the start point. If there is an even number of every character which appear between two points in the string, then you can form a palindrome out of them. The odd length check is just a special case to check for palindromes which are of odd length. It works by just pretending sequentially if a character appears an odd number of times, that it just assumes it to occur an even number of times to handle the special case of the character in the middle of an odd length palindrome.\nEdit: here is the link to the original code and explanation.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074674638_python.txt |
Q:
Hot Reload is not working in my React App
I have created this app with npx create-react-app. After this i have deleted all the files except index.js in src folder. Then Hot reload is not working. I have go to chrome and manually refreshing the page for see changes.
This is my index.js file.
import React from 'react';
import ReactDom from 'react-dom';
function Greeting() {
return (
<div>
<h1>hello World</h1>
<ul>
<li>Click Here</li>
</ul>
</div>
);
}
ReactDom.render(<Greeting />, document.getElementById('root'));
Package.json file
{
"name": "tutorial",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
A:
There was an issue - https://github.com/facebook/create-react-app/issues/9904
A workaround is putting below code in index.js to enable reloading
if (module.hot) {
module.hot.accept();
}
you must restart your server after making this change
A:
To solve the problem in hot reloading/fast_refresh I simply add CHOKIDAR_USEPOLLING=true in package.json:
"scripts": {
"start": "CHOKIDAR_USEPOLLING=true react-scripts start", //add this line
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
A:
This could be due to your filesystem, file extensions or the Create-React-App default webpack/project configuration. You don't necessarily have to change all of this because hot-reloading is supposed to work out of the box, and more so if the project has just started.
For example, I once had an issue with a Typescript installation(^17.0.1) where some files with extension .ts will not trigger hot reloading. I had to change to .tsx and add a React import. The same could happen with .js and .jsx files.
In case of problems with your filesystem (Unix, Mac) you can try the React config (FAST_REFRESH=false) here... or changing folder names, but I haven't bumped much into this.
A:
While the above solutions are also beneficial, One other way that worked for most people is creating a .env folder in your Project.
And use the following Property there.
FAST_REFRESH = false
After you add the above, you got to restart your server
A:
There were a problem with react-scripts version 4.0.1 in package.json file.
I have replaced it with 'react-scripts' : '3.4.4' and Now its working.
for more info: https://github.com/facebook/create-react-app/issues/9984
A:
Change your file index.js to index.jsx. It worked for me.
A:
If your page is not loading automatically then you have to do these steps:
add .env file
add SKIP_PREFLIGHT_CHECK=true in .env file
A:
There is a hot reloading issue for some browsers, with react version 17.
Below is the simplest way to fix this:
Go to package.json and replace react, react-dom and react-scripts
dependencies with below:
"react": "^16.13.1"
"react-dom": "^16.13.1"
"react-scripts": "3.4.3"
Delete the node_modules folder.
Run npm install (It will install all the dependencies again)
Start your CRA project with npm start
This will fix the hot reloading issue.
A:
Just incase you've tried everything with no solution, make sure you're working on your computer's drive and not saving your project on an external drive. This was my issue, I simply moved the project to my computer's drive and it worked perfectly. Happy coding guys!
A:
I tried every solution suggested in these comments and nothing worked for me. I was following a tutorial that used [email protected]. Nothing worked at all including both .env suggestions, the react-scripts suggestion, or the CHOKIDAR_USEPOLLING suggestion. I even switched between npm and yarn to see if one or the other was causing the issue.
The only thing that worked for me was using yarn add react-router-dom for the latest version without any specific version attached, and instead of a Switch using the new Routes component listed in the version 6 quick start. Now it works great with zero issue.
A:
I tried all suggestions above but not working.
Finally I've found that the reason is because of some eslint rules are violated and make the application Failed to Compile.
After I fix the rules in eslintrc.json it works
A:
Nothing of the above helped me, as soon as i was running dev server on wsl 22.02. But when i started it with git bash, it worked.
A:
I had a hot reload issue when chrome downloaded the update but didn't install it.
After installing the update, all problems disappeared
A:
I've faced the same problem using wsl2 with Ubuntu-22.04 and I solve it by moving my project from my mounted windows drive (/mnt/c) to /home directory into my wsl distro. Once done, it work perfectly and much faster !
To do it with your windows file explorer, you can found your distro files under \\wsl$ path. So basically for me it was under \\wsl$\Ubuntu-22.04\home.
I've found this solution through this thread https://github.com/facebook/create-react-app/issues/10253#issuecomment-940654613
| Hot Reload is not working in my React App | I have created this app with npx create-react-app. After this i have deleted all the files except index.js in src folder. Then Hot reload is not working. I have go to chrome and manually refreshing the page for see changes.
This is my index.js file.
import React from 'react';
import ReactDom from 'react-dom';
function Greeting() {
return (
<div>
<h1>hello World</h1>
<ul>
<li>Click Here</li>
</ul>
</div>
);
}
ReactDom.render(<Greeting />, document.getElementById('root'));
Package.json file
{
"name": "tutorial",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
| [
"There was an issue - https://github.com/facebook/create-react-app/issues/9904\n \nA workaround is putting below code in index.js to enable reloading\nif (module.hot) {\n module.hot.accept();\n}\n\nyou must restart your server after making this change\n",
"To solve the problem in hot reloading/fast_refresh I simply add CHOKIDAR_USEPOLLING=true in package.json:\n\"scripts\": {\n \"start\": \"CHOKIDAR_USEPOLLING=true react-scripts start\", //add this line\n \"build\": \"react-scripts build\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n}\n\n",
"This could be due to your filesystem, file extensions or the Create-React-App default webpack/project configuration. You don't necessarily have to change all of this because hot-reloading is supposed to work out of the box, and more so if the project has just started.\nFor example, I once had an issue with a Typescript installation(^17.0.1) where some files with extension .ts will not trigger hot reloading. I had to change to .tsx and add a React import. The same could happen with .js and .jsx files.\nIn case of problems with your filesystem (Unix, Mac) you can try the React config (FAST_REFRESH=false) here... or changing folder names, but I haven't bumped much into this.\n",
"While the above solutions are also beneficial, One other way that worked for most people is creating a .env folder in your Project.\nAnd use the following Property there.\nFAST_REFRESH = false\n\n\nAfter you add the above, you got to restart your server\n",
"There were a problem with react-scripts version 4.0.1 in package.json file.\nI have replaced it with 'react-scripts' : '3.4.4' and Now its working.\nfor more info: https://github.com/facebook/create-react-app/issues/9984\n",
"Change your file index.js to index.jsx. It worked for me.\n",
"If your page is not loading automatically then you have to do these steps:\n\nadd .env file\nadd SKIP_PREFLIGHT_CHECK=true in .env file\n\n",
"There is a hot reloading issue for some browsers, with react version 17.\nBelow is the simplest way to fix this:\n\nGo to package.json and replace react, react-dom and react-scripts\ndependencies with below:\n\"react\": \"^16.13.1\" \n\"react-dom\": \"^16.13.1\" \n\"react-scripts\": \"3.4.3\"\n\n\nDelete the node_modules folder.\n\nRun npm install (It will install all the dependencies again)\n\nStart your CRA project with npm start\n\n\nThis will fix the hot reloading issue.\n",
"Just incase you've tried everything with no solution, make sure you're working on your computer's drive and not saving your project on an external drive. This was my issue, I simply moved the project to my computer's drive and it worked perfectly. Happy coding guys!\n",
"I tried every solution suggested in these comments and nothing worked for me. I was following a tutorial that used [email protected]. Nothing worked at all including both .env suggestions, the react-scripts suggestion, or the CHOKIDAR_USEPOLLING suggestion. I even switched between npm and yarn to see if one or the other was causing the issue.\nThe only thing that worked for me was using yarn add react-router-dom for the latest version without any specific version attached, and instead of a Switch using the new Routes component listed in the version 6 quick start. Now it works great with zero issue.\n",
"I tried all suggestions above but not working.\nFinally I've found that the reason is because of some eslint rules are violated and make the application Failed to Compile.\nAfter I fix the rules in eslintrc.json it works\n",
"Nothing of the above helped me, as soon as i was running dev server on wsl 22.02. But when i started it with git bash, it worked.\n",
"I had a hot reload issue when chrome downloaded the update but didn't install it.\nAfter installing the update, all problems disappeared\n",
"I've faced the same problem using wsl2 with Ubuntu-22.04 and I solve it by moving my project from my mounted windows drive (/mnt/c) to /home directory into my wsl distro. Once done, it work perfectly and much faster !\nTo do it with your windows file explorer, you can found your distro files under \\\\wsl$ path. So basically for me it was under \\\\wsl$\\Ubuntu-22.04\\home.\nI've found this solution through this thread https://github.com/facebook/create-react-app/issues/10253#issuecomment-940654613\n"
] | [
12,
12,
7,
6,
4,
2,
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"javascript",
"jsx",
"reactjs",
"webpack"
] | stackoverflow_0065445600_javascript_jsx_reactjs_webpack.txt |
Q:
How to use Android Java codes in Unity?
My project in Unity has a cell entry system array from the link, how can I get it? I want to get +1 when translated forward, I want to get -1 when translated backwards. How can I do that?
https://developer.android.com/training/wearables/user-input/rotary-input
My project in Unity has a cell entry system array from the link, how can I get it? I want to get +1 when translated forward, I want to get -1 when translated backwards. How can I do that? https://developer.android.com/training/wearables/user-input/rotary-input
A:
I'm not sure what your "cell entry system array from the link" involves, but to get the value of a specific cell in an array in Unity, you can use the GetValue() method of the Array class. This method takes the index of the cell as a parameter and returns the cell's value at that index.
For example, if you have an array of integers called myArray and you want to get the value of the cell at index 3, you can use the following code:
int value = (int)myArray.GetValue(3);
To get the direction of translation, you can use the ev.getAxisValue() method of the MotionEvent object that is passed to the onGenericMotion() method. This method takes the axis that you want to get the value of as a parameter and returns the value of that axis for the current motion event.
For example, if you want to get the value of the AXIS_SCROLL axis for the current motion event, you can use the following code:
float value = ev.getAxisValue(MotionEvent.AXIS_SCROLL);
You can then use this value to determine the translation direction and add or subtract 1 from the cell value accordingly:
myView.setOnGenericMotionListener(new View.OnGenericMotionListener() {
@Override
public boolean onGenericMotion(View v, MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_SCROLL &&
ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)
) {
// Get the current value of the cell at index 3
int value = (int)myArray.GetValue(3);
// Get the value of the AXIS_SCROLL axis for the current motion event
float axisValue = ev.getAxisValue(MotionEvent.AXIS_SCROLL);
// Add or subtract 1 from the cell value based on the direction of translation
if (axisValue > 0) {
value++;
} else if (axisValue < 0) {
value--;
}
// Set the new value of the cell at index 3
myArray.SetValue(value, 3);
return true;
}
return false;
}
});
| How to use Android Java codes in Unity? | My project in Unity has a cell entry system array from the link, how can I get it? I want to get +1 when translated forward, I want to get -1 when translated backwards. How can I do that?
https://developer.android.com/training/wearables/user-input/rotary-input
My project in Unity has a cell entry system array from the link, how can I get it? I want to get +1 when translated forward, I want to get -1 when translated backwards. How can I do that? https://developer.android.com/training/wearables/user-input/rotary-input
| [
"I'm not sure what your \"cell entry system array from the link\" involves, but to get the value of a specific cell in an array in Unity, you can use the GetValue() method of the Array class. This method takes the index of the cell as a parameter and returns the cell's value at that index.\nFor example, if you have an array of integers called myArray and you want to get the value of the cell at index 3, you can use the following code:\nint value = (int)myArray.GetValue(3);\n\nTo get the direction of translation, you can use the ev.getAxisValue() method of the MotionEvent object that is passed to the onGenericMotion() method. This method takes the axis that you want to get the value of as a parameter and returns the value of that axis for the current motion event.\nFor example, if you want to get the value of the AXIS_SCROLL axis for the current motion event, you can use the following code:\nfloat value = ev.getAxisValue(MotionEvent.AXIS_SCROLL);\n\nYou can then use this value to determine the translation direction and add or subtract 1 from the cell value accordingly:\nmyView.setOnGenericMotionListener(new View.OnGenericMotionListener() {\n @Override\n public boolean onGenericMotion(View v, MotionEvent ev) {\n if (ev.getAction() == MotionEvent.ACTION_SCROLL &&\n ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER)\n ) {\n // Get the current value of the cell at index 3\n int value = (int)myArray.GetValue(3);\n\n // Get the value of the AXIS_SCROLL axis for the current motion event\n float axisValue = ev.getAxisValue(MotionEvent.AXIS_SCROLL);\n\n // Add or subtract 1 from the cell value based on the direction of translation\n if (axisValue > 0) {\n value++;\n } else if (axisValue < 0) {\n value--;\n }\n\n // Set the new value of the cell at index 3\n myArray.SetValue(value, 3);\n\n return true;\n }\n return false;\n }\n});\n\n"
] | [
0
] | [] | [] | [
"android",
"java",
"unity3d"
] | stackoverflow_0074669307_android_java_unity3d.txt |
Q:
how to make a mavy text animation using javascript
I want to make a wavy text animation why when the script I made the animation doesn't run. I use mark aiming to mark 1 sentence, that's why I don't use span.
// Wrap every letter in a span
var textWrapper2 = document.querySelector(".ml7 .letters2");
textWrapper2.innerHTML = textWrapper2.textContent.replace(/\S/g, "<mark class='letters2'>$&</mark>");
anime
.timeline({
loop: true
})
.add({
targets: ".ml7 .letters2",
translateY: ["1.1em", 0],
translateZ: 0,
duration: 750,
delay: (el, i) => 50 * i,
})
.add({
targets: ".ml7",
opacity: 0,
duration: 1000,
easing: "easeOutExpo",
delay: 1000,
});
.m17 .letters2 {
display: inline-block;
line-height: 1em;
}
<div class="m17">
<h1 class="text-wrapper2">text <mark>wrapper</mark class=letters2> dropDown</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
I want to make an animation in the text that I have marked. Can you help me to correct my wrong script, or additional scripts or new scripts.
A:
Sure, there are a few issues with the script you provided. First, you are using .ml7 as the class for the text wrapper and the individual letters, but in your HTML, the text wrapper has a class of .m17. This means that the script will not be able to find the text wrapper and the animation will not run.
Next, the mark elements you are using are not closed properly in your HTML. Each mark element should have a closing tag, like this:
<h1 class="text-wrapper2">text <mark class="letters2">wrapper</mark> dropDown</h1>
Finally, the timeline in your script is not being applied to any targets, so the animation will not run. To fix this, you can specify the text wrapper as the target of the timeline, like this:
anime
.timeline({
targets: ".m17",
loop: true
})
.add({
targets: ".letters2",
translateY: ["1.1em", 0],
translateZ: 0,
duration: 750,
delay: (el, i) => 50 * i,
})
.add({
opacity: 0,
duration: 1000,
easing: "easeOutExpo",
delay: 1000,
});
This should fix the issues with your script and allow the animation to run. However, keep in mind that you will need to include the necessary CSS styles for the .letters2 class in order for the animation to work properly. I hope this helps!
A:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>
| how to make a mavy text animation using javascript | I want to make a wavy text animation why when the script I made the animation doesn't run. I use mark aiming to mark 1 sentence, that's why I don't use span.
// Wrap every letter in a span
var textWrapper2 = document.querySelector(".ml7 .letters2");
textWrapper2.innerHTML = textWrapper2.textContent.replace(/\S/g, "<mark class='letters2'>$&</mark>");
anime
.timeline({
loop: true
})
.add({
targets: ".ml7 .letters2",
translateY: ["1.1em", 0],
translateZ: 0,
duration: 750,
delay: (el, i) => 50 * i,
})
.add({
targets: ".ml7",
opacity: 0,
duration: 1000,
easing: "easeOutExpo",
delay: 1000,
});
.m17 .letters2 {
display: inline-block;
line-height: 1em;
}
<div class="m17">
<h1 class="text-wrapper2">text <mark>wrapper</mark class=letters2> dropDown</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
I want to make an animation in the text that I have marked. Can you help me to correct my wrong script, or additional scripts or new scripts.
| [
"Sure, there are a few issues with the script you provided. First, you are using .ml7 as the class for the text wrapper and the individual letters, but in your HTML, the text wrapper has a class of .m17. This means that the script will not be able to find the text wrapper and the animation will not run.\nNext, the mark elements you are using are not closed properly in your HTML. Each mark element should have a closing tag, like this:\n<h1 class=\"text-wrapper2\">text <mark class=\"letters2\">wrapper</mark> dropDown</h1>\n\nFinally, the timeline in your script is not being applied to any targets, so the animation will not run. To fix this, you can specify the text wrapper as the target of the timeline, like this:\n anime\n .timeline({\n targets: \".m17\",\n loop: true\n })\n .add({\n targets: \".letters2\",\n translateY: [\"1.1em\", 0],\n translateZ: 0,\n duration: 750,\n delay: (el, i) => 50 * i,\n })\n .add({\n opacity: 0,\n duration: 1000,\n easing: \"easeOutExpo\",\n delay: 1000,\n });\n\nThis should fix the issues with your script and allow the animation to run. However, keep in mind that you will need to include the necessary CSS styles for the .letters2 class in order for the animation to work properly. I hope this helps!\n",
"\n\n<!DOCTYPE html>\n<html>\n<style>\n#container {\n width: 400px;\n height: 400px;\n position: relative;\n background: yellow;\n}\n#animate {\n width: 50px;\n height: 50px;\n position: absolute;\n background-color: red;\n}\n</style>\n<body>\n\n<p><button onclick=\"myMove()\">Click Me</button></p> \n\n<div id =\"container\">\n <div id =\"animate\"></div>\n</div>\n\n<script>\nfunction myMove() {\n let id = null;\n const elem = document.getElementById(\"animate\"); \n let pos = 0;\n clearInterval(id);\n id = setInterval(frame, 5);\n function frame() {\n if (pos == 350) {\n clearInterval(id);\n } else {\n pos++; \n elem.style.top = pos + \"px\"; \n elem.style.left = pos + \"px\"; \n }\n }\n}\n</script>\n\n</body>\n</html>\n\n\n\n"
] | [
0,
0
] | [] | [] | [
"css",
"html",
"javascript"
] | stackoverflow_0074675391_css_html_javascript.txt |
Q:
How to doubleclick on gridcell?
I want to doubleclick on particular gridcell, and after I searched the element by google chrome developer tools(select an element), the element on which I want to doubleclick comes out like this.
<td class="w2grid_input_table gridBodyDefault gridBodyDefault_data grd_mst_columnstyle_19_ w2grid_default_readonly" id="grd_mst_cell_3_19" role="gridcell" style="height: 24px;" rowspan="2" colindex="21" col_id="D_16" displaymode="label" blockselect="false" inputtype="text" or_wd="30" datatype="text" tdIndex="143" or_bgColor="">
<nobr class="w2grid_input w2grid_input_readonly">/</nobr>
</td>
How can I doubleclick on this gridcell element by writing code on 'console' section?
I have tried these...
document.getElementsByClassName('w2grid_input_table gridBodyDefault gridBodyDefault_data grd_mst_columnstyle_19_ w2grid_default_readonly');
But it's not working.
I don't know what to do. Please help me.
A:
Welcome to Stackoverflow. From your question I'm unsure as to whether you wish to handle a double click event or simulate such an event so my answer includes example code for both. For future reference, the Mozilla Documentation is a great resource for learning how to use JavaScript browser APIs.
If you want to simulate a double click event you can use a function such as this:
function simulateDoubleClick(target) {
const event = new MouseEvent('dblclick', {
view: window,
bubbles: true,
cancelable: true
});
const cancelled = !target.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
// Get a handle on the DOM element
const element = document.getElementById('id-of-html-element');
// Simulate the double click event
simulateDoubleClick(element);
See Creating and triggering events for more details.
If you want to execute a function in response to a double click event on a element then you need to use an event listener for the dblclick event. See MDN documentation.
// Define an event handler function
const handler = (event) => {
console.log(`${event.target} was double clicked!`);
};
// Attach event handler to element
const elem = document.querySelector('#doubleClickMe');
elem.addEventListener('dblclick', handler);
| How to doubleclick on gridcell? | I want to doubleclick on particular gridcell, and after I searched the element by google chrome developer tools(select an element), the element on which I want to doubleclick comes out like this.
<td class="w2grid_input_table gridBodyDefault gridBodyDefault_data grd_mst_columnstyle_19_ w2grid_default_readonly" id="grd_mst_cell_3_19" role="gridcell" style="height: 24px;" rowspan="2" colindex="21" col_id="D_16" displaymode="label" blockselect="false" inputtype="text" or_wd="30" datatype="text" tdIndex="143" or_bgColor="">
<nobr class="w2grid_input w2grid_input_readonly">/</nobr>
</td>
How can I doubleclick on this gridcell element by writing code on 'console' section?
I have tried these...
document.getElementsByClassName('w2grid_input_table gridBodyDefault gridBodyDefault_data grd_mst_columnstyle_19_ w2grid_default_readonly');
But it's not working.
I don't know what to do. Please help me.
| [
"Welcome to Stackoverflow. From your question I'm unsure as to whether you wish to handle a double click event or simulate such an event so my answer includes example code for both. For future reference, the Mozilla Documentation is a great resource for learning how to use JavaScript browser APIs.\nIf you want to simulate a double click event you can use a function such as this:\nfunction simulateDoubleClick(target) {\n const event = new MouseEvent('dblclick', {\n view: window,\n bubbles: true,\n cancelable: true\n });\n const cancelled = !target.dispatchEvent(event);\n\n if (cancelled) {\n // A handler called preventDefault.\n alert(\"cancelled\");\n } else {\n // None of the handlers called preventDefault.\n alert(\"not cancelled\");\n }\n}\n\n// Get a handle on the DOM element\nconst element = document.getElementById('id-of-html-element');\n// Simulate the double click event\nsimulateDoubleClick(element);\n\nSee Creating and triggering events for more details.\nIf you want to execute a function in response to a double click event on a element then you need to use an event listener for the dblclick event. See MDN documentation.\n// Define an event handler function\nconst handler = (event) => {\n console.log(`${event.target} was double clicked!`);\n};\n\n// Attach event handler to element\nconst elem = document.querySelector('#doubleClickMe');\nelem.addEventListener('dblclick', handler);\n\n"
] | [
0
] | [] | [] | [
"html",
"html_table",
"javascript"
] | stackoverflow_0074675282_html_html_table_javascript.txt |
Q:
Python CSV writer creates new line for each data item
I'm running Python 3.9.2 on a Raspberry Pi and I've written a script that will read water temperatures from my boiler and write them to a CSV file. However, each data item in the output file appears on a new line.
Here's my code:
from subprocess import check_output
import csv
header = ['Flow', 'Return']
cmd = ["/usr/bin/ebusctl", "read", "-f"]
data = [
[float(check_output([*cmd, "FlowTemp", "temp"]))],
[float(check_output([*cmd, "ReturnTemp", "temp"]))]
]
with open('sandbox.csv', 'w', encoding='utf8', newline='') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(data)
And here's the content of sandbox.csv:
Flow,Return
57.19
43.12
How could I fix this?
A:
CSV files contain one record per row.
The writerow method writes one record to the file which it expects to be represented as one list or tuple of values, e.g. for one record a, b, c:
[a, b, c]
The writerows method does the same for multiple records at once, which it expects to be represented as a list or tuple of records, e.g. for two records a, b, c and x, y, z:
[[a, b, c], [x, y, z]]
The data you are passing to writerows is structured like this:
[[Flow], [Return]]
This means that writerows will write two records to the file (each in one line), each containing only one value.
If you intend Flow, Return to be one record (written to one line), your data needs to be structured differently:
Either you create data = [Flow, Return] (a single record) and pass it to writerow.
Or you create data = [[Flow, Return]] (a list of records, containing only one record) and pass it to writerows.
A:
To fix the issue with each data item appearing on a new line in your CSV file, you will need to modify the way you are writing the data to the file. Currently, you are using the "writerows" method of the CSV writer to write the data, which writes each element of the "data" list as a separate row in the CSV file.
To write the data as a single row in the CSV file, you will need to modify your code to use the "writerow" method of the CSV writer instead. This method takes a single argument, which is a list of values to write to the current row in the CSV file.
Here is how you could modify your code to use the "writerow" method to write the data as a single row in the CSV file:
from subprocess import check_output
import csv
header = ['Flow', 'Return']
cmd = ["/usr/bin/ebusctl", "read", "-f"]
data = [
float(check_output([*cmd, "FlowTemp", "temp"])),
float(check_output([*cmd, "ReturnTemp", "temp"]))
]
with open('sandbox.csv', 'w', encoding='utf8', newline='') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerow(data)
In this modified code, the "data" variable is defined as a list of the values to write to the CSV file, rather than a list of lists. This allows the "writerow" method to write the values as a single row in the CSV file, rather than as separate rows.
| Python CSV writer creates new line for each data item | I'm running Python 3.9.2 on a Raspberry Pi and I've written a script that will read water temperatures from my boiler and write them to a CSV file. However, each data item in the output file appears on a new line.
Here's my code:
from subprocess import check_output
import csv
header = ['Flow', 'Return']
cmd = ["/usr/bin/ebusctl", "read", "-f"]
data = [
[float(check_output([*cmd, "FlowTemp", "temp"]))],
[float(check_output([*cmd, "ReturnTemp", "temp"]))]
]
with open('sandbox.csv', 'w', encoding='utf8', newline='') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(data)
And here's the content of sandbox.csv:
Flow,Return
57.19
43.12
How could I fix this?
| [
"CSV files contain one record per row.\nThe writerow method writes one record to the file which it expects to be represented as one list or tuple of values, e.g. for one record a, b, c:\n[a, b, c]\n\nThe writerows method does the same for multiple records at once, which it expects to be represented as a list or tuple of records, e.g. for two records a, b, c and x, y, z:\n[[a, b, c], [x, y, z]]\n\nThe data you are passing to writerows is structured like this:\n[[Flow], [Return]]\n\nThis means that writerows will write two records to the file (each in one line), each containing only one value.\nIf you intend Flow, Return to be one record (written to one line), your data needs to be structured differently:\n\nEither you create data = [Flow, Return] (a single record) and pass it to writerow.\n\nOr you create data = [[Flow, Return]] (a list of records, containing only one record) and pass it to writerows.\n\n\n",
"To fix the issue with each data item appearing on a new line in your CSV file, you will need to modify the way you are writing the data to the file. Currently, you are using the \"writerows\" method of the CSV writer to write the data, which writes each element of the \"data\" list as a separate row in the CSV file.\nTo write the data as a single row in the CSV file, you will need to modify your code to use the \"writerow\" method of the CSV writer instead. This method takes a single argument, which is a list of values to write to the current row in the CSV file.\nHere is how you could modify your code to use the \"writerow\" method to write the data as a single row in the CSV file:\nfrom subprocess import check_output\nimport csv\n\nheader = ['Flow', 'Return']\ncmd = [\"/usr/bin/ebusctl\", \"read\", \"-f\"]\ndata = [\n float(check_output([*cmd, \"FlowTemp\", \"temp\"])),\n float(check_output([*cmd, \"ReturnTemp\", \"temp\"]))\n]\n\nwith open('sandbox.csv', 'w', encoding='utf8', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(header)\n writer.writerow(data)\n\nIn this modified code, the \"data\" variable is defined as a list of the values to write to the CSV file, rather than a list of lists. This allows the \"writerow\" method to write the values as a single row in the CSV file, rather than as separate rows.\n"
] | [
0,
0
] | [] | [] | [
"csv",
"newline",
"python"
] | stackoverflow_0074675239_csv_newline_python.txt |
Q:
Chrome extension: DOMParser is not defined with Manifest v3
I have developped an extension to scrape some content from web page and up to now it was working fine but since I switched to manifest v3, the parsing doesn't work anymore.
I use the following script to read the source code:
chrome.scripting.executeScript(
{
target: {tabId: tab.id, allFrames: true},
files: ['GetSource.js'],
}, async function(results)
{
// GETTING HTML
parser = new DOMParser();
content = parser.parseFromString(results, "text/html");
... ETC ...
This code used to work fine but now I get the following message in my console:
Uncaught (in promise) ReferenceError: DOMParser is not defined
The code is part of a promise but I don't think the promise is the problem here. I basically need to load the source code into a variable so that I can parse it afterwards.
I've checked the documentation but I haven't found something mentionned that DOMParser was not going to work with v3.
Any idea?
Thanks
A:
Since service workers don't have access to DOM, it's not possible for
an extension's service worker to access the DOMParser API or create an
to parse and traverse documents.
More detail
And I solve the problem by using library dom-parser.The code could be like this
import DomParser from "dom-parser";
const parser = new DomParser();
const dom = parser.parseFromString('you html string');
| Chrome extension: DOMParser is not defined with Manifest v3 | I have developped an extension to scrape some content from web page and up to now it was working fine but since I switched to manifest v3, the parsing doesn't work anymore.
I use the following script to read the source code:
chrome.scripting.executeScript(
{
target: {tabId: tab.id, allFrames: true},
files: ['GetSource.js'],
}, async function(results)
{
// GETTING HTML
parser = new DOMParser();
content = parser.parseFromString(results, "text/html");
... ETC ...
This code used to work fine but now I get the following message in my console:
Uncaught (in promise) ReferenceError: DOMParser is not defined
The code is part of a promise but I don't think the promise is the problem here. I basically need to load the source code into a variable so that I can parse it afterwards.
I've checked the documentation but I haven't found something mentionned that DOMParser was not going to work with v3.
Any idea?
Thanks
| [
"\nSince service workers don't have access to DOM, it's not possible for\nan extension's service worker to access the DOMParser API or create an\n to parse and traverse documents. \n\nMore detail\nAnd I solve the problem by using library dom-parser.The code could be like this\nimport DomParser from \"dom-parser\";\nconst parser = new DomParser();\nconst dom = parser.parseFromString('you html string');\n\n"
] | [
0
] | [] | [] | [
"chrome_extension_manifest_v3",
"google_chrome_extension"
] | stackoverflow_0068964543_chrome_extension_manifest_v3_google_chrome_extension.txt |
Q:
Java Spring controller fetching from React fetch()
I use React for fronted + Java Spring controllers that have some endpoints for backend. But for some of endpoints I have response with React features and for some without React features. I am new with React part, so I suppose that I am missing some principles of fetch(). Please help me to understand and fix.
Case 1
App.js code:
import React, {useState, useEffect} from 'react';
import './App.css';
function App () {
const [message, setMessage] = useState("");
useEffect(() => {
fetch('http://localhost:8080/api/v1/hello')
.then(response => response.text())
.then(message => {
setMessage(message);
});
},[])
return (
<div className="App">
<header className="">
<h1>React is here!</h1>
<h2 className="App-title">{message}</h2>
</header>
</div>
)
}
export default App;
Java controller code:
@RestController
@CrossOrigin
@RequestMapping(path = "/api/v1")
public class BasicController {
@GetMapping("/hello")
public String sayHello() {
return "Hello Everyone !";
}
}
As a result I see "React is here!" + "Hello Everyone !" with according style string on localhost:8080. So I see that the backend returns value and React also works with it.
But if I go to localhost:8080/api/v1/hello, I see only "Hello Everyone !" string without React features. So the backend returns value, but React doesn't work.
Why, if I am fetching this particular endpoint? - Question 1
Actually, the same result if I use
@RequestMapping(path = "api/v1")
without the first /
Case 2
I have the same App.js but change fetch(URL) to
fetch('http://localhost:8080')
And I add a new Controller:
@RestController
@CrossOrigin
@RequestMapping(path = "/")
public class StartPageController {
@GetMapping()
public String startPage() {
return "Start page";
}
}
If I go to localhost:8080, that I am fetching I see only "Start page" string without React features. So the backend returns value, but React doesn't work.
Why, if it is the simplest option for endpoint path and even more complex fetch worked as I mentioned above? - Question 2
Case 3
As it seems that I have some issue with "/" endpoint, I decided to check how the Case 1 endpoint will work if I leave StartPageController from the Case 2. So I just return back url:
fetch('http://localhost:8080/api/v1/hello'),
but leave both controllers.
As a result, for now, I see that React features doesn't work either for localhost:8080, or localhost:8080/api/v1/hello (the last one actually as in Case 1). Only backend values "Start page" or "Hello Everyone !" return for all mentioned endpoints. Without React.
So it seems that the "/" endpoint from StartPageController doesn't work with React by itself and also doesn't allow to work other more complex endpoints as a root endpoint.
So 2 questions as a result:
What is the issue with some particular paths - Case 1?
What is the issue with "/" endpoint - Case 2 and 3?
How I run Spring boot + React - I make a .jar file by Maven, where I collect both parts for frontend and backend by .pom build configurations. And I run the .jar in Intellij IDEA. I need to do it this way because I want to deploy .jar later on AWS Elastic Beanstalk.
A:
Let's understand this code first :
@RestController
@CrossOrigin
@RequestMapping(path = "/api/v1")
public class BasicController {
@GetMapping("/hello")
public String sayHello() {
return "Hello Everyone !";
}
}
Probably your backend server is running at port 8000 and if you hit this url localhost:8080/api/v1/hello , it gives the output as "Hello Everyone" which you've returned from the controller right ? How do you expect to get React Part when you hit this endpoint ? When you run localhost:8080/api/v1/hello this is Spring Part [Java part] and not the react part. If you use this endpoint from the react app or any client you'll always get "Hello Everyone" as per your logic, same applies for the StartPage controller as well.
Try to run your react application, if you're fetching correctly, you'll see the backend part used with front end part. It's as simple as that.
See which port the react application is using ? It's probably localhost:3000 see if it's working or not. There, you'll see the result.
Hope this helps :)
| Java Spring controller fetching from React fetch() | I use React for fronted + Java Spring controllers that have some endpoints for backend. But for some of endpoints I have response with React features and for some without React features. I am new with React part, so I suppose that I am missing some principles of fetch(). Please help me to understand and fix.
Case 1
App.js code:
import React, {useState, useEffect} from 'react';
import './App.css';
function App () {
const [message, setMessage] = useState("");
useEffect(() => {
fetch('http://localhost:8080/api/v1/hello')
.then(response => response.text())
.then(message => {
setMessage(message);
});
},[])
return (
<div className="App">
<header className="">
<h1>React is here!</h1>
<h2 className="App-title">{message}</h2>
</header>
</div>
)
}
export default App;
Java controller code:
@RestController
@CrossOrigin
@RequestMapping(path = "/api/v1")
public class BasicController {
@GetMapping("/hello")
public String sayHello() {
return "Hello Everyone !";
}
}
As a result I see "React is here!" + "Hello Everyone !" with according style string on localhost:8080. So I see that the backend returns value and React also works with it.
But if I go to localhost:8080/api/v1/hello, I see only "Hello Everyone !" string without React features. So the backend returns value, but React doesn't work.
Why, if I am fetching this particular endpoint? - Question 1
Actually, the same result if I use
@RequestMapping(path = "api/v1")
without the first /
Case 2
I have the same App.js but change fetch(URL) to
fetch('http://localhost:8080')
And I add a new Controller:
@RestController
@CrossOrigin
@RequestMapping(path = "/")
public class StartPageController {
@GetMapping()
public String startPage() {
return "Start page";
}
}
If I go to localhost:8080, that I am fetching I see only "Start page" string without React features. So the backend returns value, but React doesn't work.
Why, if it is the simplest option for endpoint path and even more complex fetch worked as I mentioned above? - Question 2
Case 3
As it seems that I have some issue with "/" endpoint, I decided to check how the Case 1 endpoint will work if I leave StartPageController from the Case 2. So I just return back url:
fetch('http://localhost:8080/api/v1/hello'),
but leave both controllers.
As a result, for now, I see that React features doesn't work either for localhost:8080, or localhost:8080/api/v1/hello (the last one actually as in Case 1). Only backend values "Start page" or "Hello Everyone !" return for all mentioned endpoints. Without React.
So it seems that the "/" endpoint from StartPageController doesn't work with React by itself and also doesn't allow to work other more complex endpoints as a root endpoint.
So 2 questions as a result:
What is the issue with some particular paths - Case 1?
What is the issue with "/" endpoint - Case 2 and 3?
How I run Spring boot + React - I make a .jar file by Maven, where I collect both parts for frontend and backend by .pom build configurations. And I run the .jar in Intellij IDEA. I need to do it this way because I want to deploy .jar later on AWS Elastic Beanstalk.
| [
"Let's understand this code first :\n@RestController\n @CrossOrigin\n @RequestMapping(path = \"/api/v1\")\n public class BasicController {\n\n @GetMapping(\"/hello\")\n public String sayHello() {\n return \"Hello Everyone !\";\n }\n }\n\nProbably your backend server is running at port 8000 and if you hit this url localhost:8080/api/v1/hello , it gives the output as \"Hello Everyone\" which you've returned from the controller right ? How do you expect to get React Part when you hit this endpoint ? When you run localhost:8080/api/v1/hello this is Spring Part [Java part] and not the react part. If you use this endpoint from the react app or any client you'll always get \"Hello Everyone\" as per your logic, same applies for the StartPage controller as well.\nTry to run your react application, if you're fetching correctly, you'll see the backend part used with front end part. It's as simple as that.\nSee which port the react application is using ? It's probably localhost:3000 see if it's working or not. There, you'll see the result.\nHope this helps :)\n"
] | [
0
] | [] | [] | [
"java",
"reactjs",
"spring",
"spring_restcontroller"
] | stackoverflow_0074675260_java_reactjs_spring_spring_restcontroller.txt |
Q:
How do users who navigate using a keyboard change the style of the text they are editing in ckeditor5
Disabled users who cannot control a mouse use the keyboard to navigate the page. How do you allow them to select the various styles (like bold etc) in ckeditor5? These elements are NOT in the tabindex of the page by default.
Tabbing through a form, I expect to be able to interact with every interactable element on a page
A:
WCAG 2.1.1 says that all functionality must be available from the keyboard. Sometimes people mistakenly interpret that to mean that all interactive elements on the page must be keybaord accessible.
Here's a screenshot of ckeditor5 from their website. I'm not a ckeditor5 user but I'm assuming you're talking about the editing bar at the top.
While it's strongly encouraged to allow a keyboard user to navigate to the editing bar of ckeditor5, it's not strictly required if all the functionality of the editing bar is available via the keyboard.
For example, if I can select text then press Ctrl+B to make it bold, then the functionality of bold is available even if I can't tab to the 'B' on the editor bar.
The editing bar has a lot of stuff on it so everything would need a keyboard shortcut in order to pass WCAG 2.1.1. It looks like you can configure ckedit5 pretty extensively, https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/configuration.html
A:
I see that CKEditor 5 has a list of keyboard shortcuts in their documentation. Pressing Alt + F10 (may require Fn) when the editor input area has focus moves keyboard focus to the editor toolbar. Then, keyboard arrow keys can be used to navigate the toolbar.
I am not saying that CKEditor is accessible, but it is information you may consider.
| How do users who navigate using a keyboard change the style of the text they are editing in ckeditor5 | Disabled users who cannot control a mouse use the keyboard to navigate the page. How do you allow them to select the various styles (like bold etc) in ckeditor5? These elements are NOT in the tabindex of the page by default.
Tabbing through a form, I expect to be able to interact with every interactable element on a page
| [
"WCAG 2.1.1 says that all functionality must be available from the keyboard. Sometimes people mistakenly interpret that to mean that all interactive elements on the page must be keybaord accessible.\nHere's a screenshot of ckeditor5 from their website. I'm not a ckeditor5 user but I'm assuming you're talking about the editing bar at the top.\n\nWhile it's strongly encouraged to allow a keyboard user to navigate to the editing bar of ckeditor5, it's not strictly required if all the functionality of the editing bar is available via the keyboard.\nFor example, if I can select text then press Ctrl+B to make it bold, then the functionality of bold is available even if I can't tab to the 'B' on the editor bar.\nThe editing bar has a lot of stuff on it so everything would need a keyboard shortcut in order to pass WCAG 2.1.1. It looks like you can configure ckedit5 pretty extensively, https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/configuration.html\n",
"I see that CKEditor 5 has a list of keyboard shortcuts in their documentation. Pressing Alt + F10 (may require Fn) when the editor input area has focus moves keyboard focus to the editor toolbar. Then, keyboard arrow keys can be used to navigate the toolbar.\nI am not saying that CKEditor is accessible, but it is information you may consider.\n"
] | [
0,
0
] | [] | [] | [
"accessibility",
"ckeditor5"
] | stackoverflow_0074666923_accessibility_ckeditor5.txt |
Q:
How to have TopAppBar navigate back to the previous screen in Jetpack Compose?
In the MainActivity I use these code to navigate to the RecordActivity:
ElevatedButton(
onClick = { mContext.startActivity(Intent(mContext, RecordActivity::class.java)) },
) {}
In the RecordActivity, I want to use the following code to navigate back to the MainActivity:
val navController = rememberNavController()
TopAppBar(
title = {Text(text = "History Records")},
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, "backIcon")
}
},
)
But there is no effect When I press the back button.
Must I use NavController and NavHost? Must I build the routes for NavHost even I only have two screens to navigate? And I don't need the Navigation bar in the home page. So is there any easier way to implement the simple requirement?
A:
I have the same issue, navController.navigateUp also not working so a workaround I've found in documentation is using finish() to end an activity.
| How to have TopAppBar navigate back to the previous screen in Jetpack Compose? | In the MainActivity I use these code to navigate to the RecordActivity:
ElevatedButton(
onClick = { mContext.startActivity(Intent(mContext, RecordActivity::class.java)) },
) {}
In the RecordActivity, I want to use the following code to navigate back to the MainActivity:
val navController = rememberNavController()
TopAppBar(
title = {Text(text = "History Records")},
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, "backIcon")
}
},
)
But there is no effect When I press the back button.
Must I use NavController and NavHost? Must I build the routes for NavHost even I only have two screens to navigate? And I don't need the Navigation bar in the home page. So is there any easier way to implement the simple requirement?
| [
"I have the same issue, navController.navigateUp also not working so a workaround I've found in documentation is using finish() to end an activity.\n"
] | [
0
] | [] | [] | [
"composable",
"kotlin"
] | stackoverflow_0074069417_composable_kotlin.txt |
Q:
Change img with javascript loop
On my website normally there are two default images and I want whenever I click an H3 element to change the 2 default images with img1 or img2 ... the problem is when I click the h3 to change the 2 default imgs to img1 for example it changes only the first one so I tried to use loop but I didn't know how exactly because I'm a beginner in javascript can you please help me create a loop function using my code to change all the default images in the site to img1 or img2 ... when I click to h3
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h3 onclick="ShowImg1();">Click Here To Show IMG 1</h3>
<h3 onclick="ShowImg2();">Click Here To Show IMG 2</h3>
<h3 onclick="ShowImg3();">Click Here To Show IMG 3</h3>
<h3 onclick="ShowImg4();">Click Here To Show IMG 4</h3>
<!-- img section n#1 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>
<!-- img section n#2 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>
</body>
<script>
function ShowImg1() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp1img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg2() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp2img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg3() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp3img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg4() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp4img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
}
</script>
</html>
A:
You need to change the "id" to class, and then:
document.getElementsByClassName("exp2img").
You can't select multiple elements by id.
| Change img with javascript loop | On my website normally there are two default images and I want whenever I click an H3 element to change the 2 default images with img1 or img2 ... the problem is when I click the h3 to change the 2 default imgs to img1 for example it changes only the first one so I tried to use loop but I didn't know how exactly because I'm a beginner in javascript can you please help me create a loop function using my code to change all the default images in the site to img1 or img2 ... when I click to h3
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h3 onclick="ShowImg1();">Click Here To Show IMG 1</h3>
<h3 onclick="ShowImg2();">Click Here To Show IMG 2</h3>
<h3 onclick="ShowImg3();">Click Here To Show IMG 3</h3>
<h3 onclick="ShowImg4();">Click Here To Show IMG 4</h3>
<!-- img section n#1 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>
<!-- img section n#2 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>
</body>
<script>
function ShowImg1() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp1img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg2() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp2img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg3() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp3img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg4() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp4img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
}
</script>
</html>
| [
"You need to change the \"id\" to class, and then:\ndocument.getElementsByClassName(\"exp2img\").\n\nYou can't select multiple elements by id.\n"
] | [
0
] | [] | [] | [
"javascript"
] | stackoverflow_0074675362_javascript.txt |
Q:
how to update only the first null value in sql table
how can i update only the first null that i found in column2
column1|" column2
--------------------
value1 | value6
value2 | value7
value3 | null
value4 | null
value5 | null
i have tried doing it with
update [RS].[dbo].[req] set [column2] = 'somevalue' where [column2] = 'null'
but it changed all the values i only want the first found value to be changed
A:
To update only the first null value in a column in a SQL table using ASP.NET and SQL, you can use the ROW_NUMBER() function to identify the first null value and then use the UPDATE statement with a WHERE clause to update only that value.
Here is an example of how you can do this:
-- Create a temporary table with the rows from the original table
-- and add a new column with the row number
SELECT ROW_NUMBER() OVER (ORDER BY column1) AS row_num, column1, column2
INTO #temp
FROM [RS].[dbo].[req]
-- Update the first null value in column2 in the temporary table
UPDATE #temp
SET column2 = 'somevalue'
WHERE column2 IS NULL
AND row_num = 1
-- Replace the rows in the original table with the rows from the temporary table
-- and drop the temporary table
UPDATE [RS].[dbo].[req]
SET column1 = #temp.column1,
column2 = #temp.column2
FROM [RS].[dbo].[req]
INNER JOIN #temp
ON [RS].[dbo].[req].column1 = #temp.column1
DROP TABLE #temp
In this example, the ROW_NUMBER() function is used to add a new column to the temporary table that contains the row number of each row, ordered by column1. Then, the UPDATE statement is used to update the first null value in column2 (i.e. the row with row_num = 1) in the temporary table. Finally, the rows in the original table are updated with the rows from the temporary table, and the temporary table is dropped.
| how to update only the first null value in sql table | how can i update only the first null that i found in column2
column1|" column2
--------------------
value1 | value6
value2 | value7
value3 | null
value4 | null
value5 | null
i have tried doing it with
update [RS].[dbo].[req] set [column2] = 'somevalue' where [column2] = 'null'
but it changed all the values i only want the first found value to be changed
| [
"To update only the first null value in a column in a SQL table using ASP.NET and SQL, you can use the ROW_NUMBER() function to identify the first null value and then use the UPDATE statement with a WHERE clause to update only that value.\nHere is an example of how you can do this:\n -- Create a temporary table with the rows from the original table\n-- and add a new column with the row number\nSELECT ROW_NUMBER() OVER (ORDER BY column1) AS row_num, column1, column2\nINTO #temp\nFROM [RS].[dbo].[req]\n\n-- Update the first null value in column2 in the temporary table\nUPDATE #temp\nSET column2 = 'somevalue'\nWHERE column2 IS NULL\nAND row_num = 1\n\n-- Replace the rows in the original table with the rows from the temporary table\n-- and drop the temporary table\nUPDATE [RS].[dbo].[req]\nSET column1 = #temp.column1,\n column2 = #temp.column2\nFROM [RS].[dbo].[req]\nINNER JOIN #temp\nON [RS].[dbo].[req].column1 = #temp.column1\n\nDROP TABLE #temp\n\nIn this example, the ROW_NUMBER() function is used to add a new column to the temporary table that contains the row number of each row, ordered by column1. Then, the UPDATE statement is used to update the first null value in column2 (i.e. the row with row_num = 1) in the temporary table. Finally, the rows in the original table are updated with the rows from the temporary table, and the temporary table is dropped.\n"
] | [
0
] | [] | [] | [
"asp.net",
"sql"
] | stackoverflow_0074675387_asp.net_sql.txt |
Q:
Java 8: How to use javadoc aggregate
Introduction
I'm currently contributing to a GitHub project.
For this, I'm writing a GitHub workflow inside a GitHub Action that tests the creation of JavaDoc files.
This workflow should be run with act.
The project of the GitHub Action when I want to add this GitHub Workflow: https://github.com/MathieuSoysal/Javadoc-publisher.yml
Problem
The problem, when I execute my GitHub workflow with act I obtain this error.
| [INFO] Configuration changed, re-generating javadoc.
| [INFO]
| Usage: javadoc [options] [packagenames] [sourcefiles] [@files]
| -overview <file> Read overview documentation from HTML file
| -public Show only public classes and members
| -protected Show protected/public classes and members (default)
| -package Show package/protected/public classes and members
| -private Show all classes and members
| -help Display command line options and exit
| -doclet <class> Generate output via alternate doclet
| -docletpath <path> Specify where to find doclet class files
| -sourcepath <pathlist> Specify where to find source files
| -classpath <pathlist> Specify where to find user class files
| -cp <pathlist> Specify where to find user class files
| -exclude <pkglist> Specify a list of packages to exclude
| -subpackages <subpkglist> Specify subpackages to recursively load
| -breakiterator Compute first sentence with BreakIterator
| -bootclasspath <pathlist> Override location of class files loaded
| by the bootstrap class loader
| -source <release> Provide source compatibility with specified release
| -extdirs <dirlist> Override location of installed extensions
| -verbose Output messages about what Javadoc is doing
| -locale <name> Locale to be used, e.g. en_US or en_US_WIN
| -encoding <name> Source file encoding name
| -quiet Do not display status messages
| -J<flag> Pass <flag> directly to the runtime system
| -X Print a synopsis of nonstandard options and exit
|
| Provided by Standard doclet:
| -d <directory> Destination directory for output files
| -use Create class and package usage pages
| -version Include @version paragraphs
| -author Include @author paragraphs
| -docfilessubdirs Recursively copy doc-file subdirectories
| -splitindex Split index into one file per letter
| -windowtitle <text> Browser window title for the documentation
| -doctitle <html-code> Include title for the overview page
| -header <html-code> Include header text for each page
| -footer <html-code> Include footer text for each page
| -top <html-code> Include top text for each page
| -bottom <html-code> Include bottom text for each page
| -link <url> Create links to javadoc output at <url>
| -linkoffline <url> <url2> Link to docs at <url> using package list at <url2>
| -excludedocfilessubdir <name1>:.. Exclude any doc-files subdirectories with given name.
| -group <name> <p1>:<p2>.. Group specified packages together in overview page
| -nocomment Suppress description and tags, generate only declarations.
| -nodeprecated Do not include @deprecated information
| -noqualifier <name1>:<name2>:... Exclude the list of qualifiers from the output.
| -nosince Do not include @since information
| -notimestamp Do not include hidden time stamp
| -nodeprecatedlist Do not generate deprecated list
| -notree Do not generate class hierarchy
| -noindex Do not generate index
| -nohelp Do not generate help link
| -nonavbar Do not generate navigation bar
| -serialwarn Generate warning about @serial tag
| -tag <name>:<locations>:<header> Specify single argument custom tags
| -taglet The fully qualified name of Taglet to register
| -tagletpath The path to Taglets
| -charset <charset> Charset for cross-platform viewing of generated documentation.
| -helpfile <file> Include file that help link links to
| -linksource Generate source in HTML
| -sourcetab <tab length> Specify the number of spaces each tab takes up in the source
| -keywords Include HTML meta tags with package, class and member info
| -stylesheetfile <path> File to change style of the generated documentation
| -docencoding <name> Specify the character encoding for the output
| 1 error
| [INFO] ------------------------------------------------------------------------
| [INFO] BUILD FAILURE
| [INFO] ------------------------------------------------------------------------
| [INFO] Total time: 15.675 s
| [INFO] Finished at: 2022-12-04T09:34:07Z
| [INFO] ------------------------------------------------------------------------
| [ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.4.0:aggregate (default-cli) on project template: An error has occurred in Javadoc report generation:
| [ERROR] Exit code: 1 - javadoc: error - invalid flag: --release
| [ERROR]
| [ERROR] Command line was: /opt/hostedtoolcache/Java_Adopt_jdk/8.0.345-1/x64/jre/../bin/javadoc @options @packages
| [ERROR]
| [ERROR] Refer to the generated Javadoc files in '/workspaces/Javadoc-publisher.yml/target/site/apidocs' dir.
| [ERROR]
| [ERROR] -> [Help 1]
| [ERROR]
| [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
| [ERROR] Re-run Maven using the -X switch to enable full debug logging.
| [ERROR]
| [ERROR] For more information about the errors and possible solutions, please read the following articles:
| [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
GitHub Workflow
My GitHub Workflow :
name: Test Actions
on: [pull_request, push]
jobs:
test:
runs-on: ubuntu-latest
name: Test with Java 8
steps:
- uses: actions/checkout@v3
- uses: ./ # Uses an action in the root directory
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
javadoc-branch: javadoc-test
java-version: 8
target-folder: javadoc
- uses: GuillaumeFalourd/assert-command-line-output@v2
with:
command_line: ls -lha
contains: javadoc
expected_result: PASSED
GitHub Action
The GitHub Action of the project : https://github.com/MathieuSoysal/Javadoc-publisher.yml/blob/main/action.yml
mvn command
The executed command to generate javadoc: mvn org.apache.maven.plugins:maven-javadoc-plugin:3.4.0:aggregate
Java version
The java version is: Java Adopt 8.0.345-1
pom.xml
The pom.xml of the project:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- FIXME replace pseudo-->
<groupId>io.github.pseudo</groupId>
<!-- FIXME replace name -->
<artifactId>template</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- FIXME replace template-->
<name>template</name>
<!-- FIXME replace www.example.com-->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.release>${java.version}</maven.compiler.release>
<junit>5.9.0</junit>
<!-- Plugin versions -->
<maven.shade>3.3.0</maven.shade>
<maven.clean>3.1.0</maven.clean>
<maven.resources>3.1.0</maven.resources>
<maven.compiler>3.8.1</maven.compiler>
<maven.surefire>3.0.0-M5</maven.surefire>
<maven.jar>3.2.0</maven.jar>
<maven.install>3.0.0-M1</maven.install>
<!-- SonarCloud properties -->
<!-- FIXME replace with your SonarCloud organization on https://sonarcloud.io -->
<sonar.organization>mathieusoysal</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
</properties>
<dependencies>
<!-- Dependencies -->
<!-- Testing dependencies-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven.shade}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- FIXME replace io.github.pseudo.App-->
<mainClass>io.github.pseudo.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.0</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Question
Does someone know how we can fix this javadoc aggregate problem with jdk 8?
A:
Please remove:
<maven.compiler.release>${java.version}</maven.compiler.release>
with
your pom,
a trivial code base,
mvn clean javadoc:aggregate
, I can't even compile:
...
--- maven-compiler-plugin:3.10.1:compile (default-compile) @ template ---
Changes detected - recompiling the module!
Compiling 1 source file to C:\DEV\projects\java8-demo\target\classes
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 1.025 s
Finished at: 2022-12-04T13:09:35+01:00...
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile (default-compile) on project template: Fatal error compiling: invalid flag: --release -> [Help 1]
(invalid flag: --release)
Whereas
Commenting/deleting <maven.compiler.release/>
... gives us:
cd C:\DEV\projects\java8-demo;
"JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_333" M2_HOME=C:\\ProgramData\\chocolatey\\lib\\maven\\apache-maven-3.8.6
mvn clean javadoc:aggregate
Scanning for projects...
---------------------< io.github.pseudo:template >----------------------
Building template 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- maven-clean-plugin:3.2.0:clean (default-clean) @ template ---
Deleting C:\DEV\projects\java8-demo\target
---------------------< io.github.pseudo:template >----------------------
Building template 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
>>> maven-javadoc-plugin:3.4.1:aggregate (default-cli) > compile @ template >>>
--- jacoco-maven-plugin:0.8.8:prepare-agent (default) @ template ---
argLine set to -javaagent:C:\\Users\\xerx\\.m2\\repository\\org\\jacoco\\org.jacoco.agent\\0.8.8\\org.jacoco.agent-0.8.8-runtime.jar=destfile=C:\\DEV\\projects\\java8-demo\\target\\jacoco.exec
--- maven-resources-plugin:3.3.0:resources (default-resources) @ template ---
skip non existing resourceDirectory C:\DEV\projects\java8-demo\src\main\resources
--- maven-compiler-plugin:3.10.1:compile (default-compile) @ template ---
Changes detected - recompiling the module!
Compiling 1 source file to C:\DEV\projects\java8-demo\target\classes
<<< maven-javadoc-plugin:3.4.1:aggregate (default-cli) < compile @ template <<<
--- maven-javadoc-plugin:3.4.1:aggregate (default-cli) @ template ---
No previous run data found, generating javadoc.
Loading source file C:\DEV\projects\java8-demo\src\main\java\com\example\java8\demo\App.java...
Loading source files for package com.example.java8.demo...
Constructing Javadoc information...
Standard Doclet version 1.8.0_333
Building tree for all the packages and classes...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\App.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\package-frame.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\package-summary.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\package-tree.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\constant-values.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\class-use\App.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\class-use\App.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\com\example\java8\demo\package-use.html...
Building index for all the packages and classes...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\overview-tree.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\index-all.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\deprecated-list.html...
Building index for all classes...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\allclasses-frame.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\allclasses-noframe.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\index.html...
Generating C:\DEV\projects\java8-demo\target\site\apidocs\help-doc.html...
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 3.287 s
Finished at: 2022-12-04T13:20:08+01:00
------------------------------------------------------------------------
..the (slight) difference in maven-javadoc-plugin version should be explained by different maven versions. (we can fix it in <build.[pluginManagement.]plugins/>)
| Java 8: How to use javadoc aggregate | Introduction
I'm currently contributing to a GitHub project.
For this, I'm writing a GitHub workflow inside a GitHub Action that tests the creation of JavaDoc files.
This workflow should be run with act.
The project of the GitHub Action when I want to add this GitHub Workflow: https://github.com/MathieuSoysal/Javadoc-publisher.yml
Problem
The problem, when I execute my GitHub workflow with act I obtain this error.
| [INFO] Configuration changed, re-generating javadoc.
| [INFO]
| Usage: javadoc [options] [packagenames] [sourcefiles] [@files]
| -overview <file> Read overview documentation from HTML file
| -public Show only public classes and members
| -protected Show protected/public classes and members (default)
| -package Show package/protected/public classes and members
| -private Show all classes and members
| -help Display command line options and exit
| -doclet <class> Generate output via alternate doclet
| -docletpath <path> Specify where to find doclet class files
| -sourcepath <pathlist> Specify where to find source files
| -classpath <pathlist> Specify where to find user class files
| -cp <pathlist> Specify where to find user class files
| -exclude <pkglist> Specify a list of packages to exclude
| -subpackages <subpkglist> Specify subpackages to recursively load
| -breakiterator Compute first sentence with BreakIterator
| -bootclasspath <pathlist> Override location of class files loaded
| by the bootstrap class loader
| -source <release> Provide source compatibility with specified release
| -extdirs <dirlist> Override location of installed extensions
| -verbose Output messages about what Javadoc is doing
| -locale <name> Locale to be used, e.g. en_US or en_US_WIN
| -encoding <name> Source file encoding name
| -quiet Do not display status messages
| -J<flag> Pass <flag> directly to the runtime system
| -X Print a synopsis of nonstandard options and exit
|
| Provided by Standard doclet:
| -d <directory> Destination directory for output files
| -use Create class and package usage pages
| -version Include @version paragraphs
| -author Include @author paragraphs
| -docfilessubdirs Recursively copy doc-file subdirectories
| -splitindex Split index into one file per letter
| -windowtitle <text> Browser window title for the documentation
| -doctitle <html-code> Include title for the overview page
| -header <html-code> Include header text for each page
| -footer <html-code> Include footer text for each page
| -top <html-code> Include top text for each page
| -bottom <html-code> Include bottom text for each page
| -link <url> Create links to javadoc output at <url>
| -linkoffline <url> <url2> Link to docs at <url> using package list at <url2>
| -excludedocfilessubdir <name1>:.. Exclude any doc-files subdirectories with given name.
| -group <name> <p1>:<p2>.. Group specified packages together in overview page
| -nocomment Suppress description and tags, generate only declarations.
| -nodeprecated Do not include @deprecated information
| -noqualifier <name1>:<name2>:... Exclude the list of qualifiers from the output.
| -nosince Do not include @since information
| -notimestamp Do not include hidden time stamp
| -nodeprecatedlist Do not generate deprecated list
| -notree Do not generate class hierarchy
| -noindex Do not generate index
| -nohelp Do not generate help link
| -nonavbar Do not generate navigation bar
| -serialwarn Generate warning about @serial tag
| -tag <name>:<locations>:<header> Specify single argument custom tags
| -taglet The fully qualified name of Taglet to register
| -tagletpath The path to Taglets
| -charset <charset> Charset for cross-platform viewing of generated documentation.
| -helpfile <file> Include file that help link links to
| -linksource Generate source in HTML
| -sourcetab <tab length> Specify the number of spaces each tab takes up in the source
| -keywords Include HTML meta tags with package, class and member info
| -stylesheetfile <path> File to change style of the generated documentation
| -docencoding <name> Specify the character encoding for the output
| 1 error
| [INFO] ------------------------------------------------------------------------
| [INFO] BUILD FAILURE
| [INFO] ------------------------------------------------------------------------
| [INFO] Total time: 15.675 s
| [INFO] Finished at: 2022-12-04T09:34:07Z
| [INFO] ------------------------------------------------------------------------
| [ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.4.0:aggregate (default-cli) on project template: An error has occurred in Javadoc report generation:
| [ERROR] Exit code: 1 - javadoc: error - invalid flag: --release
| [ERROR]
| [ERROR] Command line was: /opt/hostedtoolcache/Java_Adopt_jdk/8.0.345-1/x64/jre/../bin/javadoc @options @packages
| [ERROR]
| [ERROR] Refer to the generated Javadoc files in '/workspaces/Javadoc-publisher.yml/target/site/apidocs' dir.
| [ERROR]
| [ERROR] -> [Help 1]
| [ERROR]
| [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
| [ERROR] Re-run Maven using the -X switch to enable full debug logging.
| [ERROR]
| [ERROR] For more information about the errors and possible solutions, please read the following articles:
| [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
GitHub Workflow
My GitHub Workflow :
name: Test Actions
on: [pull_request, push]
jobs:
test:
runs-on: ubuntu-latest
name: Test with Java 8
steps:
- uses: actions/checkout@v3
- uses: ./ # Uses an action in the root directory
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
javadoc-branch: javadoc-test
java-version: 8
target-folder: javadoc
- uses: GuillaumeFalourd/assert-command-line-output@v2
with:
command_line: ls -lha
contains: javadoc
expected_result: PASSED
GitHub Action
The GitHub Action of the project : https://github.com/MathieuSoysal/Javadoc-publisher.yml/blob/main/action.yml
mvn command
The executed command to generate javadoc: mvn org.apache.maven.plugins:maven-javadoc-plugin:3.4.0:aggregate
Java version
The java version is: Java Adopt 8.0.345-1
pom.xml
The pom.xml of the project:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- FIXME replace pseudo-->
<groupId>io.github.pseudo</groupId>
<!-- FIXME replace name -->
<artifactId>template</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- FIXME replace template-->
<name>template</name>
<!-- FIXME replace www.example.com-->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.release>${java.version}</maven.compiler.release>
<junit>5.9.0</junit>
<!-- Plugin versions -->
<maven.shade>3.3.0</maven.shade>
<maven.clean>3.1.0</maven.clean>
<maven.resources>3.1.0</maven.resources>
<maven.compiler>3.8.1</maven.compiler>
<maven.surefire>3.0.0-M5</maven.surefire>
<maven.jar>3.2.0</maven.jar>
<maven.install>3.0.0-M1</maven.install>
<!-- SonarCloud properties -->
<!-- FIXME replace with your SonarCloud organization on https://sonarcloud.io -->
<sonar.organization>mathieusoysal</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
</properties>
<dependencies>
<!-- Dependencies -->
<!-- Testing dependencies-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven.shade}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- FIXME replace io.github.pseudo.App-->
<mainClass>io.github.pseudo.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.0</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Question
Does someone know how we can fix this javadoc aggregate problem with jdk 8?
| [
"Please remove:\n<maven.compiler.release>${java.version}</maven.compiler.release>\n\nwith\n\nyour pom,\na trivial code base,\nmvn clean javadoc:aggregate\n\n, I can't even compile:\n...\n\n--- maven-compiler-plugin:3.10.1:compile (default-compile) @ template ---\nChanges detected - recompiling the module!\nCompiling 1 source file to C:\\DEV\\projects\\java8-demo\\target\\classes\n------------------------------------------------------------------------\nBUILD FAILURE\n------------------------------------------------------------------------\nTotal time: 1.025 s\nFinished at: 2022-12-04T13:09:35+01:00...\n------------------------------------------------------------------------\nFailed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile (default-compile) on project template: Fatal error compiling: invalid flag: --release -> [Help 1]\n\n(invalid flag: --release)\nWhereas\n\nCommenting/deleting <maven.compiler.release/>\n\n... gives us:\ncd C:\\DEV\\projects\\java8-demo; \n\"JAVA_HOME=C:\\\\Program Files\\\\Java\\\\jdk1.8.0_333\" M2_HOME=C:\\\\ProgramData\\\\chocolatey\\\\lib\\\\maven\\\\apache-maven-3.8.6\nmvn clean javadoc:aggregate\nScanning for projects...\n\n---------------------< io.github.pseudo:template >----------------------\nBuilding template 1.0-SNAPSHOT\n--------------------------------[ jar ]---------------------------------\n\n--- maven-clean-plugin:3.2.0:clean (default-clean) @ template ---\nDeleting C:\\DEV\\projects\\java8-demo\\target\n\n---------------------< io.github.pseudo:template >----------------------\nBuilding template 1.0-SNAPSHOT\n--------------------------------[ jar ]---------------------------------\n\n>>> maven-javadoc-plugin:3.4.1:aggregate (default-cli) > compile @ template >>>\n\n--- jacoco-maven-plugin:0.8.8:prepare-agent (default) @ template ---\nargLine set to -javaagent:C:\\\\Users\\\\xerx\\\\.m2\\\\repository\\\\org\\\\jacoco\\\\org.jacoco.agent\\\\0.8.8\\\\org.jacoco.agent-0.8.8-runtime.jar=destfile=C:\\\\DEV\\\\projects\\\\java8-demo\\\\target\\\\jacoco.exec\n\n--- maven-resources-plugin:3.3.0:resources (default-resources) @ template ---\nskip non existing resourceDirectory C:\\DEV\\projects\\java8-demo\\src\\main\\resources\n\n--- maven-compiler-plugin:3.10.1:compile (default-compile) @ template ---\nChanges detected - recompiling the module!\nCompiling 1 source file to C:\\DEV\\projects\\java8-demo\\target\\classes\n\n<<< maven-javadoc-plugin:3.4.1:aggregate (default-cli) < compile @ template <<<\n\n\n--- maven-javadoc-plugin:3.4.1:aggregate (default-cli) @ template ---\nNo previous run data found, generating javadoc.\n\nLoading source file C:\\DEV\\projects\\java8-demo\\src\\main\\java\\com\\example\\java8\\demo\\App.java...\nLoading source files for package com.example.java8.demo...\nConstructing Javadoc information...\nStandard Doclet version 1.8.0_333\nBuilding tree for all the packages and classes...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\App.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\package-frame.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\package-summary.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\package-tree.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\constant-values.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\class-use\\App.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\class-use\\App.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\com\\example\\java8\\demo\\package-use.html...\nBuilding index for all the packages and classes...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\overview-tree.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\index-all.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\deprecated-list.html...\nBuilding index for all classes...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\allclasses-frame.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\allclasses-noframe.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\index.html...\nGenerating C:\\DEV\\projects\\java8-demo\\target\\site\\apidocs\\help-doc.html...\n------------------------------------------------------------------------\nBUILD SUCCESS\n------------------------------------------------------------------------\nTotal time: 3.287 s\nFinished at: 2022-12-04T13:20:08+01:00\n------------------------------------------------------------------------\n\n..the (slight) difference in maven-javadoc-plugin version should be explained by different maven versions. (we can fix it in <build.[pluginManagement.]plugins/>)\n"
] | [
1
] | [] | [] | [
"github_actions",
"java",
"java_8",
"javadoc",
"maven"
] | stackoverflow_0074674376_github_actions_java_java_8_javadoc_maven.txt |
Q:
Using VisualStudio+ Python -- how to handle "overriding stdlib module" Pylance(reportShadowedImports) warning?
When running ipynbs in VS Code, I've started noticing Pylance warnings on standard library imports. I am using a conda virtual environment, and I believe the warning is related to that. An example using the glob library reads:
"env\Lib\glob.py" is overriding the stdlib "glob" modulePylance(reportShadowedImports)
So far my notebooks run as expected, but I am curious if this warning is indicative of poor layout or is just stating the obvious more of an "FYI you are not using the base install of python".
I have turned off linting and the problem stills persists. And almost nothing returns from my searches of the error "reportShadowedImports".
A:
The reason you find nothing by searching is because this check has just been implemented recently (see Github). I ran into the same problem as you because code.py from Micropython/Circuitpython also overrides the module "code" in stdlib.
The solution is simple, though you then loose out on this specific check. Just add reportShadowedImports to your pyright config. For VS Code, that would be adding it to .vscode/settings.json:
{
"python.languageServer": "Pylance",
[...]
"python.analysis.diagnosticSeverityOverrides": {
"reportShadowedImports": "none"
},
[...]
}
| Using VisualStudio+ Python -- how to handle "overriding stdlib module" Pylance(reportShadowedImports) warning? | When running ipynbs in VS Code, I've started noticing Pylance warnings on standard library imports. I am using a conda virtual environment, and I believe the warning is related to that. An example using the glob library reads:
"env\Lib\glob.py" is overriding the stdlib "glob" modulePylance(reportShadowedImports)
So far my notebooks run as expected, but I am curious if this warning is indicative of poor layout or is just stating the obvious more of an "FYI you are not using the base install of python".
I have turned off linting and the problem stills persists. And almost nothing returns from my searches of the error "reportShadowedImports".
| [
"The reason you find nothing by searching is because this check has just been implemented recently (see Github). I ran into the same problem as you because code.py from Micropython/Circuitpython also overrides the module \"code\" in stdlib.\nThe solution is simple, though you then loose out on this specific check. Just add reportShadowedImports to your pyright config. For VS Code, that would be adding it to .vscode/settings.json:\n{\n \"python.languageServer\": \"Pylance\",\n [...]\n \"python.analysis.diagnosticSeverityOverrides\": {\n \"reportShadowedImports\": \"none\"\n },\n [...]\n}\n\n"
] | [
0
] | [] | [] | [
"conda",
"pylance",
"python",
"visual_studio"
] | stackoverflow_0074660176_conda_pylance_python_visual_studio.txt |
Q:
Laravel Sail Up never finishes building during GPG command
I'm trying to setup the dev environment for an existing project on another computer under WSL2 and Windows 10. Having installed the project from its own repo with composer install and making sure a basic .env file is in place, I ran /vendor/bin/sail up to do the initial build.
Docker starts normally, but then during stage 4 of 11 RUN apt-get update && apt-get install...., it just halts when it gets to the line gpg: keybox '/root/.gnupg/pubring.kbx' created the build halts, the clock is still ticking but the operation never finishes.
I'm able to hit Ctrl + C and it Cancels cleanly.
Editing Laravel's dockerfile, I added a -v to the gpg --recv-key ... line in the script and got additional output with the operation halting after gpg: connection to dirmngr established instead.
I'm running Ubuntu under WSL2, fully updated, docker freshly installed and configured to talk to it as on my other machine where I'm not having any issues.
A:
I'm having this exact same issue...I've been trying to get a Laravel 9 new project setup on my Windows 10 & 11 machines running WSL 2 and Docker Desktop since last night and still no joy.
Here is the output of Ubuntu command line when running the Laravel new project build:
=> [ 4/11] RUN apt-get update && apt-get install -y gnupg gosu curl ca-certificates zip unzip git supervisor sqlite3 libcap2-bin libpng-dev python2 && mkdir -p ~/.gnupg && chmod 600 ~/.gnupg 640.1s
=> => # Processing triggers for ca-certificates (20211016) ...
=> => # Updating certificates in /etc/ssl/certs...
=> => # 0 added, 0 removed; done.
=> => # Running hooks in /etc/ca-certificates/update.d...
=> => # done.
=> => # gpg: keybox '/root/.gnupg/pubring.kbx' created =
=> [ 1/11] FROM docker.io/library/ubuntu:22.04@sha256:4b1d0c4a2d2aaf63b37111f34eb9fa89fa1bf53dd6e4ca954d47caebca4005c2 0.0s
=> CACHED [ 2/11] WORKDIR /var/www/html 0.0s
=> CACHED [ 3/11] RUN ln -snf /usr/share/zoneinfo/UTC /etc/localtime && echo UTC > /etc/timezone 0.0s
=> [internal] load build context 0.0s=
=> => transferring context: 99B
A:
Same issue here, using Windows 11 22H2 with the project on a Ubuntu 20.04 under WSL2.
A:
Removing the portnumber (:80) for the keyserver from the PHP 8.x docker file seems to be a workaround for this problem.
echo "keyserver hkp://keyserver.ubuntu.com" >> ~/.gnupg/dirmngr.conf \
Tested with PHP 8.1.
Source: https://github.com/laravel/sail/issues/503#issuecomment-1336273951
A:
It is possible that there is an issue with the GPG keys or the connection to the dirmngr. To troubleshoot this issue, you can try the following steps:
Check the status of your GPG keys by running the following command:
gpg --list-keys
If there are any issues with your keys, you can try to fix them by running the following command:
gpg --fix-keys
Check the connection to the dirmngr by running the following command:
gpg --status-fd 1 --no-permission-warning --list-keys
If there are any issues with the connection, you can try to restart the dirmngr by running the following command:
systemctl restart dirmngr
If the issue persists, you can try to manually install the dependencies that are failing to install during the build process by running the following commands:
apt-get update
apt-get install -y gnupg
If all else fails, you can try to rebuild the Docker container from scratch by running the following command:
docker-compose build --no-cache
This will force Docker to rebuild the container from scratch and should hopefully fix any issues with the build process.
| Laravel Sail Up never finishes building during GPG command | I'm trying to setup the dev environment for an existing project on another computer under WSL2 and Windows 10. Having installed the project from its own repo with composer install and making sure a basic .env file is in place, I ran /vendor/bin/sail up to do the initial build.
Docker starts normally, but then during stage 4 of 11 RUN apt-get update && apt-get install...., it just halts when it gets to the line gpg: keybox '/root/.gnupg/pubring.kbx' created the build halts, the clock is still ticking but the operation never finishes.
I'm able to hit Ctrl + C and it Cancels cleanly.
Editing Laravel's dockerfile, I added a -v to the gpg --recv-key ... line in the script and got additional output with the operation halting after gpg: connection to dirmngr established instead.
I'm running Ubuntu under WSL2, fully updated, docker freshly installed and configured to talk to it as on my other machine where I'm not having any issues.
| [
"I'm having this exact same issue...I've been trying to get a Laravel 9 new project setup on my Windows 10 & 11 machines running WSL 2 and Docker Desktop since last night and still no joy.\nHere is the output of Ubuntu command line when running the Laravel new project build:\n=> [ 4/11] RUN apt-get update && apt-get install -y gnupg gosu curl ca-certificates zip unzip git supervisor sqlite3 libcap2-bin libpng-dev python2 && mkdir -p ~/.gnupg && chmod 600 ~/.gnupg 640.1s\n => => # Processing triggers for ca-certificates (20211016) ...\n => => # Updating certificates in /etc/ssl/certs...\n => => # 0 added, 0 removed; done.\n => => # Running hooks in /etc/ca-certificates/update.d...\n => => # done.\n => => # gpg: keybox '/root/.gnupg/pubring.kbx' created =\n => [ 1/11] FROM docker.io/library/ubuntu:22.04@sha256:4b1d0c4a2d2aaf63b37111f34eb9fa89fa1bf53dd6e4ca954d47caebca4005c2 0.0s\n => CACHED [ 2/11] WORKDIR /var/www/html 0.0s\n => CACHED [ 3/11] RUN ln -snf /usr/share/zoneinfo/UTC /etc/localtime && echo UTC > /etc/timezone 0.0s\n => [internal] load build context 0.0s=\n => => transferring context: 99B \n\n",
"Same issue here, using Windows 11 22H2 with the project on a Ubuntu 20.04 under WSL2.\n",
"Removing the portnumber (:80) for the keyserver from the PHP 8.x docker file seems to be a workaround for this problem.\n echo \"keyserver hkp://keyserver.ubuntu.com\" >> ~/.gnupg/dirmngr.conf \\\n\nTested with PHP 8.1.\nSource: https://github.com/laravel/sail/issues/503#issuecomment-1336273951\n",
"It is possible that there is an issue with the GPG keys or the connection to the dirmngr. To troubleshoot this issue, you can try the following steps:\nCheck the status of your GPG keys by running the following command:\ngpg --list-keys\n\nIf there are any issues with your keys, you can try to fix them by running the following command:\ngpg --fix-keys\n\nCheck the connection to the dirmngr by running the following command:\ngpg --status-fd 1 --no-permission-warning --list-keys\n\nIf there are any issues with the connection, you can try to restart the dirmngr by running the following command:\nsystemctl restart dirmngr\n\nIf the issue persists, you can try to manually install the dependencies that are failing to install during the build process by running the following commands:\napt-get update\napt-get install -y gnupg\n\nIf all else fails, you can try to rebuild the Docker container from scratch by running the following command:\ndocker-compose build --no-cache\n\nThis will force Docker to rebuild the container from scratch and should hopefully fix any issues with the build process.\n"
] | [
0,
0,
0,
0
] | [] | [] | [
"docker",
"laravel",
"laravel_sail",
"wsl_2"
] | stackoverflow_0074650090_docker_laravel_laravel_sail_wsl_2.txt |
Q:
When deploying firebase cloud functions I get: Build failed: npm ERR! Cannot read property '@babel/core' of undefined
This has been the latest in a series of very frustrating errors I have been receiving the past
3 days with deploying my cloud functions.
When deploying I get:
firebase deploy --only "functions:retireAtlistedEvents,functions:enqueueAtlistedEventsToRetire"
=== Deploying to 'my-project'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build
> build
> tsc
β functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
β artifactregistry: required API artifactregistry.googleapis.com is enabled
β functions: required API cloudfunctions.googleapis.com is enabled
β functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
i functions: preparing functions directory for uploading...
i functions: packaged /home/wpghijsen/Programs/combinedInstance/treetopCombined/treetoprules/functions (188.31 KB) for uploading
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
i functions: ensuring required API cloudtasks.googleapis.com is enabled...
β functions: required API cloudscheduler.googleapis.com is enabled
β functions: required API cloudtasks.googleapis.com is enabled
β functions: functions folder uploaded successfully
i functions: updating Node.js 14 function enqueueAtlistedEventsToRetire(us-central1)...
i functions: updating Node.js 14 function retireAtlistedEvents(us-central1)...
Build failed: npm ERR! Cannot read property '@babel/core' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! /www-data-home/.npm/_logs/2022-12-03T21_14_11_382Z-debug.log; Error ID: beaf8772
Build failed: npm ERR! Cannot read property '@babel/core' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! /www-data-home/.npm/_logs/2022-12-03T21_14_54_517Z-debug.log; Error ID: beaf8772
Functions deploy had errors with the following functions:
enqueueAtlistedEventsToRetire(us-central1)
retireAtlistedEvents(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions:
- Error Failed to update function enqueueAtlistedEventsToRetire in region us-central1
- Error Failed to update function retireAtlistedEvents in region us-central1
I did the --debug option and got this for output before failure
https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense 404
[2022-12-03T21:49:54.764Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.766Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data 404
[2022-12-03T21:49:54.766Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.767Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events 404
[2022-12-03T21:49:54.767Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.769Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event 404
[2022-12-03T21:49:54.770Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.776Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat 404
[2022-12-03T21:49:54.776Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.778Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat 404
[2022-12-03T21:49:54.778Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.779Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn 404
[2022-12-03T21:49:54.779Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.780Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data 404
[2022-12-03T21:49:54.780Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.781Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events 404
[2022-12-03T21:49:54.781Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.781Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count 404
[2022-12-03T21:49:54.781Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.783Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn 404
[2022-12-03T21:49:54.783Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.783Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events 404
[2022-12-03T21:49:54.783Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.784Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape 404
[2022-12-03T21:49:54.784Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.784Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense 404
[2022-12-03T21:49:54.784Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.785Z] Functions deploy failed.
[2022-12-03T21:49:54.785Z] {
"endpoint": {
"id": "enqueueAtlistedEventsToRetire",
"project": "my-project",
"region": "us-central1",
"entryPoint": "enqueueAtlistedEventsToRetire",
"platform": "gcfv1",
"runtime": "nodejs14",
"scheduleTrigger": {
"schedule": "0,15,30,45 * * * *",
"timeZone": null,
"retryConfig": {
"maxBackoffSeconds": null,
"minBackoffSeconds": null,
"maxRetrySeconds": null,
"retryCount": null,
"maxDoublings": null
}
},
"labels": {
"deployment-tool": "cli-firebase"
},
"serviceAccount": null,
"ingressSettings": null,
"availableMemoryMb": 2048,
"timeoutSeconds": null,
"maxInstances": null,
"minInstances": null,
"vpc": null,
"environmentVariables": {
"FIREBASE_CONFIG": "{\"projectId\":\"my-project\",\"databaseURL\":\"https://my-project.firebaseio.com\",\"storageBucket\":\"my-project.appspot.com\",\"locationId\":\"us-central\"}",
"GCLOUD_PROJECT": "my-project",
"EVENTARC_CLOUD_EVENT_SOURCE": "projects/my-project/locations/us-central1/functions/upsertProEventInfoInTypesense"
},
"codebase": "default",
"securityLevel": "SECURE_ALWAYS",
"targetedByOnly": true,
"hash": "2a1b0fcfaf7a46ed932b2b3e5eea8f11c62140c5"
},
"op": "update",
"original": {
"name": "FirebaseError",
"children": [],
"exit": 1,
"message": "Build failed: npm ERR! Cannot read property '@babel/core' of undefined\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /www-data-home/.npm/_logs/2022-12-03T21_49_11_956Z-debug.log; Error ID: beaf8772",
"status": 3
}
}
[2022-12-03T21:49:54.785Z] {
"endpoint": {
"id": "retireAtlistedEvents",
"project": "my-project",
"region": "us-central1",
"entryPoint": "retireAtlistedEvents",
"platform": "gcfv1",
"runtime": "nodejs14",
"taskQueueTrigger": {
"rateLimits": {
"maxConcurrentDispatches": 6,
"maxDispatchesPerSecond": null
},
"retryConfig": {
"maxAttempts": 5,
"maxBackoffSeconds": null,
"minBackoffSeconds": 60,
"maxRetrySeconds": null,
"maxDoublings": null
}
},
"serviceAccount": null,
"ingressSettings": null,
"availableMemoryMb": 2048,
"timeoutSeconds": null,
"maxInstances": null,
"minInstances": null,
"vpc": null,
"environmentVariables": {
"FIREBASE_CONFIG": "{\"projectId\":\"my-project\",\"databaseURL\":\"https://my-project.firebaseio.com\",\"storageBucket\":\"my-project.appspot.com\",\"locationId\":\"us-central\"}",
"GCLOUD_PROJECT": "my-project",
"EVENTARC_CLOUD_EVENT_SOURCE": "projects/my-project/locations/us-central1/functions/upsertProEventInfoInTypesense"
},
"codebase": "default",
"securityLevel": "SECURE_OPTIONAL",
"targetedByOnly": true,
"hash": "2a1b0fcfaf7a46ed932b2b3e5eea8f11c62140c5",
"labels": {
"deployment-tool": "cli-firebase"
}
},
"op": "update",
"original": {
"name": "FirebaseError",
"children": [],
"exit": 1,
"message": "Build failed: npm ERR! Cannot read property '@babel/core' of undefined\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /www-data-home/.npm/_logs/2022-12-03T21_49_36_419Z-debug.log; Error ID: beaf8772",
"status": 3
}
}
Error: There was an error deploying functions:
- Error Failed to update function enqueueAtlistedEventsToRetire in region us-central1
- Error Failed to update function retireAtlistedEvents in region us-central1
This is my package.json file:
{
"name": "functions",
"type": "module",
"scripts": {
"build": "tsc",
"emulators:start": "firebase emulators:start",
"emulators:stop": "lsof -t -i:5000 -i:5001 -i:4030 -i:9099 -i:9001 -i:9199 -i:8091 -i:9090 | xargs kill -9",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"test": "mocha --reporter spec --timeout 10000",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "lib/index.js",
"dependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/runtime": "^7.2.0",
"@firebase/app-compat": "^0.1.28",
"@google-cloud/tasks": "^3.0.5",
"@types/rimraf": "^3.0.2",
"acorn": "^8.8.1",
"axios": "^0.27.2",
"chai": "^4.3.4",
"csv-parse": "^5.2.1",
"firebase-admin": "^11.3.0",
"firebase-functions": "^4.1.0",
"fs": "0.0.1-security",
"mocha": "^9.1.3",
"puppeteer": "^10.4.0",
"rimraf": "^3.0.2",
"typescript": "4.3.5",
"typesense": "^1.3.0"
},
"devDependencies": {
"firebase-functions-test": "^0.3.3"
},
"private": true
}
Please note that I also tried the latest versions of the @babel dependencies (which were not much newer) with no luck.
For your reference here are the cloud functions I was deploying:
export const retireAtlistedEvents = functions
.runWith( { memory: '2GB' })
.tasks.taskQueue({
retryConfig: {
maxAttempts: 5,
minBackoffSeconds: 60,
},
rateLimits: {
maxConcurrentDispatches: 6,
},
}).onDispatch(async (data) => {
const minEvent = data.minEvent as MinEventInfo;
functions.logger.log("THIS IS retireAtlistedEvents minEventsData Success minEvent", minEvent);
});
export const enqueueAtlistedEventsToRetire = functions
.runWith( { memory: '2GB' })
.pubsub
.schedule('0,15,30,45 * * * *').onRun(async context => {
const queue = getFunctions().taskQueue("retireAtlistedEvents");
const enqueues = [];
let minEvent: MinEventInfo = {
proId: "abcd",
eventId: "efgh"
}
enqueues.push(
queue.enqueue({minEvent: minEvent}, {
dispatchDeadlineSeconds: 20 // 20 seconds
}),
);
await Promise.all(enqueues)
.then(() => {
const exit: ExtendedExitMessage = {
exit: 0,
message: "enqueueAtlistedEventsToRetire success",
success: true,
};
return exit;
})
.catch(() => {
const exit: ExtendedExitMessage = {
exit: 1,
message: "enqueueAtlistedEventsToRetire success",
success: false,
};
return exit;
});
});
I am thinking there may be something like a v1 v2 mismatch, which I have been reading about. However, I am trying to keep everything v1 and when I go to my cloud functions, everything there says v1 for the above functions.
Any help is much appreciated.
A:
The error could be due to the issue while package installation of the property which is mentioned in the error log, as for this case it is babel core package which is shown undefined, as to prevent this you may try to re-install the package as below:
npm install @babel/core --save
Check for similar examples:
Cannot read property babel
npm throws exception cannot read property
Cannot read property https
| When deploying firebase cloud functions I get: Build failed: npm ERR! Cannot read property '@babel/core' of undefined | This has been the latest in a series of very frustrating errors I have been receiving the past
3 days with deploying my cloud functions.
When deploying I get:
firebase deploy --only "functions:retireAtlistedEvents,functions:enqueueAtlistedEventsToRetire"
=== Deploying to 'my-project'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build
> build
> tsc
β functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
β artifactregistry: required API artifactregistry.googleapis.com is enabled
β functions: required API cloudfunctions.googleapis.com is enabled
β functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
i functions: preparing functions directory for uploading...
i functions: packaged /home/wpghijsen/Programs/combinedInstance/treetopCombined/treetoprules/functions (188.31 KB) for uploading
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
i functions: ensuring required API cloudtasks.googleapis.com is enabled...
β functions: required API cloudscheduler.googleapis.com is enabled
β functions: required API cloudtasks.googleapis.com is enabled
β functions: functions folder uploaded successfully
i functions: updating Node.js 14 function enqueueAtlistedEventsToRetire(us-central1)...
i functions: updating Node.js 14 function retireAtlistedEvents(us-central1)...
Build failed: npm ERR! Cannot read property '@babel/core' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! /www-data-home/.npm/_logs/2022-12-03T21_14_11_382Z-debug.log; Error ID: beaf8772
Build failed: npm ERR! Cannot read property '@babel/core' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! /www-data-home/.npm/_logs/2022-12-03T21_14_54_517Z-debug.log; Error ID: beaf8772
Functions deploy had errors with the following functions:
enqueueAtlistedEventsToRetire(us-central1)
retireAtlistedEvents(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions:
- Error Failed to update function enqueueAtlistedEventsToRetire in region us-central1
- Error Failed to update function retireAtlistedEvents in region us-central1
I did the --debug option and got this for output before failure
https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense 404
[2022-12-03T21:49:54.764Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/upsert_pro_event_info_in_typesense\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.766Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data 404
[2022-12-03T21:49:54.766Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/set_users_geo_coded_address_data\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.767Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events 404
[2022-12-03T21:49:54.767Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/retire_atlisted_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.769Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event 404
[2022-12-03T21:49:54.770Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/pro_cancel_atlisted_pro_event\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.776Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat 404
[2022-12-03T21:49:54.776Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/archive_chat\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.778Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat 404
[2022-12-03T21:49:54.778Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/initialize_chat\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.779Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn 404
[2022-12-03T21:49:54.779Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/is_atlisted_and_claimed_cloud_fxn\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.780Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data 404
[2022-12-03T21:49:54.780Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_manage_format_initial_atlisted_data\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.781Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events 404
[2022-12-03T21:49:54.781Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/request_multiple_atlisted_pro_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.781Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count 404
[2022-12-03T21:49:54.781Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/get_at_listed_doc_count\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.783Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn 404
[2022-12-03T21:49:54.783Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/adjust_atlisted_pro_event_open_slots_cloud_fxn\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.783Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events 404
[2022-12-03T21:49:54.783Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/remove_request_multiple_atlisted_pro_events\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.784Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape 404
[2022-12-03T21:49:54.784Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/schedule_scrape\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.784Z] <<< [apiv2][status] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense 404
[2022-12-03T21:49:54.784Z] <<< [apiv2][body] DELETE https://artifactregistry.googleapis.com/v1beta2/projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense {"error":{"code":404,"message":"Package \"projects/my-project/locations/us-central1/repositories/gcf-artifacts/packages/update_user_info_in_typesense\" was not found.","status":"NOT_FOUND"}}
[2022-12-03T21:49:54.785Z] Functions deploy failed.
[2022-12-03T21:49:54.785Z] {
"endpoint": {
"id": "enqueueAtlistedEventsToRetire",
"project": "my-project",
"region": "us-central1",
"entryPoint": "enqueueAtlistedEventsToRetire",
"platform": "gcfv1",
"runtime": "nodejs14",
"scheduleTrigger": {
"schedule": "0,15,30,45 * * * *",
"timeZone": null,
"retryConfig": {
"maxBackoffSeconds": null,
"minBackoffSeconds": null,
"maxRetrySeconds": null,
"retryCount": null,
"maxDoublings": null
}
},
"labels": {
"deployment-tool": "cli-firebase"
},
"serviceAccount": null,
"ingressSettings": null,
"availableMemoryMb": 2048,
"timeoutSeconds": null,
"maxInstances": null,
"minInstances": null,
"vpc": null,
"environmentVariables": {
"FIREBASE_CONFIG": "{\"projectId\":\"my-project\",\"databaseURL\":\"https://my-project.firebaseio.com\",\"storageBucket\":\"my-project.appspot.com\",\"locationId\":\"us-central\"}",
"GCLOUD_PROJECT": "my-project",
"EVENTARC_CLOUD_EVENT_SOURCE": "projects/my-project/locations/us-central1/functions/upsertProEventInfoInTypesense"
},
"codebase": "default",
"securityLevel": "SECURE_ALWAYS",
"targetedByOnly": true,
"hash": "2a1b0fcfaf7a46ed932b2b3e5eea8f11c62140c5"
},
"op": "update",
"original": {
"name": "FirebaseError",
"children": [],
"exit": 1,
"message": "Build failed: npm ERR! Cannot read property '@babel/core' of undefined\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /www-data-home/.npm/_logs/2022-12-03T21_49_11_956Z-debug.log; Error ID: beaf8772",
"status": 3
}
}
[2022-12-03T21:49:54.785Z] {
"endpoint": {
"id": "retireAtlistedEvents",
"project": "my-project",
"region": "us-central1",
"entryPoint": "retireAtlistedEvents",
"platform": "gcfv1",
"runtime": "nodejs14",
"taskQueueTrigger": {
"rateLimits": {
"maxConcurrentDispatches": 6,
"maxDispatchesPerSecond": null
},
"retryConfig": {
"maxAttempts": 5,
"maxBackoffSeconds": null,
"minBackoffSeconds": 60,
"maxRetrySeconds": null,
"maxDoublings": null
}
},
"serviceAccount": null,
"ingressSettings": null,
"availableMemoryMb": 2048,
"timeoutSeconds": null,
"maxInstances": null,
"minInstances": null,
"vpc": null,
"environmentVariables": {
"FIREBASE_CONFIG": "{\"projectId\":\"my-project\",\"databaseURL\":\"https://my-project.firebaseio.com\",\"storageBucket\":\"my-project.appspot.com\",\"locationId\":\"us-central\"}",
"GCLOUD_PROJECT": "my-project",
"EVENTARC_CLOUD_EVENT_SOURCE": "projects/my-project/locations/us-central1/functions/upsertProEventInfoInTypesense"
},
"codebase": "default",
"securityLevel": "SECURE_OPTIONAL",
"targetedByOnly": true,
"hash": "2a1b0fcfaf7a46ed932b2b3e5eea8f11c62140c5",
"labels": {
"deployment-tool": "cli-firebase"
}
},
"op": "update",
"original": {
"name": "FirebaseError",
"children": [],
"exit": 1,
"message": "Build failed: npm ERR! Cannot read property '@babel/core' of undefined\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /www-data-home/.npm/_logs/2022-12-03T21_49_36_419Z-debug.log; Error ID: beaf8772",
"status": 3
}
}
Error: There was an error deploying functions:
- Error Failed to update function enqueueAtlistedEventsToRetire in region us-central1
- Error Failed to update function retireAtlistedEvents in region us-central1
This is my package.json file:
{
"name": "functions",
"type": "module",
"scripts": {
"build": "tsc",
"emulators:start": "firebase emulators:start",
"emulators:stop": "lsof -t -i:5000 -i:5001 -i:4030 -i:9099 -i:9001 -i:9199 -i:8091 -i:9090 | xargs kill -9",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"test": "mocha --reporter spec --timeout 10000",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "lib/index.js",
"dependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/runtime": "^7.2.0",
"@firebase/app-compat": "^0.1.28",
"@google-cloud/tasks": "^3.0.5",
"@types/rimraf": "^3.0.2",
"acorn": "^8.8.1",
"axios": "^0.27.2",
"chai": "^4.3.4",
"csv-parse": "^5.2.1",
"firebase-admin": "^11.3.0",
"firebase-functions": "^4.1.0",
"fs": "0.0.1-security",
"mocha": "^9.1.3",
"puppeteer": "^10.4.0",
"rimraf": "^3.0.2",
"typescript": "4.3.5",
"typesense": "^1.3.0"
},
"devDependencies": {
"firebase-functions-test": "^0.3.3"
},
"private": true
}
Please note that I also tried the latest versions of the @babel dependencies (which were not much newer) with no luck.
For your reference here are the cloud functions I was deploying:
export const retireAtlistedEvents = functions
.runWith( { memory: '2GB' })
.tasks.taskQueue({
retryConfig: {
maxAttempts: 5,
minBackoffSeconds: 60,
},
rateLimits: {
maxConcurrentDispatches: 6,
},
}).onDispatch(async (data) => {
const minEvent = data.minEvent as MinEventInfo;
functions.logger.log("THIS IS retireAtlistedEvents minEventsData Success minEvent", minEvent);
});
export const enqueueAtlistedEventsToRetire = functions
.runWith( { memory: '2GB' })
.pubsub
.schedule('0,15,30,45 * * * *').onRun(async context => {
const queue = getFunctions().taskQueue("retireAtlistedEvents");
const enqueues = [];
let minEvent: MinEventInfo = {
proId: "abcd",
eventId: "efgh"
}
enqueues.push(
queue.enqueue({minEvent: minEvent}, {
dispatchDeadlineSeconds: 20 // 20 seconds
}),
);
await Promise.all(enqueues)
.then(() => {
const exit: ExtendedExitMessage = {
exit: 0,
message: "enqueueAtlistedEventsToRetire success",
success: true,
};
return exit;
})
.catch(() => {
const exit: ExtendedExitMessage = {
exit: 1,
message: "enqueueAtlistedEventsToRetire success",
success: false,
};
return exit;
});
});
I am thinking there may be something like a v1 v2 mismatch, which I have been reading about. However, I am trying to keep everything v1 and when I go to my cloud functions, everything there says v1 for the above functions.
Any help is much appreciated.
| [
"The error could be due to the issue while package installation of the property which is mentioned in the error log, as for this case it is babel core package which is shown undefined, as to prevent this you may try to re-install the package as below:\nnpm install @babel/core --save\nCheck for similar examples:\n\nCannot read property babel\nnpm throws exception cannot read property\nCannot read property https\n\n"
] | [
0
] | [] | [] | [
"babel_core",
"firebase",
"google_cloud_functions",
"npm"
] | stackoverflow_0074671138_babel_core_firebase_google_cloud_functions_npm.txt |
Q:
Kentico 13 .NET Core MVC Routing Patters
I have the following code in my Startup.cs
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller}/{action}/{id?}"
);
Routing doesn't work for the following method in the controller and returns 404
public async Task<ActionResult> Index(int id)
{
}
The url I'm trying to navigate is
/home/our-villages/property/100
However, it's working fine without the parameter value '100'. It hits the controller action in this case.
/home/our-villages/property
I believe I'm missing something in reagards to setting up the routing with parameters here. Any idea?
A:
Have you tried making the id parameter for the method optional?
Try doing this
public async Task<ActionResult> Index(int id = 0)
{
}
or
public async Task<ActionResult> Index(int? id)
{
}
| Kentico 13 .NET Core MVC Routing Patters | I have the following code in my Startup.cs
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller}/{action}/{id?}"
);
Routing doesn't work for the following method in the controller and returns 404
public async Task<ActionResult> Index(int id)
{
}
The url I'm trying to navigate is
/home/our-villages/property/100
However, it's working fine without the parameter value '100'. It hits the controller action in this case.
/home/our-villages/property
I believe I'm missing something in reagards to setting up the routing with parameters here. Any idea?
| [
"Have you tried making the id parameter for the method optional?\nTry doing this\npublic async Task<ActionResult> Index(int id = 0)\n{\n}\n\nor\npublic async Task<ActionResult> Index(int? id)\n{\n}\n\n"
] | [
0
] | [] | [] | [
"kentico",
"kentico_13"
] | stackoverflow_0074567849_kentico_kentico_13.txt |
Q:
Remotely controlling passwords with python
I wrote a code that does a long automatic work for the game with python. I will convert this code to exe and send it to people, but I will give a password with a certain lifetime for them to use. At the same time, when I send this application to everyone, I have to remotely check passwords, if necessary, I have to delete them before they expire. How can I perform this remote password check?
For example, let's say I threw this exe to someone and gave a password to open it. Is there a way to remotely control it and delete it before it expires if necessary?
A:
It sounds like you are looking for a way to remotely manage the passwords that are used to access your Python application. There are a few different ways you could do this, depending on your specific needs and the resources that are available to you.
One approach you could take is to create a server that manages the passwords and provides an API for your application to access. Your application could then use this API to authenticate users and check the status of their passwords. If necessary, you could also use this API to remotely delete passwords or disable access for specific users.
Alternatively, you could also use a cloud service such as AWS or Azure to manage the passwords and provide an API for your application to access. This would allow you to take advantage of the scalability and reliability of a cloud platform, and would also provide you with tools for managing and securing the passwords.
I hope this helps! Let me know if you have any other questions.
| Remotely controlling passwords with python | I wrote a code that does a long automatic work for the game with python. I will convert this code to exe and send it to people, but I will give a password with a certain lifetime for them to use. At the same time, when I send this application to everyone, I have to remotely check passwords, if necessary, I have to delete them before they expire. How can I perform this remote password check?
For example, let's say I threw this exe to someone and gave a password to open it. Is there a way to remotely control it and delete it before it expires if necessary?
| [
"It sounds like you are looking for a way to remotely manage the passwords that are used to access your Python application. There are a few different ways you could do this, depending on your specific needs and the resources that are available to you.\nOne approach you could take is to create a server that manages the passwords and provides an API for your application to access. Your application could then use this API to authenticate users and check the status of their passwords. If necessary, you could also use this API to remotely delete passwords or disable access for specific users.\nAlternatively, you could also use a cloud service such as AWS or Azure to manage the passwords and provide an API for your application to access. This would allow you to take advantage of the scalability and reliability of a cloud platform, and would also provide you with tools for managing and securing the passwords.\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074674905_python.txt |
Q:
How to change default discount in python using classes and inheriance?
I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have access on it.
class A:
def __init__(self, x, y, discount=0):
self.discount=0
if self.discount>0:
discount = self.discount
else:
discount=0
self.discount=discount
self.x=x
self.y=y
self.discount=discount
discount=5
class B(A):
def __init__ (self,x,y,z):
super().__init__(x,y)
B.z=z
B.discount=5
class C(A):
def __init__ (self,x,y,a):
super().__init__(x,y)
C.a=a
C.discount = 10
a = y*10
one=A(1,2)
print(one.x)
print(one.discount)
two = B(1,2,3)
print(two.x)
print(two.z)
print(two.discount)
three = C(4,5,6)
print(three.x)
print(three.discount)
Output:
1
0
1
3
0
4
0
Tried to do some calculations and integrate methods, but it only works for methoid but not on the class, as you can see, the discount is set to 0 and doesn't change.
A:
The constructor of your A class seems quite confusing. If the only thing you need is to check if the discount parameter is greater than 0 and set it to your instance's discount variable, you can simplify your code like this:
class A:
def __init__(self, x, y, discount=0):
self.discount=0
if discount>0:
self.discount = discount
self.x=x
self.y=y
Moreover, when you try to modify an instance variable in a subclass, you can still use self:
class B(A):
def __init__ (self,x,y,z):
super().__init__(x,y)
self.z=z
self.discount=5
class C(A):
def __init__ (self,x,y,a):
super().__init__(x,y)
self.a=a
self.discount = 10
a = y*10
Running the commands again, you 'll get:
1
0
1
3
5
4
10
You can find more about instance and class variables here and inheritance here.
| How to change default discount in python using classes and inheriance? | I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have access on it.
class A:
def __init__(self, x, y, discount=0):
self.discount=0
if self.discount>0:
discount = self.discount
else:
discount=0
self.discount=discount
self.x=x
self.y=y
self.discount=discount
discount=5
class B(A):
def __init__ (self,x,y,z):
super().__init__(x,y)
B.z=z
B.discount=5
class C(A):
def __init__ (self,x,y,a):
super().__init__(x,y)
C.a=a
C.discount = 10
a = y*10
one=A(1,2)
print(one.x)
print(one.discount)
two = B(1,2,3)
print(two.x)
print(two.z)
print(two.discount)
three = C(4,5,6)
print(three.x)
print(three.discount)
Output:
1
0
1
3
0
4
0
Tried to do some calculations and integrate methods, but it only works for methoid but not on the class, as you can see, the discount is set to 0 and doesn't change.
| [
"The constructor of your A class seems quite confusing. If the only thing you need is to check if the discount parameter is greater than 0 and set it to your instance's discount variable, you can simplify your code like this:\nclass A:\n def __init__(self, x, y, discount=0):\n self.discount=0\n if discount>0:\n self.discount = discount\n self.x=x\n self.y=y\n\nMoreover, when you try to modify an instance variable in a subclass, you can still use self:\nclass B(A):\n def __init__ (self,x,y,z):\n super().__init__(x,y)\n self.z=z\n self.discount=5\n \nclass C(A):\n def __init__ (self,x,y,a):\n super().__init__(x,y) \n self.a=a\n self.discount = 10\n a = y*10\n\nRunning the commands again, you 'll get:\n1\n0\n1\n3\n5\n4\n10\n\nYou can find more about instance and class variables here and inheritance here.\n"
] | [
0
] | [] | [] | [
"attributes",
"class",
"inheritance",
"oop",
"python"
] | stackoverflow_0074675515_attributes_class_inheritance_oop_python.txt |
Q:
How to disable a part of CSS code if it is not supported in a browser?
The @property CSS rule is a new addition in the CSS world, which is not yet supported in Firefox and some other browsers. I am trying to create a doughnut chart using CSS, where I try to animate it using the @property rule since, background-image cannot be directly animated.
But, since this at-rule is not supported everywhere, the colored portion of the chart does not show up properly (say, on Firefox) and I would like to disable all the animation functionality along with the unsupported @property rule when the browser does not support it, and just make it work without the animations.
Is there a way to conditionally set the code like an if statement in CSS? [SCSS would be fine too!]
@property --percent-inner {
syntax: "<percentage>";
inherits: false;
initial-value: 0%;
}
.graph {
position: relative;
height: 200px;
width: 200px;
border-radius: 1000px;
display: flex;
justify-content: center;
align-items: center;
animation: 1000ms ease-in-out forwards emerge;
--percent-inner: 0;
background-image: conic-gradient(var(--color) var(--percent-inner), #bbb 0%);
}
@keyframes emerge {
from {
--percent-inner: 0%;
}
to {
--percent-inner: var(--percent);
}
}
.graph::before {
position: absolute;
content: "";
height: 150px;
width: 150px;
background: #fff;
border-radius: 1000px;
}
<div class="graph" style="--color: #8F00FF; --percent: 78%;"></div>
Bibliography:
Reference Codepen (resolved)
MDN Docs for @property rule
Related
A:
Write the code differently.
I used mask to replace the pseudo element but it's irrelevant to the initial question
@property --percent {
syntax: "<percentage>";
inherits: false;
initial-value: 0%;
}
.graph {
height: 200px;
width: 200px;
border-radius: 50%;
animation: 1000ms ease-in-out forwards emerge;
background-image: conic-gradient(var(--color) var(--percent), #bbb 0%);
-webkit-mask: radial-gradient(50% 50%,#0000 calc(99% - 25px),#000 calc(100% - 25px));
}
@keyframes emerge {
from {
--percent: 0%;
}
}
<div class="graph" style="--color: #8F00FF; --percent: 78%;"></div>
| How to disable a part of CSS code if it is not supported in a browser? | The @property CSS rule is a new addition in the CSS world, which is not yet supported in Firefox and some other browsers. I am trying to create a doughnut chart using CSS, where I try to animate it using the @property rule since, background-image cannot be directly animated.
But, since this at-rule is not supported everywhere, the colored portion of the chart does not show up properly (say, on Firefox) and I would like to disable all the animation functionality along with the unsupported @property rule when the browser does not support it, and just make it work without the animations.
Is there a way to conditionally set the code like an if statement in CSS? [SCSS would be fine too!]
@property --percent-inner {
syntax: "<percentage>";
inherits: false;
initial-value: 0%;
}
.graph {
position: relative;
height: 200px;
width: 200px;
border-radius: 1000px;
display: flex;
justify-content: center;
align-items: center;
animation: 1000ms ease-in-out forwards emerge;
--percent-inner: 0;
background-image: conic-gradient(var(--color) var(--percent-inner), #bbb 0%);
}
@keyframes emerge {
from {
--percent-inner: 0%;
}
to {
--percent-inner: var(--percent);
}
}
.graph::before {
position: absolute;
content: "";
height: 150px;
width: 150px;
background: #fff;
border-radius: 1000px;
}
<div class="graph" style="--color: #8F00FF; --percent: 78%;"></div>
Bibliography:
Reference Codepen (resolved)
MDN Docs for @property rule
Related
| [
"Write the code differently.\nI used mask to replace the pseudo element but it's irrelevant to the initial question\n\n\n@property --percent {\n syntax: \"<percentage>\";\n inherits: false;\n initial-value: 0%;\n}\n\n.graph {\n height: 200px;\n width: 200px;\n border-radius: 50%;\n animation: 1000ms ease-in-out forwards emerge;\n background-image: conic-gradient(var(--color) var(--percent), #bbb 0%);\n -webkit-mask: radial-gradient(50% 50%,#0000 calc(99% - 25px),#000 calc(100% - 25px));\n}\n\n@keyframes emerge {\n from {\n --percent: 0%;\n }\n}\n<div class=\"graph\" style=\"--color: #8F00FF; --percent: 78%;\"></div>\n\n\n\n"
] | [
3
] | [] | [] | [
"css",
"css_variables",
"html"
] | stackoverflow_0074675338_css_css_variables_html.txt |
Q:
Spring Boot how to return my own validation constraint error messages
I need to have my own error response body when something goes wrong with my request and I am trying to use the @NotEmpty constraint message attribute to return the error message,
This is my class that returns the error message using the body that I need:
package c.m.nanicolina.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler(value = {MissingServletRequestParameterException.class})
public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
ApiError apiError = new ApiError(ex.getMessage(), ex.getMessage(), 1000);
return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
}
}
With this CustomResponseEntityExceptionHandler I can return my own response body in case of validation errors.
What I am trying now is to get the message from the validation constraints.
This is my controller with the NotEmpty constraint:
package c.m.nanicolina.controllers;
import c.m.nanicolina.models.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
@RestController
public class MinimumStockController {
@RequestMapping(value = "/minimumstock")
public Product product(
@RequestParam(value = "product.sku") @NotEmpty(message = "Product.sku cannot be empty") String sku,
@RequestParam(value = "stock.branch.id") String branchID) {
return null;
}
}
In my exception, I can't find a way to get that message Product.sku cannot be empty and show it in my error response.
I have also checked the class MissingServletRequestParameterException and there is the method getMessage which is returning the default message.
A:
Yes it is doable & spring very well supports it. You are just missing some configuration to enable it in spring.
Use Spring@Validated annotation to enable spring to validate controller
Handle ConstraintViolationException in your ControllerAdvice to catch all failed validation messages.
Mark required=false in @RequestParam, so it will not throw MissingServletRequestParameterException and rather move to next step of constraint validation.
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler
public ResponseEntity<ApiError> handle(ConstraintViolationException exception) {
//you will get all javax failed validation, can be more than one
//so you can return the set of error messages or just the first message
String errorMessage = new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage();
ApiError apiError = new ApiError(errorMessage, errorMessage, 1000);
return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
}
}
@RestController
@Validated
public class MinimumStockController {
@RequestMapping(value = "/minimumstock")
public Product product(
@RequestParam(value = "product.sku", required=false) @NotEmpty(message = "Product.sku cannot be empty") String sku,
@RequestParam(value = "stock.branch.id", required=false) String branchID) {
return null;
}
}
NOTE: MissingServletRequestParameterException won't have access to javax validation messages, as it is thrown before constraint validation occurs in the request lifecycle.
A:
If this can help, I found the solution for this issue here: https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/
You have to add this method to your CustomResponseEntityExceptionHandler class:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ErrorMessage error = new ErrorMessage(new Date(), details.toString());
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
A:
You should put this on your handler.
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler(value = { MissingServletRequestParameterException.class })
public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
String message = ex.getParameterName() + " cannot be empty";
ApiError apiError = new ApiError(ex.getMessage(), message, 1000);
return new ResponseEntity < ApiError > (apiError, null, HttpStatus.BAD_REQUEST);
}
}
UPDATE
I don't know how you can get a default message, but as a workaround, you could do the validation on your controller and throw an custom exception if the parameter is empty, then handle in your CustomResponseEntityExceptionHandler.
Something like the following:
Set required=false
@RequestMapping(value = "/minimumstock")
public Product product(@RequestParam(required = false) String sku, @RequestParam(value = "stock.branch.id") String branchID) {
if (StringUtils.isEmpty(sku))
throw YourException("Product.sku cannot be empty");
return null;
}
A:
Yes it is possible. Do this:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ArgumentsErrorResponseDTO> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
ServiceException exception = ServiceException.wrap(ex, ErrorCode.FIELD_VALIDATION);
BindingResult results = ex.getBindingResult();
for (FieldError e: results.getFieldErrors()) {
exception.addLog(e.getDefaultMessage(), e.getField());
}
// log details in log
log.error("Invalid arguments exception: {}", exception.logWithDetails(), exception);
return ResponseEntity.status(exception.getErrorCode().getHttpStatus())
.body(ArgumentsErrorResponseDTO.builder()
.code(exception.getErrorCode().getCode())
.message(exception.getMessage())
.details(exception.getProperties())
.build());
}
A:
Use @ExceptionHandler(MethodArgumentNotValidException.class)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> validationHandler(MethodArgumentNotValidException exception) {
HashMap<String, Object> resObj = new HashMap<String, Object>();
String errorMsg = "validation is failed!";
if (exception.getErrorCount() > 0) {
List <String> errorDetails = new ArrayList<>();
for (ObjectError error : exception.getBindingResult().getAllErrors()) {
errorDetails.add(error.getDefaultMessage());
}
if (errorDetails.size() > 0) errorMsg = errorDetails.get(0);
}
resObj.put("status", GlobalConst.BAD_REQUEST_CODE);
resObj.put("message", errorMsg);
return new ResponseEntity<>(resObj, HttpStatus.OK);
}
| Spring Boot how to return my own validation constraint error messages | I need to have my own error response body when something goes wrong with my request and I am trying to use the @NotEmpty constraint message attribute to return the error message,
This is my class that returns the error message using the body that I need:
package c.m.nanicolina.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {
@ExceptionHandler(value = {MissingServletRequestParameterException.class})
public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
ApiError apiError = new ApiError(ex.getMessage(), ex.getMessage(), 1000);
return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
}
}
With this CustomResponseEntityExceptionHandler I can return my own response body in case of validation errors.
What I am trying now is to get the message from the validation constraints.
This is my controller with the NotEmpty constraint:
package c.m.nanicolina.controllers;
import c.m.nanicolina.models.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
@RestController
public class MinimumStockController {
@RequestMapping(value = "/minimumstock")
public Product product(
@RequestParam(value = "product.sku") @NotEmpty(message = "Product.sku cannot be empty") String sku,
@RequestParam(value = "stock.branch.id") String branchID) {
return null;
}
}
In my exception, I can't find a way to get that message Product.sku cannot be empty and show it in my error response.
I have also checked the class MissingServletRequestParameterException and there is the method getMessage which is returning the default message.
| [
"Yes it is doable & spring very well supports it. You are just missing some configuration to enable it in spring.\n\n\nUse Spring@Validated annotation to enable spring to validate controller\nHandle ConstraintViolationException in your ControllerAdvice to catch all failed validation messages.\nMark required=false in @RequestParam, so it will not throw MissingServletRequestParameterException and rather move to next step of constraint validation.\n\n\n@ControllerAdvice\npublic class CustomResponseEntityExceptionHandler {\n\n @ExceptionHandler\n public ResponseEntity<ApiError> handle(ConstraintViolationException exception) {\n //you will get all javax failed validation, can be more than one\n //so you can return the set of error messages or just the first message\n String errorMessage = new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage();\n ApiError apiError = new ApiError(errorMessage, errorMessage, 1000); \n return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);\n }\n}\n\n\n\n@RestController\n@Validated\npublic class MinimumStockController {\n\n @RequestMapping(value = \"/minimumstock\")\n public Product product(\n @RequestParam(value = \"product.sku\", required=false) @NotEmpty(message = \"Product.sku cannot be empty\") String sku,\n @RequestParam(value = \"stock.branch.id\", required=false) String branchID) {\n return null;\n }\n}\n\nNOTE: MissingServletRequestParameterException won't have access to javax validation messages, as it is thrown before constraint validation occurs in the request lifecycle.\n",
"If this can help, I found the solution for this issue here: https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/\nYou have to add this method to your CustomResponseEntityExceptionHandler class:\n @Override\n protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {\n List<String> details = new ArrayList<>();\n for(ObjectError error : ex.getBindingResult().getAllErrors()) {\n details.add(error.getDefaultMessage());\n }\n ErrorMessage error = new ErrorMessage(new Date(), details.toString());\n return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);\n }\n\n",
"You should put this on your handler.\n@ControllerAdvice\npublic class CustomResponseEntityExceptionHandler {\n\n @ExceptionHandler(value = { MissingServletRequestParameterException.class })\n public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {\n String message = ex.getParameterName() + \" cannot be empty\";\n ApiError apiError = new ApiError(ex.getMessage(), message, 1000);\n return new ResponseEntity < ApiError > (apiError, null, HttpStatus.BAD_REQUEST);\n }\n}\n\nUPDATE\nI don't know how you can get a default message, but as a workaround, you could do the validation on your controller and throw an custom exception if the parameter is empty, then handle in your CustomResponseEntityExceptionHandler.\nSomething like the following:\nSet required=false\n@RequestMapping(value = \"/minimumstock\")\npublic Product product(@RequestParam(required = false) String sku, @RequestParam(value = \"stock.branch.id\") String branchID) {\n if (StringUtils.isEmpty(sku)) \n throw YourException(\"Product.sku cannot be empty\");\n\n return null;\n}\n\n",
"Yes it is possible. Do this:\n@ExceptionHandler(MethodArgumentNotValidException.class)\npublic ResponseEntity<ArgumentsErrorResponseDTO> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {\n\n ServiceException exception = ServiceException.wrap(ex, ErrorCode.FIELD_VALIDATION);\n BindingResult results = ex.getBindingResult();\n for (FieldError e: results.getFieldErrors()) {\n exception.addLog(e.getDefaultMessage(), e.getField());\n }\n // log details in log\n log.error(\"Invalid arguments exception: {}\", exception.logWithDetails(), exception);\n return ResponseEntity.status(exception.getErrorCode().getHttpStatus())\n .body(ArgumentsErrorResponseDTO.builder()\n .code(exception.getErrorCode().getCode())\n .message(exception.getMessage())\n .details(exception.getProperties())\n .build());\n}\n\n",
"\n\nUse @ExceptionHandler(MethodArgumentNotValidException.class)\n@ExceptionHandler(MethodArgumentNotValidException.class)\n public ResponseEntity<Object> validationHandler(MethodArgumentNotValidException exception) {\n HashMap<String, Object> resObj = new HashMap<String, Object>();\n String errorMsg = \"validation is failed!\";\n if (exception.getErrorCount() > 0) {\n List <String> errorDetails = new ArrayList<>();\n for (ObjectError error : exception.getBindingResult().getAllErrors()) {\n errorDetails.add(error.getDefaultMessage());\n }\n\n if (errorDetails.size() > 0) errorMsg = errorDetails.get(0);\n }\n \n resObj.put(\"status\", GlobalConst.BAD_REQUEST_CODE);\n resObj.put(\"message\", errorMsg);\n return new ResponseEntity<>(resObj, HttpStatus.OK);\n }\n\n"
] | [
20,
1,
0,
0,
0
] | [] | [] | [
"exception_handling",
"java",
"query_parameters",
"spring_boot",
"validation"
] | stackoverflow_0051331679_exception_handling_java_query_parameters_spring_boot_validation.txt |
Q:
Calculate distance between a point and a line segment in latitude and longitude
I have a line segments defined with a start and an end point:
A:
x1 = 10.7196405787775
y1 = 59.9050401935882
B:
x2 = 10.7109989561813
y2 = 59.9018650448204
where x defines longitude and y defines latitude.
I also have a point:
P:
x0 = 10.6542116666667
y0 = 59.429105
How do I compute the shortest distance between the line segment and the point? I know how to do this in Cartesian coordinates, but not in long/lat coordinates.
A:
Here is an implementation of a formula off Wikipedia:
def distance(p0, p1, p2): # p3 is the point
x0, y0 = p0
x1, y1 = p1
x2, y2 = p2
nom = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)
denom = ((y2 - y1)**2 + (x2 - x1) ** 2) ** 0.5
result = nom / denom
return result
print distance((0, 0), (3, 4), (5, 6))
# should probably test less obvious cases
assert 1 == distance((0, 0), (1, 1), (2, 1))
# change 0.001 to whatever accuracy you demand on testing.
# Notice that it's never perfect...
assert 0.5 * (2 ** 0.5) - distance((0, 0), (1, 0), (0, 1)) < 0.001
A:
To compute the shortest distance between a line segment and a point in longitude/latitude coordinates using Python, you can first convert the longitude/latitude coordinates to Cartesian coordinates using a map projection. Then, you can use the formula for the shortest distance between a line segment and a point in Cartesian coordinates to calculate the distance.
Here is an example of how you can do this using the pyproj package to convert the coordinates and the math module to calculate the distance:
import pyproj
import math
# Define the start and end points of the line segment
x1 = 10.7196405787775
y1 = 59.9050401935882
x2 = 10.7109989561813
y2 = 59.9018650448204
# Define the point
x0 = 10.6542116666667
y0 = 59.429105
# Create a map projection object
projection = pyproj.Proj(init="epsg:4326")
# Convert the longitude/latitude coordinates to Cartesian coordinates
x1, y1 = projection(x1, y1)
x2, y2 = projection(x2, y2)
x0, y0 = projection(x0, y0)
# Compute the shortest distance between the line segment and the point
dx = x2 - x1
dy = y2 - y1
t = ((x0 - x1) * dx + (y0 - y1) * dy) / (dx * dx + dy * dy)
if t < 0:
# The shortest distance is the distance between the point and the start point of the line segment
distance = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
elif t > 1:
# The shortest distance is the distance between the point and the end point of the line segment
distance = math.sqrt((x2 - x0) ** 2 + (y2 - y0) ** 2)
else:
# The shortest distance is the distance between the point and the line segment
x = x1 + t * dx
y = y1 + t * dy
distance = math.sqrt((x - x0) ** 2 + (y - y0) ** 2)
# Print the distance
print(distance)
In this example, the longitude/latitude coordinates are converted to Cartesian coordinates using the pyproj package and a map projection with the EPSG code 4326 (WGS 84). Then, the formula for the shortest distance between a line segment and a point in Cartesian coordinates is used to calculate the distance
A:
Using the helpful Python geocoding library geopy, and the formula for the midpoint of a great circle from Chris Veness's geodesy formulae, we can find the distance between a great circle arc and a given point:
from math import sin, cos, atan2, sqrt, degrees, radians, pi
from geopy.distance import great_circle as distance
from geopy.point import Point
def midpoint(a, b):
a_lat, a_lon = radians(a.latitude), radians(a.longitude)
b_lat, b_lon = radians(b.latitude), radians(b.longitude)
delta_lon = b_lon - a_lon
B_x = cos(b_lat) * cos(delta_lon)
B_y = cos(b_lat) * sin(delta_lon)
mid_lat = atan2(
sin(a_lat) + sin(b_lat),
sqrt(((cos(a_lat) + B_x)**2 + B_y**2))
)
mid_lon = a_lon + atan2(B_y, cos(a_lat) + B_x)
# Normalise
mid_lon = (mid_lon + 3*pi) % (2*pi) - pi
return Point(latitude=degrees(mid_lat), longitude=degrees(mid_lon))
Which in this example gives:
# Example:
a = Point(latitude=59.9050401935882, longitude=10.7196405787775)
b = Point(latitude=59.9018650448204, longitude=10.7109989561813)
p = Point(latitude=59.429105, longitude=10.6542116666667)
d = distance(midpoint(a, b), p)
print d.km
# 52.8714586903
| Calculate distance between a point and a line segment in latitude and longitude | I have a line segments defined with a start and an end point:
A:
x1 = 10.7196405787775
y1 = 59.9050401935882
B:
x2 = 10.7109989561813
y2 = 59.9018650448204
where x defines longitude and y defines latitude.
I also have a point:
P:
x0 = 10.6542116666667
y0 = 59.429105
How do I compute the shortest distance between the line segment and the point? I know how to do this in Cartesian coordinates, but not in long/lat coordinates.
| [
"Here is an implementation of a formula off Wikipedia:\ndef distance(p0, p1, p2): # p3 is the point\n x0, y0 = p0\n x1, y1 = p1\n x2, y2 = p2\n nom = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)\n denom = ((y2 - y1)**2 + (x2 - x1) ** 2) ** 0.5\n result = nom / denom\n return result\n\nprint distance((0, 0), (3, 4), (5, 6))\n\n# should probably test less obvious cases\nassert 1 == distance((0, 0), (1, 1), (2, 1))\n# change 0.001 to whatever accuracy you demand on testing.\n# Notice that it's never perfect...\nassert 0.5 * (2 ** 0.5) - distance((0, 0), (1, 0), (0, 1)) < 0.001\n\n",
"To compute the shortest distance between a line segment and a point in longitude/latitude coordinates using Python, you can first convert the longitude/latitude coordinates to Cartesian coordinates using a map projection. Then, you can use the formula for the shortest distance between a line segment and a point in Cartesian coordinates to calculate the distance.\nHere is an example of how you can do this using the pyproj package to convert the coordinates and the math module to calculate the distance:\nimport pyproj\nimport math\n\n# Define the start and end points of the line segment\nx1 = 10.7196405787775\ny1 = 59.9050401935882\nx2 = 10.7109989561813\ny2 = 59.9018650448204\n\n# Define the point\nx0 = 10.6542116666667\ny0 = 59.429105\n\n# Create a map projection object\nprojection = pyproj.Proj(init=\"epsg:4326\")\n\n# Convert the longitude/latitude coordinates to Cartesian coordinates\nx1, y1 = projection(x1, y1)\nx2, y2 = projection(x2, y2)\nx0, y0 = projection(x0, y0)\n\n# Compute the shortest distance between the line segment and the point\ndx = x2 - x1\ndy = y2 - y1\n\nt = ((x0 - x1) * dx + (y0 - y1) * dy) / (dx * dx + dy * dy)\n\nif t < 0:\n # The shortest distance is the distance between the point and the start point of the line segment\n distance = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)\n\nelif t > 1:\n # The shortest distance is the distance between the point and the end point of the line segment\n distance = math.sqrt((x2 - x0) ** 2 + (y2 - y0) ** 2)\n\nelse:\n # The shortest distance is the distance between the point and the line segment\n x = x1 + t * dx\n y = y1 + t * dy\n distance = math.sqrt((x - x0) ** 2 + (y - y0) ** 2)\n\n# Print the distance\nprint(distance)\n\nIn this example, the longitude/latitude coordinates are converted to Cartesian coordinates using the pyproj package and a map projection with the EPSG code 4326 (WGS 84). Then, the formula for the shortest distance between a line segment and a point in Cartesian coordinates is used to calculate the distance\n",
"Using the helpful Python geocoding library geopy, and the formula for the midpoint of a great circle from Chris Veness's geodesy formulae, we can find the distance between a great circle arc and a given point:\nfrom math import sin, cos, atan2, sqrt, degrees, radians, pi\nfrom geopy.distance import great_circle as distance\nfrom geopy.point import Point\n\n\ndef midpoint(a, b):\n a_lat, a_lon = radians(a.latitude), radians(a.longitude)\n b_lat, b_lon = radians(b.latitude), radians(b.longitude)\n delta_lon = b_lon - a_lon\n B_x = cos(b_lat) * cos(delta_lon)\n B_y = cos(b_lat) * sin(delta_lon)\n mid_lat = atan2(\n sin(a_lat) + sin(b_lat),\n sqrt(((cos(a_lat) + B_x)**2 + B_y**2))\n )\n mid_lon = a_lon + atan2(B_y, cos(a_lat) + B_x)\n # Normalise\n mid_lon = (mid_lon + 3*pi) % (2*pi) - pi\n return Point(latitude=degrees(mid_lat), longitude=degrees(mid_lon))\n\nWhich in this example gives:\n# Example:\na = Point(latitude=59.9050401935882, longitude=10.7196405787775)\nb = Point(latitude=59.9018650448204, longitude=10.7109989561813)\np = Point(latitude=59.429105, longitude=10.6542116666667)\n\nd = distance(midpoint(a, b), p)\nprint d.km\n# 52.8714586903\n\n"
] | [
0,
0,
-1
] | [] | [] | [
"latitude_longitude",
"python"
] | stackoverflow_0027461634_latitude_longitude_python.txt |
Q:
EVP_KEY get raw private key in C
Good day,
I have been trying to do a simple exercise where I could generate the public and the private key using RSA with Openssl and print them both. My code looks something like this:
size_t private_key_len = KEY_LENGTH;
EVP_PKEY *pkey = EVP_RSA_gen(KEY_LENGTH);
if (pkey == NULL)
{
fprintf(stderr, "error: rsa gen\n");
ERR_print_errors_fp(stderr);
return NULL;
}
unsigned char *private_key = calloc((KEY_LENGTH + 1),sizeof(unsigned char));
EVP_PKEY_get_raw_private_key(pkey, private_key, &private_key_len);
printf("%s\n",private_key);
So normally it should print the private key, given that KEY_LENGTH is 1024, however it just prints nothing (The zeros initialized by calloc). I have tried with malloc too, the result is similar the only difference being that it prints 0xBE.
So basically the array private_key is never filled, and I have no idea why.
What am I missing to make this work?
Thanks in advance!
A:
Quoting the man page with emphasis changed:
EVP_PKEY_get_raw_private_key() fills the buffer provided by priv with raw private key data. The size of the priv buffer should be in *len on entry to the function, and on exit *len is updated with the number of bytes actually written. If the buffer priv is NULL then *len is populated with the number of bytes required to hold the key. The calling application is responsible for ensuring that the buffer is large enough to receive the private key data. This function only works for algorithms that support raw private keys. Currently this is: EVP_PKEY_HMAC, EVP_PKEY_POLY1305, EVP_PKEY_SIPHASH, EVP_PKEY_X25519, EVP_PKEY_ED25519, EVP_PKEY_X448 or EVP_PKEY_ED448.
Notice that RSA is not one of the supported algorithms.
You can "print" an RSA key either by converting each of its components (n,e,d,p,q,dp,dp,qinv) to printable form, which EVP_PKEY_print_private does for you, or getting the encoding of the whole key in PEM which is 'printable' in the sense of being printable and typable characters, but not the sense of being easily understood (or copied or created) by people, with PEM_write_PrivateKey or PEM_write_RSAPrivateKey.
Also, the value you pass to EVP_RSA_gen is in bits, but the size of displayed components of an RSA key (other than e, which is small) will be in hex or decimal digits or (mostly) base64 characters.
| EVP_KEY get raw private key in C | Good day,
I have been trying to do a simple exercise where I could generate the public and the private key using RSA with Openssl and print them both. My code looks something like this:
size_t private_key_len = KEY_LENGTH;
EVP_PKEY *pkey = EVP_RSA_gen(KEY_LENGTH);
if (pkey == NULL)
{
fprintf(stderr, "error: rsa gen\n");
ERR_print_errors_fp(stderr);
return NULL;
}
unsigned char *private_key = calloc((KEY_LENGTH + 1),sizeof(unsigned char));
EVP_PKEY_get_raw_private_key(pkey, private_key, &private_key_len);
printf("%s\n",private_key);
So normally it should print the private key, given that KEY_LENGTH is 1024, however it just prints nothing (The zeros initialized by calloc). I have tried with malloc too, the result is similar the only difference being that it prints 0xBE.
So basically the array private_key is never filled, and I have no idea why.
What am I missing to make this work?
Thanks in advance!
| [
"Quoting the man page with emphasis changed:\n\nEVP_PKEY_get_raw_private_key() fills the buffer provided by priv with raw private key data. The size of the priv buffer should be in *len on entry to the function, and on exit *len is updated with the number of bytes actually written. If the buffer priv is NULL then *len is populated with the number of bytes required to hold the key. The calling application is responsible for ensuring that the buffer is large enough to receive the private key data. This function only works for algorithms that support raw private keys. Currently this is: EVP_PKEY_HMAC, EVP_PKEY_POLY1305, EVP_PKEY_SIPHASH, EVP_PKEY_X25519, EVP_PKEY_ED25519, EVP_PKEY_X448 or EVP_PKEY_ED448.\n\nNotice that RSA is not one of the supported algorithms.\nYou can \"print\" an RSA key either by converting each of its components (n,e,d,p,q,dp,dp,qinv) to printable form, which EVP_PKEY_print_private does for you, or getting the encoding of the whole key in PEM which is 'printable' in the sense of being printable and typable characters, but not the sense of being easily understood (or copied or created) by people, with PEM_write_PrivateKey or PEM_write_RSAPrivateKey.\nAlso, the value you pass to EVP_RSA_gen is in bits, but the size of displayed components of an RSA key (other than e, which is small) will be in hex or decimal digits or (mostly) base64 characters.\n"
] | [
1
] | [] | [] | [
"c",
"openssl",
"rsa"
] | stackoverflow_0074675205_c_openssl_rsa.txt |
Q:
Is it possible to check the return of a function, if true assigning the value to a variable?
For something simple like:
def my_func(x):
if x == 4:
return 25
return False
result = my_func(4)
if result:
print(result)
is it possible to check the result and assign the return value in one line?
Something like:
if my_func(4) => x:
print(x)
A:
Sure, a ternary expression can be used, such as:
return 25 if x == 4 else False
| Is it possible to check the return of a function, if true assigning the value to a variable? | For something simple like:
def my_func(x):
if x == 4:
return 25
return False
result = my_func(4)
if result:
print(result)
is it possible to check the result and assign the return value in one line?
Something like:
if my_func(4) => x:
print(x)
| [
"Sure, a ternary expression can be used, such as:\nreturn 25 if x == 4 else False\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074675550_python_python_3.x.txt |
Q:
How can I manage dotfiles repo push/pull automatically? (or w/ scripts)
Introduction
Hi
I'm trying to manage my dotfiles repository between my linux computer and my codeberg account
I have my dotfiles repo on my computer
I'd like to use the automatic push/pull changes function of codeberg
The repository on codeberg is private
Problems
Do you know any way of solving these 2 issues?
Problem 1 #Security #Syncing #Authorization
How can I manage to clone/push/pull (make changes in general) on the codeberg repository without having the credentials asked each time? I've heard about "setting SSH keys" but I don't know how to do that
This could create me problems, when trying to set up automation scripts
Problem 2
How can I setup an automatic push/pull repository, without having conflicts?
For example, if I change 2 files, or even the same one, one on my computer through emacs, and the other one on codeberg through my browser.
I could just sync the org files and not the actual data folders
I'd like to know how to avoid completely those situations (to reduce the number of things to manage) or a safe way to manage this things, through codeberg functions or bash script which I'd run through Cron
Informations
Codeberg
Based on Gitea
Gnu Stow
While trying to clone the private repo, I cannot get rid of the credential asking phase, plus, I have no idea how to avoid conflicts between commit versions (local-codeberg)
A:
To clone, push, and pull from your private Codeberg repository without having to enter your credentials each time, you can use SSH keys to authenticate your computer with Codeberg. This will allow you to securely access your repository without having to enter your credentials every time.
Here's how to set up SSH keys on Codeberg:
Generate an SSH key on your local computer by running the following command:
ssh-keygen -t rsa
Copy the contents of the newly-generated id_rsa.pub file, which contains your public SSH key, to your clipboard.
Go to the "SSH Keys" section of your Codeberg account settings and click the "Add SSH Key" button.
Paste your public SSH key into the "Key" field and give your key a name in the "Title" field. Click the "Add key" button to save your key.
Clone your Codeberg repository using the SSH URL, which should be in the format [email protected]:/.git.
git clone [email protected]:<username>/<repo>.git
You should now be able to push and pull changes to your Codeberg repository without having to enter your credentials each time.
To avoid conflicts between local and Codeberg versions of your repository, you can use the git pull command with the --rebase flag. This will apply your local changes on top of the changes pulled from Codeberg, instead of merging them, which can help prevent conflicts.
One way to avoid conflicts in your dotfiles repository is to use a tool called Gnu Stow. Gnu Stow is a command-line tool that allows you to manage your dotfiles in a modular way. It creates symlinks from the files in your dotfiles repository to the appropriate locations in your home directory.
For example, if you have a .bashrc file in your dotfiles repository, you can use Gnu Stow to create a symlink from that file to the .bashrc file in your home directory. This way, any changes you make to the file in your dotfiles repository will be automatically reflected in your home directory.
To use Gnu Stow, first clone your dotfiles repository to your computer. Then, navigate to the directory where your dotfiles are stored and run the following command:
stow <directory>
Replace with the name of the directory containing the files you want to symlink. For example, if your dotfiles repository contains a directory called bash with a .bashrc file, you would run the following command:
stow bash
This will create a symlink from the .bashrc file in the bash directory to the .bashrc file in your home directory.
Once you have set up Gnu Stow, you can use it to manage your dotfiles repository and avoid conflicts. Whenever you make a change to a file in your dotfiles repository, simply run the stow command again to update the symlinks. This will ensure that your dotfiles are always up to date and in sync between your computer and your codeberg repository.
| How can I manage dotfiles repo push/pull automatically? (or w/ scripts) | Introduction
Hi
I'm trying to manage my dotfiles repository between my linux computer and my codeberg account
I have my dotfiles repo on my computer
I'd like to use the automatic push/pull changes function of codeberg
The repository on codeberg is private
Problems
Do you know any way of solving these 2 issues?
Problem 1 #Security #Syncing #Authorization
How can I manage to clone/push/pull (make changes in general) on the codeberg repository without having the credentials asked each time? I've heard about "setting SSH keys" but I don't know how to do that
This could create me problems, when trying to set up automation scripts
Problem 2
How can I setup an automatic push/pull repository, without having conflicts?
For example, if I change 2 files, or even the same one, one on my computer through emacs, and the other one on codeberg through my browser.
I could just sync the org files and not the actual data folders
I'd like to know how to avoid completely those situations (to reduce the number of things to manage) or a safe way to manage this things, through codeberg functions or bash script which I'd run through Cron
Informations
Codeberg
Based on Gitea
Gnu Stow
While trying to clone the private repo, I cannot get rid of the credential asking phase, plus, I have no idea how to avoid conflicts between commit versions (local-codeberg)
| [
"To clone, push, and pull from your private Codeberg repository without having to enter your credentials each time, you can use SSH keys to authenticate your computer with Codeberg. This will allow you to securely access your repository without having to enter your credentials every time.\nHere's how to set up SSH keys on Codeberg:\nGenerate an SSH key on your local computer by running the following command:\nssh-keygen -t rsa\n\nCopy the contents of the newly-generated id_rsa.pub file, which contains your public SSH key, to your clipboard.\nGo to the \"SSH Keys\" section of your Codeberg account settings and click the \"Add SSH Key\" button.\nPaste your public SSH key into the \"Key\" field and give your key a name in the \"Title\" field. Click the \"Add key\" button to save your key.\nClone your Codeberg repository using the SSH URL, which should be in the format [email protected]:/.git.\ngit clone [email protected]:<username>/<repo>.git\n\nYou should now be able to push and pull changes to your Codeberg repository without having to enter your credentials each time.\nTo avoid conflicts between local and Codeberg versions of your repository, you can use the git pull command with the --rebase flag. This will apply your local changes on top of the changes pulled from Codeberg, instead of merging them, which can help prevent conflicts.\nOne way to avoid conflicts in your dotfiles repository is to use a tool called Gnu Stow. Gnu Stow is a command-line tool that allows you to manage your dotfiles in a modular way. It creates symlinks from the files in your dotfiles repository to the appropriate locations in your home directory.\nFor example, if you have a .bashrc file in your dotfiles repository, you can use Gnu Stow to create a symlink from that file to the .bashrc file in your home directory. This way, any changes you make to the file in your dotfiles repository will be automatically reflected in your home directory.\nTo use Gnu Stow, first clone your dotfiles repository to your computer. Then, navigate to the directory where your dotfiles are stored and run the following command:\nstow <directory>\n\nReplace with the name of the directory containing the files you want to symlink. For example, if your dotfiles repository contains a directory called bash with a .bashrc file, you would run the following command:\nstow bash\n\nThis will create a symlink from the .bashrc file in the bash directory to the .bashrc file in your home directory.\nOnce you have set up Gnu Stow, you can use it to manage your dotfiles repository and avoid conflicts. Whenever you make a change to a file in your dotfiles repository, simply run the stow command again to update the symlinks. This will ensure that your dotfiles are always up to date and in sync between your computer and your codeberg repository.\n"
] | [
0
] | [] | [] | [
"devops",
"dotfiles",
"git",
"stow"
] | stackoverflow_0074675520_devops_dotfiles_git_stow.txt |
Q:
pyenv: python :command not found
I want to use Python3 with pyenv.
$ pyenv root
/Users/asari/.pyenv
$ pyenv versions
system
2.7.15
3.6.2
3.6.3
3.6.4
* 3.6.6 (set by /Users/asari/workspace/hoge/.python-version)
$ python -V
pyenv: python: command not found
The `python' command exists in these Python versions:
2.7.15
but, python command not found.
I read it in .pyenv/shims/python, thought that there was not python in .pyenv/versions/3.6.6/bin/, but I did not know why python was missing.
$ pwd
/Users/asari/.pyenv/versions/3.6.6/bin
$ ls -la
total 12096
drwxr-xr-x 19 asari staff 608 8 16 00:51 .
drwxr-xr-x 6 asari staff 192 8 16 00:51 ..
lrwxr-xr-x 1 asari staff 8 8 16 00:51 2to3 -> 2to3-3.6
-rwxr-xr-x 1 asari staff 135 8 16 00:51 2to3-3.6
-rwxr-xr-x 1 asari staff 276 8 16 00:51 easy_install-3.6
lrwxr-xr-x 1 asari staff 7 8 16 00:51 idle3 -> idle3.6
-rwxr-xr-x 1 asari staff 133 8 16 00:51 idle3.6
-rwxr-xr-x 1 asari staff 258 8 16 00:51 pip3
-rwxr-xr-x 1 asari staff 258 8 16 00:51 pip3.6
lrwxr-xr-x 1 asari staff 8 8 16 00:51 pydoc3 -> pydoc3.6
-rwxr-xr-x 1 asari staff 118 8 16 00:51 pydoc3.6
lrwxr-xr-x 1 asari staff 9 8 16 00:51 python3 -> python3.6
lrwxr-xr-x 1 asari staff 16 8 16 00:51 python3-config -> python3.6-config
-rwxr-xr-x 2 asari staff 3078944 8 16 00:51 python3.6
lrwxr-xr-x 1 asari staff 17 8 16 00:51 python3.6-config -> python3.6m-config
-rwxr-xr-x 2 asari staff 3078944 8 16 00:51 python3.6m
-rwxr-xr-x 1 asari staff 2076 8 16 00:51 python3.6m-config
lrwxr-xr-x 1 asari staff 10 8 16 00:51 pyvenv -> pyvenv-3.6
-rwxr-xr-x 1 asari staff 475 8 16 00:51 pyvenv-3.6
$PATH
$ echo $PATH | perl -p -e 's/:/\n/g'
/Users/asari/.pyenv/shims
/Users/asari/.pyenv/bin
/Users/asari/.rbenv/shims
/Users/asari/.cargo/bin
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
install log
$ pyenv install 3.6.6
python-build: use openssl from homebrew
python-build: use readline from homebrew
Downloading Python-3.6.6.tar.xz...
-> https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
Installing Python-3.6.6...
python-build: use readline from homebrew
Installed Python-3.6.6 to /Users/asari/.pyenv/versions/3.6.6
$ pyenv --version
pyenv 1.2.7
$ brew list | grep py
python
python@2
pyenv clone and installed from github(I have not installed pyenv on brew)
.zshrc
# python
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
Thank you for your time.
UPDATE
I created python 's symlink, and python worked.
Why is there no python s symlink?
(I was wondering if install failed, I am running install and uninstall many times
create symlink
$ pwd
/Users/asari/.pyenv/versions/3.6.6/bin
$ ln -s python3 python
Work,
$ pwd
/Users/asari/workspace/hoge
$ python -V
Python 3.6.6
A:
Added to ~/.bashrc
alias python="$(pyenv which python)"
alias pip="$(pyenv which pip)"
A:
Under mac OS 10.15
We add the following to .bashrc file or .zshrc file
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/shims:$PATH"
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
A:
on MAC OS. I solved it by adding to below lines to the ~/.bash_profile
At the terminal call vi ~/.bash_profile
Insert 2 below lines
alias python="$(pyenv which python)"
alias pip="$(pyenv which pip)"
Call this command after saving above file source ~/.bash_profile
A:
For me the config in my .zshrc.local file needed an update. Using the info on configure your shell's environment for Pyenv page I changed the pyenv init stuff to this:
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
if [ -n "$PS1" -a -n "$BASH_VERSION" ]; then source ~/.bashrc; fi
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
A:
when I use python with pyenv, show me:
/Users/zhezhezhu/.pyenv/shims/python: line 21: /usr/local/Cellar/pyenv/1.2.18/libexec/pyenv: No such file or directory
I solved it by : pyenv rehash
A:
I was using Ubuntu 20.04 and it seemed like I had wrongly setup the commands in my ~/.bashrc. I followed configure your shell's environment for Pyenv:
If your ~/.profile sources ~/.bashrc (Debian, Ubuntu, Mint):
# the sed invocation inserts the lines at the start of the file
# after any initial comment lines
sed -Ei -e '/^([^#]|$)/ {a \
export PYENV_ROOT="$HOME/.pyenv"
a \
export PATH="$PYENV_ROOT/bin:$PATH"
a \
' -e ':a' -e '$!{n;ba};}' ~/.profile
echo 'eval "$(pyenv init --path)"' >>~/.profile
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
If you are using MacOs, Fedora, or CentOS, please follow the link above. The commands may also change in the future, depending on pyenv/os/distributions udpates.
A:
On MacOS Montery 12.5 there is no longer a python binary in /usr/local/bin/. A quick fix is to ensure that is a default ref that points to the system python3.
ln -s python3 /usr/local/bin/python
A:
I was experiencing the same error. I just had to follow the error message pyenv was saying:
Note: See 'pyenv help global' for tips on allowing both...
Which made me run the following command:
pyenv global 2.7.18 3.10.6
which are versions existing in my pyenv versions
A:
Using Ubuntu 18.04 environment, using pyenv 2.2.5 here is what you need to update the .bashrc:
export PATH="~/.pyenv/bin:$PATH"
if ! command -v pyenv &> /dev/null
then # If no pyenv is found
echo "pyenv could not be found, cannot initialize env"
else
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
fi
If you are using some other OS, then it may be that you need to add this to another dotfile such as .bash_profile. For more detailed info, check out the docs: https://github.com/pyenv/pyenv#basic-github-checkout
A:
add below 2 lines to ./zshrc IS THE ANSWER, GIVEN THAT you already have eval "$(pyenv init -)"
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/shims:$PATH"
Trick is to let shims play its deserving part.
A:
I solved it.
I used the following grep option in .zshrc
export GREP_OPTIONS = '- color = auto'
It seems that even if ANSI escape code was included in the search result of grep used in pyenv, it was not used properly as a character string.
I think that you all know, but GREP_OPTIONS is deprecated.
A:
In my case shims were initialized correctly:
$ which python
/home/me/.pyenv/shims/python
Yet, similar to richard-domingo's answer, I was seeing:
$ pyenv which python
pyenv: python: command not found
The `python' command exists in these Python versions:
3.8.13
Note: See 'pyenv help global' for tips on allowing both
python2 and python3 to be found.
The problem here was that the active python version was system, and my system python3 did not have a python alias (symlink).
Two options to fix this:
either create a python symlink for the system's python3, similar to cmcginty's answer, for example:
ln -s python3 /usr/bin/python
or explicitly set the python version to one of the versions listed in the error message, using e.g. pyenv shell, pyenv local, or pyenv global, depending on your use-case. This is explained in the documentation and discussed here and here.
In this case
pyenv local 3.8.13
whould create/modify a .python-version file in the current directory.
It is really worth reading the following section in the docs: Understanding Python version selection.
A:
I had previously installed pyenv and then installed my required python distribution as follows:
pyenv install 3.7.10
To remove subsequent pyenv: python :command not found errors -- I first had to run:
pyenv global 3.7.10
That solved my problem.
| pyenv: python :command not found | I want to use Python3 with pyenv.
$ pyenv root
/Users/asari/.pyenv
$ pyenv versions
system
2.7.15
3.6.2
3.6.3
3.6.4
* 3.6.6 (set by /Users/asari/workspace/hoge/.python-version)
$ python -V
pyenv: python: command not found
The `python' command exists in these Python versions:
2.7.15
but, python command not found.
I read it in .pyenv/shims/python, thought that there was not python in .pyenv/versions/3.6.6/bin/, but I did not know why python was missing.
$ pwd
/Users/asari/.pyenv/versions/3.6.6/bin
$ ls -la
total 12096
drwxr-xr-x 19 asari staff 608 8 16 00:51 .
drwxr-xr-x 6 asari staff 192 8 16 00:51 ..
lrwxr-xr-x 1 asari staff 8 8 16 00:51 2to3 -> 2to3-3.6
-rwxr-xr-x 1 asari staff 135 8 16 00:51 2to3-3.6
-rwxr-xr-x 1 asari staff 276 8 16 00:51 easy_install-3.6
lrwxr-xr-x 1 asari staff 7 8 16 00:51 idle3 -> idle3.6
-rwxr-xr-x 1 asari staff 133 8 16 00:51 idle3.6
-rwxr-xr-x 1 asari staff 258 8 16 00:51 pip3
-rwxr-xr-x 1 asari staff 258 8 16 00:51 pip3.6
lrwxr-xr-x 1 asari staff 8 8 16 00:51 pydoc3 -> pydoc3.6
-rwxr-xr-x 1 asari staff 118 8 16 00:51 pydoc3.6
lrwxr-xr-x 1 asari staff 9 8 16 00:51 python3 -> python3.6
lrwxr-xr-x 1 asari staff 16 8 16 00:51 python3-config -> python3.6-config
-rwxr-xr-x 2 asari staff 3078944 8 16 00:51 python3.6
lrwxr-xr-x 1 asari staff 17 8 16 00:51 python3.6-config -> python3.6m-config
-rwxr-xr-x 2 asari staff 3078944 8 16 00:51 python3.6m
-rwxr-xr-x 1 asari staff 2076 8 16 00:51 python3.6m-config
lrwxr-xr-x 1 asari staff 10 8 16 00:51 pyvenv -> pyvenv-3.6
-rwxr-xr-x 1 asari staff 475 8 16 00:51 pyvenv-3.6
$PATH
$ echo $PATH | perl -p -e 's/:/\n/g'
/Users/asari/.pyenv/shims
/Users/asari/.pyenv/bin
/Users/asari/.rbenv/shims
/Users/asari/.cargo/bin
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
install log
$ pyenv install 3.6.6
python-build: use openssl from homebrew
python-build: use readline from homebrew
Downloading Python-3.6.6.tar.xz...
-> https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
Installing Python-3.6.6...
python-build: use readline from homebrew
Installed Python-3.6.6 to /Users/asari/.pyenv/versions/3.6.6
$ pyenv --version
pyenv 1.2.7
$ brew list | grep py
python
python@2
pyenv clone and installed from github(I have not installed pyenv on brew)
.zshrc
# python
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
Thank you for your time.
UPDATE
I created python 's symlink, and python worked.
Why is there no python s symlink?
(I was wondering if install failed, I am running install and uninstall many times
create symlink
$ pwd
/Users/asari/.pyenv/versions/3.6.6/bin
$ ln -s python3 python
Work,
$ pwd
/Users/asari/workspace/hoge
$ python -V
Python 3.6.6
| [
"Added to ~/.bashrc\nalias python=\"$(pyenv which python)\"\nalias pip=\"$(pyenv which pip)\"\n\n",
"Under mac OS 10.15\nWe add the following to .bashrc file or .zshrc file\nexport PYENV_ROOT=\"$HOME/.pyenv\"\nexport PATH=\"$PYENV_ROOT/shims:$PATH\"\n\nif which pyenv > /dev/null; then eval \"$(pyenv init -)\"; fi\n\n",
"on MAC OS. I solved it by adding to below lines to the ~/.bash_profile\nAt the terminal call vi ~/.bash_profile\nInsert 2 below lines\nalias python=\"$(pyenv which python)\"\nalias pip=\"$(pyenv which pip)\"\n\nCall this command after saving above file source ~/.bash_profile\n",
"For me the config in my .zshrc.local file needed an update. Using the info on configure your shell's environment for Pyenv page I changed the pyenv init stuff to this:\nexport PYENV_ROOT=\"$HOME/.pyenv\"\nexport PATH=\"$PYENV_ROOT/bin:$PATH\"\neval \"$(pyenv init --path)\"\nif [ -n \"$PS1\" -a -n \"$BASH_VERSION\" ]; then source ~/.bashrc; fi\n\neval \"$(pyenv init -)\"\neval \"$(pyenv virtualenv-init -)\"\n\n",
"when I use python with pyenv, show me:\n/Users/zhezhezhu/.pyenv/shims/python: line 21: /usr/local/Cellar/pyenv/1.2.18/libexec/pyenv: No such file or directory\n\nI solved it by : pyenv rehash\n",
"I was using Ubuntu 20.04 and it seemed like I had wrongly setup the commands in my ~/.bashrc. I followed configure your shell's environment for Pyenv:\nIf your ~/.profile sources ~/.bashrc (Debian, Ubuntu, Mint):\n# the sed invocation inserts the lines at the start of the file\n# after any initial comment lines\nsed -Ei -e '/^([^#]|$)/ {a \\\nexport PYENV_ROOT=\"$HOME/.pyenv\"\na \\\nexport PATH=\"$PYENV_ROOT/bin:$PATH\"\na \\\n' -e ':a' -e '$!{n;ba};}' ~/.profile\necho 'eval \"$(pyenv init --path)\"' >>~/.profile\n\necho 'eval \"$(pyenv init -)\"' >> ~/.bashrc\n\nIf you are using MacOs, Fedora, or CentOS, please follow the link above. The commands may also change in the future, depending on pyenv/os/distributions udpates.\n",
"On MacOS Montery 12.5 there is no longer a python binary in /usr/local/bin/. A quick fix is to ensure that is a default ref that points to the system python3.\nln -s python3 /usr/local/bin/python\n\n",
"I was experiencing the same error. I just had to follow the error message pyenv was saying:\nNote: See 'pyenv help global' for tips on allowing both...\n\nWhich made me run the following command:\npyenv global 2.7.18 3.10.6\n\nwhich are versions existing in my pyenv versions\n",
"Using Ubuntu 18.04 environment, using pyenv 2.2.5 here is what you need to update the .bashrc:\nexport PATH=\"~/.pyenv/bin:$PATH\"\nif ! command -v pyenv &> /dev/null\nthen # If no pyenv is found \n echo \"pyenv could not be found, cannot initialize env\"\nelse\n eval \"$(pyenv init --path)\"\n eval \"$(pyenv init -)\"\n eval \"$(pyenv virtualenv-init -)\"\nfi\n\nIf you are using some other OS, then it may be that you need to add this to another dotfile such as .bash_profile. For more detailed info, check out the docs: https://github.com/pyenv/pyenv#basic-github-checkout\n",
"add below 2 lines to ./zshrc IS THE ANSWER, GIVEN THAT you already have eval \"$(pyenv init -)\"\nexport PYENV_ROOT=\"$HOME/.pyenv\"\nexport PATH=\"$PYENV_ROOT/shims:$PATH\"\n\nTrick is to let shims play its deserving part.\n",
"I solved it.\nI used the following grep option in .zshrc\nexport GREP_OPTIONS = '- color = auto'\n\nIt seems that even if ANSI escape code was included in the search result of grep used in pyenv, it was not used properly as a character string.\nI think that you all know, but GREP_OPTIONS is deprecated.\n",
"In my case shims were initialized correctly:\n$ which python\n/home/me/.pyenv/shims/python\n\nYet, similar to richard-domingo's answer, I was seeing:\n$ pyenv which python\npyenv: python: command not found\n\nThe `python' command exists in these Python versions:\n 3.8.13\n\nNote: See 'pyenv help global' for tips on allowing both\n python2 and python3 to be found.\n\nThe problem here was that the active python version was system, and my system python3 did not have a python alias (symlink).\nTwo options to fix this:\n\neither create a python symlink for the system's python3, similar to cmcginty's answer, for example:\nln -s python3 /usr/bin/python\n\n\nor explicitly set the python version to one of the versions listed in the error message, using e.g. pyenv shell, pyenv local, or pyenv global, depending on your use-case. This is explained in the documentation and discussed here and here.\nIn this case\npyenv local 3.8.13\n\nwhould create/modify a .python-version file in the current directory.\n\n\nIt is really worth reading the following section in the docs: Understanding Python version selection.\n",
"I had previously installed pyenv and then installed my required python distribution as follows:\npyenv install 3.7.10\n\nTo remove subsequent pyenv: python :command not found errors -- I first had to run:\npyenv global 3.7.10\n\nThat solved my problem.\n"
] | [
24,
8,
7,
6,
3,
2,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"pyenv",
"python"
] | stackoverflow_0051863225_pyenv_python.txt |
Q:
Can a deploy with multiple ReplicaSets run CMD different command?
I want to create few pods from same image (I have the Dockerfile) so i want to use ReplicaSets.
but the final CMD command need to be different for each container.
for exmple
(https://www.devspace.sh/docs/5.x/configuration/images/entrypoint-cmd):
image:
frontend:
image: john/appfrontend
cmd:
- run
- dev
And the other container will do:
image:
frontend:
image: john/appfrontend
cmd:
- run
- <new value>
Also I would like to move the CMD value from a list, so i would like the value there to be variable (it will be in a loop so each Pod will have to be created separately).
Is it possible?
A:
You can't directly do this as you've described it. A ReplicaSet manages some number of identical Pods, where the command, environment variables, and every other detail except for the Pod name are the same across every replica.
In practice you don't usually directly use ReplicaSets; instead, you create a Deployment, which creates one or more ReplicaSets, which create Pods. The same statement and mechanics apply to Deployments, though.
Since this is specifically in the context of a Helm chart, you can have two separate Deployment YAML files in your chart, but then use Helm templating to reduce the amount of code that needs to be repeated. You can add a helper template to templates/_helpers.tpl that contains most of the data for a container
# templates/_helpers.tpl
{{- define "myapp.container" -}}
image: my-image:{{ .Values.tag }}
env:
- name: FOO
value: bar
- name: ET
value: cetera
{{ end -}}
Now you can have two template Deployment files, but provide a separate command: for each.
# templates/deployment-one.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "myapp.name" . }}-one
labels:
{{ include "myapp.labels" . | indent 4 }}
spec:
replicas: {{ .Values.one.replicas }}
template:
metadata:
labels:
{{ include "myapp.labels" . | indent 8 }}
spec:
containers:
- name: frontend
{{ include "myapp.container" . | indent 10 }}
command:
- npm
- run
- dev
There is still a fair amount to copy and paste, but you should be able to cp the whole file. Most of the boilerplate is Kubernetes boilerplate and every Deployment will have these parts; little of it is specific to any given application.
If your image has a default CMD (this is good practice) then you can omit the command: override on one of the Deployments, and it will run that default CMD.
In the question you make specific reference to Dockerfile CMD. One important terminology difference is that Kubernetes command: overrides Docker ENTRYPOINT, and Kubernetes args: matches CMD. If you are using an entrypoint wrapper script, in this example you will need to provide args: instead of command: so that the wrapper is still invoked.
| Can a deploy with multiple ReplicaSets run CMD different command? | I want to create few pods from same image (I have the Dockerfile) so i want to use ReplicaSets.
but the final CMD command need to be different for each container.
for exmple
(https://www.devspace.sh/docs/5.x/configuration/images/entrypoint-cmd):
image:
frontend:
image: john/appfrontend
cmd:
- run
- dev
And the other container will do:
image:
frontend:
image: john/appfrontend
cmd:
- run
- <new value>
Also I would like to move the CMD value from a list, so i would like the value there to be variable (it will be in a loop so each Pod will have to be created separately).
Is it possible?
| [
"You can't directly do this as you've described it. A ReplicaSet manages some number of identical Pods, where the command, environment variables, and every other detail except for the Pod name are the same across every replica.\nIn practice you don't usually directly use ReplicaSets; instead, you create a Deployment, which creates one or more ReplicaSets, which create Pods. The same statement and mechanics apply to Deployments, though.\nSince this is specifically in the context of a Helm chart, you can have two separate Deployment YAML files in your chart, but then use Helm templating to reduce the amount of code that needs to be repeated. You can add a helper template to templates/_helpers.tpl that contains most of the data for a container\n# templates/_helpers.tpl\n{{- define \"myapp.container\" -}}\nimage: my-image:{{ .Values.tag }}\nenv:\n - name: FOO\n value: bar\n - name: ET\n value: cetera\n{{ end -}}\n\nNow you can have two template Deployment files, but provide a separate command: for each.\n# templates/deployment-one.yml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: {{ include \"myapp.name\" . }}-one\n labels:\n{{ include \"myapp.labels\" . | indent 4 }}\nspec:\n replicas: {{ .Values.one.replicas }}\n template:\n metadata:\n labels:\n{{ include \"myapp.labels\" . | indent 8 }}\n spec:\n containers:\n - name: frontend\n{{ include \"myapp.container\" . | indent 10 }}\n command:\n - npm\n - run\n - dev\n\nThere is still a fair amount to copy and paste, but you should be able to cp the whole file. Most of the boilerplate is Kubernetes boilerplate and every Deployment will have these parts; little of it is specific to any given application.\nIf your image has a default CMD (this is good practice) then you can omit the command: override on one of the Deployments, and it will run that default CMD.\nIn the question you make specific reference to Dockerfile CMD. One important terminology difference is that Kubernetes command: overrides Docker ENTRYPOINT, and Kubernetes args: matches CMD. If you are using an entrypoint wrapper script, in this example you will need to provide args: instead of command: so that the wrapper is still invoked.\n"
] | [
0
] | [] | [] | [
"kubernetes",
"kubernetes_helm"
] | stackoverflow_0074675015_kubernetes_kubernetes_helm.txt |
Q:
Problem when creating a map using Google Maps' API and geolocation
I have to create a map that returns the location of a client using Google Maps API, it's for an assignment.
The code works fine, it locates the longitude and latitude and prints it on screen, pbut when it's time to create the map throws me this error: message: "Map: Expected mapDiv of type Element but was passed null. name: InvalidValueError"
Does anyone know why that appears since I did specify mapDiv
map = new google.maps.Map(document.getElementById("map"), {center: {lat: latitud, lng: longitud}, zoom: 14});...
var longitud;
var latitud;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
latitud = crd.latitude
longitud = crd.longitude
document.getElementById("latitud").innerHTML = latitud
document.getElementById("longitud").innerHTML = longitud
};
function error(err) {
document.getElementById("map").innerHTML = ('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error);
function initMap(){
map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latitud, lng: longitud},
zoom: 14
});
}
.map{
margin: 0 auto;
width: 300px;
height: 300px;
}
<head>
<meta charset="utf-8">
<script type="text/javascript" src="funciones.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0dtNMb8xZh0aMLX4P-KiNccovF1w2tpM&callback=initMap"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tcuida</title>
</head>
<div class="paginaPrinc" id="paginaPrinc">
<div id="latitud"></div>
<div id="longitud"></div>
<div id="map" class="map"></div>
</div>
A:
This occurs when document.getElementById("map") returns null or type other than div.
map = new google.maps.Map(element, options)
The 1st parameter in the function expects element of div type
A:
I get a different error with the posted code: InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number, because the geolocation service is asynchronous, and the map is created before it returns a result.
You have a race condition between two asynchronous operations:
the load of the Google Maps Javascript API v3, which calls initMap
the return of the results of the geolocation service, which calls success
Best would be to remove the race condition, either have the geolocation function call initMap or have the initMap function make the geolocation request.
Example of the second option:
function initMap(){
navigator.geolocation.getCurrentPosition(success, error);
}
function success(pos) {
var crd = pos.coords;
latitud = crd.latitude
longitud = crd.longitude
document.getElementById("latitud").innerHTML = latitud
document.getElementById("longitud").innerHTML = longitud
map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latitud, lng: longitud},
zoom: 14
});
};
working example
proof of concept fiddle
code snippet:
var longitud;
var latitud;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
latitud = crd.latitude
longitud = crd.longitude
document.getElementById("latitud").innerHTML = latitud
document.getElementById("longitud").innerHTML = longitud
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: latitud,
lng: longitud
},
zoom: 14
});
};
function error(err) {
document.getElementById("map").innerHTML = ('ERROR(' + err.code + '): ' + err.message);
};
function initMap() {
navigator.geolocation.getCurrentPosition(success, error);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
.map,
.paginaPrinc {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div class="paginaPrinc" id="paginaPrinc">
<div id="latitud"></div>
<div id="longitud"></div>
<div id="map" class="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
A:
You need to add a div with id "map". Else document.getElementById("map") will return null so you will get that error.
<div id="map" style="width: auto; height: 550px; position: relative; overflow: hidden;"></div>
A:
when you try to get the element ID, need to fully load the page. Otherwise, in the script part, it cannot find the html element.
Correction: window.onload=function(){ inimap(){}}
| Problem when creating a map using Google Maps' API and geolocation | I have to create a map that returns the location of a client using Google Maps API, it's for an assignment.
The code works fine, it locates the longitude and latitude and prints it on screen, pbut when it's time to create the map throws me this error: message: "Map: Expected mapDiv of type Element but was passed null. name: InvalidValueError"
Does anyone know why that appears since I did specify mapDiv
map = new google.maps.Map(document.getElementById("map"), {center: {lat: latitud, lng: longitud}, zoom: 14});...
var longitud;
var latitud;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
latitud = crd.latitude
longitud = crd.longitude
document.getElementById("latitud").innerHTML = latitud
document.getElementById("longitud").innerHTML = longitud
};
function error(err) {
document.getElementById("map").innerHTML = ('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error);
function initMap(){
map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latitud, lng: longitud},
zoom: 14
});
}
.map{
margin: 0 auto;
width: 300px;
height: 300px;
}
<head>
<meta charset="utf-8">
<script type="text/javascript" src="funciones.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0dtNMb8xZh0aMLX4P-KiNccovF1w2tpM&callback=initMap"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tcuida</title>
</head>
<div class="paginaPrinc" id="paginaPrinc">
<div id="latitud"></div>
<div id="longitud"></div>
<div id="map" class="map"></div>
</div>
| [
"This occurs when document.getElementById(\"map\") returns null or type other than div.\nmap = new google.maps.Map(element, options)\nThe 1st parameter in the function expects element of div type\n",
"I get a different error with the posted code: InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number, because the geolocation service is asynchronous, and the map is created before it returns a result.\nYou have a race condition between two asynchronous operations:\n\nthe load of the Google Maps Javascript API v3, which calls initMap\nthe return of the results of the geolocation service, which calls success\n\nBest would be to remove the race condition, either have the geolocation function call initMap or have the initMap function make the geolocation request.\nExample of the second option:\nfunction initMap(){\n navigator.geolocation.getCurrentPosition(success, error);\n}\n\nfunction success(pos) {\n var crd = pos.coords;\n latitud = crd.latitude\n longitud = crd.longitude \n document.getElementById(\"latitud\").innerHTML = latitud \n document.getElementById(\"longitud\").innerHTML = longitud \n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: {lat: latitud, lng: longitud},\n zoom: 14\n });\n};\n\nworking example\nproof of concept fiddle\ncode snippet:\n\n\nvar longitud;\nvar latitud;\n\nvar options = {\n enableHighAccuracy: true,\n timeout: 5000,\n maximumAge: 0\n};\n\nfunction success(pos) {\n var crd = pos.coords;\n latitud = crd.latitude\n longitud = crd.longitude\n document.getElementById(\"latitud\").innerHTML = latitud\n document.getElementById(\"longitud\").innerHTML = longitud\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: {\n lat: latitud,\n lng: longitud\n },\n zoom: 14\n });\n};\n\nfunction error(err) {\n document.getElementById(\"map\").innerHTML = ('ERROR(' + err.code + '): ' + err.message);\n};\n\nfunction initMap() {\n navigator.geolocation.getCurrentPosition(success, error);\n}\n/* Always set the map height explicitly to define the size of the div\n * element that contains the map. */\n\n.map,\n.paginaPrinc {\n height: 80%;\n}\n\n\n/* Optional: Makes the sample page fill the window. */\n\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n<div class=\"paginaPrinc\" id=\"paginaPrinc\">\n <div id=\"latitud\"></div>\n <div id=\"longitud\"></div>\n <div id=\"map\" class=\"map\"></div>\n</div>\n<script src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap\" async defer></script>\n\n\n\n",
"You need to add a div with id \"map\". Else document.getElementById(\"map\") will return null so you will get that error.\n <div id=\"map\" style=\"width: auto; height: 550px; position: relative; overflow: hidden;\"></div>\n\n",
"when you try to get the element ID, need to fully load the page. Otherwise, in the script part, it cannot find the html element.\nCorrection: window.onload=function(){ inimap(){}}\n"
] | [
8,
3,
2,
0
] | [] | [] | [
"google_maps",
"html",
"javascript",
"maps"
] | stackoverflow_0062724548_google_maps_html_javascript_maps.txt |
Q:
ComputerCraft coroutine can't move turtles (1.19.2; Fabric)
I've tried to make a control panel for my mining turtle, so I got into using Lua coroutines, because I needed the turtle to listen even if it's currently mining, but every time I call function round() it won't continue. I tried to place print('test') in between every near lines of code and I found that the round() function works untill the turtle.turnLeft() part.
The turtle has following code:
rednet.open('right')
local status = 'None'
io.output(io.stdout)
io.input(io.stdin)
io.write('Control Panel ID: ')
local baseId = tonumber(io.read())
io.write('Blocks: ')
local blcks = tonumber(io.read())
function round()
turtle.dig()
--- Here the function stops ---
turtle.turnLeft()
turtle.dig()
turtle.forward()
turtle.turnRight()
turtle.dig()
turtle.digDown()
turtle.down()
turtle.dig()
turtle.turnRight()
turtle.dig()
turtle.forward()
turtle.turnLeft()
turtle.dig()
sleep(0.2)
end
function listen()
if true then
id, message = rednet.receive()
if message == 'down' then
print('Down!')
coroutine.resume(downCo, blcks)
elseif message == 'up' then
coroutine.resume(upCo, blcks)
elseif message == 'refuel' then
turtle.refuel()
elseif message == 'status' then
rednet.send(baseId, status)
elseif message == 'stop' then
print('Lol')
elseif message == 'fuel' then
rednet.send(baseId, turtle.getFuelLevel())
end
end
end
downCo = coroutine.create(function(blcks)
local a = 0
print('Going down! '..blcks)
status = 'Going down'
while a <= blcks do
a = a + 1
round()
end
local status = 'Done'
end)
upCo = coroutine.create(function(blcks)
local status = 'Going up'
for i = blcks,1,-1 do
turtle.digUp()
turtle.up()
end
local status = 'Done'
end)
while true do
listen()
end
I couldn't find any information about that the coroutines can't support turtle movement or anything like that
I tried to turn it into coroutine too, but it just happened to stuck at the same point.
A:
It looks like you are trying to use coroutines in your turtle's code, but you are not using them correctly. Coroutines are a way to allow your code to pause and resume, but they do not automatically run in parallel like threads do.
In your code, you are calling coroutine.resume to start the coroutine, but you are not yielding control back to the main thread at any point. This means that your coroutines will start and then immediately stop, because they have not yielded control back to the main thread.
To fix this, you will need to add a coroutine.yield call in your round function. This will allow the coroutine to pause and give control back to the main thread, so that other coroutines can run. Here is how your code could look with this change:
rednet.open('right')
local status = 'None'
io.output(io.stdout)
io.input(io.stdin)
io.write('Control Panel ID: ')
local baseId = tonumber(io.read())
io.write('Blocks: ')
local blcks = tonumber(io.read())
function round()
turtle.dig()
--- Here the function stops ---
turtle.turnLeft()
turtle.dig()
turtle.forward()
turtle.turnRight()
turtle.dig()
turtle.digDown()
turtle.down()
turtle.dig()
turtle.turnRight()
turtle.dig()
turtle.forward()
turtle.turnLeft()
turtle.dig()
coroutine.yield() -- Add this line to yield control back to the main thread
end
function listen()
if true then
id, message = rednet.receive()
if message == 'down' then
print('Down!')
coroutine.resume(downCo, blcks)
elseif message == 'up' then
coroutine.resume(upCo, blcks)
elseif message == 'refuel' then
turtle.refuel()
elseif message == 'status' then
rednet.send(baseId, status)
elseif message == 'stop' then
print('Lol')
elseif message == 'fuel' then
rednet.send(baseId, turtle.getFuelLevel())
end
end
end
downCo = coroutine.create(function(blcks)
local a = 0
print('Going down! '..blcks)
status = 'Going down'
while a <= blcks do
a = a + 1
round()
end
local status = 'Done'
end)
upCo = coroutine.create(function(blcks)
local status = 'Going up'
for i = blcks,1,-1 do
turtle.digUp()
turtle.up()
end
local status = 'Done'
end)
while true do
listen()
end
This should allow your coroutines to run in parallel and allow your turtle to move while it is listening for messages.
| ComputerCraft coroutine can't move turtles (1.19.2; Fabric) | I've tried to make a control panel for my mining turtle, so I got into using Lua coroutines, because I needed the turtle to listen even if it's currently mining, but every time I call function round() it won't continue. I tried to place print('test') in between every near lines of code and I found that the round() function works untill the turtle.turnLeft() part.
The turtle has following code:
rednet.open('right')
local status = 'None'
io.output(io.stdout)
io.input(io.stdin)
io.write('Control Panel ID: ')
local baseId = tonumber(io.read())
io.write('Blocks: ')
local blcks = tonumber(io.read())
function round()
turtle.dig()
--- Here the function stops ---
turtle.turnLeft()
turtle.dig()
turtle.forward()
turtle.turnRight()
turtle.dig()
turtle.digDown()
turtle.down()
turtle.dig()
turtle.turnRight()
turtle.dig()
turtle.forward()
turtle.turnLeft()
turtle.dig()
sleep(0.2)
end
function listen()
if true then
id, message = rednet.receive()
if message == 'down' then
print('Down!')
coroutine.resume(downCo, blcks)
elseif message == 'up' then
coroutine.resume(upCo, blcks)
elseif message == 'refuel' then
turtle.refuel()
elseif message == 'status' then
rednet.send(baseId, status)
elseif message == 'stop' then
print('Lol')
elseif message == 'fuel' then
rednet.send(baseId, turtle.getFuelLevel())
end
end
end
downCo = coroutine.create(function(blcks)
local a = 0
print('Going down! '..blcks)
status = 'Going down'
while a <= blcks do
a = a + 1
round()
end
local status = 'Done'
end)
upCo = coroutine.create(function(blcks)
local status = 'Going up'
for i = blcks,1,-1 do
turtle.digUp()
turtle.up()
end
local status = 'Done'
end)
while true do
listen()
end
I couldn't find any information about that the coroutines can't support turtle movement or anything like that
I tried to turn it into coroutine too, but it just happened to stuck at the same point.
| [
"It looks like you are trying to use coroutines in your turtle's code, but you are not using them correctly. Coroutines are a way to allow your code to pause and resume, but they do not automatically run in parallel like threads do.\nIn your code, you are calling coroutine.resume to start the coroutine, but you are not yielding control back to the main thread at any point. This means that your coroutines will start and then immediately stop, because they have not yielded control back to the main thread.\nTo fix this, you will need to add a coroutine.yield call in your round function. This will allow the coroutine to pause and give control back to the main thread, so that other coroutines can run. Here is how your code could look with this change:\nrednet.open('right')\nlocal status = 'None'\n\nio.output(io.stdout)\nio.input(io.stdin)\n\nio.write('Control Panel ID: ')\nlocal baseId = tonumber(io.read())\nio.write('Blocks: ')\nlocal blcks = tonumber(io.read())\n\nfunction round()\n turtle.dig()\n --- Here the function stops ---\n turtle.turnLeft()\n turtle.dig()\n turtle.forward()\n turtle.turnRight()\n turtle.dig()\n turtle.digDown()\n turtle.down()\n turtle.dig()\n turtle.turnRight()\n turtle.dig()\n turtle.forward()\n turtle.turnLeft()\n turtle.dig()\n coroutine.yield() -- Add this line to yield control back to the main thread\nend\n\nfunction listen()\n if true then\n id, message = rednet.receive()\n if message == 'down' then\n print('Down!')\n coroutine.resume(downCo, blcks)\n elseif message == 'up' then\n coroutine.resume(upCo, blcks)\n elseif message == 'refuel' then\n turtle.refuel()\n elseif message == 'status' then\n rednet.send(baseId, status)\n elseif message == 'stop' then\n print('Lol')\n elseif message == 'fuel' then\n rednet.send(baseId, turtle.getFuelLevel())\n end\n end\nend\n\ndownCo = coroutine.create(function(blcks)\n local a = 0\n print('Going down! '..blcks)\n status = 'Going down'\n while a <= blcks do\n a = a + 1\n round()\n end\n local status = 'Done'\nend)\n\nupCo = coroutine.create(function(blcks)\n local status = 'Going up'\n for i = blcks,1,-1 do\n turtle.digUp()\n turtle.up()\n end\n local status = 'Done'\nend)\n\nwhile true do\n listen()\nend\n\nThis should allow your coroutines to run in parallel and allow your turtle to move while it is listening for messages.\n"
] | [
0
] | [] | [] | [
"computercraft",
"lua"
] | stackoverflow_0074663014_computercraft_lua.txt |
Q:
Laravel 9 serializeDate() Not Working on Other Columns
I want to return json wit all the data with a timestamp datatype turned into ISO 8601 automatically. This should be easily achievable after Laravel 7 but I still face the issue.
I have created two columns start_time and end_time with the timestamp data type. While returning the results in JSON, Laravel only converts created_at and updated_at into ISO8601 (e.g. 2022-04-26T09:44:47.000000Z). The two columns I created are returned as they are stored in the database (e.g. 2022-01-17 19:45:07).
Anything I added in serializeDate() to replace the default method would only affect created_at and updated_at.
The closest I can get is to add below to my model, but it still has a slight difference in format (e.g. 2022-04-26T10:30:00Z vs 2022-04-26T09:44:47.000000Z).
protected $casts = [
'start_time' => 'date:Y-m-d\TH:i:s\Z',
'end_time' => 'date:Y-m-d\TH:i:s\Z',
];
A:
This may not answer the questions directly but I found a workaround. What you can do is Carbon::parse those columns returned as stored in the database before returning them in Json.
Here is an example if you are returning all the slots in your database:
foreach ($slots as $slot) {
$slot->start = Carbon::parse($slot->start_time);
$slot->end = Carbon::parse($slot->end_time);
}
return response()->json($slots);
A:
It's simply because you need to tell Laravel about the columns it should consider as dates in your model, by default created_at and updated_at are considered.
There is a protected property called $dates, it takes an array of all the columns to be considered as dates. the serializeDate method looks after that property.
protected $dates = [
'reception_date',
'response_date' ,
'...'
];
protected function serializeDate(DateTimeInterface $date)
{
// you may give whatever format you want
return $date->translatedFormat('d M Y Γ H:i');
}
A:
you can cast columns to date and serializeDate() function will automatically cast your date columns
use DateTimeInterface;
class Project extends Model
{
protected $casts = [
'start_time' => 'date',
'end_time' => 'date',
];
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
}
A:
To fix this issue, you can override the default serializeDate() method in your model and add the columns you want to be serialized in the same format as created_at and updated_at.
For example:
public function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d\TH:i:s.u\Z');
}
You can also use the Carbon library to handle the date formatting:
public function serializeDate(DateTimeInterface $date)
{
return Carbon::parse($date)->toIso8601String();
}
Then in your controller, you can return the results with the custom serializeDate() method by using the $with method:
return Model::with([
'start_time' => function($query) {
$query->serializeDate();
},
'end_time' => function($query) {
$query->serializeDate();
},
])->get();
This should return the results in the desired ISO 8601 format for the start_time and end_time columns.
| Laravel 9 serializeDate() Not Working on Other Columns | I want to return json wit all the data with a timestamp datatype turned into ISO 8601 automatically. This should be easily achievable after Laravel 7 but I still face the issue.
I have created two columns start_time and end_time with the timestamp data type. While returning the results in JSON, Laravel only converts created_at and updated_at into ISO8601 (e.g. 2022-04-26T09:44:47.000000Z). The two columns I created are returned as they are stored in the database (e.g. 2022-01-17 19:45:07).
Anything I added in serializeDate() to replace the default method would only affect created_at and updated_at.
The closest I can get is to add below to my model, but it still has a slight difference in format (e.g. 2022-04-26T10:30:00Z vs 2022-04-26T09:44:47.000000Z).
protected $casts = [
'start_time' => 'date:Y-m-d\TH:i:s\Z',
'end_time' => 'date:Y-m-d\TH:i:s\Z',
];
| [
"This may not answer the questions directly but I found a workaround. What you can do is Carbon::parse those columns returned as stored in the database before returning them in Json.\nHere is an example if you are returning all the slots in your database:\nforeach ($slots as $slot) {\n $slot->start = Carbon::parse($slot->start_time);\n $slot->end = Carbon::parse($slot->end_time);\n}\n\nreturn response()->json($slots);\n\n",
"It's simply because you need to tell Laravel about the columns it should consider as dates in your model, by default created_at and updated_at are considered.\nThere is a protected property called $dates, it takes an array of all the columns to be considered as dates. the serializeDate method looks after that property.\nprotected $dates = [\n 'reception_date',\n 'response_date' ,\n '...'\n];\n\n\nprotected function serializeDate(DateTimeInterface $date)\n{\n // you may give whatever format you want\n return $date->translatedFormat('d M Y Γ H:i');\n}\n\n",
"you can cast columns to date and serializeDate() function will automatically cast your date columns\nuse DateTimeInterface;\n\nclass Project extends Model\n{\n protected $casts = [\n 'start_time' => 'date',\n 'end_time' => 'date',\n ];\n\n protected function serializeDate(DateTimeInterface $date)\n {\n return $date->format('Y-m-d H:i:s');\n }\n}\n\n",
"To fix this issue, you can override the default serializeDate() method in your model and add the columns you want to be serialized in the same format as created_at and updated_at.\nFor example:\npublic function serializeDate(DateTimeInterface $date)\n{\n return $date->format('Y-m-d\\TH:i:s.u\\Z');\n}\n\nYou can also use the Carbon library to handle the date formatting:\npublic function serializeDate(DateTimeInterface $date)\n{\n return Carbon::parse($date)->toIso8601String();\n}\n\nThen in your controller, you can return the results with the custom serializeDate() method by using the $with method:\nreturn Model::with([\n 'start_time' => function($query) {\n $query->serializeDate();\n },\n 'end_time' => function($query) {\n $query->serializeDate();\n },\n])->get();\n\nThis should return the results in the desired ISO 8601 format for the start_time and end_time columns.\n"
] | [
0,
0,
0,
0
] | [] | [] | [
"laravel",
"laravel_9"
] | stackoverflow_0072013136_laravel_laravel_9.txt |
Q:
Fastest gap sequence for shell sort?
According to Marcin Ciura's Optimal (best known) sequence of increments for shell sort algorithm,
the best sequence for shellsort is 1, 4, 10, 23, 57, 132, 301, 701...,
but how can I generate such a sequence?
In Marcin Ciura's paper, he said:
Both Knuthβs and Hibbardβs sequences
are relatively bad, because they are
defined by simple linear recurrences.
but most algorithm books I found tend to use Knuthβs sequence: k = 3k + 1, because it's easy to generate. What's your way of generating a shellsort sequence?
A:
Ciura's paper generates the sequence empirically -- that is, he tried a bunch of combinations and this was the one that worked the best. Generating an optimal shellsort sequence has proven to be tricky, and the problem has so far been resistant to analysis.
The best known increment is Sedgewick's, which you can read about here (see p. 7).
A:
If your data set has a definite upper bound in size, then you can hardcode the step sequence. You should probably only worry about generality if your data set is likely to grow without an upper bound.
The sequence shown seems to grow roughly as an exponential series, albeit with quirks. There seems to be a majority of prime numbers, but with non-primes in the mix as well. I don't see an obvious generation formula.
A valid question, assuming you must deal with arbitrarily large sets, is whether you need to emphasise worst-case performance, average-case performance, or almost-sorted performance. If the latter, you may find that a plain insertion sort using a binary search for the insertion step might be better than a shellsort. If you need good worst-case performance, then Sedgewick's sequence appears to be favoured. The sequence you mention is optimised for average-case performance, where the number of comparisons outweighs the number of moves.
A:
I would not be ashamed to take the advice given in Wikipedia's Shellsort article,
With respect to the average number of comparisons, the best known gap
sequences are 1, 4, 10, 23, 57, 132, 301, 701 and similar, with gaps
found experimentally. Optimal gaps beyond 701 remain unknown, but good
results can be obtained by extending the above sequence according to
the recursive formula h_k = \lfloor 2.25 h_{k-1} \rfloor.
Tokuda's sequence [1, 4, 9, 20, 46, 103, ...], defined by the simple formula h_k = \lceil h'_k
\rceil, where h'k = 2.25h'k β 1 + 1, h'1 = 1, can be recommended for
practical applications.
guessing from the pseudonym, it seems Marcin Ciura edited the WP article himself.
A:
The sequence is 1, 4, 10, 23, 57, 132, 301, 701, 1750. For every next number after 1750 multiply previous number by 2.25 and round down.
A:
Sedgewick observes that coprimality is good. This rings true: if there are separate βstreamsβ not much cross-compared until the gap is small, and one stream contains mostly smalls and one mostly larges, then the small gap might need to move elements far. Coprimality maximises cross-stream comparison.
Gonnet and Baeza-Yates advise growth by a factor of about 2.2; Tokuda by 2.25. It is well known that if there is a mathematical constant between 2β
and 2ΒΌ then it mustβ be precisely β5 β 2.236.
So start {1, 3}, and then each subsequent is the integer closest to previousΒ·β5 that is coprime to all previous except 1. This sequence can be pre-calculated and embedded in code. There follow the values up to 2βΆβ΄ β eighteen quintillion.
{1, 3, 7, 16, 37, 83, 187, 419, 937, 2099, 4693, 10499, 23479, 52501, 117391, 262495, 586961, 1312481, 2934793, 6562397, 14673961, 32811973, 73369801, 164059859, 366848983, 820299269, 1834244921, 4101496331, 9171224603, 20507481647, 45856123009, 102537408229, 229280615033, 512687041133, 1146403075157, 2563435205663, 5732015375783, 12817176028331, 28660076878933, 64085880141667, 143300384394667, 320429400708323, 716501921973329, 1602147003541613, 3582509609866643, 8010735017708063, 17912548049333207, 40053675088540303, 89562740246666023, 200268375442701509, 447813701233330109, 1001341877213507537, 2239068506166650537, 5006709386067537661, 11195342530833252689}
(Obviously, omit those that would overflow the relevant array index type. So if that is a signed long long, omit the last.)
On average these have β1.96 distinct prime factors and β2.07 non-distinct prime factors; 19/55 β 35% are prime; and all but three are square-free (2β΄, 13Β·19Β² = 4693, 3291992692409Β·23Β³ β 4.0Β·10ΒΉβΆ).
I would welcome formal reasoning about this sequence.
β Thereβs a little mischief in this βwell known β¦ mustβ. Choosing ββ guarantees that the closest number that is coprime cannot be a tie, but rational with odd denominator would achieve same. And I like the simplicity of β5, though other possibilities include e^β
, 11^β
, Ο/β2, and βΟ divided by the Chow-Robbins constant. Simplicity favours β5.
A:
I've found this sequence similar to Marcin Ciura's sequence:
1, 4, 9, 23, 57, 138, 326, 749, 1695, 3785, 8359, 18298, 39744, etc.
For example, Ciura's sequence is:
1, 4, 10, 23, 57, 132, 301, 701, 1750
This is a mean of prime numbers. Python code to find mean of prime numbers is here:
import numpy as np
def isprime(n):
''' Check if integer n is a prime '''
n = abs(int(n)) # n is a positive integer
if n < 2: # 0 and 1 are not primes
return False
if n == 2: # 2 is the only even prime number
return True
if not n & 1: # all other even numbers are not primes
return False
# Range starts with 3 and only needs to go up the square root
# of n for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
# To apply a function to a numpy array, one have to vectorize the function
vectorized_isprime = np.vectorize(isprime)
a = np.arange(10000000)
primes = a[vectorized_isprime(a)]
#print(primes)
for i in range(2,20):
print(primes[0:2**i].mean())
The output is:
4.25
9.625
23.8125
57.84375
138.953125
326.1015625
749.04296875
1695.60742188
3785.09082031
8359.52587891
18298.4733887
39744.887085
85764.6216431
184011.130096
392925.738174
835387.635033
1769455.40302
3735498.24225
The gap in the sequence is slowly decreasing from 2.5 to 2.
Maybe this association could improve the Shellsort in the future.
A:
I discussed this question here yesterday including the gap sequences I have found work best given a specific (low) n.
In the middle I write
A nasty side-effect of shellsort is that when using a set of random
combinations of n entries (to save processing/evaluation time) to test
gaps you may end up with either the best gaps for n entries or the
best gaps for your set of combinations - most likely the latter.
The problem lies in testing the proposed gaps such that valid conclusions can be drawn. Obviously, testing the gaps against all n! orderings that a set of n unique values can be expressed as is unfeasible. Testing in this manner for n=16, for example, means that 20,922,789,888,000 different combinations of n values must be sorted to determine the exact average, worst and reverse-sorted cases - just to test one set of gaps and that set might not be the best. 2^(16-2) sets of gaps are possible for n=16, the first being {1} and the last {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1}.
To illustrate how using random combinations might give incorrect results assume n=3 that can assume six different orderings 012, 021, 102, 120, 201 and 210. You produce a set of two random sequences to test the two possible gap sets, {1} and {2,1}. Assume that these sequences turn out to be 021 and 201. for {1} 021 can be sorted with three comparisons (02, 21 and 01) and 201 with (20, 21, 01) giving a total of six comparisons, divide by two and voilΓ , an average of 3 and a worst case of 3. Using {2,1} gives (01, 02, 21 and 01) for 021 and (21, 10 and 12) for 201. Seven comparisons with a worst case of 4 and an average of 3.5. The actual average and worst case for {1] is 8/3 and 3, respectively. For {2,1} the values are 10/3 and 4. The averages were too high in both cases and the worst cases were correct. Had 012 been one of the cases {1} would have given a 2.5 average - too low.
Now extend this to finding a set of random sequences for n=16 such that no set of gaps tested will be favored in comparison with the others and the result close (or equal) to the true values, all the while keeping processing to a minimum. Can it be done? Possibly. After all, everything is possible - but is it probable? I think that for this problem random is the wrong approach. Selecting the sequences according to some system may be less bad and might even be good.
A:
More information regarding jdaw1's post:
Gonnet and Baeza-Yates advise growth by a factor of about 2.2; Tokuda by 2.25. It is well known that if there is a mathematical constant between 2β
and 2ΒΌ then it mustβ be precisely β5 β 2.236.
It is known that β5 * β5 is 5 so I think every other index should increase by a factor of five. So first index being 1 insertion sort, second being 3 then each other subsequent is of the factor 5. There follow the values up to 2βΆβ΄ β eighteen quintillion.
{1, 3,, 15,, 75,, 375,, 1 875,, 9 375,, 46 875,, 234 375,, 1 171 875,, 5 859 375,, 29 296 875,, 146 484 375,, 732 421 875,, 3 662 109 375,, 18 310 546 875,, 91 552 734 375,, 457 763 671 875,, 2Β 288Β 818Β 359Β 375,, 11Β 444Β 091Β 796Β 875,, 57Β 220Β 458Β 984Β 375,, 286Β 102Β 294Β 921Β 875,, 1Β 430Β 511Β 474Β 609Β 375}
The values in the gaps can simply be calculated by taking the value before and multiply by β5 rounding to whole numbers giving the resulting array (using 2.2360679775 * 5 ^ n * 3):
{1, 3, 7, 15, 34, 75, 168, 375, 839, 1 875, 4 193, 9 375, 20 963, 46 875, 104 816, 234 375, 524 078, 1 171 875, 2 620 392, 5 859 375, 13 101 961, 29 296 875, 65 509 804, 146 484 375, 327 549 020, 732 421 875, 1 637 745 101, 3 662 109 375, 8 188 725 504, 18 310 546 875, 40 943 627 518, 91 552 734 375, 204Β 718Β 137Β 589, 457 763 671 875, 1Β 023Β 590Β 687Β 943, 2Β 288Β 818Β 359Β 375, 5Β 117Β 953Β 439Β 713, 11Β 444Β 091Β 796Β 875, 25Β 589Β 767Β 198Β 563, 57Β 220Β 458Β 984Β 375, 127Β 948Β 835Β 992Β 813, 286Β 102Β 294Β 921Β 875, 639Β 744Β 179Β 964Β 066, 1Β 430Β 511Β 474Β 609Β 375, 3Β 198Β 720Β 899Β 820Β 328, 7Β 152Β 557Β 373Β 046Β 875, 15Β 993Β 604Β 499Β 101Β 639, 35Β 762Β 786Β 865Β 234Β 375, 79Β 968Β 022Β 495Β 508Β 194, 178Β 813Β 934Β 326Β 171Β 875, 399Β 840Β 112Β 477Β 540Β 970, 894Β 069Β 671Β 630Β 859Β 375, 1Β 999Β 200Β 562Β 387Β 704Β 849, 4Β 470Β 348Β 358Β 154Β 296Β 875, 9Β 996Β 002Β 811Β 938Β 524Β 246}
(Obviously, omit those that would overflow the relevant array index type. So if that is a signed long long, omit the last.)
| Fastest gap sequence for shell sort? | According to Marcin Ciura's Optimal (best known) sequence of increments for shell sort algorithm,
the best sequence for shellsort is 1, 4, 10, 23, 57, 132, 301, 701...,
but how can I generate such a sequence?
In Marcin Ciura's paper, he said:
Both Knuthβs and Hibbardβs sequences
are relatively bad, because they are
defined by simple linear recurrences.
but most algorithm books I found tend to use Knuthβs sequence: k = 3k + 1, because it's easy to generate. What's your way of generating a shellsort sequence?
| [
"Ciura's paper generates the sequence empirically -- that is, he tried a bunch of combinations and this was the one that worked the best. Generating an optimal shellsort sequence has proven to be tricky, and the problem has so far been resistant to analysis.\nThe best known increment is Sedgewick's, which you can read about here (see p. 7). \n",
"If your data set has a definite upper bound in size, then you can hardcode the step sequence. You should probably only worry about generality if your data set is likely to grow without an upper bound.\nThe sequence shown seems to grow roughly as an exponential series, albeit with quirks. There seems to be a majority of prime numbers, but with non-primes in the mix as well. I don't see an obvious generation formula.\nA valid question, assuming you must deal with arbitrarily large sets, is whether you need to emphasise worst-case performance, average-case performance, or almost-sorted performance. If the latter, you may find that a plain insertion sort using a binary search for the insertion step might be better than a shellsort. If you need good worst-case performance, then Sedgewick's sequence appears to be favoured. The sequence you mention is optimised for average-case performance, where the number of comparisons outweighs the number of moves.\n",
"I would not be ashamed to take the advice given in Wikipedia's Shellsort article,\n\nWith respect to the average number of comparisons, the best known gap\n sequences are 1, 4, 10, 23, 57, 132, 301, 701 and similar, with gaps\n found experimentally. Optimal gaps beyond 701 remain unknown, but good\n results can be obtained by extending the above sequence according to\n the recursive formula h_k = \\lfloor 2.25 h_{k-1} \\rfloor.\nTokuda's sequence [1, 4, 9, 20, 46, 103, ...], defined by the simple formula h_k = \\lceil h'_k\n \\rceil, where h'k = 2.25h'k β 1 + 1, h'1 = 1, can be recommended for\n practical applications.\n\nguessing from the pseudonym, it seems Marcin Ciura edited the WP article himself.\n",
"The sequence is 1, 4, 10, 23, 57, 132, 301, 701, 1750. For every next number after 1750 multiply previous number by 2.25 and round down.\n",
"Sedgewick observes that coprimality is good. This rings true: if there are separate βstreamsβ not much cross-compared until the gap is small, and one stream contains mostly smalls and one mostly larges, then the small gap might need to move elements far. Coprimality maximises cross-stream comparison.\nGonnet and Baeza-Yates advise growth by a factor of about 2.2; Tokuda by 2.25. It is well known that if there is a mathematical constant between 2β
and 2ΒΌ then it mustβ be precisely β5 β 2.236.\nSo start {1, 3}, and then each subsequent is the integer closest to previousΒ·β5 that is coprime to all previous except 1. This sequence can be pre-calculated and embedded in code. There follow the values up to 2βΆβ΄ β eighteen quintillion.\n{1, 3, 7, 16, 37, 83, 187, 419, 937, 2099, 4693, 10499, 23479, 52501, 117391, 262495, 586961, 1312481, 2934793, 6562397, 14673961, 32811973, 73369801, 164059859, 366848983, 820299269, 1834244921, 4101496331, 9171224603, 20507481647, 45856123009, 102537408229, 229280615033, 512687041133, 1146403075157, 2563435205663, 5732015375783, 12817176028331, 28660076878933, 64085880141667, 143300384394667, 320429400708323, 716501921973329, 1602147003541613, 3582509609866643, 8010735017708063, 17912548049333207, 40053675088540303, 89562740246666023, 200268375442701509, 447813701233330109, 1001341877213507537, 2239068506166650537, 5006709386067537661, 11195342530833252689}\n(Obviously, omit those that would overflow the relevant array index type. So if that is a signed long long, omit the last.)\nOn average these have β1.96 distinct prime factors and β2.07 non-distinct prime factors; 19/55 β 35% are prime; and all but three are square-free (2β΄, 13Β·19Β² = 4693, 3291992692409Β·23Β³ β 4.0Β·10ΒΉβΆ).\nI would welcome formal reasoning about this sequence.\nβ Thereβs a little mischief in this βwell known β¦ mustβ. Choosing ββ guarantees that the closest number that is coprime cannot be a tie, but rational with odd denominator would achieve same. And I like the simplicity of β5, though other possibilities include e^β
, 11^β
, Ο/β2, and βΟ divided by the Chow-Robbins constant. Simplicity favours β5.\n",
"I've found this sequence similar to Marcin Ciura's sequence:\n1, 4, 9, 23, 57, 138, 326, 749, 1695, 3785, 8359, 18298, 39744, etc.\n\nFor example, Ciura's sequence is:\n1, 4, 10, 23, 57, 132, 301, 701, 1750\n\nThis is a mean of prime numbers. Python code to find mean of prime numbers is here:\nimport numpy as np\n\ndef isprime(n):\n ''' Check if integer n is a prime '''\n n = abs(int(n)) # n is a positive integer\n if n < 2: # 0 and 1 are not primes\n return False\n if n == 2: # 2 is the only even prime number\n return True\n if not n & 1: # all other even numbers are not primes\n return False\n # Range starts with 3 and only needs to go up the square root\n # of n for all odd numbers\n for x in range(3, int(n**0.5)+1, 2):\n if n % x == 0:\n return False\n return True\n\n# To apply a function to a numpy array, one have to vectorize the function\nvectorized_isprime = np.vectorize(isprime)\n\na = np.arange(10000000)\nprimes = a[vectorized_isprime(a)]\n#print(primes)\nfor i in range(2,20):\n print(primes[0:2**i].mean())\n\nThe output is:\n4.25\n9.625\n23.8125\n57.84375\n138.953125\n326.1015625\n749.04296875\n1695.60742188\n3785.09082031\n8359.52587891\n18298.4733887\n39744.887085\n85764.6216431\n184011.130096\n392925.738174\n835387.635033\n1769455.40302\n3735498.24225\n\nThe gap in the sequence is slowly decreasing from 2.5 to 2.\nMaybe this association could improve the Shellsort in the future.\n",
"I discussed this question here yesterday including the gap sequences I have found work best given a specific (low) n.\nIn the middle I write\n\nA nasty side-effect of shellsort is that when using a set of random\n combinations of n entries (to save processing/evaluation time) to test\n gaps you may end up with either the best gaps for n entries or the\n best gaps for your set of combinations - most likely the latter.\n\nThe problem lies in testing the proposed gaps such that valid conclusions can be drawn. Obviously, testing the gaps against all n! orderings that a set of n unique values can be expressed as is unfeasible. Testing in this manner for n=16, for example, means that 20,922,789,888,000 different combinations of n values must be sorted to determine the exact average, worst and reverse-sorted cases - just to test one set of gaps and that set might not be the best. 2^(16-2) sets of gaps are possible for n=16, the first being {1} and the last {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1}.\nTo illustrate how using random combinations might give incorrect results assume n=3 that can assume six different orderings 012, 021, 102, 120, 201 and 210. You produce a set of two random sequences to test the two possible gap sets, {1} and {2,1}. Assume that these sequences turn out to be 021 and 201. for {1} 021 can be sorted with three comparisons (02, 21 and 01) and 201 with (20, 21, 01) giving a total of six comparisons, divide by two and voilΓ , an average of 3 and a worst case of 3. Using {2,1} gives (01, 02, 21 and 01) for 021 and (21, 10 and 12) for 201. Seven comparisons with a worst case of 4 and an average of 3.5. The actual average and worst case for {1] is 8/3 and 3, respectively. For {2,1} the values are 10/3 and 4. The averages were too high in both cases and the worst cases were correct. Had 012 been one of the cases {1} would have given a 2.5 average - too low.\nNow extend this to finding a set of random sequences for n=16 such that no set of gaps tested will be favored in comparison with the others and the result close (or equal) to the true values, all the while keeping processing to a minimum. Can it be done? Possibly. After all, everything is possible - but is it probable? I think that for this problem random is the wrong approach. Selecting the sequences according to some system may be less bad and might even be good.\n",
"More information regarding jdaw1's post:\n\nGonnet and Baeza-Yates advise growth by a factor of about 2.2; Tokuda by 2.25. It is well known that if there is a mathematical constant between 2β
and 2ΒΌ then it mustβ be precisely β5 β 2.236.\n\nIt is known that β5 * β5 is 5 so I think every other index should increase by a factor of five. So first index being 1 insertion sort, second being 3 then each other subsequent is of the factor 5. There follow the values up to 2βΆβ΄ β eighteen quintillion.\n{1, 3,, 15,, 75,, 375,, 1 875,, 9 375,, 46 875,, 234 375,, 1 171 875,, 5 859 375,, 29 296 875,, 146 484 375,, 732 421 875,, 3 662 109 375,, 18 310 546 875,, 91 552 734 375,, 457 763 671 875,, 2Β 288Β 818Β 359Β 375,, 11Β 444Β 091Β 796Β 875,, 57Β 220Β 458Β 984Β 375,, 286Β 102Β 294Β 921Β 875,, 1Β 430Β 511Β 474Β 609Β 375}\nThe values in the gaps can simply be calculated by taking the value before and multiply by β5 rounding to whole numbers giving the resulting array (using 2.2360679775 * 5 ^ n * 3):\n{1, 3, 7, 15, 34, 75, 168, 375, 839, 1 875, 4 193, 9 375, 20 963, 46 875, 104 816, 234 375, 524 078, 1 171 875, 2 620 392, 5 859 375, 13 101 961, 29 296 875, 65 509 804, 146 484 375, 327 549 020, 732 421 875, 1 637 745 101, 3 662 109 375, 8 188 725 504, 18 310 546 875, 40 943 627 518, 91 552 734 375, 204Β 718Β 137Β 589, 457 763 671 875, 1Β 023Β 590Β 687Β 943, 2Β 288Β 818Β 359Β 375, 5Β 117Β 953Β 439Β 713, 11Β 444Β 091Β 796Β 875, 25Β 589Β 767Β 198Β 563, 57Β 220Β 458Β 984Β 375, 127Β 948Β 835Β 992Β 813, 286Β 102Β 294Β 921Β 875, 639Β 744Β 179Β 964Β 066, 1Β 430Β 511Β 474Β 609Β 375, 3Β 198Β 720Β 899Β 820Β 328, 7Β 152Β 557Β 373Β 046Β 875, 15Β 993Β 604Β 499Β 101Β 639, 35Β 762Β 786Β 865Β 234Β 375, 79Β 968Β 022Β 495Β 508Β 194, 178Β 813Β 934Β 326Β 171Β 875, 399Β 840Β 112Β 477Β 540Β 970, 894Β 069Β 671Β 630Β 859Β 375, 1Β 999Β 200Β 562Β 387Β 704Β 849, 4Β 470Β 348Β 358Β 154Β 296Β 875, 9Β 996Β 002Β 811Β 938Β 524Β 246}\n\n(Obviously, omit those that would overflow the relevant array index type. So if that is a signed long long, omit the last.)\n\n"
] | [
14,
6,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"performance",
"shellsort",
"sorting"
] | stackoverflow_0002539545_algorithm_performance_shellsort_sorting.txt |
Q:
If inside each in handlebars.js
I would like to be able to do below with Handlebars.js, but it's not working?
{{#each questions}}
<p>{{content}}</p>
{{#if user}} display reply button {/if}
{{/each}}
I want to display all questions and if the user is logged in he can reply.
here is my nodejs code
router.get('/question', function(req, res){
Question.find({}).then (questions =>{
res.render('question',{questions});
});
});
A:
If inside each in handlebars.js, then you need to use **/ (**/user)
try like this ,
{{#each questions}}
<p>{{content}}</p>
{{#if ../user}} display reply button {/if}
{{/each}}
| If inside each in handlebars.js | I would like to be able to do below with Handlebars.js, but it's not working?
{{#each questions}}
<p>{{content}}</p>
{{#if user}} display reply button {/if}
{{/each}}
I want to display all questions and if the user is logged in he can reply.
here is my nodejs code
router.get('/question', function(req, res){
Question.find({}).then (questions =>{
res.render('question',{questions});
});
});
| [
"If inside each in handlebars.js, then you need to use **/ (**/user)\ntry like this ,\n {{#each questions}}\n <p>{{content}}</p> \n {{#if ../user}} display reply button {/if}\n {{/each}}\n\n"
] | [
0
] | [] | [] | [
"express_handlebars",
"handlebars.js",
"node.js"
] | stackoverflow_0048230397_express_handlebars_handlebars.js_node.js.txt |
Q:
How to select Object(s) from a JSON message in Python?
I received this data from an API,
But i am unable to select the Objects i want.
It shows the candle data from 3 tickers;"ETHUSDT","BTCUSDT" and "BNBUSDT",
but they are all under the same identifiers...
I need the closing prices('c' values of each ticker) so it would be something like:
anyone knows how to get something like;
ETHUSDT('c')='1253.28000000'
BTCUSDT('c')='16912.93000000'
BNBUSDT('c')='289.60000000'
(Data coming in through a websocket, so i cant split it up in 3 messages)
##Thanks in advance!!
{'E': 1670154095936, 'e': 'kline', 'k': {'B': '0', 'L': 1036708466, '`Q': '403679.79500200', 'T': 1670154119999, 'V': '322.25210000', 'c': '1253.28000000', 'f': 1036707674, 'h': '1253.28000000', 'i': '1m', 'l': '1251.64000000', 'n': 793, 'o': '1253.02000000', 'q': '741683.22211300', 's': 'ETHUSDT', 't': 1670154060000, 'v': '592.10530000', 'x': False}, 's': 'ETHUSDT'} {'E': 1670154096509, 'e': 'kline', 'k': {'B': '0', 'L': 2285413599, 'Q': '2955493.90319840', 'T': 1670154119999, 'V': '174.76525000', 'c': '16912.93000000', 'f': 2285408203, 'h': '16922.53000000', 'i': '1m', 'l': '16905.01000000', 'n': 5397, 'o': '16920.08000000', 'q': '5748552.34500920', 's': 'BTCUSDT', 't': 1670154060000, 'v': '339.92573000', 'x': False}, 's': 'BTCUSDT'} {'E': 1670154096937, 'e': 'kline', 'k': {'B': '0', 'L': 608211438, 'Q': '16414.84590000', 'T': 1670154119999, 'V': '56.69100000', 'c': '289.60000000', 'f': 608211306, 'h': '289.70000000', 'i': '1m', 'l': '289.40000000', 'n': 133, 'o': '289.70000000', 'q': '40301.72990000', 's': 'BNBUSDT', 't': 1670154060000, 'v': '139.20100000', 'x': False}, 's': 'BNBUSDT'}
this just gave me all of the data
``def on_message(ws,message):
json_message = json.loads(message)
candle = json_message['data']['k']
A:
you can use:
outs=[]
for i in your_json:
outs.append("{}(c)={}".format(i['s'],i['k']['c']))
#['ETHUSDT(c)=1253.28000000', 'BTCUSDT(c)=16912.93000000', 'BNBUSDT(c)=289.60000000']
| How to select Object(s) from a JSON message in Python? | I received this data from an API,
But i am unable to select the Objects i want.
It shows the candle data from 3 tickers;"ETHUSDT","BTCUSDT" and "BNBUSDT",
but they are all under the same identifiers...
I need the closing prices('c' values of each ticker) so it would be something like:
anyone knows how to get something like;
ETHUSDT('c')='1253.28000000'
BTCUSDT('c')='16912.93000000'
BNBUSDT('c')='289.60000000'
(Data coming in through a websocket, so i cant split it up in 3 messages)
##Thanks in advance!!
{'E': 1670154095936, 'e': 'kline', 'k': {'B': '0', 'L': 1036708466, '`Q': '403679.79500200', 'T': 1670154119999, 'V': '322.25210000', 'c': '1253.28000000', 'f': 1036707674, 'h': '1253.28000000', 'i': '1m', 'l': '1251.64000000', 'n': 793, 'o': '1253.02000000', 'q': '741683.22211300', 's': 'ETHUSDT', 't': 1670154060000, 'v': '592.10530000', 'x': False}, 's': 'ETHUSDT'} {'E': 1670154096509, 'e': 'kline', 'k': {'B': '0', 'L': 2285413599, 'Q': '2955493.90319840', 'T': 1670154119999, 'V': '174.76525000', 'c': '16912.93000000', 'f': 2285408203, 'h': '16922.53000000', 'i': '1m', 'l': '16905.01000000', 'n': 5397, 'o': '16920.08000000', 'q': '5748552.34500920', 's': 'BTCUSDT', 't': 1670154060000, 'v': '339.92573000', 'x': False}, 's': 'BTCUSDT'} {'E': 1670154096937, 'e': 'kline', 'k': {'B': '0', 'L': 608211438, 'Q': '16414.84590000', 'T': 1670154119999, 'V': '56.69100000', 'c': '289.60000000', 'f': 608211306, 'h': '289.70000000', 'i': '1m', 'l': '289.40000000', 'n': 133, 'o': '289.70000000', 'q': '40301.72990000', 's': 'BNBUSDT', 't': 1670154060000, 'v': '139.20100000', 'x': False}, 's': 'BNBUSDT'}
this just gave me all of the data
``def on_message(ws,message):
json_message = json.loads(message)
candle = json_message['data']['k']
| [
"you can use:\nouts=[]\nfor i in your_json:\n outs.append(\"{}(c)={}\".format(i['s'],i['k']['c']))\n\n#['ETHUSDT(c)=1253.28000000', 'BTCUSDT(c)=16912.93000000', 'BNBUSDT(c)=289.60000000']\n\n"
] | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074675545_json_python.txt |
Q:
What does EXISTS 1 in SQL mean?
I'm quite new to the subquery topic. I want to understand what EXISTS 1 in SQL mean because when I replace 1 with *, it returns the same result.
A:
In SQL, the EXISTS keyword is used in a subquery to check if a row exists in the outer query. For example, the following query uses the EXISTS keyword in a subquery to find all products that have at least one order:
SELECT * FROM products
WHERE EXISTS (
SELECT 1 FROM orders
WHERE orders.product_id = products.id
)
In this query, the subquery SELECT 1 FROM orders WHERE orders.product_id = products.id returns a 1 if an order exists for the product in the outer query, and NULL if no order exists. The EXISTS keyword then checks if the result of the subquery is not NULL (i.e. if an order exists), and returns the products in the outer query that satisfy this condition.
In this case, using SELECT 1 in the subquery is equivalent to using SELECT *, because EXISTS only checks if a row exists and does not care about the actual values in the row. Therefore, the following query would produce the same result:
SELECT * FROM products
WHERE EXISTS (
SELECT * FROM orders
WHERE orders.product_id = products.id
)
However, using SELECT 1 in the subquery can be more efficient than using SELECT *, because it only returns a single value instead of all the values in the row, which can reduce the amount of data that needs to be transferred between the database server and the client.
| What does EXISTS 1 in SQL mean? | I'm quite new to the subquery topic. I want to understand what EXISTS 1 in SQL mean because when I replace 1 with *, it returns the same result.
| [
"In SQL, the EXISTS keyword is used in a subquery to check if a row exists in the outer query. For example, the following query uses the EXISTS keyword in a subquery to find all products that have at least one order:\nSELECT * FROM products\nWHERE EXISTS (\n SELECT 1 FROM orders\n WHERE orders.product_id = products.id\n)\n\nIn this query, the subquery SELECT 1 FROM orders WHERE orders.product_id = products.id returns a 1 if an order exists for the product in the outer query, and NULL if no order exists. The EXISTS keyword then checks if the result of the subquery is not NULL (i.e. if an order exists), and returns the products in the outer query that satisfy this condition.\nIn this case, using SELECT 1 in the subquery is equivalent to using SELECT *, because EXISTS only checks if a row exists and does not care about the actual values in the row. Therefore, the following query would produce the same result:\nSELECT * FROM products\nWHERE EXISTS (\n SELECT * FROM orders\n WHERE orders.product_id = products.id\n)\n\nHowever, using SELECT 1 in the subquery can be more efficient than using SELECT *, because it only returns a single value instead of all the values in the row, which can reduce the amount of data that needs to be transferred between the database server and the client.\n"
] | [
0
] | [] | [] | [
"mysql",
"sql",
"subquery"
] | stackoverflow_0074675591_mysql_sql_subquery.txt |
Q:
Populate all fields in mongoose?
Is there a way to populate all fields when running a mongoose query, in case you don't know in advance which fields are the referenced documents? Something like this:
schema = new Schema({ ref: {type:ObjectId, ref:'ref'}});
db = Model('data', schema);
db.find({}).populate('*').
// or
db.find({}).populate({path:'*'}).
//=> {ref: {_id:...,}} // "ref" is populated automatically
A:
I wrote a small plugin. It goes through the schema and looks for fields with a ref property and adds them as a path which is fed to .populate() in a pre-find hook. Tested with Mongoose v4
function autoPopulateAllFields(schema) {
var paths = '';
schema.eachPath(function process(pathname, schemaType) {
if (pathname=='_id') return;
if (schemaType.options.ref)
paths += ' ' + pathname;
});
schema.pre('find', handler);
schema.pre('findOne', handler);
function handler(next) {
this.populate(paths);
next();
}
};
module.exports = autoPopulateAllFields;
var articleSchema = new Schema({
text: {type: 'String'},
author: {type: 'ObjectId', ref: 'user'}
});
articleSchema.plugin(autoPopulateAllFields);
var Article = mongoose.model('article', articleSchema);
Article.find({}) => [ {text:..., author: { _id:..., name:... /*auto-populated*/} } ]
A:
I think it's better to export a variable somewhere that contains the list of all populated fields like :
export const POPULATED_FIELDS = ['filed1','field2']
then when you want to populate the fields just wrtie
Model.findById('some_id').populate(POPULATED_FIELDS)
| Populate all fields in mongoose? | Is there a way to populate all fields when running a mongoose query, in case you don't know in advance which fields are the referenced documents? Something like this:
schema = new Schema({ ref: {type:ObjectId, ref:'ref'}});
db = Model('data', schema);
db.find({}).populate('*').
// or
db.find({}).populate({path:'*'}).
//=> {ref: {_id:...,}} // "ref" is populated automatically
| [
"I wrote a small plugin. It goes through the schema and looks for fields with a ref property and adds them as a path which is fed to .populate() in a pre-find hook. Tested with Mongoose v4\nfunction autoPopulateAllFields(schema) {\n var paths = '';\n schema.eachPath(function process(pathname, schemaType) {\n if (pathname=='_id') return;\n if (schemaType.options.ref)\n paths += ' ' + pathname;\n });\n\n schema.pre('find', handler);\n schema.pre('findOne', handler);\n\n function handler(next) {\n this.populate(paths);\n next();\n }\n};\nmodule.exports = autoPopulateAllFields;\n\nvar articleSchema = new Schema({\n text: {type: 'String'},\n author: {type: 'ObjectId', ref: 'user'}\n});\narticleSchema.plugin(autoPopulateAllFields);\nvar Article = mongoose.model('article', articleSchema);\n\nArticle.find({}) => [ {text:..., author: { _id:..., name:... /*auto-populated*/} } ]\n\n",
"I think it's better to export a variable somewhere that contains the list of all populated fields like :\nexport const POPULATED_FIELDS = ['filed1','field2']\n\nthen when you want to populate the fields just wrtie\nModel.findById('some_id').populate(POPULATED_FIELDS)\n\n"
] | [
6,
2
] | [] | [] | [
"mongodb",
"mongoose",
"node.js"
] | stackoverflow_0032407262_mongodb_mongoose_node.js.txt |
Q:
How can i use Select SUM in the column? PHP
Is it possible if i will sum and group by my table? instead of putting it in the variable i want it to display in the fetch data table
my table is something like this
name
qty
date
milktea
50
december 3 2022
milktea
100
december 1 2022
and when i use this query in the phpmyadmin
SELECT product_name, SUM(case when qty>0 then qty else 0 end) as total_stocks
FROM product_inventory GROUP BY product_name;
it works though but when i add it into my program to the contoller and models i start to received an error of data table fetch i'm using code igniter here is my code:
controller:
public function fetchProductData1()
{
if(!in_array('viewProduct', $this->permission)) {
redirect('dashboard', 'refresh');
}
$result = array('data' => array());
$data = $this->model_productstock->getProductData1();
foreach ($data as $key => $value) {
$availability = ($value['active'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
$result['data'][$key] = array(
$value['product_name'],
$value['qty'],
$availability,
);
} // /foreach
echo json_encode($result);
}
and in models:
public function getProductData1($id = null)
{
if($id) {
$sql = "SELECT * FROM product_inventory where id = ?";
$query = $this->db->query($sql, array($id));
return $query->row_array();
}
$user_id = $this->session->userdata('id');
if($user_id == 1) {
$sql = "SELECT * FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql);
return $query->result_array();
}
else {
$user_data = $this->model_users->getUserData($user_id);
$sql = "SELECT * FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql);
$data = array();
return $data;
}
}
as you can see i tired the group by and it's working but whenever i add the select sum it start to datatable fetch error i want my output to be:
name
qty
milktea
150
here is when i print the $result: here is the response
{"data":[["REG Okinawa","10","<span class=\"label label-success\">Active<\/span>"],["Tapsilog","45","<span class=\"label label-success\">Active<\/span>"]]}Array
(
[data] => Array
(
[0] => Array
(
[0] => REG Okinawa
[1] => 10
[2] => <span class="label label-success">Active</span>
)
[1] => Array
(
[0] => Tapsilog
[1] => 45
[2] => <span class="label label-success">Active</span>
)
)
)
A:
It looks like you're trying to sum the values of the qty column and display the result in your table. To do this, you can modify your getProductData1() method to include the SUM() function in your query like this:
public function getProductData1($id = null)
{
if($id) {
$sql = "SELECT * FROM product_inventory where id = ?";
$query = $this->db->query($sql, array($id));
return $query->row_array();
}
$user_id = $this->session->userdata('id');
if($user_id == 1) {
$sql = "SELECT product_name, SUM(qty) as total_qty, active FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql);
return $query->result_array();
}
else {
$user_data = $this->model_users->getUserData($user_id);
$sql = "SELECT product_name, SUM(qty) as total_qty, active FROM product_inventory WHERE qty > 0 AND user_id = ? GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql, array($user_id));
return $query->result_array();
}
}
Then, in your fetchProductData1() method, you can modify the foreach loop to display the total_qty value instead of the qty value like this:
public function fetchProductData1()
{
$result = array('data' => array());
$data = $this->model_products->getProductData1();
foreach ($data as $key => $value) {
$availability = ($value['active'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
$result['data'][$key] = array(
$value['product_name'],
$value['total_qty'],
$availability,
);
}
echo json_encode($result);
}
| How can i use Select SUM in the column? PHP | Is it possible if i will sum and group by my table? instead of putting it in the variable i want it to display in the fetch data table
my table is something like this
name
qty
date
milktea
50
december 3 2022
milktea
100
december 1 2022
and when i use this query in the phpmyadmin
SELECT product_name, SUM(case when qty>0 then qty else 0 end) as total_stocks
FROM product_inventory GROUP BY product_name;
it works though but when i add it into my program to the contoller and models i start to received an error of data table fetch i'm using code igniter here is my code:
controller:
public function fetchProductData1()
{
if(!in_array('viewProduct', $this->permission)) {
redirect('dashboard', 'refresh');
}
$result = array('data' => array());
$data = $this->model_productstock->getProductData1();
foreach ($data as $key => $value) {
$availability = ($value['active'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
$result['data'][$key] = array(
$value['product_name'],
$value['qty'],
$availability,
);
} // /foreach
echo json_encode($result);
}
and in models:
public function getProductData1($id = null)
{
if($id) {
$sql = "SELECT * FROM product_inventory where id = ?";
$query = $this->db->query($sql, array($id));
return $query->row_array();
}
$user_id = $this->session->userdata('id');
if($user_id == 1) {
$sql = "SELECT * FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql);
return $query->result_array();
}
else {
$user_data = $this->model_users->getUserData($user_id);
$sql = "SELECT * FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC";
$query = $this->db->query($sql);
$data = array();
return $data;
}
}
as you can see i tired the group by and it's working but whenever i add the select sum it start to datatable fetch error i want my output to be:
name
qty
milktea
150
here is when i print the $result: here is the response
{"data":[["REG Okinawa","10","<span class=\"label label-success\">Active<\/span>"],["Tapsilog","45","<span class=\"label label-success\">Active<\/span>"]]}Array
(
[data] => Array
(
[0] => Array
(
[0] => REG Okinawa
[1] => 10
[2] => <span class="label label-success">Active</span>
)
[1] => Array
(
[0] => Tapsilog
[1] => 45
[2] => <span class="label label-success">Active</span>
)
)
)
| [
"It looks like you're trying to sum the values of the qty column and display the result in your table. To do this, you can modify your getProductData1() method to include the SUM() function in your query like this:\npublic function getProductData1($id = null)\n{\n if($id) {\n $sql = \"SELECT * FROM product_inventory where id = ?\";\n $query = $this->db->query($sql, array($id));\n return $query->row_array();\n } \n \n $user_id = $this->session->userdata('id');\n if($user_id == 1) {\n $sql = \"SELECT product_name, SUM(qty) as total_qty, active FROM product_inventory WHERE qty > 0 GROUP BY product_name ORDER BY id ASC\";\n $query = $this->db->query($sql);\n return $query->result_array(); \n \n }\n else {\n $user_data = $this->model_users->getUserData($user_id);\n $sql = \"SELECT product_name, SUM(qty) as total_qty, active FROM product_inventory WHERE qty > 0 AND user_id = ? GROUP BY product_name ORDER BY id ASC\";\n $query = $this->db->query($sql, array($user_id));\n\n return $query->result_array(); \n }\n}\n\nThen, in your fetchProductData1() method, you can modify the foreach loop to display the total_qty value instead of the qty value like this:\npublic function fetchProductData1()\n{\n $result = array('data' => array());\n\n $data = $this->model_products->getProductData1();\n\n foreach ($data as $key => $value) {\n\n $availability = ($value['active'] == 1) ? '<span class=\"label label-success\">Active</span>' : '<span class=\"label label-danger\">Inactive</span>';\n\n $result['data'][$key] = array(\n $value['product_name'],\n $value['total_qty'],\n $availability,\n\n );\n }\n\n echo json_encode($result);\n}\n\n"
] | [
1
] | [] | [] | [
"codeigniter",
"codeigniter_3",
"php",
"select"
] | stackoverflow_0074675519_codeigniter_codeigniter_3_php_select.txt |
Q:
How can I get the correct DPI of my screen in WPF?
This may sound like a duplicate question, but I promise it is not. I have already looked at the answers provided in other questions, such as the one at the following link:
How can I get the DPI in WPF?
The problem is, they are not returning the correct DPI.
I know for a fact that my monitor (Dell U3415W) has a DPI of 109 ppi. The resolution is 3440x1440.
In WPF, I have attempted the following methods to get the DPI of my screen:
//Method 1
var dpi_scale = VisualTreeHelper.GetDpi(this);
double dpiX = dpi_scale.PixelsPerInchX;
double dpiY = dpi_scale.PixelsPerInchY;
//Method 2
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
{
double dpiX = g.DpiX;
double dpiY = g.DpiY;
}
//Method 3
PresentationSource source = PresentationSource.FromVisual(this);
double dpiX, dpiY;
if (source != null)
{
dpiX = 96.0 * source.CompositionTarget.TransformToDevice.M11;
dpiY = 96.0 * source.CompositionTarget.TransformToDevice.M22;
}
All three of the above methods return 192 as my DPI (The scale factor being returned in methods #1 and #3 is 2).
I am writing code in which I need to reliably display the distances (in physical units such as centimeters) between some objects on the screen, and this code will not just be running on my screen so I can't just hardcode "109" into it.
On a related note, I am mystified by what seems to be an instance of WPF using actual pixels instead of device-independent pixels.
I have the following XAML declaring a window with a simple grid and a rectangle inside of the grid:
<Window x:Class="MyTestWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="768"
Width="1024">
<Grid x:Name="MainObjectLocationGrid">
<Rectangle x:Name="MainObjectLocationRectangle" HorizontalAlignment="Left" VerticalAlignment="Top" />
</Grid>
</Window>
In the code-behind, I have some code that sets some properties on that rectangle:
MainObjectLocationRectangle.Width = 189.5625;
MainObjectLocationRectangle.Height = 146.4;
MainObjectLocationRectangle.Fill = new SolidColorBrush(Colors.White);
MainObjectLocationRectangle.Stroke = new SolidColorBrush(Colors.Transparent);
MainObjectLocationRectangle.StrokeThickness = 0;
MainObjectLocationRectangle.Margin = new Thickness(0, 0, 0, 0);
When my rectangle appears on the screen, the rectangle is 4.4cm x 3.4cm in size. WPF says that 1 device-independent pixel is 1/96th of an inch, so I would assume that 96 dip is 1 inch (which is 2.54 cm). Therefore 189.5625 dip should be 1.9746 inches (or 5.01 cm). Yet it seems that it isn't using dip in this instance. If we insert my monitor's actual resolution (109 dpi) into the equation, we get the actual size of the rectangle being displayed:
189.5625 pixels / 109 dpi = 1.7391 inches (or 4.4 cm)
Yet in the WPF documentation it states that the Width and Height properties use device-independent pixels:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.width?view=netframework-4.7.2#System_Windows_FrameworkElement_Width
So, to conclude:
(1) Why are all the accepted methods for querying the DPI not returning the correct DPI to me?
(2) Why does it seem like when I set the size of the rectangle, it is interpreting that size in units of pixels rather than device-independent pixels?
Thanks for any help!!!
A:
While Windows knows the resolution of the monitor, it doesn't appear to actually know the physical size of the monitor. And thus it has no means of determining the actual physical DPI. Windows simply assumes all screens are 96 dpi. If the user selects a scale factor in display settings, Windows adjusts the system dpi based upon that.
It is best for your app to have a calibration page, where it displays a line on the screen, and asks the user to measure it with a ruler and input the measurement. That would give you enough information to figure out the actual dpi of the screen. And technically, you'd need to do this both horizontally and vertically as the DPIs in each direction could, in theory, be different. (But I think in practice, they are almost always the same.)
A:
This is old question but you can get the physical specifications of a monitor from Windows.Devices.Display.DisplayMonitor.
Prepare to use WinRT, then call Windows.Devices.Enumeration.DeviceInformation.FindAllAsync method.
using Windows.Devices.Display;
using Windows.Devices.Enumeration;
public async Task CheckMonitors()
{
const string deviceInstanceIdKey = "System.Devices.DeviceInstanceId";
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DisplayMonitor.GetDeviceSelector(), new[] { deviceInstanceIdKey });
foreach (DeviceInformation? device in devices)
{
DisplayMonitor? monitor = await DisplayMonitor.FromInterfaceIdAsync(device.Id);
if (monitor is null)
continue;
Debug.WriteLine($"DeviceInstanceId: {device.Properties[deviceInstanceIdKey]}");
Debug.WriteLine($"DisplayName: {monitor.DisplayName}");
Debug.WriteLine($"PhysicalSizeInInches: {monitor.PhysicalSizeInInches}");
Debug.WriteLine($"RawDpiX: {monitor.RawDpiX}");
Debug.WriteLine($"RawDpiY: {monitor.RawDpiY}");
Debug.WriteLine($"NativeResolutionInRawPixels: {monitor.NativeResolutionInRawPixels.Width},{monitor.NativeResolutionInRawPixels.Height}");
}
}
In the case of Dell U2415, this code produces the following:
DisplayName: DELL U2415
PhysicalSizeInInches: 20.393702,12.755906
RawDpiX: 94.14671
RawDpiY: 94.074066
NativeResolutionInRawPixels: 1920,1200
Make a calculation as you wish.
| How can I get the correct DPI of my screen in WPF? | This may sound like a duplicate question, but I promise it is not. I have already looked at the answers provided in other questions, such as the one at the following link:
How can I get the DPI in WPF?
The problem is, they are not returning the correct DPI.
I know for a fact that my monitor (Dell U3415W) has a DPI of 109 ppi. The resolution is 3440x1440.
In WPF, I have attempted the following methods to get the DPI of my screen:
//Method 1
var dpi_scale = VisualTreeHelper.GetDpi(this);
double dpiX = dpi_scale.PixelsPerInchX;
double dpiY = dpi_scale.PixelsPerInchY;
//Method 2
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
{
double dpiX = g.DpiX;
double dpiY = g.DpiY;
}
//Method 3
PresentationSource source = PresentationSource.FromVisual(this);
double dpiX, dpiY;
if (source != null)
{
dpiX = 96.0 * source.CompositionTarget.TransformToDevice.M11;
dpiY = 96.0 * source.CompositionTarget.TransformToDevice.M22;
}
All three of the above methods return 192 as my DPI (The scale factor being returned in methods #1 and #3 is 2).
I am writing code in which I need to reliably display the distances (in physical units such as centimeters) between some objects on the screen, and this code will not just be running on my screen so I can't just hardcode "109" into it.
On a related note, I am mystified by what seems to be an instance of WPF using actual pixels instead of device-independent pixels.
I have the following XAML declaring a window with a simple grid and a rectangle inside of the grid:
<Window x:Class="MyTestWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="768"
Width="1024">
<Grid x:Name="MainObjectLocationGrid">
<Rectangle x:Name="MainObjectLocationRectangle" HorizontalAlignment="Left" VerticalAlignment="Top" />
</Grid>
</Window>
In the code-behind, I have some code that sets some properties on that rectangle:
MainObjectLocationRectangle.Width = 189.5625;
MainObjectLocationRectangle.Height = 146.4;
MainObjectLocationRectangle.Fill = new SolidColorBrush(Colors.White);
MainObjectLocationRectangle.Stroke = new SolidColorBrush(Colors.Transparent);
MainObjectLocationRectangle.StrokeThickness = 0;
MainObjectLocationRectangle.Margin = new Thickness(0, 0, 0, 0);
When my rectangle appears on the screen, the rectangle is 4.4cm x 3.4cm in size. WPF says that 1 device-independent pixel is 1/96th of an inch, so I would assume that 96 dip is 1 inch (which is 2.54 cm). Therefore 189.5625 dip should be 1.9746 inches (or 5.01 cm). Yet it seems that it isn't using dip in this instance. If we insert my monitor's actual resolution (109 dpi) into the equation, we get the actual size of the rectangle being displayed:
189.5625 pixels / 109 dpi = 1.7391 inches (or 4.4 cm)
Yet in the WPF documentation it states that the Width and Height properties use device-independent pixels:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.width?view=netframework-4.7.2#System_Windows_FrameworkElement_Width
So, to conclude:
(1) Why are all the accepted methods for querying the DPI not returning the correct DPI to me?
(2) Why does it seem like when I set the size of the rectangle, it is interpreting that size in units of pixels rather than device-independent pixels?
Thanks for any help!!!
| [
"While Windows knows the resolution of the monitor, it doesn't appear to actually know the physical size of the monitor. And thus it has no means of determining the actual physical DPI. Windows simply assumes all screens are 96 dpi. If the user selects a scale factor in display settings, Windows adjusts the system dpi based upon that.\nIt is best for your app to have a calibration page, where it displays a line on the screen, and asks the user to measure it with a ruler and input the measurement. That would give you enough information to figure out the actual dpi of the screen. And technically, you'd need to do this both horizontally and vertically as the DPIs in each direction could, in theory, be different. (But I think in practice, they are almost always the same.)\n",
"This is old question but you can get the physical specifications of a monitor from Windows.Devices.Display.DisplayMonitor.\nPrepare to use WinRT, then call Windows.Devices.Enumeration.DeviceInformation.FindAllAsync method.\nusing Windows.Devices.Display;\nusing Windows.Devices.Enumeration;\n\npublic async Task CheckMonitors()\n{\n const string deviceInstanceIdKey = \"System.Devices.DeviceInstanceId\";\n\n DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DisplayMonitor.GetDeviceSelector(), new[] { deviceInstanceIdKey });\n foreach (DeviceInformation? device in devices)\n {\n DisplayMonitor? monitor = await DisplayMonitor.FromInterfaceIdAsync(device.Id);\n if (monitor is null)\n continue;\n\n Debug.WriteLine($\"DeviceInstanceId: {device.Properties[deviceInstanceIdKey]}\");\n Debug.WriteLine($\"DisplayName: {monitor.DisplayName}\");\n Debug.WriteLine($\"PhysicalSizeInInches: {monitor.PhysicalSizeInInches}\");\n Debug.WriteLine($\"RawDpiX: {monitor.RawDpiX}\");\n Debug.WriteLine($\"RawDpiY: {monitor.RawDpiY}\");\n Debug.WriteLine($\"NativeResolutionInRawPixels: {monitor.NativeResolutionInRawPixels.Width},{monitor.NativeResolutionInRawPixels.Height}\");\n }\n}\n\nIn the case of Dell U2415, this code produces the following:\nDisplayName: DELL U2415\nPhysicalSizeInInches: 20.393702,12.755906\nRawDpiX: 94.14671\nRawDpiY: 94.074066\nNativeResolutionInRawPixels: 1920,1200\n\nMake a calculation as you wish.\n"
] | [
0,
0
] | [] | [] | [
"c#",
"dpi",
"wpf"
] | stackoverflow_0054659859_c#_dpi_wpf.txt |
Q:
Remove() function doesn't remove the element from BST
I'm trying to add a remove method to my BST But I just can't figure out what is wrong. I have defined the pointer variable using let but it's still not working. It seems like it doesn't update the root object.
const Node = (data, left = null, right = null) => {
return {data, left, right};
};
const Tree = array => {
const remDupsAndSort = array => {
const mergeSort = array => {
if(array.length <= 1) return array;
let leftArr = array.slice(0, array.length / 2);
let rightArr = array.slice(array.length / 2);
return merge(mergeSort(rightArr), mergeSort(leftArr))
};
const merge = (leftArr, rightArr) => {
let sorted = [];
while(leftArr.length && rightArr.length){
if(leftArr[0] < rightArr[0]){
sorted.push(leftArr.shift());
}else{
sorted.push(rightArr.shift());
}
};
return [...sorted, ...leftArr, ...rightArr]
};
return mergeSort([... new Set(array)])
};
array = remDupsAndSort(array);
const buildTree = (array, start, end) => {
if(start > end) return null;
let mid = Math.floor((start + end) / 2);
let node = Node(array[mid]);
node.left = buildTree(array, start, mid - 1);
node.right = buildTree(array, mid + 1, end);
return node;
};
const remove = value => {
if(!root) return root;
let pointer = root;
while(pointer){
if(value < pointer.data){
pointer = pointer.left
}
else if(value > pointer.data){
pointer = pointer.right;
}else{
if(!pointer.right && !pointer.left){
return null;
}
if(!pointer.left){
return pointer.right;
}else if(!pointer.right){
return pointer.left;
}else{
let nextBiggest = pointer.right;
while(nextBiggest.left){
nextBiggest = nextBiggest.left;
}
return pointer = nextBiggest;
}
}
}
};
let root = buildTree(array, 0, array.length - 1);
return {root, remove}
};
When I run the code it doesn't remove anything from the tree. What am I missing?
A:
let pointer = root; will assign the value of root to the pointer variable. Changing the value of pointer will not change the value of the original variable though. The variable is an object, and changing the key values within that object will cause the original to change.
So you either need to set the value of each key individually (which won't work really in this case because you want to set the whole value to be null sometimes), or you can track the parent value as you traverse through the tree so that you can modify parent.left and parent.right (or go a completely different route make a recursive removal function)
A:
Thanks to @abney317 the problem was solved by tracking the parent nodes. Although I'm not happiest with this code and it's not the most good looking code I've done, but I'm sharing it here just in case some one needed it.
const remove = value => {
if(!root) return root;
let pointer = root;
let parent = null;
while(pointer){
if(value < pointer.data){
parent = pointer;
pointer = pointer.left
}
else if(value > pointer.data){
parent = pointer;
pointer = pointer.right;
}else{
if(!pointer.right && !pointer.left){
if(pointer === parent.left) return parent.left = null;
if(pointer === parent.right) return parent.right = null;
}
if(!pointer.left){
if(pointer === parent.left) return parent.left = pointer.right
if(pointer === parent.right) return parent.right = pointer.right
}else if(!pointer.right){
if(pointer === parent.left) return parent.left = pointer.left
if(pointer === parent.right) return parent.right = pointer.left
}else{
let replacingNode = pointer.right;
let replacingParent = pointer;
while(replacingNode.left){
replacingParent = replacingNode;
replacingNode = replacingNode.left;
}
if(pointer === root){
replacingNode.right = root.right;
replacingNode.left = root.left;
root = replacingNode;
if(replacingNode === replacingParent.left) return replacingParent.left = null;
if(replacingNode === replacingParent.right) return replacingParent.right = null;
}
if(pointer === parent.left){
if(replacingNode === pointer.left){
replacingNode.left = null;
}else{
replacingNode.left = pointer.left;
}
if(replacingNode === pointer.right){
replacingNode.right = null;
}else{
replacingNode.right = pointer.right;
}
parent.left = replacingNode;
if(replacingNode === replacingParent.left) return replacingParent.left = null;
if(replacingNode === replacingParent.right) return replacingParent.right = null;
}
if(pointer === parent.right){
if(replacingNode === pointer.left){
replacingNode.left = null;
}else{
replacingNode.left = pointer.left;
}
if(replacingNode === pointer.right){
replacingNode.right = null;
}else{
replacingNode.right = pointer.right;
}
parent.right = replacingNode;
if(replacingNode === replacingParent.left) return replacingParent.left = null;
if(replacingNode === replacingParent.right) return replacingParent.right = null;
}
}
}
}
};
| Remove() function doesn't remove the element from BST | I'm trying to add a remove method to my BST But I just can't figure out what is wrong. I have defined the pointer variable using let but it's still not working. It seems like it doesn't update the root object.
const Node = (data, left = null, right = null) => {
return {data, left, right};
};
const Tree = array => {
const remDupsAndSort = array => {
const mergeSort = array => {
if(array.length <= 1) return array;
let leftArr = array.slice(0, array.length / 2);
let rightArr = array.slice(array.length / 2);
return merge(mergeSort(rightArr), mergeSort(leftArr))
};
const merge = (leftArr, rightArr) => {
let sorted = [];
while(leftArr.length && rightArr.length){
if(leftArr[0] < rightArr[0]){
sorted.push(leftArr.shift());
}else{
sorted.push(rightArr.shift());
}
};
return [...sorted, ...leftArr, ...rightArr]
};
return mergeSort([... new Set(array)])
};
array = remDupsAndSort(array);
const buildTree = (array, start, end) => {
if(start > end) return null;
let mid = Math.floor((start + end) / 2);
let node = Node(array[mid]);
node.left = buildTree(array, start, mid - 1);
node.right = buildTree(array, mid + 1, end);
return node;
};
const remove = value => {
if(!root) return root;
let pointer = root;
while(pointer){
if(value < pointer.data){
pointer = pointer.left
}
else if(value > pointer.data){
pointer = pointer.right;
}else{
if(!pointer.right && !pointer.left){
return null;
}
if(!pointer.left){
return pointer.right;
}else if(!pointer.right){
return pointer.left;
}else{
let nextBiggest = pointer.right;
while(nextBiggest.left){
nextBiggest = nextBiggest.left;
}
return pointer = nextBiggest;
}
}
}
};
let root = buildTree(array, 0, array.length - 1);
return {root, remove}
};
When I run the code it doesn't remove anything from the tree. What am I missing?
| [
"let pointer = root; will assign the value of root to the pointer variable. Changing the value of pointer will not change the value of the original variable though. The variable is an object, and changing the key values within that object will cause the original to change.\nSo you either need to set the value of each key individually (which won't work really in this case because you want to set the whole value to be null sometimes), or you can track the parent value as you traverse through the tree so that you can modify parent.left and parent.right (or go a completely different route make a recursive removal function)\n",
"Thanks to @abney317 the problem was solved by tracking the parent nodes. Although I'm not happiest with this code and it's not the most good looking code I've done, but I'm sharing it here just in case some one needed it.\nconst remove = value => {\n if(!root) return root;\n let pointer = root;\n let parent = null;\n while(pointer){\n if(value < pointer.data){\n parent = pointer;\n pointer = pointer.left\n }\n else if(value > pointer.data){\n parent = pointer;\n pointer = pointer.right;\n }else{\n if(!pointer.right && !pointer.left){\n if(pointer === parent.left) return parent.left = null;\n if(pointer === parent.right) return parent.right = null;\n }\n if(!pointer.left){\n if(pointer === parent.left) return parent.left = pointer.right\n if(pointer === parent.right) return parent.right = pointer.right\n }else if(!pointer.right){\n if(pointer === parent.left) return parent.left = pointer.left\n if(pointer === parent.right) return parent.right = pointer.left\n }else{\n let replacingNode = pointer.right;\n let replacingParent = pointer;\n while(replacingNode.left){\n replacingParent = replacingNode;\n replacingNode = replacingNode.left;\n }\n if(pointer === root){\n replacingNode.right = root.right;\n replacingNode.left = root.left;\n root = replacingNode;\n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n\n }\n if(pointer === parent.left){\n if(replacingNode === pointer.left){\n replacingNode.left = null;\n }else{\n replacingNode.left = pointer.left;\n }\n if(replacingNode === pointer.right){\n replacingNode.right = null;\n }else{\n replacingNode.right = pointer.right;\n }\n parent.left = replacingNode;\n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n } \n if(pointer === parent.right){\n if(replacingNode === pointer.left){\n replacingNode.left = null;\n }else{\n replacingNode.left = pointer.left;\n }\n if(replacingNode === pointer.right){\n replacingNode.right = null;\n }else{\n replacingNode.right = pointer.right;\n }\n parent.right = replacingNode; \n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n } \n } \n }\n }\n };\n\n"
] | [
1,
0
] | [] | [] | [
"binary_search_tree",
"javascript"
] | stackoverflow_0074663754_binary_search_tree_javascript.txt |
Q:
React: Passing a dictionary of functions but somehow failing to access it correctly
I have an App component where I define two functions A and B.
I am then passing these two functions to a Card component as follow
<Card
key = {el.key}
item={el}
onPress={{
select : ()=>A(el.key),
discard : ()=>B(el.key)
}}
/>
however, for some reason, when inside my Card i do something like
....
<div
className={className}
onClick={props.onPress.select}>
</div>
...
I get this nasty error
react-dom.development.js:18687 The above error occurred in the <Card> component:
at Card (http://localhost:5174/src/components/Card.jsx?t=1670102247232:33:48)
at div
at div
at div
at App (http://localhost:5174/src/App.jsx?t=1670102247232:24:31)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'select')
at Card (Card.jsx:28:32)
at renderWithHooks (react-dom.development.js:16305:18)
at mountIndeterminateComponent (react-dom.development.js:20074:13)
at beginWork (react-dom.development.js:21587:16)
at beginWork$1 (react-dom.development.js:27426:14)
at performUnitOfWork (react-dom.development.js:26557:12)
at workLoopSync (react-dom.development.js:26466:5)
at renderRootSync (react-dom.development.js:26434:7)
at recoverFromConcurrentError (react-dom.development.js:25850:20)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:22)
what am I doing wrong?
Here below both the App code and the Card code
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import Card from './components/Card'
import data from "./assets/data.json"
import {nanoid} from "nanoid"
function App() {
const [people, setPeople] = useState(data['people'].map(
el=>{
return {
...el,
'key' : nanoid(),
}
}
))
const [myCard, setMyCard] = useState(
{
"name":"Name and Surname",
"img":"https://i.picsum.photos/id/1070/200/300.jpg?hmac=dJNTYlLwT_0RupxbJNbw5Wj-q2cCTB4Xh-GqWRofIIc",
"description": "This is a silly descriptionhis is a silly descriptionhis is a silly description",
'key' : nanoid(),
"selected":false,
"active":true,
}
)
function SelectCard(CardKey){
console.log('SelectCard')
setPeople(oldPeople=>{
return oldPeople.map(el=>{
return el.key === CardKey
? { ...el, 'state': el.state === 'active'?'selected': 'active'}
: { ...el, 'state':'active'}
})
})
}
function DiscardCard(CardKey){
console.log('DiscardCard')
setPeople(oldPeople=>{
return oldPeople.map(el=>{
return el.key === CardKey
? { ...el, 'state': el.state === 'discarded'?'active': 'discarded'}
: { ...el}
})
})
}
const cards = people.map(el=>{
return <Card
key = {el.key}
item={el}
onPress={{
select : ()=>SelectCard(el.key),
discard : ()=>DiscardCard(el.key)
}}
/>
})
return (
<div className="App">
<div className='container'>
<div className='left'>
<div className='cards'>
{cards}
</div>
</div>
<div className = 'right'>
<h4>You are: </h4>
<Card key = {myCard.key} item={myCard}/>
</div>
</div>
</div>
)
}
export default App
and the card
import { useState } from 'react'
function Card(props) {
//const [count, setCount] = useState(0)
function getClassName(state) {
switch (state) {
case "active":
return "";
case "selected":
return "overlay-selected";
case "discarded":
return "overlay-discarded";
case "complete":
return "overlay-complete";
default:
return "";
}
}
const className = `card ${getClassName(props.item.state)}`
return (
<div
className={className}
onClick={props.onPress.select}>
<img className='card-img' alt='Card Image' src={props.item.img} />
<h3 className='card-title'>{props.item.name} </h3>
{ props.item.state === 'selected' ?
<div className='card-cta'>
<button
className='btn btn-back'
onClick={ props.item.selected ? (event)=>
{
props.onPress.select
//event.stopPropagation()
}
: ()=>{}}
>Back</button>
<button
className='btn btn-discard'
onClick={
(event) =>{
//event.stopPropagation()
props.onPress.discard
console.log('called me')
}
}
>Discard</button>
</div>
:
<p className='card-description'>{props.item.description} </p>
}
</div>
)
}
export default Card
A:
This happens for the
<h4>You are: </h4>
<Card key={myCard.key} item={myCard} />
where you do not pass any onPress property.
So you need to either pass dummy methods for this case as well, or use the optional chaining operator ?., like so props.onPress?.select
Additionally, you should actually call the methods from your buttons
so
(event) =>{
//event.stopPropagation()
props.onPress.discard
console.log('called me')
}
should become
(event) =>{
//event.stopPropagation()
props.onPress.discard() // <-- added the () here
console.log('called me')
}
| React: Passing a dictionary of functions but somehow failing to access it correctly | I have an App component where I define two functions A and B.
I am then passing these two functions to a Card component as follow
<Card
key = {el.key}
item={el}
onPress={{
select : ()=>A(el.key),
discard : ()=>B(el.key)
}}
/>
however, for some reason, when inside my Card i do something like
....
<div
className={className}
onClick={props.onPress.select}>
</div>
...
I get this nasty error
react-dom.development.js:18687 The above error occurred in the <Card> component:
at Card (http://localhost:5174/src/components/Card.jsx?t=1670102247232:33:48)
at div
at div
at div
at App (http://localhost:5174/src/App.jsx?t=1670102247232:24:31)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'select')
at Card (Card.jsx:28:32)
at renderWithHooks (react-dom.development.js:16305:18)
at mountIndeterminateComponent (react-dom.development.js:20074:13)
at beginWork (react-dom.development.js:21587:16)
at beginWork$1 (react-dom.development.js:27426:14)
at performUnitOfWork (react-dom.development.js:26557:12)
at workLoopSync (react-dom.development.js:26466:5)
at renderRootSync (react-dom.development.js:26434:7)
at recoverFromConcurrentError (react-dom.development.js:25850:20)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:22)
what am I doing wrong?
Here below both the App code and the Card code
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import Card from './components/Card'
import data from "./assets/data.json"
import {nanoid} from "nanoid"
function App() {
const [people, setPeople] = useState(data['people'].map(
el=>{
return {
...el,
'key' : nanoid(),
}
}
))
const [myCard, setMyCard] = useState(
{
"name":"Name and Surname",
"img":"https://i.picsum.photos/id/1070/200/300.jpg?hmac=dJNTYlLwT_0RupxbJNbw5Wj-q2cCTB4Xh-GqWRofIIc",
"description": "This is a silly descriptionhis is a silly descriptionhis is a silly description",
'key' : nanoid(),
"selected":false,
"active":true,
}
)
function SelectCard(CardKey){
console.log('SelectCard')
setPeople(oldPeople=>{
return oldPeople.map(el=>{
return el.key === CardKey
? { ...el, 'state': el.state === 'active'?'selected': 'active'}
: { ...el, 'state':'active'}
})
})
}
function DiscardCard(CardKey){
console.log('DiscardCard')
setPeople(oldPeople=>{
return oldPeople.map(el=>{
return el.key === CardKey
? { ...el, 'state': el.state === 'discarded'?'active': 'discarded'}
: { ...el}
})
})
}
const cards = people.map(el=>{
return <Card
key = {el.key}
item={el}
onPress={{
select : ()=>SelectCard(el.key),
discard : ()=>DiscardCard(el.key)
}}
/>
})
return (
<div className="App">
<div className='container'>
<div className='left'>
<div className='cards'>
{cards}
</div>
</div>
<div className = 'right'>
<h4>You are: </h4>
<Card key = {myCard.key} item={myCard}/>
</div>
</div>
</div>
)
}
export default App
and the card
import { useState } from 'react'
function Card(props) {
//const [count, setCount] = useState(0)
function getClassName(state) {
switch (state) {
case "active":
return "";
case "selected":
return "overlay-selected";
case "discarded":
return "overlay-discarded";
case "complete":
return "overlay-complete";
default:
return "";
}
}
const className = `card ${getClassName(props.item.state)}`
return (
<div
className={className}
onClick={props.onPress.select}>
<img className='card-img' alt='Card Image' src={props.item.img} />
<h3 className='card-title'>{props.item.name} </h3>
{ props.item.state === 'selected' ?
<div className='card-cta'>
<button
className='btn btn-back'
onClick={ props.item.selected ? (event)=>
{
props.onPress.select
//event.stopPropagation()
}
: ()=>{}}
>Back</button>
<button
className='btn btn-discard'
onClick={
(event) =>{
//event.stopPropagation()
props.onPress.discard
console.log('called me')
}
}
>Discard</button>
</div>
:
<p className='card-description'>{props.item.description} </p>
}
</div>
)
}
export default Card
| [
"This happens for the\n<h4>You are: </h4>\n<Card key={myCard.key} item={myCard} />\n\nwhere you do not pass any onPress property.\nSo you need to either pass dummy methods for this case as well, or use the optional chaining operator ?., like so props.onPress?.select\n\nAdditionally, you should actually call the methods from your buttons\nso\n(event) =>{\n //event.stopPropagation()\n props.onPress.discard\n console.log('called me')\n}\n\nshould become\n(event) =>{\n //event.stopPropagation()\n props.onPress.discard() // <-- added the () here\n console.log('called me')\n}\n\n"
] | [
0
] | [] | [] | [
"javascript",
"reactjs"
] | stackoverflow_0074675346_javascript_reactjs.txt |
Q:
How to add Toggle Class to links with React.js?
I need to add toggle class active after clicking on the links has menu.
const AllLinksNavbar = Array.from(
document.querySelectorAll(".has-menu")
)
AllLinksNavbar.forEach( element => {
element.addEventListener('click', (e) => {
e.preventDefault();
element.classList.toggle('active')
});
} )
A:
in react we work with states.
you need to create state with const [className, setClassName] = useState("someClass");
then you need to change this class by the function setClassName
onClick={()=>{
if(className.includes("active")){
setClassName(className.replace("active",""))
} else {
setClassName(className + " active")
}
}}
then use this state as a class name for the element
<div className={className}> </div>
| How to add Toggle Class to links with React.js? | I need to add toggle class active after clicking on the links has menu.
const AllLinksNavbar = Array.from(
document.querySelectorAll(".has-menu")
)
AllLinksNavbar.forEach( element => {
element.addEventListener('click', (e) => {
e.preventDefault();
element.classList.toggle('active')
});
} )
| [
"in react we work with states.\nyou need to create state with const [className, setClassName] = useState(\"someClass\");\nthen you need to change this class by the function setClassName\nonClick={()=>{ \n if(className.includes(\"active\")){\n setClassName(className.replace(\"active\",\"\"))\n } else {\n setClassName(className + \" active\")\n }\n}}\n\nthen use this state as a class name for the element\n<div className={className}> </div>\n\n"
] | [
0
] | [] | [] | [
"array.prototype.map",
"javascript",
"jquery",
"reactjs",
"redux"
] | stackoverflow_0074675301_array.prototype.map_javascript_jquery_reactjs_redux.txt |
Q:
How to find element with "== $0" after end tag in html using Xpath, css or any other locators in Selenium Python?
the html tag
<div class=""><div>Bengaluru, Karnataka</div></div>
Consider the above example for reference.
I tried the following code but it doesn't work!!!
driver.find_element(By.XPATH,'//div[@class=""]').text.strip()
A:
You can use this:
driver.find_element(By.XPATH, ".//div[@class='']/div").text
Output:
Bengaluru, Karnataka
A:
You can not filter by that "==$0"
But you can use this xpath, which will return to you the element with following requirements:
It is a "div"
That "div" contains an attribute "class"
That "class" attribute has a length of 0 chars
This is the xpath:
//div[@class[string-length()=0]]
| How to find element with "== $0" after end tag in html using Xpath, css or any other locators in Selenium Python? | the html tag
<div class=""><div>Bengaluru, Karnataka</div></div>
Consider the above example for reference.
I tried the following code but it doesn't work!!!
driver.find_element(By.XPATH,'//div[@class=""]').text.strip()
| [
"You can use this:\ndriver.find_element(By.XPATH, \".//div[@class='']/div\").text\n\nOutput:\nBengaluru, Karnataka\n\n",
"You can not filter by that \"==$0\"\nBut you can use this xpath, which will return to you the element with following requirements:\n\nIt is a \"div\"\nThat \"div\" contains an attribute \"class\"\nThat \"class\" attribute has a length of 0 chars\n\nThis is the xpath:\n//div[@class[string-length()=0]]\n\n"
] | [
0,
0
] | [] | [] | [
"html",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074675452_html_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Display different background color for DIV's, based on a result individual digits value 0/1
In a form, I'm forming a string with java script and collecting it's result into a SQLite table the state of 12 checkboxes, under a string of binary values like "000011111100" .
<script>
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("mounths").textContent = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
document.getElementById("results").innerHTML = document.getElementById("mounths").innerHTML;
}
</script>
After the string is formed is sent through POST method into a SQLite table.
Calling back this value is also simple because I can echo it with a PHP script (more or less like this)
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT months FROM MyTable where MyID='this_value'");
$stmt->execute();
$data = $stmt->fetchcolumn(PDO::FETCH_ASSOC);
if ( !empty($data) ) {
echo $data['mounths'];
}
} else {
echo "Record missing!";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This value is not needed to be visible, I can hide it or not echo it at all.
But I want to use it in a different way.
When I recall this value, I want it to break it into it's individual values of "0" and "1" and according to these values, I want to color 12 DIVs (or table cells) into some predefined colors:
$color1 = red;
$color2 = white;
I know that for reaching my goal, I should do something like from here, and somehow adapting it:
Change Row background color based on cell value
$data( function(value){
if(value == "0"){
html += '<div style="background-color: red;">'+some_content+'</div>';
}
else{
html += '<div style="background-color: white;">'+some_content+'</div>';
}
});
I found some similar questions (coloring and splitting) in these articles, but nothing I could apply just by myself:
PHP - Display different image based on mysql row result
Split into different rows based on condition
SQL - Split Row into multiple based on month
different color of row based on result in PHP
Split SQL rows array into multiple arrays based on date
Split a div background color based on $index in ng-repeat
Can you help me to achieve something like this: starting from the step where I recall the string value from the database (database column name "mounths") ?
<p hidden><?php echo $data['mounths']; ?></p>
If hiding the result is not necessary is even better.
A:
$html = ''; // predefine $html in case array is empty
foreach($data as $column=>$value){
$color = !$value ? 'red' : 'white'; // set color based on value
$html.="<div style='color:$color;'>--Some-Content--</div>"; // append to html
}
echo $html;
A:
If I make individual inserts into my SQLite table for every months,
I can manage to change the background of the DIV's or table cells (TD's)
to achieve this :
(colors are defined in external CSS file based on class used in TD's) and the used code for that is this one (probably not the most elegant but a working one):
<?php
$IDmush = $_GET['IDmush'];
try
{
$conn = new PDO('sqlite:db/myDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM myTable WHERE myID='$myID'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($data))
{
foreach ($data as $row) // I'm not sure if FOREACH is needed here
{
echo "<table><tr>";
if ($row['jan'] == '1')
{
echo "<td class='season1' >Jan</td>";
}
else
{
echo "<td class='season2' >Jan</td>";
}
if ($row['feb'] == '1')
{
echo "<td class='season1' >Feb</td>";
}
else
{
echo "<td class='season2' >Feb</td>";
}
if ($row['mar'] == '1')
{
echo "<td class='season1' >Mar</td>";
}
else
{
echo "<td class='season2' >Mar</td>";
}
if ($row['apr'] == '1')
{
echo "<td class='season1' >Apr</td>";
}
else
{
echo "<td class='season2' >Apr</td>";
}
if ($row['mai'] == '1')
{
echo "<td class='season1' >May</td>";
}
else
{
echo "<td class='season2' >May</td>";
}
if ($row['jun'] == '1')
{
echo "<td class='season1' >Jun</td>";
}
else
{
echo "<td class='season2' >Jun</td>";
}
if ($row['jul'] == '1')
{
echo "<td class='season1' >Jul</td>";
}
else
{
echo "<td class='season2' >Jul</td>";
}
if ($row['aug'] == '1')
{
echo "<td class='season1' >Aug</td>";
}
else
{
echo "<td class='season2' >Aug</td>";
}
if ($row['sep'] == '1')
{
echo "<td class='season1' >Sep</td>";
}
else
{
echo "<td class='season2' >Sep</td>";
}
if ($row['oct'] == '1')
{
echo "<td class='season1' >Oct</td>";
}
else
{
echo "<td class='season2' >Oct</td>";
}
if ($row['nov'] == '1')
{
echo "<td class='season1' >Nov</td>";
}
else
{
echo "<td class='season2' >Nov</td>";
}
if ($row['dec'] == '1')
{
echo "<td class='season1' >Dec</td>";
}
else
{
echo "<td class='season2' >Dec</td>";
}
echo "</tr></table>";
}
}
else
{
echo "No records found.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
But again, since my database already has over 2.5k records, registered with the season in a string format like ("000000111100", "001111110000", "111111111111"...).
Please help me with a full code to break these strings again in basic digits, associate every digits to a month, display the months and apply the background color to them as in the above image.
My code works with individual records, but i want to use the database as it is, without alteration, because it's used by others as well and would be verry inconvenient to remodel it now. Thank you.
| Display different background color for DIV's, based on a result individual digits value 0/1 | In a form, I'm forming a string with java script and collecting it's result into a SQLite table the state of 12 checkboxes, under a string of binary values like "000011111100" .
<script>
const checkboxes = [...document.querySelectorAll('input[type=checkbox]')];
function RegMD() {
document.getElementById("mounths").textContent = checkboxes.reduce((a, b) => a + (b.checked ? 1 : 0), "");
document.getElementById("results").innerHTML = document.getElementById("mounths").innerHTML;
}
</script>
After the string is formed is sent through POST method into a SQLite table.
Calling back this value is also simple because I can echo it with a PHP script (more or less like this)
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT months FROM MyTable where MyID='this_value'");
$stmt->execute();
$data = $stmt->fetchcolumn(PDO::FETCH_ASSOC);
if ( !empty($data) ) {
echo $data['mounths'];
}
} else {
echo "Record missing!";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This value is not needed to be visible, I can hide it or not echo it at all.
But I want to use it in a different way.
When I recall this value, I want it to break it into it's individual values of "0" and "1" and according to these values, I want to color 12 DIVs (or table cells) into some predefined colors:
$color1 = red;
$color2 = white;
I know that for reaching my goal, I should do something like from here, and somehow adapting it:
Change Row background color based on cell value
$data( function(value){
if(value == "0"){
html += '<div style="background-color: red;">'+some_content+'</div>';
}
else{
html += '<div style="background-color: white;">'+some_content+'</div>';
}
});
I found some similar questions (coloring and splitting) in these articles, but nothing I could apply just by myself:
PHP - Display different image based on mysql row result
Split into different rows based on condition
SQL - Split Row into multiple based on month
different color of row based on result in PHP
Split SQL rows array into multiple arrays based on date
Split a div background color based on $index in ng-repeat
Can you help me to achieve something like this: starting from the step where I recall the string value from the database (database column name "mounths") ?
<p hidden><?php echo $data['mounths']; ?></p>
If hiding the result is not necessary is even better.
| [
"$html = ''; // predefine $html in case array is empty \nforeach($data as $column=>$value){\n $color = !$value ? 'red' : 'white'; // set color based on value\n $html.=\"<div style='color:$color;'>--Some-Content--</div>\"; // append to html\n}\necho $html;\n\n",
"If I make individual inserts into my SQLite table for every months,\nI can manage to change the background of the DIV's or table cells (TD's)\nto achieve this :\n\n(colors are defined in external CSS file based on class used in TD's) and the used code for that is this one (probably not the most elegant but a working one):\n<?php\n$IDmush = $_GET['IDmush'];\ntry\n{\n $conn = new PDO('sqlite:db/myDatabase.db');\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $stmt = $conn->prepare(\"SELECT * FROM myTable WHERE myID='$myID'\");\n $stmt->execute();\n $data = $stmt->fetchAll(PDO::FETCH_ASSOC);\n if (!empty($data))\n {\n foreach ($data as $row) // I'm not sure if FOREACH is needed here\n {\n echo \"<table><tr>\";\n if ($row['jan'] == '1')\n {\n echo \"<td class='season1' >Jan</td>\";\n }\n else\n {\n echo \"<td class='season2' >Jan</td>\";\n }\n if ($row['feb'] == '1')\n {\n echo \"<td class='season1' >Feb</td>\";\n }\n else\n {\n echo \"<td class='season2' >Feb</td>\";\n }\n if ($row['mar'] == '1')\n {\n echo \"<td class='season1' >Mar</td>\";\n }\n else\n {\n echo \"<td class='season2' >Mar</td>\";\n }\n if ($row['apr'] == '1')\n {\n echo \"<td class='season1' >Apr</td>\";\n }\n else\n {\n echo \"<td class='season2' >Apr</td>\";\n }\n if ($row['mai'] == '1')\n {\n echo \"<td class='season1' >May</td>\";\n }\n else\n {\n echo \"<td class='season2' >May</td>\";\n }\n if ($row['jun'] == '1')\n {\n echo \"<td class='season1' >Jun</td>\";\n }\n else\n {\n echo \"<td class='season2' >Jun</td>\";\n }\n if ($row['jul'] == '1')\n {\n echo \"<td class='season1' >Jul</td>\";\n }\n else\n {\n echo \"<td class='season2' >Jul</td>\";\n }\n if ($row['aug'] == '1')\n {\n echo \"<td class='season1' >Aug</td>\";\n }\n else\n {\n echo \"<td class='season2' >Aug</td>\";\n }\n if ($row['sep'] == '1')\n {\n echo \"<td class='season1' >Sep</td>\";\n }\n else\n {\n echo \"<td class='season2' >Sep</td>\";\n }\n if ($row['oct'] == '1')\n {\n echo \"<td class='season1' >Oct</td>\";\n }\n else\n {\n echo \"<td class='season2' >Oct</td>\";\n }\n if ($row['nov'] == '1')\n {\n echo \"<td class='season1' >Nov</td>\";\n }\n else\n {\n echo \"<td class='season2' >Nov</td>\";\n }\n if ($row['dec'] == '1')\n {\n echo \"<td class='season1' >Dec</td>\";\n }\n else\n {\n echo \"<td class='season2' >Dec</td>\";\n }\n echo \"</tr></table>\";\n }\n }\n else\n {\n echo \"No records found.\";\n }\n}\ncatch(PDOException $e)\n{\n echo \"Error: \" . $e->getMessage();\n}\n$conn = null;\n?>\n\nBut again, since my database already has over 2.5k records, registered with the season in a string format like (\"000000111100\", \"001111110000\", \"111111111111\"...).\nPlease help me with a full code to break these strings again in basic digits, associate every digits to a month, display the months and apply the background color to them as in the above image.\nMy code works with individual records, but i want to use the database as it is, without alteration, because it's used by others as well and would be verry inconvenient to remodel it now. Thank you.\n"
] | [
0,
0
] | [] | [] | [
"css",
"javascript",
"php"
] | stackoverflow_0074317616_css_javascript_php.txt |
Q:
An issue in checkout page
Hi there I have wordpress site , and someone wrote plugin for me , and now when I installed on my website I'm getting this errors on my "checkout" page :
Warning: Illegal string offset 'snumber' in /home/afraa/public_html/wp-content/plugins/avin-customize2/avin-customize.php on line 176
Fatal error: Uncaught Error: Call to undefined method stdClass::get_label() in /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php:354 Stack trace: #0 /home/afraa/public_html/wp-content/themes/zanbil/woocommerce/cart/cart-shipping.php(39): wc_cart_totals_shipping_method_label(Object(stdClass)) #1 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(345): include('/home/afraa/pub...') #2 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php(236): wc_get_template('cart/cart-shipp...', Array) #3 /home/afraa/public_html/wp-content/themes/zanbil/woocommerce/cart/cart-totals.php(46): wc_cart_totals_shipping_html() #4 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(345): include('/home/afraa/pub...') #5 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-template-functions.php(2136): wc_get_template('cart/cart-total...') #6 /home/afraa/public_html/wp-includes/class-wp-hook.php(30 in /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php on line 354
when I checked the lines I didn't get anything wrong , can anyone help me to fix this ?
these are the lines :
$fields['billing']['billing_s_number'] = array(
'label' => 'Ψ΄Ω
Ψ§Ψ±Ω Ψ«Ψ¨Ψͺ',
'required' => false,
'clear' => false,
'class' => array('du-none'),
'type' => 'text',
this is the line 176 : 'default' => get_user_meta(get_current_user_id(), 'company_data', true)['snumber'] ?: ""
);
please anyone who know PHP please help me to fix this
A:
get_user_meta(get_current_user_id(), 'company_data', true) don't have snumber key.
Could you try :
isset(get_user_meta(get_current_user_id(), 'company_data', true)['snumber']) ? get_user_meta(get_current_user_id(), 'company_data', true)['snumber']: ""
Regards,
| An issue in checkout page | Hi there I have wordpress site , and someone wrote plugin for me , and now when I installed on my website I'm getting this errors on my "checkout" page :
Warning: Illegal string offset 'snumber' in /home/afraa/public_html/wp-content/plugins/avin-customize2/avin-customize.php on line 176
Fatal error: Uncaught Error: Call to undefined method stdClass::get_label() in /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php:354 Stack trace: #0 /home/afraa/public_html/wp-content/themes/zanbil/woocommerce/cart/cart-shipping.php(39): wc_cart_totals_shipping_method_label(Object(stdClass)) #1 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(345): include('/home/afraa/pub...') #2 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php(236): wc_get_template('cart/cart-shipp...', Array) #3 /home/afraa/public_html/wp-content/themes/zanbil/woocommerce/cart/cart-totals.php(46): wc_cart_totals_shipping_html() #4 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(345): include('/home/afraa/pub...') #5 /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-template-functions.php(2136): wc_get_template('cart/cart-total...') #6 /home/afraa/public_html/wp-includes/class-wp-hook.php(30 in /home/afraa/public_html/wp-content/plugins/woocommerce/includes/wc-cart-functions.php on line 354
when I checked the lines I didn't get anything wrong , can anyone help me to fix this ?
these are the lines :
$fields['billing']['billing_s_number'] = array(
'label' => 'Ψ΄Ω
Ψ§Ψ±Ω Ψ«Ψ¨Ψͺ',
'required' => false,
'clear' => false,
'class' => array('du-none'),
'type' => 'text',
this is the line 176 : 'default' => get_user_meta(get_current_user_id(), 'company_data', true)['snumber'] ?: ""
);
please anyone who know PHP please help me to fix this
| [
"get_user_meta(get_current_user_id(), 'company_data', true) don't have snumber key.\nCould you try :\nisset(get_user_meta(get_current_user_id(), 'company_data', true)['snumber']) ? get_user_meta(get_current_user_id(), 'company_data', true)['snumber']: \"\"\n\nRegards,\n"
] | [
0
] | [] | [] | [
"checkout",
"custom_wordpress_pages",
"php",
"wordpress",
"wordpress_gutenberg"
] | stackoverflow_0074675395_checkout_custom_wordpress_pages_php_wordpress_wordpress_gutenberg.txt |
Q:
Access denied when creating keystore for Android app
I am trying to sign my Android app so I can release it in Market. When I generate the keystore, I get an access denied error. How do I fix this?
This is what I've been trying to do:
Right click project in Eclipse Helios.
Android Tools > Export Signed Application Package.
Click next.
I check "Create new keystore" and realize it does nothing to help me. It still asks for the location of keystore. So I decide to do it the hard way.
Turned off read-only access on C:\Program Files\Java\jdk1.6.0_25\bin and granted the CREATOR OWNER group full control of the folder.
Open command line on Windows 7 64-bit.
Traverse to C:\Program Files\Java\jdk1.6.0_25\bin.
Run keytool.
Got an access denied error.
.
C:\Program Files\Java\jdk1.6.0_25\bin>keytool -genkey -v -alias company -keyalg R
SA -keysize 2048 -validity 10000 -keystore company.keystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: John Smith
What is the name of your organizational unit?
[Unknown]: Android
What is the name of your organization?
[Unknown]: Company
What is the name of your City or Locality?
[Unknown]: Albany
What is the name of your State or Province?
[Unknown]: NY
What is the two-letter country code for this unit?
[Unknown]: US
Is CN=John Smith, OU=Android, O=Company, L=Albany, ST=NY, C=US correct?
[no]: yes
Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with
a validity of 10,000 days
for: CN=John Smith, OU=Android, O=Company, L=Albany, ST=NY, C=US
Enter key password for <veetle>
(RETURN if same as keystore password):
Re-enter new password:
[Storing company.keystore]
keytool error: java.io.FileNotFoundException: veetle.keystore (Access is denied)
java.io.FileNotFoundException: veetle.keystore (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
at sun.security.tools.KeyTool.doCommands(KeyTool.java:902)
at sun.security.tools.KeyTool.run(KeyTool.java:172)
at sun.security.tools.KeyTool.main(KeyTool.java:166)
Edit:
Everytime I check the folder permissions, I see that it has reverted back to read-only. There were no errors whenever I turned off read-only.
A:
Below steps worked for me:
Run command prompt as administrator
Unchecked the read only options in C:\Program Files\Java\jdk1.6.0_25\bin This may not be required
keytool -genkey -v -keystore d:\my_private_key.keystore -alias my_key_alias -keyalg RSA -keysize 2048 -validity 10000
Tell it to create it in drive D:.
A:
It does help you. You have to specify the location of the file that will be generated. For example specify C:\Documents and Settings\loginname\market.keystore
A:
Access denied because you are not an admin.
Simply open the cmd prompt as an administrator - that worked for me.
A:
The keystore that the Android SDK needs access to is not the same of the JDK. You can simply use the "create new keystore" option of the Android wizard and choose any folder you have write access to: the wizard will create there a new keystore. You don't need to use keytool form JDK.
A:
opening Command Prompt as a Administrator helped me.(For Windows 8.1)
A:
I had the same problem. You need to define your JAVA_HOME environment variable.
Read the "Basic Setup for signing" paragraph of this link : http://developer.android.com/guide/publishing/app-signing.html#setup
It says:
Before you begin, make sure that the Keytool utility and Jarsigner utility are available to the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell the SDK build tools how to find these utilities by setting your JAVA_HOME environment variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and Jarsigner to your PATH variable.
If you are developing on a version of Linux that originally came with GNU Compiler for Java, make sure that the system is using the JDK version of Keytool, rather than the gcj version. If Keytool is already in your PATH, it might be pointing to a symlink at /usr/bin/keytool. In this case, check the symlink target to be sure it points to the Keytool in the JDK.
A:
Fixing the problem on win7 (yuk) without Eclipse:
i have the environment variable JAVA_HOME set to ..../JDK1.7.0_03 (android programmed from GLbasic), and i did only 2 things to fix the problem:
1) in the folder ..../Java/JDK1.7.0_03 i removed the "read-only" permission of the /bin sub-folder, which contains keytool.exe.
2) i opened the console "as administrator" (although it's the only account on my win7).
then you do cd...JDK / bin, run again keytool.exe, and you get the file nickname.keystore auto-generated in JDK / bin.
Once everything is done you could re-assign the "read-only" permission.
Good luck!
A:
Running eclipse as administrator solve the problem, then type the following:
keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000
Hope it help?
A:
If you are using Windows 7, make sure you are running eclipse as an administrator.
A:
chagning read only on windows 7 helped me. don't forget the default password "changeit"
A:
Make sure there is no other keystore file at this location C:\Program Files\Java\jdk1.6.0_25\bin. If there is, keep it somewhere else and try the command again:
keytool -genkey -v -keystore d:\my_private_key.keystore -alias my_key_alias -keyalg RSA -keysize 2048 -validity 10000
A:
Seems that it's easier to accomplish it in command line via keytool and the latest genkeypair approach. I finished up with the following:
keytool -genkeypair -keystore ~/.android/release.keystore -alias <my_alias> -storepass <my_cert_pass> -keyalg RSA
Then I got a set of questions regarding name, organization, location and password for my alias and that was it!
A:
If you are on Mac, Add "sudo" at the beginning of your command "keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000"
A:
I got this problem running on linux. The solution was to specify the path relative to the root directory (/), rather than relative to home (~).
A:
It does help you when you open a cmd as an administrator.
A:
run cmd as administrator
go to the file: C:\Program Files\Java\jdk-17.0.5\bin>
type this command:
.\keytool -genkey -alias bootscurity -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore bootsecurityp.12 -validity 3650
check the folder: C:\Program Files\Java\jdk-17.0.5\bin
and it will find your key named "bootsecurityp.12"
| Access denied when creating keystore for Android app | I am trying to sign my Android app so I can release it in Market. When I generate the keystore, I get an access denied error. How do I fix this?
This is what I've been trying to do:
Right click project in Eclipse Helios.
Android Tools > Export Signed Application Package.
Click next.
I check "Create new keystore" and realize it does nothing to help me. It still asks for the location of keystore. So I decide to do it the hard way.
Turned off read-only access on C:\Program Files\Java\jdk1.6.0_25\bin and granted the CREATOR OWNER group full control of the folder.
Open command line on Windows 7 64-bit.
Traverse to C:\Program Files\Java\jdk1.6.0_25\bin.
Run keytool.
Got an access denied error.
.
C:\Program Files\Java\jdk1.6.0_25\bin>keytool -genkey -v -alias company -keyalg R
SA -keysize 2048 -validity 10000 -keystore company.keystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: John Smith
What is the name of your organizational unit?
[Unknown]: Android
What is the name of your organization?
[Unknown]: Company
What is the name of your City or Locality?
[Unknown]: Albany
What is the name of your State or Province?
[Unknown]: NY
What is the two-letter country code for this unit?
[Unknown]: US
Is CN=John Smith, OU=Android, O=Company, L=Albany, ST=NY, C=US correct?
[no]: yes
Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with
a validity of 10,000 days
for: CN=John Smith, OU=Android, O=Company, L=Albany, ST=NY, C=US
Enter key password for <veetle>
(RETURN if same as keystore password):
Re-enter new password:
[Storing company.keystore]
keytool error: java.io.FileNotFoundException: veetle.keystore (Access is denied)
java.io.FileNotFoundException: veetle.keystore (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
at sun.security.tools.KeyTool.doCommands(KeyTool.java:902)
at sun.security.tools.KeyTool.run(KeyTool.java:172)
at sun.security.tools.KeyTool.main(KeyTool.java:166)
Edit:
Everytime I check the folder permissions, I see that it has reverted back to read-only. There were no errors whenever I turned off read-only.
| [
"Below steps worked for me:\n\nRun command prompt as administrator\nUnchecked the read only options in C:\\Program Files\\Java\\jdk1.6.0_25\\bin This may not be required\nkeytool -genkey -v -keystore d:\\my_private_key.keystore -alias my_key_alias -keyalg RSA -keysize 2048 -validity 10000\n\nTell it to create it in drive D:.\n",
"It does help you. You have to specify the location of the file that will be generated. For example specify C:\\Documents and Settings\\loginname\\market.keystore\n",
"Access denied because you are not an admin. \nSimply open the cmd prompt as an administrator - that worked for me.\n",
"The keystore that the Android SDK needs access to is not the same of the JDK. You can simply use the \"create new keystore\" option of the Android wizard and choose any folder you have write access to: the wizard will create there a new keystore. You don't need to use keytool form JDK.\n",
"opening Command Prompt as a Administrator helped me.(For Windows 8.1)\n",
"I had the same problem. You need to define your JAVA_HOME environment variable.\nRead the \"Basic Setup for signing\" paragraph of this link : http://developer.android.com/guide/publishing/app-signing.html#setup\nIt says:\n\nBefore you begin, make sure that the Keytool utility and Jarsigner utility are available to the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell the SDK build tools how to find these utilities by setting your JAVA_HOME environment variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and Jarsigner to your PATH variable.\nIf you are developing on a version of Linux that originally came with GNU Compiler for Java, make sure that the system is using the JDK version of Keytool, rather than the gcj version. If Keytool is already in your PATH, it might be pointing to a symlink at /usr/bin/keytool. In this case, check the symlink target to be sure it points to the Keytool in the JDK.\n\n",
"Fixing the problem on win7 (yuk) without Eclipse:\ni have the environment variable JAVA_HOME set to ..../JDK1.7.0_03 (android programmed from GLbasic), and i did only 2 things to fix the problem:\n1) in the folder ..../Java/JDK1.7.0_03 i removed the \"read-only\" permission of the /bin sub-folder, which contains keytool.exe.\n2) i opened the console \"as administrator\" (although it's the only account on my win7).\nthen you do cd...JDK / bin, run again keytool.exe, and you get the file nickname.keystore auto-generated in JDK / bin.\nOnce everything is done you could re-assign the \"read-only\" permission.\nGood luck!\n",
"Running eclipse as administrator solve the problem, then type the following:\nkeytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000\n\nHope it help?\n",
"If you are using Windows 7, make sure you are running eclipse as an administrator.\n",
"chagning read only on windows 7 helped me. don't forget the default password \"changeit\"\n",
"Make sure there is no other keystore file at this location C:\\Program Files\\Java\\jdk1.6.0_25\\bin. If there is, keep it somewhere else and try the command again:\nkeytool -genkey -v -keystore d:\\my_private_key.keystore -alias my_key_alias -keyalg RSA -keysize 2048 -validity 10000 \n",
"Seems that it's easier to accomplish it in command line via keytool and the latest genkeypair approach. I finished up with the following:\nkeytool -genkeypair -keystore ~/.android/release.keystore -alias <my_alias> -storepass <my_cert_pass> -keyalg RSA\n\nThen I got a set of questions regarding name, organization, location and password for my alias and that was it!\n",
"If you are on Mac, Add \"sudo\" at the beginning of your command \"keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000\"\n",
"I got this problem running on linux. The solution was to specify the path relative to the root directory (/), rather than relative to home (~).\n",
"It does help you when you open a cmd as an administrator.\n",
"\nrun cmd as administrator\ngo to the file: C:\\Program Files\\Java\\jdk-17.0.5\\bin>\ntype this command:\n\n\n.\\keytool -genkey -alias bootscurity -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore bootsecurityp.12 -validity 3650\n\n\ncheck the folder: C:\\Program Files\\Java\\jdk-17.0.5\\bin\nand it will find your key named \"bootsecurityp.12\"\n\n"
] | [
75,
54,
13,
9,
4,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"android",
"keytool",
"private_key"
] | stackoverflow_0006602422_android_keytool_private_key.txt |
Q:
l10n '.arb' file format
A project I came across has localization with follow structure
Each language has a directory under which there would be one file with same name as directory + '.arb' extension.
en/en.arb
I am not able to find a document that explains the format of this file.
Sample content from the .arb file
"FOO_123": "Your pending cost is {COST}",
"@FOO_123": {
"source_text": "Your pending cost is {COST}",
"placeholders": {
"COST": {
"example": "$123.45",
"description": "cost presented with currency symbol"
}
}
The closest one I could find is this.
Is this authoritative document for understanding '.arb' files?
What does a resource whose value has an anchor tag with a href look like? Is this correct way?
"FOO_124": "Refer to this {LINK}",
"@FOO_124": {
"source_text": "Refer to this {LINK}",
"placeholders": {
"LINK": {
"example": "<a href="https://en.wikipedia.org/">Encyclopedia</a>",
"description": "Link to the Encyclopedia page"
}
}
A:
ARB is google's format for localization, it is used in the web and in flutter framework
from ARB (Application Resource Bundle Specification)
Application Resource Bundle (abbr. ARB) is a localization resource
format that is simple (based on JSON), extensible (vocabulary can be
added without affecting existing tools and usage), and directly usable
(applications can access the resource directly from this format
without converting to another form).
In ARB, localizable resources are encoded as a JSON object. Each
resource will have a resource entry identified by resource key, and an
optional resource attribute entry with resource attribute key.
this answer is a summarization of my search and hopefully, it will save someones' time.
A:
ARB stands for Application Resource Bundle.
It is actually a JSON file on steroids intended for localization, with .arb extension. Since it is based on JSON, it just defines standardized ways how to add more information around key-value pairs.
It is used for the web and flutter apps localization.
Note, the official ARB specification is generic, and may sometimes differ from localization library implementations.
Regarding translations with anchor tags within it, it again depends on the localization library implementation.
Below is shown an example in Flutter.
ARB file example:
{
...
"commonLink": "link",
"@commonLink": {
"description": "Link desc."
},
"commonReferContent": "Refer to this ",
"@commonReferContent": {
"description": "Refer content desc."
}
...
}
Usage example:
...
RichText(
text: TextSpan(children: [
TextSpan(
style: TextStyle(color: Colors.black),
text: S.of(context).commonReferContent,
),
TextSpan(
style: TextStyle(
color: Theme.of(context).primaryColor,
decoration: TextDecoration.underline),
text: S.of(context).commonLink,
recognizer: TapGestureRecognizer()
..onTap = handleReferLinkTap),
]),
),
...
For more details about the ARB in Flutter, check out this article.
A:
Just need to mention one thing that, in plain app_lang.arb Flutter l10n implementation description(@"yourKeyName": {}) is required, not optional. Alternate, recommended option is using Flutter Intl - Flutter localization binding from .arb files with official Intl library. It also nativly supports usng loclizotion without context. More details about Flutter i18n plugins is here.
| l10n '.arb' file format | A project I came across has localization with follow structure
Each language has a directory under which there would be one file with same name as directory + '.arb' extension.
en/en.arb
I am not able to find a document that explains the format of this file.
Sample content from the .arb file
"FOO_123": "Your pending cost is {COST}",
"@FOO_123": {
"source_text": "Your pending cost is {COST}",
"placeholders": {
"COST": {
"example": "$123.45",
"description": "cost presented with currency symbol"
}
}
The closest one I could find is this.
Is this authoritative document for understanding '.arb' files?
What does a resource whose value has an anchor tag with a href look like? Is this correct way?
"FOO_124": "Refer to this {LINK}",
"@FOO_124": {
"source_text": "Refer to this {LINK}",
"placeholders": {
"LINK": {
"example": "<a href="https://en.wikipedia.org/">Encyclopedia</a>",
"description": "Link to the Encyclopedia page"
}
}
| [
"ARB is google's format for localization, it is used in the web and in flutter framework\nfrom ARB (Application Resource Bundle Specification)\n\nApplication Resource Bundle (abbr. ARB) is a localization resource\n format that is simple (based on JSON), extensible (vocabulary can be\n added without affecting existing tools and usage), and directly usable\n (applications can access the resource directly from this format\n without converting to another form).\nIn ARB, localizable resources are encoded as a JSON object. Each\n resource will have a resource entry identified by resource key, and an\n optional resource attribute entry with resource attribute key.\n\nthis answer is a summarization of my search and hopefully, it will save someones' time.\n",
"ARB stands for Application Resource Bundle.\nIt is actually a JSON file on steroids intended for localization, with .arb extension. Since it is based on JSON, it just defines standardized ways how to add more information around key-value pairs.\nIt is used for the web and flutter apps localization.\nNote, the official ARB specification is generic, and may sometimes differ from localization library implementations.\nRegarding translations with anchor tags within it, it again depends on the localization library implementation.\nBelow is shown an example in Flutter.\nARB file example:\n{\n ...\n \"commonLink\": \"link\",\n \"@commonLink\": {\n \"description\": \"Link desc.\"\n },\n \"commonReferContent\": \"Refer to this \",\n \"@commonReferContent\": {\n \"description\": \"Refer content desc.\"\n }\n ...\n}\n\nUsage example:\n...\nRichText(\n text: TextSpan(children: [\n TextSpan(\n style: TextStyle(color: Colors.black),\n text: S.of(context).commonReferContent,\n ),\n TextSpan(\n style: TextStyle(\n color: Theme.of(context).primaryColor,\n decoration: TextDecoration.underline),\n text: S.of(context).commonLink,\n recognizer: TapGestureRecognizer()\n ..onTap = handleReferLinkTap),\n ]),\n),\n...\n\nFor more details about the ARB in Flutter, check out this article.\n",
"Just need to mention one thing that, in plain app_lang.arb Flutter l10n implementation description(@\"yourKeyName\": {}) is required, not optional. Alternate, recommended option is using Flutter Intl - Flutter localization binding from .arb files with official Intl library. It also nativly supports usng loclizotion without context. More details about Flutter i18n plugins is here.\n"
] | [
14,
1,
0
] | [] | [] | [
"internationalization",
"localization"
] | stackoverflow_0043082804_internationalization_localization.txt |
Q:
Why if statement is not working in sas macro?
I wanna get back one character by calling this macro but there is an error:
%macro getcategory(date=);
%global category;
%if %year(date) < 2002 %then %do;
%let category = A;
%mend;
%getcategory(date=1999);
I tried with symput but not working.
A:
It looks like you are trying to use the %year() function to determine the year of the date parameter that is passed to the getcategory macro. However, the %year() function is not part of the SAS language.
To get the year from a SAS date value, you can use the year() function, which is part of the SAS date and time functions. Here is an example of how you might use it:
%macro getcategory(date=);
%global category;
%let year = %sysfunc(year(date));
%if &year < 2002 %then %do;
%let category = A;
%end;
%mend;
%getcategory(date=1999);
In this example, the %sysfunc() function is used to call the year() function within the macro. This is necessary because the year() function is a SAS function, not a macro language function.
Note that the year() function returns the year as a four-digit number, so you will need to compare it to the value 2002 rather than the value 2.
I hope this helps! Let me know if you have any other questions.
| Why if statement is not working in sas macro? | I wanna get back one character by calling this macro but there is an error:
%macro getcategory(date=);
%global category;
%if %year(date) < 2002 %then %do;
%let category = A;
%mend;
%getcategory(date=1999);
I tried with symput but not working.
| [
"It looks like you are trying to use the %year() function to determine the year of the date parameter that is passed to the getcategory macro. However, the %year() function is not part of the SAS language.\nTo get the year from a SAS date value, you can use the year() function, which is part of the SAS date and time functions. Here is an example of how you might use it:\n%macro getcategory(date=);\n %global category;\n\n %let year = %sysfunc(year(date));\n %if &year < 2002 %then %do;\n %let category = A;\n %end;\n%mend;\n\n%getcategory(date=1999);\n\nIn this example, the %sysfunc() function is used to call the year() function within the macro. This is necessary because the year() function is a SAS function, not a macro language function.\nNote that the year() function returns the year as a four-digit number, so you will need to compare it to the value 2002 rather than the value 2.\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"sas",
"sas_macro"
] | stackoverflow_0074675596_sas_sas_macro.txt |
Q:
How can I embed a variable that updates every time the command is run?
I am trying to get my discord bot (coded in python) to embed the contents of a string variable that I set up.
I am unable to figure out how to make the bot embed the string, as well as how to make the variable update every time the command is run.
I made a function for the playerlist variable in the hopes that it would run every time I called it, but I wanted for some guidance on whether this is correct or not, as well as my problem of displaying it.
def playerlist():
req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) #spoopy disguise
webpage = urlopen(req).read()
soup = soup(webpage, "html.parser")
cleansoup = (soup.get_text(strip=True, separator=" "))
x = cleansoup.split("""Play time""")[-1]
x = x.split("""Most Time Played""")[0]
print(x)
@commands.hybrid_command(
name="playerlist",
description="This should pull a player list with playtimes",
)
# This will only allow non-blacklisted members to execute the command
@checks.not_blacklisted()
async def playerlist(self, context: Context) -> None:
"""
playerlist from battlemetrics
"""
playerlist()
embed = discord.Embed(
title="Playerlist",
description=x,
color=0x9C84EF
)
await context.send(embed=embed)
I get an error message saying that "x" is not defined. I can understand why it would say it is not defined but It is still confusing because it should have been defined from the function?
Thank you very much for your time
A:
you can return x from the playerlist function
def playerlist():
req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) #spoopy disguise
webpage = urlopen(req).read()
soup = soup(webpage, "html.parser")
cleansoup = (soup.get_text(strip=True, separator=" "))
x = cleansoup.split("""Play time""")[-1]
x = x.split("""Most Time Played""")[0]
return x
and recalling it anytime
@commands.hybrid_command(
name="playerlist",
description="This should pull a player list with playtimes",
)
# This will only allow non-blacklisted members to execute the command
@checks.not_blacklisted()
async def playerlist(self, context: Context) -> None:
"""
playerlist from battlemetrics
"""
x = playerlist()
embed = discord.Embed(
title="Playerlist",
description=x,
color=0x9C84EF
)
await context.send(embed=embed)
| How can I embed a variable that updates every time the command is run? | I am trying to get my discord bot (coded in python) to embed the contents of a string variable that I set up.
I am unable to figure out how to make the bot embed the string, as well as how to make the variable update every time the command is run.
I made a function for the playerlist variable in the hopes that it would run every time I called it, but I wanted for some guidance on whether this is correct or not, as well as my problem of displaying it.
def playerlist():
req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) #spoopy disguise
webpage = urlopen(req).read()
soup = soup(webpage, "html.parser")
cleansoup = (soup.get_text(strip=True, separator=" "))
x = cleansoup.split("""Play time""")[-1]
x = x.split("""Most Time Played""")[0]
print(x)
@commands.hybrid_command(
name="playerlist",
description="This should pull a player list with playtimes",
)
# This will only allow non-blacklisted members to execute the command
@checks.not_blacklisted()
async def playerlist(self, context: Context) -> None:
"""
playerlist from battlemetrics
"""
playerlist()
embed = discord.Embed(
title="Playerlist",
description=x,
color=0x9C84EF
)
await context.send(embed=embed)
I get an error message saying that "x" is not defined. I can understand why it would say it is not defined but It is still confusing because it should have been defined from the function?
Thank you very much for your time
| [
"you can return x from the playerlist function\ndef playerlist():\n req = Request(url, headers = {'User-Agent': 'Mozilla/5.0'}) #spoopy disguise\n webpage = urlopen(req).read()\n\n soup = soup(webpage, \"html.parser\")\n\n cleansoup = (soup.get_text(strip=True, separator=\" \"))\n\n x = cleansoup.split(\"\"\"Play time\"\"\")[-1]\n x = x.split(\"\"\"Most Time Played\"\"\")[0]\n return x\n\nand recalling it anytime\n @commands.hybrid_command(\n name=\"playerlist\",\n description=\"This should pull a player list with playtimes\",\n )\n # This will only allow non-blacklisted members to execute the command\n @checks.not_blacklisted()\n async def playerlist(self, context: Context) -> None:\n \"\"\"\n playerlist from battlemetrics\n \"\"\"\n x = playerlist()\n embed = discord.Embed(\n title=\"Playerlist\",\n description=x,\n color=0x9C84EF\n )\n await context.send(embed=embed)\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"discord.py",
"python"
] | stackoverflow_0074674934_beautifulsoup_discord.py_python.txt |
Q:
axios transformRequest - how to alter JSON payload
I am using axios in my Express API and I want to transform the payload before sending it off to another API. axios has just the thing for this called transformRequest. This is where I ran into issues though.
The code I have looks like:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return data;
},
],
});
// firing off my request using the instance above:
const postData = {
id: 1,
name: 'James',
};
instance.post('/getStuff', postData)
and ultimately, I want to post api-url.com the JSON: {"SecretStuff": "some-base64-string"} - not the postData object shown above.
From the docs, it says: "The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream" - but of course here I am returning an object, data. Oddly enough in the axios docs it shows them returning data from transformRequest, but in their case that must be the correct data type.
How do I actually transform a payload with axios?
A:
axios.create({
transformRequest: [(data, headers) => {
// modify data here
return data;
}, ...axios.defaults.transformRequest]
});
have to append the original axios.defaults.transformRequest to the transformRequest option here..
A:
Wouldn't you want to JSON.stringify() your transformed post data? Like below:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return JSON.stringify(data);
},
],
});
A:
To amend the values instead of override the output in the request I would do this:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
data.append('myKey','myValue');
return data;
},
]
});
A:
Here's what worked for me in TypeScript, inspired by the concat solution from Phil here: https://stackoverflow.com/a/70949237/2339352
The goal here was to use the humps library to convert to/from a snake case Python API:
this.axios = axios.create({
transformResponse: (data: any) => {
return humps.camelizeKeys(JSON.parse(data))
},
transformRequest: [(data: any) => {
return humps.decamelizeKeys(data);
}].concat(axios.defaults.transformRequest ? axios.defaults.transformRequest : [])
});
| axios transformRequest - how to alter JSON payload | I am using axios in my Express API and I want to transform the payload before sending it off to another API. axios has just the thing for this called transformRequest. This is where I ran into issues though.
The code I have looks like:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return data;
},
],
});
// firing off my request using the instance above:
const postData = {
id: 1,
name: 'James',
};
instance.post('/getStuff', postData)
and ultimately, I want to post api-url.com the JSON: {"SecretStuff": "some-base64-string"} - not the postData object shown above.
From the docs, it says: "The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream" - but of course here I am returning an object, data. Oddly enough in the axios docs it shows them returning data from transformRequest, but in their case that must be the correct data type.
How do I actually transform a payload with axios?
| [
"axios.create({\n transformRequest: [(data, headers) => {\n // modify data here\n return data;\n }, ...axios.defaults.transformRequest]\n});\n\nhave to append the original axios.defaults.transformRequest to the transformRequest option here.. \n",
"Wouldn't you want to JSON.stringify() your transformed post data? Like below:\nconst instance = axios.create({\n baseURL: 'api-url.com',\n transformRequest: [\n (data, headers) => {\n const encryptedString = encryptPayload(JSON.stringify(data));\n\n data = {\n SecretStuff: encryptedString,\n };\n\n return JSON.stringify(data);\n },\n ], \n});\n\n",
"To amend the values instead of override the output in the request I would do this:\nconst instance = axios.create({\nbaseURL: 'api-url.com',\ntransformRequest: [\n (data, headers) => {\n data.append('myKey','myValue'); \n return data;\n },\n]\n});\n\n",
"Here's what worked for me in TypeScript, inspired by the concat solution from Phil here: https://stackoverflow.com/a/70949237/2339352\nThe goal here was to use the humps library to convert to/from a snake case Python API:\nthis.axios = axios.create({\n transformResponse: (data: any) => {\n return humps.camelizeKeys(JSON.parse(data))\n },\n transformRequest: [(data: any) => {\n return humps.decamelizeKeys(data);\n }].concat(axios.defaults.transformRequest ? axios.defaults.transformRequest : [])\n});\n\n"
] | [
25,
10,
0,
0
] | [] | [] | [
"axios",
"javascript"
] | stackoverflow_0048819885_axios_javascript.txt |
Q:
Simple Apps Script timing out on execution
I am only beginner level at C+ and I'm trying to execute what I think is a simple script in Apps Script for this spreadsheet: https://docs.google.com/spreadsheets/d/1lu0_B1OdjU6Y5KF4zomCpQNiGCGklVoZDF8rQ8HQBhQ/edit?usp=sharing
The execution is timing out and it doesn't give me much information as to why but it has to be something to do with the parts of the template I have changed. Namely just the for loop in task 3. Maybe the way i have concatenated too? I am not familiar with Java and may be missing something very obvious. I'm not familiar with how it should be set out either so please be kind.
function routineActivator() {
/**
Task 1) Open the Event Calendar.
**/
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = 'myEmail';
var eventCal = CalendarApp.getCalendarById(calendarId);
/**
Task 2) Pull each shift information into the code, in a form that the code can understand.
**/
var routine = spreadsheet.getRange('A4:D74').getValues();
/**
Task 3) Do the work!
**/
for (x=0; x<routine.length; x++) {
var task = routine[x];
var des = task[3]
if(des=1){
var label = task[2];
var startTime = task[0] + task[1];
while (des != 2){
var endTime = task[0] + task[1];
task++;
}
eventCal.createEvent(label, startTime, endTime);
}
}
/**
Task 4) Make it easy to use.
**/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Sync to Calendar')
.addItem('Schedule tasks now', 'routineActivator')
}
}
I have tried to run it but it loops and times out.
A:
The problem is that the following will loop forever and never exit:
if (des = 1) {
while (des != 2) {
}
}
des will always be 1 because you are using the assignment operator = instead of the comparison operator ===.
Changing the operator is not enough to fix the problem, though, because when des is 1, it is not 2, and the while loop will never exit. You need to modify des in the while loop.
| Simple Apps Script timing out on execution | I am only beginner level at C+ and I'm trying to execute what I think is a simple script in Apps Script for this spreadsheet: https://docs.google.com/spreadsheets/d/1lu0_B1OdjU6Y5KF4zomCpQNiGCGklVoZDF8rQ8HQBhQ/edit?usp=sharing
The execution is timing out and it doesn't give me much information as to why but it has to be something to do with the parts of the template I have changed. Namely just the for loop in task 3. Maybe the way i have concatenated too? I am not familiar with Java and may be missing something very obvious. I'm not familiar with how it should be set out either so please be kind.
function routineActivator() {
/**
Task 1) Open the Event Calendar.
**/
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = 'myEmail';
var eventCal = CalendarApp.getCalendarById(calendarId);
/**
Task 2) Pull each shift information into the code, in a form that the code can understand.
**/
var routine = spreadsheet.getRange('A4:D74').getValues();
/**
Task 3) Do the work!
**/
for (x=0; x<routine.length; x++) {
var task = routine[x];
var des = task[3]
if(des=1){
var label = task[2];
var startTime = task[0] + task[1];
while (des != 2){
var endTime = task[0] + task[1];
task++;
}
eventCal.createEvent(label, startTime, endTime);
}
}
/**
Task 4) Make it easy to use.
**/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Sync to Calendar')
.addItem('Schedule tasks now', 'routineActivator')
}
}
I have tried to run it but it loops and times out.
| [
"The problem is that the following will loop forever and never exit:\n if (des = 1) {\n while (des != 2) {\n }\n }\n\ndes will always be 1 because you are using the assignment operator = instead of the comparison operator ===.\nChanging the operator is not enough to fix the problem, though, because when des is 1, it is not 2, and the while loop will never exit. You need to modify des in the while loop.\n"
] | [
0
] | [] | [] | [
"google_apps_script",
"javascript"
] | stackoverflow_0074675007_google_apps_script_javascript.txt |
Q:
Return the unique address sorted by shortest distance to an input lat long in OpenSearch/ElasticSearch
I have a database with following sample.
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.0,
"_source" : {
"address" : "Graha Blok A",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5881896,
"lon" : 106.747485
}
}
},
{
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.0,
"_source" : {
"address" : "Graha",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5895002,
"lon" : 106.7488968
}
}
},
{
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "3",
"_score" : 0.0,
"_source" : {
"address" : "Graha",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5884867,
"lon" : 106.749212
Expected Return shall be, where the address shall be unique
{Graha Block A, Graha}
I have written following code, and able to get the address with shortest distance to an input lat, long. However I was unable to get the Unique Address. Please advise
{ "size": 10,
"query": {
"bool": {
"must": {
"geo_distance": {
"distance": "1km",
"location": [
106.7485418,
-6.5875987
]
}
},
"filter": {"match" : {"geohash6" : "qqgft0"}}
}
},
"sort": [
"_score",
{
"_geo_distance": {
"location": {
"lat": -6.5875987,
"lon": 106.7485418
},
"order": "asc",
"unit": "m",
"distance_type": "plane"
}
}
]
}
A:
To get unique values for the "address" field in your Elasticsearch query, you can use the "terms" aggregation. This will group the results by the "address" field and only return unique values.
Here's an example of how you can use the "terms" aggregation to get unique values for the "address" field in your Elasticsearch query:
{
"size": 10,
"query": {
"bool": {
"must": {
"geo_distance": {
"distance": "1km",
"location": [
106.7485418,
-6.5875987
]
}
},
"filter": {"match" : {"geohash6" : "qqgft0"}}
}
},
"sort": [
"_score",
{
"_geo_distance": {
"location": {
"lat": -6.5875987,
"lon": 106.7485418
},
"order": "asc",
"unit": "m",
"distance_type": "plane"
}
}
],
"aggs": {
"unique_addresses": {
"terms": {
"field": "address"
}
}
}
}
This will return the unique values for the "address" field in your Elasticsearch results, grouped by the "address" field. You can then access the results of the aggregation using the "unique_addresses
| Return the unique address sorted by shortest distance to an input lat long in OpenSearch/ElasticSearch | I have a database with following sample.
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.0,
"_source" : {
"address" : "Graha Blok A",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5881896,
"lon" : 106.747485
}
}
},
{
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.0,
"_source" : {
"address" : "Graha",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5895002,
"lon" : 106.7488968
}
}
},
{
"_index" : "python-address-test",
"_type" : "_doc",
"_id" : "3",
"_score" : 0.0,
"_source" : {
"address" : "Graha",
"geohash6" : "qqgft0",
"location" : {
"lat" : -6.5884867,
"lon" : 106.749212
Expected Return shall be, where the address shall be unique
{Graha Block A, Graha}
I have written following code, and able to get the address with shortest distance to an input lat, long. However I was unable to get the Unique Address. Please advise
{ "size": 10,
"query": {
"bool": {
"must": {
"geo_distance": {
"distance": "1km",
"location": [
106.7485418,
-6.5875987
]
}
},
"filter": {"match" : {"geohash6" : "qqgft0"}}
}
},
"sort": [
"_score",
{
"_geo_distance": {
"location": {
"lat": -6.5875987,
"lon": 106.7485418
},
"order": "asc",
"unit": "m",
"distance_type": "plane"
}
}
]
}
| [
"To get unique values for the \"address\" field in your Elasticsearch query, you can use the \"terms\" aggregation. This will group the results by the \"address\" field and only return unique values.\nHere's an example of how you can use the \"terms\" aggregation to get unique values for the \"address\" field in your Elasticsearch query:\n{\n\"size\": 10,\n\"query\": {\n\"bool\": {\n\"must\": {\n\"geo_distance\": {\n\"distance\": \"1km\",\n\"location\": [\n106.7485418,\n-6.5875987\n]\n}\n},\n\"filter\": {\"match\" : {\"geohash6\" : \"qqgft0\"}}\n}\n},\n\"sort\": [\n\"_score\",\n{\n\"_geo_distance\": {\n\"location\": {\n\"lat\": -6.5875987,\n\"lon\": 106.7485418\n},\n\"order\": \"asc\",\n\"unit\": \"m\",\n\"distance_type\": \"plane\"\n}\n}\n],\n\"aggs\": {\n\"unique_addresses\": {\n\"terms\": {\n\"field\": \"address\"\n}\n}\n}\n}\n\nThis will return the unique values for the \"address\" field in your Elasticsearch results, grouped by the \"address\" field. You can then access the results of the aggregation using the \"unique_addresses\n"
] | [
0
] | [] | [] | [
"elasticsearch",
"opensearch"
] | stackoverflow_0074675517_elasticsearch_opensearch.txt |
Q:
How can i install deleted default api service in kubernetes?
I am on Kubernetes v1.22.13. When i was trying to delete a namespace that's stuck in status terminating, i deleted api-service v1.networking.k8s.io by mistake with:
kubectl delete apiservices.apiregistration.k8s.io v1.networking.k8s.io
And now i don't have crds related to v1.networking.k8s.io such as Ingress. When i try to install ingress-controller it gives the error:
error: resource mapping not found for name: "nginx" namespace: "" from "https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.4.0/deploy/static/provider/cloud/deploy.yaml": no matches for kind "IngressClass" in version "networking.k8s.io/v1"
How can i undo that operation? Or how can i bring back api-resource v1.networking.k8s.io?
Tried to find a way to undo it and install it manually but i couldn't find the manifest related to that.
A:
you have accidentally deleted the v1.networking.k8s.io API service, which is used by the Kubernetes networking APIs. To undo this operation, you will need to recreate the API service by running the following command:
kubectl create apiservices.apiregistration.k8s.io v1.networking.k8s.io --service-name=networking.k8s.io
This should recreate the v1.networking.k8s.io API service, allowing you to use the networking APIs again. However, if you still cannot use the networking APIs, you may need to restart the kube-apiserver and kube-controller-manager processes on your Kubernetes cluster.
A:
you can recreate it via the following:
cat <<EOF | kubectl apply -f -
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
labels:
kube-aggregator.kubernetes.io/automanaged: onstart
name: v1.networking.k8s.io
spec:
group: networking.k8s.io
groupPriorityMinimum: 17200
version: v1
versionPriority: 15
EOF
| How can i install deleted default api service in kubernetes? | I am on Kubernetes v1.22.13. When i was trying to delete a namespace that's stuck in status terminating, i deleted api-service v1.networking.k8s.io by mistake with:
kubectl delete apiservices.apiregistration.k8s.io v1.networking.k8s.io
And now i don't have crds related to v1.networking.k8s.io such as Ingress. When i try to install ingress-controller it gives the error:
error: resource mapping not found for name: "nginx" namespace: "" from "https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.4.0/deploy/static/provider/cloud/deploy.yaml": no matches for kind "IngressClass" in version "networking.k8s.io/v1"
How can i undo that operation? Or how can i bring back api-resource v1.networking.k8s.io?
Tried to find a way to undo it and install it manually but i couldn't find the manifest related to that.
| [
"you have accidentally deleted the v1.networking.k8s.io API service, which is used by the Kubernetes networking APIs. To undo this operation, you will need to recreate the API service by running the following command:\nkubectl create apiservices.apiregistration.k8s.io v1.networking.k8s.io --service-name=networking.k8s.io\n\nThis should recreate the v1.networking.k8s.io API service, allowing you to use the networking APIs again. However, if you still cannot use the networking APIs, you may need to restart the kube-apiserver and kube-controller-manager processes on your Kubernetes cluster.\n",
"you can recreate it via the following:\ncat <<EOF | kubectl apply -f -\napiVersion: apiregistration.k8s.io/v1\nkind: APIService\nmetadata:\n labels:\n kube-aggregator.kubernetes.io/automanaged: onstart\n name: v1.networking.k8s.io\nspec:\n group: networking.k8s.io\n groupPriorityMinimum: 17200\n version: v1\n versionPriority: 15\nEOF\n\n"
] | [
0,
0
] | [] | [] | [
"kubernetes",
"kubernetes_apiserver",
"nginx_ingress"
] | stackoverflow_0074628719_kubernetes_kubernetes_apiserver_nginx_ingress.txt |
Q:
ModuleNotFoundError: No module named 'flask_mqtt'
I'm trying to run flask-mqtt on raspberry pi. I am running python version 3.7.3 it looks like I can't update python to 3.10 on pi. I don't know if that is necessary. I have installed flask-mqtt with following command
pip install Flask-MQTT:
Requirement already satisfied: Flask-MQTT in /home/pi/.local/lib/python2.7/site-packages (1.0.7)
Requirement already satisfied: Flask in /usr/lib/python2.7/dist-packages (from Flask-MQTT) (1.0.2)
Requirement already satisfied: paho-mqtt in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (1.6.1)
Requirement already satisfied: typing; python_version < "3.5" in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (3.10.0.0)
I have both tried running app.py in virtual environment and directly on pi system
everytime I run it i get ModuleNotFoundError like following
Traceback (most recent call last):
File "app.py", line 2, in
from flask_mqtt import Mqtt
ModuleNotFoundError: No module named 'flask_mqtt'
I am running Raspberry Pi OS (Legacy) on Raspberry Pi model 3 b+
A:
Based on the output of the pip install command you included in your question, it appears that flask-mqtt was installed for Python 2.7, but you're trying to run your script with Python 3.7. You can confirm the version of Python that your script is using by adding the following line at the beginning of the script to print version of python script is using:
import sys
print(sys.version)
To fix the ModuleNotFoundError that you're seeing, install the flask-mqtt library for the version of Python that your script is using. If your script is using Python 3.7, you can use the following command to install the library:
pip3 install Flask-MQTT
A:
Problem Solved!
the issue had something to do with port numbers. seems like I was always trying to run on port 80. when I changed to other ports, for example 8080 it worked. I am not sure why because nothing else is listening to port 80 I tried Following
telnet 192.168.8.175 80
and no connection
the final solution was to change...
if __name__ == '__main__': <br>
app.run(debug=True, port=80, host='0.0.0.0') <br>
to...
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Thanks for the help!
| ModuleNotFoundError: No module named 'flask_mqtt' | I'm trying to run flask-mqtt on raspberry pi. I am running python version 3.7.3 it looks like I can't update python to 3.10 on pi. I don't know if that is necessary. I have installed flask-mqtt with following command
pip install Flask-MQTT:
Requirement already satisfied: Flask-MQTT in /home/pi/.local/lib/python2.7/site-packages (1.0.7)
Requirement already satisfied: Flask in /usr/lib/python2.7/dist-packages (from Flask-MQTT) (1.0.2)
Requirement already satisfied: paho-mqtt in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (1.6.1)
Requirement already satisfied: typing; python_version < "3.5" in /home/pi/.local/lib/python2.7/site-packages (from Flask-MQTT) (3.10.0.0)
I have both tried running app.py in virtual environment and directly on pi system
everytime I run it i get ModuleNotFoundError like following
Traceback (most recent call last):
File "app.py", line 2, in
from flask_mqtt import Mqtt
ModuleNotFoundError: No module named 'flask_mqtt'
I am running Raspberry Pi OS (Legacy) on Raspberry Pi model 3 b+
| [
"Based on the output of the pip install command you included in your question, it appears that flask-mqtt was installed for Python 2.7, but you're trying to run your script with Python 3.7. You can confirm the version of Python that your script is using by adding the following line at the beginning of the script to print version of python script is using:\nimport sys\n\nprint(sys.version)\n\nTo fix the ModuleNotFoundError that you're seeing, install the flask-mqtt library for the version of Python that your script is using. If your script is using Python 3.7, you can use the following command to install the library:\npip3 install Flask-MQTT\n",
"Problem Solved!\nthe issue had something to do with port numbers. seems like I was always trying to run on port 80. when I changed to other ports, for example 8080 it worked. I am not sure why because nothing else is listening to port 80 I tried Following\n\ntelnet 192.168.8.175 80\n\nand no connection\nthe final solution was to change...\nif __name__ == '__main__': <br>\n app.run(debug=True, port=80, host='0.0.0.0') <br>\n\nto...\nif __name__ == '__main__': \n app.run(host='0.0.0.0', port=8080)\n\nThanks for the help!\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074671732_python.txt |
Q:
Group SQL results by date
I'm having trouble splitting the results from a SQL query into dates.
I have something like that:
i have something like that
And I want something like that:
i want this
// I use bootstrap...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="list-group">';
while($row = $result->fetch_assoc()) {
$newDate = date("d.m.Y", strtotime($row["dataczas"]));
$transactiontitle = $row["tytul"];
echo '<a href="transakcja/?id='.$row["idTransakcji"].'" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 text-truncate">'.$row["nazwa"].'</h5><small class="text-muted text-nowrap"><i class="bi bi-calendar3 text-muted"></i> '.$newDate.'</small>
</div>
<p class="mb-1">'.$row["kwota"].' CAD</p>
<p class="mb-1 text-truncate text-muted">
'.
$transactiontitle
.'
</p>
</a>';
}
echo "</div>";
}
Above - my PHP code right now.
I would like to group rows by date like on the image above.
A:
As far as I can see from your images, the output of the query is already sorted by date. So let me assume that that is indeed the case. All you have to do is print the date when it changes. You can do something like this:
$currentDate = '';
while($row = $result->fetch_assoc()) {
$newDate = date("d.m.Y", strtotime($row["dataczas"]));
if ($newDate != $currentDate) {
echo 'Make date row here with date: ' . $newDate;
$currentDate = $newDate;
}
// here comes the rest of the transaction
}
This code keep track of the current date, and whenever it changes it create a new date row in the output.
| Group SQL results by date | I'm having trouble splitting the results from a SQL query into dates.
I have something like that:
i have something like that
And I want something like that:
i want this
// I use bootstrap...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="list-group">';
while($row = $result->fetch_assoc()) {
$newDate = date("d.m.Y", strtotime($row["dataczas"]));
$transactiontitle = $row["tytul"];
echo '<a href="transakcja/?id='.$row["idTransakcji"].'" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 text-truncate">'.$row["nazwa"].'</h5><small class="text-muted text-nowrap"><i class="bi bi-calendar3 text-muted"></i> '.$newDate.'</small>
</div>
<p class="mb-1">'.$row["kwota"].' CAD</p>
<p class="mb-1 text-truncate text-muted">
'.
$transactiontitle
.'
</p>
</a>';
}
echo "</div>";
}
Above - my PHP code right now.
I would like to group rows by date like on the image above.
| [
"As far as I can see from your images, the output of the query is already sorted by date. So let me assume that that is indeed the case. All you have to do is print the date when it changes. You can do something like this:\n$currentDate = '';\nwhile($row = $result->fetch_assoc()) {\n $newDate = date(\"d.m.Y\", strtotime($row[\"dataczas\"]));\n if ($newDate != $currentDate) {\n echo 'Make date row here with date: ' . $newDate;\n $currentDate = $newDate;\n }\n // here comes the rest of the transaction\n}\n\nThis code keep track of the current date, and whenever it changes it create a new date row in the output.\n"
] | [
0
] | [] | [] | [
"html",
"mysqli",
"php"
] | stackoverflow_0074675513_html_mysqli_php.txt |
Q:
Entity is trying to insert a new record for a related table when I want it to update
I know this is an issue with me understanding how entity and database tables/relationships work.. I'm just trying to figure out where I am making a mistake.
I have a shopping cart table, with a foreign key to a related project table. I am trying to insert a new shopping cart record to the database, and by default entity is trying to insert a new project. However, I don't want a new project, I want the existing project updated in the database.
Here is the code for the insert and update of the shopping cart/project:
public async Task<IActionResult> MakePayment(int? projectId)
{
ShoppingCart cart = new ShoppingCart()
{
ProjectId = projectId,
Project = await _dbContext.Projects.Where(p => p.Id == projectId).Select(p => new Project()
{
AmountPaid = p.AmountPaid,
RemainingBalance = p.RemainingBalance,
OriginalPrice = p.OriginalPrice
}).FirstOrDefaultAsync()
};
//set payment amount to remaining balance by default
cart.PaymentAmount = cart.Project.RemainingBalance;
return View(cart);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> MakePayment(ShoppingCart shoppingCart)
{
//get user id of logged in user
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
//if claim is null, that means we are not logged in
if(claim != null)//claim should never be null, because we are using the Authorize Data Annotation
{
shoppingCart.AppUserId = claim.Value;
//get the related project to update payment values
var dbProject = await _dbContext.Projects.Where(p => p.Id == shoppingCart.ProjectId).FirstOrDefaultAsync();
if(dbProject != null)
{
dbProject.AmountPaid += shoppingCart.PaymentAmount;
dbProject.RemainingBalance = dbProject.OriginalPrice - dbProject.AmountPaid;
}
await _dbContext.SaveChangesAsync();
}
await _dbContext.ShoppingCarts.AddAsync(shoppingCart);
await _dbContext.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Here are my table models for the shopping cart and project tables (Code-first):
Shopping Cart table:
namespace FordWare.Models
{
public class ShoppingCart
{
#nullable disable
[Key]
[Required]
public int Id { get; set; }
#nullable enable
public string? AppUserId { get; set; }
#nullable enable
[ValidateNever]
public AppUser? AppUser { get; set; }
#nullable enable
public int? ProjectId { get; set; }
#nullable enable
[ValidateNever]
public Project? Project { get; set; }
#nullable enable
public double? PaymentAmount { get; set; }
}
}
Project table:
namespace FordWare.Models
{
public class Project
{
#nullable disable
[Required]
[Key]
public int Id { get; set; }
#nullable disable
[Required]
public string Description { get; set; }
#nullable enable
[ValidateNever]
[DisplayName("Image")]
public string? ImageURL { get; set; }
#nullable enable
public string? LinkToProject { get; set; }
#nullable enable
public double? OriginalPrice { get; set; }
#nullable enable
public double? AmountPaid { get; set; }
#nullable enable
public double? RemainingBalance { get; set; }
#nullable disable
[Required]
public string ServiceCSV { get; set; }
#nullable enable
[DisplayName("Company")]
public int? CompanyId { get; set; }
#nullable enable
[ForeignKey("CompanyId")]
[ValidateNever]
public Company? Company { get; set; }
#nullable disable
[Required]
public double EstimatedHours { get; set; }
#nullable disable
[Required]
public double EstimatedPrice { get; set; }
#nullable disable
[Required]
public DateTime TargetStartDate { get; set; }
#nullable disable
[Required]
public DateTime TargetCompletionDate { get; set; }
}
}
This is the error I get when trying to Add a new shopping cart, then save changes in the database.. It is trying to insert a new project, and the description column on projects is required... so it is throwing a null error... However, I don't want to insert a new project here... It is trying to do this I guess because of the Project navigation property on the ShoppingCart model:
A:
As @progman has already stated in the comments, this is probably due to the Project property of the ShoppingCart being posted on your MakePaymentmethod. From the Entity Framework documentation:
However, the Add methods don't just work on an individual entity. They actually start tracking an entire graph of related entities, putting them all to the Added state. For example, to insert a new blog and associated new posts
So if you post a Project on the ShoppingCart that does not exist on the database, Entity Framework will create a new one. And if the Project exists, your previous query will track it and my guess is that Entity Framework will navigate the newly attached ShoppingCart an edit the existing project properties with the values found on the shoppingCart.Project.
Maybe you can check the change debugging information, it looks very promising for the kind of issue you want to debug.
| Entity is trying to insert a new record for a related table when I want it to update | I know this is an issue with me understanding how entity and database tables/relationships work.. I'm just trying to figure out where I am making a mistake.
I have a shopping cart table, with a foreign key to a related project table. I am trying to insert a new shopping cart record to the database, and by default entity is trying to insert a new project. However, I don't want a new project, I want the existing project updated in the database.
Here is the code for the insert and update of the shopping cart/project:
public async Task<IActionResult> MakePayment(int? projectId)
{
ShoppingCart cart = new ShoppingCart()
{
ProjectId = projectId,
Project = await _dbContext.Projects.Where(p => p.Id == projectId).Select(p => new Project()
{
AmountPaid = p.AmountPaid,
RemainingBalance = p.RemainingBalance,
OriginalPrice = p.OriginalPrice
}).FirstOrDefaultAsync()
};
//set payment amount to remaining balance by default
cart.PaymentAmount = cart.Project.RemainingBalance;
return View(cart);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> MakePayment(ShoppingCart shoppingCart)
{
//get user id of logged in user
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
//if claim is null, that means we are not logged in
if(claim != null)//claim should never be null, because we are using the Authorize Data Annotation
{
shoppingCart.AppUserId = claim.Value;
//get the related project to update payment values
var dbProject = await _dbContext.Projects.Where(p => p.Id == shoppingCart.ProjectId).FirstOrDefaultAsync();
if(dbProject != null)
{
dbProject.AmountPaid += shoppingCart.PaymentAmount;
dbProject.RemainingBalance = dbProject.OriginalPrice - dbProject.AmountPaid;
}
await _dbContext.SaveChangesAsync();
}
await _dbContext.ShoppingCarts.AddAsync(shoppingCart);
await _dbContext.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Here are my table models for the shopping cart and project tables (Code-first):
Shopping Cart table:
namespace FordWare.Models
{
public class ShoppingCart
{
#nullable disable
[Key]
[Required]
public int Id { get; set; }
#nullable enable
public string? AppUserId { get; set; }
#nullable enable
[ValidateNever]
public AppUser? AppUser { get; set; }
#nullable enable
public int? ProjectId { get; set; }
#nullable enable
[ValidateNever]
public Project? Project { get; set; }
#nullable enable
public double? PaymentAmount { get; set; }
}
}
Project table:
namespace FordWare.Models
{
public class Project
{
#nullable disable
[Required]
[Key]
public int Id { get; set; }
#nullable disable
[Required]
public string Description { get; set; }
#nullable enable
[ValidateNever]
[DisplayName("Image")]
public string? ImageURL { get; set; }
#nullable enable
public string? LinkToProject { get; set; }
#nullable enable
public double? OriginalPrice { get; set; }
#nullable enable
public double? AmountPaid { get; set; }
#nullable enable
public double? RemainingBalance { get; set; }
#nullable disable
[Required]
public string ServiceCSV { get; set; }
#nullable enable
[DisplayName("Company")]
public int? CompanyId { get; set; }
#nullable enable
[ForeignKey("CompanyId")]
[ValidateNever]
public Company? Company { get; set; }
#nullable disable
[Required]
public double EstimatedHours { get; set; }
#nullable disable
[Required]
public double EstimatedPrice { get; set; }
#nullable disable
[Required]
public DateTime TargetStartDate { get; set; }
#nullable disable
[Required]
public DateTime TargetCompletionDate { get; set; }
}
}
This is the error I get when trying to Add a new shopping cart, then save changes in the database.. It is trying to insert a new project, and the description column on projects is required... so it is throwing a null error... However, I don't want to insert a new project here... It is trying to do this I guess because of the Project navigation property on the ShoppingCart model:
| [
"As @progman has already stated in the comments, this is probably due to the Project property of the ShoppingCart being posted on your MakePaymentmethod. From the Entity Framework documentation:\n\nHowever, the Add methods don't just work on an individual entity. They actually start tracking an entire graph of related entities, putting them all to the Added state. For example, to insert a new blog and associated new posts\n\nSo if you post a Project on the ShoppingCart that does not exist on the database, Entity Framework will create a new one. And if the Project exists, your previous query will track it and my guess is that Entity Framework will navigate the newly attached ShoppingCart an edit the existing project properties with the values found on the shoppingCart.Project.\nMaybe you can check the change debugging information, it looks very promising for the kind of issue you want to debug.\n"
] | [
0
] | [] | [] | [
".net_6.0",
"c#",
"entity_framework_core"
] | stackoverflow_0074670659_.net_6.0_c#_entity_framework_core.txt |
Q:
Is it bad practice to use dependency injection to create a singleton object that can then be used throughout the app in swift?
So imagine I have an object User like so:
class User {
var id: Int
var name: String
var phone: String
}
And some service that gets the details like so:
protocol UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void)
}
and then an API Service
class UserAPIService: UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void) {
// GET USER FROM API HERE
}
}
And a service for testing
class UserTestService: UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void) {
// RETURN SOME TEST USER HERE
}
}
Now the obvious implementation here is in any class that requires the service in the app you create a UserAPIService object and inject it in to use. And then in testing you create the UserTestService and inject it in to use.
So this means (for my use case), that every ViewModal which hits this function, I need to create and inject in the service. Now that is fine, and it seems to be the practice that I see everywhere, but my question is, why not create a singleton on app/test start so that I don't have to inject it everywhere? For example, create a singleton instance of the UserService like so:
fileprivate _current: UserService?
class UserServiceManager {
static var current: UserService {
get {
if let c = _current { return c }
return UserAPIService() //return some default if not set
}
set {
_current = newVal
}
}
}
Then we can set the required usage in either the App Delegates didFinishLaunchingWithOptions or Tests setUpWithError like so:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UserServiceManager.current = UserAPIService()
return true
}
and
override func setUpWithError() throws {
UserServiceManager.current = UserTestService()
}
Now everywhere I use it, I don't need to inject it, I can just use the UserServiceManager.current request. Is this bad practice? And if so, why? It seems like a more DRY version. My only concern I can see this far is that if I decide to split my code into modules, then I will have to import each module into the AppDelegate.
A:
If you are going to use the same object for every injection, then you don't need injection in the first place.
If you are not going to use the same object for every injection, then a singleton is a poor choice for generating runtime objects, because
being static, no access to any runtime properties
only one instance at a time, when you expect many runtime variations
problems with singletons in general, you have no way to track who mutates it from where.
From your use case here, I'd say create the service as a singleton, then you can remove all injection.
There are libraries that build around singleton for complex dependencies, which imo are over-generalization. For example, I never need to inject network service to anything. Why made complex dependencies in the first place?
So yes, I think singleton for dependency injection is a bad practice. For other purpose, depends on usage.
| Is it bad practice to use dependency injection to create a singleton object that can then be used throughout the app in swift? | So imagine I have an object User like so:
class User {
var id: Int
var name: String
var phone: String
}
And some service that gets the details like so:
protocol UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void)
}
and then an API Service
class UserAPIService: UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void) {
// GET USER FROM API HERE
}
}
And a service for testing
class UserTestService: UserService {
func getUser(withID id: Int, completion: @escaping(_ user: User, _ error: Error) -> Void) {
// RETURN SOME TEST USER HERE
}
}
Now the obvious implementation here is in any class that requires the service in the app you create a UserAPIService object and inject it in to use. And then in testing you create the UserTestService and inject it in to use.
So this means (for my use case), that every ViewModal which hits this function, I need to create and inject in the service. Now that is fine, and it seems to be the practice that I see everywhere, but my question is, why not create a singleton on app/test start so that I don't have to inject it everywhere? For example, create a singleton instance of the UserService like so:
fileprivate _current: UserService?
class UserServiceManager {
static var current: UserService {
get {
if let c = _current { return c }
return UserAPIService() //return some default if not set
}
set {
_current = newVal
}
}
}
Then we can set the required usage in either the App Delegates didFinishLaunchingWithOptions or Tests setUpWithError like so:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UserServiceManager.current = UserAPIService()
return true
}
and
override func setUpWithError() throws {
UserServiceManager.current = UserTestService()
}
Now everywhere I use it, I don't need to inject it, I can just use the UserServiceManager.current request. Is this bad practice? And if so, why? It seems like a more DRY version. My only concern I can see this far is that if I decide to split my code into modules, then I will have to import each module into the AppDelegate.
| [
"If you are going to use the same object for every injection, then you don't need injection in the first place.\nIf you are not going to use the same object for every injection, then a singleton is a poor choice for generating runtime objects, because\n\nbeing static, no access to any runtime properties\n\nonly one instance at a time, when you expect many runtime variations\n\nproblems with singletons in general, you have no way to track who mutates it from where.\n\n\nFrom your use case here, I'd say create the service as a singleton, then you can remove all injection.\nThere are libraries that build around singleton for complex dependencies, which imo are over-generalization. For example, I never need to inject network service to anything. Why made complex dependencies in the first place?\nSo yes, I think singleton for dependency injection is a bad practice. For other purpose, depends on usage.\n"
] | [
2
] | [] | [] | [
"ios",
"software_design",
"swift"
] | stackoverflow_0073075072_ios_software_design_swift.txt |
Q:
Trying to map on api but an error occured
https://codesandbox.io/s/priceless-lake-s2qh1l?file=/src/NewsItem.js
Here i am trying to map on an api but an error occured
Tihis is what I tried , as I need to map to render the page accordingly
{item.map(list => (
<h1>list.title</h1>
))}
A:
Hi @Farah Fahmy,
Above the error:-
TypeError item.map is not a function.
That means your API data which you fetch is not in array-in-object form or simply in array form. As you know, all mapping method. If its filter , map, reduce, shift etc. only work with array.
I check your API data which you are fetching and as I mention above your data is not proper form. Its return object.
So, you just need to add in your setItems([data]) like this. now it's working fine.
And also try to do in async function. When you fetch data.
Check out this:- codesandbox.
| Trying to map on api but an error occured | https://codesandbox.io/s/priceless-lake-s2qh1l?file=/src/NewsItem.js
Here i am trying to map on an api but an error occured
Tihis is what I tried , as I need to map to render the page accordingly
{item.map(list => (
<h1>list.title</h1>
))}
| [
"Hi @Farah Fahmy,\nAbove the error:-\n\nTypeError item.map is not a function.\n\nThat means your API data which you fetch is not in array-in-object form or simply in array form. As you know, all mapping method. If its filter , map, reduce, shift etc. only work with array.\nI check your API data which you are fetching and as I mention above your data is not proper form. Its return object.\nSo, you just need to add in your setItems([data]) like this. now it's working fine.\nAnd also try to do in async function. When you fetch data.\nCheck out this:- codesandbox.\n"
] | [
0
] | [] | [] | [
"reactjs"
] | stackoverflow_0074675479_reactjs.txt |
Q:
for loop and if in python and csv
Worked on csv data need to use if statment for three column in the data ( if Vshale <= 0.35 and Effective_porosity>=0.1 and SW_SIM <=0.5 ) if these condition found mack true in new column else false
CUTOFF =[]
for (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:
if [i <= '0.35', j >= '0.1' , z <= '0.5']:
well[''] = CUTOFF .append('True')
else:
well[''] = CUTOFFa .append('False ')
A:
you should use the and statement as a part of you if logic.
CUTOFF =[]
for (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:
if i <= '0.35' and j >= '0.1' and z <= '0.5':
well[''] = CUTOFF.append('True')
else:
well[''] = CUTOFF.append('False')
as well you had a few white spaces on your .append() to your new list and your second .append() also was referencing a new list CUTOFFA. So I changed that to your original list. You also had an indentation error on the else:.
from the way you describe what you need I think this should be what you need, although I am not 100% sure.
hope that works.
| for loop and if in python and csv | Worked on csv data need to use if statment for three column in the data ( if Vshale <= 0.35 and Effective_porosity>=0.1 and SW_SIM <=0.5 ) if these condition found mack true in new column else false
CUTOFF =[]
for (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:
if [i <= '0.35', j >= '0.1' , z <= '0.5']:
well[''] = CUTOFF .append('True')
else:
well[''] = CUTOFFa .append('False ')
| [
"you should use the and statement as a part of you if logic.\n\nCUTOFF =[]\nfor (i,j,z) in well['Vshale','Effective_Porosity','SW_SIM']:\n if i <= '0.35' and j >= '0.1' and z <= '0.5':\n well[''] = CUTOFF.append('True')\n else:\n well[''] = CUTOFF.append('False')\n\nas well you had a few white spaces on your .append() to your new list and your second .append() also was referencing a new list CUTOFFA. So I changed that to your original list. You also had an indentation error on the else:.\nfrom the way you describe what you need I think this should be what you need, although I am not 100% sure.\nhope that works.\n"
] | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074675431_for_loop_if_statement_python.txt |
Q:
Convert html to json in c#
I have a c# post which returns me html. My post is checking for an organization name and return the list of organizations with that name. My problem is that the post returns the html for whole page and i want only the list of organizations. I think that i should convert to json, or there is other possibility?
Post method:
WebRequest request = WebRequest.Create("http://www.mfinante.ro/numeCod.html");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "judet=40&name=ORACLE&submit=Vizualizare";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
A:
The best way to parse an HTML into JSON is
Parse your HTML using HTML Agility Pack.
Depending on what is in your HTML you can create a class in c# and create an object of it OR you can create a list of objects if HTML content is repetitive.
Class MyItem
{
int employeeId = 0;
string employeeName = String.Empty;
}
List<MyItem> list = new List<MyItem>();
JavaScriptSerializer js = new JavaScriptSerializer();
js.Serialize(list);
A:
Depending on the endpoint, you might have luck adding an Accept header to the request, asking for JSON.
I do not what properties that might be set on a WebRequest, but it might be something like
request.Accept = "application/json";
In that way, the request will ask the server to return the result in a JSON format, which might be more usable for you.
If it fails, then you'll have to extract the content from the HTML, constructing an object and then serialise that object into JSON.
A:
I will tell why your question can cause confusion. Consider example of html:
<html>
<body>
<p> example of paragraph </p>
</body>
</html>
Example of json:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
json is something, on which html is generated or initial fundament. So when you say you want to convert html to json it's really confusing, because it is impossible to figure out according to which rules you want to make this conversion. Or which tags from html should be ignored/added while creating json.
A:
There is no direct way to convert HTML to JSON. Make a tool!
However, the easiest way I found was to copy/paste the HTML directly from a browser, into Excel, with some manipulation to form a "table" structure.
Next use an Office Script to convert from Excel to JSON.
A:
I created a function to convert the json from HTML to json thanks to the other answer.
public string convertHtmlToJson(string finalHtml, string title, bool status)
{
Wpjson jsonObject = new Wpjson();
jsonObject.Title = title;
jsonObject.Content = finalHtml;
jsonObject.Status = status;
return new JavaScriptSerializer().Serialize(jsonObject);
}
In my class file I created I called it Wpjson and inside I put below:
public class Wpjson
{
string title = string.Empty;
string content = string.Empty;
bool status = false;
public string Title
{ get { return title; } set { title = value; } }
public string Content
{ get { return content; } set { content = value; } }
public bool Status
{ get { return status; } set { status = value; } }
}
| Convert html to json in c# | I have a c# post which returns me html. My post is checking for an organization name and return the list of organizations with that name. My problem is that the post returns the html for whole page and i want only the list of organizations. I think that i should convert to json, or there is other possibility?
Post method:
WebRequest request = WebRequest.Create("http://www.mfinante.ro/numeCod.html");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "judet=40&name=ORACLE&submit=Vizualizare";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
| [
"The best way to parse an HTML into JSON is\n\nParse your HTML using HTML Agility Pack.\nDepending on what is in your HTML you can create a class in c# and create an object of it OR you can create a list of objects if HTML content is repetitive.\nClass MyItem\n{\n int employeeId = 0;\n string employeeName = String.Empty;\n}\n\nList<MyItem> list = new List<MyItem>();\nJavaScriptSerializer js = new JavaScriptSerializer();\njs.Serialize(list);\n\n\n",
"Depending on the endpoint, you might have luck adding an Accept header to the request, asking for JSON.\nI do not what properties that might be set on a WebRequest, but it might be something like\nrequest.Accept = \"application/json\";\n\nIn that way, the request will ask the server to return the result in a JSON format, which might be more usable for you.\nIf it fails, then you'll have to extract the content from the HTML, constructing an object and then serialise that object into JSON.\n",
"I will tell why your question can cause confusion. Consider example of html:\n<html>\n<body>\n<p> example of paragraph </p>\n</body> \n</html>\n Example of json:\n\n{\"employees\":[\n{\"firstName\":\"John\", \"lastName\":\"Doe\"},\n{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n{\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n]}\n\njson is something, on which html is generated or initial fundament. So when you say you want to convert html to json it's really confusing, because it is impossible to figure out according to which rules you want to make this conversion. Or which tags from html should be ignored/added while creating json.\n",
"There is no direct way to convert HTML to JSON. Make a tool!\nHowever, the easiest way I found was to copy/paste the HTML directly from a browser, into Excel, with some manipulation to form a \"table\" structure.\nNext use an Office Script to convert from Excel to JSON.\n",
"I created a function to convert the json from HTML to json thanks to the other answer.\npublic string convertHtmlToJson(string finalHtml, string title, bool status)\n {\n\n Wpjson jsonObject = new Wpjson();\n jsonObject.Title = title;\n jsonObject.Content = finalHtml;\n jsonObject.Status = status;\n\n return new JavaScriptSerializer().Serialize(jsonObject);\n\n\n }\n\nIn my class file I created I called it Wpjson and inside I put below:\n public class Wpjson\n {\n\n string title = string.Empty;\n string content = string.Empty;\n bool status = false;\n\n\n\n public string Title\n { get { return title; } set { title = value; } }\n\n public string Content\n { get { return content; } set { content = value; } }\n\n public bool Status\n { get { return status; } set { status = value; } }\n }\n\n"
] | [
1,
0,
0,
0,
0
] | [] | [] | [
"c#",
"html",
"json",
"post"
] | stackoverflow_0043755970_c#_html_json_post.txt |
Q:
How to deep copy nested map in flutter?
final Map<String, List<List<dynamic>>> originalData = {
"Chicago": [
[
8512,
7,
3620.15,
],
[
8421,
7,
5625,
],
],
"California": [
[
8512,
21,
11407.630000000001,
],
[
8708,
12,
5537.84,
],
]
};
Map<String, List<List<dynamic>>> myNewMap = Map.from(originalData);
myNewMap.forEach((st, data) {
data.forEach((List<dynamic> row) {
row.insert(0, st);
});
});
I tried Map.from(), ...OriginalData, and many more methods but it still change the OriginalData.
Expected Result should be:
myNewMap = {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}
originalData = {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}
Flutter uses shallow copy, but I also tried known methods of deep copy but nothing works.
Please help me to get over this.
A:
I referred to this site. According to this site, the problem in your code is that in the multi-dimensional map the method used by you doesn't work it only works in one dimensional maps.
Full Code
import 'dart:convert';
void main() {
final Map originalData = {
"Chicago": [
[
8512,
7,
3620.15,
],
[
8421,
7,
5625,
],
],
"California": [
[
8512,
21,
11407.630000000001,
],
[
8708,
12,
5537.84,
],
]
};
Map myNewMap = json.decode(json.encode(originalData));
myNewMap.forEach((st, data) {
data.forEach((row) {
row.insert(0, st);
});
});
print("New Map: $myNewMap");
print("Original Map: $originalData");
}
Output
New Map: {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}
Original Map: {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}
Hope this helps. Happy Coding :)
| How to deep copy nested map in flutter? | final Map<String, List<List<dynamic>>> originalData = {
"Chicago": [
[
8512,
7,
3620.15,
],
[
8421,
7,
5625,
],
],
"California": [
[
8512,
21,
11407.630000000001,
],
[
8708,
12,
5537.84,
],
]
};
Map<String, List<List<dynamic>>> myNewMap = Map.from(originalData);
myNewMap.forEach((st, data) {
data.forEach((List<dynamic> row) {
row.insert(0, st);
});
});
I tried Map.from(), ...OriginalData, and many more methods but it still change the OriginalData.
Expected Result should be:
myNewMap = {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}
originalData = {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}
Flutter uses shallow copy, but I also tried known methods of deep copy but nothing works.
Please help me to get over this.
| [
"I referred to this site. According to this site, the problem in your code is that in the multi-dimensional map the method used by you doesn't work it only works in one dimensional maps.\nFull Code\nimport 'dart:convert';\n\nvoid main() {\nfinal Map originalData = {\n \"Chicago\": [\n [\n 8512,\n 7,\n 3620.15,\n ],\n [\n 8421,\n 7,\n 5625,\n ],\n ],\n \"California\": [\n [\n 8512,\n 21,\n 11407.630000000001,\n ],\n [\n 8708,\n 12,\n 5537.84,\n ],\n ]\n };\n\n Map myNewMap = json.decode(json.encode(originalData));\n\n myNewMap.forEach((st, data) {\n data.forEach((row) {\n row.insert(0, st);\n });\n});\n print(\"New Map: $myNewMap\");\n print(\"Original Map: $originalData\");\n}\n\nOutput\nNew Map: {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}\nOriginal Map: {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}\n\nHope this helps. Happy Coding :)\n"
] | [
0
] | [] | [] | [
"dart",
"deep_copy",
"flutter",
"flutter_android"
] | stackoverflow_0074675261_dart_deep_copy_flutter_flutter_android.txt |
Q:
How to upload multiple image on firebase using swift?
I just want to upload multiple image on firebase using swift. I am now uploading one image but unable to upload multiple image. Here is my code
let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOF_REF).child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil,completion: {(metadata,error) in
if error != nil {
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let postReference = ref.child("posts")
let newPostId = postReference.childByAutoId().key
let newPostReference = postReference.child(newPostId)
newPostReference.setValue(["photoUrl":photoUrl,"caption":self.textView.text!])
A:
Currently there is no direct API to uploading/downloading the files in batch. We can not use loop because all the tasks perform asynchronously. What we can do is to use a recursive function.
Core Logic
let images = [image1, image2, image3, image4]
func uploadImage(forIndex index: Int) {
if index < images.count {
/// Perform uploading
/// After successfully uploading call this method again by increment the **index = index + 1**
return;
}
/// All images have been uploaded successfully
}
Full Code Example
1. I created a custom class for file uploading
import UIKit
import Firebase
class FirFile: NSObject {
/// Singleton instance
static let shared: FirFile = FirFile()
/// Path
let kFirFileStorageRef = Storage.storage().reference().child("Files")
/// Current uploading task
var currentUploadTask: StorageUploadTask?
func upload(data: Data,
withName fileName: String,
block: @escaping (_ url: String?) -> Void) {
// Create a reference to the file you want to upload
let fileRef = kFirFileStorageRef.child(fileName)
/// Start uploading
upload(data: data, withName: fileName, atPath: fileRef) { (url) in
block(url)
}
}
func upload(data: Data,
withName fileName: String,
atPath path:StorageReference,
block: @escaping (_ url: String?) -> Void) {
// Upload the file to the path
self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
let url = metaData?.downloadURL()?.absoluteString
block(url)
}
}
func cancel() {
self.currentUploadTask?.cancel()
}
}
2. Here how can we use this
First of all create a completion block for main function which will let you know when all images will be uploaded successfully.
/// This is your images array
let images = [image1, image2, image3, image4]
/// Here is the completion block
typealias FileCompletionBlock = () -> Void
var block: FileCompletionBlock?
Below are two functions first one is the initial one which will start the uploading and the second one is a recursion which will call itself if there is next image available to upload.
func startUploading(completion: @escaping FileCompletionBlock) {
if images.count == 0 {
completion()
return;
}
block = completion
uploadImage(forIndex: 0)
}
func uploadImage(forIndex index:Int) {
if index < images.count {
/// Perform uploading
let data = UIImagePNGRepresentation(images[index])!
let fileName = String(format: "%@.png", "yourUniqueFileName")
FirFile.shared.upload(data: data, withName: fileName, block: { (url) in
/// After successfully uploading call this method again by increment the **index = index + 1**
print(url ?? "Couldn't not upload. You can either check the error or just skip this.")
self.uploadImage(forIndex: index + 1)
})
return;
}
if block != nil {
block!()
}
}
And finally here is the main function with completion block
startUploading {
/// All the images have been uploaded successfully.
}
EDIT "upload" function for new Firebase:
The only difference is the way of getting downloading url. Here is the new Firebase doc on same.
func upload(data: Data,
withName fileName: String,
atPath path:StorageReference,
block: @escaping (_ url: String?) -> Void) {
// Upload the file to the path
self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
guard let metadata = metadata else {
Β Β // Uh-oh, an error occurred!
block(nil)
Β Β return
Β }
Β // Metadata contains file metadata such as size, content-type.
Β // let size = metadata.size
Β // You can also access to download URL after upload.
Β path.downloadURL { (url, error) in
Β Β guard let downloadURL = url else {
Β Β Β // Uh-oh, an error occurred!
block(nil)
return
Β Β }
block(url)
Β }
}
}
A:
With the new concurrency API and the updated Firebase API this got a lot simpler.
func someUpload(someImagesData: [Data]) async throws -> [String] {
// your path
let storageRef = storageRoot.child("somePath")
return try await withThrowingTaskGroup(of: String.self) { group in
// the urlStrings you are eventually returning
var urlStrings = [String]()
// just using index for testing purposes so each image doesnt rewrites itself
// of course you can also use a hash or a custom id instead of the index
// looping over each image data and the index
for (index, data) in someImagesData.enumerated() {
// adding the method of storing our image and retriving the urlString to the task group
group.addTask(priority: .background) {
let _ = try await storageRef.child("\(index)").putDataAsync(data)
return try await storageRef.child("\(index)").downloadURL().absoluteString
}
}
for try await uploadedPhotoString in group {
// for each task in the group, add the newly uploaded urlSting to our array...
urlStrings.append(uploadedPhotoString)
}
// ... and lastly returning it
return urlStrings
}
}
| How to upload multiple image on firebase using swift? | I just want to upload multiple image on firebase using swift. I am now uploading one image but unable to upload multiple image. Here is my code
let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOF_REF).child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil,completion: {(metadata,error) in
if error != nil {
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let postReference = ref.child("posts")
let newPostId = postReference.childByAutoId().key
let newPostReference = postReference.child(newPostId)
newPostReference.setValue(["photoUrl":photoUrl,"caption":self.textView.text!])
| [
"Currently there is no direct API to uploading/downloading the files in batch. We can not use loop because all the tasks perform asynchronously. What we can do is to use a recursive function.\nCore Logic\nlet images = [image1, image2, image3, image4]\nfunc uploadImage(forIndex index: Int) {\n if index < images.count {\n /// Perform uploading\n /// After successfully uploading call this method again by increment the **index = index + 1**\n return;\n }\n\n /// All images have been uploaded successfully\n}\n\nFull Code Example\n1. I created a custom class for file uploading\nimport UIKit\nimport Firebase\n\nclass FirFile: NSObject {\n\n /// Singleton instance\n static let shared: FirFile = FirFile()\n\n /// Path\n let kFirFileStorageRef = Storage.storage().reference().child(\"Files\")\n\n /// Current uploading task\n var currentUploadTask: StorageUploadTask?\n\n func upload(data: Data,\n withName fileName: String,\n block: @escaping (_ url: String?) -> Void) {\n\n // Create a reference to the file you want to upload\n let fileRef = kFirFileStorageRef.child(fileName)\n\n /// Start uploading\n upload(data: data, withName: fileName, atPath: fileRef) { (url) in\n block(url)\n }\n }\n\n func upload(data: Data,\n withName fileName: String,\n atPath path:StorageReference,\n block: @escaping (_ url: String?) -> Void) {\n\n // Upload the file to the path\n self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in\n let url = metaData?.downloadURL()?.absoluteString\n block(url)\n }\n }\n\n func cancel() {\n self.currentUploadTask?.cancel()\n }\n}\n\n2. Here how can we use this\nFirst of all create a completion block for main function which will let you know when all images will be uploaded successfully.\n/// This is your images array\nlet images = [image1, image2, image3, image4]\n\n/// Here is the completion block\ntypealias FileCompletionBlock = () -> Void\nvar block: FileCompletionBlock?\n\nBelow are two functions first one is the initial one which will start the uploading and the second one is a recursion which will call itself if there is next image available to upload.\nfunc startUploading(completion: @escaping FileCompletionBlock) {\n if images.count == 0 {\n completion()\n return;\n }\n\n block = completion\n uploadImage(forIndex: 0)\n}\n\nfunc uploadImage(forIndex index:Int) {\n\n if index < images.count {\n /// Perform uploading\n let data = UIImagePNGRepresentation(images[index])!\n let fileName = String(format: \"%@.png\", \"yourUniqueFileName\")\n\n FirFile.shared.upload(data: data, withName: fileName, block: { (url) in\n /// After successfully uploading call this method again by increment the **index = index + 1**\n print(url ?? \"Couldn't not upload. You can either check the error or just skip this.\")\n self.uploadImage(forIndex: index + 1)\n })\n return;\n }\n\n if block != nil {\n block!()\n }\n}\n\nAnd finally here is the main function with completion block\nstartUploading {\n /// All the images have been uploaded successfully.\n}\n\nEDIT \"upload\" function for new Firebase:\nThe only difference is the way of getting downloading url. Here is the new Firebase doc on same.\nfunc upload(data: Data,\n withName fileName: String,\n atPath path:StorageReference,\n block: @escaping (_ url: String?) -> Void) {\n\n // Upload the file to the path\n self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in\n guard let metadata = metadata else {\nΒ Β // Uh-oh, an error occurred!\n block(nil)\nΒ Β return\nΒ }\nΒ // Metadata contains file metadata such as size, content-type.\nΒ // let size = metadata.size\nΒ // You can also access to download URL after upload.\nΒ path.downloadURL { (url, error) in\nΒ Β guard let downloadURL = url else {\nΒ Β Β // Uh-oh, an error occurred!\n block(nil)\n return\nΒ Β }\n block(url)\nΒ }\n }\n}\n\n",
"With the new concurrency API and the updated Firebase API this got a lot simpler.\nfunc someUpload(someImagesData: [Data]) async throws -> [String] {\n // your path\n let storageRef = storageRoot.child(\"somePath\")\n \n return try await withThrowingTaskGroup(of: String.self) { group in\n \n // the urlStrings you are eventually returning\n var urlStrings = [String]()\n \n // just using index for testing purposes so each image doesnt rewrites itself\n // of course you can also use a hash or a custom id instead of the index\n \n // looping over each image data and the index\n for (index, data) in someImagesData.enumerated() {\n \n // adding the method of storing our image and retriving the urlString to the task group\n group.addTask(priority: .background) {\n let _ = try await storageRef.child(\"\\(index)\").putDataAsync(data)\n return try await storageRef.child(\"\\(index)\").downloadURL().absoluteString\n }\n }\n \n for try await uploadedPhotoString in group {\n // for each task in the group, add the newly uploaded urlSting to our array...\n urlStrings.append(uploadedPhotoString)\n }\n // ... and lastly returning it\n return urlStrings\n }\n }\n\n"
] | [
13,
0
] | [] | [] | [
"firebase",
"firebase_storage",
"ios",
"swift"
] | stackoverflow_0049934195_firebase_firebase_storage_ios_swift.txt |
Q:
Trying to generate a simple password generator in C#. This is what I have so far. Trying to get the console to print out what the user has picked
I can't seem to figure out how to print out what the user has entered for their password once their finished answering the questions.
I want to use 4 different for loops for upperCase, lowerCase, numbers, symbols,based on what the user has entered. If anyone has any different ideas please share. It would be a great help. I'm new to programming.
Here is what I have so far
string upperCase = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ;
string lowerCase = ("abcdefghijklmnopqrstuvwxyz");
string numbers = ("1234567890" );
string specChac = ("!@#$%^&*():<>?/");
string randomPassword = upperCase + lowerCase + numbers + specChac;
string allPasswords = "randomPassword";
Random rnd = new Random();
Console.WriteLine("Welocme to the C# password generator! ");
Console.WriteLine("----------------------------------------");
Console.WriteLine("How many uppercase letters would you like in your password ?");
int upperAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many lowercase letters would you like in your password ?");
int lowerAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many numbers would you like in your password ?");
int numAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many special characters would you like in your password?");
int charAmount = int.Parse(Console.ReadLine());
A:
To finish the password generator, you could use the System.Random class to generate a random password that meets the specified criteria. For example, you could use the Next method to generate random numbers, the ToChar method to convert the numbers to characters, and the Concat method to combine the characters into a single string. Here's an example of how you could use these methods to generate a random password:
// Create a random number generator
var random = new Random();
// Create arrays of characters to use in the password
// you can use your own arrays instead of these.
var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
var lowerChars = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
var numChars = "0123456789".ToCharArray();
var specialChars = "!@#$%^&*()".ToCharArray();
// Generate the password
var password = Enumerable.Empty<char>();
password = password.Concat(Enumerable.Range(0, upperAmount).Select(i => upperChars[random.Next(upperChars.Length)]));
password = password.Concat(Enumerable.Range(0, lowerAmount).Select(i => lowerChars[random.Next(lowerChars.Length)]));
password = password.Concat(Enumerable.Range(0, numAmount).Select(i => numChars[random.Next(numChars.Length)]));
password = password.Concat(Enumerable.Range(0, charAmount).Select(i => specialChars[random.Next(specialChars.Length)]));
// Shuffle the password
password = password.OrderBy(c => random.Next());
// Convert the password to a string and display it
Console.WriteLine(string.Join("", password));
This code uses the System.Linq namespace, so you will need to add a using statement for that namespace at the top of your file. Also, note that this code doesn't check if the user's input is valid (e.g. if they entered negative numbers or numbers that are too large), so you may want to add some error checking to your code.
-chatgpt
A:
Well, there are many many ways on how to implement that.
Here is one showing the concept of seeding.
Instead of defining the possible characters I just assign the possible minimum and maximum ASCII character code.
You can do it however you want.
internal static class RandomPswd
{
const int CHAR_UPPER_MIN = 0x41;
const int CHAR_UPPER_MAX = 0x5a;
const int CHAR_LOWER_MIN = 0x61;
const int CHAR_LOWER_MAX = 0x7a;
const int CHAR_DIGIT_MIN = 0x30;
const int CHAR_DIGIT_MAX = 0x39;
const int CHAR_SYMBL_MIN = 0x21;
const int CHAR_SYMBL_MAX = 0x2f;
private static void Shuffle(char[] buffer)
{
int seed = GetSeed();
Random r = new Random(seed);
int n = buffer.Length;
while (n > 1) {
int k = r.Next(n--);
char t = buffer[n];
buffer[n] = buffer[k];
buffer[k] = t;
}
}
private static int GetSeed()
{
unchecked
{
int hash = (int)DateTime.Now.Ticks * 7302013 ^ Environment.UserName.GetHashCode();
hash = hash * 7302013 ^ (CHAR_UPPER_MIN.GetHashCode());
hash = hash * 7302013 ^ (CHAR_UPPER_MAX.GetHashCode());
hash = hash * 7302013 ^ (CHAR_LOWER_MIN.GetHashCode());
hash = hash * 7302013 ^ (CHAR_LOWER_MAX.GetHashCode());
hash = hash * 7302013 ^ (CHAR_DIGIT_MIN.GetHashCode());
hash = hash * 7302013 ^ (CHAR_DIGIT_MAX.GetHashCode());
hash = hash * 7302013 ^ (CHAR_SYMBL_MIN.GetHashCode());
hash = hash * 7302013 ^ (CHAR_SYMBL_MAX.GetHashCode());
return hash;
}
}
public static string Create(int upper, int lower, int digits, int symbols)
{
char[] upperChars = new char[upper];
char[] lowerChars = new char[lower];
char[] digitChars = new char[digits];
char[] symblChars = new char[symbols];
int seed = GetSeed();
Random r = new Random(seed);
for (int i=0; i<upper; i++) {
upperChars[i] = (char)r.Next(CHAR_UPPER_MIN, CHAR_UPPER_MAX);
}
seed = GetSeed();
r = new Random(seed);
for (int i = 0; i < lower; i++) {
lowerChars[i] = (char)r.Next(CHAR_LOWER_MIN, CHAR_LOWER_MAX);
}
seed = GetSeed();
r = new Random(seed);
for (int i = 0; i < digits; i++) {
digitChars[i] = (char)r.Next(CHAR_DIGIT_MIN, CHAR_DIGIT_MAX);
}
seed = GetSeed();
r = new Random(seed);
for (int i=0; i< symbols; i++) {
symblChars[i] = (char)r.Next(CHAR_SYMBL_MIN, CHAR_SYMBL_MAX);
}
char[] buf = new char[upper + lower + digits + symbols];
upperChars.CopyTo(buf, 0);
lowerChars.CopyTo(buf, upper);
digitChars.CopyTo(buf, upper + lower);
symblChars.CopyTo(buf, upper + lower + digits);
Shuffle(buf);
return new string(buf);
}
}
static void Main()
{
var pw = RandomPswd.Create(12, 8, 7, 5);
}
| Trying to generate a simple password generator in C#. This is what I have so far. Trying to get the console to print out what the user has picked | I can't seem to figure out how to print out what the user has entered for their password once their finished answering the questions.
I want to use 4 different for loops for upperCase, lowerCase, numbers, symbols,based on what the user has entered. If anyone has any different ideas please share. It would be a great help. I'm new to programming.
Here is what I have so far
string upperCase = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ;
string lowerCase = ("abcdefghijklmnopqrstuvwxyz");
string numbers = ("1234567890" );
string specChac = ("!@#$%^&*():<>?/");
string randomPassword = upperCase + lowerCase + numbers + specChac;
string allPasswords = "randomPassword";
Random rnd = new Random();
Console.WriteLine("Welocme to the C# password generator! ");
Console.WriteLine("----------------------------------------");
Console.WriteLine("How many uppercase letters would you like in your password ?");
int upperAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many lowercase letters would you like in your password ?");
int lowerAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many numbers would you like in your password ?");
int numAmount = int.Parse(Console.ReadLine());
Console.WriteLine("How many special characters would you like in your password?");
int charAmount = int.Parse(Console.ReadLine());
| [
"To finish the password generator, you could use the System.Random class to generate a random password that meets the specified criteria. For example, you could use the Next method to generate random numbers, the ToChar method to convert the numbers to characters, and the Concat method to combine the characters into a single string. Here's an example of how you could use these methods to generate a random password:\n// Create a random number generator\nvar random = new Random();\n\n// Create arrays of characters to use in the password\n// you can use your own arrays instead of these.\nvar upperChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".ToCharArray();\nvar lowerChars = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray();\nvar numChars = \"0123456789\".ToCharArray();\nvar specialChars = \"!@#$%^&*()\".ToCharArray();\n\n// Generate the password\nvar password = Enumerable.Empty<char>();\npassword = password.Concat(Enumerable.Range(0, upperAmount).Select(i => upperChars[random.Next(upperChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, lowerAmount).Select(i => lowerChars[random.Next(lowerChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, numAmount).Select(i => numChars[random.Next(numChars.Length)]));\npassword = password.Concat(Enumerable.Range(0, charAmount).Select(i => specialChars[random.Next(specialChars.Length)]));\n\n// Shuffle the password\npassword = password.OrderBy(c => random.Next());\n\n// Convert the password to a string and display it\nConsole.WriteLine(string.Join(\"\", password));\n\n\n\nThis code uses the System.Linq namespace, so you will need to add a using statement for that namespace at the top of your file. Also, note that this code doesn't check if the user's input is valid (e.g. if they entered negative numbers or numbers that are too large), so you may want to add some error checking to your code.\n-chatgpt\n",
"Well, there are many many ways on how to implement that.\nHere is one showing the concept of seeding.\nInstead of defining the possible characters I just assign the possible minimum and maximum ASCII character code.\nYou can do it however you want.\ninternal static class RandomPswd\n{\n const int CHAR_UPPER_MIN = 0x41;\n const int CHAR_UPPER_MAX = 0x5a;\n const int CHAR_LOWER_MIN = 0x61;\n const int CHAR_LOWER_MAX = 0x7a;\n const int CHAR_DIGIT_MIN = 0x30;\n const int CHAR_DIGIT_MAX = 0x39;\n const int CHAR_SYMBL_MIN = 0x21;\n const int CHAR_SYMBL_MAX = 0x2f;\n\n\n private static void Shuffle(char[] buffer)\n {\n int seed = GetSeed();\n Random r = new Random(seed);\n\n int n = buffer.Length;\n while (n > 1) {\n int k = r.Next(n--);\n char t = buffer[n];\n buffer[n] = buffer[k];\n buffer[k] = t;\n }\n }\n\n\n private static int GetSeed()\n {\n unchecked\n {\n int hash = (int)DateTime.Now.Ticks * 7302013 ^ Environment.UserName.GetHashCode();\n hash = hash * 7302013 ^ (CHAR_UPPER_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_UPPER_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_LOWER_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_LOWER_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_DIGIT_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_DIGIT_MAX.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_SYMBL_MIN.GetHashCode());\n hash = hash * 7302013 ^ (CHAR_SYMBL_MAX.GetHashCode());\n return hash;\n } \n }\n\n public static string Create(int upper, int lower, int digits, int symbols)\n {\n char[] upperChars = new char[upper];\n char[] lowerChars = new char[lower];\n char[] digitChars = new char[digits];\n char[] symblChars = new char[symbols];\n\n int seed = GetSeed();\n Random r = new Random(seed);\n for (int i=0; i<upper; i++) {\n upperChars[i] = (char)r.Next(CHAR_UPPER_MIN, CHAR_UPPER_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i = 0; i < lower; i++) {\n lowerChars[i] = (char)r.Next(CHAR_LOWER_MIN, CHAR_LOWER_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i = 0; i < digits; i++) {\n digitChars[i] = (char)r.Next(CHAR_DIGIT_MIN, CHAR_DIGIT_MAX);\n }\n\n seed = GetSeed();\n r = new Random(seed);\n for (int i=0; i< symbols; i++) {\n symblChars[i] = (char)r.Next(CHAR_SYMBL_MIN, CHAR_SYMBL_MAX);\n }\n\n char[] buf = new char[upper + lower + digits + symbols];\n upperChars.CopyTo(buf, 0);\n lowerChars.CopyTo(buf, upper);\n digitChars.CopyTo(buf, upper + lower);\n symblChars.CopyTo(buf, upper + lower + digits);\n Shuffle(buf);\n\n return new string(buf);\n }\n}\n \n \nstatic void Main()\n{\n var pw = RandomPswd.Create(12, 8, 7, 5);\n}\n\n"
] | [
2,
0
] | [] | [] | [
"c#"
] | stackoverflow_0074671516_c#.txt |
Q:
Getting incorrect output from the flax model's init call
I am trying to create a simple neural network using flax, as shown below.
However, the params frozen dict I receive as the output to of model.init is empty instead of having the parameters of the neural network. Also the the type(predictions) is flax.linen.combinators.Sequential object instead of being a DeviceArray.
Can someone help me understand what is wrong with this code snippet?
import jax
import jax.numpy as jnp
import flax.linen as nn
import matplotlib.pyplot as plt
class MLP(nn.Module):
@nn.compact
def __call__(self, x):
return nn.Sequential(
[
nn.Dense(40),
nn.relu,
nn.Dense(40),
nn.Dense(1),
]
)
model = MLP()
dummy_input = jnp.ones((40, 40, 1))
params = model.init(jax.random.PRNGKey(0), dummy_input)
jax.tree_util.tree_map(lambda x: x.shape, params)
n = 100
x_inputs = jnp.linspace(-10, 10, n).reshape(1, -1)
y_targets = jnp.sin(x_inputs)
predictions = model.apply(params, x_inputs)
plt.plot(x_inputs.reshape(-1), y_targets.reshape(-1))
plt.plot(x_inputs.reshape(-1), predictions.reshape(-1))
A:
The issue is that you are passing a three-dimensional array to the init method of your MLP model, but the model expects a two-dimensional input. The dummy_input array that you are passing to the init method has shape (40, 40, 1), but it should have shape (40, 1) instead.
To fix this issue, you can change the dummy_input array to have the correct shape:
dummy_input = jnp.ones((40, 1))
| Getting incorrect output from the flax model's init call | I am trying to create a simple neural network using flax, as shown below.
However, the params frozen dict I receive as the output to of model.init is empty instead of having the parameters of the neural network. Also the the type(predictions) is flax.linen.combinators.Sequential object instead of being a DeviceArray.
Can someone help me understand what is wrong with this code snippet?
import jax
import jax.numpy as jnp
import flax.linen as nn
import matplotlib.pyplot as plt
class MLP(nn.Module):
@nn.compact
def __call__(self, x):
return nn.Sequential(
[
nn.Dense(40),
nn.relu,
nn.Dense(40),
nn.Dense(1),
]
)
model = MLP()
dummy_input = jnp.ones((40, 40, 1))
params = model.init(jax.random.PRNGKey(0), dummy_input)
jax.tree_util.tree_map(lambda x: x.shape, params)
n = 100
x_inputs = jnp.linspace(-10, 10, n).reshape(1, -1)
y_targets = jnp.sin(x_inputs)
predictions = model.apply(params, x_inputs)
plt.plot(x_inputs.reshape(-1), y_targets.reshape(-1))
plt.plot(x_inputs.reshape(-1), predictions.reshape(-1))
| [
"The issue is that you are passing a three-dimensional array to the init method of your MLP model, but the model expects a two-dimensional input. The dummy_input array that you are passing to the init method has shape (40, 40, 1), but it should have shape (40, 1) instead.\nTo fix this issue, you can change the dummy_input array to have the correct shape:\ndummy_input = jnp.ones((40, 1))\n\n"
] | [
0
] | [] | [] | [
"flax",
"jax"
] | stackoverflow_0074675528_flax_jax.txt |
Q:
catching an error or exception thrown from a dynamically appended script element - possible?
I want to stop script execution in a dynamically appended script (as in include_guard) by throwing an error from the appended file. Then I want to catch this error from the file that did the "appending" (as in "making things clean").
index.html
<!DOCTYPE html>
<html>
<head>
<title>pickle</title>
</head>
<body>
<script type="text/javascript">
var de = document.createElement("script");
de.src = "file.js";
document.head.appendChild(de);
</script>
</body>
</html>
file.js
throw new Error("blabla");
How can I catch the error thrown ?
Something like this doesn't catch anything (probably because the appending is happening in a different thread):
var de = document.createElement("script");
de.src = "file.js";
try {
document.head.appendChild(de);
}
catch(e) {
console.log("got it");
}
I also tried setting an error listener to the window object, which does receive error notification, but the error is not caught.
Reason I want to do that: I wrote a javascript includer that works pretty much like the c/c++ #include directive with support for a #pragma once-like feature.
If a file is included 2+ times and it was tagged as once, I need to stop execution for this file - by throwing or erroring the script from inside the once() function.
Note: it aleady works. My once() function throws a custom include_guard object and script execution is halted. If possible, I want to catch that error and print a warning instead, to make things look cleaner (not a life or death situation...).
A:
It is possible to cancel an error by listening to it in window.onerror and returning true from the handler.
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event
Example:
window.onerror = function(event, source, lineno, colno, error) {
if (error instanceof my_custom_error) {
console.warn(my_custom_error + " was canceled.");
return true;
}
//don't disrupt anything else
return false;
}
In the specific issue of the OP tho, error is null and the error string in event is a generic Script error message (tested on Chrome), so this method can't be used.
It seems the reason for error to be null is that the error is thrown from a different file.
| catching an error or exception thrown from a dynamically appended script element - possible? | I want to stop script execution in a dynamically appended script (as in include_guard) by throwing an error from the appended file. Then I want to catch this error from the file that did the "appending" (as in "making things clean").
index.html
<!DOCTYPE html>
<html>
<head>
<title>pickle</title>
</head>
<body>
<script type="text/javascript">
var de = document.createElement("script");
de.src = "file.js";
document.head.appendChild(de);
</script>
</body>
</html>
file.js
throw new Error("blabla");
How can I catch the error thrown ?
Something like this doesn't catch anything (probably because the appending is happening in a different thread):
var de = document.createElement("script");
de.src = "file.js";
try {
document.head.appendChild(de);
}
catch(e) {
console.log("got it");
}
I also tried setting an error listener to the window object, which does receive error notification, but the error is not caught.
Reason I want to do that: I wrote a javascript includer that works pretty much like the c/c++ #include directive with support for a #pragma once-like feature.
If a file is included 2+ times and it was tagged as once, I need to stop execution for this file - by throwing or erroring the script from inside the once() function.
Note: it aleady works. My once() function throws a custom include_guard object and script execution is halted. If possible, I want to catch that error and print a warning instead, to make things look cleaner (not a life or death situation...).
| [
"It is possible to cancel an error by listening to it in window.onerror and returning true from the handler.\nDocumentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event\nExample:\nwindow.onerror = function(event, source, lineno, colno, error) {\n if (error instanceof my_custom_error) {\n console.warn(my_custom_error + \" was canceled.\");\n return true;\n }\n\n //don't disrupt anything else\n return false;\n}\n\nIn the specific issue of the OP tho, error is null and the error string in event is a generic Script error message (tested on Chrome), so this method can't be used.\nIt seems the reason for error to be null is that the error is thrown from a different file.\n"
] | [
0
] | [] | [] | [
"javascript"
] | stackoverflow_0074647504_javascript.txt |
Q:
Using Python Panda aggregates operation
I have a table like this-
Hotel Earning
Abu 1000
Zain 400
Show 500
Zint 300
Abu 500
Zain 700
Abu 500
Abu 500
Abu 800
Abu 1600
Show 1300
Zint 600
Using Panda, How to group by hotel and calculate the min, median and max of the earning on each hotel. And at the end print the aggregates values Hotel name "Abu".
Output:
[500.0, 650.0, 1600.0]
A:
Pandas DataFrame aggregate() Method
The aggregate() method allows you to apply a function or a list of function names to be executed along one of the axis of the DataFrame, default 0, which is the index (row) axis. Note: the agg() method is an alias of the aggregate()Β method.
A:
import pandas as pd
# Read the data into a Pandas DataFrame
df = pd.read_csv('hotel_earnings.csv')
# Group the data by hotel
hotels = df.groupby('Hotel')
# Calculate the min, median, and max of the earning for each hotel
earnings = hotels['Earning'].agg(['min', 'median', 'max'])
# Print the aggregated values for the hotel named "Abu"
print(earnings.loc['Abu'])
This code reads the data from the hotel_earnings.csv file into a Pandas DataFrame, groups the data by hotel, and calculates the minimum, median, and maximum earning for each hotel. It then prints the aggregated values for the hotel named "Abu"
A:
Use agg:
df.groupby('Hotel').agg([('Min' , 'min'), ('Max', 'max'), ('Median', 'median')])
# Out:
# Earning
# Min Max Median
# Hotel
# Abu 500 1600 650.0
# Show 500 1300 900.0
# Zain 400 700 550.0
# Zint 300 600 450.0
For more statistics you can also use describe()
df.groupby('Hotel').describe()
# Out:
# Earning
# count mean std min 25% 50% 75% max
# Hotel
# Abu 6.0 816.666667 435.507367 500.0 500.0 650.0 950.0 1600.0
# Show 2.0 900.000000 565.685425 500.0 700.0 900.0 1100.0 1300.0
# Zain 2.0 550.000000 212.132034 400.0 475.0 550.0 625.0 700.0
# Zint 2.0 450.000000 212.132034 300.0 375.0 450.0 525.0 600.0
| Using Python Panda aggregates operation | I have a table like this-
Hotel Earning
Abu 1000
Zain 400
Show 500
Zint 300
Abu 500
Zain 700
Abu 500
Abu 500
Abu 800
Abu 1600
Show 1300
Zint 600
Using Panda, How to group by hotel and calculate the min, median and max of the earning on each hotel. And at the end print the aggregates values Hotel name "Abu".
Output:
[500.0, 650.0, 1600.0]
| [
"Pandas DataFrame aggregate() Method\nThe aggregate() method allows you to apply a function or a list of function names to be executed along one of the axis of the DataFrame, default 0, which is the index (row) axis. Note: the agg() method is an alias of the aggregate()Β method.\n",
"import pandas as pd\n\n# Read the data into a Pandas DataFrame\ndf = pd.read_csv('hotel_earnings.csv')\n\n# Group the data by hotel\nhotels = df.groupby('Hotel')\n\n# Calculate the min, median, and max of the earning for each hotel\nearnings = hotels['Earning'].agg(['min', 'median', 'max'])\n\n# Print the aggregated values for the hotel named \"Abu\"\nprint(earnings.loc['Abu'])\n\nThis code reads the data from the hotel_earnings.csv file into a Pandas DataFrame, groups the data by hotel, and calculates the minimum, median, and maximum earning for each hotel. It then prints the aggregated values for the hotel named \"Abu\"\n",
"Use agg:\ndf.groupby('Hotel').agg([('Min' , 'min'), ('Max', 'max'), ('Median', 'median')])\n# Out:\n# Earning \n# Min Max Median\n# Hotel \n# Abu 500 1600 650.0\n# Show 500 1300 900.0\n# Zain 400 700 550.0\n# Zint 300 600 450.0\n\nFor more statistics you can also use describe()\ndf.groupby('Hotel').describe()\n# Out: \n# Earning \n# count mean std min 25% 50% 75% max\n# Hotel \n# Abu 6.0 816.666667 435.507367 500.0 500.0 650.0 950.0 1600.0\n# Show 2.0 900.000000 565.685425 500.0 700.0 900.0 1100.0 1300.0\n# Zain 2.0 550.000000 212.132034 400.0 475.0 550.0 625.0 700.0\n# Zint 2.0 450.000000 212.132034 300.0 375.0 450.0 525.0 600.0\n\n"
] | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074675584_pandas_python.txt |
Q:
Inifinite loop loading items with paging3 and Jetpack compose UI
I have a simple app with a single screen, displaying movies in a Composable items list:
I use Android's paging3 library in order to load the movies page by page, and things seem to be working well:
@Composable
fun FlixListScreen(viewModel: MoviesViewModel) {
val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()
MoviesList(lazyMovieItems)
}
@Composable
fun MoviesList(lazyPagedMovies: LazyPagingItems<Movie>) {
LazyColumn(modifier = Modifier.padding(horizontal = 16.dp)) {
itemsIndexed(lazyPagedMovies) { index, movie ->
MoviesListItem(index, movie!!)
}
}
}
In an attempt to add a progress indicator to the initial loading phase (e.g. as explained in an Android code-lab), I've tried applying the following conditional, based on loadState.refresh:
@Composable
fun FlixListScreen(viewModel: MoviesViewModel) {
val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()
// Added: Show a progress indicator while the data is loading
if (lazyPagedMovies.loadState.refresh is LoadState.Loading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
MoviesList(lazyMovieItems)
}
Instead of displaying the progress indicator, this naive addition seem to be putting the paging loader into an infinite loop, where the first page gets fetched over and over indefinitely, without any items effectively being loaded (let alone displayed) into the list.
Side note: Just to rule out that this all has something to do with the condition itself, it appears that even adding as little as this log: Log.i("DBG", ""+lazyPagesMovies.loadState) with no conditions at all, introduces the undesired behavior.
I'm using Kotlin version 1.7.10 and the various Compose libraries in version 1.3.1.
A:
Seems that with simple code I might have somehow hit some Compose related edge-case. I've managed to work around things by introducing the progress-indicator conditional under a sub-function (composeable) that accepts the paging items directly:
@Composable
fun FlixListScreen(viewModel: MoviesViewModel) {
val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()
MoviesScreen(lazyMovieItems) // was: MoviesList(lazyMovieItems)
}
// Newly added intermediate function
@Composable
fun MoviesScreen(lazyPagedMovies: LazyPagingItems<Movie>) {
MoviesList(lazyPagedMovies)
if (lazyPagedMovies.loadState.refresh is LoadState.Loading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
}
@Composable
fun MoviesList(lazyPagedMovies: LazyPagingItems<Movie>) {
// ... (unchanged)
}
| Inifinite loop loading items with paging3 and Jetpack compose UI | I have a simple app with a single screen, displaying movies in a Composable items list:
I use Android's paging3 library in order to load the movies page by page, and things seem to be working well:
@Composable
fun FlixListScreen(viewModel: MoviesViewModel) {
val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()
MoviesList(lazyMovieItems)
}
@Composable
fun MoviesList(lazyPagedMovies: LazyPagingItems<Movie>) {
LazyColumn(modifier = Modifier.padding(horizontal = 16.dp)) {
itemsIndexed(lazyPagedMovies) { index, movie ->
MoviesListItem(index, movie!!)
}
}
}
In an attempt to add a progress indicator to the initial loading phase (e.g. as explained in an Android code-lab), I've tried applying the following conditional, based on loadState.refresh:
@Composable
fun FlixListScreen(viewModel: MoviesViewModel) {
val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()
// Added: Show a progress indicator while the data is loading
if (lazyPagedMovies.loadState.refresh is LoadState.Loading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
MoviesList(lazyMovieItems)
}
Instead of displaying the progress indicator, this naive addition seem to be putting the paging loader into an infinite loop, where the first page gets fetched over and over indefinitely, without any items effectively being loaded (let alone displayed) into the list.
Side note: Just to rule out that this all has something to do with the condition itself, it appears that even adding as little as this log: Log.i("DBG", ""+lazyPagesMovies.loadState) with no conditions at all, introduces the undesired behavior.
I'm using Kotlin version 1.7.10 and the various Compose libraries in version 1.3.1.
| [
"Seems that with simple code I might have somehow hit some Compose related edge-case. I've managed to work around things by introducing the progress-indicator conditional under a sub-function (composeable) that accepts the paging items directly:\n@Composable\nfun FlixListScreen(viewModel: MoviesViewModel) {\n val lazyMovieItems = viewModel.moviesPageFlow.collectAsLazyPagingItems()\n MoviesScreen(lazyMovieItems) // was: MoviesList(lazyMovieItems)\n}\n\n// Newly added intermediate function\n@Composable\nfun MoviesScreen(lazyPagedMovies: LazyPagingItems<Movie>) {\n MoviesList(lazyPagedMovies)\n\n if (lazyPagedMovies.loadState.refresh is LoadState.Loading) {\n LinearProgressIndicator(modifier = Modifier.fillMaxWidth())\n }\n}\n\n@Composable\nfun MoviesList(lazyPagedMovies: LazyPagingItems<Movie>) {\n // ... (unchanged)\n}\n\n"
] | [
1
] | [] | [] | [
"android",
"android_jetpack_compose",
"android_paging_3"
] | stackoverflow_0074675699_android_android_jetpack_compose_android_paging_3.txt |
Q:
Hyperledger: The current identity, with the name 'admin' and the identifier has not been registered
I was in charge of solving a problem in Hyperledger which consists of identity expiration, unfortunately i do not have much details about the network itself, i've tried to delete the card using:
composer card delete admin@network
And using import:
composer card import -f admin.card
Both card and bna are the in the same directory, but when doing so if i try to ping the network it shows the following error:
Hyperledger: The current identity, with the name 'admin' and the identifier <ID> has not been registered
I just need to recover this admin user without loosing or changing anything in the network.
A:
There was a golden rule for hyperledger composer networks. Never let your identities expire. If you have (and it sounds like you have) then you will be locked out of your business network and there are no tools in hyperledger Composer to help you recover. Hyperledger Composer has been end of life for quite a while now so no one will be using it or developing it anymore.
A:
Have you check the listed cards on the network?
composer card list
for identity expiration and can't get access to your network, you can try this.
Set your machine datetime before the card expired.
go to your network directory ex. cd ~/example-network.
then request new identity:
composer identity request -c PeerAdmin@hlfv1 -u admin -s adminpw newadmin
create new admin card:
composer card create -p config/connection.json -u newadmin -n example-network -c newadmin/admin-pub.pem -k newadmin/admin-priv.pem
import created card:
composer card import -f [email protected]
extract created card (it's actually compressed file), i recommend to extract into new directory called newadmin.
bind new identity:
composer identity bind -c oldadmin@example-network --participantId resource:org.hyperledger.composer.system.NetworkAdmin#admin --certificateFile newadmin/credentials/certificate
set back your machine datetime.
now you have access to your network again.
composer network ping -c newadmin@example-network
cheers.
| Hyperledger: The current identity, with the name 'admin' and the identifier has not been registered | I was in charge of solving a problem in Hyperledger which consists of identity expiration, unfortunately i do not have much details about the network itself, i've tried to delete the card using:
composer card delete admin@network
And using import:
composer card import -f admin.card
Both card and bna are the in the same directory, but when doing so if i try to ping the network it shows the following error:
Hyperledger: The current identity, with the name 'admin' and the identifier <ID> has not been registered
I just need to recover this admin user without loosing or changing anything in the network.
| [
"There was a golden rule for hyperledger composer networks. Never let your identities expire. If you have (and it sounds like you have) then you will be locked out of your business network and there are no tools in hyperledger Composer to help you recover. Hyperledger Composer has been end of life for quite a while now so no one will be using it or developing it anymore.\n",
"Have you check the listed cards on the network?\ncomposer card list\n\nfor identity expiration and can't get access to your network, you can try this.\nSet your machine datetime before the card expired.\ngo to your network directory ex. cd ~/example-network.\nthen request new identity:\ncomposer identity request -c PeerAdmin@hlfv1 -u admin -s adminpw newadmin\n\ncreate new admin card:\ncomposer card create -p config/connection.json -u newadmin -n example-network -c newadmin/admin-pub.pem -k newadmin/admin-priv.pem\n\nimport created card:\ncomposer card import -f [email protected]\n\nextract created card (it's actually compressed file), i recommend to extract into new directory called newadmin.\nbind new identity:\ncomposer identity bind -c oldadmin@example-network --participantId resource:org.hyperledger.composer.system.NetworkAdmin#admin --certificateFile newadmin/credentials/certificate\n\nset back your machine datetime.\nnow you have access to your network again.\ncomposer network ping -c newadmin@example-network\n\ncheers.\n"
] | [
0,
0
] | [] | [] | [
"hyperledger",
"hyperledger_composer",
"hyperledger_fabric"
] | stackoverflow_0073884561_hyperledger_hyperledger_composer_hyperledger_fabric.txt |
Q:
FileNotFoundError: [Errno 2] No such file or directory: b'/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3' ( kivy app )
Since I got this error when building project in Xcode,
ModuleNotFoundError: No module named 'requests'
and then I'm trying to install the requests module with git command.
python toolchain.py pip install requests
However, I read the logs and I got this FileNotFoundError message. How can I deal with the error?
[INFO ] Using the bundled version for recipe 'host_setuptools3'
[INFO ] Using the bundled version for recipe 'hostopenssl'
[INFO ] Using the bundled version for recipe 'hostpython3'
[INFO ] Global: hostpython located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/python
[INFO ] Global: hostpgen located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pgen
[INFO ] Using the bundled version for recipe 'ios'
[INFO ] Using the bundled version for recipe 'kivy'
[INFO ] Using the bundled version for recipe 'libffi'
[INFO ] Include dir added: {arch.arch}/ffi
[INFO ] Using the bundled version for recipe 'openssl'
[INFO ] Include dir added: {arch.arch}/openssl
[INFO ] Using the bundled version for recipe 'pyobjus'
[INFO ] Using the bundled version for recipe 'python3'
[INFO ] Using the bundled version for recipe 'sdl2'
[INFO ] Include dir added: common/sdl2
[INFO ] Using the bundled version for recipe 'sdl2_image'
[INFO ] Include dir added: common/sdl2_image
[INFO ] Using the bundled version for recipe 'sdl2_mixer'
[INFO ] Include dir added: common/sdl2_mixer
[INFO ] Using the bundled version for recipe 'sdl2_ttf'
[INFO ] Include dir added: common/sdl2_ttf
[INFO ] Executing pip with: ['install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests']
[INFO ] Running Shell: /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3 ('install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests') {'_env': {'CC': '/bin/false', 'CXX': '/bin/false', 'PYTHONPATH': '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3/lib/python3.9/site-packages', 'PYTHONOPTIMIZE': '2'}, '_iter': True, '_out_bufsize': 1, '_err_to_out': True}
Traceback (most recent call last):
File "/Users/<myname>/Desktop/kivy/kivy-ios/toolchain.py", line 3, in <module>
main()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1555, in main
ToolchainCL()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1299, in __init__
getattr(self, args.command)()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1514, in pip
_pip(sys.argv[2:])
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1186, in _pip
shprint(pip_cmd, *args, _env=pip_env)
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 55, in shprint
cmd = command(*args, **kwargs)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 1524, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 780, in __init__
self.process = OProc(self, self.log, cmd, stdin, stdout, stderr,
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 2125, in __init__
raise ForkException(fork_exc)
sh.ForkException:
Original exception:
===================
Traceback (most recent call last):
File "/Users/gordonkwok/Desktop/kivy/kivy-ios/<myenv>/lib/python3.9/site-packages/sh.py", line 2080, in __init__
os.execve(cmd[0], cmd, ca["env"])
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3'
So I looked the file "/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3" and the virtual environment file "/Users//Desktop/kivy/kivy-ios//lib/python3.9/site-packages/sh.py" to see whether they are existed. And both of them are really existed! I'm so confuse with this error. So please help me out here! It is the finally step for me to run my first app soon! Thanks!
A:
Let's tackle this in steps:
I'm making the assumption that your toolchain.py file is the script you would like to run, for which you need the requests module.
Step 1: Activate your virtual environment (you have possibly already done this)
Before installing a new module using pip install <module>, you want to activate your virtual environment, because you want to install it in there.
You can do this by doing:
In linux: source <your-venv-path>/bin/activate
In windows: <your-venv-path>\Scripts\activate.bat
Some good answers on how to activate a virtual environment can be found for Windows and for Linux.
Step 2: Install the requests module
Now your virtual environment is active, you should be able to install the requests module like this:
pip install requests
Step 3: Run your script
After this, you should be able to run your script with the requests module installed like so:
python toolchain.py
A:
I have tried many ways to solve the issue in the last few days but failed. Finally, an admin in the kivy discord helps me solve the issue.
In my case, maybe I used the command sudo toolchain.py build python kivy. However, sudo is bad, and maybe what caused this issue.
After I clean up the build and reinstall all kivy using toolchain.py build python kivy, I finally solve the issue. Thank you for the help from the admin and kivy community!
| FileNotFoundError: [Errno 2] No such file or directory: b'/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3' ( kivy app ) | Since I got this error when building project in Xcode,
ModuleNotFoundError: No module named 'requests'
and then I'm trying to install the requests module with git command.
python toolchain.py pip install requests
However, I read the logs and I got this FileNotFoundError message. How can I deal with the error?
[INFO ] Using the bundled version for recipe 'host_setuptools3'
[INFO ] Using the bundled version for recipe 'hostopenssl'
[INFO ] Using the bundled version for recipe 'hostpython3'
[INFO ] Global: hostpython located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/python
[INFO ] Global: hostpgen located at /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pgen
[INFO ] Using the bundled version for recipe 'ios'
[INFO ] Using the bundled version for recipe 'kivy'
[INFO ] Using the bundled version for recipe 'libffi'
[INFO ] Include dir added: {arch.arch}/ffi
[INFO ] Using the bundled version for recipe 'openssl'
[INFO ] Include dir added: {arch.arch}/openssl
[INFO ] Using the bundled version for recipe 'pyobjus'
[INFO ] Using the bundled version for recipe 'python3'
[INFO ] Using the bundled version for recipe 'sdl2'
[INFO ] Include dir added: common/sdl2
[INFO ] Using the bundled version for recipe 'sdl2_image'
[INFO ] Include dir added: common/sdl2_image
[INFO ] Using the bundled version for recipe 'sdl2_mixer'
[INFO ] Include dir added: common/sdl2_mixer
[INFO ] Using the bundled version for recipe 'sdl2_ttf'
[INFO ] Include dir added: common/sdl2_ttf
[INFO ] Executing pip with: ['install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests']
[INFO ] Running Shell: /Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3 ('install', '--isolated', '--prefix', '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3', 'requests') {'_env': {'CC': '/bin/false', 'CXX': '/bin/false', 'PYTHONPATH': '/Users/<myname>/Desktop/kivy/kivy-ios/dist/root/python3/lib/python3.9/site-packages', 'PYTHONOPTIMIZE': '2'}, '_iter': True, '_out_bufsize': 1, '_err_to_out': True}
Traceback (most recent call last):
File "/Users/<myname>/Desktop/kivy/kivy-ios/toolchain.py", line 3, in <module>
main()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1555, in main
ToolchainCL()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1299, in __init__
getattr(self, args.command)()
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1514, in pip
_pip(sys.argv[2:])
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 1186, in _pip
shprint(pip_cmd, *args, _env=pip_env)
File "/Users/<myname>/Desktop/kivy/kivy-ios/kivy_ios/toolchain.py", line 55, in shprint
cmd = command(*args, **kwargs)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 1524, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 780, in __init__
self.process = OProc(self, self.log, cmd, stdin, stdout, stderr,
File "/Users/<myname>/Desktop/kivy/kivy-ios/posEnv/lib/python3.9/site-packages/sh.py", line 2125, in __init__
raise ForkException(fork_exc)
sh.ForkException:
Original exception:
===================
Traceback (most recent call last):
File "/Users/gordonkwok/Desktop/kivy/kivy-ios/<myenv>/lib/python3.9/site-packages/sh.py", line 2080, in __init__
os.execve(cmd[0], cmd, ca["env"])
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/<myname>/Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3'
So I looked the file "/Users//Desktop/kivy/kivy-ios/dist/hostpython3/bin/pip3" and the virtual environment file "/Users//Desktop/kivy/kivy-ios//lib/python3.9/site-packages/sh.py" to see whether they are existed. And both of them are really existed! I'm so confuse with this error. So please help me out here! It is the finally step for me to run my first app soon! Thanks!
| [
"Let's tackle this in steps:\nI'm making the assumption that your toolchain.py file is the script you would like to run, for which you need the requests module.\nStep 1: Activate your virtual environment (you have possibly already done this)\nBefore installing a new module using pip install <module>, you want to activate your virtual environment, because you want to install it in there.\nYou can do this by doing:\n\nIn linux: source <your-venv-path>/bin/activate\nIn windows: <your-venv-path>\\Scripts\\activate.bat\n\nSome good answers on how to activate a virtual environment can be found for Windows and for Linux.\nStep 2: Install the requests module\nNow your virtual environment is active, you should be able to install the requests module like this:\npip install requests\nStep 3: Run your script\nAfter this, you should be able to run your script with the requests module installed like so:\npython toolchain.py\n",
"I have tried many ways to solve the issue in the last few days but failed. Finally, an admin in the kivy discord helps me solve the issue.\nIn my case, maybe I used the command sudo toolchain.py build python kivy. However, sudo is bad, and maybe what caused this issue.\nAfter I clean up the build and reinstall all kivy using toolchain.py build python kivy, I finally solve the issue. Thank you for the help from the admin and kivy community!\n"
] | [
2,
1
] | [] | [] | [
"kivy",
"python",
"xcode"
] | stackoverflow_0074611396_kivy_python_xcode.txt |
Q:
Flutter localization without context
I am trying to localize my app in flutter. I created the needed string.arb files for the supported languages.
Why does AppLocalizations.of(context) need a context?
I simply want to access the named strings in the files/locales files/classes.
At some point in the app I build a List and fill it later via overriding some fields with a separate class.
However, this class has no context but I want to use localized strings in it.
Can I write a method which gets me the Localization of whatever String I put in?
A:
If you would prefer to not use a package then here is a solution that worked for me. Now the most common implementation of AppLocalizations I've seen usually has these two lines:
//.........
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
//.........
The implementation of the delegate would look something like this:
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const _AppLocalizationsDelegate();
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations localizations = new AppLocalizations(locale);
await localizations.load();
return localizations;
}
//... the rest omitted for brevity
}
Notice the load method on the delegate returns a Future<AppLocalizations>. The load method is usually called once from main and never again so you can take advantage of that by adding a static instance of AppLocalizations to the delegate. So now your delegate would look like this:
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const _AppLocalizationsDelegate();
static AppLocalizations instance;
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations localizations = new AppLocalizations(locale);
await localizations.load();
instance = localizations; // set the static instance here
return localizations;
}
//... the rest omitted for brevity
}
Then on your AppLocalizations class you would now have:
//.........
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
static AppLocalizations get instance => _AppLocalizationsDelegate.instance; // add this
//.........
Now in your translate helper method you could have:
String tr(String key) {
return AppLocalizations.instance.translate(key);
}
No context needed.
A:
We can resolve this by using get_it easily, we can use the string anywhere after this setup.
Install this to your vscode Flutter Intl VSCode Extension
setup pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations: # Add this line
sdk: flutter # Add this line
intl: ^0.17.0 # Add this line
get_it: ^7.2.0 # Add this line
flutter:
uses-material-design: true
generate: true # Add this line
flutter_intl: # Add this line
enabled: true # Add this line
class_name: I10n # Add this line
main_locale: en # Add this line
arb_dir: lib/core/localization/l10n # Add this line
output_dir: lib/core/localization/generated # Add this line
Setup main.dart
import 'package:component_gallery/core/localization/generated/l10n.dart';
import 'package:component_gallery/locator.dart';
import 'package:component_gallery/ui/pages/home.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
setupLocator();
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
I10n.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: I10n.delegate.supportedLocales,
localeResolutionCallback: (deviceLocale, supportedLocales) {
if (supportedLocales
.map((e) => e.languageCode)
.contains(deviceLocale?.languageCode)) {
return deviceLocale;
} else {
return const Locale('en', '');
}
},
home: HomePage(),
);
}
}
setup locator.dart
import 'package:component_gallery/core/services/navigation_service.dart';
import 'package:get_it/get_it.dart';
GetIt locator = GetIt.instance;
void setupLocator() {
locator.registerLazySingleton(() => I10n());
}
Use it with Get_it without context as
final I10n _i10n = locator<I10n>();
class MessageComponent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
_i10n.sample,
textAlign: TextAlign.center,
);
}
}
A:
There is a library called easy_localization that does localization without context, you can simply use that one. Library also provides more convenient approach of writing less code and still localizing all the segments of the app. An example main class:
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]).then((_) {
runApp(EasyLocalization(
child: MyApp(),
useOnlyLangCode: true,
startLocale: Locale('nl'),
fallbackLocale: Locale('nl'),
supportedLocales: [
Locale('nl'),
Locale('en'),
],
path: 'lang',
));
});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(),
supportedLocales: EasyLocalization.of(context).supportedLocales,
locale: EasyLocalization.of(context).locale,
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
EasyLocalization.of(context).delegate,
],
localeResolutionCallback: (locale, supportedLocales) {
if (locale == null) {
EasyLocalization.of(context).locale = supportedLocales.first;
Intl.defaultLocale = '${supportedLocales.first}';
return supportedLocales.first;
}
for (Locale supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode) {
EasyLocalization.of(context).locale = supportedLocale;
Intl.defaultLocale = '$supportedLocale';
return supportedLocale;
}
}
EasyLocalization.of(context).locale = supportedLocales.first;
Intl.defaultLocale = '${supportedLocales.first}';
return supportedLocales.first;
},
);
}
}
Also don't forget to put localization path to your pubspec.yamal file!
After all of this is done, you can simply just use it in a Text widget like this:
Text(tr('someJsonKey'),),
A:
If you know the desired Locale then you could use:
final locale = Locale('en');
AppLocalizations t = await AppLocalizations.delegate.load(locale);
println(t.someTranslationKey);
Instead of hardcoding Locale('en') you could implement some kind of resolver to find out what the desired locale is. The supported languages are AppLocalizations.supportedLocales.
A:
Latest: the current Flutter Intl plugin makes this approach obsolete, at least if you use a supported IDE. You have a context-free alternative there:
S.current.translationKey
Previous: Starting from the suggestions of Stuck, this is the final solution I found. It isn't as cheap as the simple lookup with the context, so only use it if really necessary and make sure you call it once and use as many times as possible. But this approach works even if you have no context at all, for instance, you are in a background service or any other program part without UI.
Future<AppLocalizations> loadLocalization() async {
final parts = Intl.getCurrentLocale().split('_');
final locale = Locale(parts.first, parts.last);
return await AppLocalizations.delegate.load(locale);
}
Using it is just the same as usual:
final t = await loadLocalization();
print(t.translationKey);
Update: the singleton I suggested in the comments could look like:
class Localization {
static final Localization _instance = Localization._internal();
AppLocalizations? _current;
Localization._internal();
factory Localization() => _instance;
Future<AppLocalizations> loadCurrent() async {
if (_current == null) {
final parts = Intl.getCurrentLocale().split('_');
final locale = Locale(parts.first, parts.last);
_current = await AppLocalizations.delegate.load(locale);
}
return Future.value(_current);
}
void invalidate() {
_current = null;
}
}
and used like:
final t = await Localization().loadCurrent();
To keep track of language changes, call this from your main build():
PlatformDispatcher.instance.onLocaleChanged = () => Localization().invalidate();
A:
In my case, I am using the Minimal internationalization version.
Adapting chinloyal's answer to the Minimal internationalization version.
Apply chinloyal's solution but with this difference:
From this:
@override
Future<AppLocalizations> load(Locale locale) {
return SynchronousFuture<AppLocalizations>(AppLocalizations(locale));
}
To this:
@override
Future<AppLocalizations> load(Locale locale) async {
var localizations =
await SynchronousFuture<AppLocalizations>(AppLocalizations(locale));
instance = localizations; // set the static instance here
return localizations;
}
A:
My 2 cents into it, just not to loose the solution :)
I totally get why Flutter localization solutions needs BuildContext - makes total sense. But, if I explicitly don't want runtime language switch, and happy with the app restart?
That's the solution I came up with that seems to work pretty well.
Assuming you've followed Flutter's official localization steps, create a global variable that will be used to accessing the AppLocalizations class.
i18n.dart:
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
AppLocalizations get tr => _tr!; // helper function to avoid typing '!' all the time
AppLocalizations? _tr; // global variable
class AppTranslations {
static init(BuildContext context) {
_tr = AppLocalizations.of(context);
}
}
Now, somewhere in your main wrapper (the one below MaterialApp) call to set the localizations for the currently selected locale:
AppTranslations.init(context);
It could be initState() or even build() of the main widget (it's safe to call this multiple times, obviously).
Now you can simply call:
import 'package:my_app/i18n.dart'
...
Text(tr.welcome_text)
// or
print(tr.welcome_text);
...
A:
I was already using easy_localization package, so this found me very easy.
Trick I used to get app language without context as below
en-US.json
{
"app_locale":"en"
}
ar-SA.json
{
"app_locale":"ar"
}
Used it like a way in utility/extension function
LocaleKeys.app_locale.tr() //will return 'en' for English, 'ar' for Arabic
A:
The best approach is using Flutter Intl (Flutter i18n plugins) as it is built by Flutter developers. It has a method to use without context like the following (Code example from the Visual Studio Marketplace details page):
Widget build(BuildContext context) {
return Column(children: [
Text(
S.of(context).pageHomeConfirm,
),
Text(
S.current.pageHomeConfirm,// If you don't have `context` to pass
),
]);
}
More details on official plugin page and Visual Studio Marketplace details page
| Flutter localization without context | I am trying to localize my app in flutter. I created the needed string.arb files for the supported languages.
Why does AppLocalizations.of(context) need a context?
I simply want to access the named strings in the files/locales files/classes.
At some point in the app I build a List and fill it later via overriding some fields with a separate class.
However, this class has no context but I want to use localized strings in it.
Can I write a method which gets me the Localization of whatever String I put in?
| [
"If you would prefer to not use a package then here is a solution that worked for me. Now the most common implementation of AppLocalizations I've seen usually has these two lines:\n//.........\nstatic const LocalizationsDelegate<AppLocalizations> delegate =\n _AppLocalizationsDelegate();\n\nstatic AppLocalizations of(BuildContext context) {\n return Localizations.of<AppLocalizations>(context, AppLocalizations);\n}\n//.........\n\nThe implementation of the delegate would look something like this:\nclass _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {\n const _AppLocalizationsDelegate();\n\n @override\n Future<AppLocalizations> load(Locale locale) async {\n AppLocalizations localizations = new AppLocalizations(locale);\n await localizations.load();\n\n return localizations;\n }\n\n //... the rest omitted for brevity\n}\n\nNotice the load method on the delegate returns a Future<AppLocalizations>. The load method is usually called once from main and never again so you can take advantage of that by adding a static instance of AppLocalizations to the delegate. So now your delegate would look like this:\nclass _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {\n const _AppLocalizationsDelegate();\n\n static AppLocalizations instance;\n\n @override\n Future<AppLocalizations> load(Locale locale) async {\n AppLocalizations localizations = new AppLocalizations(locale);\n await localizations.load();\n\n instance = localizations; // set the static instance here\n\n return localizations;\n }\n\n //... the rest omitted for brevity\n}\n\nThen on your AppLocalizations class you would now have:\n//.........\nstatic const LocalizationsDelegate<AppLocalizations> delegate =\n _AppLocalizationsDelegate();\n\nstatic AppLocalizations of(BuildContext context) {\n return Localizations.of<AppLocalizations>(context, AppLocalizations);\n}\n\nstatic AppLocalizations get instance => _AppLocalizationsDelegate.instance; // add this\n//.........\n\n\nNow in your translate helper method you could have:\nString tr(String key) {\n return AppLocalizations.instance.translate(key);\n}\n\nNo context needed.\n",
"We can resolve this by using get_it easily, we can use the string anywhere after this setup.\n\nInstall this to your vscode Flutter Intl VSCode Extension\n\nsetup pubspec.yaml\ndependencies:\nflutter:\n sdk: flutter\nflutter_localizations: # Add this line\n sdk: flutter # Add this line\nintl: ^0.17.0 # Add this line\nget_it: ^7.2.0 # Add this line\n\n\nflutter:\n uses-material-design: true\n generate: true # Add this line\n\n\nflutter_intl: # Add this line\n enabled: true # Add this line\n class_name: I10n # Add this line\n main_locale: en # Add this line\n arb_dir: lib/core/localization/l10n # Add this line\n output_dir: lib/core/localization/generated # Add this line\n\n\nSetup main.dart\nimport 'package:component_gallery/core/localization/generated/l10n.dart';\nimport 'package:component_gallery/locator.dart';\nimport 'package:component_gallery/ui/pages/home.dart';\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_localizations/flutter_localizations.dart';\n\nvoid main() {\n setupLocator();\n runApp(App());\n}\n\nclass App extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n localizationsDelegates: [\n I10n.delegate,\n GlobalMaterialLocalizations.delegate,\n GlobalWidgetsLocalizations.delegate,\n GlobalCupertinoLocalizations.delegate,\n ],\n supportedLocales: I10n.delegate.supportedLocales,\n localeResolutionCallback: (deviceLocale, supportedLocales) {\n if (supportedLocales\n .map((e) => e.languageCode)\n .contains(deviceLocale?.languageCode)) {\n return deviceLocale;\n } else {\n return const Locale('en', '');\n }\n },\n home: HomePage(),\n );\n }\n}\n\n\nsetup locator.dart\nimport 'package:component_gallery/core/services/navigation_service.dart';\nimport 'package:get_it/get_it.dart';\n\nGetIt locator = GetIt.instance;\n\nvoid setupLocator() {\n locator.registerLazySingleton(() => I10n());\n}\n\n\n\nUse it with Get_it without context as\nfinal I10n _i10n = locator<I10n>();\nclass MessageComponent extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Text(\n _i10n.sample,\n textAlign: TextAlign.center,\n );\n }\n}\n\n\n\n\n",
"There is a library called easy_localization that does localization without context, you can simply use that one. Library also provides more convenient approach of writing less code and still localizing all the segments of the app. An example main class: \nvoid main() {\n WidgetsFlutterBinding.ensureInitialized();\n SystemChrome.setPreferredOrientations([\n DeviceOrientation.portraitUp,\n ]).then((_) {\n runApp(EasyLocalization(\n child: MyApp(),\n useOnlyLangCode: true,\n startLocale: Locale('nl'),\n fallbackLocale: Locale('nl'),\n supportedLocales: [\n Locale('nl'),\n Locale('en'),\n ],\n path: 'lang',\n ));\n });\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: SplashScreen(),\n supportedLocales: EasyLocalization.of(context).supportedLocales,\n locale: EasyLocalization.of(context).locale,\n localizationsDelegates: [\n GlobalMaterialLocalizations.delegate,\n GlobalWidgetsLocalizations.delegate,\n GlobalCupertinoLocalizations.delegate,\n DefaultCupertinoLocalizations.delegate,\n EasyLocalization.of(context).delegate,\n ],\n localeResolutionCallback: (locale, supportedLocales) {\n if (locale == null) {\n EasyLocalization.of(context).locale = supportedLocales.first;\n Intl.defaultLocale = '${supportedLocales.first}';\n return supportedLocales.first;\n }\n\n for (Locale supportedLocale in supportedLocales) {\n if (supportedLocale.languageCode == locale.languageCode) {\n EasyLocalization.of(context).locale = supportedLocale;\n Intl.defaultLocale = '$supportedLocale';\n return supportedLocale;\n }\n }\n\n EasyLocalization.of(context).locale = supportedLocales.first;\n Intl.defaultLocale = '${supportedLocales.first}';\n return supportedLocales.first;\n },\n );\n }\n}\n\nAlso don't forget to put localization path to your pubspec.yamal file!\nAfter all of this is done, you can simply just use it in a Text widget like this: \nText(tr('someJsonKey'),),\n\n",
"If you know the desired Locale then you could use:\nfinal locale = Locale('en');\nAppLocalizations t = await AppLocalizations.delegate.load(locale);\nprintln(t.someTranslationKey);\n\nInstead of hardcoding Locale('en') you could implement some kind of resolver to find out what the desired locale is. The supported languages are AppLocalizations.supportedLocales.\n",
"Latest: the current Flutter Intl plugin makes this approach obsolete, at least if you use a supported IDE. You have a context-free alternative there:\nS.current.translationKey\n\n\nPrevious: Starting from the suggestions of Stuck, this is the final solution I found. It isn't as cheap as the simple lookup with the context, so only use it if really necessary and make sure you call it once and use as many times as possible. But this approach works even if you have no context at all, for instance, you are in a background service or any other program part without UI.\nFuture<AppLocalizations> loadLocalization() async {\n final parts = Intl.getCurrentLocale().split('_');\n final locale = Locale(parts.first, parts.last);\n return await AppLocalizations.delegate.load(locale);\n}\n\nUsing it is just the same as usual:\nfinal t = await loadLocalization();\nprint(t.translationKey);\n\nUpdate: the singleton I suggested in the comments could look like:\nclass Localization {\n static final Localization _instance = Localization._internal();\n AppLocalizations? _current;\n\n Localization._internal();\n\n factory Localization() => _instance;\n\n Future<AppLocalizations> loadCurrent() async {\n if (_current == null) {\n final parts = Intl.getCurrentLocale().split('_');\n final locale = Locale(parts.first, parts.last);\n _current = await AppLocalizations.delegate.load(locale);\n }\n return Future.value(_current);\n }\n\n void invalidate() {\n _current = null;\n }\n}\n\nand used like:\nfinal t = await Localization().loadCurrent();\n\nTo keep track of language changes, call this from your main build():\nPlatformDispatcher.instance.onLocaleChanged = () => Localization().invalidate();\n\n",
"In my case, I am using the Minimal internationalization version.\nAdapting chinloyal's answer to the Minimal internationalization version.\nApply chinloyal's solution but with this difference:\nFrom this:\n @override\n Future<AppLocalizations> load(Locale locale) {\n return SynchronousFuture<AppLocalizations>(AppLocalizations(locale));\n }\n\nTo this:\n @override\n Future<AppLocalizations> load(Locale locale) async {\n var localizations =\n await SynchronousFuture<AppLocalizations>(AppLocalizations(locale));\n\n instance = localizations; // set the static instance here\n\n return localizations;\n }\n\n",
"My 2 cents into it, just not to loose the solution :)\nI totally get why Flutter localization solutions needs BuildContext - makes total sense. But, if I explicitly don't want runtime language switch, and happy with the app restart?\nThat's the solution I came up with that seems to work pretty well.\nAssuming you've followed Flutter's official localization steps, create a global variable that will be used to accessing the AppLocalizations class.\ni18n.dart:\nimport 'package:flutter/material.dart';\nimport 'package:flutter_gen/gen_l10n/app_localizations.dart';\n\nAppLocalizations get tr => _tr!; // helper function to avoid typing '!' all the time\nAppLocalizations? _tr; // global variable \n\nclass AppTranslations {\n static init(BuildContext context) {\n _tr = AppLocalizations.of(context);\n }\n}\n\nNow, somewhere in your main wrapper (the one below MaterialApp) call to set the localizations for the currently selected locale:\n AppTranslations.init(context);\n\nIt could be initState() or even build() of the main widget (it's safe to call this multiple times, obviously).\nNow you can simply call:\nimport 'package:my_app/i18n.dart'\n\n...\n Text(tr.welcome_text)\n\n // or\n\n print(tr.welcome_text);\n...\n\n",
"I was already using easy_localization package, so this found me very easy.\nTrick I used to get app language without context as below\nen-US.json\n{\n \"app_locale\":\"en\"\n}\n\nar-SA.json\n{\n \"app_locale\":\"ar\"\n}\n\nUsed it like a way in utility/extension function\nLocaleKeys.app_locale.tr() //will return 'en' for English, 'ar' for Arabic\n\n",
"The best approach is using Flutter Intl (Flutter i18n plugins) as it is built by Flutter developers. It has a method to use without context like the following (Code example from the Visual Studio Marketplace details page):\nWidget build(BuildContext context) {\n return Column(children: [\n Text(\n S.of(context).pageHomeConfirm,\n ),\n Text(\n S.current.pageHomeConfirm,// If you don't have `context` to pass\n ),\n ]);\n}\n\nMore details on official plugin page and Visual Studio Marketplace details page\n"
] | [
13,
10,
8,
5,
3,
1,
1,
1,
0
] | [] | [] | [
"flutter",
"localization"
] | stackoverflow_0061563074_flutter_localization.txt |
Q:
The following assertion was thrown while applying parent data.: Incorrect use of ParentDataWidget. in flutter Flutter
This is my code
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hexated/Refactored/widgets/facultyHome.dart';
import 'package:hexated/Refactored/widgets/headings.dart';
import 'package:hexated/Refactored/widgets/onlineDot.dart';
class facultyProfile extends StatefulWidget {
const facultyProfile({Key? key}) : super(key: key);
@override
State<facultyProfile> createState() => _facultyProfileState();
}
class _facultyProfileState extends State<facultyProfile> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: const Color(0xFF000000),
appBar: AppBar(
backgroundColor: const Color(0xFF2B2E3F),
elevation: 0,
),
body: Column(
children: [
Container(
height: height * 0.312,
width: width * 1,
color: Color(0xFF2B2E3F),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
avatar(
radius: 50,
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Abraham Johnson",
style: TextStyle(
color: Colors.white,
fontSize: 19,
fontWeight: FontWeight.bold),
),
const SizedBox(
width: 2,
),
onlineDot(
statusColor: const Color(0xFF42FF00),
w: 11,
h: 11,
),
],
),
const Text(
"Director",
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w300,
),
),
],
),
),
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const [
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: Icon(
Icons.call,
color: Color(0xFFB3B4B7),
size: 33,
),
),
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: Icon(
Icons.mail,
color: Color(0xFFB3B4B7),
size: 33,
),
),
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: FaIcon(
FontAwesomeIcons.solidBell,
color: Color(0xFFB3B4B7),
size: 33,
)),
],
),
const SizedBox(
height: 20,
),
const Divider(
color: Color(0xFF6A6C70),
indent: 20,
endIndent: 20,
),
const SizedBox(
height: 15,
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: headings(headingText: "Contact")),
const SizedBox(
height: 15,
),
const Text(
"Mobile",
style: TextStyle(color: Colors.white),
),
],
),
);
}
}
The ParentDataWidget Positioned(right: 5.0, bottom: 2.0) wants to apply ParentData of type StackParentData to a RenderObject, which has been set up to accept ParentData of incompatible type FlexParentData.
Usually, this means that the Positioned widget has the wrong ancestor RenderObjectWidget. Typically, Positioned widgets are placed directly inside Stack widgets.
The offending Positioned is currently placed inside a Row widget.
A:
It looks like you are using the Positioned widget incorrectly in your code. The Positioned widget is a child of the Stack widget and it should be used to position children relative to the top, right, bottom, or left edge of the Stack.
For example, if you want to position a child widget at the bottom right corner of the Stack, you can use the Positioned widget like this:
Stack(
children: [
Positioned(
right: 5.0,
bottom: 2.0,
child: Container(
// Your child widget here
),
),
],
)
If you want to use the Positioned widget outside of the Stack, you can use the Positioned.fill constructor to make it fill the entire screen.
Positioned.fill(
child: Container(
// Your child widget here
),
)
| The following assertion was thrown while applying parent data.: Incorrect use of ParentDataWidget. in flutter Flutter | This is my code
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hexated/Refactored/widgets/facultyHome.dart';
import 'package:hexated/Refactored/widgets/headings.dart';
import 'package:hexated/Refactored/widgets/onlineDot.dart';
class facultyProfile extends StatefulWidget {
const facultyProfile({Key? key}) : super(key: key);
@override
State<facultyProfile> createState() => _facultyProfileState();
}
class _facultyProfileState extends State<facultyProfile> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: const Color(0xFF000000),
appBar: AppBar(
backgroundColor: const Color(0xFF2B2E3F),
elevation: 0,
),
body: Column(
children: [
Container(
height: height * 0.312,
width: width * 1,
color: Color(0xFF2B2E3F),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
avatar(
radius: 50,
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Abraham Johnson",
style: TextStyle(
color: Colors.white,
fontSize: 19,
fontWeight: FontWeight.bold),
),
const SizedBox(
width: 2,
),
onlineDot(
statusColor: const Color(0xFF42FF00),
w: 11,
h: 11,
),
],
),
const Text(
"Director",
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w300,
),
),
],
),
),
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const [
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: Icon(
Icons.call,
color: Color(0xFFB3B4B7),
size: 33,
),
),
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: Icon(
Icons.mail,
color: Color(0xFFB3B4B7),
size: 33,
),
),
CircleAvatar(
backgroundColor: Color(0xFF282B35),
radius: 30,
child: FaIcon(
FontAwesomeIcons.solidBell,
color: Color(0xFFB3B4B7),
size: 33,
)),
],
),
const SizedBox(
height: 20,
),
const Divider(
color: Color(0xFF6A6C70),
indent: 20,
endIndent: 20,
),
const SizedBox(
height: 15,
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: headings(headingText: "Contact")),
const SizedBox(
height: 15,
),
const Text(
"Mobile",
style: TextStyle(color: Colors.white),
),
],
),
);
}
}
The ParentDataWidget Positioned(right: 5.0, bottom: 2.0) wants to apply ParentData of type StackParentData to a RenderObject, which has been set up to accept ParentData of incompatible type FlexParentData.
Usually, this means that the Positioned widget has the wrong ancestor RenderObjectWidget. Typically, Positioned widgets are placed directly inside Stack widgets.
The offending Positioned is currently placed inside a Row widget.
| [
"It looks like you are using the Positioned widget incorrectly in your code. The Positioned widget is a child of the Stack widget and it should be used to position children relative to the top, right, bottom, or left edge of the Stack.\nFor example, if you want to position a child widget at the bottom right corner of the Stack, you can use the Positioned widget like this:\nStack(\n children: [\n Positioned(\n right: 5.0,\n bottom: 2.0,\n child: Container(\n // Your child widget here\n ),\n ),\n ],\n)\n\nIf you want to use the Positioned widget outside of the Stack, you can use the Positioned.fill constructor to make it fill the entire screen.\nPositioned.fill(\n child: Container(\n // Your child widget here\n ),\n)\n\n"
] | [
0
] | [] | [] | [
"flutter"
] | stackoverflow_0074675685_flutter.txt |
Q:
Quickfix list, how to add and remove entries
In vim I ususally use the quickfix list as a type of todo list to fix errors or to refactor code. But I have a few problems in my workflow:
If I have to jump forward with :cn multiple times to compare others parts of the code, finding the last edited entry with :cp is difficult. :cw helps, but on bigger lists, it gets difficult, too. Removing fixed entries would be helpful.
On refactoring I encounter sometimes pieces of code I want to return later. Using global marks is ok, but adding the current position to the quickfix list would be more helpful.
So I hoped to find a simple command with :help quicktext to add a position to the quickfix list or to remove an already fixed entry. But all I could find is :cbuffer or :caddb. But on editing the buffer after :cw I get a message, it is not modifiable. The help text offers the following solution (but I do not really want to write temporary files):
Note: Making changes in the quickfix window has no effect on the list of
errors. 'modifiable' is off to avoid making changes. If you delete or insert
lines anyway, the relation between the text and the error number is messed up.
If you really want to do this, you could write the contents of the quickfix
window to a file and use ":cfile" to have it parsed and used as the new error
list.
And maybe with :cad one could add the current line? Or has anyone an alternative workflow in mind?
A:
Update: New official vim plugin cfilter
Since 21.8.2018 (patch: 8.1.0311) the plugin cfilter is distributed in $VIMRUNTIME itself. It is documented under :h cfilter-plugin.
Load plugin cfilter when needed or load it always in your vimrc
:packadd cfilter
Filter quickfix list with
:Cfilter DPUST
A:
I found your question while looking particularly for the ability to remove items from the quickfix list. I'm not super good at vimscript, so there's probably a more elegant solution, but here's what I came up with.
This overrides dd in the quickfix list (which is pretty much useless anyway, since modifiable is off) to remove the current line (the current line of the cursor, not the current quickfix item) from the quickfix list.
I couldn't figure out how to programmatically determine the current quickfix item, which is how I settled on using dd, to make it more obvious that it applies to the line of the cursor.
I hope you might find this useful.
" When using `dd` in the quickfix list, remove the item from the quickfix list.
function! RemoveQFItem()
let curqfidx = line('.') - 1
let qfall = getqflist()
call remove(qfall, curqfidx)
call setqflist(qfall, 'r')
execute curqfidx + 1 . "cfirst"
:copen
endfunction
:command! RemoveQFItem :call RemoveQFItem()
" Use map <buffer> to only map dd in the quickfix window. Requires +localmap
autocmd FileType qf map <buffer> dd :RemoveQFItem<cr>
UPDATE: I've fixed a few issues I've found with the above function.
A:
Adding and removing entries to and from the quickfix list is usually done with :help setqflist() and :help getqflist().
You also have :help :caddexpr, which contains an example that looks a lot like what you are trying to do, but there's unfortunately no symmetrical :cremoveexpr.
Since we are at it, my plugin vim-qf lets you filter, save, modify, combine, and restore quickfix lists so it may be useful for you. Adding/removing arbitrary items from a qf/loc list sounds like a possible feature by the wayβ¦
A:
Here's a shorter way of achieving the same thing without having to use a plugin or define a function...
Just pop this into ftplugin/qf.vim. For Neovim, put this file at ~/.config/nvim/after/ftplugin/qf.vim.
This syntax adds a dd keybinding to the quickfix file type only. This removes the current line from the list.
For example, use :cope to open a quickfix buffer and try dd there.
nnoremap <buffer> <silent> dd
\ <Cmd>call setqflist(filter(getqflist(), {idx -> idx != line('.') - 1}), 'r') <Bar> cc<CR>
Note: I believe the <Cmd> map is only available in Neovim, In which case you'd just remove that and add a : if you're in regular vim.
A:
:set modifiable or :set ma makes the buffer modifiable so you can dd lines out of the quickfix list.
A:
Vimscript has a python-like way to select array ranges, so you can also select the current quickfix list using [n:n] as the index.
:call setqflist(getqflist()[1:])
...will remove the first item from the list.
:call setqflist(getqflist()[:0])
...will remove the last.
You can also concat arrays using + so...
:call setqflist(getqflist()[1:] + getqflist()[:0])
...works as well!
A:
The solution I'm using is below. I don't like remapping 'dd', since '.' won't repeat the command afterwards. Plus, other ways of modifying the list won't work as expected, like for instance, ':g/{pattern}/d'. The solution below simply allows normal vim modification to the list, while keeping the locations updated. Lastly, in the solution below, I haven't mapped the function 'AddLocationToQuickfixList' to anything, since key mappings are highly personal. You can map it to whatever you like. When it's called, it will add your current location to the quickfix list.
function! AddLocationToQuickfixList()
let l:current_location = {'pattern': '', 'valid': 1, 'vcol': 0, 'nr': 0, 'module': '', 'type': ''}
let l:current_location['bufnr'] = bufnr('%')
let l:current_location['lnum'] = line('.')
let l:current_location['end_lnum'] = line('.')
let l:current_location['col'] = 1
let l:current_location['end_col'] = len(getline('.')) + 1
let l:current_location['text'] = trim(getline('.'))
let l:qflist = getqflist()
if index(l:qflist, l:current_location) == -1
copen
call add(l:qflist, l:current_location)
call setqflist(l:qflist, 'r')
endif
endfunction
function! WindowIsList()
if WindowIsLocationList() || WindowIsQuickfixList()
return 1
endif
return 0
endfunction
function! WindowIsLocationList()
let l:qfvar = getwininfo(win_getid())[0]['quickfix']
let l:llvar = getwininfo(win_getid())[0]['loclist']
if l:llvar == 1 && l:qfvar == 1
return 1
endif
return 0
endfunction
function! WindowIsQuickfixList()
let l:qfvar = getwininfo(win_getid())[0]['quickfix']
let l:llvar = getwininfo(win_getid())[0]['loclist']
if l:llvar == 0 && l:qfvar == 1
return 1
endif
return 0
endfunction
function! UpdateList()
"Determine whether or not the current list is a location list or quickfix list.
" In the event it's neither, return.
if WindowIsLocationList()
let l:list_type = "location"
elseif WindowIsQuickfixList()
let l:list_type = "quickfix"
else
return
endif
"Store the line number of the cursor.
" The list will have to be reloaded, which moves the cursor to the top.
" This will be used to restore its location.
let l:iniline = line('.')
"Get the current contents of the list.
" Note that this will include any deleted lines.
" When a line is deleted from a list, only the window text is updated by default.
if l:list_type == "location"
let l:old_list = getloclist(0)
elseif l:list_type == "quickfix"
let l:old_list = getqflist()
endif
"Get a list of all the lines visible in the list's window.
" Note that this list will NOT include any deleted lines.
" This will be used to filter the list contents.
let l:window_text = getline(1, '$')
"Create an empty list to populate with list items.
" Any item in the old_list that gets to stay will be added to this list.
let l:new_list = []
"Loop through the old_list.
for l:list_item in l:old_list
"Using the list_item, produce its corresponding display text (what the user sees in the list's window).
let l:buffer_name = expand("#" .. l:list_item['bufnr'])
if l:list_item['end_lnum'] == l:list_item['lnum']
let l:line_numbers = l:list_item['lnum']
else
let l:line_numbers = l:list_item['lnum'] .. "-" .. l:list_item['end_lnum']
endif
let l:column_numbers = l:list_item['col'] .. "-" .. l:list_item['end_col']
let l:preview_text = trim(l:list_item['text'])
let l:list_item_display_text = l:buffer_name .. "|" .. l:line_numbers .. " col " .. l:column_numbers .. "| " .. l:preview_text
"If the list item's display text is found in the current window text (ie, it has not been deleted by the user), add the list_item to new_list.
if index(l:window_text, l:list_item_display_text) != -1
call add(l:new_list, l:list_item)
endif
endfor
"Update the contents of the list.
if l:list_type == "location"
call setloclist(0, l:new_list, 'r')
elseif l:list_type == "quickfix"
call setqflist(l:new_list, 'r')
endif
"Restore the cursor's line number.
exe "exe " .. l:iniline
"Make sure the list is modifiable.
set modifiable
endfunction
autocmd BufWinEnter * if WindowIsList() | set modifiable | endif
autocmd TextChanged * if WindowIsList() | call UpdateList() | endif
EDIT: I added the BufWinEnter autocmd to handle setting the first instance of a list modifiable, and I removed 1 unnecessary line of code from the 'UpdateList' function.
A:
I add some features on accepted answer that supporting count operation and visual operation.
" When using `dd` in the quickfix list, remove the item from the quickfix list.
function! RemoveQFItem(mode) range abort
let l:qf_list = getqflist()
" distinguish mode for getting delete index and delete count
if a:mode == 'v'
let l:del_qf_idx = getpos("'<")[1] - 1
let l:del_ct = getpos("'>")[1] - l:del_qf_idx
else
let l:del_qf_idx = line('.') - 1
let l:del_ct = v:count > 1 ? v:count : 1
endif
" delete lines and update quickfix
for item in range(l:del_ct)
call remove(l:qf_list, l:del_qf_idx)
endfor
call setqflist(l:qf_list, 'r')
if len(l:qf_list) > 0
execute l:del_qf_idx + 1 . 'cfirst'
copen
else
cclose
endif
endfunction
autocmd FileType qf nmap <buffer> dd :call RemoveQFItem('n')<cr>
autocmd FileType qf vmap <buffer> dd :call RemoveQFItem('v')<cr>
| Quickfix list, how to add and remove entries | In vim I ususally use the quickfix list as a type of todo list to fix errors or to refactor code. But I have a few problems in my workflow:
If I have to jump forward with :cn multiple times to compare others parts of the code, finding the last edited entry with :cp is difficult. :cw helps, but on bigger lists, it gets difficult, too. Removing fixed entries would be helpful.
On refactoring I encounter sometimes pieces of code I want to return later. Using global marks is ok, but adding the current position to the quickfix list would be more helpful.
So I hoped to find a simple command with :help quicktext to add a position to the quickfix list or to remove an already fixed entry. But all I could find is :cbuffer or :caddb. But on editing the buffer after :cw I get a message, it is not modifiable. The help text offers the following solution (but I do not really want to write temporary files):
Note: Making changes in the quickfix window has no effect on the list of
errors. 'modifiable' is off to avoid making changes. If you delete or insert
lines anyway, the relation between the text and the error number is messed up.
If you really want to do this, you could write the contents of the quickfix
window to a file and use ":cfile" to have it parsed and used as the new error
list.
And maybe with :cad one could add the current line? Or has anyone an alternative workflow in mind?
| [
"Update: New official vim plugin cfilter\nSince 21.8.2018 (patch: 8.1.0311) the plugin cfilter is distributed in $VIMRUNTIME itself. It is documented under :h cfilter-plugin.\nLoad plugin cfilter when needed or load it always in your vimrc\n:packadd cfilter\n\nFilter quickfix list with\n:Cfilter DPUST\n\n",
"I found your question while looking particularly for the ability to remove items from the quickfix list. I'm not super good at vimscript, so there's probably a more elegant solution, but here's what I came up with.\nThis overrides dd in the quickfix list (which is pretty much useless anyway, since modifiable is off) to remove the current line (the current line of the cursor, not the current quickfix item) from the quickfix list.\nI couldn't figure out how to programmatically determine the current quickfix item, which is how I settled on using dd, to make it more obvious that it applies to the line of the cursor.\nI hope you might find this useful.\n\" When using `dd` in the quickfix list, remove the item from the quickfix list.\nfunction! RemoveQFItem()\n let curqfidx = line('.') - 1\n let qfall = getqflist()\n call remove(qfall, curqfidx)\n call setqflist(qfall, 'r')\n execute curqfidx + 1 . \"cfirst\"\n :copen\nendfunction\n:command! RemoveQFItem :call RemoveQFItem()\n\" Use map <buffer> to only map dd in the quickfix window. Requires +localmap\nautocmd FileType qf map <buffer> dd :RemoveQFItem<cr>\n\nUPDATE: I've fixed a few issues I've found with the above function.\n",
"Adding and removing entries to and from the quickfix list is usually done with :help setqflist() and :help getqflist().\nYou also have :help :caddexpr, which contains an example that looks a lot like what you are trying to do, but there's unfortunately no symmetrical :cremoveexpr.\n\nSince we are at it, my plugin vim-qf lets you filter, save, modify, combine, and restore quickfix lists so it may be useful for you. Adding/removing arbitrary items from a qf/loc list sounds like a possible feature by the wayβ¦\n",
"Here's a shorter way of achieving the same thing without having to use a plugin or define a function...\nJust pop this into ftplugin/qf.vim. For Neovim, put this file at ~/.config/nvim/after/ftplugin/qf.vim.\nThis syntax adds a dd keybinding to the quickfix file type only. This removes the current line from the list.\nFor example, use :cope to open a quickfix buffer and try dd there.\nnnoremap <buffer> <silent> dd\n \\ <Cmd>call setqflist(filter(getqflist(), {idx -> idx != line('.') - 1}), 'r') <Bar> cc<CR>\n\nNote: I believe the <Cmd> map is only available in Neovim, In which case you'd just remove that and add a : if you're in regular vim.\n",
":set modifiable or :set ma makes the buffer modifiable so you can dd lines out of the quickfix list.\n",
"Vimscript has a python-like way to select array ranges, so you can also select the current quickfix list using [n:n] as the index.\n:call setqflist(getqflist()[1:])\n\n...will remove the first item from the list.\n:call setqflist(getqflist()[:0])\n\n...will remove the last.\nYou can also concat arrays using + so...\n:call setqflist(getqflist()[1:] + getqflist()[:0])\n\n...works as well!\n",
"The solution I'm using is below. I don't like remapping 'dd', since '.' won't repeat the command afterwards. Plus, other ways of modifying the list won't work as expected, like for instance, ':g/{pattern}/d'. The solution below simply allows normal vim modification to the list, while keeping the locations updated. Lastly, in the solution below, I haven't mapped the function 'AddLocationToQuickfixList' to anything, since key mappings are highly personal. You can map it to whatever you like. When it's called, it will add your current location to the quickfix list.\nfunction! AddLocationToQuickfixList()\n let l:current_location = {'pattern': '', 'valid': 1, 'vcol': 0, 'nr': 0, 'module': '', 'type': ''}\n let l:current_location['bufnr'] = bufnr('%')\n let l:current_location['lnum'] = line('.')\n let l:current_location['end_lnum'] = line('.')\n let l:current_location['col'] = 1\n let l:current_location['end_col'] = len(getline('.')) + 1\n let l:current_location['text'] = trim(getline('.'))\n let l:qflist = getqflist()\n if index(l:qflist, l:current_location) == -1\n copen\n call add(l:qflist, l:current_location)\n call setqflist(l:qflist, 'r')\n endif\nendfunction\n\nfunction! WindowIsList()\n if WindowIsLocationList() || WindowIsQuickfixList()\n return 1\n endif\n return 0\nendfunction\n\nfunction! WindowIsLocationList()\n let l:qfvar = getwininfo(win_getid())[0]['quickfix']\n let l:llvar = getwininfo(win_getid())[0]['loclist']\n if l:llvar == 1 && l:qfvar == 1\n return 1\n endif\n return 0\nendfunction\n\nfunction! WindowIsQuickfixList()\n let l:qfvar = getwininfo(win_getid())[0]['quickfix']\n let l:llvar = getwininfo(win_getid())[0]['loclist']\n if l:llvar == 0 && l:qfvar == 1\n return 1\n endif\n return 0\nendfunction\n\nfunction! UpdateList()\n \"Determine whether or not the current list is a location list or quickfix list.\n \" In the event it's neither, return.\n if WindowIsLocationList()\n let l:list_type = \"location\"\n elseif WindowIsQuickfixList()\n let l:list_type = \"quickfix\"\n else\n return\n endif\n \"Store the line number of the cursor.\n \" The list will have to be reloaded, which moves the cursor to the top.\n \" This will be used to restore its location.\n let l:iniline = line('.')\n \"Get the current contents of the list.\n \" Note that this will include any deleted lines.\n \" When a line is deleted from a list, only the window text is updated by default.\n if l:list_type == \"location\"\n let l:old_list = getloclist(0)\n elseif l:list_type == \"quickfix\"\n let l:old_list = getqflist()\n endif\n \"Get a list of all the lines visible in the list's window.\n \" Note that this list will NOT include any deleted lines.\n \" This will be used to filter the list contents.\n let l:window_text = getline(1, '$')\n \"Create an empty list to populate with list items.\n \" Any item in the old_list that gets to stay will be added to this list.\n let l:new_list = []\n \"Loop through the old_list.\n for l:list_item in l:old_list\n \"Using the list_item, produce its corresponding display text (what the user sees in the list's window).\n let l:buffer_name = expand(\"#\" .. l:list_item['bufnr'])\n if l:list_item['end_lnum'] == l:list_item['lnum']\n let l:line_numbers = l:list_item['lnum']\n else\n let l:line_numbers = l:list_item['lnum'] .. \"-\" .. l:list_item['end_lnum']\n endif\n let l:column_numbers = l:list_item['col'] .. \"-\" .. l:list_item['end_col']\n let l:preview_text = trim(l:list_item['text'])\n let l:list_item_display_text = l:buffer_name .. \"|\" .. l:line_numbers .. \" col \" .. l:column_numbers .. \"| \" .. l:preview_text\n \"If the list item's display text is found in the current window text (ie, it has not been deleted by the user), add the list_item to new_list.\n if index(l:window_text, l:list_item_display_text) != -1\n call add(l:new_list, l:list_item)\n endif\n endfor\n \"Update the contents of the list.\n if l:list_type == \"location\"\n call setloclist(0, l:new_list, 'r')\n elseif l:list_type == \"quickfix\"\n call setqflist(l:new_list, 'r')\n endif\n \"Restore the cursor's line number.\n exe \"exe \" .. l:iniline\n \"Make sure the list is modifiable.\n set modifiable\nendfunction\n\nautocmd BufWinEnter * if WindowIsList() | set modifiable | endif\nautocmd TextChanged * if WindowIsList() | call UpdateList() | endif\n\nEDIT: I added the BufWinEnter autocmd to handle setting the first instance of a list modifiable, and I removed 1 unnecessary line of code from the 'UpdateList' function.\n",
"I add some features on accepted answer that supporting count operation and visual operation.\n\" When using `dd` in the quickfix list, remove the item from the quickfix list.\nfunction! RemoveQFItem(mode) range abort\n let l:qf_list = getqflist()\n\n \" distinguish mode for getting delete index and delete count\n if a:mode == 'v'\n let l:del_qf_idx = getpos(\"'<\")[1] - 1\n let l:del_ct = getpos(\"'>\")[1] - l:del_qf_idx\n else\n let l:del_qf_idx = line('.') - 1\n let l:del_ct = v:count > 1 ? v:count : 1\n endif\n\n \" delete lines and update quickfix\n for item in range(l:del_ct)\n call remove(l:qf_list, l:del_qf_idx)\n endfor\n call setqflist(l:qf_list, 'r')\n\n if len(l:qf_list) > 0\n execute l:del_qf_idx + 1 . 'cfirst'\n copen\n else\n cclose\n endif\nendfunction\n\nautocmd FileType qf nmap <buffer> dd :call RemoveQFItem('n')<cr>\nautocmd FileType qf vmap <buffer> dd :call RemoveQFItem('v')<cr>\n\n\n\n"
] | [
16,
15,
8,
7,
2,
0,
0,
0
] | [] | [] | [
"vim"
] | stackoverflow_0042905008_vim.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.