content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
visual studio code CMD.EXE was started with the above path as the current directory. UNC paths are not supported. Defaulting to Windows directory
I am new to javaScript, trying to set up Visual Studio Code.
I have installed NodeJs and Visual Studio Code, with windows Powershell.
In visual studio > terminal if I run npm view command I am getting following error
CMD .EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
npm ERR! Invalid package
Can anyone please take a look at this issue. Is this because of restrictions on corporate systems?
A:
It looks like your project directory (and your profile) is stored on a network fileshare, which is quite common in corporate environments.
You can ask your IT to create a mapped drive with your profile, or you can use the pushd command to create a temporary mapping.
Before opening the project in Visual studio run this from your command line (replace the path with your actual UNC path):
pushd \\corpserver\share$\jdoe\projects\java\...
the command will place you in the newly created temporary drive.
Copy the new temporary path
Open Visual Studio Code and open your project from this temporary path
You should now be able to use terminal and build/run scripts
A:
In my case, I forgot to install NodeJS in WSL. Then, node was taken from Windows.
> which node
/mnt/c/Program Files/nodejs/node.exe
Installing NodeJS on my WSL did the trick
> sudo apt-get install nodejs
|
visual studio code CMD.EXE was started with the above path as the current directory. UNC paths are not supported. Defaulting to Windows directory
|
I am new to javaScript, trying to set up Visual Studio Code.
I have installed NodeJs and Visual Studio Code, with windows Powershell.
In visual studio > terminal if I run npm view command I am getting following error
CMD .EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
npm ERR! Invalid package
Can anyone please take a look at this issue. Is this because of restrictions on corporate systems?
|
[
"It looks like your project directory (and your profile) is stored on a network fileshare, which is quite common in corporate environments.\nYou can ask your IT to create a mapped drive with your profile, or you can use the pushd command to create a temporary mapping.\n\nBefore opening the project in Visual studio run this from your command line (replace the path with your actual UNC path):\npushd \\\\corpserver\\share$\\jdoe\\projects\\java\\... \nthe command will place you in the newly created temporary drive.\n\nCopy the new temporary path\n\nOpen Visual Studio Code and open your project from this temporary path\n\nYou should now be able to use terminal and build/run scripts\n\n\n",
"In my case, I forgot to install NodeJS in WSL. Then, node was taken from Windows.\n> which node\n/mnt/c/Program Files/nodejs/node.exe\n\nInstalling NodeJS on my WSL did the trick\n> sudo apt-get install nodejs\n\n"
] |
[
9,
0
] |
[] |
[] |
[
"npm",
"visual_studio_code"
] |
stackoverflow_0060908563_npm_visual_studio_code.txt
|
Q:
Cakephp 4 save delete auto_increment
I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => '[email protected]',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
A:
It was that the sql file used in the bootstrap didn't have the autoincrement value.
|
Cakephp 4 save delete auto_increment
|
I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => '[email protected]',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
|
[
"It was that the sql file used in the bootstrap didn't have the autoincrement value.\n"
] |
[
0
] |
[] |
[] |
[
"auto_increment",
"cakephp",
"cakephp_4.x",
"phpunit",
"testing"
] |
stackoverflow_0074577474_auto_increment_cakephp_cakephp_4.x_phpunit_testing.txt
|
Q:
Django registration form gives error, when password can not pass validation
I am trying to make user registration with automatic login. When passwords are different or do not pass validation, there is no message from the form. It throws an error:
AttributeError at /accounts/register/
'AnonymousUser' object has no attribute '_meta'
I think the error comes from the login(request, self.object) line. I have tried to fix the problem with overriding the clean() method in the form, but it did not work. I am not sure what to do.
my model:
class AppUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
email = models.EmailField(
unique=True,
blank=False,
null=False,
)
is_staff = models.BooleanField(
default=False,
blank=False,
null=False,
)
USERNAME_FIELD = 'email'
objects = AppUserManager()
my form:
class SignUpForm(auth_forms.UserCreationForm):
class Meta:
model = UserModel
fields = (UserModel.USERNAME_FIELD, 'password1', 'password2',)
field_classes = {
'email': auth_forms.UsernameField,
}
my view:
class SignUpView(views.CreateView):
template_name = 'accounts/user/register-user-page.html'
form_class = SignUpForm
success_url = reverse_lazy('home')
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
login(request, self.object)
return response
A:
You need to override form_valid() instead of post().
from django.http import HttpResponseRedirect
def form_valid(self, form):
user = form.save() #save the user
login(request, user)
return HttpResponseRedirect(self.get_success_url())
|
Django registration form gives error, when password can not pass validation
|
I am trying to make user registration with automatic login. When passwords are different or do not pass validation, there is no message from the form. It throws an error:
AttributeError at /accounts/register/
'AnonymousUser' object has no attribute '_meta'
I think the error comes from the login(request, self.object) line. I have tried to fix the problem with overriding the clean() method in the form, but it did not work. I am not sure what to do.
my model:
class AppUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
email = models.EmailField(
unique=True,
blank=False,
null=False,
)
is_staff = models.BooleanField(
default=False,
blank=False,
null=False,
)
USERNAME_FIELD = 'email'
objects = AppUserManager()
my form:
class SignUpForm(auth_forms.UserCreationForm):
class Meta:
model = UserModel
fields = (UserModel.USERNAME_FIELD, 'password1', 'password2',)
field_classes = {
'email': auth_forms.UsernameField,
}
my view:
class SignUpView(views.CreateView):
template_name = 'accounts/user/register-user-page.html'
form_class = SignUpForm
success_url = reverse_lazy('home')
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
login(request, self.object)
return response
|
[
"You need to override form_valid() instead of post().\nfrom django.http import HttpResponseRedirect\n\ndef form_valid(self, form):\n user = form.save() #save the user\n login(request, user)\n return HttpResponseRedirect(self.get_success_url())\n\n"
] |
[
0
] |
[] |
[] |
[
"authentication",
"django",
"python"
] |
stackoverflow_0074667644_authentication_django_python.txt
|
Q:
Underlying data structure of LinkedList Class implementing collections interface in java is Linear or Doubly?
List<String> list = new LinkedList();
This "list" is created in java. As we know , every class in Collections framework has some underlying data structure. LinkedList in java has Linear LinkedList implementation or Doubly LinkedList implementation as its underlying Data structure?
A:
According to the documentation LinkedList is an implementation of the Doubly-linked list data structure:
All of the operations perform as could be expected for a doubly-linked list.
|
Underlying data structure of LinkedList Class implementing collections interface in java is Linear or Doubly?
|
List<String> list = new LinkedList();
This "list" is created in java. As we know , every class in Collections framework has some underlying data structure. LinkedList in java has Linear LinkedList implementation or Doubly LinkedList implementation as its underlying Data structure?
|
[
"According to the documentation LinkedList is an implementation of the Doubly-linked list data structure:\n\nAll of the operations perform as could be expected for a doubly-linked list.\n\n"
] |
[
0
] |
[] |
[] |
[
"data_structures",
"doubly_linked_list",
"java",
"list",
"singly_linked_list"
] |
stackoverflow_0074668362_data_structures_doubly_linked_list_java_list_singly_linked_list.txt
|
Q:
How do you count the number of negative items in a list using a recursive function?
I have to make a recursive function that counts how many negative values there are in a given list, but I can't figure out what I am supposed to return for each conditional.
def countNegatives(list):
"""Takes in a list of numbers and
returns the number of negative numbers
that are inside the list."""
count = 0
if len(list) == 0:
return 0
else:
if list[0] < 0:
return count + 1
else:
return countNegatives(list[1:])
print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1
A:
When list[0] < 0 your code ignores the rest of the list, yet there could be more negative values there to count.
So in that case don't do:
return count + 1
but:
return 1 + countNegatives(list[1:])
A:
The step you were missing is to add the count to the returned value of the recursive call, so that the returned values of all recursive calls get summed up at the end. Here's one way you could do this:
def countNegatives(list):
#if the list length is zero, we are done
if len(list) == 0:
return 0
# Get the count of this iteration
count = 1 if list[0] < 0 else 0
# sum the count of this iteration with the count of all subsequent iterations
return count + countNegatives(list[1:])
So, for your first example, the actual steps taken by your code would look like:
return 0 + countNegatives([1, -1, 3, -5, 6])
return 0 + countNegatives([-1, 3, -5, 6])
return 1 + countNegatives([3, -5, 6])
return 0 + countNegatives([-5, 6])
return 1 + countNegatives([6])
return 0 + countNegatives([])
return 0
Expanding all the values gives:
return 0 + 0 + 1 + 0 + 1 + 0 + 0
A:
Recursion is a functional heritage and so using it with functional style yields the best results. That means avoiding things like mutation, variable reassignments, and other side effects. We can implement using straightforward mathematical induction -
If the input list is empty, there is nothing to count. Return the empty result, 0
(inductive) the input list has at least one element. If the first element is negative, return 1 plus the sum of the recursive sub-problem
(inductive) the input list has at least one element and the first element is positive. Return 0 plus the sum of the recursive sub-problem
def countNegatives(t):
if not t: return 0 # 1
elif t[0] < 0: return 1 + countNegatives(t[1:]) # 2
else: return 0 + countNegatives(t[1:]) # 3
Python 3.10 offers an elegant pattern matching solution -
def countNegatives(t):
match t:
case []: #1
return 0
case [n, *next] if n < 0: #2
return 1 + countNegatives(next)
case [_, *next]: #3
return 0 + countNegatives(next)
A:
All of the answers provided so far will fail with a stack overflow condition if given a large list, such as:
print(countNegatives([i-5000 for i in range(10000)]))
They all break a problem of size n into two subproblems of size 1 and size n-1, so the recursive stack growth is O(n). Python’s default stack size maxes out at around 1000 function calls, so this limits that approach to smaller lists.
When possible, it's a good idea to try to split a recursive problem of size n into two subproblems that are half that size. Successive halving yields a stack growth that is O(log n), so it can handle vastly larger problems.
For your problem note that the number of negatives in a list of size n > 2 is the number in the first half of the list plus the number in the second half of the list. If the list has one element, return 1 if it's negative. If it's non-negative or the list is empty, return 0.
def countNegatives(lst):
size = len(lst) # evaluate len() only once
if size > 1:
mid = size // 2 # find midpoint of lst
return countNegatives(lst[:mid]) + countNegatives(lst[mid:])
if size == 1 and lst[0] < 0:
return 1
return 0
print(countNegatives([0, 1, -1, 3, -5, 6])) # 2
print(countNegatives([-1, -3, 50, -4, -5, 1])) # 4
print(countNegatives([i - 5000 for i in range(10000)])) # 5000
With this approach you'll run out of memory to store the list long before you would get a stack overflow condition.
|
How do you count the number of negative items in a list using a recursive function?
|
I have to make a recursive function that counts how many negative values there are in a given list, but I can't figure out what I am supposed to return for each conditional.
def countNegatives(list):
"""Takes in a list of numbers and
returns the number of negative numbers
that are inside the list."""
count = 0
if len(list) == 0:
return 0
else:
if list[0] < 0:
return count + 1
else:
return countNegatives(list[1:])
print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1
|
[
"When list[0] < 0 your code ignores the rest of the list, yet there could be more negative values there to count.\nSo in that case don't do:\n return count + 1\n\nbut:\n return 1 + countNegatives(list[1:])\n\n",
"The step you were missing is to add the count to the returned value of the recursive call, so that the returned values of all recursive calls get summed up at the end. Here's one way you could do this:\ndef countNegatives(list):\n #if the list length is zero, we are done\n if len(list) == 0:\n return 0\n\n # Get the count of this iteration\n count = 1 if list[0] < 0 else 0\n # sum the count of this iteration with the count of all subsequent iterations\n return count + countNegatives(list[1:])\n\nSo, for your first example, the actual steps taken by your code would look like:\nreturn 0 + countNegatives([1, -1, 3, -5, 6])\nreturn 0 + countNegatives([-1, 3, -5, 6])\nreturn 1 + countNegatives([3, -5, 6])\nreturn 0 + countNegatives([-5, 6])\nreturn 1 + countNegatives([6])\nreturn 0 + countNegatives([])\nreturn 0\n\nExpanding all the values gives:\nreturn 0 + 0 + 1 + 0 + 1 + 0 + 0 \n\n",
"Recursion is a functional heritage and so using it with functional style yields the best results. That means avoiding things like mutation, variable reassignments, and other side effects. We can implement using straightforward mathematical induction -\n\nIf the input list is empty, there is nothing to count. Return the empty result, 0\n(inductive) the input list has at least one element. If the first element is negative, return 1 plus the sum of the recursive sub-problem\n(inductive) the input list has at least one element and the first element is positive. Return 0 plus the sum of the recursive sub-problem\n\ndef countNegatives(t):\n if not t: return 0 # 1\n elif t[0] < 0: return 1 + countNegatives(t[1:]) # 2\n else: return 0 + countNegatives(t[1:]) # 3\n\nPython 3.10 offers an elegant pattern matching solution -\ndef countNegatives(t):\n match t:\n case []: #1\n return 0\n case [n, *next] if n < 0: #2\n return 1 + countNegatives(next)\n case [_, *next]: #3\n return 0 + countNegatives(next)\n\n",
"All of the answers provided so far will fail with a stack overflow condition if given a large list, such as:\nprint(countNegatives([i-5000 for i in range(10000)]))\n\nThey all break a problem of size n into two subproblems of size 1 and size n-1, so the recursive stack growth is O(n). Python’s default stack size maxes out at around 1000 function calls, so this limits that approach to smaller lists.\nWhen possible, it's a good idea to try to split a recursive problem of size n into two subproblems that are half that size. Successive halving yields a stack growth that is O(log n), so it can handle vastly larger problems.\nFor your problem note that the number of negatives in a list of size n > 2 is the number in the first half of the list plus the number in the second half of the list. If the list has one element, return 1 if it's negative. If it's non-negative or the list is empty, return 0.\ndef countNegatives(lst):\n size = len(lst) # evaluate len() only once\n if size > 1:\n mid = size // 2 # find midpoint of lst\n return countNegatives(lst[:mid]) + countNegatives(lst[mid:])\n if size == 1 and lst[0] < 0:\n return 1\n return 0\n\nprint(countNegatives([0, 1, -1, 3, -5, 6])) # 2\nprint(countNegatives([-1, -3, 50, -4, -5, 1])) # 4\nprint(countNegatives([i - 5000 for i in range(10000)])) # 5000\n\nWith this approach you'll run out of memory to store the list long before you would get a stack overflow condition.\n"
] |
[
0,
0,
0,
0
] |
[
"The problem with your code is that you are not keeping track of the running count of negative numbers in the recursive calls. Specifically, you are returning count + 1 when the first item of the list is negative, and discarding the rest of the list, instead of using a recursive call to count the number of negative items in the rest of the list.\nTo fix the problem, you can add the result of the recursive call to count in both cases, when the first item is negative and when it is not. This way, the running count of negative items will be accumulated through the recursive calls, and returned as the final result when the base case is reached.\nHere's a corrected version of your code:\ndef countNegatives(lst):\n \"\"\"Takes in a list of numbers and\n returns the number of negative numbers\n that are inside the list.\"\"\"\n count = 0\n if len(lst) == 0:\n return 0\n else:\n if lst[0] < 0:\n count += 1\n count += countNegatives(lst[1:])\n return count\n\nprint(countNegatives([0, 1, -1, 3, -5, 6])) # Output: 2\nprint(countNegatives([-1, -3, 50, -4, -5, 1])) # Output: 4\n\nNote that I renamed the parameter list to lst, because list is the name of a built-in Python data type, and it is a good practice to avoid using built-in names as variable names.\n",
"You want to accumulate count, so pass it to the recursive function. The first caller starts at zero, so you have a good default.\ndef countNegatives(list, count=0):\n \"\"\"Takes in a list of numbers and\n returns the number of negative numbers\n that are inside the list.\"\"\"\n if len(list):\n count += list[0] < 0\n return countNegatives(list[1:], count)\n else:\n return count\n\nresult = countNegatives([1,99, -3, 6, -66, -7, 12, -1, -1])\nprint(result)\nassert result == 5\n \n\n"
] |
[
-1,
-1
] |
[
"python",
"recursion"
] |
stackoverflow_0074659510_python_recursion.txt
|
Q:
How to redirect an authenticated (using Django) user to VueJS frontend?
I have a simple VueJS setup that involves some use of a router. This runs on one local server. I also have a django backend project that runs on a second local server. I would like for a django view to take my user to my vue frontend. What approach could I take to reach this?
I have not yet made an attempt but if there is a specific part of my code I would need to show to get support then do let me know.
I have consider the below SO post however it does not address my issue relating to what a view function would need to consist of.
Setup django social auth with vuejs frontend
In a webpack project people make use of a vue.config.js file like below but I am using vite of course and so I do not know how to make a connection.
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
publicPath: "http://0.0.0.0:8080",
outputDir: "./dist/",
chainWebpack: config => {
config.optimization.splitChunks(false)
config.plugin('BundleTracker').use(BundleTracker, [
{
filename: './webpack-stats.json'
}
])
config.resolve.alias.set('__STATIC__', 'static')
config.devServer
.public('http://0.0.0.0:8080')
.host('0.0.0.0')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({'Access-Control-Allow-Origin': ['\*']})
}
};
A:
from django.shortcuts import redirect
def login(request):
# Verify the user's authentication data
# and authenticate the user if the data is valid
# ...
# Redirect the user to the VueJS frontend
return redirect('https://vuejs.app')
In this example, when the user is successfully authenticated in your Django application, the redirect function is called to redirect the user to the specified URL (in this case, https://vuejs.app). This will allow the user to access the VueJS frontend without having to log in again.
|
How to redirect an authenticated (using Django) user to VueJS frontend?
|
I have a simple VueJS setup that involves some use of a router. This runs on one local server. I also have a django backend project that runs on a second local server. I would like for a django view to take my user to my vue frontend. What approach could I take to reach this?
I have not yet made an attempt but if there is a specific part of my code I would need to show to get support then do let me know.
I have consider the below SO post however it does not address my issue relating to what a view function would need to consist of.
Setup django social auth with vuejs frontend
In a webpack project people make use of a vue.config.js file like below but I am using vite of course and so I do not know how to make a connection.
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
publicPath: "http://0.0.0.0:8080",
outputDir: "./dist/",
chainWebpack: config => {
config.optimization.splitChunks(false)
config.plugin('BundleTracker').use(BundleTracker, [
{
filename: './webpack-stats.json'
}
])
config.resolve.alias.set('__STATIC__', 'static')
config.devServer
.public('http://0.0.0.0:8080')
.host('0.0.0.0')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({'Access-Control-Allow-Origin': ['\*']})
}
};
|
[
"\nfrom django.shortcuts import redirect\n\ndef login(request):\n # Verify the user's authentication data\n # and authenticate the user if the data is valid\n # ...\n\n # Redirect the user to the VueJS frontend\n return redirect('https://vuejs.app')\n\n\nIn this example, when the user is successfully authenticated in your Django application, the redirect function is called to redirect the user to the specified URL (in this case, https://vuejs.app). This will allow the user to access the VueJS frontend without having to log in again.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python",
"vite",
"vue.js",
"webpack"
] |
stackoverflow_0074668331_django_python_vite_vue.js_webpack.txt
|
Q:
How to export data from files react-native
I have a few files like Train.js and Result.js.
How can i make export voiceData from Train.js to Result.js? Files bellow:
Train.js
const Train = () => {
const [user] = useAuth()
let [started, setStarted] = useState(false);
let [results, setResults] = useState([]);
const [voiceData, setVoiceData] = useState([]);
const navigation = useNavigation()
const toResult = () => {
navigation.navigate('Result')
}
Result.js:
return (
<View style={styles.container}>
<Text>{voiceData}</Text>
<View>
A:
Depends on how you are using it and what you want to do with it but here's an example of exporting and importing.
// Train.js
export default Train = () => {
const voiceData = "hesdsdsdsdllo";
return voiceData;
}
// App.js
import React from 'react';
import Train from './Train.js';
export function App(props) {
return (
<div className='App'>
<h1>Hello React. {Train()}</h1>
</div>
);
}
Train is a function so return what you need from it.
|
How to export data from files react-native
|
I have a few files like Train.js and Result.js.
How can i make export voiceData from Train.js to Result.js? Files bellow:
Train.js
const Train = () => {
const [user] = useAuth()
let [started, setStarted] = useState(false);
let [results, setResults] = useState([]);
const [voiceData, setVoiceData] = useState([]);
const navigation = useNavigation()
const toResult = () => {
navigation.navigate('Result')
}
Result.js:
return (
<View style={styles.container}>
<Text>{voiceData}</Text>
<View>
|
[
"Depends on how you are using it and what you want to do with it but here's an example of exporting and importing.\n// Train.js\nexport default Train = () => {\n const voiceData = \"hesdsdsdsdllo\";\n return voiceData;\n}\n\n// App.js\nimport React from 'react';\nimport Train from './Train.js';\n\nexport function App(props) {\n return (\n <div className='App'>\n <h1>Hello React. {Train()}</h1>\n </div>\n );\n}\n\nTrain is a function so return what you need from it.\n"
] |
[
1
] |
[] |
[] |
[
"react_native"
] |
stackoverflow_0074668210_react_native.txt
|
Q:
How to use data attribute value inside Javascript code?
I want to use the data attribute value inside Javascript code. I have a simple code for countdown timer from W3 Schools. Where I need to write Countdown Last Date, or completing Date. But I want something like that, data-attribute value will be place inside the Last date position. Look at this code;
<p id="demo"></p>
<script>
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
I want something like that;
<p id="demo" data-attribute="Jan 5, 2024 15:37:25"></p>
This data attribute value or time will be place inside var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
So that it can change from HTML Part. don't need to go Javascript code. If there's any way using jquery, I will do. how can I do it ?
Show or use data-attribute value inside Javascript Code.
A:
To access the value of a data-* attribute in JavaScript, you can use the getAttribute() method and pass in the attribute name.
For example, if you have an element with a data-time attribute like this:
<p id="demo" data-time="Jan 5, 2024 15:37:25"></p>
You can access the value of the data-time attribute like this:
var time = document.getElementById('demo').getAttribute('data-time');
Then you can use the time variable in your JavaScript code, such as when creating a new Date object like this:
var countDownDate = new Date(time).getTime();
You can also use jQuery to access the data-time attribute like this:
var time = $('#demo').attr('data-time');
Then you can use the time variable in your JavaScript code in the same way as shown above.
|
How to use data attribute value inside Javascript code?
|
I want to use the data attribute value inside Javascript code. I have a simple code for countdown timer from W3 Schools. Where I need to write Countdown Last Date, or completing Date. But I want something like that, data-attribute value will be place inside the Last date position. Look at this code;
<p id="demo"></p>
<script>
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
I want something like that;
<p id="demo" data-attribute="Jan 5, 2024 15:37:25"></p>
This data attribute value or time will be place inside var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
So that it can change from HTML Part. don't need to go Javascript code. If there's any way using jquery, I will do. how can I do it ?
Show or use data-attribute value inside Javascript Code.
|
[
"To access the value of a data-* attribute in JavaScript, you can use the getAttribute() method and pass in the attribute name.\nFor example, if you have an element with a data-time attribute like this:\n<p id=\"demo\" data-time=\"Jan 5, 2024 15:37:25\"></p>\nYou can access the value of the data-time attribute like this:\nvar time = document.getElementById('demo').getAttribute('data-time');\nThen you can use the time variable in your JavaScript code, such as when creating a new Date object like this:\nvar countDownDate = new Date(time).getTime();\nYou can also use jQuery to access the data-time attribute like this:\nvar time = $('#demo').attr('data-time');\nThen you can use the time variable in your JavaScript code in the same way as shown above.\n"
] |
[
0
] |
[] |
[] |
[
"countdown",
"custom_data_attribute",
"html",
"javascript",
"jquery"
] |
stackoverflow_0074668320_countdown_custom_data_attribute_html_javascript_jquery.txt
|
Q:
Traefik: How do I redirect https to http with Docker?
I inherited a project that is using Traefik with Docker but I have no experience with Traefik so seeking some assistance.
Say I have domain https://xxx.testsite.com I have been asked to redirect any traffic from https to http.
I've tried configuring a middleware to redirect but it didn't work.
Currently, if I visit http://xxx.testsite.com my website does load.
If I visit https://xxx.testsite.com I get a 404 page not found.
How can I can configure my files to accomplish this?
My project directory structure is
my_project/
├─ testsite/
│ ├─ docker-compose.yml
│ ├─ docker-compose-https.yml
│ ├─ web
│ │ ├─index.html
├─ traefik.yml
├─ traefik.toml
├─ acme.json
my_project/traefik.toml
[web]
logLevel = "DEBUG"
defaultEntryPoints = ["https","http"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.dashboard]
address = ":8088"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[retry]
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "jltxxxx.com"
watch = true
exposedByDefault = false
network = "jh"
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[acme.httpChallenge]
entryPoint = "http"
my_project/traefik.yml
version: '2'
services:
traefik:
image: traefik:v1.7
restart: unless-stopped
networks:
- testsite
ports:
- '8100:80'
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./traefik.toml:/traefik.toml
- ./acme.json:/acme.json
logging:
options:
max-size: 100m
networks:
testsite:
external:
name: testsite_default
my_project/testsite/docker-compose.yml
version: '2'
services:
web:
image: 'flipbox/php:72-apache'
restart: unless-stopped
volumes:
- '.:/var/www/html/'
labels:
- 'traefik.enable=true'
- 'traefik.backend=testsite_web_1'
- 'traefik.docker.network=testsite'
- 'traefik.frontend.rule=Host:xxx.testsite.com, www.xxx.testsite.com'
logging:
options:
max-size: 500m
my_project/testsite/docker-compose-https.yml
version: '2'
services:
web:
image: 'flipbox/php:72-apache'
restart: unless-stopped
volumes:
- '.:/var/www/html/'
labels:
- 'traefik.enable=true'
- 'traefik.port=80'
- 'traefik.frontend.entryPoints=https'
- 'traefik.backend=testsite_web_1'
- 'traefik.docker.network=testsite'
- 'traefik.frontend.rule=Host:xxx.testsite.com, www.xxx.testsite.com'
logging:
options:
max-size: 500m
A:
I'm not familiar with the Traefik v1 syntax, but I hope this code for Traefik v2 might give an idea how to do this in v1. And also to answer the question for other people using Traefik v2.
First of all, there are many things in this configuration that doesn't seem right. To name an example, the ports specified in the static config and the ports you expose in the Traefik container do not match.
But to come back to the redirect part, there are two options:
Either you can redirect ALL incoming traffic to HTTPS by adding the following to the static configuration of the Traefik container:
command:
- "--entrypoints.websecure.address=:443"
- "--entrypoints.web.address=:80"
- "--entrypoints.web.http.redirections.entryPoint.to=websecure"
- "--entrypoints.web.http.redirections.entryPoint.scheme=https"
- "--entrypoints.web.http.redirections.entrypoint.permanent=true"
Or you can redirect traffic to HTTPS for a single container by adding the following to the dynamic configuration of the application container:
labels:
- "traefik.enable=true"
- "traefik.http.middlewares.myapp-redirect.redirectscheme.scheme=https"
- "traefik.http.middlewares.myapp-redirect.redirectscheme.permanent=true"
- "traefik.http.routers.myapp.middlewares=myapp-redirect"
- "traefik.http.routers.myapp.rule=Host(`myapp.localhost`)"
- "traefik.http.routers.myapp.entrypoints=web"
- "traefik.http.routers.myapp-secure.rule=Host(`myapp.localhost`)"
- "traefik.http.routers.myapp-secure.entrypoints=websecure"
- "traefik.http.routers.myapp-secure.tls=true"
- "traefik.http.routers.myapp-secure.tls.certresolver=le"
|
Traefik: How do I redirect https to http with Docker?
|
I inherited a project that is using Traefik with Docker but I have no experience with Traefik so seeking some assistance.
Say I have domain https://xxx.testsite.com I have been asked to redirect any traffic from https to http.
I've tried configuring a middleware to redirect but it didn't work.
Currently, if I visit http://xxx.testsite.com my website does load.
If I visit https://xxx.testsite.com I get a 404 page not found.
How can I can configure my files to accomplish this?
My project directory structure is
my_project/
├─ testsite/
│ ├─ docker-compose.yml
│ ├─ docker-compose-https.yml
│ ├─ web
│ │ ├─index.html
├─ traefik.yml
├─ traefik.toml
├─ acme.json
my_project/traefik.toml
[web]
logLevel = "DEBUG"
defaultEntryPoints = ["https","http"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.dashboard]
address = ":8088"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[retry]
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "jltxxxx.com"
watch = true
exposedByDefault = false
network = "jh"
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[acme.httpChallenge]
entryPoint = "http"
my_project/traefik.yml
version: '2'
services:
traefik:
image: traefik:v1.7
restart: unless-stopped
networks:
- testsite
ports:
- '8100:80'
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./traefik.toml:/traefik.toml
- ./acme.json:/acme.json
logging:
options:
max-size: 100m
networks:
testsite:
external:
name: testsite_default
my_project/testsite/docker-compose.yml
version: '2'
services:
web:
image: 'flipbox/php:72-apache'
restart: unless-stopped
volumes:
- '.:/var/www/html/'
labels:
- 'traefik.enable=true'
- 'traefik.backend=testsite_web_1'
- 'traefik.docker.network=testsite'
- 'traefik.frontend.rule=Host:xxx.testsite.com, www.xxx.testsite.com'
logging:
options:
max-size: 500m
my_project/testsite/docker-compose-https.yml
version: '2'
services:
web:
image: 'flipbox/php:72-apache'
restart: unless-stopped
volumes:
- '.:/var/www/html/'
labels:
- 'traefik.enable=true'
- 'traefik.port=80'
- 'traefik.frontend.entryPoints=https'
- 'traefik.backend=testsite_web_1'
- 'traefik.docker.network=testsite'
- 'traefik.frontend.rule=Host:xxx.testsite.com, www.xxx.testsite.com'
logging:
options:
max-size: 500m
|
[
"I'm not familiar with the Traefik v1 syntax, but I hope this code for Traefik v2 might give an idea how to do this in v1. And also to answer the question for other people using Traefik v2.\nFirst of all, there are many things in this configuration that doesn't seem right. To name an example, the ports specified in the static config and the ports you expose in the Traefik container do not match.\nBut to come back to the redirect part, there are two options:\nEither you can redirect ALL incoming traffic to HTTPS by adding the following to the static configuration of the Traefik container:\ncommand:\n - \"--entrypoints.websecure.address=:443\"\n - \"--entrypoints.web.address=:80\"\n - \"--entrypoints.web.http.redirections.entryPoint.to=websecure\"\n - \"--entrypoints.web.http.redirections.entryPoint.scheme=https\"\n - \"--entrypoints.web.http.redirections.entrypoint.permanent=true\"\n\nOr you can redirect traffic to HTTPS for a single container by adding the following to the dynamic configuration of the application container:\nlabels:\n - \"traefik.enable=true\"\n - \"traefik.http.middlewares.myapp-redirect.redirectscheme.scheme=https\"\n - \"traefik.http.middlewares.myapp-redirect.redirectscheme.permanent=true\"\n - \"traefik.http.routers.myapp.middlewares=myapp-redirect\"\n - \"traefik.http.routers.myapp.rule=Host(`myapp.localhost`)\"\n - \"traefik.http.routers.myapp.entrypoints=web\"\n - \"traefik.http.routers.myapp-secure.rule=Host(`myapp.localhost`)\"\n - \"traefik.http.routers.myapp-secure.entrypoints=websecure\"\n - \"traefik.http.routers.myapp-secure.tls=true\"\n - \"traefik.http.routers.myapp-secure.tls.certresolver=le\"\n\n"
] |
[
0
] |
[] |
[] |
[
"docker",
"http",
"https",
"redirect",
"traefik"
] |
stackoverflow_0070584646_docker_http_https_redirect_traefik.txt
|
Q:
Inserting cli options into virtualenv.cli_run within a python file
Problem Code Picture
I want to write a Python script that creates a new virtual environment with the following virtualenv CLI options:
--app-data APP_DATA (a folder APP_DATA for the cache)
--seeder {app-data,pip}
If I give those two as strings in a list (see picture) I get:
TypeError: options must be of type VirtualEnvOptions
A:
When you call cli_run as part of virtualenv, you don't need to include the first argument, in this case "venv".
this should work:
from virtualenv import cli_run
cli_run(["--app-data APP_DATA", "--seeder {app-data,pip}"]);
A:
According to virtualenv's documentation section "Programmatic API", this seems like the following should work:
from virtualenv import cli_run
cli_run(['path/to/venv', '--app-data', 'path/to/app_data', '--seeder', 'app-data'])
|
Inserting cli options into virtualenv.cli_run within a python file
|
Problem Code Picture
I want to write a Python script that creates a new virtual environment with the following virtualenv CLI options:
--app-data APP_DATA (a folder APP_DATA for the cache)
--seeder {app-data,pip}
If I give those two as strings in a list (see picture) I get:
TypeError: options must be of type VirtualEnvOptions
|
[
"When you call cli_run as part of virtualenv, you don't need to include the first argument, in this case \"venv\".\nthis should work:\nfrom virtualenv import cli_run\ncli_run([\"--app-data APP_DATA\", \"--seeder {app-data,pip}\"]);\n\n",
"According to virtualenv's documentation section \"Programmatic API\", this seems like the following should work:\nfrom virtualenv import cli_run\n\ncli_run(['path/to/venv', '--app-data', 'path/to/app_data', '--seeder', 'app-data'])\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"virtualenv"
] |
stackoverflow_0074662331_python_virtualenv.txt
|
Q:
React Typescript requires to override render() method
I have a nx monorepo project with react frontend component. I have started writing the components in jsx format, then changed to typescript by adding types where needed and changing filenames to .tsx.
In my .tsx files I have some code in classes and some in javascript functions. The code that is in classes is throwing a strange error on compilation:
Errors
Here is my code:
App.tsx:
class App extends React.Component<unknown, AppState> {
static contextType = UserContext;
context!: React.ContextType<typeof UserContext>;
constructor(props: unknown) {
super(props);
this.state = ({
sidebarOpen: false,
currPage: 'Players',
});
this.navbarClick = this.navbarClick.bind(this);
this.openSidebar = this.openSidebar.bind(this);
this.closeSidebar = this.closeSidebar.bind(this);
this.setSidebarOpen = this.setSidebarOpen.bind(this);
this.setCurrPage = this.setCurrPage.bind(this);
}
setSidebarOpen(param: boolean) {
this.setState({
sidebarOpen: param,
});
}
setCurrPage(param: string) {
this.setState({
currPage: param,
});
}
navbarClick(choice: string) {
this.setCurrPage(choice);
}
openSidebar() {
this.setSidebarOpen(true);
}
closeSidebar() {
this.setSidebarOpen(false);
}
/* The Application first checks for a valid token, if doesn't exist, display the login component until token is valid.
The Application renders 3 windows to screen: sidebar, navbar and main window. There is a state param currPage
which is updated from Navbar and responsible to re-render the Main component with the appropriate page
*/
public render() {
const { token, setToken, username } = this.context!;
if (!token) {
return <Login />;
}
return (
<div className="container-fluid">
<div className="sidebar">
<Sidebar sidebarOpen={this.state.sidebarOpen} closeSidebar={this.closeSidebar} username={username} clickFunc={this.navbarClick} setToken={setToken}/>
</div>
<div className="content">
<div className="navbar">
<Navbar sidebarOpen={this.state.sidebarOpen} openSidebar={this.openSidebar}/>
</div>
<div className="main">
<Main username={username} page={this.state.currPage}/>
</div>
</div>
</div>
)
}
}
export default App;
main.tsx:
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { UserContextProvider } from './store/user-context';
ReactDOM.render(
<React.StrictMode>
<UserContextProvider>
<App />
</UserContextProvider>,
</React.StrictMode>,
document.getElementById('root')
)
UserContext.tsx:
import React, { createContext, useContext, useState } from 'react';
export interface UserContextIntf {
role: string,
setRole(role: string): void,
token: string,
setToken(token: string): void,
username: string,
setUsername(username: string): void
}
const UserContext = createContext<UserContextIntf>({
role: "",
setRole: (role: string) => {},
token: "",
setToken: (role: string) => {},
username: "",
setUsername: (role: string) => {},
});
export function UserContextProvider(props: any) {
const [role, setRole] = useState<string>("");
const [token, setToken] = useState<string>("");
const [username, setUsername] = useState<string>("");
const context: UserContextIntf = {
role, setRole,
token, setToken,
username, setUsername
};
return <UserContext.Provider value={context}> {props.children} </UserContext.Provider>;
}
export default UserContext;
A:
I also had this problem. it's a NX bug about a line in package.json:
"noImplicitOverride": true,
got to your package.json and delete this line or assign it false :
"noImplicitOverride": false,
|
React Typescript requires to override render() method
|
I have a nx monorepo project with react frontend component. I have started writing the components in jsx format, then changed to typescript by adding types where needed and changing filenames to .tsx.
In my .tsx files I have some code in classes and some in javascript functions. The code that is in classes is throwing a strange error on compilation:
Errors
Here is my code:
App.tsx:
class App extends React.Component<unknown, AppState> {
static contextType = UserContext;
context!: React.ContextType<typeof UserContext>;
constructor(props: unknown) {
super(props);
this.state = ({
sidebarOpen: false,
currPage: 'Players',
});
this.navbarClick = this.navbarClick.bind(this);
this.openSidebar = this.openSidebar.bind(this);
this.closeSidebar = this.closeSidebar.bind(this);
this.setSidebarOpen = this.setSidebarOpen.bind(this);
this.setCurrPage = this.setCurrPage.bind(this);
}
setSidebarOpen(param: boolean) {
this.setState({
sidebarOpen: param,
});
}
setCurrPage(param: string) {
this.setState({
currPage: param,
});
}
navbarClick(choice: string) {
this.setCurrPage(choice);
}
openSidebar() {
this.setSidebarOpen(true);
}
closeSidebar() {
this.setSidebarOpen(false);
}
/* The Application first checks for a valid token, if doesn't exist, display the login component until token is valid.
The Application renders 3 windows to screen: sidebar, navbar and main window. There is a state param currPage
which is updated from Navbar and responsible to re-render the Main component with the appropriate page
*/
public render() {
const { token, setToken, username } = this.context!;
if (!token) {
return <Login />;
}
return (
<div className="container-fluid">
<div className="sidebar">
<Sidebar sidebarOpen={this.state.sidebarOpen} closeSidebar={this.closeSidebar} username={username} clickFunc={this.navbarClick} setToken={setToken}/>
</div>
<div className="content">
<div className="navbar">
<Navbar sidebarOpen={this.state.sidebarOpen} openSidebar={this.openSidebar}/>
</div>
<div className="main">
<Main username={username} page={this.state.currPage}/>
</div>
</div>
</div>
)
}
}
export default App;
main.tsx:
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { UserContextProvider } from './store/user-context';
ReactDOM.render(
<React.StrictMode>
<UserContextProvider>
<App />
</UserContextProvider>,
</React.StrictMode>,
document.getElementById('root')
)
UserContext.tsx:
import React, { createContext, useContext, useState } from 'react';
export interface UserContextIntf {
role: string,
setRole(role: string): void,
token: string,
setToken(token: string): void,
username: string,
setUsername(username: string): void
}
const UserContext = createContext<UserContextIntf>({
role: "",
setRole: (role: string) => {},
token: "",
setToken: (role: string) => {},
username: "",
setUsername: (role: string) => {},
});
export function UserContextProvider(props: any) {
const [role, setRole] = useState<string>("");
const [token, setToken] = useState<string>("");
const [username, setUsername] = useState<string>("");
const context: UserContextIntf = {
role, setRole,
token, setToken,
username, setUsername
};
return <UserContext.Provider value={context}> {props.children} </UserContext.Provider>;
}
export default UserContext;
|
[
"I also had this problem. it's a NX bug about a line in package.json:\n \"noImplicitOverride\": true,\ngot to your package.json and delete this line or assign it false :\n \"noImplicitOverride\": false,\n"
] |
[
0
] |
[] |
[] |
[
"react_typescript",
"reactjs",
"typescript"
] |
stackoverflow_0072310788_react_typescript_reactjs_typescript.txt
|
Q:
Is there any plan for a ROS2 distro compatible with C++20?
ROS2 humble distro currently supports C++17. Can it support C++20 modules?
Is there any prospect for a future ROS2 distro to support, be compatible with C++20, or leverage C++20 features?
Is there any plan for a future ROS2 distro that compiles with C++20
One that utilises C++20 features (especially C++20 modules)
How far are we from supporting C++20 modules? Will "modules" ever be supported, or are they in conflict with how ROS2 is designed?
A:
Today, you can build your own packages with C++20, and link them to ROS 2 packages build with C++17 just fine.
Be aware though: not all C++20 features are supported on all compilers. Of note: as of writing, C++20 Modules are only partially supported on GCC, Clang, and MSVC, so I would guess a full migration of the ROS core to C++20 modules is a long way off. See https://en.cppreference.com/w/cpp/compiler_support for a more detailed summary.
As far as ROS2 design, plans, and direction, you should probably post on https://discourse.ros.org/
|
Is there any plan for a ROS2 distro compatible with C++20?
|
ROS2 humble distro currently supports C++17. Can it support C++20 modules?
Is there any prospect for a future ROS2 distro to support, be compatible with C++20, or leverage C++20 features?
Is there any plan for a future ROS2 distro that compiles with C++20
One that utilises C++20 features (especially C++20 modules)
How far are we from supporting C++20 modules? Will "modules" ever be supported, or are they in conflict with how ROS2 is designed?
|
[
"Today, you can build your own packages with C++20, and link them to ROS 2 packages build with C++17 just fine.\nBe aware though: not all C++20 features are supported on all compilers. Of note: as of writing, C++20 Modules are only partially supported on GCC, Clang, and MSVC, so I would guess a full migration of the ROS core to C++20 modules is a long way off. See https://en.cppreference.com/w/cpp/compiler_support for a more detailed summary.\nAs far as ROS2 design, plans, and direction, you should probably post on https://discourse.ros.org/\n"
] |
[
0
] |
[] |
[] |
[
"c++20",
"ros2"
] |
stackoverflow_0074640580_c++20_ros2.txt
|
Q:
Create a unique ID based on the value in a row for MySQL
I am in the process of creating a web application for a genealogy project. I want each person I add onto the database to have a unique id, based on the first 3 characters of their surname (let's call it, for the purpose of explaining, 'surname-string'), concatenated with an autoincrement (which starts from 00001 for each unique 'surname-string').
For example - a person's surname is "Smith". The surname-string will be SMI and due to the fact that they are the first surname-string "SMI" the full reference will be SMI00001. Another person's surname is Black, making their surname-string BLA, and because they are the first one with the surname-string BLA, their reference will be BLA00001. A third person's surname is also Smith - they are the second person with the SMI surname-string, so their reference should be SMI00002.
This unique id will be used in the persons URL, to be searched by and create relationships between people in the database.
I have no clue how to approach this logically.
I have not tried anything yet. It goes way over my head!
A:
This method is sketchy, normally you should use auto-increment from database (numeric) or auto generate unique ID, for example md5(time().'randomsalt'.$username).
But if you have to use XXX00000 format you will need function to:
check if there is BLA00001 in database
if yes, check BLA00002 etc.
if no, create new entry
This will be very slow after some time plus every name have maximum 99999 chances of existence, after that you need to change BLA to BL1, BL2 etc.
A:
You can do this using a before insert trigger.
Consider the following table, where uniqu_identifier is the unique identifier based on the surname:
CREATE TABLE test(
id bigint NOT NULL AUTO_INCREMENT,
surname varchar(20),
uniqu_identifier varchar(30) ,
PRIMARY KEY (id)
) ;
You have to use a trigger because MySQL doesn't allow using the auto_increment column on a generated as column.
A trigger would be something like:
CREATE TRIGGER test_BEFORE_INSERT
BEFORE INSERT ON test
FOR EACH ROW
BEGIN
IF EXISTS (SELECT 1 FROM test WHERE left(surname,3) = left(new.surname,3)) THEN
SET new.uniqu_identifier = (select concat(upper(left(new.surname,3)),'0000' ,max(right(uniqu_identifier,1)) +1) from test );
ELSE
SET new.uniqu_identifier = concat(upper(left(new.surname,3)),'00001');
END IF ;
END
Some insert values
insert into test (surname) values ('SMITH');
insert into test (surname) values ('SMITH1');
insert into test (surname) values ('JOHN');
select *
from test;
Result:
id surname uniqu_identifier
1 SMITH SMI00001
2 SMITH1 SMI00002
3 JOHN JOH00001
https://dbfiddle.uk/Wc58Ne_j
A:
Hy
On Create Table you can make the default value of UID like this :
Create Table 'Users'
(ID...
UID varchar(100) Default (CONCAT(SUBSTRING(Firstname, 1, 3), LPAD(ID, 8, '0')))
Substring to return the first 3 char of the username
LPAD to convert the int to 8 digits (ex : 1 => 00000001)
|
Create a unique ID based on the value in a row for MySQL
|
I am in the process of creating a web application for a genealogy project. I want each person I add onto the database to have a unique id, based on the first 3 characters of their surname (let's call it, for the purpose of explaining, 'surname-string'), concatenated with an autoincrement (which starts from 00001 for each unique 'surname-string').
For example - a person's surname is "Smith". The surname-string will be SMI and due to the fact that they are the first surname-string "SMI" the full reference will be SMI00001. Another person's surname is Black, making their surname-string BLA, and because they are the first one with the surname-string BLA, their reference will be BLA00001. A third person's surname is also Smith - they are the second person with the SMI surname-string, so their reference should be SMI00002.
This unique id will be used in the persons URL, to be searched by and create relationships between people in the database.
I have no clue how to approach this logically.
I have not tried anything yet. It goes way over my head!
|
[
"This method is sketchy, normally you should use auto-increment from database (numeric) or auto generate unique ID, for example md5(time().'randomsalt'.$username).\nBut if you have to use XXX00000 format you will need function to:\n\ncheck if there is BLA00001 in database\nif yes, check BLA00002 etc.\nif no, create new entry\n\nThis will be very slow after some time plus every name have maximum 99999 chances of existence, after that you need to change BLA to BL1, BL2 etc.\n",
"You can do this using a before insert trigger.\nConsider the following table, where uniqu_identifier is the unique identifier based on the surname:\nCREATE TABLE test(\nid bigint NOT NULL AUTO_INCREMENT,\nsurname varchar(20),\nuniqu_identifier varchar(30) ,\n PRIMARY KEY (id)\n ) ;\n\nYou have to use a trigger because MySQL doesn't allow using the auto_increment column on a generated as column.\nA trigger would be something like:\nCREATE TRIGGER test_BEFORE_INSERT\n BEFORE INSERT ON test \n FOR EACH ROW\n BEGIN\n IF EXISTS (SELECT 1 FROM test WHERE left(surname,3) = left(new.surname,3)) THEN\n SET new.uniqu_identifier = (select concat(upper(left(new.surname,3)),'0000' ,max(right(uniqu_identifier,1)) +1) from test );\n ELSE \n SET new.uniqu_identifier = concat(upper(left(new.surname,3)),'00001');\n END IF ;\n END\n\nSome insert values\ninsert into test (surname) values ('SMITH');\ninsert into test (surname) values ('SMITH1');\ninsert into test (surname) values ('JOHN');\n\nselect * \nfrom test;\n\nResult:\nid surname uniqu_identifier\n1 SMITH SMI00001\n2 SMITH1 SMI00002\n3 JOHN JOH00001\n\nhttps://dbfiddle.uk/Wc58Ne_j\n",
"Hy\nOn Create Table you can make the default value of UID like this :\nCreate Table 'Users'\n(ID...\nUID varchar(100) Default (CONCAT(SUBSTRING(Firstname, 1, 3), LPAD(ID, 8, '0')))\nSubstring to return the first 3 char of the username\nLPAD to convert the int to 8 digits (ex : 1 => 00000001)\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"laravel",
"mysql",
"php",
"reference",
"uniqueidentifier"
] |
stackoverflow_0074667952_laravel_mysql_php_reference_uniqueidentifier.txt
|
Q:
Change classname dynamiclly in React
hello im trying to change a class name dynamiclly in react
hello im trying to change a class name dynamiclly in react
i am importing the classes from a realted css file like this
import classes from "./Board.module.css";
and in my Board componnet i want to return a classname based on somthing i genarate
it can be "card" "card activate " "card disable"
and i have 3 class in my css file
.card{
do card somthing
}
.card.activate{
do card activate somthing
}
.card.disable{
do card disable somthing
}
how can i do it becuase concateing dosent seem to be working
edit:
I am trying to to this:
import "./Board.module.css"
const Card = (props) => {
const itemClass =
"card" + (props.item.stat ? " active " + props.item.stat : "");
return (
<div className={itemClass} onClick={() => props.clickHandler(props.id)}>
<label>{props.item.content}</label>
</div>
);
};
export default Card;
and the CSS is :
.card.wrong{
background-color: red;
}
.card.correct{
background-color: green;
}
.card.active{
transform: rotateY(0);
}
i am doing so that every time i click a card i change its class name to active and somthing and base on that i do a color but
the class is undifined so i dont know what to do
A:
To change a class name dynamically in React, you can use the classnames package. Here's an example of how you could use it:
import classnames from 'classnames';
import classes from './Board.module.css';
const Board = () => {
const className = classnames(
classes.card,
{
[classes.activate]: isActive,
[classes.disable]: isDisabled,
}
);
return (
<div className={className}>
...
</div>
);
};
In this example, className will be set to card by default. If isActive is true, then className will be set to card activate. If isDisabled is true, then className will be set to card disable. You can add additional conditions to specify different class names based on your specific needs.
A:
Have you tried looking the element in inspect mode to see whether the classes are getting attached without spaces?
Eg. card active is getting applied as cardactive.
However, here's how you'd do it :
// Board.module.css
.card{
do card somthing
}
.card.activate{
do card activate somthing
}
.card.disable{
do card disable somthing
}
Here's a snippet of the component which uses the classes dynamically.
A dummy condition is used to simulate the truthy/falsy behavior that changes the class. Replace this using your custom logic.
Using string literals you can dynamically toggle between the classes as shown below:
import "./Board.module.css";
const MyComponent = () => {
const [condtion, setCondition] = useState(false); // this is the condition that toggles the class
return (
<>
<span className={`card ${condition ? 'activate' : 'disable'}`}>Hello world</span>
</>
Note: the activate and disable class-Names are strings and not variables.
|
Change classname dynamiclly in React
|
hello im trying to change a class name dynamiclly in react
hello im trying to change a class name dynamiclly in react
i am importing the classes from a realted css file like this
import classes from "./Board.module.css";
and in my Board componnet i want to return a classname based on somthing i genarate
it can be "card" "card activate " "card disable"
and i have 3 class in my css file
.card{
do card somthing
}
.card.activate{
do card activate somthing
}
.card.disable{
do card disable somthing
}
how can i do it becuase concateing dosent seem to be working
edit:
I am trying to to this:
import "./Board.module.css"
const Card = (props) => {
const itemClass =
"card" + (props.item.stat ? " active " + props.item.stat : "");
return (
<div className={itemClass} onClick={() => props.clickHandler(props.id)}>
<label>{props.item.content}</label>
</div>
);
};
export default Card;
and the CSS is :
.card.wrong{
background-color: red;
}
.card.correct{
background-color: green;
}
.card.active{
transform: rotateY(0);
}
i am doing so that every time i click a card i change its class name to active and somthing and base on that i do a color but
the class is undifined so i dont know what to do
|
[
"To change a class name dynamically in React, you can use the classnames package. Here's an example of how you could use it:\nimport classnames from 'classnames';\nimport classes from './Board.module.css';\n\nconst Board = () => {\n const className = classnames(\n classes.card,\n {\n [classes.activate]: isActive,\n [classes.disable]: isDisabled,\n }\n );\n\n return (\n <div className={className}>\n ...\n </div>\n );\n};\n\nIn this example, className will be set to card by default. If isActive is true, then className will be set to card activate. If isDisabled is true, then className will be set to card disable. You can add additional conditions to specify different class names based on your specific needs.\n",
"Have you tried looking the element in inspect mode to see whether the classes are getting attached without spaces?\nEg. card active is getting applied as cardactive.\nHowever, here's how you'd do it :\n// Board.module.css\n.card{\ndo card somthing\n\n}\n.card.activate{\ndo card activate somthing\n\n}\n.card.disable{\ndo card disable somthing\n\n}\n\nHere's a snippet of the component which uses the classes dynamically.\nA dummy condition is used to simulate the truthy/falsy behavior that changes the class. Replace this using your custom logic.\nUsing string literals you can dynamically toggle between the classes as shown below:\nimport \"./Board.module.css\";\n\nconst MyComponent = () => {\nconst [condtion, setCondition] = useState(false); // this is the condition that toggles the class\nreturn (\n<>\n <span className={`card ${condition ? 'activate' : 'disable'}`}>Hello world</span>\n</>\n\nNote: the activate and disable class-Names are strings and not variables.\n"
] |
[
0,
0
] |
[] |
[] |
[
"reactjs"
] |
stackoverflow_0074668309_reactjs.txt
|
Q:
Get Text from SVG using Python Selenium
My first time trying to extract data from an SVG element, following is the SVG element and the code I have tried to put up by reading stuff on the internet, I have absolutely no clue how wrong I am and why so.
<svg class="rv-xy-plot__inner" width="282" height="348">
<g class="rv-xy-plot__series rv-xy-plot__series--bar " transform="rrr">
<rect y="rrr" height="rrr" x="0" width="rrr" style="rrr;"></rect>
<rect y="rrr" height="rrr" x="0" width="rrr" style="rrr;"></rect>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--bar " transform="rrr">
<rect y="rrr" height="rrr" x="rrr" width="rrr" style="rrr;"></rect>
<rect y="rrr" height="rrr" x="rrr" width="rrr" style="rrr;"></rect>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary" transform="rrr">
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">Category 1</text>
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">Category 2</text>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary" transform="rrr">
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">44.83%</text>
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">0.00%</text>
</g>
</svg>
I am trying to get the Categories and corresponding Percentages from the last 2 blocks of the SVG, I've replaced all the values with the string 'rrr' just to make it more readable here.
I'm trying,
driver.find_element(By.XPATH,"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']").get_attribute('innerText')
Like I said, I don't know what I'm doing here, what I've so far understood is svg elements need to be represented as a 'custom ?' XPATH which involves stacking all elements into an XPATH which is relative to each other, however I have no clue on how to extract the expected output like below.
Category 1 - 44.83%
Category 2 - 0.00%
Any help is appreciated. Thanks.
A:
You can try something like :
for sv in driver.find_elements(By.XPATH,"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']"):
txt= sv.find_emlement(By.XPATH, './/text').text
print(txt)
#OR
for sv in driver.find_elements(By.XPATH,"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text"):
txt= sv.text
print(txt)
A:
sv = driver.find_elements(By.XPATH,"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']")
This gives me a list I can iterate through to get the values.
Thanks to the idea from @Fazlul, the modification I've made is //*[name()='text'] at the end.
|
Get Text from SVG using Python Selenium
|
My first time trying to extract data from an SVG element, following is the SVG element and the code I have tried to put up by reading stuff on the internet, I have absolutely no clue how wrong I am and why so.
<svg class="rv-xy-plot__inner" width="282" height="348">
<g class="rv-xy-plot__series rv-xy-plot__series--bar " transform="rrr">
<rect y="rrr" height="rrr" x="0" width="rrr" style="rrr;"></rect>
<rect y="rrr" height="rrr" x="0" width="rrr" style="rrr;"></rect>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--bar " transform="rrr">
<rect y="rrr" height="rrr" x="rrr" width="rrr" style="rrr;"></rect>
<rect y="rrr" height="rrr" x="rrr" width="rrr" style="rrr;"></rect>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary" transform="rrr">
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">Category 1</text>
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">Category 2</text>
</g>
<g class="rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary" transform="rrr">
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">44.83%</text>
<text dominant-baseline="rrr" class="rv-xy-plot__series--label-text">0.00%</text>
</g>
</svg>
I am trying to get the Categories and corresponding Percentages from the last 2 blocks of the SVG, I've replaced all the values with the string 'rrr' just to make it more readable here.
I'm trying,
driver.find_element(By.XPATH,"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']").get_attribute('innerText')
Like I said, I don't know what I'm doing here, what I've so far understood is svg elements need to be represented as a 'custom ?' XPATH which involves stacking all elements into an XPATH which is relative to each other, however I have no clue on how to extract the expected output like below.
Category 1 - 44.83%
Category 2 - 0.00%
Any help is appreciated. Thanks.
|
[
"You can try something like :\nfor sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(txt)\n\n#OR\n for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text\"):\n txt= sv.text\n print(txt)\n \n \n\n",
"sv = driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']\")\n\nThis gives me a list I can iterate through to get the values.\nThanks to the idea from @Fazlul, the modification I've made is //*[name()='text'] at the end.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"selenium",
"svg",
"web_scraping"
] |
stackoverflow_0074663657_python_selenium_svg_web_scraping.txt
|
Q:
How to achieve a modal similar to Bootstrap modal in .NET MAUI?
How can I achieve a Bootstrap modal dialog on .NET MAUI? Where..
Backdrop fade in or out
Modal content slide up or down
Modal can be close by clicking backdrop or by clicking custom close button
I've tried to find some existing libraries but have not been able to get the same effect.
Desired modal link: https://www.awesomescreenshot.com/video/11412401?key=4805d42e3e44dbabb15ff52cc2d70369
A:
You could use the BottomSheet control for this,
More information here: https://blogs.xgenoapps.com/post/2022/07/23/maui-bottom-sheet
Add the namespace:
xmlns:controls="clr-namespace:XGENO.Maui.Controls;assembly=Maui.Controls.BottomSheet"
And then all you have to do is something like:
<controls:BottomSheet
x:Name="simpleBottomSheet"
HeaderText="Simple Example">
<controls:BottomSheet.BottomSheetContent>
<Label
Text="Hello from Bottom Sheet. This is a simple implementation with no customization." />
</controls:BottomSheet.BottomSheetContent>
</controls:BottomSheet>
Also, the Github is here : https://github.com/naweed/Maui.Controls.BottomSheet
Goodluck!
Also, I have a free set of controls(Android/iOS) you can check out if you are interested. It already has a bunch of controls and I am planning to add more :D https://github.com/FreakyAli/MAUI.FreakyControls
A:
You could use net maui toolkit to open a popup page and show as modal.
Refer to this video:
https://www.youtube.com/watch?v=yM7opXlu-MU
|
How to achieve a modal similar to Bootstrap modal in .NET MAUI?
|
How can I achieve a Bootstrap modal dialog on .NET MAUI? Where..
Backdrop fade in or out
Modal content slide up or down
Modal can be close by clicking backdrop or by clicking custom close button
I've tried to find some existing libraries but have not been able to get the same effect.
Desired modal link: https://www.awesomescreenshot.com/video/11412401?key=4805d42e3e44dbabb15ff52cc2d70369
|
[
"You could use the BottomSheet control for this,\nMore information here: https://blogs.xgenoapps.com/post/2022/07/23/maui-bottom-sheet\nAdd the namespace:\nxmlns:controls=\"clr-namespace:XGENO.Maui.Controls;assembly=Maui.Controls.BottomSheet\"\n\nAnd then all you have to do is something like:\n<controls:BottomSheet\nx:Name=\"simpleBottomSheet\"\nHeaderText=\"Simple Example\">\n\n <controls:BottomSheet.BottomSheetContent> \n <Label\n Text=\"Hello from Bottom Sheet. This is a simple implementation with no customization.\" />\n </controls:BottomSheet.BottomSheetContent>\n \n</controls:BottomSheet>\n\nAlso, the Github is here : https://github.com/naweed/Maui.Controls.BottomSheet\nGoodluck!\nAlso, I have a free set of controls(Android/iOS) you can check out if you are interested. It already has a bunch of controls and I am planning to add more :D https://github.com/FreakyAli/MAUI.FreakyControls\n",
"You could use net maui toolkit to open a popup page and show as modal.\nRefer to this video:\nhttps://www.youtube.com/watch?v=yM7opXlu-MU\n"
] |
[
0,
0
] |
[] |
[] |
[
".net_maui",
"modal_dialog"
] |
stackoverflow_0073877089_.net_maui_modal_dialog.txt
|
Q:
Why system path behaviour in pycharm seems to be different that using directly the conda env?
this is actually my first question in stack overflow :D. As background: I started learning python by myself almost 1 year ago in parallel of my work (Industrial Engineer), so feel free to point any mistakes. Any feedback will be very appreciated (including the format of this question).
I was trying to a have a project structure with multiple folders where to organize the scripts clearly. Eveything was going peachy until I wanted to schedulesome scripts using bat files.
When running my scripts (with absolute imports) in Pycharm everything works without problems, but when I try to run same scripts via bat files the imports fails!
For this question I created a new (simplified) project and created a new conda enviroment (both called test) with a example of the structure of folders where I can reproduce this error. Inside those folders I have the a script (main.py) calling a function from another script (library.py)
main.py :
from A.B.C import library
library.Function_Alpha('hello world ')
library.py:
def Function_Alpha(txt):
print(txt)
main.bat
"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
pause
When I run the script using pycharm everything goes as expected:
C:\Localdata\ANACONDA\envs\test\python.exe C:/Users/bpereira/PycharmProjects/test/X/main.py
hello world
Process finished with exit code 0
But when I try running the bat file:
cmd.exe /c main.bat
C:\Users\bpereira\PycharmProjects\test\X>"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
Traceback (most recent call last):
File "C:/Users/bpereira/PycharmProjects/test/X/main.py", line 1, in <module>
from A.B.C import library
ModuleNotFoundError: No module named 'A'
C:\Users\bpereira\PycharmProjects\test\X>pause
Press any key to continue . . .
Is Pycharm doing something with the system paths that I am not aware?
How I can emulate the behaviour of pycharm using the bat files?
I tried adding the system path manually in the script and it works:
*main.py:
import sys
sys.path.append(r'C:/Users/bpereira/PycharmProjects/test')
from A.B.C import library
library.Function_Alpha('hello world ')
main.bat execution:
cmd.exe /c main.bat
C:\Users\bpereira\PycharmProjects\test\X>"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
hello world
C:\Users\bpereira\PycharmProjects\test\X>pause
Press any key to continue . . .
But I am actually trying to understand how pycharm does this automatically and if I can reproduce that without having to append the sys.path on each script.
In the actual project when I do this contaiment (sys.path.append) the scripts are able to run but I face other errors like SLL module missing while calling the request function. Again this works flawlessly within pycharm but from the bat files the request module seems to behave differently, which I think is realted to the system paths.
(Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")
For info: I am running this on the company laptop where I do not have admin rights and I am not able to edit the system paths.
A:
Solved.
After some more investigation it was clear that I was facing 2 problems:
Not declaring the env path in the system
Not activating the virtual enviroment properly (hence the SSL error)
Since I do not have the admin rights of the laptop (corporate one) I solved the path issue by defining the the project path in the .bat file, adding the path temporally each time the env is activated.
The one-liner I wrote in the initial .bat is not activating the enviroment. The correct way is to call the 'activate.bat' in the conda folder.
Hereby the solution in the .bat file:
@echo off
rem Define path to conda installation and env name.
set CONDAPATH= #CondaPath
set ENVNAME= #EnvName
rem Activate the env
if %ENVNAME%==base (set ENVPATH=%CONDAPATH%) else (set ENVPATH=%CONDAPATH%\envs\%ENVNAME%)
call %CONDAPATH%\Scripts\activate.bat %ENVPATH%
set PYTHONPATH= #ProjectPath
rem Run a python script in that environment
python #ScriptPath_1
python #ScriptPath_2
python #ScriptPath_3
rem Deactivate the environment
call conda deactivate
Hope this helps someone trying to automate python scripts using the windows task scheduler with .bat files
|
Why system path behaviour in pycharm seems to be different that using directly the conda env?
|
this is actually my first question in stack overflow :D. As background: I started learning python by myself almost 1 year ago in parallel of my work (Industrial Engineer), so feel free to point any mistakes. Any feedback will be very appreciated (including the format of this question).
I was trying to a have a project structure with multiple folders where to organize the scripts clearly. Eveything was going peachy until I wanted to schedulesome scripts using bat files.
When running my scripts (with absolute imports) in Pycharm everything works without problems, but when I try to run same scripts via bat files the imports fails!
For this question I created a new (simplified) project and created a new conda enviroment (both called test) with a example of the structure of folders where I can reproduce this error. Inside those folders I have the a script (main.py) calling a function from another script (library.py)
main.py :
from A.B.C import library
library.Function_Alpha('hello world ')
library.py:
def Function_Alpha(txt):
print(txt)
main.bat
"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
pause
When I run the script using pycharm everything goes as expected:
C:\Localdata\ANACONDA\envs\test\python.exe C:/Users/bpereira/PycharmProjects/test/X/main.py
hello world
Process finished with exit code 0
But when I try running the bat file:
cmd.exe /c main.bat
C:\Users\bpereira\PycharmProjects\test\X>"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
Traceback (most recent call last):
File "C:/Users/bpereira/PycharmProjects/test/X/main.py", line 1, in <module>
from A.B.C import library
ModuleNotFoundError: No module named 'A'
C:\Users\bpereira\PycharmProjects\test\X>pause
Press any key to continue . . .
Is Pycharm doing something with the system paths that I am not aware?
How I can emulate the behaviour of pycharm using the bat files?
I tried adding the system path manually in the script and it works:
*main.py:
import sys
sys.path.append(r'C:/Users/bpereira/PycharmProjects/test')
from A.B.C import library
library.Function_Alpha('hello world ')
main.bat execution:
cmd.exe /c main.bat
C:\Users\bpereira\PycharmProjects\test\X>"C:\Localdata\ANACONDA\envs\test\python.exe" "C:/Users/bpereira/PycharmProjects/test/X/main.py"
hello world
C:\Users\bpereira\PycharmProjects\test\X>pause
Press any key to continue . . .
But I am actually trying to understand how pycharm does this automatically and if I can reproduce that without having to append the sys.path on each script.
In the actual project when I do this contaiment (sys.path.append) the scripts are able to run but I face other errors like SLL module missing while calling the request function. Again this works flawlessly within pycharm but from the bat files the request module seems to behave differently, which I think is realted to the system paths.
(Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")
For info: I am running this on the company laptop where I do not have admin rights and I am not able to edit the system paths.
|
[
"Solved.\nAfter some more investigation it was clear that I was facing 2 problems:\n\nNot declaring the env path in the system\nNot activating the virtual enviroment properly (hence the SSL error)\n\nSince I do not have the admin rights of the laptop (corporate one) I solved the path issue by defining the the project path in the .bat file, adding the path temporally each time the env is activated.\nThe one-liner I wrote in the initial .bat is not activating the enviroment. The correct way is to call the 'activate.bat' in the conda folder.\nHereby the solution in the .bat file:\n@echo off\nrem Define path to conda installation and env name.\nset CONDAPATH= #CondaPath\nset ENVNAME= #EnvName\n\nrem Activate the env\nif %ENVNAME%==base (set ENVPATH=%CONDAPATH%) else (set ENVPATH=%CONDAPATH%\\envs\\%ENVNAME%)\ncall %CONDAPATH%\\Scripts\\activate.bat %ENVPATH%\n\nset PYTHONPATH= #ProjectPath\n\nrem Run a python script in that environment\npython #ScriptPath_1\npython #ScriptPath_2\npython #ScriptPath_3\n\nrem Deactivate the environment\ncall conda deactivate\n\nHope this helps someone trying to automate python scripts using the windows task scheduler with .bat files\n"
] |
[
0
] |
[] |
[] |
[
"import",
"path",
"pycharm",
"python"
] |
stackoverflow_0074352567_import_path_pycharm_python.txt
|
Q:
How can I decode JWT token in android?
I have a jwt token like this
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
How can I decode this so that I can get the payload like this
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
I have used this library , but can't find a way to do what I want
A:
you should split string:
If you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):
header
{
"alg": "HS256",
"typ": "JWT"
}
body
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Code example:
public class JWTUtils {
public static void decoded(String JWTEncoded) throws Exception {
try {
String[] split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
Log.d("JWT_DECODED", "Body: " + getJson(split[1]));
} catch (UnsupportedEncodingException e) {
//Error
}
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException{
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
}
Call method for example
JWTUtils.decoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");
library reference:
https://github.com/jwtk/jjwt
jwt test:
https://jwt.io/
A:
I used a third-party library named JWTDecode.Android https://github.com/auth0/JWTDecode.Android. The documentation is reasonably good. From your question, The sub, name, etc are a part of the body and are called Claims. You could get them like this using the above library:
JWT parsedJWT = new JWT(jwtToken);
Claim subscriptionMetaData = parsedJWT.getClaim("name");
String parsedValue = subscriptionMetaData.asString();
A:
This works using Java 8's Base64 class:
public String getDecodedJwt(String jwt)
{
String result = "";
String[] parts = jwt.split("[.]");
try
{
int index = 0;
for(String part: parts)
{
if (index >= 2)
break;
index++;
byte[] partAsBytes = part.getBytes("UTF-8");
String decodedPart = new String(java.util.Base64.getUrlDecoder().decode(partAsBytes), "UTF-8");
result += decodedPart;
}
}
catch(Exception e)
{
throw new RuntimeException("Couldnt decode jwt", e);
}
return result;
}
A:
If the project is already using AWSCognito SDK then CognitoJWTParser class can be used.
It has static methods getHeader(), getPayload(), getSignature().
https://github.com/aws-amplify/aws-sdk-android/blob/master/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/util/CognitoJWTParser.java
A:
I've used it in a Java web application and the code will look something like the below:-
Jwts.parser().setSigningKey('secret-key').parseClaimsJws(token).getBody()
It will return claims which contain the required values.
A:
this code convert JWT to String and work on any API
public static String getDecodedJwt(String jwt)
{
StringBuilder result = new StringBuilder();
String[] parts = jwt.split("[.]");
try
{
int index = 0;
for(String part: parts)
{
if (index >= 2)
break;
index++;
byte[] decodedBytes = Base64.decode(part.getBytes("UTF-8"), Base64.URL_SAFE);
result.append(new String(decodedBytes, "UTF-8"));
}
}
catch(Exception e)
{
throw new RuntimeException("Couldnt decode jwt", e);
}
return result.toString();
}
Example :
JWTUtils.getDecodedJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")
And finally the resulting conversion
{"alg":"HS256","typ":"JWT"}{"sub":"1234567890","name":"John Doe","iat":1516239022}
A:
Based partially on the code provided by Brad Parks, adapted for use with lower versions of Android by using Apache Commons and converted to Kotlin:
In build.gradle:
implementation 'apache-codec:commons-codec:1.2'
In a Kotlin class:
fun decodeToken(token: String): String{
val tokenParts: Array<String> = token.split(".").toTypedArray()
if(tokenParts.isEmpty()) return token
var decodedString = ""
for(part: String in tokenParts){
val partByteArray: ByteArray =
stringToFullBase64EncodedLength(part).toByteArray(Charsets.US_ASCII)
val decodedPart = String(Base64.decodeBase64(partByteArray))
decodedString+=decodedPart
// There are a maximum of two parts in an OAuth token,
// and arrays are 0-indexed, so if the index is 1
// we have processed the second part and should break.
if(tokenParts.indexOf(part) == 1) break
}
return decodedString
}
private fun stringToFullBase64EncodedLength(string: String): String{
// A properly base64 encoded string must be divisible by 4
// We'll pad it to the nearest multiple of 4 without losing data:
val targetLength: Int = ( 4 * ceil( string.length.toDouble()/4 ) ).toInt()
// Now, we get the difference, and add it with a reserved character (`=`)
// to the end of the string. It will get removed later.
val requiredPadding: Int = targetLength-string.length
return string+"=".repeat(requiredPadding)
}
A:
A no dependency version in Kotlin with Android SDK 26+ (Oreo):
fun extractJwt(jwt: String): String {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return "Requires SDK 26"
val parts = jwt.split(".")
return try {
val charset = charset("UTF-8")
val header = String(Base64.getUrlDecoder().decode(parts[0].toByteArray(charset)), charset)
val payload = String(Base64.getUrlDecoder().decode(parts[1].toByteArray(charset)), charset)
"$header\n$payload"
} catch (e: Exception) {
"Error parsing JWT: $e"
}
}
A:
If you are using the library io.jsonwebtoken.Jwts, then use the following snippet. It works for me.
try {
val claims: Claims =
Jwts.parser().setSigningKey(secretKey.toByteArray()).parseClaimsJws(token).body
return ConnectionClaim(claims["uid"].toString(), claims["key"].toString())
} catch (e: JwtException) {
e.printStackTrace()
}
A:
Almost all forgot to add imports and select android.util.Base64!
import android.util.Base64
import org.json.JSONException
// Json data class
data class Data(
val name: String?,
val nonce: String?,
// Other access_token fields
)
fun parseAccessToken(token: String): Data? {
return try {
val part = token.split(".")[1]
val s = decodeJwt(part)
// obj is an object of Gson or Moshi library
obj.fromJson(s)
} catch (e: Exception) {
null
}
}
@Throws(JSONException::class)
private fun decodeJwt(text: String): String {
val s = Base64.decode(text, Base64.URL_SAFE)
return String(s)
}
|
How can I decode JWT token in android?
|
I have a jwt token like this
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
How can I decode this so that I can get the payload like this
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
I have used this library , but can't find a way to do what I want
|
[
"you should split string:\nIf you pass the first two sections through a base 64 decoder, you'll get the following (formatting added for clarity):\nheader\n{\n \"alg\": \"HS256\",\n \"typ\": \"JWT\"\n}\n\nbody\n {\n \"sub\": \"1234567890\",\n \"name\": \"John Doe\",\n \"admin\": true\n}\n\nCode example:\npublic class JWTUtils {\n\n public static void decoded(String JWTEncoded) throws Exception {\n try {\n String[] split = JWTEncoded.split(\"\\\\.\");\n Log.d(\"JWT_DECODED\", \"Header: \" + getJson(split[0]));\n Log.d(\"JWT_DECODED\", \"Body: \" + getJson(split[1]));\n } catch (UnsupportedEncodingException e) {\n //Error\n }\n }\n\n private static String getJson(String strEncoded) throws UnsupportedEncodingException{\n byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);\n return new String(decodedBytes, \"UTF-8\");\n }\n}\n\nCall method for example \nJWTUtils.decoded(\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ\");\n\nlibrary reference: \nhttps://github.com/jwtk/jjwt\njwt test:\nhttps://jwt.io/\n",
"I used a third-party library named JWTDecode.Android https://github.com/auth0/JWTDecode.Android. The documentation is reasonably good. From your question, The sub, name, etc are a part of the body and are called Claims. You could get them like this using the above library:\nJWT parsedJWT = new JWT(jwtToken);\nClaim subscriptionMetaData = parsedJWT.getClaim(\"name\");\nString parsedValue = subscriptionMetaData.asString();\n\n",
"This works using Java 8's Base64 class:\npublic String getDecodedJwt(String jwt)\n{\n String result = \"\";\n\n String[] parts = jwt.split(\"[.]\");\n try\n {\n int index = 0;\n for(String part: parts)\n {\n if (index >= 2)\n break;\n\n index++;\n byte[] partAsBytes = part.getBytes(\"UTF-8\");\n String decodedPart = new String(java.util.Base64.getUrlDecoder().decode(partAsBytes), \"UTF-8\");\n\n result += decodedPart;\n }\n }\n catch(Exception e)\n {\n throw new RuntimeException(\"Couldnt decode jwt\", e);\n }\n\n return result;\n}\n\n",
"If the project is already using AWSCognito SDK then CognitoJWTParser class can be used.\nIt has static methods getHeader(), getPayload(), getSignature().\nhttps://github.com/aws-amplify/aws-sdk-android/blob/master/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/util/CognitoJWTParser.java\n",
"I've used it in a Java web application and the code will look something like the below:-\nJwts.parser().setSigningKey('secret-key').parseClaimsJws(token).getBody()\n\nIt will return claims which contain the required values.\n",
"this code convert JWT to String and work on any API\n public static String getDecodedJwt(String jwt)\n {\n StringBuilder result = new StringBuilder();\n\n String[] parts = jwt.split(\"[.]\");\n try\n {\n int index = 0;\n for(String part: parts)\n {\n if (index >= 2)\n break;\n index++;\n byte[] decodedBytes = Base64.decode(part.getBytes(\"UTF-8\"), Base64.URL_SAFE);\n result.append(new String(decodedBytes, \"UTF-8\"));\n }\n }\n catch(Exception e)\n {\n throw new RuntimeException(\"Couldnt decode jwt\", e);\n }\n\n return result.toString();\n }\n\nExample :\nJWTUtils.getDecodedJwt(\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\")\n\nAnd finally the resulting conversion\n{\"alg\":\"HS256\",\"typ\":\"JWT\"}{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}\n\n",
"Based partially on the code provided by Brad Parks, adapted for use with lower versions of Android by using Apache Commons and converted to Kotlin:\nIn build.gradle:\nimplementation 'apache-codec:commons-codec:1.2'\n\nIn a Kotlin class:\nfun decodeToken(token: String): String{\n val tokenParts: Array<String> = token.split(\".\").toTypedArray()\n if(tokenParts.isEmpty()) return token\n var decodedString = \"\"\n for(part: String in tokenParts){\n val partByteArray: ByteArray =\n stringToFullBase64EncodedLength(part).toByteArray(Charsets.US_ASCII)\n val decodedPart = String(Base64.decodeBase64(partByteArray))\n decodedString+=decodedPart\n // There are a maximum of two parts in an OAuth token,\n // and arrays are 0-indexed, so if the index is 1\n // we have processed the second part and should break.\n if(tokenParts.indexOf(part) == 1) break\n }\n return decodedString\n}\n\nprivate fun stringToFullBase64EncodedLength(string: String): String{\n\n // A properly base64 encoded string must be divisible by 4\n // We'll pad it to the nearest multiple of 4 without losing data:\n val targetLength: Int = ( 4 * ceil( string.length.toDouble()/4 ) ).toInt()\n\n // Now, we get the difference, and add it with a reserved character (`=`)\n // to the end of the string. It will get removed later.\n val requiredPadding: Int = targetLength-string.length\n return string+\"=\".repeat(requiredPadding)\n\n}\n\n",
"A no dependency version in Kotlin with Android SDK 26+ (Oreo):\nfun extractJwt(jwt: String): String {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return \"Requires SDK 26\"\n val parts = jwt.split(\".\")\n return try {\n val charset = charset(\"UTF-8\")\n val header = String(Base64.getUrlDecoder().decode(parts[0].toByteArray(charset)), charset)\n val payload = String(Base64.getUrlDecoder().decode(parts[1].toByteArray(charset)), charset)\n \"$header\\n$payload\"\n } catch (e: Exception) {\n \"Error parsing JWT: $e\"\n }\n}\n\n",
"If you are using the library io.jsonwebtoken.Jwts, then use the following snippet. It works for me.\ntry {\n val claims: Claims =\n Jwts.parser().setSigningKey(secretKey.toByteArray()).parseClaimsJws(token).body\n return ConnectionClaim(claims[\"uid\"].toString(), claims[\"key\"].toString())\n\n } catch (e: JwtException) {\n e.printStackTrace()\n }\n\n",
"Almost all forgot to add imports and select android.util.Base64!\nimport android.util.Base64\nimport org.json.JSONException\n\n// Json data class\ndata class Data(\n val name: String?,\n val nonce: String?,\n // Other access_token fields\n)\n\nfun parseAccessToken(token: String): Data? {\n return try {\n val part = token.split(\".\")[1]\n val s = decodeJwt(part)\n // obj is an object of Gson or Moshi library\n obj.fromJson(s)\n } catch (e: Exception) {\n null\n }\n}\n\n@Throws(JSONException::class)\nprivate fun decodeJwt(text: String): String {\n val s = Base64.decode(text, Base64.URL_SAFE)\n return String(s)\n}\n\n"
] |
[
78,
9,
4,
2,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"android",
"java",
"jwt"
] |
stackoverflow_0037695877_android_java_jwt.txt
|
Q:
React JS - Error Maximum update depth exceeded
I was testing out useSyncExternalStore to replace a store subscription used with useEffect,
Basically this is the usage of the hook,
const state = BoardState.getInstance();
const boardUIstate = useSyncExternalStore(
(observer) => state.subscribe(observer),
() => getUiStateFromExternalState(state.getState())
);
The state is a class implemented with classic observable pattern combine with a singleton,
export class BoardState<T> extends Subject<T> {
private static instance: BoardState<unknown> | undefined;
private constructor() {
super();
}
public static getInstance<T>(): BoardState<T> {
if (!BoardState.instance) {
BoardState.instance = new BoardState();
return BoardState.instance as BoardState<T>;
}
return BoardState.instance as BoardState<T>;
}
}
The extended Subject class tracks the state and the observers & implements the subscribe - unsubscribe methods,
export class Subject<T> {
protected state: T | undefined;
private observers: any[] = [];
subscribe(fn: (newState: T | undefined) => void) {
this.observers.push(fn);
return () => this.unsubscribe(fn);
}
private unsubscribe(fn: (newState: T | undefined) => void) {
this.observers = this.observers.filter((ob) => ob !== fn);
}
setState(state: T) {
this.state = state;
this.observers.map((ob) => ob(this.state));
}
...
}
I can see on my local development server, it is complaining about this,
Warning: The result of getSnapshot should be cached to avoid an
infinite loop
What's this caching ? How do I do that ? ( bug ? )
With the error,
Maximum update depth exceeded. This can happen when a component
repeatedly calls setState inside componentWillUpdate or
componentDidUpdate. React limits the number of nested updates to
prevent infinite loops.
Above external state works with useEffect & i can not see any issue with the implementation either. Any thoughts ?
Sandbox link
A:
My Bad, Found out that I need to use use-sync-external-store/with-selector
So I changed my code from,
const state = BoardState.getInstance();
const boardUIstate = useSyncExternalStore(
(observer) => state.subscribe(observer),
() => getUiStateFromExternalState(state.getState())
);
to
import {useSyncExternalStoreWithSelector} from 'use-sync-external-store/with-selector';
const state = BoardState.getInstance();
const boardUIstate = useSyncExternalStoreWithSelector<
Record<string, string | null> | undefined,
(number | null)[]
>(
state.subscribe.bind(state),
() => {
const state = state.getState();
return state;
},
undefined,
(snapshot) => {
return getUiStateFromExternalState(snapshot)
}
);
|
React JS - Error Maximum update depth exceeded
|
I was testing out useSyncExternalStore to replace a store subscription used with useEffect,
Basically this is the usage of the hook,
const state = BoardState.getInstance();
const boardUIstate = useSyncExternalStore(
(observer) => state.subscribe(observer),
() => getUiStateFromExternalState(state.getState())
);
The state is a class implemented with classic observable pattern combine with a singleton,
export class BoardState<T> extends Subject<T> {
private static instance: BoardState<unknown> | undefined;
private constructor() {
super();
}
public static getInstance<T>(): BoardState<T> {
if (!BoardState.instance) {
BoardState.instance = new BoardState();
return BoardState.instance as BoardState<T>;
}
return BoardState.instance as BoardState<T>;
}
}
The extended Subject class tracks the state and the observers & implements the subscribe - unsubscribe methods,
export class Subject<T> {
protected state: T | undefined;
private observers: any[] = [];
subscribe(fn: (newState: T | undefined) => void) {
this.observers.push(fn);
return () => this.unsubscribe(fn);
}
private unsubscribe(fn: (newState: T | undefined) => void) {
this.observers = this.observers.filter((ob) => ob !== fn);
}
setState(state: T) {
this.state = state;
this.observers.map((ob) => ob(this.state));
}
...
}
I can see on my local development server, it is complaining about this,
Warning: The result of getSnapshot should be cached to avoid an
infinite loop
What's this caching ? How do I do that ? ( bug ? )
With the error,
Maximum update depth exceeded. This can happen when a component
repeatedly calls setState inside componentWillUpdate or
componentDidUpdate. React limits the number of nested updates to
prevent infinite loops.
Above external state works with useEffect & i can not see any issue with the implementation either. Any thoughts ?
Sandbox link
|
[
"My Bad, Found out that I need to use use-sync-external-store/with-selector\nSo I changed my code from,\n const state = BoardState.getInstance();\n\n const boardUIstate = useSyncExternalStore(\n (observer) => state.subscribe(observer),\n () => getUiStateFromExternalState(state.getState())\n );\n\nto\nimport {useSyncExternalStoreWithSelector} from 'use-sync-external-store/with-selector';\n\nconst state = BoardState.getInstance();\n\nconst boardUIstate = useSyncExternalStoreWithSelector<\n Record<string, string | null> | undefined,\n (number | null)[]\n>(\n state.subscribe.bind(state),\n () => {\n const state = state.getState();\n return state;\n },\n undefined,\n (snapshot) => {\n return getUiStateFromExternalState(snapshot)\n }\n);\n\n"
] |
[
0
] |
[] |
[] |
[
"react_hooks",
"reactjs"
] |
stackoverflow_0074668135_react_hooks_reactjs.txt
|
Q:
How to sort recyclerview data fetched from firebase by value in mvvm architecture
I am trying to sort datas which are fetched from firebase realtime database according to the value of a child using MVVM architecture the daabase reference is created in a repository
GroupNoticeRepository
class GroupNoticeRepository(private var groupSelected: String) {
val auth = Firebase.auth
val user = auth.currentUser!!.uid
private val scheduleReference: DatabaseReference =
FirebaseDatabase.getInstance().getReference("group-notice").child(groupSelected)
@Volatile
private var INSTANCE: GroupNoticeRepository? = null
fun getInstance(): GroupNoticeRepository {
return INSTANCE ?: synchronized(this) {
val instance = GroupNoticeRepository(groupSelected)
INSTANCE = instance
instance
}
}
fun loadSchedules(allSchedules: MutableLiveData<List<GroupNoticeData>>) {
scheduleReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val scheduleList: List<GroupNoticeData> =
snapshot.children.map { dataSnapshot ->
dataSnapshot.getValue(GroupNoticeData::class.java)!!
}
allSchedules.postValue(scheduleList)
} catch (_: Exception) {
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
GroupNoticeFragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = binding.taskList
recycler.layoutManager = LinearLayoutManager(context)
recycler.setHasFixedSize(true)
adapter = GroupNoticeAdapter(_inflater)
recycler.adapter = adapter
viewModel = ViewModelProvider(this)[GroupNoticeViewModel::class.java]
viewModel.initialize(groupId)
viewModel.allSchedules.observe(viewLifecycleOwner) {
adapter!!.updateUserList(it)
}
}
GroupNoticeViewModel
class GroupNoticeViewModel : ViewModel() {
private lateinit var repository: GroupNoticeRepository
private val _allSchedules = MutableLiveData<List<GroupNoticeData>>()
val allSchedules: LiveData<List<GroupNoticeData>> = _allSchedules
fun initialize(groupSelected: String) {
repository = GroupNoticeRepository(groupSelected).getInstance()
repository.loadSchedules(_allSchedules)
}
}
`
As you can see the current structure
group-notice
-groupId(groups)
-noticeId (notices)
- taskDate
Here under group notice there are some groups and in each group there are some notices(noticeId) .
Each notice has a task date . Now I am trying to sort the notices according to the taskdate meaning the taskDate which will is closer to todays date will view first in the recycler view. Or the notice with latest taskdate given will appear first in the recycler view .
A:
The best way to sort recyclerview data fetched from Firebase in an MVVM architecture is to use a custom Comparator. You can define a Comparator that takes two objects (in your case, two Firebase data objects) and compares their values. Then you can use this Comparator to sort the list of Firebase data objects before it is used to populate the RecyclerView.
Yes, here is an example of a custom Comparator that compares two Firebase data objects based on their 'name' field:
public class FirebaseDataComparator implements Comparator<FirebaseData> {
@Override
public int compare(FirebaseData o1, FirebaseData o2) {
return o1.getName().compareTo(o2.getName());
}
}
Then you can use this Comparator to sort a list of Firebase data objects before it is used to populate the RecyclerView:
List dataList = ... // get list of Firebase data objects
Collections.sort(dataList, new FirebaseDataComparator());
// use dataList to populate RecyclerView
A:
Just as hassan bazai said I followed the same concept of comparing two dates
class FirebaseDataComparator : Comparator<GroupNoticeData?> {
override fun compare(p0: GroupNoticeData?, p1: GroupNoticeData?): Int {
val dateFormat = SimpleDateFormat("dd/MM/yyyy")
val firstDate: Date = dateFormat.parse(p0?.taskdate!!) as Date
val secondDate: Date = dateFormat.parse(p1?.taskdate!!) as Date
return firstDate.compareTo(secondDate)
}
}
Here groupNoticeData is the data class I am using to populate the data in my recycler View and took two objects of them . Parsed their date format accordingly and later on compared them.
And in the recyclerViewAdapter before adding my data, I sorted them using the comparator class and added them later on. Here is the part where I had to use the comparator class.
fun updateNoticeList(notices: List<GroupNoticeData>) {
Collections.sort(notices, FirebaseDataComparator())
this.tasks.clear()
this.tasks.addAll(notices)
notifyDataSetChanged()
}
|
How to sort recyclerview data fetched from firebase by value in mvvm architecture
|
I am trying to sort datas which are fetched from firebase realtime database according to the value of a child using MVVM architecture the daabase reference is created in a repository
GroupNoticeRepository
class GroupNoticeRepository(private var groupSelected: String) {
val auth = Firebase.auth
val user = auth.currentUser!!.uid
private val scheduleReference: DatabaseReference =
FirebaseDatabase.getInstance().getReference("group-notice").child(groupSelected)
@Volatile
private var INSTANCE: GroupNoticeRepository? = null
fun getInstance(): GroupNoticeRepository {
return INSTANCE ?: synchronized(this) {
val instance = GroupNoticeRepository(groupSelected)
INSTANCE = instance
instance
}
}
fun loadSchedules(allSchedules: MutableLiveData<List<GroupNoticeData>>) {
scheduleReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
try {
val scheduleList: List<GroupNoticeData> =
snapshot.children.map { dataSnapshot ->
dataSnapshot.getValue(GroupNoticeData::class.java)!!
}
allSchedules.postValue(scheduleList)
} catch (_: Exception) {
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
GroupNoticeFragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = binding.taskList
recycler.layoutManager = LinearLayoutManager(context)
recycler.setHasFixedSize(true)
adapter = GroupNoticeAdapter(_inflater)
recycler.adapter = adapter
viewModel = ViewModelProvider(this)[GroupNoticeViewModel::class.java]
viewModel.initialize(groupId)
viewModel.allSchedules.observe(viewLifecycleOwner) {
adapter!!.updateUserList(it)
}
}
GroupNoticeViewModel
class GroupNoticeViewModel : ViewModel() {
private lateinit var repository: GroupNoticeRepository
private val _allSchedules = MutableLiveData<List<GroupNoticeData>>()
val allSchedules: LiveData<List<GroupNoticeData>> = _allSchedules
fun initialize(groupSelected: String) {
repository = GroupNoticeRepository(groupSelected).getInstance()
repository.loadSchedules(_allSchedules)
}
}
`
As you can see the current structure
group-notice
-groupId(groups)
-noticeId (notices)
- taskDate
Here under group notice there are some groups and in each group there are some notices(noticeId) .
Each notice has a task date . Now I am trying to sort the notices according to the taskdate meaning the taskDate which will is closer to todays date will view first in the recycler view. Or the notice with latest taskdate given will appear first in the recycler view .
|
[
"The best way to sort recyclerview data fetched from Firebase in an MVVM architecture is to use a custom Comparator. You can define a Comparator that takes two objects (in your case, two Firebase data objects) and compares their values. Then you can use this Comparator to sort the list of Firebase data objects before it is used to populate the RecyclerView.\nYes, here is an example of a custom Comparator that compares two Firebase data objects based on their 'name' field:\npublic class FirebaseDataComparator implements Comparator<FirebaseData> {\n @Override\n public int compare(FirebaseData o1, FirebaseData o2) {\n return o1.getName().compareTo(o2.getName());\n }\n}\n\nThen you can use this Comparator to sort a list of Firebase data objects before it is used to populate the RecyclerView:\nList dataList = ... // get list of Firebase data objects\nCollections.sort(dataList, new FirebaseDataComparator());\n// use dataList to populate RecyclerView\n",
"Just as hassan bazai said I followed the same concept of comparing two dates\nclass FirebaseDataComparator : Comparator<GroupNoticeData?> {\n override fun compare(p0: GroupNoticeData?, p1: GroupNoticeData?): Int {\n\n val dateFormat = SimpleDateFormat(\"dd/MM/yyyy\")\n\n val firstDate: Date = dateFormat.parse(p0?.taskdate!!) as Date\n val secondDate: Date = dateFormat.parse(p1?.taskdate!!) as Date\n\n return firstDate.compareTo(secondDate)\n }\n}\n\nHere groupNoticeData is the data class I am using to populate the data in my recycler View and took two objects of them . Parsed their date format accordingly and later on compared them.\nAnd in the recyclerViewAdapter before adding my data, I sorted them using the comparator class and added them later on. Here is the part where I had to use the comparator class.\nfun updateNoticeList(notices: List<GroupNoticeData>) {\n Collections.sort(notices, FirebaseDataComparator())\n this.tasks.clear()\n this.tasks.addAll(notices)\n\n notifyDataSetChanged()\n\n }\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"android_mvvm",
"android_recyclerview",
"firebase_realtime_database",
"kotlin",
"sorting"
] |
stackoverflow_0074666795_android_mvvm_android_recyclerview_firebase_realtime_database_kotlin_sorting.txt
|
Q:
How to have more than 6 row-cols?
I am trying to have 9 columns per row using row-cols-*, but it doesn't work with more than 6:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row row-cols-lg-9 row-cols-md-9 row-cols-sm-9 row-cols-9 text-center">
<div>Item1</div>
<div>Item2</div>
<div>Item3</div>
<div>Item4</div>
<div>Item5</div>
<div>Item6</div>
<div>Item7</div>
<div>Item8</div>
<div>Item9</div>
<div>Item10</div>
<div>Item11</div>
<div>Item12</div>
<div>Item13</div>
<div>Item14</div>
<div>Item15</div>
</div>
How can I use more than 6? I need 9 in my case. I thought I could have up to 12.
A:
The row-cols-* class that you are using is not designed to support more than 6 columns per row. This class is part of the Bootstrap grid system, which is a responsive layout system that uses a 12-column grid to create layouts that adapt to different screen sizes.
The row-cols-* class is used to specify the number of columns that should be used for each item in the row, and it is designed to be used with values between 1 and 6. For example, if you specify row-cols-4, each item in the row will be displayed in a 4-column grid, and the items will be automatically distributed across the row.
If you want to use more than 6 columns per row, you can use the col-* class to specify the number of columns that each item should occupy. This class is part of the Bootstrap grid system and can be used to create custom grid layouts. For example, if you want to create a 9-column layout, you could use the col-3 class for each item in the row, which will cause each item to occupy 3 columns in the grid.
A:
Yes, you are correct. If you are adding items dynamically, you will need to keep track of the current number of columns and the screen size, and adjust the classes on your elements accordingly.
Here is an example of how you could do this:
// Define the number of columns per screen size
const numColumns = {
xs: 3,
sm: 6,
md: 9,
lg: 12,
};
// Keep track of the current number of columns
let currentColumns = 0;
// Add an item to the grid
function addItem() {
// Create a new "item" element
const item = document.createElement("div");
item.classList.add("item");
// Set the appropriate column classes based on the current number of columns
// and the screen size
if (currentColumns === 0) {
item.classList.add("col-xs-12");
item.classList.add("col-sm-6");
item.classList.add("col-md-4");
item.classList.add("col-lg-3");
} else if (currentColumns < numColumns.sm) {
item.classList.add("col-sm-6");
item.classList.add("col-md-4");
item.classList.add("col-lg-3");
} else if (currentColumns < numColumns.md) {
item.classList.add("col-md-4");
item.classList.add("col-lg-3");
} else {
item.classList.add("col-lg-3");
}
// Add the item to the grid
const grid = document.getElementById("grid");
grid.appendChild(item);
// Increment the current number of columns
currentColumns++;
}
This code defines an object that specifies the number of columns per screen size (numColumns), and a variable that keeps track of the current number of columns (currentColumns). The addItem function creates a new div element and sets the appropriate classes based on the current
|
How to have more than 6 row-cols?
|
I am trying to have 9 columns per row using row-cols-*, but it doesn't work with more than 6:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row row-cols-lg-9 row-cols-md-9 row-cols-sm-9 row-cols-9 text-center">
<div>Item1</div>
<div>Item2</div>
<div>Item3</div>
<div>Item4</div>
<div>Item5</div>
<div>Item6</div>
<div>Item7</div>
<div>Item8</div>
<div>Item9</div>
<div>Item10</div>
<div>Item11</div>
<div>Item12</div>
<div>Item13</div>
<div>Item14</div>
<div>Item15</div>
</div>
How can I use more than 6? I need 9 in my case. I thought I could have up to 12.
|
[
"The row-cols-* class that you are using is not designed to support more than 6 columns per row. This class is part of the Bootstrap grid system, which is a responsive layout system that uses a 12-column grid to create layouts that adapt to different screen sizes.\nThe row-cols-* class is used to specify the number of columns that should be used for each item in the row, and it is designed to be used with values between 1 and 6. For example, if you specify row-cols-4, each item in the row will be displayed in a 4-column grid, and the items will be automatically distributed across the row.\nIf you want to use more than 6 columns per row, you can use the col-* class to specify the number of columns that each item should occupy. This class is part of the Bootstrap grid system and can be used to create custom grid layouts. For example, if you want to create a 9-column layout, you could use the col-3 class for each item in the row, which will cause each item to occupy 3 columns in the grid.\n",
"Yes, you are correct. If you are adding items dynamically, you will need to keep track of the current number of columns and the screen size, and adjust the classes on your elements accordingly.\nHere is an example of how you could do this:\n// Define the number of columns per screen size\nconst numColumns = {\n xs: 3,\n sm: 6,\n md: 9,\n lg: 12,\n};\n\n// Keep track of the current number of columns\nlet currentColumns = 0;\n\n// Add an item to the grid\nfunction addItem() {\n // Create a new \"item\" element\n const item = document.createElement(\"div\");\n item.classList.add(\"item\");\n\n // Set the appropriate column classes based on the current number of columns\n // and the screen size\n if (currentColumns === 0) {\n item.classList.add(\"col-xs-12\");\n item.classList.add(\"col-sm-6\");\n item.classList.add(\"col-md-4\");\n item.classList.add(\"col-lg-3\");\n } else if (currentColumns < numColumns.sm) {\n item.classList.add(\"col-sm-6\");\n item.classList.add(\"col-md-4\");\n item.classList.add(\"col-lg-3\");\n } else if (currentColumns < numColumns.md) {\n item.classList.add(\"col-md-4\");\n item.classList.add(\"col-lg-3\");\n } else {\n item.classList.add(\"col-lg-3\");\n }\n\n // Add the item to the grid\n const grid = document.getElementById(\"grid\");\n grid.appendChild(item);\n\n // Increment the current number of columns\n currentColumns++;\n}\n\nThis code defines an object that specifies the number of columns per screen size (numColumns), and a variable that keeps track of the current number of columns (currentColumns). The addItem function creates a new div element and sets the appropriate classes based on the current\n"
] |
[
0,
0
] |
[] |
[] |
[
"bootstrap_5",
"twitter_bootstrap"
] |
stackoverflow_0074667901_bootstrap_5_twitter_bootstrap.txt
|
Q:
How do I copy file from docker container to dockerfile building stage
I want to copy some files from another docker container to my dockerfile building stage like this.
FROM linux/optimize as building_stage
COPY {container_id}:/some_file /var/root
I have tried specifying container_id but it didn't work. how can I copy file from another container?
A:
Copying from running container to image does not seem possible.
Two ways this can be achieved
If some_file exists in the image (not created by container)
COPY --from=<Image Name>:<tag> /some_file /var/root
some_file was created after container creation (docker run): copy some_file from container volumes,
COPY /container/volume/with/some_file /var/root
If the volume is not known then just copy some_file to . before docker build
Dockerfile
FROM linux/optimize as building_stage
COPY ./some_file /var/root
docker cp SOME_FILE_CONTAINER:/some_file .
docker build
|
How do I copy file from docker container to dockerfile building stage
|
I want to copy some files from another docker container to my dockerfile building stage like this.
FROM linux/optimize as building_stage
COPY {container_id}:/some_file /var/root
I have tried specifying container_id but it didn't work. how can I copy file from another container?
|
[
"Copying from running container to image does not seem possible.\nTwo ways this can be achieved\n\nIf some_file exists in the image (not created by container)\n\nCOPY --from=<Image Name>:<tag> /some_file /var/root\n\n\nsome_file was created after container creation (docker run): copy some_file from container volumes,\n\nCOPY /container/volume/with/some_file /var/root\n\nIf the volume is not known then just copy some_file to . before docker build\nDockerfile\nFROM linux/optimize as building_stage\nCOPY ./some_file /var/root\n\ndocker cp SOME_FILE_CONTAINER:/some_file .\ndocker build\n\n"
] |
[
1
] |
[] |
[] |
[
"docker",
"dockerfile"
] |
stackoverflow_0074668250_docker_dockerfile.txt
|
Q:
How should queryset be set for related fields
I have two models named book and chapter. each book can have many chapters, so models are like:
class Book(models.Model):
title = models.CharField(max_length=100)
class Chapter(models.Model):
title = models.CharField(max_length=100)
book = models.ForeignKey("books.Book", on_delete=models.CASCADE)
and serializers are like:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ["title"]
class ChapterSerializer(serializers.ModelSerializer):
book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all())
class Meta:
model = Chapter
fields = ["title", "chapter_number", "text", "book"]
So my question is here: Is it OK to set queryset=Book.objects.all()) for related field?
I mean, if the number of books gets bigger, wouldn't be any problem to query all the books to set the right book?
A:
Serializers can be nested.
class ChapterSerializer(serializers.ModelSerializer):
book = BookSerializer(read_only=True)
class Meta:
model = Chapter
fields = ["title", "chapter_number", "text", "book"]
|
How should queryset be set for related fields
|
I have two models named book and chapter. each book can have many chapters, so models are like:
class Book(models.Model):
title = models.CharField(max_length=100)
class Chapter(models.Model):
title = models.CharField(max_length=100)
book = models.ForeignKey("books.Book", on_delete=models.CASCADE)
and serializers are like:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ["title"]
class ChapterSerializer(serializers.ModelSerializer):
book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all())
class Meta:
model = Chapter
fields = ["title", "chapter_number", "text", "book"]
So my question is here: Is it OK to set queryset=Book.objects.all()) for related field?
I mean, if the number of books gets bigger, wouldn't be any problem to query all the books to set the right book?
|
[
"Serializers can be nested.\nclass ChapterSerializer(serializers.ModelSerializer):\n book = BookSerializer(read_only=True)\n class Meta:\n model = Chapter\n fields = [\"title\", \"chapter_number\", \"text\", \"book\"]\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_model_field",
"django_models",
"django_rest_framework",
"django_serializer"
] |
stackoverflow_0074667607_django_django_model_field_django_models_django_rest_framework_django_serializer.txt
|
Q:
CSS Grid on 100vh screen disturbing the layout on mobile devices when clicking input field virtual keyboard opened
I am working on designing Web Application which wants only 100% of screen means not to scroll, that's why am using 100vh . In which having some input fields, its working fine on the desktop but when i am clicking on input field on Mobiles and Tablets there keyboard is opening by which layout is getting effected Click how its working. Anyone can help me that how can i handle this situation using CSS or JS, So that the layout is also correct and can be typed on the keyboard as well.. Thanks in advance.
Here is a link click here to know what is happening.
The way I tried is that when the input field is active then the screen size which is being compressing will add 250px height for particular devices.
const documentHeight = () => {
const doc = document.documentElement;
const platforms = ["Android", "Linux", "arm"];
const isAndroid = new RegExp(platforms.join("|")).test(
window.navigator.userAgent
);
if (!isAndroid)
document.addEventListener("touchmove", function (event) {
event.preventDefault();
});
if (window.innerHeight < 667 && isAndroid) height = 250;
else height = 0;
doc.style.setProperty(
"--doc-height",
`${window.innerHeight + height}px`
);
};
window.addEventListener("resize", documentHeight);
let htmlTag = document.getElementsByTagName("html");
let root = document.getElementById("root");
{
if (width <= 768) {
documentHeight();
htmlTag[0].style.position = "fixed";
htmlTag[0].style.overflow = "hidden";
htmlTag[0].style.width = "100vw";
}
} else {
const doc = document.documentElement;
doc.style.removeProperty("--doc-height");
}
});
A:
Your Layout also completely overlapping, if opening this site on mobile in landscape mode. You are trying to fit a lot of Informations to a small space.
In my opinion, there are two possibilities.
First would be to pass your wish, to accomplish fit everything at 100vh. Nearly all pages are not only 100vh. And your page won't look worse if you do this.
Second would be to hide the about, main and footer content on mobile, and if you click on each of them, they will flip up the content.
#EDIT:
Probably your wish:
first checking for media querys (the best option, because user agent detection is not good for modern websited) You could also watch here and add other things to detect a mobile.
then adding an eventlitener to the inputs, if they are active => add some space.
const media = window.matchMedia("(max-width: 600px)");
if (media.matches) {
const container_fluid = document.querySelector(".container-fluid");
const inputs = document.querySelectorAll("input");
inputs.forEach((input) => {
input.addEventListener("focus", () => {
container_fluid.setAttribute(
"style",
"height:" + (window.innerHeight + 100) + "px;"
);
});
input.addEventListener("blur", () => {
container_fluid.setAttribute("style", "height: 100vh;");
});
});
}
Hope i could help.
|
CSS Grid on 100vh screen disturbing the layout on mobile devices when clicking input field virtual keyboard opened
|
I am working on designing Web Application which wants only 100% of screen means not to scroll, that's why am using 100vh . In which having some input fields, its working fine on the desktop but when i am clicking on input field on Mobiles and Tablets there keyboard is opening by which layout is getting effected Click how its working. Anyone can help me that how can i handle this situation using CSS or JS, So that the layout is also correct and can be typed on the keyboard as well.. Thanks in advance.
Here is a link click here to know what is happening.
The way I tried is that when the input field is active then the screen size which is being compressing will add 250px height for particular devices.
const documentHeight = () => {
const doc = document.documentElement;
const platforms = ["Android", "Linux", "arm"];
const isAndroid = new RegExp(platforms.join("|")).test(
window.navigator.userAgent
);
if (!isAndroid)
document.addEventListener("touchmove", function (event) {
event.preventDefault();
});
if (window.innerHeight < 667 && isAndroid) height = 250;
else height = 0;
doc.style.setProperty(
"--doc-height",
`${window.innerHeight + height}px`
);
};
window.addEventListener("resize", documentHeight);
let htmlTag = document.getElementsByTagName("html");
let root = document.getElementById("root");
{
if (width <= 768) {
documentHeight();
htmlTag[0].style.position = "fixed";
htmlTag[0].style.overflow = "hidden";
htmlTag[0].style.width = "100vw";
}
} else {
const doc = document.documentElement;
doc.style.removeProperty("--doc-height");
}
});
|
[
"Your Layout also completely overlapping, if opening this site on mobile in landscape mode. You are trying to fit a lot of Informations to a small space.\nIn my opinion, there are two possibilities.\nFirst would be to pass your wish, to accomplish fit everything at 100vh. Nearly all pages are not only 100vh. And your page won't look worse if you do this.\nSecond would be to hide the about, main and footer content on mobile, and if you click on each of them, they will flip up the content.\n#EDIT:\nProbably your wish:\nfirst checking for media querys (the best option, because user agent detection is not good for modern websited) You could also watch here and add other things to detect a mobile.\nthen adding an eventlitener to the inputs, if they are active => add some space.\nconst media = window.matchMedia(\"(max-width: 600px)\");\nif (media.matches) {\n const container_fluid = document.querySelector(\".container-fluid\");\n const inputs = document.querySelectorAll(\"input\");\n\n inputs.forEach((input) => {\n input.addEventListener(\"focus\", () => {\n container_fluid.setAttribute(\n \"style\",\n \"height:\" + (window.innerHeight + 100) + \"px;\"\n );\n });\n input.addEventListener(\"blur\", () => {\n container_fluid.setAttribute(\"style\", \"height: 100vh;\");\n });\n });\n}\n\nHope i could help.\n"
] |
[
0
] |
[] |
[] |
[
"css",
"html",
"javascript",
"jquery",
"reactjs"
] |
stackoverflow_0074667866_css_html_javascript_jquery_reactjs.txt
|
Q:
Highlight text in different colors - TextField in Flutter
Is there any way to highlight a specific part of a text inside a TextField in flutter like you can do in Microsoft Word?
Something like this but inside a Text Field in my flutter app:
A:
The simplest way appears to be using a series of styled TextSpans.
Marc on Flutter Clutter has a really good tutorial on this:
https://www.flutterclutter.dev/flutter/tutorials/styling-parts-of-a-textfield/2021/101326/
|
Highlight text in different colors - TextField in Flutter
|
Is there any way to highlight a specific part of a text inside a TextField in flutter like you can do in Microsoft Word?
Something like this but inside a Text Field in my flutter app:
|
[
"The simplest way appears to be using a series of styled TextSpans.\nMarc on Flutter Clutter has a really good tutorial on this:\nhttps://www.flutterclutter.dev/flutter/tutorials/styling-parts-of-a-textfield/2021/101326/\n"
] |
[
0
] |
[
"Have you specified the textSelectionTheme property in your themes?\n\nTheme(data: Theme.of(context).copyWith(textSelectionTheme: TextSelectionThemeData(selectionColor: Colors.blue.withOpacity(0.5), child: YourTextField() )) ),\n\n"
] |
[
-1
] |
[
"dart",
"flutter",
"highlight",
"text",
"textfield"
] |
stackoverflow_0071818115_dart_flutter_highlight_text_textfield.txt
|
Q:
Blazor httpClient failing to make external API call
I'm trying to make a simple REST API call but it seems security policies are stopping me and I don't know how to fix it. The code makes a call to an open API to get a joke. However I get the following error:
dotnet.6.0.11.pbddgabtj1.js:1 Refused to connect to 'http://api.chucknorris.io/jokes/random' because it violates the document's Content Security Policy.
I have added the content security policy to my header in wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss"></a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
The component that does the call looks like this:
@page "/"
<PageTitle>Index</PageTitle>
<br />
<h4>Joke of the day:</h4>
<p>@joke</p>
@code{
string joke = "No Joke";
private readonly HttpClient clientHttp;
public Index()
{
clientHttp = new HttpClient();
}
protected override async Task OnInitializedAsync(){
var url = new Uri("http://api.chucknorris.io/jokes/random");
joke = "";
try
{
var result = await clientHttp.GetAsync(url);
joke = result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Failed to get the joke. Error: ", e.Message);
}
if (string.IsNullOrEmpty(joke))
joke = "No Joke";
}
}
Any ideas what I'm missing?
A:
Found the answer. You need to whitelist the API call.
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
font-src 'self';
connect-src 'self'
https://api.chucknorris.io/jokes/random;
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
|
Blazor httpClient failing to make external API call
|
I'm trying to make a simple REST API call but it seems security policies are stopping me and I don't know how to fix it. The code makes a call to an open API to get a joke. However I get the following error:
dotnet.6.0.11.pbddgabtj1.js:1 Refused to connect to 'http://api.chucknorris.io/jokes/random' because it violates the document's Content Security Policy.
I have added the content security policy to my header in wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<meta http-equiv="Content-Security-Policy"
content="base-uri 'self';
block-all-mixed-content;
default-src 'self';
img-src data: https:;
object-src 'none';
script-src 'self'
'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='
'unsafe-eval';
style-src 'self'
'unsafe-inline';
upgrade-insecure-requests;">
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss"></a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
The component that does the call looks like this:
@page "/"
<PageTitle>Index</PageTitle>
<br />
<h4>Joke of the day:</h4>
<p>@joke</p>
@code{
string joke = "No Joke";
private readonly HttpClient clientHttp;
public Index()
{
clientHttp = new HttpClient();
}
protected override async Task OnInitializedAsync(){
var url = new Uri("http://api.chucknorris.io/jokes/random");
joke = "";
try
{
var result = await clientHttp.GetAsync(url);
joke = result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Failed to get the joke. Error: ", e.Message);
}
if (string.IsNullOrEmpty(joke))
joke = "No Joke";
}
}
Any ideas what I'm missing?
|
[
"Found the answer. You need to whitelist the API call.\n<meta http-equiv=\"Content-Security-Policy\"\n content=\"base-uri 'self';\n block-all-mixed-content;\n default-src 'self';\n font-src 'self';\n connect-src 'self' \n https://api.chucknorris.io/jokes/random;\n img-src data: https:;\n object-src 'none';\n script-src 'self'\n 'sha256-v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA='\n 'unsafe-eval';\n style-src 'self'\n 'unsafe-inline';\n upgrade-insecure-requests;\">\n\n"
] |
[
0
] |
[] |
[] |
[
"api",
"blazor",
"dotnet_httpclient",
"rest"
] |
stackoverflow_0074666226_api_blazor_dotnet_httpclient_rest.txt
|
Q:
My data show up 2 twice whil use function? Operation file C++ - Case: Delete Specific Line in c++
I got a task that is:
Write a simple program that can be used to delete data on one
one line specified in a file with the following steps:
Manually create a file containing:
i. Fill from line 1
ii. Fill from line 2
ii. Fill from line 3
iv. Fill in line 4
Display the entire contents of the file.
Appears the choice of how many rows to delete.
Delete data in the selected row.
Display the entire contents of the file.
I have created the program as below:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Function Prototipe
void garis();
void show_databefore();
void show_data();
void del_line(const char *file_name, int n);
// Variable Declaration
int n;
ifstream myFile;
string output,buffer;
// Main Function
int main(){
cout << "Show data and delete specific line Program " << endl;
garis ();
cout << "The Data " << endl;
show_databefore();
garis();
cout << "Select the Rows of data you want to delete: ";
cin >> n;
cout << "\nBefore " << endl;
// If Case after input n
if((0 < n) && (n < 100)){
del_line("data1.txt", n); // this process will delete the row that has been selected.
} else {
cout << "Error" << endl;}
show_data(); // when calling this function. Display on the console, data is displayed 2 times.
return 0;
}
//Function to delete data in the row that has been selected
void del_line(const char *file_name, int n){
ifstream fin(file_name);
ofstream fout;
fout.open("temp.txt", ios::out);
char ch;
int line = 1;
while(fin.get(ch))
{
if(ch == '\n')
line++;
if(line != n)
fout<<ch;
}
fout.close();
fin.close();
remove(file_name);
rename("temp.txt", file_name);
}
// Function to display data1.txt to the console
void show_databefore(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output << endl;
myFile.close();
}
// Function to display data1.txt to the console T
// This fuction actually same as show_databefore.
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
//Function to provide a boundary line.
void garis(){
cout << "======================================================= " << endl << endl;
}
When I run my program it works, but when I bring up data to the console, my data appears 2 times and I've tried the method without using the function. However, the result remains the same.
Here is the result
Can anyone help me? Or maybe there's an easier way to build my program? Thank you
A:
This code is bugged in two different ways
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
The first bug is the incorrect use of eof. The second bug is the use of the global variable output. The code assumes that the variable is an empty string when the function is entered, but because it's a global variable there is no way to ensure this. Here's a fixed version, the global variable is now a local variable and the eof problem has been fixed.
void show_data(){
string output; // local variable
myFile.open("data1.txt");
while (getline(myFile,buffer)){
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
Don't needlessly use global variables, they are a huge source of bugs, as well as many other problems. There are several others in your code. They should all be removed.
|
My data show up 2 twice whil use function? Operation file C++ - Case: Delete Specific Line in c++
|
I got a task that is:
Write a simple program that can be used to delete data on one
one line specified in a file with the following steps:
Manually create a file containing:
i. Fill from line 1
ii. Fill from line 2
ii. Fill from line 3
iv. Fill in line 4
Display the entire contents of the file.
Appears the choice of how many rows to delete.
Delete data in the selected row.
Display the entire contents of the file.
I have created the program as below:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Function Prototipe
void garis();
void show_databefore();
void show_data();
void del_line(const char *file_name, int n);
// Variable Declaration
int n;
ifstream myFile;
string output,buffer;
// Main Function
int main(){
cout << "Show data and delete specific line Program " << endl;
garis ();
cout << "The Data " << endl;
show_databefore();
garis();
cout << "Select the Rows of data you want to delete: ";
cin >> n;
cout << "\nBefore " << endl;
// If Case after input n
if((0 < n) && (n < 100)){
del_line("data1.txt", n); // this process will delete the row that has been selected.
} else {
cout << "Error" << endl;}
show_data(); // when calling this function. Display on the console, data is displayed 2 times.
return 0;
}
//Function to delete data in the row that has been selected
void del_line(const char *file_name, int n){
ifstream fin(file_name);
ofstream fout;
fout.open("temp.txt", ios::out);
char ch;
int line = 1;
while(fin.get(ch))
{
if(ch == '\n')
line++;
if(line != n)
fout<<ch;
}
fout.close();
fin.close();
remove(file_name);
rename("temp.txt", file_name);
}
// Function to display data1.txt to the console
void show_databefore(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output << endl;
myFile.close();
}
// Function to display data1.txt to the console T
// This fuction actually same as show_databefore.
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
//Function to provide a boundary line.
void garis(){
cout << "======================================================= " << endl << endl;
}
When I run my program it works, but when I bring up data to the console, my data appears 2 times and I've tried the method without using the function. However, the result remains the same.
Here is the result
Can anyone help me? Or maybe there's an easier way to build my program? Thank you
|
[
"This code is bugged in two different ways\nvoid show_data(){\n myFile.open(\"data1.txt\");\n while (!myFile.eof()){\n getline(myFile,buffer);\n output.append(\"\\n\" + buffer); \n }\n cout << output;\n myFile.close(); \n}\n\nThe first bug is the incorrect use of eof. The second bug is the use of the global variable output. The code assumes that the variable is an empty string when the function is entered, but because it's a global variable there is no way to ensure this. Here's a fixed version, the global variable is now a local variable and the eof problem has been fixed.\nvoid show_data(){\n string output; // local variable\n myFile.open(\"data1.txt\");\n while (getline(myFile,buffer)){\n output.append(\"\\n\" + buffer); \n }\n cout << output;\n myFile.close(); \n}\n\nDon't needlessly use global variables, they are a huge source of bugs, as well as many other problems. There are several others in your code. They should all be removed.\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"file",
"operation",
"trending"
] |
stackoverflow_0074668134_c++_file_operation_trending.txt
|
Q:
Can't find uninitialised value (valgrind)
So I'm making a queue list and I'm trying to get rid of memory leaks and uninitialised values. But when running with valgrind I keep getting Conditional jump or move depends on uninitialised value(s).
I tried to debug the code and find the error but I can't.
Here is the code I'm running:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct Node{
string item;
Node* next;
Node* prev;
};
struct Queue{
int size;
Node* head = NULL;
Node* tail = NULL;
};
//Makes queue
Queue* createQueue(){
Queue* n = new Queue;
n->head = NULL;
n->tail = NULL;
n->size = 0;
return n;
}
//checks if empty
bool isEmpty(Queue* List){
if( List->size == 0){
return true;
}else{
return false;
}
}
// add item to queue
bool enqueue(Queue* List, string added){
Node* newy= new Node;
if(List->tail == NULL){
List->head = List->tail = newy;
return true;
}
List->tail->next = newy;
List->tail = newy;
List->size++;
return true;
}
//remove item from queue
string dequeue(Queue* List){
Node* tempo = List->head;
if(List->head == NULL){
return "ERROR";
}
else if (tempo->next !=NULL){
tempo = tempo->next;
return List->head->item;
free(List->head);
List->head = tempo;
}else{
return List->head->item;
free(List->head);
List->head= NULL;
List->tail = NULL;
}
}
// display the queue
void print(Queue* List){
Node* yuuur = List->head;
while(yuuur != NULL){
cout<<(yuuur->item)<<endl;
yuuur = yuuur->next;
}
}
// destroy queue
void destroyQueue(Queue* List){
while(List->head !=NULL){
Node *tempo = List->head;
List->head= List->head->next;
delete tempo;
}
List->tail = NULL;
List->head = NULL;
delete List;
}
My main to test the code:
//test code
int main(){
Queue* q = createQueue();
cout << boolalpha << isEmpty(q) << endl;
cout << dequeue(q) << endl;
enqueue(q, "Jos");
enqueue(q ,"An");
enqueue(q, "Peter");
print(q); //Jos, An en Peter worden op drie regels geprint
string first = dequeue(q);
cout << first << endl; //Jos wordt geprint
print(q); //An en Peter worden geprint
destroyQueue(q);
return 0;
}
Valgrind error:
==77== Memcheck, a memory error detector
==77== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==77== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==77== Command: student/labo13
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401002: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x40103F: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401097: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400E23: destroyQueue(Queue*) (in /task/student/labo13)
==77== by 0x4010A3: main (in /task/student/labo13)
==77==
==77==
==77== HEAP SUMMARY:
==77== in use at exit: 0 bytes in 0 blocks
==77== total heap usage: 10 allocs, 10 frees, 263 bytes allocated
==77==
==77== All heap blocks were freed -- no leaks are possible
==77==
==77== For counts of detected and suppressed errors, rerun with: -v
==77== Use --track-origins=yes to see where uninitialised values come from
==77== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
A:
In enqueue function, you do:
Node* newy= new Node;
if(List->tail == NULL){
List->head = List->tail = newy;
return true;
}
At this point, newy is a newly initialized Node object; however, none of its members have been set. You also don't adjust the size of the Queue.
Secondly, let's say that tail is not NULL, then you do:
List->tail->next = newy;
List->tail = newy;
List->size++;
return true;
Again, at this point, newy does not have any of its members set.
What you probably want to do is (I didn't try it):
bool enqueue(Queue* List, const string &added){
Node* newy= new Node;
newy->item = added;
newy->next = nullptr;
newy->prev = List->tail;
List->size++;
if(List->tail == nullptr){
List->head = List->tail = newy;
return true;
}
List->tail->next = newy;
List->tail = newy;
return true;
}
On another note, it seems like you are trying to treat C++ like it' C. You should use proper classes and member functions.
|
Can't find uninitialised value (valgrind)
|
So I'm making a queue list and I'm trying to get rid of memory leaks and uninitialised values. But when running with valgrind I keep getting Conditional jump or move depends on uninitialised value(s).
I tried to debug the code and find the error but I can't.
Here is the code I'm running:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct Node{
string item;
Node* next;
Node* prev;
};
struct Queue{
int size;
Node* head = NULL;
Node* tail = NULL;
};
//Makes queue
Queue* createQueue(){
Queue* n = new Queue;
n->head = NULL;
n->tail = NULL;
n->size = 0;
return n;
}
//checks if empty
bool isEmpty(Queue* List){
if( List->size == 0){
return true;
}else{
return false;
}
}
// add item to queue
bool enqueue(Queue* List, string added){
Node* newy= new Node;
if(List->tail == NULL){
List->head = List->tail = newy;
return true;
}
List->tail->next = newy;
List->tail = newy;
List->size++;
return true;
}
//remove item from queue
string dequeue(Queue* List){
Node* tempo = List->head;
if(List->head == NULL){
return "ERROR";
}
else if (tempo->next !=NULL){
tempo = tempo->next;
return List->head->item;
free(List->head);
List->head = tempo;
}else{
return List->head->item;
free(List->head);
List->head= NULL;
List->tail = NULL;
}
}
// display the queue
void print(Queue* List){
Node* yuuur = List->head;
while(yuuur != NULL){
cout<<(yuuur->item)<<endl;
yuuur = yuuur->next;
}
}
// destroy queue
void destroyQueue(Queue* List){
while(List->head !=NULL){
Node *tempo = List->head;
List->head= List->head->next;
delete tempo;
}
List->tail = NULL;
List->head = NULL;
delete List;
}
My main to test the code:
//test code
int main(){
Queue* q = createQueue();
cout << boolalpha << isEmpty(q) << endl;
cout << dequeue(q) << endl;
enqueue(q, "Jos");
enqueue(q ,"An");
enqueue(q, "Peter");
print(q); //Jos, An en Peter worden op drie regels geprint
string first = dequeue(q);
cout << first << endl; //Jos wordt geprint
print(q); //An en Peter worden geprint
destroyQueue(q);
return 0;
}
Valgrind error:
==77== Memcheck, a memory error detector
==77== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==77== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==77== Command: student/labo13
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401002: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x40103F: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401097: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400E23: destroyQueue(Queue*) (in /task/student/labo13)
==77== by 0x4010A3: main (in /task/student/labo13)
==77==
==77==
==77== HEAP SUMMARY:
==77== in use at exit: 0 bytes in 0 blocks
==77== total heap usage: 10 allocs, 10 frees, 263 bytes allocated
==77==
==77== All heap blocks were freed -- no leaks are possible
==77==
==77== For counts of detected and suppressed errors, rerun with: -v
==77== Use --track-origins=yes to see where uninitialised values come from
==77== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
|
[
"In enqueue function, you do:\n Node* newy= new Node;\n if(List->tail == NULL){\n List->head = List->tail = newy;\n return true;\n }\n\nAt this point, newy is a newly initialized Node object; however, none of its members have been set. You also don't adjust the size of the Queue.\nSecondly, let's say that tail is not NULL, then you do:\n List->tail->next = newy;\n List->tail = newy;\n List->size++;\n return true;\n\nAgain, at this point, newy does not have any of its members set.\nWhat you probably want to do is (I didn't try it):\nbool enqueue(Queue* List, const string &added){\n Node* newy= new Node;\n newy->item = added;\n newy->next = nullptr;\n newy->prev = List->tail;\n List->size++;\n if(List->tail == nullptr){\n List->head = List->tail = newy;\n return true;\n }\n List->tail->next = newy;\n List->tail = newy;\n return true;\n}\n\n\nOn another note, it seems like you are trying to treat C++ like it' C. You should use proper classes and member functions.\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"memory",
"queue"
] |
stackoverflow_0074668400_c++_memory_queue.txt
|
Q:
Cutting an array into consistent pieces of any size, with recursion
The problem is to, given an array, write a generator function that will yield all combinations of cutting the array into consistent pieces(arrays of elements that are consecutive in the given array) of any size and which together make up the whole given array. The elements in any one of the combinations don't have to be of the same size.
For example given an array [1,2,3,4] I want to yield:
[[1],[2],[3],[4]]
[[1,2],[3],[4]]
[[1],[2,3],[4]]
[[1],[2],[3,4]]
[[1,2],[3,4]]
[[1],[2,3,4]]
[[1,2,3],[4]]
[[1,2,3,4]]
def powerset_but_consistent(T):
if len(T)==0:
return
for el in T:
yield el
for k in range(len(el)):
yield ([el[:k],el[k:]])
#for l in range(k, len(el)):
# yield ([el[:k],el[k:l],el[l:]])
powerset_but_consistent([T[:k],T[k:]])
T = [[1,2,3,4,5]]
subsets = [x for x in powerset_but_consistent(T)]
for i in subsets:
print(i)
And this prints only those combinations that are made of two arrays. If I uncomment what I commented then it will also print combinations consisting of 3 arrays. If I add another inner for loop, it will print those combinations consisting of 4 arrays and so on... How can I use recursion instead of infinite inner for loops? Is it time for using something like:
for x in powerset_but_consistent(T[some_slicing] or something else) ?
I find it difficult to understand this construction. Can anyone help?
A:
One of the algorithm commonly used for these type of questions (permutations and combinations) is using depth-first-search (DFS). Here's a link to a more similar but harder leetcode problem on palindrome partitioning that uses backtracking and DFS. My solution is based off of that leetcode post.
Algorithm
If my explanation is not enough go through the leetcode link provided above it may make sense.
The general idea is iteration through the list and get all the combinations from current element by resursively traversing through the remaining elements after the current elements.
Pseudocode
function recursive (list)
recurise condition
yield child
for element in remaining-elements:
// Get the combinations from all elements start from 'element'
partitions = recursive (...)
// join the list of elements already explored with the provided combinations
for every child from partitions:
yield combination_before + child
The major concept through this is using Depth-First-Search, and maybe figuring out the recursive condition as that really took me a while when.
You can also optimize the code by storing the results of the deep recursive operations in a dictionary and access them when you revisit over in the next iterations. I'm also pretty sure there is some optimal dynamic programming solution for this somewhere out there. Goodluck, hope this helped
Edit: My bad, I realised i had the actual solution before the edit, had no idea that may slighty conflict with individual community guidelines.
|
Cutting an array into consistent pieces of any size, with recursion
|
The problem is to, given an array, write a generator function that will yield all combinations of cutting the array into consistent pieces(arrays of elements that are consecutive in the given array) of any size and which together make up the whole given array. The elements in any one of the combinations don't have to be of the same size.
For example given an array [1,2,3,4] I want to yield:
[[1],[2],[3],[4]]
[[1,2],[3],[4]]
[[1],[2,3],[4]]
[[1],[2],[3,4]]
[[1,2],[3,4]]
[[1],[2,3,4]]
[[1,2,3],[4]]
[[1,2,3,4]]
def powerset_but_consistent(T):
if len(T)==0:
return
for el in T:
yield el
for k in range(len(el)):
yield ([el[:k],el[k:]])
#for l in range(k, len(el)):
# yield ([el[:k],el[k:l],el[l:]])
powerset_but_consistent([T[:k],T[k:]])
T = [[1,2,3,4,5]]
subsets = [x for x in powerset_but_consistent(T)]
for i in subsets:
print(i)
And this prints only those combinations that are made of two arrays. If I uncomment what I commented then it will also print combinations consisting of 3 arrays. If I add another inner for loop, it will print those combinations consisting of 4 arrays and so on... How can I use recursion instead of infinite inner for loops? Is it time for using something like:
for x in powerset_but_consistent(T[some_slicing] or something else) ?
I find it difficult to understand this construction. Can anyone help?
|
[
"One of the algorithm commonly used for these type of questions (permutations and combinations) is using depth-first-search (DFS). Here's a link to a more similar but harder leetcode problem on palindrome partitioning that uses backtracking and DFS. My solution is based off of that leetcode post.\nAlgorithm\nIf my explanation is not enough go through the leetcode link provided above it may make sense.\nThe general idea is iteration through the list and get all the combinations from current element by resursively traversing through the remaining elements after the current elements.\nPseudocode\nfunction recursive (list)\n recurise condition\n yield child\n \n for element in remaining-elements:\n // Get the combinations from all elements start from 'element'\n partitions = recursive (...)\n\n // join the list of elements already explored with the provided combinations\n for every child from partitions:\n yield combination_before + child\n\n\nThe major concept through this is using Depth-First-Search, and maybe figuring out the recursive condition as that really took me a while when.\nYou can also optimize the code by storing the results of the deep recursive operations in a dictionary and access them when you revisit over in the next iterations. I'm also pretty sure there is some optimal dynamic programming solution for this somewhere out there. Goodluck, hope this helped\nEdit: My bad, I realised i had the actual solution before the edit, had no idea that may slighty conflict with individual community guidelines.\n"
] |
[
0
] |
[] |
[] |
[
"generator",
"multidimensional_array",
"python",
"recursion"
] |
stackoverflow_0074667555_generator_multidimensional_array_python_recursion.txt
|
Q:
How can i get the correct qty with FIFO? PHP
everytime i process in my Sales how can i trigger to get the sum and not only the first row of the table i want i have the same product name and qty this is my product inventory
example is that i have a qty of 50 and in item 2 i have 100 like this
name
qty
date
milktea
50
december 3 2022
milktea
100
december 1 2022
and in my SALES if i enter 140 it must supposed to be
name
qty
date
milktea
0
december 3 2022
milktea
10
december 1 2022
but instead it just remove the first qty and the second 1 remain like this
name
qty
date
milktea
0
december 3 2022
milktea
100
december 1 2022
my code is here
public function update($id)
{
if($id) {
$user_id = $this->session->userdata('id');
$user_data = $this->model_users->getUserData($user_id);
// update the table info
$order_data = $this->getOrdersData($id);
$data = $this->model_tables->update($order_data['table_id'], array('available' => 1));
if($this->input->post('paid_status') == 1) {
$this->model_tables->update($this->input->post('table_name'), array('available' => 1));
}
else {
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
}
$data = array(
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => ($this->input->post('change_value') > 0) ? $this->input->post('paid_status') : 2,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'cash_tendered' => $this->input->post('cash_tendered'),
'total_change' => ($this->input->post('change_value') > 0) ? $this->input->post('change_value') : 0,
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'remarks' => $this->input->post('remarks'),
);
$this->db->where('id', $id);
$update = $this->db->update('orders', $data);
// now remove the order item data
$this->db->where('order_id', $id);
$this->db->delete('order_items');
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
$prodid = $this->input->post('product')[$x];
$product_data = $this->model_products->getProductData([$prodid]);
$prodname = $product_data['name'];
$inputQuantity = (int)$this->input->post('qty')[$x];
$this->db->where('qty >', 0);
$this->db->order_by('expiration_date', 'ASC');
$this->db->limit(1);
$this->db->set('qty', "qty-$inputQuantity", false);
$this->db->update('product_inventory');
}
return true;
}
}
A:
It looks like the issue you are having is that your code is not properly updating the quantities in the order_items table. In your code, you are looping through each item in the order and updating the order_items table with the new quantity. However, you are not taking into account the fact that the same product may appear multiple times in the order.
One way to solve this problem would be to loop through the order items and update the quantity for each item, but also keep track of the total quantity for each product. Then, at the end of the loop, you can update the order_items table with the correct quantity for each product.
Here is an example of how this could be done:
Copy code
// Loop through the order items and keep track of the total quantity for each product
$product_quantities = array();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$product_id = $this->input->post('product')[$x];
$qty = $this->input->post('qty')[$x];
// If this is the first time we are seeing this product, initialize its quantity to 0
if (!isset($product_quantities[$product_id])) {
$product_quantities[$product_id] = 0;
}
// Add the quantity of this item to the total quantity for this product
$product_quantities[$product_id] += $qty;
}
// Loop through the product quantities and update the `order_items` table
foreach ($product_quantities as $product_id => $qty) {
$data = array(
'qty' => $qty
);
$this->db->where('product_id', $product_id);
$this->db->where('order_id', $id);
$this->db->update('order_items', $data);
}
|
How can i get the correct qty with FIFO? PHP
|
everytime i process in my Sales how can i trigger to get the sum and not only the first row of the table i want i have the same product name and qty this is my product inventory
example is that i have a qty of 50 and in item 2 i have 100 like this
name
qty
date
milktea
50
december 3 2022
milktea
100
december 1 2022
and in my SALES if i enter 140 it must supposed to be
name
qty
date
milktea
0
december 3 2022
milktea
10
december 1 2022
but instead it just remove the first qty and the second 1 remain like this
name
qty
date
milktea
0
december 3 2022
milktea
100
december 1 2022
my code is here
public function update($id)
{
if($id) {
$user_id = $this->session->userdata('id');
$user_data = $this->model_users->getUserData($user_id);
// update the table info
$order_data = $this->getOrdersData($id);
$data = $this->model_tables->update($order_data['table_id'], array('available' => 1));
if($this->input->post('paid_status') == 1) {
$this->model_tables->update($this->input->post('table_name'), array('available' => 1));
}
else {
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
}
$data = array(
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => ($this->input->post('change_value') > 0) ? $this->input->post('paid_status') : 2,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'cash_tendered' => $this->input->post('cash_tendered'),
'total_change' => ($this->input->post('change_value') > 0) ? $this->input->post('change_value') : 0,
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'remarks' => $this->input->post('remarks'),
);
$this->db->where('id', $id);
$update = $this->db->update('orders', $data);
// now remove the order item data
$this->db->where('order_id', $id);
$this->db->delete('order_items');
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
$prodid = $this->input->post('product')[$x];
$product_data = $this->model_products->getProductData([$prodid]);
$prodname = $product_data['name'];
$inputQuantity = (int)$this->input->post('qty')[$x];
$this->db->where('qty >', 0);
$this->db->order_by('expiration_date', 'ASC');
$this->db->limit(1);
$this->db->set('qty', "qty-$inputQuantity", false);
$this->db->update('product_inventory');
}
return true;
}
}
|
[
"It looks like the issue you are having is that your code is not properly updating the quantities in the order_items table. In your code, you are looping through each item in the order and updating the order_items table with the new quantity. However, you are not taking into account the fact that the same product may appear multiple times in the order.\nOne way to solve this problem would be to loop through the order items and update the quantity for each item, but also keep track of the total quantity for each product. Then, at the end of the loop, you can update the order_items table with the correct quantity for each product.\nHere is an example of how this could be done:\nCopy code\n// Loop through the order items and keep track of the total quantity for each product\n$product_quantities = array();\n$count_product = count($this->input->post('product'));\nfor($x = 0; $x < $count_product; $x++) {\n $product_id = $this->input->post('product')[$x];\n $qty = $this->input->post('qty')[$x];\n\n // If this is the first time we are seeing this product, initialize its quantity to 0\n if (!isset($product_quantities[$product_id])) {\n $product_quantities[$product_id] = 0;\n }\n\n // Add the quantity of this item to the total quantity for this product\n $product_quantities[$product_id] += $qty;\n}\n\n// Loop through the product quantities and update the `order_items` table\nforeach ($product_quantities as $product_id => $qty) {\n $data = array(\n 'qty' => $qty\n );\n $this->db->where('product_id', $product_id);\n $this->db->where('order_id', $id);\n $this->db->update('order_items', $data);\n}\n\n\n"
] |
[
0
] |
[] |
[] |
[
"codeigniter",
"codeigniter_3",
"mysql",
"php",
"post"
] |
stackoverflow_0074668417_codeigniter_codeigniter_3_mysql_php_post.txt
|
Q:
React 18 is causing a simple menu to stop working as it was previously. Why?
My menu stopped working after I updated to React 18. I am not in strict mode.
The code below used to work as I expected. But now I observed a "strange" effect.
Clicking on the menu icon will correctly "turn on" the menu box. What is bizarre is that when the menu box is turned on, it sets up an event handler to detect clicks on the document.body.
It then detects a second click on the document.body (there is only one click), closing the menu, so in effect you never see the menu. That is, it is now broken.
MenuBox should not even be rendered when Menu.jsx is clicked. Hence the event handler should not even be setup.
Menu
export default () => {
const dispatch = useDispatch();
const menu = useSelector((state)=>state.MenuPage.on);
function clicked() {
console.log('DEBUG: Menu.jsx clicked')
dispatch({type: 'toggleMenuPage'});
}
return (
<div id="menu_hold">
<SVGMenu onClick={clicked} id='menu_top'/>
{menu && <MenuBox/>}
</div>
);
};
Here is the document.body handler in MenuBox.
MenuBox
useEffect(() => {
console.log('DEBUG: MenuBox.jsx useEffect()')
function bodyClicked() {
dispatch({type: 'toggleMenuPageOff'});
}
document.body.addEventListener('click', bodyClicked);
return () => {
document.body.removeEventListener('click', bodyClicked);
};
});
A:
One issue with the code you provided is that you are using an effect inside the MenuBox component to attach an event listener to the document.body element. This is problematic because the effect will be run every time the MenuBox component is rendered, which means that a new event listener will be attached each time.
If you want to attach an event listener to the document.body element that is only attached once, you should do this in a separate component that is only rendered once in your app. This way, the effect that attaches the event listener will only be run once.
You can then use the useRef() hook in the MenuBox component to store a reference to the event listener. This will allow you to remove the event listener when the MenuBox component unmounts.
Here is an example of how you could do this:
// This is a separate component that is only rendered once in your app
const BodyClickListener = () => {
const dispatch = useDispatch();
const listenerRef = useRef(null);
useEffect(() => {
const bodyClicked = () => {
dispatch({type: 'toggleMenuPageOff'});
};
listenerRef.current = bodyClicked;
document.body.addEventListener('click', listenerRef.current);
}, []); // Empty array means this effect only runs once
return null; // This component doesn't render anything
};
// This is the MenuBox component
const MenuBox = () => {
const dispatch = useDispatch();
useEffect(() => {
return () => {
// This will remove the event listener when the component unmounts
document.body.removeEventListener('click', listenerRef.current);
};
}, []); // Empty array means this effect only runs once
return (...); // Your menu box code here
};
Another issue with the code you provided is that the MenuBox component is rendered every time the parent component is rendered. This means that the MenuBox component will be re-created every time the Menu component is rendered, which is likely not what you want.
To fix this, you can move the menu variable outside of the Menu component and use it to conditionally render the MenuBox component. This way, the MenuBox component will only be created once and will only be re-rendered if the menu variable changes.
Here is an example of how you could do this:
const menu = useSelector((state) => state.MenuPage.on);
const Menu = () => {
const dispatch = useDispatch();
function clicked() {
console.log('DEBUG: Menu.jsx clicked')
dispatch({type: 'toggleMenuPage'});
}
return (
<div id="menu_hold">
<SVGMenu onClick={clicked} id='menu_top'/>
{menu && <MenuBox/>}
</div>
);
};
I hope this helps! Let me know if you have any other questions.
|
React 18 is causing a simple menu to stop working as it was previously. Why?
|
My menu stopped working after I updated to React 18. I am not in strict mode.
The code below used to work as I expected. But now I observed a "strange" effect.
Clicking on the menu icon will correctly "turn on" the menu box. What is bizarre is that when the menu box is turned on, it sets up an event handler to detect clicks on the document.body.
It then detects a second click on the document.body (there is only one click), closing the menu, so in effect you never see the menu. That is, it is now broken.
MenuBox should not even be rendered when Menu.jsx is clicked. Hence the event handler should not even be setup.
Menu
export default () => {
const dispatch = useDispatch();
const menu = useSelector((state)=>state.MenuPage.on);
function clicked() {
console.log('DEBUG: Menu.jsx clicked')
dispatch({type: 'toggleMenuPage'});
}
return (
<div id="menu_hold">
<SVGMenu onClick={clicked} id='menu_top'/>
{menu && <MenuBox/>}
</div>
);
};
Here is the document.body handler in MenuBox.
MenuBox
useEffect(() => {
console.log('DEBUG: MenuBox.jsx useEffect()')
function bodyClicked() {
dispatch({type: 'toggleMenuPageOff'});
}
document.body.addEventListener('click', bodyClicked);
return () => {
document.body.removeEventListener('click', bodyClicked);
};
});
|
[
"One issue with the code you provided is that you are using an effect inside the MenuBox component to attach an event listener to the document.body element. This is problematic because the effect will be run every time the MenuBox component is rendered, which means that a new event listener will be attached each time.\nIf you want to attach an event listener to the document.body element that is only attached once, you should do this in a separate component that is only rendered once in your app. This way, the effect that attaches the event listener will only be run once.\nYou can then use the useRef() hook in the MenuBox component to store a reference to the event listener. This will allow you to remove the event listener when the MenuBox component unmounts.\nHere is an example of how you could do this:\n// This is a separate component that is only rendered once in your app\nconst BodyClickListener = () => {\n const dispatch = useDispatch();\n const listenerRef = useRef(null);\n\n useEffect(() => {\n const bodyClicked = () => {\n dispatch({type: 'toggleMenuPageOff'});\n };\n listenerRef.current = bodyClicked;\n document.body.addEventListener('click', listenerRef.current);\n }, []); // Empty array means this effect only runs once\n\n return null; // This component doesn't render anything\n};\n\n// This is the MenuBox component\nconst MenuBox = () => {\n const dispatch = useDispatch();\n\n useEffect(() => {\n return () => {\n // This will remove the event listener when the component unmounts\n document.body.removeEventListener('click', listenerRef.current);\n };\n }, []); // Empty array means this effect only runs once\n\n return (...); // Your menu box code here\n};\n\nAnother issue with the code you provided is that the MenuBox component is rendered every time the parent component is rendered. This means that the MenuBox component will be re-created every time the Menu component is rendered, which is likely not what you want.\nTo fix this, you can move the menu variable outside of the Menu component and use it to conditionally render the MenuBox component. This way, the MenuBox component will only be created once and will only be re-rendered if the menu variable changes.\nHere is an example of how you could do this:\nconst menu = useSelector((state) => state.MenuPage.on);\n\nconst Menu = () => {\n const dispatch = useDispatch();\n\n function clicked() {\n console.log('DEBUG: Menu.jsx clicked')\n dispatch({type: 'toggleMenuPage'});\n }\n\n return (\n <div id=\"menu_hold\">\n <SVGMenu onClick={clicked} id='menu_top'/>\n {menu && <MenuBox/>}\n </div>\n );\n};\n\nI hope this helps! Let me know if you have any other questions.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"reactjs"
] |
stackoverflow_0074668306_javascript_reactjs.txt
|
Q:
Need to write in C a logical statement calculator that takes two inputs (either a number or a letter) and a (<, >, =) operator and checks if true
The calculator should take inputs like (23>3) or (a>9) and prints if it's true or false. My main difficulty is doing it for letters. I only managed to do it for numbers. I don't know how to define the scanf to accept a letter. When a letter is compared to a number, I need to compare the letters' ASCII values. So, if I do a>9 it actually checks if 97>9 (97 is the ASCII value of 'a').
#include <stdio.h>
int main() {
int num1, num2;
char operator;
printf("Please write your logical statement:");
scanf("%d %c %d", &num1, &operator, &num2);
if (operator=='>')
{
if (num1>num2)
{
printf("True");
}
else
{
printf("false");
}
}
else if (operator =='<')
{
if (num1<num2)
{
printf("True");
}
else
{
printf("false");
}
}
else if (operator == '=')
{
if (num1==num2)
{
printf("True");
}
else
{
printf("False");
}
}
}
How do I modify it to also accept characters?
A:
There are many ways you can do this. A fairly straightforward way is to read your two operands as strings and then have a function that either converts those strings into their component numbers or returns the (ASCII) value of the (single) character.
Here is such a function and a modified version of your main to use it:
#include <stdio.h>
#include <string.h> // For strlen
#include <ctype.h> // For isalpha
int GetValue(char* input, int* value)
{
if (sscanf(input, "%d", value) == 1) { // Successfully read a number
return 1;
}
else if (strlen(input) == 1 && isalpha(input[0])) { // For single letters ...
*value = input[0];
return 1;
}
return 0; // Return zero to indicate failure
}
int main(void)
{
char in1[10], in2[10]; // Buffers for input operands (may like to make bigger)
char op;
int num1, num2;
printf("Please write your logical statement:");
// See notes below for an explanation of the format specifiers...
if (scanf("%9[a-zA-Z0-9] %c %9[a-zA-Z0-9]", in1, &op, in2) != 3) {
printf("Invalid input!\n");
return 1;
}
if (!GetValue(in1, &num1)) {
printf("Invalid operand 1\n");
return 1;
}
if (!GetValue(in2, &num2)) {
printf("Invalid operand 2\n");
return 1;
}
if (op == '>') {
printf((num1 > num2) ? "True" : "False");
}
else if (op =='<') {
printf((num1 < num2) ? "True" : "False");
}
else if (op == '=') {
printf((num1 == num2) ? "True" : "False");
}
else {
printf("unrecognized operator");
}
return 0;
}
A short explanation of the %9s[a-zA-Z0-9] format specifier (the "set" format described on this cppreference page): This allows any characters from the three ranges ('a' thru 'z', 'A' thru 'Z' and '0' thru '9') as input to the corresponding char[] arguments. Thus, the input (to the first field) will stop when one of your operators is seen. The '9' immediately after the '%' limits input to the two fields to 9 characters, thus preventing buffer overflow; if you change the size of your in1 and in2 arrays, then change that value accordingly (it should be no greater than one less than the size of the array, to allow for the nul-terminator).
Note that I have also added some (possible) improvements:
Always check the value returned by scanf, to make sure it succeeded
You can use the "conditional (ternary) operator" to make your output code (printf blocks) rather more succinct.
A:
One thing that you could do is to use
scanf( "%c %c %c", &digit1, &operator, &digit2 );
but this would only work if the user enters single digits, not a multi-digit number such as 23.
Instead of using the function scanf, it is generally recommended to always read an entire line of input at once, including the newline character. The function scanf can do nasty things, such as leaving the newline character on the input stream, which can cause trouble.
In order to read a whole line of input at once, I recommend using the function fgets.
I recommend that you treat all characters up to, but not including the operator character, as a separate string. You can then determine whether this string is a valid integer by using the function strtol. If it is not, you can then check the length of the string, to verify that it is only a single character. If it represents neither, then your program should print an error message and exit.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
//This function will convert a string to a number. If the
//string represents an actual number, it will return this
//number. If the string contains a single letter, it will
//return the ASCII code of this letter. Otherwise, the
//function will exit the program with an error message.
long convert_string_to_number( const char *str )
{
long num;
char *p;
//attempt to convert the string into a number
num = strtol( str, &p, 10 );
if ( p == str )
{
//failed to convert string to number, so we must
//now determine whether it is a single letter
if ( strlen(str) == 1 && isalpha( (unsigned char)str[0] ) )
{
//return the ASCII code of the character
return str[0];
}
else
{
printf( "Error: Operand must be either a number or a single letter!\n" );
exit( EXIT_FAILURE );
}
}
//verify that all remaining characters are whitespace
//characters, so that input such as "6abc<23" gets
//rejected
for ( ; *p != '\0'; p++ )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( "Error: Unexpected character found!\n" );
exit( EXIT_FAILURE );
}
}
return num;
}
bool perform_operation( long num1, char operator, long num2 )
{
switch ( operator )
{
case '<':
return num1 < num2;
case '>':
return num1 > num2;
case '=':
return num1 == num2;
default:
printf( "Error: Invalid operator!\n" );
exit( EXIT_FAILURE );
}
}
int main( void )
{
char line[200];
char *p;
char operator;
long num1, num2;
//attempt to read one line of input
if ( fgets( line, sizeof line, stdin ) == NULL )
{
printf( "Input error!\n" );
exit( EXIT_FAILURE );
}
//attempt to find operator
p = strpbrk( line, "<>=" );
//print error message and abort if no operator found
if ( p == NULL )
{
printf( "Error: No valid operator found!\n" );
exit( EXIT_FAILURE );
}
//remember the operator
operator = *p;
//overwrite the operator with a null character, to
//separate the input string into two strings
*p = '\0';
//make the pointer p point to the start of the second
//string
p++;
//attempt to convert both strings to a number
num1 = convert_string_to_number( line );
num2 = convert_string_to_number( p );
//perform the actual operation and print the result
if ( perform_operation( num1, operator, num2 ) )
{
printf( "True" );
}
else
{
printf( "False" );
}
}
This program has the following behavior:
abc
Error: No valid operator found!
=
Error: Operand must be either a number or a single letter!
6abc<23
Error: Unexpected character found!
6<23
True
a=98
False
a=97
True
|
Need to write in C a logical statement calculator that takes two inputs (either a number or a letter) and a (<, >, =) operator and checks if true
|
The calculator should take inputs like (23>3) or (a>9) and prints if it's true or false. My main difficulty is doing it for letters. I only managed to do it for numbers. I don't know how to define the scanf to accept a letter. When a letter is compared to a number, I need to compare the letters' ASCII values. So, if I do a>9 it actually checks if 97>9 (97 is the ASCII value of 'a').
#include <stdio.h>
int main() {
int num1, num2;
char operator;
printf("Please write your logical statement:");
scanf("%d %c %d", &num1, &operator, &num2);
if (operator=='>')
{
if (num1>num2)
{
printf("True");
}
else
{
printf("false");
}
}
else if (operator =='<')
{
if (num1<num2)
{
printf("True");
}
else
{
printf("false");
}
}
else if (operator == '=')
{
if (num1==num2)
{
printf("True");
}
else
{
printf("False");
}
}
}
How do I modify it to also accept characters?
|
[
"There are many ways you can do this. A fairly straightforward way is to read your two operands as strings and then have a function that either converts those strings into their component numbers or returns the (ASCII) value of the (single) character.\nHere is such a function and a modified version of your main to use it:\n#include <stdio.h>\n#include <string.h> // For strlen\n#include <ctype.h> // For isalpha\n\nint GetValue(char* input, int* value)\n{\n if (sscanf(input, \"%d\", value) == 1) { // Successfully read a number\n return 1;\n }\n else if (strlen(input) == 1 && isalpha(input[0])) { // For single letters ...\n *value = input[0];\n return 1;\n }\n return 0; // Return zero to indicate failure\n}\n\nint main(void)\n{\n char in1[10], in2[10]; // Buffers for input operands (may like to make bigger)\n char op;\n int num1, num2;\n\n printf(\"Please write your logical statement:\");\n // See notes below for an explanation of the format specifiers...\n if (scanf(\"%9[a-zA-Z0-9] %c %9[a-zA-Z0-9]\", in1, &op, in2) != 3) {\n printf(\"Invalid input!\\n\");\n return 1;\n }\n if (!GetValue(in1, &num1)) {\n printf(\"Invalid operand 1\\n\");\n return 1;\n }\n if (!GetValue(in2, &num2)) {\n printf(\"Invalid operand 2\\n\");\n return 1;\n }\n\n if (op == '>') {\n printf((num1 > num2) ? \"True\" : \"False\");\n }\n else if (op =='<') {\n printf((num1 < num2) ? \"True\" : \"False\");\n }\n else if (op == '=') {\n printf((num1 == num2) ? \"True\" : \"False\");\n }\n else {\n printf(\"unrecognized operator\");\n }\n return 0;\n}\n\nA short explanation of the %9s[a-zA-Z0-9] format specifier (the \"set\" format described on this cppreference page): This allows any characters from the three ranges ('a' thru 'z', 'A' thru 'Z' and '0' thru '9') as input to the corresponding char[] arguments. Thus, the input (to the first field) will stop when one of your operators is seen. The '9' immediately after the '%' limits input to the two fields to 9 characters, thus preventing buffer overflow; if you change the size of your in1 and in2 arrays, then change that value accordingly (it should be no greater than one less than the size of the array, to allow for the nul-terminator).\nNote that I have also added some (possible) improvements:\n\nAlways check the value returned by scanf, to make sure it succeeded\nYou can use the \"conditional (ternary) operator\" to make your output code (printf blocks) rather more succinct.\n\n",
"One thing that you could do is to use\nscanf( \"%c %c %c\", &digit1, &operator, &digit2 );\n\nbut this would only work if the user enters single digits, not a multi-digit number such as 23.\nInstead of using the function scanf, it is generally recommended to always read an entire line of input at once, including the newline character. The function scanf can do nasty things, such as leaving the newline character on the input stream, which can cause trouble.\nIn order to read a whole line of input at once, I recommend using the function fgets.\nI recommend that you treat all characters up to, but not including the operator character, as a separate string. You can then determine whether this string is a valid integer by using the function strtol. If it is not, you can then check the length of the string, to verify that it is only a single character. If it represents neither, then your program should print an error message and exit.\nHere is an example:\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdbool.h>\n\n//This function will convert a string to a number. If the\n//string represents an actual number, it will return this\n//number. If the string contains a single letter, it will\n//return the ASCII code of this letter. Otherwise, the\n//function will exit the program with an error message.\nlong convert_string_to_number( const char *str )\n{\n long num;\n char *p;\n\n //attempt to convert the string into a number\n num = strtol( str, &p, 10 );\n\n if ( p == str )\n {\n //failed to convert string to number, so we must\n //now determine whether it is a single letter\n if ( strlen(str) == 1 && isalpha( (unsigned char)str[0] ) )\n {\n //return the ASCII code of the character\n return str[0];\n }\n else\n {\n printf( \"Error: Operand must be either a number or a single letter!\\n\" );\n exit( EXIT_FAILURE );\n }\n }\n\n //verify that all remaining characters are whitespace\n //characters, so that input such as \"6abc<23\" gets\n //rejected\n for ( ; *p != '\\0'; p++ )\n {\n if ( !isspace( (unsigned char)*p ) )\n {\n printf( \"Error: Unexpected character found!\\n\" );\n exit( EXIT_FAILURE );\n }\n }\n\n return num;\n}\n\nbool perform_operation( long num1, char operator, long num2 )\n{\n switch ( operator )\n {\n case '<':\n return num1 < num2;\n case '>':\n return num1 > num2;\n case '=':\n return num1 == num2;\n default:\n printf( \"Error: Invalid operator!\\n\" );\n exit( EXIT_FAILURE );\n }\n}\n\nint main( void )\n{\n char line[200];\n char *p;\n char operator;\n long num1, num2;\n\n //attempt to read one line of input\n if ( fgets( line, sizeof line, stdin ) == NULL )\n {\n printf( \"Input error!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to find operator\n p = strpbrk( line, \"<>=\" );\n\n //print error message and abort if no operator found\n if ( p == NULL )\n {\n printf( \"Error: No valid operator found!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //remember the operator\n operator = *p;\n\n //overwrite the operator with a null character, to\n //separate the input string into two strings\n *p = '\\0';\n\n //make the pointer p point to the start of the second\n //string\n p++;\n\n //attempt to convert both strings to a number\n num1 = convert_string_to_number( line );\n num2 = convert_string_to_number( p );\n\n //perform the actual operation and print the result\n if ( perform_operation( num1, operator, num2 ) )\n {\n printf( \"True\" );\n }\n else\n {\n printf( \"False\" );\n }\n}\n\nThis program has the following behavior:\nabc\nError: No valid operator found!\n\n=\nError: Operand must be either a number or a single letter!\n\n6abc<23\nError: Unexpected character found!\n\n6<23\nTrue\n\na=98\nFalse\n\na=97\nTrue\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"c",
"calculator",
"logic"
] |
stackoverflow_0074668114_c_calculator_logic.txt
|
Q:
What consequences does it have, if I use `Any` as a type parameter constraint in general?
I can use an unconstrained type paramter:
interface State<V>
or I can use a constrained type parameter:
interface State<V: Any>
This seems to be the same, because "In Kotlin, everything is an object [...]". But this may be deceptive. What consequences does it have, if I favor the second instead of the first?
A:
Please be aware the default upper bound is not Any, but Any?. There is no difference if we write interface State<V> or interface State<V : Any?> - this is the same thing.
However, interface State<V : Any> is different, it constrains T to be not nullable type:
interface State<V : Any>
class StringState : State<String> // ok
class NullableStringState : State<String?> // compile error
Both above classes compile fine if we don't specify the upper bound or we set it to Any?.
A:
Using Any as a type parameter constraint in Kotlin has the effect of allowing any type to be used as a type parameter. This can be very useful in some cases, as it allows you to create generic functions and classes that can accept any type, but it also has some drawbacks. For example, using Any as a type parameter constraint can lead to code that is not type-safe and can make it difficult to debug potential errors. Additionally, it can make it difficult to understand the code and can lead to unexpected behavior.
|
What consequences does it have, if I use `Any` as a type parameter constraint in general?
|
I can use an unconstrained type paramter:
interface State<V>
or I can use a constrained type parameter:
interface State<V: Any>
This seems to be the same, because "In Kotlin, everything is an object [...]". But this may be deceptive. What consequences does it have, if I favor the second instead of the first?
|
[
"Please be aware the default upper bound is not Any, but Any?. There is no difference if we write interface State<V> or interface State<V : Any?> - this is the same thing.\nHowever, interface State<V : Any> is different, it constrains T to be not nullable type:\ninterface State<V : Any>\n\nclass StringState : State<String> // ok\nclass NullableStringState : State<String?> // compile error\n\nBoth above classes compile fine if we don't specify the upper bound or we set it to Any?.\n",
"Using Any as a type parameter constraint in Kotlin has the effect of allowing any type to be used as a type parameter. This can be very useful in some cases, as it allows you to create generic functions and classes that can accept any type, but it also has some drawbacks. For example, using Any as a type parameter constraint can lead to code that is not type-safe and can make it difficult to debug potential errors. Additionally, it can make it difficult to understand the code and can lead to unexpected behavior.\n"
] |
[
1,
0
] |
[] |
[] |
[
"kotlin"
] |
stackoverflow_0074666674_kotlin.txt
|
Q:
how to apply common configuration to all entities in ef core
I have entities derived from a base entity in my application which uses ef core code-first approach.
Base class
public abstract class BaseEntity<T> : IEntity<T>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public T Id { get; set; }
object IEntity.Id { get { return Id; } set { } }
private DateTime? createdOn;
[DataType(DataType.DateTime)]
public DateTime CreatedOn { get => createdOn ?? DateTime.Now; set => createdOn = value; }
[DataType(DataType.DateTime)]
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
// Auto increment for all entities.
public int OrderId { get; set; }
}
And an entity
public class UserEntity : BaseEntity<int>
{
public string EmployeeId { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
I can apply the .ValueGeneratedOnAdd() method on property OrderId in OnModelCreating for each entity however, is there a way to apply a general rule for all entities without repeatig yourself?
A:
With the lack of custom conventions, you could use the typical modelBuilder.Model.GetEntityTypes() loop, identify the target entity types and invoke common configuration.
Identification in your case is a bit complicated because of the base generic class, but doable by iterating down Type.BaseType and check for BaseEntity<>. Once you find it, you can retrieve the generic argument T which you'll need later.
If you don't want to use generic class implementing IEnityTypeConfiguration<TEntity>, then the idea is to put the implementation in generic constrained method like this
static void Configure<TEntity, T>(ModelBuilder modelBuilder)
where TEntity : BaseEntity<T>
{
modelBuilder.Entity<TEntity>(builder =>
{
builder.Property(e => e.OrderId).ValueGeneratedOnAdd();
});
}
Passing the actual entity type TEntity to modelBuilder.Enity method is crucial, because otherwise EF Core will consider whatever you pass to be an entity type and configure TPH inheritance.
Calling the method requires reflection - finding the generic method definition, using MakeGenericMethod and then Invoke.
Here is all that encapsulated in a static class:
public static class BaseEntityConfiguration
{
static void Configure<TEntity, T>(ModelBuilder modelBuilder)
where TEntity : BaseEntity<T>
{
modelBuilder.Entity<TEntity>(builder =>
{
builder.Property(e => e.OrderId).ValueGeneratedOnAdd();
});
}
public static ModelBuilder ApplyBaseEntityConfiguration(this ModelBuilder modelBuilder)
{
var method = typeof(BaseEntityConfiguration).GetTypeInfo().DeclaredMethods
.Single(m => m.Name == nameof(Configure));
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.ClrType.IsBaseEntity(out var T))
method.MakeGenericMethod(entityType.ClrType, T).Invoke(null, new[] { modelBuilder });
}
return modelBuilder;
}
static bool IsBaseEntity(this Type type, out Type T)
{
for (var baseType = type.BaseType; baseType != null; baseType = baseType.BaseType)
{
if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == typeof(BaseEntity<>))
{
T = baseType.GetGenericArguments()[0];
return true;
}
}
T = null;
return false;
}
}
Now all you need is to call it from inside your OnModelCreating override:
modelBuilder.ApplyBaseEntityConfiguration();
A:
In EF6 you can use:
modelBuilder.Properties<int>().Where(p=>p.Name == "OrderId").Configure(c => c.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
A:
foreach (var item in modelBuilder.Model.GetEntityTypes())
{
item.FindProperty("CreatedOn")?.SetDefaultValueSql("GETDATE()");
item.FindProperty("ModifiedOn")?.SetDefaultValueSql("GETDATE()");
item.FindProperty("AAStatus")?.SetDefaultValue("Alive");
}
i researched and found this thread, my solution after reading it is
|
how to apply common configuration to all entities in ef core
|
I have entities derived from a base entity in my application which uses ef core code-first approach.
Base class
public abstract class BaseEntity<T> : IEntity<T>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public T Id { get; set; }
object IEntity.Id { get { return Id; } set { } }
private DateTime? createdOn;
[DataType(DataType.DateTime)]
public DateTime CreatedOn { get => createdOn ?? DateTime.Now; set => createdOn = value; }
[DataType(DataType.DateTime)]
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
// Auto increment for all entities.
public int OrderId { get; set; }
}
And an entity
public class UserEntity : BaseEntity<int>
{
public string EmployeeId { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
I can apply the .ValueGeneratedOnAdd() method on property OrderId in OnModelCreating for each entity however, is there a way to apply a general rule for all entities without repeatig yourself?
|
[
"With the lack of custom conventions, you could use the typical modelBuilder.Model.GetEntityTypes() loop, identify the target entity types and invoke common configuration.\nIdentification in your case is a bit complicated because of the base generic class, but doable by iterating down Type.BaseType and check for BaseEntity<>. Once you find it, you can retrieve the generic argument T which you'll need later.\nIf you don't want to use generic class implementing IEnityTypeConfiguration<TEntity>, then the idea is to put the implementation in generic constrained method like this\nstatic void Configure<TEntity, T>(ModelBuilder modelBuilder)\n where TEntity : BaseEntity<T>\n{\n modelBuilder.Entity<TEntity>(builder =>\n {\n builder.Property(e => e.OrderId).ValueGeneratedOnAdd();\n });\n}\n\nPassing the actual entity type TEntity to modelBuilder.Enity method is crucial, because otherwise EF Core will consider whatever you pass to be an entity type and configure TPH inheritance.\nCalling the method requires reflection - finding the generic method definition, using MakeGenericMethod and then Invoke.\nHere is all that encapsulated in a static class:\npublic static class BaseEntityConfiguration\n{\n static void Configure<TEntity, T>(ModelBuilder modelBuilder)\n where TEntity : BaseEntity<T>\n {\n modelBuilder.Entity<TEntity>(builder =>\n {\n builder.Property(e => e.OrderId).ValueGeneratedOnAdd();\n });\n }\n\n public static ModelBuilder ApplyBaseEntityConfiguration(this ModelBuilder modelBuilder)\n {\n var method = typeof(BaseEntityConfiguration).GetTypeInfo().DeclaredMethods\n .Single(m => m.Name == nameof(Configure));\n foreach (var entityType in modelBuilder.Model.GetEntityTypes())\n {\n if (entityType.ClrType.IsBaseEntity(out var T))\n method.MakeGenericMethod(entityType.ClrType, T).Invoke(null, new[] { modelBuilder });\n }\n return modelBuilder;\n }\n\n static bool IsBaseEntity(this Type type, out Type T)\n {\n for (var baseType = type.BaseType; baseType != null; baseType = baseType.BaseType)\n {\n if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == typeof(BaseEntity<>))\n {\n T = baseType.GetGenericArguments()[0];\n return true;\n }\n }\n T = null;\n return false;\n }\n}\n\nNow all you need is to call it from inside your OnModelCreating override:\nmodelBuilder.ApplyBaseEntityConfiguration();\n\n",
"In EF6 you can use:\nmodelBuilder.Properties<int>().Where(p=>p.Name == \"OrderId\").Configure(c => c.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));\n\n",
"foreach (var item in modelBuilder.Model.GetEntityTypes())\n{\n item.FindProperty(\"CreatedOn\")?.SetDefaultValueSql(\"GETDATE()\");\n item.FindProperty(\"ModifiedOn\")?.SetDefaultValueSql(\"GETDATE()\");\n item.FindProperty(\"AAStatus\")?.SetDefaultValue(\"Alive\");\n}\n\ni researched and found this thread, my solution after reading it is\n"
] |
[
28,
0,
0
] |
[] |
[] |
[
"c#",
"entity_framework_core"
] |
stackoverflow_0053275567_c#_entity_framework_core.txt
|
Q:
Init values in class extending ChangeNotifier
I am new to Flutter, and I have been trying to make a very basic example: changing the theme at runtime from dark to light.
So far so good, it works using ChangeNotifier, but now I'd like to initialize my _isDarkMode variable at startup, by using SharedPreferences.
My solution feels like a hack, and is completely wrong: it seems to load from the preferences, but the end result is always dark mode.
This is what I did. First, I modified the class with an init function, and added the necessary calls to SharedPreferences:
class PreferencesModel extends ChangeNotifier {
static const _darkModeSetting = "darkmode";
bool _isDarkMode = true; // default, overridden by init()
bool get isDarkMode => _isDarkMode;
ThemeData get appTheme => _isDarkMode ? AppThemes.darkTheme : AppThemes.lightTheme;
void init() async {
final prefs = await SharedPreferences.getInstance();
final bool? dark = prefs.getBool(_darkModeSetting);
_isDarkMode = dark ?? false;
await prefs.setBool(_darkModeSetting, _isDarkMode);
}
void setDarkMode(bool isDark) async {
print("setting preferences dark mode to ${isDark}");
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_darkModeSetting, isDark);
_isDarkMode = isDark;
notifyListeners();
}
}
Then, in the main I call the init from the create lambda of the ChangeNotifierProvider:
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) {
var prefs = PreferencesModel();
prefs.init(); // overrides dark mode
return prefs;
})
],
child: const MyApp(),
)
);
}
The State creating the MaterialApp initializes the ThemeMode based on the preferences:
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Consumer<PreferencesModel>(
builder: (context, preferences, child) {
return MaterialApp(
title: 'MyApp',
home: MainPage(title: 'MyApp'),
theme: AppThemes.lightTheme,
darkTheme: AppThemes.darkTheme,
themeMode: preferences.isDarkMode ? ThemeMode.dark : ThemeMode.light,
);
}
);
}
}
Of course if I change the settings in my settings page (with preferences.setDarkMode(index == 1); on a ToggleButton handler) it works, changing at runtime from light to dark and back. The initialization is somehow completely flawed.
What am I missing here?
A:
Unconventionally, I answer my own question.
The solution is to move the preferences reading to the main, changing the main to be async.
First, the PreferencesModel should have a constructor that sets the initial dark mode:
class PreferencesModel extends ChangeNotifier {
static const darkModeSetting = "darkmode";
PreferencesModel(bool dark) {
_isDarkMode = dark;
}
bool _isDarkMode = true;
// ...
Then, the main function can be async, and use the shared preferences correctly, passing the dark mode to the PreferencesModel:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final bool dark = prefs.getBool(PreferencesModel.darkModeSetting) ?? false;
print("main found dark as ${dark}");
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => PreferencesModel(dark))
],
child: const RecallableApp(),
)
);
}
Please note the WidgetsFlutterBinding.ensureInitialized(); call, otherwise the shared preferences won't work and the app crashes.
|
Init values in class extending ChangeNotifier
|
I am new to Flutter, and I have been trying to make a very basic example: changing the theme at runtime from dark to light.
So far so good, it works using ChangeNotifier, but now I'd like to initialize my _isDarkMode variable at startup, by using SharedPreferences.
My solution feels like a hack, and is completely wrong: it seems to load from the preferences, but the end result is always dark mode.
This is what I did. First, I modified the class with an init function, and added the necessary calls to SharedPreferences:
class PreferencesModel extends ChangeNotifier {
static const _darkModeSetting = "darkmode";
bool _isDarkMode = true; // default, overridden by init()
bool get isDarkMode => _isDarkMode;
ThemeData get appTheme => _isDarkMode ? AppThemes.darkTheme : AppThemes.lightTheme;
void init() async {
final prefs = await SharedPreferences.getInstance();
final bool? dark = prefs.getBool(_darkModeSetting);
_isDarkMode = dark ?? false;
await prefs.setBool(_darkModeSetting, _isDarkMode);
}
void setDarkMode(bool isDark) async {
print("setting preferences dark mode to ${isDark}");
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_darkModeSetting, isDark);
_isDarkMode = isDark;
notifyListeners();
}
}
Then, in the main I call the init from the create lambda of the ChangeNotifierProvider:
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) {
var prefs = PreferencesModel();
prefs.init(); // overrides dark mode
return prefs;
})
],
child: const MyApp(),
)
);
}
The State creating the MaterialApp initializes the ThemeMode based on the preferences:
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Consumer<PreferencesModel>(
builder: (context, preferences, child) {
return MaterialApp(
title: 'MyApp',
home: MainPage(title: 'MyApp'),
theme: AppThemes.lightTheme,
darkTheme: AppThemes.darkTheme,
themeMode: preferences.isDarkMode ? ThemeMode.dark : ThemeMode.light,
);
}
);
}
}
Of course if I change the settings in my settings page (with preferences.setDarkMode(index == 1); on a ToggleButton handler) it works, changing at runtime from light to dark and back. The initialization is somehow completely flawed.
What am I missing here?
|
[
"Unconventionally, I answer my own question.\nThe solution is to move the preferences reading to the main, changing the main to be async.\nFirst, the PreferencesModel should have a constructor that sets the initial dark mode:\nclass PreferencesModel extends ChangeNotifier {\n static const darkModeSetting = \"darkmode\";\n\n PreferencesModel(bool dark) {\n _isDarkMode = dark;\n }\n\n bool _isDarkMode = true;\n // ...\n\nThen, the main function can be async, and use the shared preferences correctly, passing the dark mode to the PreferencesModel:\nvoid main() async {\n WidgetsFlutterBinding.ensureInitialized();\n\n final prefs = await SharedPreferences.getInstance();\n final bool dark = prefs.getBool(PreferencesModel.darkModeSetting) ?? false;\n print(\"main found dark as ${dark}\");\n\n runApp(\n MultiProvider(\n providers: [\n ChangeNotifierProvider(create: (context) => PreferencesModel(dark))\n ],\n child: const RecallableApp(),\n )\n );\n}\n\nPlease note the WidgetsFlutterBinding.ensureInitialized(); call, otherwise the shared preferences won't work and the app crashes.\n"
] |
[
0
] |
[] |
[] |
[
"flutter",
"flutter_change_notifier",
"sharedpreferences"
] |
stackoverflow_0074645923_flutter_flutter_change_notifier_sharedpreferences.txt
|
Q:
Trying to run Jupyter-Dash and getting "an integer is required" error
I am trying to get the first Dash example from https://dash.plotly.com/basic-callbacks running in a Jupyter Notebook with Jupyter Dash and the app runs fine as a standalone application, but errors out when implemented in the notebook and I can't figure this out. I get
TypeError: an integer is required (got type NoneType)
when I try to run the notebook.
from jupyter_dash import JupyterDash
import dash_html_components as html
import dash_core_components as dcc
import dash
from dash.dependencies import Input, Output
app = JupyterDash(__name__)
app.layout = html.Div([
html.H6("Change the value in the text box to see callbacks in action!"),
html.Div([
"Input: ",
dcc.Input(id='my-input', value='initial value', type='text')
]),
html.Br(),
html.Div(id='my-output'),
])
@app.callback(
Output(component_id='my-output', component_property='children'),
[Input(component_id='my-input', component_property='value')]
)
def update_output_div(input_value):
return f'Output: {input_value}'
if __name__ == '__main__':
app.run_server(mode="external")
The main difference is with the imports and app.run_server()
In pycharm I just had from dash import Dash, html, dcc, Input, Output and app.run_server(debug=True). From what I've researched there's some issues with versioning and the updates I made should have fixed the issues and I can't seem to find anything about the error I am getting.
EDIT: Traceback from error
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\1/ipykernel_31316/4067692673.py in <module>
28
29 if __name__ == '__main__':
---> 30 app.run_server(mode="external")
~\AppData\Local\Programs\Python\Python39\lib\site-packages\jupyter_dash\jupyter_app.py in run_server(self, mode, width, height, inline_exceptions, **kwargs)
220 self._terminate_server_for_port(host, port)
221
--> 222 # Configure pathname prefix
223 requests_pathname_prefix = self.config.get('requests_pathname_prefix', None)
224 if self._input_pathname_prefix is None:
~\AppData\Local\Programs\Python\Python39\lib\site-packages\jupyter_dash\_stoppable_thread.py in kill(self)
TypeError: an integer is required (got type NoneType)
A:
I had the same problem, and I found your question while trying to find a solution.
Try adding host as string and port as integer types inside run_server like this:
app.run_server(mode='external', host='your_host', port=your_port)
My host is 127.0.0.1, and the port is 8050.
Hope it helps
|
Trying to run Jupyter-Dash and getting "an integer is required" error
|
I am trying to get the first Dash example from https://dash.plotly.com/basic-callbacks running in a Jupyter Notebook with Jupyter Dash and the app runs fine as a standalone application, but errors out when implemented in the notebook and I can't figure this out. I get
TypeError: an integer is required (got type NoneType)
when I try to run the notebook.
from jupyter_dash import JupyterDash
import dash_html_components as html
import dash_core_components as dcc
import dash
from dash.dependencies import Input, Output
app = JupyterDash(__name__)
app.layout = html.Div([
html.H6("Change the value in the text box to see callbacks in action!"),
html.Div([
"Input: ",
dcc.Input(id='my-input', value='initial value', type='text')
]),
html.Br(),
html.Div(id='my-output'),
])
@app.callback(
Output(component_id='my-output', component_property='children'),
[Input(component_id='my-input', component_property='value')]
)
def update_output_div(input_value):
return f'Output: {input_value}'
if __name__ == '__main__':
app.run_server(mode="external")
The main difference is with the imports and app.run_server()
In pycharm I just had from dash import Dash, html, dcc, Input, Output and app.run_server(debug=True). From what I've researched there's some issues with versioning and the updates I made should have fixed the issues and I can't seem to find anything about the error I am getting.
EDIT: Traceback from error
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\1/ipykernel_31316/4067692673.py in <module>
28
29 if __name__ == '__main__':
---> 30 app.run_server(mode="external")
~\AppData\Local\Programs\Python\Python39\lib\site-packages\jupyter_dash\jupyter_app.py in run_server(self, mode, width, height, inline_exceptions, **kwargs)
220 self._terminate_server_for_port(host, port)
221
--> 222 # Configure pathname prefix
223 requests_pathname_prefix = self.config.get('requests_pathname_prefix', None)
224 if self._input_pathname_prefix is None:
~\AppData\Local\Programs\Python\Python39\lib\site-packages\jupyter_dash\_stoppable_thread.py in kill(self)
TypeError: an integer is required (got type NoneType)
|
[
"I had the same problem, and I found your question while trying to find a solution.\nTry adding host as string and port as integer types inside run_server like this:\napp.run_server(mode='external', host='your_host', port=your_port)\nMy host is 127.0.0.1, and the port is 8050.\nHope it helps\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"jupyterdash",
"plotly_dash",
"python"
] |
stackoverflow_0073421435_jupyter_notebook_jupyterdash_plotly_dash_python.txt
|
Q:
why my data is coming as null or default in ui from view model in kotlin?
I set up mvvm structure and call two functions in viewmodel. Functions return values, but these values always come as values that I define as null or default.
Why can't I access my data in the view model in the UI?
I can see the data properly in the view model
hear is my code
my ui
if (viewModel.isDialogShown) {
AlertDialog(
onDismiss = {
viewModel.onDismissClick()
},
onConfirm = {
println("First"+viewModel.getFirstConversionRateByCurrency(viewModel.dropDownMenuItem1))
println("SECOND:"+viewModel.getSecondConversionRateByCurrency(viewModel.dropDownMenuItem2))
}
)
}
If the user says confirm in the alert dialog in my UI, these functions are called and I print the returned values for testing purposes, but because I define null as default in the viewmodel, it always comes null.
my view model
@HiltViewModel
class ExchangeMainViewModel @Inject constructor(
private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase
) : ViewModel() {
var second : Double?=null
var first : Double? = null
fun getFirstConversionRateByCurrency(currency:String) : String {
viewModelScope.launch {
first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
}
return first.toString()
}
fun getSecondConversionRateByCurrency(currency:String) :String {
viewModelScope.launch {
second = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
}
return second.toString()
}
}
Also, I defined the viewmodel in ui as you can see the below like this, could it be because of this?
@Composable
fun DropDownMenu(
viewModel: ExchangeMainViewModel = hiltViewModel()
) {
The result in the console is as follows
A:
All those functions your are calling are executing a coroutine from viewModelScope.launch{…} and at the time you launched them you immediately return a value from the method return.xxx.toString() where the xxx (first and second) doesn't have a value yet since what you are expecting is coming from a concurrent execution not a sequential one.
viewModelScope.launch { // launch me separately and wait for any value that will set the `first`
first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
}
// return from this function now with a null value, since it was initialized as null
return first.toString()
This is a rough implementation, though I'm not sure if this would work, but this should give you a headstart
Your new ViewModel
@HiltViewModel
class ExchangeMainViewModel @Inject constructor(
private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase
) : ViewModel() {
var conversionValue by mutableStateOf<ConversionValues?>(null)
fun getFirstConversionRateByCurrency(currency:String) {
viewModelScope.launch {
val first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
val second = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
conversionValue = ConversionValues(first, second)
}
}
}
the Data Class for first and second
data class ConversionValues(
val first : Double,
val second: Double
)
and your composable
@Composable
fun DropDownMenu(
viewModel: ExchangeMainViewModel = hiltViewModel()
) {
val conversionValue = vieModel.conversionValue
if (viewModel.isDialogShown) {
AlertDialog(
onDismiss = {
viewModel.onDismissClick()
},
onConfirm {
println("First" + conversionValue.first)
println("SECOND:"+conversionValue.second)
}
)
}
}
|
why my data is coming as null or default in ui from view model in kotlin?
|
I set up mvvm structure and call two functions in viewmodel. Functions return values, but these values always come as values that I define as null or default.
Why can't I access my data in the view model in the UI?
I can see the data properly in the view model
hear is my code
my ui
if (viewModel.isDialogShown) {
AlertDialog(
onDismiss = {
viewModel.onDismissClick()
},
onConfirm = {
println("First"+viewModel.getFirstConversionRateByCurrency(viewModel.dropDownMenuItem1))
println("SECOND:"+viewModel.getSecondConversionRateByCurrency(viewModel.dropDownMenuItem2))
}
)
}
If the user says confirm in the alert dialog in my UI, these functions are called and I print the returned values for testing purposes, but because I define null as default in the viewmodel, it always comes null.
my view model
@HiltViewModel
class ExchangeMainViewModel @Inject constructor(
private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase
) : ViewModel() {
var second : Double?=null
var first : Double? = null
fun getFirstConversionRateByCurrency(currency:String) : String {
viewModelScope.launch {
first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
}
return first.toString()
}
fun getSecondConversionRateByCurrency(currency:String) :String {
viewModelScope.launch {
second = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)
}
return second.toString()
}
}
Also, I defined the viewmodel in ui as you can see the below like this, could it be because of this?
@Composable
fun DropDownMenu(
viewModel: ExchangeMainViewModel = hiltViewModel()
) {
The result in the console is as follows
|
[
"All those functions your are calling are executing a coroutine from viewModelScope.launch{…} and at the time you launched them you immediately return a value from the method return.xxx.toString() where the xxx (first and second) doesn't have a value yet since what you are expecting is coming from a concurrent execution not a sequential one.\nviewModelScope.launch { // launch me separately and wait for any value that will set the `first`\n first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)\n}\n\n// return from this function now with a null value, since it was initialized as null\nreturn first.toString() \n\n\nThis is a rough implementation, though I'm not sure if this would work, but this should give you a headstart\nYour new ViewModel\n@HiltViewModel\nclass ExchangeMainViewModel @Inject constructor(\n\n private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase\n) : ViewModel() {\n\n var conversionValue by mutableStateOf<ConversionValues?>(null)\n\n fun getFirstConversionRateByCurrency(currency:String) {\n\n viewModelScope.launch {\n\n val first = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)\n val second = getConversionRateByCurrencyUseCase.getConversionRateByCurrency(currency)\n\n conversionValue = ConversionValues(first, second)\n }\n }\n}\n\nthe Data Class for first and second\ndata class ConversionValues(\n val first : Double,\n val second: Double\n)\n\nand your composable\n@Composable\nfun DropDownMenu(\n viewModel: ExchangeMainViewModel = hiltViewModel()\n) {\n \n val conversionValue = vieModel.conversionValue\n\n if (viewModel.isDialogShown) {\n\n AlertDialog(\n onDismiss = {\n viewModel.onDismissClick()\n },\n onConfirm {\n\n println(\"First\" + conversionValue.first)\n println(\"SECOND:\"+conversionValue.second)\n }\n )\n }\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"kotlin"
] |
stackoverflow_0074668198_kotlin.txt
|
Q:
OCI Access private Load balancer through public Network Load Balancer
I can not access layer 7 application load balancer backends via layer 4 network load balancer.
In a VCN there are two subnets, public and private, both containing compute instances.
A (layer 7, application) Load Balancer has a backend set with two backends (compute instances' IPs) and a listener on port 80. The LB and backends are in the same private subnet. The instances are running httpd. The load balancer, its backend sets and backends all have OK health.
The load balancer's endpoint can be used successfully from instances in the public and private subnets.
A Network Load Balancer in the public subnet has a backend set with one backend, port 80 on the private IP of the private subnet's load balancer. This remains critical and the backend set remains offline despite its target, the private load balancer, being in full health and accessible from the same subnet where the network load balancer is. The TCP health check points to port 80.
To rule out networking issues, I created a TCP port forwarder in an instance in the private subnet (using "socat" to forward requests to the load balancer IP). I changed the network load balancer's backend to point to, instead of the load balancer's IP, to the IP of instance running the port forwarder. This works perfectly - the http backends can be accessed from the public network load balancer's public IP no problems at all.
To allay security list concerns, I have "permit all" for traffic between both subnets. Everything is fully accessible as expected when accessed from instances in both subnets.
Why is the network load balancer showing its endpoint, the private subnet's load balancer, is critical and shutting it down, when it is really up, accessible and healthy?
Is it possible to access one loadbalancer from another? what am I doing wrong?
To help troubleshoot this, I created a backend set with 3 backends
The first backend is one of the backends behind the load balancer, you can see that's ok.
The second backend is the load balancer, you can see it's critical.
The third backend (port 1103) is the instance with the port-forwarding to the load balancer which is at 10.0.1.108:80. You can see it's ok. The port forwarding is done like this socat tcp-listen:1103,reuseaddr,fork tcp:10.0.1.108:80. I can see traffic through this and I can see it hit alternate backends as expected.
I've taken the first backend offline becasue it doesn't use the load balancer (but its health shows the backend is healthy).
The health check looks like this. It works for two of the backends but not the one that is the load balancer:
I also tried using a TCP health check but it made no difference.
The load balancer subnet's security list has a rule allowing everything from the private subnet (added whilst testing this), egress from both subnets is allow all 0.0.0.0/0.
The status of the application load balancer is good
The VCN's subnets
The load balancer is accessible from an instance in the public subnet, the same subnet where the network load balancer is.
A:
It is possible to access one load balancer from another, but it requires proper configuration and troubleshooting to ensure that the backend instances are accessible. In this case, it seems that the network load balancer is not properly configured to access the private load balancer.
One potential issue is that the network load balancer is not properly configured to reach the private load balancer's endpoint. This could be due to a variety of factors, including incorrect IP addresses or port numbers, network security rules blocking access, or incorrect load balancer settings.
Another potential issue is that the network load balancer is not performing the proper health checks to determine if the private load balancer is healthy and available. This could be due to incorrect health check settings, such as incorrect port numbers or incorrect health check URLs.
To resolve these issues, it may be necessary to carefully review and troubleshoot the network and load balancer configurations, including network security rules, load balancer settings, and health check settings. It may also be helpful to test and verify access to the private load balancer's endpoint using a compute instance in the public subnet, to ensure that it is reachable and functioning properly.
|
OCI Access private Load balancer through public Network Load Balancer
|
I can not access layer 7 application load balancer backends via layer 4 network load balancer.
In a VCN there are two subnets, public and private, both containing compute instances.
A (layer 7, application) Load Balancer has a backend set with two backends (compute instances' IPs) and a listener on port 80. The LB and backends are in the same private subnet. The instances are running httpd. The load balancer, its backend sets and backends all have OK health.
The load balancer's endpoint can be used successfully from instances in the public and private subnets.
A Network Load Balancer in the public subnet has a backend set with one backend, port 80 on the private IP of the private subnet's load balancer. This remains critical and the backend set remains offline despite its target, the private load balancer, being in full health and accessible from the same subnet where the network load balancer is. The TCP health check points to port 80.
To rule out networking issues, I created a TCP port forwarder in an instance in the private subnet (using "socat" to forward requests to the load balancer IP). I changed the network load balancer's backend to point to, instead of the load balancer's IP, to the IP of instance running the port forwarder. This works perfectly - the http backends can be accessed from the public network load balancer's public IP no problems at all.
To allay security list concerns, I have "permit all" for traffic between both subnets. Everything is fully accessible as expected when accessed from instances in both subnets.
Why is the network load balancer showing its endpoint, the private subnet's load balancer, is critical and shutting it down, when it is really up, accessible and healthy?
Is it possible to access one loadbalancer from another? what am I doing wrong?
To help troubleshoot this, I created a backend set with 3 backends
The first backend is one of the backends behind the load balancer, you can see that's ok.
The second backend is the load balancer, you can see it's critical.
The third backend (port 1103) is the instance with the port-forwarding to the load balancer which is at 10.0.1.108:80. You can see it's ok. The port forwarding is done like this socat tcp-listen:1103,reuseaddr,fork tcp:10.0.1.108:80. I can see traffic through this and I can see it hit alternate backends as expected.
I've taken the first backend offline becasue it doesn't use the load balancer (but its health shows the backend is healthy).
The health check looks like this. It works for two of the backends but not the one that is the load balancer:
I also tried using a TCP health check but it made no difference.
The load balancer subnet's security list has a rule allowing everything from the private subnet (added whilst testing this), egress from both subnets is allow all 0.0.0.0/0.
The status of the application load balancer is good
The VCN's subnets
The load balancer is accessible from an instance in the public subnet, the same subnet where the network load balancer is.
|
[
"It is possible to access one load balancer from another, but it requires proper configuration and troubleshooting to ensure that the backend instances are accessible. In this case, it seems that the network load balancer is not properly configured to access the private load balancer.\nOne potential issue is that the network load balancer is not properly configured to reach the private load balancer's endpoint. This could be due to a variety of factors, including incorrect IP addresses or port numbers, network security rules blocking access, or incorrect load balancer settings.\nAnother potential issue is that the network load balancer is not performing the proper health checks to determine if the private load balancer is healthy and available. This could be due to incorrect health check settings, such as incorrect port numbers or incorrect health check URLs.\nTo resolve these issues, it may be necessary to carefully review and troubleshoot the network and load balancer configurations, including network security rules, load balancer settings, and health check settings. It may also be helpful to test and verify access to the private load balancer's endpoint using a compute instance in the public subnet, to ensure that it is reachable and functioning properly.\n"
] |
[
0
] |
[] |
[] |
[
"load_balancing",
"oracle_cloud_infrastructure"
] |
stackoverflow_0074668441_load_balancing_oracle_cloud_infrastructure.txt
|
Q:
Rolling difference in group and divivded by group sum in Pandas
I am wondering if there's an easier/faster way (ideally in pipe method so it looks nicer!) I can work out the rolling difference divided by previous group sum. In the result outout, pc column is the column I am after.
import pandas as pd
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2020-01-01", "2020-01-01", "2021-01-01", "2021-01-01", "2021-01-01", "2022-01-01", "2022-01-01", "2022-01-01"],
"City": ["London", "New York", "Tokyo", "London", "New York", "Tokyo", "London", "New York", "Tokyo"],
"Pop": [90, 70, 60, 85, 60, 45, 70, 40, 32],
}
)
Date City Pop
0 2020-01-01 London 90
1 2020-01-01 New York 70
2 2020-01-01 Tokyo 60
3 2021-01-01 London 85
4 2021-01-01 New York 60
5 2021-01-01 Tokyo 45
6 2022-01-01 London 70
7 2022-01-01 New York 40
8 2022-01-01 Tokyo 32
df['pop_diff'] = df.groupby(['City'])['Pop'].diff()
df['total'] = df.groupby('Date').Pop.transform('sum')
df['total_shift'] = df.groupby('City')['total'].shift()
df['pc'] = df['pop_diff'] / df['total_shift']
Date City Pop pop_diff total total_shift pc
0 2020-01-01 London 90 NaN 220 NaN NaN
1 2020-01-01 New York 70 NaN 220 NaN NaN
2 2020-01-01 Tokyo 60 NaN 220 NaN NaN
3 2021-01-01 London 85 -5.0 190 220.0 -0.022727
4 2021-01-01 New York 60 -10.0 190 220.0 -0.045455
5 2021-01-01 Tokyo 45 -15.0 190 220.0 -0.068182
6 2022-01-01 London 70 -15.0 142 190.0 -0.078947
7 2022-01-01 New York 40 -20.0 142 190.0 -0.105263
8 2022-01-01 Tokyo 32 -13.0 142 190.0 -0.068421
A:
Here is one way to do it with Pandas assign and pipe:
df = (
df.assign(total=df.groupby("Date")["Pop"].transform("sum"))
.pipe(
lambda df_: df_.assign(
pc=df_.groupby(["City"])
.agg({"Pop": "diff", "total": "shift"})
.pipe(lambda x: x["Pop"] / x["total"])
)
)
.drop(columns="total")
)
Then:
print(df)
# Output
Date City Pop pc
0 2020-01-01 London 90 NaN
1 2020-01-01 New York 70 NaN
2 2020-01-01 Tokyo 60 NaN
3 2021-01-01 London 85 -0.022727
4 2021-01-01 New York 60 -0.045455
5 2021-01-01 Tokyo 45 -0.068182
6 2022-01-01 London 70 -0.078947
7 2022-01-01 New York 40 -0.105263
8 2022-01-01 Tokyo 32 -0.068421
|
Rolling difference in group and divivded by group sum in Pandas
|
I am wondering if there's an easier/faster way (ideally in pipe method so it looks nicer!) I can work out the rolling difference divided by previous group sum. In the result outout, pc column is the column I am after.
import pandas as pd
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2020-01-01", "2020-01-01", "2021-01-01", "2021-01-01", "2021-01-01", "2022-01-01", "2022-01-01", "2022-01-01"],
"City": ["London", "New York", "Tokyo", "London", "New York", "Tokyo", "London", "New York", "Tokyo"],
"Pop": [90, 70, 60, 85, 60, 45, 70, 40, 32],
}
)
Date City Pop
0 2020-01-01 London 90
1 2020-01-01 New York 70
2 2020-01-01 Tokyo 60
3 2021-01-01 London 85
4 2021-01-01 New York 60
5 2021-01-01 Tokyo 45
6 2022-01-01 London 70
7 2022-01-01 New York 40
8 2022-01-01 Tokyo 32
df['pop_diff'] = df.groupby(['City'])['Pop'].diff()
df['total'] = df.groupby('Date').Pop.transform('sum')
df['total_shift'] = df.groupby('City')['total'].shift()
df['pc'] = df['pop_diff'] / df['total_shift']
Date City Pop pop_diff total total_shift pc
0 2020-01-01 London 90 NaN 220 NaN NaN
1 2020-01-01 New York 70 NaN 220 NaN NaN
2 2020-01-01 Tokyo 60 NaN 220 NaN NaN
3 2021-01-01 London 85 -5.0 190 220.0 -0.022727
4 2021-01-01 New York 60 -10.0 190 220.0 -0.045455
5 2021-01-01 Tokyo 45 -15.0 190 220.0 -0.068182
6 2022-01-01 London 70 -15.0 142 190.0 -0.078947
7 2022-01-01 New York 40 -20.0 142 190.0 -0.105263
8 2022-01-01 Tokyo 32 -13.0 142 190.0 -0.068421
|
[
"Here is one way to do it with Pandas assign and pipe:\ndf = (\n df.assign(total=df.groupby(\"Date\")[\"Pop\"].transform(\"sum\"))\n .pipe(\n lambda df_: df_.assign(\n pc=df_.groupby([\"City\"])\n .agg({\"Pop\": \"diff\", \"total\": \"shift\"})\n .pipe(lambda x: x[\"Pop\"] / x[\"total\"])\n )\n )\n .drop(columns=\"total\")\n)\n\nThen:\nprint(df)\n# Output\n Date City Pop pc\n0 2020-01-01 London 90 NaN\n1 2020-01-01 New York 70 NaN\n2 2020-01-01 Tokyo 60 NaN\n3 2021-01-01 London 85 -0.022727\n4 2021-01-01 New York 60 -0.045455\n5 2021-01-01 Tokyo 45 -0.068182\n6 2022-01-01 London 70 -0.078947\n7 2022-01-01 New York 40 -0.105263\n8 2022-01-01 Tokyo 32 -0.068421\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074654758_pandas_python.txt
|
Q:
C# when building a multiple choice quiz, how do we count the correct / wrong answers and form a score base on the counts?
So i am going to have 4 questions and each question is worth 25 points and full point is 100.
I am not sure how to count the answer base on my code and form score code.
Thank you for helping me out.
(I put 1 question to make the code shorter but in my VS there are 4 questions)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MCQuiz
{
class Program
{
static void Main(string[] args)
{
string answer;
Console.WriteLine("Q1-Every Statement in C# language must terminate with: ");
Console.WriteLine(" \t a. ; ");
Console.WriteLine(" \t b. , ");
Console.WriteLine(" \t c. . ");
Console.WriteLine(" \t d. ? ");
Console.WriteLine();
Console.Write("Enter the letter (a, b, c, d) for correct Answer: ")
answer = Console.ReadLine();
if (answer == "a")
{
Console.WriteLine("Your Answer '{0}' is Correct.", answer);
}
else
{
Console.WriteLine("Your Answer '{0}' is Wrong.", answer);
}
Console.WriteLine();
Console.WriteLine("****************************************");
}
}
}
A:
You could track the totalScore in an integer variable and add 25 each correct answer using the += operator, which is a shorthand for totalScore = totalScore + 25 in the following example.
class Program
{
static void Main(string[] args)
{
int totalScore = 0; // initiate variable
string answer;
Console.WriteLine("Q1-Every Statement in C# language must terminate with: ");
Console.WriteLine(" \t a. ; ");
Console.WriteLine(" \t b. , ");
Console.WriteLine(" \t c. . ");
Console.WriteLine(" \t d. ? ");
Console.WriteLine();
Console.Write("Enter the letter (a, b, c, d) for correct Answer: ")
answer = Console.ReadLine();
if (answer == "a")
{
totalScore += 25; // add score
Console.WriteLine("Your Answer '{0}' is Correct.", answer);
}
else
{
Console.WriteLine("Your Answer '{0}' is Wrong.", answer);
}
Console.WriteLine();
Console.WriteLine("****************************************");
Console.WriteLine($"You scored {totalScore} points"); // output result
}
}
|
C# when building a multiple choice quiz, how do we count the correct / wrong answers and form a score base on the counts?
|
So i am going to have 4 questions and each question is worth 25 points and full point is 100.
I am not sure how to count the answer base on my code and form score code.
Thank you for helping me out.
(I put 1 question to make the code shorter but in my VS there are 4 questions)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MCQuiz
{
class Program
{
static void Main(string[] args)
{
string answer;
Console.WriteLine("Q1-Every Statement in C# language must terminate with: ");
Console.WriteLine(" \t a. ; ");
Console.WriteLine(" \t b. , ");
Console.WriteLine(" \t c. . ");
Console.WriteLine(" \t d. ? ");
Console.WriteLine();
Console.Write("Enter the letter (a, b, c, d) for correct Answer: ")
answer = Console.ReadLine();
if (answer == "a")
{
Console.WriteLine("Your Answer '{0}' is Correct.", answer);
}
else
{
Console.WriteLine("Your Answer '{0}' is Wrong.", answer);
}
Console.WriteLine();
Console.WriteLine("****************************************");
}
}
}
|
[
"You could track the totalScore in an integer variable and add 25 each correct answer using the += operator, which is a shorthand for totalScore = totalScore + 25 in the following example.\nclass Program\n{\n static void Main(string[] args)\n {\n int totalScore = 0; // initiate variable\n string answer;\n\n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n\n\n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n\n answer = Console.ReadLine();\n\n if (answer == \"a\")\n {\n totalScore += 25; // add score\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n Console.WriteLine($\"You scored {totalScore} points\"); // output result\n }\n}\n\n"
] |
[
1
] |
[
"\nI already created a quiz maker in console application.\nTake a look Quiz maker.\nSee below code snippet for you question.\n\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Threading.Tasks;\n \n namespace MCQuiz\n {\n class Program\n {\n static void Main(string[] args)\n {\n \n \n string answer;\n string totalScore = 0;\n \n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n \n \n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n \n answer = Console.ReadKey();\n \n if (answer == \"a\")\n {\n totalScore += 25;\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n \n }\n }\n }\n\n\n"
] |
[
-1
] |
[
"c#",
"multiple_choice"
] |
stackoverflow_0074665959_c#_multiple_choice.txt
|
Q:
In pytorch torchscript, how to compile with multi heads?
I have a model with multiple optional
heads and would like to compile into torchscript.
Is there a way to compile correctly ?
I tried to search, but the closest answer is this one,
which does not provide any work-around.
https://discuss.pytorch.org/t/using-torschscript-to-save-a-model-with-multiple-heads/158709
A:
Yes, you can use the torch.jit.trace or torch.jit.script functions to compile a PyTorch model into TorchScript. If your model has multiple optional heads, you can specify which one to use when tracing or scripting the model by passing the name of the head as an argument to the torch.jit.trace or torch.jit.script function
|
In pytorch torchscript, how to compile with multi heads?
|
I have a model with multiple optional
heads and would like to compile into torchscript.
Is there a way to compile correctly ?
I tried to search, but the closest answer is this one,
which does not provide any work-around.
https://discuss.pytorch.org/t/using-torschscript-to-save-a-model-with-multiple-heads/158709
|
[
"Yes, you can use the torch.jit.trace or torch.jit.script functions to compile a PyTorch model into TorchScript. If your model has multiple optional heads, you can specify which one to use when tracing or scripting the model by passing the name of the head as an argument to the torch.jit.trace or torch.jit.script function\n"
] |
[
0
] |
[] |
[] |
[
"pytorch",
"torchscript"
] |
stackoverflow_0074668422_pytorch_torchscript.txt
|
Q:
d3 force directed graph & svelte reactive statement
I tried to make a simple d3 force-directed graph with the svelte reactive statement, but apparently, it's not working together.
1st example, this is the simplest way I make the graph (working REPL):
<script>
import * as d3 from 'd3'
import { onMount } from 'svelte'
import data from './data.json'
let svg,
width = 500,
height = 400,
links, nodes
let simulation = d3.forceSimulation(data)
</script>
<svg
bind:this={svg}
width={width}
height={height}
viewBox="{-width/2} {-height/2} {width} {height}"
>
{#each data as node}
<g class="g-nodes" >
<circle bind:this={nodes}
fill="cornflowerblue"
r="5"
cx={node.x}
cy={node.y}
></circle>
</g>
{/each}
</svg>
2nd example, I want to add some force with reactive statement to it, let's say forceX, and it doesn't work, until I add simulation.tick(100) or any number > 0 inside the .tick() (working REPL):
<script>
// the before part is still the same
let simulation = d3.forceSimulation(data)
$: simulation.force("x", d3.forceX(0)) // not working, the circle stay at the initial position
$: simulation.tick(100) // the force worked, but not animating from the initial position
</script>
<!-- the rest of svg is still the same -->
3rd example, I tried the .on("tick") with function. The function is fired (I only give a console.log to test if the tick working.) but I have no idea how to pass the modified data to the {#each} block. Looking at the console.log(data) inside the update function, the x and y data are changing every tick, but not updating the actual circle position. (working REPL):
<script>
// the before part is still the same
let simulation = d3.forceSimulation(data)
function update() {
console.log(data)
return data // I don't know if it's the correct way, but still not working tho
}
$: simulation.force("x", d3.forceX(0))
$: simulation.on("tick", update)
</script>
<!-- the rest of svg is still the same -->
data.json
[
{value: 10},
{value: 12},
{value: 15},
{value: 8},
{value: 7},
{value: 12},
{value: 25},
{value: 20},
{value: 16},
{value: 13},
{value: 5},
{value: 7},
{value: 8},
{value: 10},
{value: 12},
{value: 14},
{value: 24},
{value: 23},
{value: 22},
{value: 11},
]
A:
The simplest way to address your problem in step #3 is to declare a displayData array, to copy over data into displayData inside your update function, and to iterate your #each block over displayData.
data being an import variable, you cannot directly reassign to it, and because you cannot reassign to it, it is not reactive and data updates do not trigger a re-render.
By assigning data to displayData in your update function (which will run on every tick), you will trigger a re-render of your #each block (provided you now iterate over displayData).
Working REPL
|
d3 force directed graph & svelte reactive statement
|
I tried to make a simple d3 force-directed graph with the svelte reactive statement, but apparently, it's not working together.
1st example, this is the simplest way I make the graph (working REPL):
<script>
import * as d3 from 'd3'
import { onMount } from 'svelte'
import data from './data.json'
let svg,
width = 500,
height = 400,
links, nodes
let simulation = d3.forceSimulation(data)
</script>
<svg
bind:this={svg}
width={width}
height={height}
viewBox="{-width/2} {-height/2} {width} {height}"
>
{#each data as node}
<g class="g-nodes" >
<circle bind:this={nodes}
fill="cornflowerblue"
r="5"
cx={node.x}
cy={node.y}
></circle>
</g>
{/each}
</svg>
2nd example, I want to add some force with reactive statement to it, let's say forceX, and it doesn't work, until I add simulation.tick(100) or any number > 0 inside the .tick() (working REPL):
<script>
// the before part is still the same
let simulation = d3.forceSimulation(data)
$: simulation.force("x", d3.forceX(0)) // not working, the circle stay at the initial position
$: simulation.tick(100) // the force worked, but not animating from the initial position
</script>
<!-- the rest of svg is still the same -->
3rd example, I tried the .on("tick") with function. The function is fired (I only give a console.log to test if the tick working.) but I have no idea how to pass the modified data to the {#each} block. Looking at the console.log(data) inside the update function, the x and y data are changing every tick, but not updating the actual circle position. (working REPL):
<script>
// the before part is still the same
let simulation = d3.forceSimulation(data)
function update() {
console.log(data)
return data // I don't know if it's the correct way, but still not working tho
}
$: simulation.force("x", d3.forceX(0))
$: simulation.on("tick", update)
</script>
<!-- the rest of svg is still the same -->
data.json
[
{value: 10},
{value: 12},
{value: 15},
{value: 8},
{value: 7},
{value: 12},
{value: 25},
{value: 20},
{value: 16},
{value: 13},
{value: 5},
{value: 7},
{value: 8},
{value: 10},
{value: 12},
{value: 14},
{value: 24},
{value: 23},
{value: 22},
{value: 11},
]
|
[
"The simplest way to address your problem in step #3 is to declare a displayData array, to copy over data into displayData inside your update function, and to iterate your #each block over displayData.\ndata being an import variable, you cannot directly reassign to it, and because you cannot reassign to it, it is not reactive and data updates do not trigger a re-render.\nBy assigning data to displayData in your update function (which will run on every tick), you will trigger a re-render of your #each block (provided you now iterate over displayData).\nWorking REPL\n"
] |
[
1
] |
[] |
[] |
[
"d3.js",
"svelte"
] |
stackoverflow_0074665797_d3.js_svelte.txt
|
Q:
Flutter / Dart - the use of "resultTextFieldController.text = resultOfCalculation;"
Flutter / Dart - I have a simple diabetic app but am new to programming, so struggling a lot, even after watching hours of Flutter youtube videos! My app currently has 4 input fields on one row and the result of a calculation of input1 - input2 below it. I would like to change this, so that the top row has Input / Input / Output (in similar boxes) and the second row has Input / Input / Output (in similar boxes). The code for my current app is shown below after some help on Stackoverflow. It has been suggested that I use the command "resultTextFieldController.text = resultOfCalculation;" to put the result in a text box, but my main issue is where to put that line as everywhere I have put it so far, the line gets underlined in red.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Help with a meal....';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
backgroundColor: Colors.grey,
foregroundColor: Colors.black,
),
body: const AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({super.key});
@override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = TextEditingController();
TextEditingController num2controller = TextEditingController();
TextEditingController num3controller = TextEditingController();
TextEditingController num4controller = TextEditingController();
String result = "0";
_calculate() {
if (num1controller.text.isNotEmpty && num2controller.text.isNotEmpty) {
setState(() {
double sum = double.parse(num1controller.text) -
double.parse(num2controller.text);
result = sum.toStringAsFixed(1);
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Row(
children: <Widget>[
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num1controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num2controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num3controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num4controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
),
const SizedBox(
width: 8,
),
],
),
Text(
'Difference between Target Level and Current Level: $result'),
],
),
),
),
);
}
}
A:
Full Code
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Help with a meal....';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
backgroundColor: Colors.grey,
foregroundColor: Colors.black,
),
body: const AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({super.key});
@override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController numR1C1controller =
TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C
TextEditingController numR1C2controller = TextEditingController();
TextEditingController numR1C3controller = TextEditingController();
TextEditingController numR2C1controller = TextEditingController();
TextEditingController numR2C2controller = TextEditingController();
TextEditingController numR2C3controller = TextEditingController();
String result = "0";
String result2 = "0";
_calculateR1() {
if (numR1C1controller.text.isNotEmpty &&
numR1C2controller.text.isNotEmpty) {
setState(() {
double sum = double.parse(numR1C1controller.text) -
double.parse(numR1C2controller.text);
numR1C3controller.text = sum.toStringAsFixed(1);
result = sum.toStringAsFixed(1);
});
}
}
_calculateR2() {
if (numR2C1controller.text.isNotEmpty &&
numR2C2controller.text.isNotEmpty) {
setState(() {
double sum = double.parse(numR2C1controller.text) -
double.parse(numR2C2controller.text);
numR2C3controller.text = sum.toStringAsFixed(1);
result2 = sum.toStringAsFixed(1);
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Row(
children: <Widget>[
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculateR1(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR1C1controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculateR1(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR1C2controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculateR1(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR1C3controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Result',
hintText: '',
),
),
),
const SizedBox(
width: 8,
),
],
),
const SizedBox(
height: 8,
),
Row(
children: [
Expanded(
child: TextField(
onChanged: (value) => _calculateR2(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR2C1controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculateR2(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR2C2controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculateR2(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: numR2C3controller,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Result',
hintText: '',
),
),
),
const SizedBox(
width: 8,
),
],
),
Text(
'Difference between Target Level and Current Level: $result'),
],
),
),
),
);
}
}
Output
Add this line to the textfield widget to allow only numbers to be inputted in the text field.
inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
Hope this helps. Happy Coding :)
|
Flutter / Dart - the use of "resultTextFieldController.text = resultOfCalculation;"
|
Flutter / Dart - I have a simple diabetic app but am new to programming, so struggling a lot, even after watching hours of Flutter youtube videos! My app currently has 4 input fields on one row and the result of a calculation of input1 - input2 below it. I would like to change this, so that the top row has Input / Input / Output (in similar boxes) and the second row has Input / Input / Output (in similar boxes). The code for my current app is shown below after some help on Stackoverflow. It has been suggested that I use the command "resultTextFieldController.text = resultOfCalculation;" to put the result in a text box, but my main issue is where to put that line as everywhere I have put it so far, the line gets underlined in red.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Help with a meal....';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
backgroundColor: Colors.grey,
foregroundColor: Colors.black,
),
body: const AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
const AddTwoNumbers({super.key});
@override
// ignore: library_private_types_in_public_api
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = TextEditingController();
TextEditingController num2controller = TextEditingController();
TextEditingController num3controller = TextEditingController();
TextEditingController num4controller = TextEditingController();
String result = "0";
_calculate() {
if (num1controller.text.isNotEmpty && num2controller.text.isNotEmpty) {
setState(() {
double sum = double.parse(num1controller.text) -
double.parse(num2controller.text);
result = sum.toStringAsFixed(1);
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Row(
children: <Widget>[
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num1controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Target Level',
hintText: 'Enter First Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 20.0),
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num2controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Level',
hintText: 'Enter Second Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num3controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs',
hintText: 'Enter Third Number',
),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: TextField(
onChanged: (value) => _calculate(),
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
controller: num4controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Meal carbs 2',
hintText: 'Enter Fourth Number',
),
),
),
const SizedBox(
width: 8,
),
],
),
Text(
'Difference between Target Level and Current Level: $result'),
],
),
),
),
);
}
}
|
[
"Full Code\nimport 'package:flutter/material.dart';\nimport 'package:flutter/services.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n const appTitle = 'Help with a meal....';\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n title: appTitle,\n home: Scaffold(\n appBar: AppBar(\n title: const Text(appTitle),\n backgroundColor: Colors.grey,\n foregroundColor: Colors.black,\n ),\n body: const AddTwoNumbers(),\n ),\n );\n }\n}\n\nclass AddTwoNumbers extends StatefulWidget {\n const AddTwoNumbers({super.key});\n\n @override\n // ignore: library_private_types_in_public_api\n _AddTwoNumbersState createState() => _AddTwoNumbersState();\n}\n\nclass _AddTwoNumbersState extends State<AddTwoNumbers> {\n TextEditingController numR1C1controller =\n TextEditingController(); //Changed name of the texteditingcontroller as Row as R and Column as C\n TextEditingController numR1C2controller = TextEditingController();\n TextEditingController numR1C3controller = TextEditingController();\n TextEditingController numR2C1controller = TextEditingController();\n TextEditingController numR2C2controller = TextEditingController();\n TextEditingController numR2C3controller = TextEditingController();\n String result = \"0\";\n String result2 = \"0\";\n\n _calculateR1() {\n if (numR1C1controller.text.isNotEmpty &&\n numR1C2controller.text.isNotEmpty) {\n setState(() {\n double sum = double.parse(numR1C1controller.text) -\n double.parse(numR1C2controller.text);\n numR1C3controller.text = sum.toStringAsFixed(1);\n result = sum.toStringAsFixed(1);\n });\n }\n }\n\n _calculateR2() {\n if (numR2C1controller.text.isNotEmpty &&\n numR2C2controller.text.isNotEmpty) {\n setState(() {\n double sum = double.parse(numR2C1controller.text) -\n double.parse(numR2C2controller.text);\n numR2C3controller.text = sum.toStringAsFixed(1);\n result2 = sum.toStringAsFixed(1);\n });\n }\n }\n\n @override\n Widget build(BuildContext context) {\n return SafeArea(\n child: Scaffold(\n body: Container(\n padding: const EdgeInsets.all(10.0),\n child: Column(\n children: [\n Row(\n children: <Widget>[\n Expanded(\n child: TextField(\n textAlign: TextAlign.center,\n style: const TextStyle(fontSize: 20.0),\n onChanged: (value) => _calculateR1(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR1C1controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Target Level',\n hintText: 'Enter First Number',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n Expanded(\n child: TextField(\n textAlign: TextAlign.center,\n style: const TextStyle(fontSize: 20.0),\n onChanged: (value) => _calculateR1(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR1C2controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Current Level',\n hintText: 'Enter Second Number',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n Expanded(\n child: TextField(\n textAlign: TextAlign.center,\n style: const TextStyle(fontSize: 20.0),\n onChanged: (value) => _calculateR1(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR1C3controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Result',\n hintText: '',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n ],\n ),\n const SizedBox(\n height: 8,\n ),\n Row(\n children: [\n Expanded(\n child: TextField(\n onChanged: (value) => _calculateR2(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR2C1controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Current Meal carbs',\n hintText: 'Enter Third Number',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n Expanded(\n child: TextField(\n onChanged: (value) => _calculateR2(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR2C2controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Current Meal carbs 2',\n hintText: 'Enter Fourth Number',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n Expanded(\n child: TextField(\n textAlign: TextAlign.center,\n style: const TextStyle(fontSize: 20.0),\n onChanged: (value) => _calculateR2(),\n keyboardType:\n const TextInputType.numberWithOptions(decimal: true),\n controller: numR2C3controller,\n inputFormatters: <TextInputFormatter>[\n FilteringTextInputFormatter.digitsOnly\n ],\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Result',\n hintText: '',\n ),\n ),\n ),\n const SizedBox(\n width: 8,\n ),\n ],\n ),\n Text(\n 'Difference between Target Level and Current Level: $result'),\n ],\n ),\n ),\n ),\n );\n }\n}\n\nOutput\n\nAdd this line to the textfield widget to allow only numbers to be inputted in the text field.\n inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],\n\nHope this helps. Happy Coding :)\n"
] |
[
0
] |
[] |
[] |
[
"dart",
"flutter",
"row"
] |
stackoverflow_0074666886_dart_flutter_row.txt
|
Q:
How is this mystery function using (foldr), right associative if it takes out the elements from the list starting from the left?
mystery [1,2,3]
= foldr snoc [] [1,2,3]
= snoc 1 (foldr snoc [] [2,3])
= snoc 1 (snoc 2 (foldr snoc [] [3]))
= snoc 1 (snoc 2 (snoc 3 (foldr snoc [] [])))
= snoc 1 (snoc 2 (snoc 3 ([])))
= snoc 1 (snoc 2 ([3] ++ [2])
= [3,2] ++ [1]
= [3,2,1]
I don't get how it is being right associative here using foldr. Since it takes 1 out of the list first, isn't that starting to evaluate from the left side of the list slowly to the right?
Thanks.
A:
Since it takes 1 out of the list first, isn't that starting to evaluate from the left side of the list slowly to the right? Thanks.
Indeed, it is evaluating from the left but snoc is defined as
snoc x y = y ++ [x]
hence in the next step x appears to move from the "left" (first argument of snoc) to the "right" (in the second argument of ++).
So, we have
snoc 1 (snoc 2 (snoc 3 ([])))
= snoc 2 (snoc 3 ([])) ++ [1]
= (snoc 3 ([]) ++ [2]) ++ [1]
= (([] ++ [3]) ++ [2]) ++ [1]
= [3,2,1]
If we wanted to follow the evaluation strategy more pedantically, we should write:
mystery [1,2,3]
= foldr snoc [] [1,2,3]
= snoc 1 (foldr snoc [] [2,3])
= foldr snoc [] [2,3] ++ [1]
= snoc 2 (foldr snoc [] [3]) ++ [1]
= (foldr snoc [] [3] ++ [2]) ++ [1]
= (snoc 3 (foldr snoc [] []) ++ [2]) ++ [1]
= ((foldr snoc [] [] ++ [3]) ++ [2]) ++ [1]
= (([] ++ [3]) ++ [2]) ++ [1]
= ... = [3,2,1]
Note how in each step we simplify as to the left as possible.
That being said, in Haskell the evaluation order is not so important: as long as you perform correct reductions (and terminate) you 'll always end up with the same result. Evaluation order only matters when evaluating performance (and termination).
|
How is this mystery function using (foldr), right associative if it takes out the elements from the list starting from the left?
|
mystery [1,2,3]
= foldr snoc [] [1,2,3]
= snoc 1 (foldr snoc [] [2,3])
= snoc 1 (snoc 2 (foldr snoc [] [3]))
= snoc 1 (snoc 2 (snoc 3 (foldr snoc [] [])))
= snoc 1 (snoc 2 (snoc 3 ([])))
= snoc 1 (snoc 2 ([3] ++ [2])
= [3,2] ++ [1]
= [3,2,1]
I don't get how it is being right associative here using foldr. Since it takes 1 out of the list first, isn't that starting to evaluate from the left side of the list slowly to the right?
Thanks.
|
[
"\nSince it takes 1 out of the list first, isn't that starting to evaluate from the left side of the list slowly to the right? Thanks.\n\nIndeed, it is evaluating from the left but snoc is defined as\nsnoc x y = y ++ [x]\n\nhence in the next step x appears to move from the \"left\" (first argument of snoc) to the \"right\" (in the second argument of ++).\nSo, we have\nsnoc 1 (snoc 2 (snoc 3 ([])))\n= snoc 2 (snoc 3 ([])) ++ [1]\n= (snoc 3 ([]) ++ [2]) ++ [1]\n= (([] ++ [3]) ++ [2]) ++ [1]\n= [3,2,1]\n\n\nIf we wanted to follow the evaluation strategy more pedantically, we should write:\nmystery [1,2,3]\n= foldr snoc [] [1,2,3]\n= snoc 1 (foldr snoc [] [2,3])\n= foldr snoc [] [2,3] ++ [1]\n= snoc 2 (foldr snoc [] [3]) ++ [1]\n= (foldr snoc [] [3] ++ [2]) ++ [1]\n= (snoc 3 (foldr snoc [] []) ++ [2]) ++ [1]\n= ((foldr snoc [] [] ++ [3]) ++ [2]) ++ [1]\n= (([] ++ [3]) ++ [2]) ++ [1]\n= ... = [3,2,1]\n\nNote how in each step we simplify as to the left as possible.\nThat being said, in Haskell the evaluation order is not so important: as long as you perform correct reductions (and terminate) you 'll always end up with the same result. Evaluation order only matters when evaluating performance (and termination).\n"
] |
[
0
] |
[] |
[] |
[
"haskell"
] |
stackoverflow_0074668432_haskell.txt
|
Q:
Do need use imagedestroy() before unset Array in PHP?
So i got array like this:
$array = [];
$array[0] = imagecreatetruecolor(10, 10);
$array[1] = imagecreatetruecolor(10, 10);
...
$array[1000] = imagecreatetruecolor(10, 10);
All elemets in array above is GdImage. So, do i need to do something like this before unset array to free memory?
foreach($array as $value)
{
imagedestroy($value);
}
$array = null;
unset($array);
or just do?
$array = null;
unset($array);
A:
Reference https://www.php.net/manual/en/function.imagedestroy.php says:
8.0.0 This function is a NOP now.
So, there's no need to call it. Just unset() or set to null as you asked. The garbage collector will free the memory.
|
Do need use imagedestroy() before unset Array in PHP?
|
So i got array like this:
$array = [];
$array[0] = imagecreatetruecolor(10, 10);
$array[1] = imagecreatetruecolor(10, 10);
...
$array[1000] = imagecreatetruecolor(10, 10);
All elemets in array above is GdImage. So, do i need to do something like this before unset array to free memory?
foreach($array as $value)
{
imagedestroy($value);
}
$array = null;
unset($array);
or just do?
$array = null;
unset($array);
|
[
"Reference https://www.php.net/manual/en/function.imagedestroy.php says:\n\n8.0.0 This function is a NOP now.\n\nSo, there's no need to call it. Just unset() or set to null as you asked. The garbage collector will free the memory.\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"image",
"php"
] |
stackoverflow_0074668445_arrays_image_php.txt
|
Q:
Error: RPC failed; Curl 92 HTTP/2 stream 5 was not closed cleanly before end of the underlying stream
I've been trying to push my code from VS code to a newly created github repo but it keeps giving an error.
The process begins but ends halfway.
I tried switching networks but nothing changed.
A:
Here are some possible solutions to this error:
Check your internet connection. Make sure you have a stable and fast
connection to avoid any interruption during the push process.
Restart your computer and try again. This could help resolve any
temporary issues that may be causing the error.
Check if the repository URL is correct. Make sure you are using the
correct URL for the repository you are trying to push to.
Try pushing using the command line. Open a terminal window in VS
Code and try pushing using the git push command. This can help
determine if the issue is specific to the VS Code extension or not.
If you are using a VPN, try disabling it and see if that resolves
the issue. Some VPNs can cause issues with HTTP/2 streams.
Check if there are any pending changes or conflicts in your local
repository that need to be resolved before pushing.
Try clearing the git cache and see if that fixes the issue. You can
do this by running the following command: git config --global
credential.helper 'cache --timeout=0'
If none of the above solutions work, try contacting GitHub support
for further assistance.
|
Error: RPC failed; Curl 92 HTTP/2 stream 5 was not closed cleanly before end of the underlying stream
|
I've been trying to push my code from VS code to a newly created github repo but it keeps giving an error.
The process begins but ends halfway.
I tried switching networks but nothing changed.
|
[
"Here are some possible solutions to this error:\n\nCheck your internet connection. Make sure you have a stable and fast\nconnection to avoid any interruption during the push process.\nRestart your computer and try again. This could help resolve any\ntemporary issues that may be causing the error.\nCheck if the repository URL is correct. Make sure you are using the\ncorrect URL for the repository you are trying to push to.\nTry pushing using the command line. Open a terminal window in VS\nCode and try pushing using the git push command. This can help\ndetermine if the issue is specific to the VS Code extension or not.\nIf you are using a VPN, try disabling it and see if that resolves\nthe issue. Some VPNs can cause issues with HTTP/2 streams.\nCheck if there are any pending changes or conflicts in your local\nrepository that need to be resolved before pushing.\nTry clearing the git cache and see if that fixes the issue. You can\ndo this by running the following command: git config --global\ncredential.helper 'cache --timeout=0'\nIf none of the above solutions work, try contacting GitHub support\nfor further assistance.\n\n"
] |
[
0
] |
[] |
[] |
[
"git_push"
] |
stackoverflow_0074668476_git_push.txt
|
Q:
ESP32 and Raspberry Pi connection issue
I have a problem with the serial connection between an ESP32 and a Raspberry Pi.
I have two simple example codes as follows, one made in python to read the data in RPi and the other to send a message by serial constantly.
import serial
arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
while True:
data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
if data:
print data
Once connected the following happens:
I activate the python script and the data is read correctly.
If I turn off the script using CTRL+C
I activate the python script again
No data is displayed
The same happens if I connect and disconnect the USB cable.
If I restart the ESP32 then it starts working again (but I can't restart it constantly).
I also try with cat command but it only work one time, after trying CTRL+C and doing it again it does not print anything in the command terminal
cat /dev/ttyUSB0
I did this same test with the arduino serial terminal in windows but it works perfectly, connecting or disconnecting, it always resumes the data acquisition.
Should I take something else into account that I am not seeing at the hardware level?
It should be noted that the ports are active and I can receive data, the problem is when the operation is restarted when the script does not seem to accept it anymore. Is the port then unused?
Thanks
A:
Try using a keyboard interrupt to properly close the serial port when you quit the script.
import serial
with serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1) as ser:
run = True
while run:
try:
data = ser.readline()[:-2] #the last BYTES gets rid of the new-line chars
if data:
print data
except KeyboardInterrupt: // Responds to ctrl-c
run = False
ser.close()
A:
For getting data from Esp32 to Raspberry pi, you first need to install Arduino IDE on Raspberry pi from (https://www.arduino.cc/en/software). Make sure you have install Linux ARM 32/64 bit version on raspberry pi. Then install it. After installing it you need to open it on background while Serial monitor should be on. Hopefully you can get your data from Esp without any interruption.
|
ESP32 and Raspberry Pi connection issue
|
I have a problem with the serial connection between an ESP32 and a Raspberry Pi.
I have two simple example codes as follows, one made in python to read the data in RPi and the other to send a message by serial constantly.
import serial
arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
while True:
data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
if data:
print data
Once connected the following happens:
I activate the python script and the data is read correctly.
If I turn off the script using CTRL+C
I activate the python script again
No data is displayed
The same happens if I connect and disconnect the USB cable.
If I restart the ESP32 then it starts working again (but I can't restart it constantly).
I also try with cat command but it only work one time, after trying CTRL+C and doing it again it does not print anything in the command terminal
cat /dev/ttyUSB0
I did this same test with the arduino serial terminal in windows but it works perfectly, connecting or disconnecting, it always resumes the data acquisition.
Should I take something else into account that I am not seeing at the hardware level?
It should be noted that the ports are active and I can receive data, the problem is when the operation is restarted when the script does not seem to accept it anymore. Is the port then unused?
Thanks
|
[
"Try using a keyboard interrupt to properly close the serial port when you quit the script.\nimport serial\n\nwith serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1) as ser:\n run = True\n while run:\n try:\n data = ser.readline()[:-2] #the last BYTES gets rid of the new-line chars\n if data:\n print data\n except KeyboardInterrupt: // Responds to ctrl-c\n run = False\n\n ser.close()\n\n",
"For getting data from Esp32 to Raspberry pi, you first need to install Arduino IDE on Raspberry pi from (https://www.arduino.cc/en/software). Make sure you have install Linux ARM 32/64 bit version on raspberry pi. Then install it. After installing it you need to open it on background while Serial monitor should be on. Hopefully you can get your data from Esp without any interruption.\n"
] |
[
0,
0
] |
[] |
[] |
[
"esp32",
"raspberry_pi"
] |
stackoverflow_0067242706_esp32_raspberry_pi.txt
|
Q:
How do I get variables from a Python script that are visible in the sh script?
I need to send notifications about new ssh connections.
I was able to implement this through the sh script. But it is difficult to maintain, I would like to use a python script instead.
notify-lo.py
#!/usr/bin/env python3
....
....
I made the script an executable file.
chmod +x notify-lo.py
I added my script call to the pam_exec module calls.
session optional pam_exec.so /usr/local/bin/notify-lo.py
Is it even possible to implement this? Will I be able to have access from my script to variables such as $PAM_TYPE, $PAM_SERVICE, $PAM_RUSER and others?
UPDATE.
An example of what my shell script is doing now (I want to replace it with python).
#!/bin/bash
TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ID="xxxxxxxxxxxxxx"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"
if [ "$PAM_TYPE" != "open_session" ]
then
exit 0
else
curl -s -X POST $URL -d chat_id=$ID -d text="$(echo -e "Host: `hostname`\nUser: $PAM_USER\nHost: $PAM_RHOST")" > /dev/null 2>&1
exit 0
fi
A:
These variables that are available to the shell script are called environment variables and are separate from Python variables. To get environment variables in python, you need to use the os.environ dictionary. You can do it like this:
import os
pam_type = os.environ['PAM_TYPE']
print(pam_type)
pam_service = os.environ['PAM_SERVICE']
print(pam_service)
pam_ruser = os.environ['PAM_RUSER']
print(pam_ruser)
Note that you need to remove the leading dollar sign ($)
|
How do I get variables from a Python script that are visible in the sh script?
|
I need to send notifications about new ssh connections.
I was able to implement this through the sh script. But it is difficult to maintain, I would like to use a python script instead.
notify-lo.py
#!/usr/bin/env python3
....
....
I made the script an executable file.
chmod +x notify-lo.py
I added my script call to the pam_exec module calls.
session optional pam_exec.so /usr/local/bin/notify-lo.py
Is it even possible to implement this? Will I be able to have access from my script to variables such as $PAM_TYPE, $PAM_SERVICE, $PAM_RUSER and others?
UPDATE.
An example of what my shell script is doing now (I want to replace it with python).
#!/bin/bash
TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ID="xxxxxxxxxxxxxx"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"
if [ "$PAM_TYPE" != "open_session" ]
then
exit 0
else
curl -s -X POST $URL -d chat_id=$ID -d text="$(echo -e "Host: `hostname`\nUser: $PAM_USER\nHost: $PAM_RHOST")" > /dev/null 2>&1
exit 0
fi
|
[
"These variables that are available to the shell script are called environment variables and are separate from Python variables. To get environment variables in python, you need to use the os.environ dictionary. You can do it like this:\nimport os\n\n\npam_type = os.environ['PAM_TYPE']\nprint(pam_type)\n\npam_service = os.environ['PAM_SERVICE']\nprint(pam_service)\n\npam_ruser = os.environ['PAM_RUSER']\nprint(pam_ruser)\n\nNote that you need to remove the leading dollar sign ($)\n"
] |
[
2
] |
[] |
[] |
[
"linux",
"python",
"shell"
] |
stackoverflow_0074668478_linux_python_shell.txt
|
Q:
Add a reaction to a message in with interaction
Discord.py 2.0
I cant add reaction in interaction message
@bot.tree.command()
@app_commands.describe(question="Give a title")
async def poll(interaction: discord.Interaction, question: str):
emb = discord.Embed(title=f":bar_chart: {question}\n",
type="rich")
message = await interaction.response.send_message(embed=emb)
emoji = ("✅")
await interaction.message.add_reaction(emoji)
Also getting error: discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'
A:
I think it is:
await message.add_reaction(emoji)
|
Add a reaction to a message in with interaction
|
Discord.py 2.0
I cant add reaction in interaction message
@bot.tree.command()
@app_commands.describe(question="Give a title")
async def poll(interaction: discord.Interaction, question: str):
emb = discord.Embed(title=f":bar_chart: {question}\n",
type="rich")
message = await interaction.response.send_message(embed=emb)
emoji = ("✅")
await interaction.message.add_reaction(emoji)
Also getting error: discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'
|
[
"I think it is:\nawait message.add_reaction(emoji)\n\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0074668456_discord_discord.py_python.txt
|
Q:
How to create an unlimited Azure Video Indexer account
How can I create an unlimited account on Azure Video Indexer and access it from videoindexer.ai?
My Observation
Although a solid service, some things are quite complicated, e.g.,
sign up/in and account management, where a single email address
could create different accounts based on whether the
authentication was done with AAD or Personal Microsoft or Google
account.
The workflow seems confusing for an Azure newbie. A first time user
should just be able to create an unlimited account without going down the
rabbit hole reading different disconnected documentations which are
usually not helpful.
A:
I created unlimited (paid) accounts but couldn't find them on videoindexer.ai. I had to switch between tenants to resolve the issue.
Reference: https://learn.microsoft.com/en-us/azure/azure-video-indexer/switch-tenants-portal
|
How to create an unlimited Azure Video Indexer account
|
How can I create an unlimited account on Azure Video Indexer and access it from videoindexer.ai?
My Observation
Although a solid service, some things are quite complicated, e.g.,
sign up/in and account management, where a single email address
could create different accounts based on whether the
authentication was done with AAD or Personal Microsoft or Google
account.
The workflow seems confusing for an Azure newbie. A first time user
should just be able to create an unlimited account without going down the
rabbit hole reading different disconnected documentations which are
usually not helpful.
|
[
"I created unlimited (paid) accounts but couldn't find them on videoindexer.ai. I had to switch between tenants to resolve the issue.\nReference: https://learn.microsoft.com/en-us/azure/azure-video-indexer/switch-tenants-portal\n"
] |
[
0
] |
[] |
[] |
[
"azure",
"video_indexer"
] |
stackoverflow_0074664562_azure_video_indexer.txt
|
Q:
Is there a C# coding style manual ? I need to know how to style/indent long statements
does anybody know how to style/indent long C# statements? I don't know exactly how to style that code, i use to put enter's to clear up the code, but i would like to have a manual or guide that specifies how to style that kind of code.
Here i have a few examples:
Thank you!
A:
This is opinion based somehow, but your code should be readable and lines should not be too long to make users scroll horizontally anywhere. by the way, you can see the Microsoft official coding conventions here :
Microsoft Coding Conventions
|
Is there a C# coding style manual ? I need to know how to style/indent long statements
|
does anybody know how to style/indent long C# statements? I don't know exactly how to style that code, i use to put enter's to clear up the code, but i would like to have a manual or guide that specifies how to style that kind of code.
Here i have a few examples:
Thank you!
|
[
"This is opinion based somehow, but your code should be readable and lines should not be too long to make users scroll horizontally anywhere. by the way, you can see the Microsoft official coding conventions here :\nMicrosoft Coding Conventions\n"
] |
[
0
] |
[
"Use whitespaces. These are ignored while compiling\n"
] |
[
-1
] |
[
"c#",
"coding_style"
] |
stackoverflow_0074667301_c#_coding_style.txt
|
Q:
Nuxt 3 #imports should be transformed with real imports
I am using Nuxt 3 and I want to import vuetify.
I've successfully imported vuetify and I can use the componetns of vuetify. And everythinh is working fine, but I am getting a warning and don't know how to fix it
I've added vuetify as a plugin.
This is the warning:
[nuxt] #imports should be transformed with real imports. There seems to be something wrong with the imports plugin.
This is my nuxt.config.ts
export default defineNuxtConfig({
css: [
'vuetify/lib/styles/main.sass'
],
build: {
transpile: [
'vuetify'
]
}
})
And my plugins/vuetify.ts
import {defineNuxtPlugin} from "#app";
import {createVuetify} from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
export default defineNuxtPlugin((nuxtApp) => {
const vuetify = createVuetify({
components,
directives
})
nuxtApp.vueApp.use(vuetify)
})
A:
From here, it looks like you also need to set the following
const vuetify = createVuetify({
ssr: true,
})
|
Nuxt 3 #imports should be transformed with real imports
|
I am using Nuxt 3 and I want to import vuetify.
I've successfully imported vuetify and I can use the componetns of vuetify. And everythinh is working fine, but I am getting a warning and don't know how to fix it
I've added vuetify as a plugin.
This is the warning:
[nuxt] #imports should be transformed with real imports. There seems to be something wrong with the imports plugin.
This is my nuxt.config.ts
export default defineNuxtConfig({
css: [
'vuetify/lib/styles/main.sass'
],
build: {
transpile: [
'vuetify'
]
}
})
And my plugins/vuetify.ts
import {defineNuxtPlugin} from "#app";
import {createVuetify} from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
export default defineNuxtPlugin((nuxtApp) => {
const vuetify = createVuetify({
components,
directives
})
nuxtApp.vueApp.use(vuetify)
})
|
[
"From here, it looks like you also need to set the following\nconst vuetify = createVuetify({\n ssr: true,\n})\n\n"
] |
[
1
] |
[] |
[] |
[
"nuxt.js",
"nuxtjs3",
"vue.js",
"vuetify.js"
] |
stackoverflow_0074668273_nuxt.js_nuxtjs3_vue.js_vuetify.js.txt
|
Q:
How should I initialize ngbDatepicker with formControlName instead of [(ngmodel)]
I need to use ReactiveForms, with [formGroup] and formGroupName="field"
<form [formGroup]="generalForm" (ngSubmit)="onSubmit()">
<input class="form-control" placeholder="yyyy-mm-dd"
formControlName="dateIni" ngbDatepicker #a="ngbDatepicker">
</form>
Component.ts
generalForm: FormGroup;
ngOnInit() {
this.generalForm = this.formBuilder.group({
name: ['', Validators.required],
dateIni: ['', Validators.required],
dateFin: ['', Validators.required],
registerDateLimit: ['', Validators.required],
});
}
In my code, I tried to put a default value:
public dateIni: { year: 2017, month: 8, day: 8 };
or
@Input() dateIni: { year: 2017, month: 8, day: 8 };
but it is not taking the default value and all the docs only mention the case with template forms.
Any Idea how should I do it ?
A:
I have faced the same problem and resolved using below code snippet
import { Component, OnInit, EventEmitter } from '@angular/core';
import { FormBuilder, Validators, FormArray, FormGroup } from '@angular/forms';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
generalForm: FormGroup;
constructor(
private fb: FormBuilder,
private datePipe: DatePipe) { }
ngOnInit() {
this.intilizeForm();
const dateIni = "2018-12-08"
const iniYear = Number(this.datePipe.transform(dateIni, 'yyyy'));
const iniMonth = Number(this.datePipe.transform(dateIni, 'MM'));
const iniDay = Number(this.datePipe.transform(dateIni, 'dd'));
this.generalForm.controls.dateIni.setValue({
year: iniYear ,
month: iniMonth ,
day: iniDay
});
}
intilizeForm(): void {
// Here also we can set the intial value Like dateIni:[ {year:2018,month:08, day: 12}, .....
this.generalForm = this.fb.group({
name: ['', Validators.required],
dateIni: ['', Validators.required],
dateFin: ['', Validators.required],
registerDateLimit: ['', Validators.required],
});
}
A:
dateIni: ['', Validators.required],
you need to put your initial value here like
dateIni: ['2014-01-01', Validators.required],
in correct format
A:
Datepicker is integrated with Angular forms and works with both reactive and template-driven forms. So you could use [(ngModel)], [formControl], formControlName, etc. Using ngModel will allow you both to get and set selected value
Example with formControlName
HTML
<input
formControlName="date_input"
placeholder="yyyy-mm-dd"
ngbDatepicker
#de="ngbDatepicker">
Typescript
public myForm: FormGroup;
// ...
// > converting the date String to Date object
let date = new Date('2022-12-01T00:00:00+00:00');
this.myForm.setValue({
// ...
date_input : {
year: date.getUTCFullYear(), // output: 2022
month: date.getUTCMonth() +1, // output: 12
day: date.getUTCDate() // output: 01
},
// ...
});
|
How should I initialize ngbDatepicker with formControlName instead of [(ngmodel)]
|
I need to use ReactiveForms, with [formGroup] and formGroupName="field"
<form [formGroup]="generalForm" (ngSubmit)="onSubmit()">
<input class="form-control" placeholder="yyyy-mm-dd"
formControlName="dateIni" ngbDatepicker #a="ngbDatepicker">
</form>
Component.ts
generalForm: FormGroup;
ngOnInit() {
this.generalForm = this.formBuilder.group({
name: ['', Validators.required],
dateIni: ['', Validators.required],
dateFin: ['', Validators.required],
registerDateLimit: ['', Validators.required],
});
}
In my code, I tried to put a default value:
public dateIni: { year: 2017, month: 8, day: 8 };
or
@Input() dateIni: { year: 2017, month: 8, day: 8 };
but it is not taking the default value and all the docs only mention the case with template forms.
Any Idea how should I do it ?
|
[
"I have faced the same problem and resolved using below code snippet\n\n import { Component, OnInit, EventEmitter } from '@angular/core';\n import { FormBuilder, Validators, FormArray, FormGroup } from '@angular/forms';\n import { DatePipe } from '@angular/common';\n \n @Component({\n selector: 'app-profile',\n templateUrl: './profile.component.html',\n styleUrls: ['./profile.component.css']\n })\n export class ProfileComponent implements OnInit {\n \n generalForm: FormGroup;\n \n constructor(\n private fb: FormBuilder,\n private datePipe: DatePipe) { }\n \n ngOnInit() {\n \n this.intilizeForm();\n \n const dateIni = \"2018-12-08\"\n const iniYear = Number(this.datePipe.transform(dateIni, 'yyyy'));\n const iniMonth = Number(this.datePipe.transform(dateIni, 'MM'));\n const iniDay = Number(this.datePipe.transform(dateIni, 'dd'));\n this.generalForm.controls.dateIni.setValue({\n year: iniYear ,\n month: iniMonth ,\n day: iniDay\n });\n \n }\n \n intilizeForm(): void {\n // Here also we can set the intial value Like dateIni:[ {year:2018,month:08, day: 12}, ..... \n this.generalForm = this.fb.group({\n name: ['', Validators.required],\n dateIni: ['', Validators.required],\n dateFin: ['', Validators.required],\n registerDateLimit: ['', Validators.required],\n \n });\n \n }\n\n",
" dateIni: ['', Validators.required],\n\nyou need to put your initial value here like\n dateIni: ['2014-01-01', Validators.required],\n\nin correct format\n",
"Datepicker is integrated with Angular forms and works with both reactive and template-driven forms. So you could use [(ngModel)], [formControl], formControlName, etc. Using ngModel will allow you both to get and set selected value\nExample with formControlName\nHTML\n<input\n formControlName=\"date_input\" \n placeholder=\"yyyy-mm-dd\"\n ngbDatepicker\n #de=\"ngbDatepicker\">\n\nTypescript\npublic myForm: FormGroup; \n\n// ...\n\n// > converting the date String to Date object\nlet date = new Date('2022-12-01T00:00:00+00:00'); \n\nthis.myForm.setValue({\n\n // ...\n\n date_input : {\n year: date.getUTCFullYear(), // output: 2022\n month: date.getUTCMonth() +1, // output: 12\n day: date.getUTCDate() // output: 01\n },\n\n // ...\n\n});\n\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"angular",
"ng_bootstrap"
] |
stackoverflow_0050805667_angular_ng_bootstrap.txt
|
Q:
Regex match any characters prefixed with a string and specific length in JavaScript
I need to write a JavaScript program where it validates input.
Requirement:
Input will have a specific prefix. (eg: --NAME--)
After this prefix, there can be any characters. (eg:
--NAME--any-name_wit#-any*_special_char@#$%)
Minimum length of total input (or length of suffix) should be 50 (for example)
I was able to write regex for the first two points, but I couldn't include the final point.
here is what I have tried for the first two points.
input.match(^--NAME--(.*)$)
A:
Use pattern /^--NAME--.{42,}$/
.{42,} - This will match 42 or more characters. The total will be 50 including the prefix (--NAME--).
const regex = /^--NAME--.{42,}$/
console.log(regex.test("--NAME--C$#V"))
console.log(regex.test("--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff"))
Demo in regex101.com
A:
You can use a lookahead assertion for length:
/^(?=.{50})--NAME--.*$/
From start, at least 50 characters, starting with --NAME--.
|
Regex match any characters prefixed with a string and specific length in JavaScript
|
I need to write a JavaScript program where it validates input.
Requirement:
Input will have a specific prefix. (eg: --NAME--)
After this prefix, there can be any characters. (eg:
--NAME--any-name_wit#-any*_special_char@#$%)
Minimum length of total input (or length of suffix) should be 50 (for example)
I was able to write regex for the first two points, but I couldn't include the final point.
here is what I have tried for the first two points.
input.match(^--NAME--(.*)$)
|
[
"Use pattern /^--NAME--.{42,}$/\n.{42,} - This will match 42 or more characters. The total will be 50 including the prefix (--NAME--).\n\n\nconst regex = /^--NAME--.{42,}$/\n\nconsole.log(regex.test(\"--NAME--C$#V\"))\nconsole.log(regex.test(\"--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff\"))\n\n\n\nDemo in regex101.com\n",
"You can use a lookahead assertion for length:\n/^(?=.{50})--NAME--.*$/\n\nFrom start, at least 50 characters, starting with --NAME--.\n"
] |
[
2,
1
] |
[] |
[] |
[
"javascript",
"regex"
] |
stackoverflow_0074668364_javascript_regex.txt
|
Q:
Text of the textbox is always empty on a customized styling in wpf
Hey I'm designing a new style for a textbox in my WPF application using XAML codes. The textbox is a combination of textbox and textblock, I used the textblock to show name of the textbox when the text is null, and disappears when the text is filled, but there is a problem when I run the app and fill something in the textbox it seems that it's working properly but in the backend when I want to access the textbox Text it's null even though it's filled!!!!
Am I doing something wrong from the base or I missed something to do.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type TextBox}"
x:Key="TextBoxTheme">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border CornerRadius="10"
Background="#353340"
Width="200"
Height="40">
<Grid>
<Rectangle StrokeThickness="1"/>
<TextBox Margin="1"
Text="{TemplateBinding Property=Text}"
BorderThickness="0"
Background="Transparent"
VerticalAlignment="Center"
Padding="5"
Foreground="#CFCFCF"
x:Name="textBox"/>
<TextBlock IsHitTestVisible="False"
Text="{TemplateBinding Name}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="10, 0, 0, 0"
FontSize="11"
Foreground="DarkGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=textBox}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
<Setter Property="Visibility" Value="Hidden"/>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
A:
Instead of giving the TextBox an area to display its contents, you have overlapped it on top with another TextBox.
To display its content, the TextBox looks in the Template for ScrollViewer x:Name="PART_ContentHost".
Try a Template like this:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<Grid>
<TextBlock x:Name="PART_TextBlock" Text="{TemplateBinding Name}" Visibility="Collapsed"/>
<ScrollViewer x:Name="PART_ContentHost"
Focusable="false"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Text"
Value="{x:Static sys:String.Empty}">
<Setter TargetName="PART_TextBlock" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
A:
Found this on the YouTube video comments where this question code comes from. In the template xaml file do the following:
Repalce This:
Text="{TemplateBinding Text}"
With This:
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}"
I was able to capture text from the TextChanged event after this change.
|
Text of the textbox is always empty on a customized styling in wpf
|
Hey I'm designing a new style for a textbox in my WPF application using XAML codes. The textbox is a combination of textbox and textblock, I used the textblock to show name of the textbox when the text is null, and disappears when the text is filled, but there is a problem when I run the app and fill something in the textbox it seems that it's working properly but in the backend when I want to access the textbox Text it's null even though it's filled!!!!
Am I doing something wrong from the base or I missed something to do.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type TextBox}"
x:Key="TextBoxTheme">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border CornerRadius="10"
Background="#353340"
Width="200"
Height="40">
<Grid>
<Rectangle StrokeThickness="1"/>
<TextBox Margin="1"
Text="{TemplateBinding Property=Text}"
BorderThickness="0"
Background="Transparent"
VerticalAlignment="Center"
Padding="5"
Foreground="#CFCFCF"
x:Name="textBox"/>
<TextBlock IsHitTestVisible="False"
Text="{TemplateBinding Name}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="10, 0, 0, 0"
FontSize="11"
Foreground="DarkGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=textBox}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
<Setter Property="Visibility" Value="Hidden"/>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
|
[
"Instead of giving the TextBox an area to display its contents, you have overlapped it on top with another TextBox.\nTo display its content, the TextBox looks in the Template for ScrollViewer x:Name=\"PART_ContentHost\".\nTry a Template like this:\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <Border x:Name=\"border\" BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\" Background=\"{TemplateBinding Background}\" SnapsToDevicePixels=\"True\">\n <Grid>\n <TextBlock x:Name=\"PART_TextBlock\" Text=\"{TemplateBinding Name}\" Visibility=\"Collapsed\"/>\n <ScrollViewer x:Name=\"PART_ContentHost\"\n Focusable=\"false\"\n HorizontalScrollBarVisibility=\"Hidden\"\n VerticalScrollBarVisibility=\"Hidden\"/>\n </Grid>\n </Border>\n <ControlTemplate.Triggers>\n <Trigger Property=\"Text\"\n Value=\"{x:Static sys:String.Empty}\">\n <Setter TargetName=\"PART_TextBlock\" Property=\"Visibility\" Value=\"Visible\"/>\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n\n",
"Found this on the YouTube video comments where this question code comes from. In the template xaml file do the following:\nRepalce This:\nText=\"{TemplateBinding Text}\"\nWith This:\nText=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}\"\nI was able to capture text from the TextChanged event after this change.\n"
] |
[
1,
0
] |
[
"If you check the documentation for TemplateBinding you'll see it's just syntactic sugar for a one-way RelativeSource binding to the templated parent, so all you need to do is change your TextBox binding to make it two-way:\nText=\"{Binding Path=Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}\"\n\nAlso, I disagree with the comment above about this not being a good idea, one of the whole purposes of WPF's templating system is to make it possible to template existing controls e.g. for redistribution of libraries etc. That said, I don't think Name is the best property to use for your hint text, if for no other reason than the fact that it doesn't allow spaces. A much better solution would be to use an attached property. For a quick-and-dirty solution there's also the Tag property, which you're free to use for whatever you want.\n"
] |
[
-1
] |
[
"c#",
"data_binding",
"styles",
"wpf",
"xaml"
] |
stackoverflow_0068129692_c#_data_binding_styles_wpf_xaml.txt
|
Q:
Vuejs: Multiple CSS template in one application
I'm Vuejs beginners. How can I have multiple template in one application?
Example, for SignIn page, i would like to use Flatkit template, and for Admin dashboard, i would like to use other template (Dashboard). How do i combine those template in one app? In my index.html file, I already insert element for Flatkit, but when I insert Dashboard element, the CSS not working. What is the way to combine those link and script element
Here the project flow
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<!-- LOGIN TEMPLATE -->
<!-- for ios 7 style, multi-resolution icon of 152x152 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-barstyle" content="black-translucent">
<link rel="apple-touch-icon" href="./Flatkit/assets/images/logo.png">
<meta name="apple-mobile-web-app-title" content="Flatkit">
<!-- for Chrome on Android, multi-resolution icon of 196x196 -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="./Flatkit/assets/images/logo.png">
<!-- style -->
<link rel="stylesheet" href="./Flatkit/assets/animate.css/animate.min.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/glyphicons/glyphicons.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/font-awesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/material-design-icons/material-design-icons.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<!-- build:css ../assets/styles/app.min.css -->
<link rel="stylesheet" href="./Flatkit/assets/styles/app.css" type="text/css" />
<!-- endbuild -->
<link rel="stylesheet" href="./Flatkit/assets/styles/font.css" type="text/css" />
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
<script src="./Flatkit/libs/jquery/jquery/dist/jquery.js"></script>
<!-- Bootstrap -->
<script src="./Flatkit/libs/jquery/tether/dist/js/tether.min.js"></script>
<script src="./Flatkit/libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<!-- core -->
<script src="./Flatkit/libs/jquery/underscore/underscore-min.js"></script>
<script src="./Flatkit/libs/jquery/jQuery-Storage-API/jquery.storageapi.min.js"></script>
<script src="./Flatkit/libs/jquery/PACE/pace.min.js"></script>
<script src="./Flatkit/scripts/config.lazyload.js"></script>
<script src="./Flatkit/scripts/palette.js"></script>
<script src="./Flatkit/scripts/ui-load.js"></script>
<script src="./Flatkits/cripts/ui-jp.js"></script>
<script src="./Flatkit/scripts/ui-include.js"></script>
<script src="./Flatkit/scripts/ui-device.js"></script>
<script src="./Flatkit/scripts/ui-form.js"></script>
<script src="./Flatkit/scripts/ui-nav.js"></script>
<script src="./Flatkit/scripts/ui-screenfull.js"></script>
<script src="./Flatkit/scripts/ui-scroll-to.js"></script>
<script src="./Flatkit/scripts/ui-toggle-class.js"></script>
<script src="./Flatkitscripts/app.js"></script>
<!-- ajax -->
<script src="./Flatkit/libs/jquery/jquery-pjax/jquery.pjax.js"></script>
<script src="./Flatkit/scripts/ajax.js"></script>
<!-- endbuild -->
</body>
</html>
A:
you can use 2 different main html page if your main scripts are entirely different. You can configure it in backend.
Another idea is adding only common scripts and styles in html file. And use your scoped styles in components. Add style of each component in "style" tag below "script" tag. make the style scoped using :
VUE COMPONENT:
<template>
</template>
<script>
<script>
<style scoped>
/* your style */
</style>
Scope of this style would only be applicable to current component.
|
Vuejs: Multiple CSS template in one application
|
I'm Vuejs beginners. How can I have multiple template in one application?
Example, for SignIn page, i would like to use Flatkit template, and for Admin dashboard, i would like to use other template (Dashboard). How do i combine those template in one app? In my index.html file, I already insert element for Flatkit, but when I insert Dashboard element, the CSS not working. What is the way to combine those link and script element
Here the project flow
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<!-- LOGIN TEMPLATE -->
<!-- for ios 7 style, multi-resolution icon of 152x152 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-barstyle" content="black-translucent">
<link rel="apple-touch-icon" href="./Flatkit/assets/images/logo.png">
<meta name="apple-mobile-web-app-title" content="Flatkit">
<!-- for Chrome on Android, multi-resolution icon of 196x196 -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="./Flatkit/assets/images/logo.png">
<!-- style -->
<link rel="stylesheet" href="./Flatkit/assets/animate.css/animate.min.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/glyphicons/glyphicons.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/font-awesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/material-design-icons/material-design-icons.css" type="text/css" />
<link rel="stylesheet" href="./Flatkit/assets/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<!-- build:css ../assets/styles/app.min.css -->
<link rel="stylesheet" href="./Flatkit/assets/styles/app.css" type="text/css" />
<!-- endbuild -->
<link rel="stylesheet" href="./Flatkit/assets/styles/font.css" type="text/css" />
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
<script src="./Flatkit/libs/jquery/jquery/dist/jquery.js"></script>
<!-- Bootstrap -->
<script src="./Flatkit/libs/jquery/tether/dist/js/tether.min.js"></script>
<script src="./Flatkit/libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<!-- core -->
<script src="./Flatkit/libs/jquery/underscore/underscore-min.js"></script>
<script src="./Flatkit/libs/jquery/jQuery-Storage-API/jquery.storageapi.min.js"></script>
<script src="./Flatkit/libs/jquery/PACE/pace.min.js"></script>
<script src="./Flatkit/scripts/config.lazyload.js"></script>
<script src="./Flatkit/scripts/palette.js"></script>
<script src="./Flatkit/scripts/ui-load.js"></script>
<script src="./Flatkits/cripts/ui-jp.js"></script>
<script src="./Flatkit/scripts/ui-include.js"></script>
<script src="./Flatkit/scripts/ui-device.js"></script>
<script src="./Flatkit/scripts/ui-form.js"></script>
<script src="./Flatkit/scripts/ui-nav.js"></script>
<script src="./Flatkit/scripts/ui-screenfull.js"></script>
<script src="./Flatkit/scripts/ui-scroll-to.js"></script>
<script src="./Flatkit/scripts/ui-toggle-class.js"></script>
<script src="./Flatkitscripts/app.js"></script>
<!-- ajax -->
<script src="./Flatkit/libs/jquery/jquery-pjax/jquery.pjax.js"></script>
<script src="./Flatkit/scripts/ajax.js"></script>
<!-- endbuild -->
</body>
</html>
|
[
"you can use 2 different main html page if your main scripts are entirely different. You can configure it in backend.\nAnother idea is adding only common scripts and styles in html file. And use your scoped styles in components. Add style of each component in \"style\" tag below \"script\" tag. make the style scoped using :\nVUE COMPONENT:\n<template>\n</template>\n\n<script>\n<script>\n\n<style scoped>\n /* your style */ \n</style>\n\nScope of this style would only be applicable to current component.\n"
] |
[
0
] |
[] |
[] |
[
"css",
"html",
"javascript",
"vue.js"
] |
stackoverflow_0074668392_css_html_javascript_vue.js.txt
|
Q:
Referencing Previous Version of File using Filename
I am saving workbooks with v[ ] next to them to differentiate between latest and earlier versions.
Workbook v1
Workbook v2
...
Workbook v365
Is there a way to create a dynamic formula that does the following:
Detects the current version (365)
References a specific cell (e.g. A2) in the previous version (Workbook v364)
Please let me know! Any help would be really appreciated.
A:
Since you did not answer my clarification questions, the next code will assume that the current workbook is the active one, all versions exist in the same folder and the "reference cell" will be a range in the previous version workbook where from a value must be extracted and it will be found in a sheet named as the active one in the current workbook:
Sub referenceThePrevVersion()
Dim wb As Workbook, curVers As Long, curName As String
Dim prevVersName As String, refVal As Variant, arrCur
Const refCell As String = "A2"
Set wb = ActiveWorkbook 'it my be ThisWorkbook if you need this one where the code exists
curName = wb.name 'the current workbook name
arrCur = Split(curName) 'split its name by spaces and place the words in an array
curVers = CLng(Mid(Split(arrCur(UBound(arrCur)), ".")(0), 2)) 'extract the current version
prevVersName = VBA.replace(curName, "v" & curVers, "v" & curVers - 1) 'obtain the prev version decreasing a unit
'extract the value of refCell, without opening the previous workbook:
refVal = CellV(wb.Path & "\", prevVersName, wb.ActiveSheet.name, Range(refCell).address(, , xlR1C1))
MsgBox refVal 'show the extracted value...
End Sub
Private Function CellV(fpath As String, fName As String, SheetName As String, strRange As String) As Variant
Dim strForm As String
strForm = "'" & fpath & "[" & fName & "]" & SheetName & "'!" & strRange
CellV = Application.ExecuteExcel4Macro(strForm)
End Function
The extracted value is CellV. It now is shown in a message, you may use it as you need.
Of course, if you know the previous version name and its path, you can open it and do whatever you need with its data.
Please, send some feedback after testing the code. If something not clear enough, do not hesitate to ask for clarifications.
|
Referencing Previous Version of File using Filename
|
I am saving workbooks with v[ ] next to them to differentiate between latest and earlier versions.
Workbook v1
Workbook v2
...
Workbook v365
Is there a way to create a dynamic formula that does the following:
Detects the current version (365)
References a specific cell (e.g. A2) in the previous version (Workbook v364)
Please let me know! Any help would be really appreciated.
|
[
"Since you did not answer my clarification questions, the next code will assume that the current workbook is the active one, all versions exist in the same folder and the \"reference cell\" will be a range in the previous version workbook where from a value must be extracted and it will be found in a sheet named as the active one in the current workbook:\nSub referenceThePrevVersion()\n Dim wb As Workbook, curVers As Long, curName As String\n Dim prevVersName As String, refVal As Variant, arrCur\n Const refCell As String = \"A2\"\n\n Set wb = ActiveWorkbook 'it my be ThisWorkbook if you need this one where the code exists\n curName = wb.name 'the current workbook name\n arrCur = Split(curName) 'split its name by spaces and place the words in an array\n curVers = CLng(Mid(Split(arrCur(UBound(arrCur)), \".\")(0), 2)) 'extract the current version\n prevVersName = VBA.replace(curName, \"v\" & curVers, \"v\" & curVers - 1) 'obtain the prev version decreasing a unit\n \n 'extract the value of refCell, without opening the previous workbook:\n refVal = CellV(wb.Path & \"\\\", prevVersName, wb.ActiveSheet.name, Range(refCell).address(, , xlR1C1))\n \n MsgBox refVal 'show the extracted value...\nEnd Sub\n\nPrivate Function CellV(fpath As String, fName As String, SheetName As String, strRange As String) As Variant\n Dim strForm As String\n strForm = \"'\" & fpath & \"[\" & fName & \"]\" & SheetName & \"'!\" & strRange\n CellV = Application.ExecuteExcel4Macro(strForm)\nEnd Function\n\nThe extracted value is CellV. It now is shown in a message, you may use it as you need.\nOf course, if you know the previous version name and its path, you can open it and do whatever you need with its data.\nPlease, send some feedback after testing the code. If something not clear enough, do not hesitate to ask for clarifications.\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"vba",
"xls"
] |
stackoverflow_0074667929_excel_vba_xls.txt
|
Q:
DevOps: Building a production server
I'm completely new to devops and I'm quickly becoming overwhelmed with all the options.
I write python web applications as a solo developer, on my local machine. I have a "staging" server on DigitalOcean, I have multiple websites under different subdomains (eg. myapp.staging.mywebsite.dev). I use git on my local machine and use branches to create multiple versions of my apps and then I use git to push my code to this server so I can see how it looks on the web.
When I'm happy with my web app I want to be able to deploy it to a separate production server on DigitalOcean so I can get real users using my apps. I could just use git to push my code to a new server but are there any other options that will help me create a live site?
A:
In our systems, we handle this scenario with a dedicated publish branch.
The GitHub action workflow for publishing starts like this:
name: Publish
on:
push:
branches: [publish]
so it's only triggered by a push to publish and it deploys to the gh-pages branch in our case.
All the draft work and the review versions live in different branches, with the publish branch itself set to be protected so nothing can pushed to it without proper review.
We also have a review branch where we stage things for pre-publication review, and we merge into publish from review. A colleague has set that part up, but the review branch gets deployed into a staging subdomain similar to yours so we can review it before publication.
|
DevOps: Building a production server
|
I'm completely new to devops and I'm quickly becoming overwhelmed with all the options.
I write python web applications as a solo developer, on my local machine. I have a "staging" server on DigitalOcean, I have multiple websites under different subdomains (eg. myapp.staging.mywebsite.dev). I use git on my local machine and use branches to create multiple versions of my apps and then I use git to push my code to this server so I can see how it looks on the web.
When I'm happy with my web app I want to be able to deploy it to a separate production server on DigitalOcean so I can get real users using my apps. I could just use git to push my code to a new server but are there any other options that will help me create a live site?
|
[
"In our systems, we handle this scenario with a dedicated publish branch.\nThe GitHub action workflow for publishing starts like this:\nname: Publish\n\non:\n push:\n branches: [publish]\n\nso it's only triggered by a push to publish and it deploys to the gh-pages branch in our case.\nAll the draft work and the review versions live in different branches, with the publish branch itself set to be protected so nothing can pushed to it without proper review.\nWe also have a review branch where we stage things for pre-publication review, and we merge into publish from review. A colleague has set that part up, but the review branch gets deployed into a staging subdomain similar to yours so we can review it before publication.\n"
] |
[
0
] |
[] |
[] |
[
"digital_ocean",
"git",
"python"
] |
stackoverflow_0074667043_digital_ocean_git_python.txt
|
Q:
sum of setof in prolog
I have this predicate to get the sum of the length of all borders of a country. I could solve it with findall but I have to use setof. My facts look like this:
borders(sweden,finland,586).
borders(norway,sweden,1619).
My code
circumference(C, Country) :-
findall(X, ( borders(Country, _, X) ; borders(_, Country, X)), Kms),
sum_list(Kms, C).
A:
You cannot find the sum using bagof directly, all you can do is make a list and then sum that list (but you knew that already). In SWI-Prolog there is library(aggregate) that does the bagging and the summing for you. With the facts you have, you would write:
?- aggregate(sum(X), Y^( borders(Y, sweden, X) ; borders(sweden, Y, X) ), Circumference).
Circumference = 2205.
If you instead must obey the whims of your instructor and type "bagof" yourself, or if you are not allowed to use a modern, open source, comprehensive Prolog implementation, you can use the same approach with bagof and manually build the list before summing it:
?- bagof(X, Y^( borders(Y, sweden, X) ; borders(sweden, Y, X) ), Borders).
Borders = [1619, 586].
For reasons that are lost in the mists of time the funny thing with the Var^Goal that you see in both aggregate and bagof is called "existentially qualifying the variables in Goal". You might also read that "^ prevents binding Var in Goal". I cannot explain what this really means.
A:
I ended up using this:
circumference(Z, Country) :- setof(X, Q^(borders(Q,Country,X);borders(Country,Q,X)),Border),
sum_list(Border,Z).
% Adds the numbers in a list.
sum_list([], 0).
sum_list([H|T], Sum) :-
sum_list(T, Rest),
Sum is H + Rest.
|
sum of setof in prolog
|
I have this predicate to get the sum of the length of all borders of a country. I could solve it with findall but I have to use setof. My facts look like this:
borders(sweden,finland,586).
borders(norway,sweden,1619).
My code
circumference(C, Country) :-
findall(X, ( borders(Country, _, X) ; borders(_, Country, X)), Kms),
sum_list(Kms, C).
|
[
"You cannot find the sum using bagof directly, all you can do is make a list and then sum that list (but you knew that already). In SWI-Prolog there is library(aggregate) that does the bagging and the summing for you. With the facts you have, you would write:\n?- aggregate(sum(X), Y^( borders(Y, sweden, X) ; borders(sweden, Y, X) ), Circumference).\nCircumference = 2205.\n\nIf you instead must obey the whims of your instructor and type \"bagof\" yourself, or if you are not allowed to use a modern, open source, comprehensive Prolog implementation, you can use the same approach with bagof and manually build the list before summing it:\n?- bagof(X, Y^( borders(Y, sweden, X) ; borders(sweden, Y, X) ), Borders).\nBorders = [1619, 586].\n\nFor reasons that are lost in the mists of time the funny thing with the Var^Goal that you see in both aggregate and bagof is called \"existentially qualifying the variables in Goal\". You might also read that \"^ prevents binding Var in Goal\". I cannot explain what this really means.\n",
"I ended up using this:\ncircumference(Z, Country) :- setof(X, Q^(borders(Q,Country,X);borders(Country,Q,X)),Border),\n sum_list(Border,Z).\n\n\n% Adds the numbers in a list. \nsum_list([], 0).\nsum_list([H|T], Sum) :-\n sum_list(T, Rest),\n Sum is H + Rest.\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"prolog",
"set",
"sum"
] |
stackoverflow_0069607706_prolog_set_sum.txt
|
Q:
Referencing bool on another game object not working?
I have a hitbox with a script called "accept", I then have 2 prefabs that have a public bool of "isPoor". One of the prefabs = true, the other = false.
When the prefabs with isPoor = true goes into the "accept" hitbox I want the game to fail, and when isPoor = false goes into "accept" hitbox I want the player to win.
The problem with the code I have is that it only ever fails the game, even when an NPC with isPoor = false goes into the "accept" hitbox.
This is the code for the accept hitbox.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class accept : MonoBehaviour
{
public LayerMask grabbable;
public GameObject Spawner;
bool isPoor;
public GameManager gameManager;
public void OnTriggerEnter2D(Collider2D other)
{
isPoor = other.gameObject.GetComponent<Poor>().isPoor;
if (isPoor = true)
{
gameManager.GameOver();
}
if (isPoor = false)
{
gameManager.GameWon();
}
Destroy(other.gameObject);
Spawner.GetComponent<Spawner>().Spawn();
}
}
It's my first time using Unity so I'm a bit stumped. But it seems that the script just treats both prefabs as if they had isPoor = true.
A:
There is no point in making isPoor a field in class accept (which would store it for the entire lifetime of the object), since you are retrieving a new value anyway in OnTriggerEnter2D. Make it a local variable.
Then = is assignment, not comparison (you will get a warning for using = in Visual Studio). Use == for comparison. But for a Boolean this is not necessary. Just test like this:
// bool isPoor; drop this declaration!
public void OnTriggerEnter2D(Collider2D other)
{
bool isPoor = other.gameObject.GetComponent<Poor>().isPoor;
if (isPoor) {
// isPoor == true here
gameManager.GameOver();
} else {
// isPoor == false here
gameManager.GameWon();
}
Destroy(other.gameObject);
Spawner.GetComponent<Spawner>().Spawn();
}
Note that C# has the concept of the "assignment expression" which - besides doing the assignment - yields the assigned value, which is always true in your first if and always false in your second if.
A:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class accept : MonoBehaviour
{
public LayerMask grabbable;
public GameObject Spawner;
bool isPoor;
public GameManager gameManager;
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.GetComponent<Poor>().isPoor)
gameManager.GameOver();
else
gameManager.GameWon();
Destroy(other.gameObject);
Spawner.GetComponent<Spawner>().Spawn();
}
}
|
Referencing bool on another game object not working?
|
I have a hitbox with a script called "accept", I then have 2 prefabs that have a public bool of "isPoor". One of the prefabs = true, the other = false.
When the prefabs with isPoor = true goes into the "accept" hitbox I want the game to fail, and when isPoor = false goes into "accept" hitbox I want the player to win.
The problem with the code I have is that it only ever fails the game, even when an NPC with isPoor = false goes into the "accept" hitbox.
This is the code for the accept hitbox.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class accept : MonoBehaviour
{
public LayerMask grabbable;
public GameObject Spawner;
bool isPoor;
public GameManager gameManager;
public void OnTriggerEnter2D(Collider2D other)
{
isPoor = other.gameObject.GetComponent<Poor>().isPoor;
if (isPoor = true)
{
gameManager.GameOver();
}
if (isPoor = false)
{
gameManager.GameWon();
}
Destroy(other.gameObject);
Spawner.GetComponent<Spawner>().Spawn();
}
}
It's my first time using Unity so I'm a bit stumped. But it seems that the script just treats both prefabs as if they had isPoor = true.
|
[
"There is no point in making isPoor a field in class accept (which would store it for the entire lifetime of the object), since you are retrieving a new value anyway in OnTriggerEnter2D. Make it a local variable.\nThen = is assignment, not comparison (you will get a warning for using = in Visual Studio). Use == for comparison. But for a Boolean this is not necessary. Just test like this:\n// bool isPoor; drop this declaration!\n\npublic void OnTriggerEnter2D(Collider2D other)\n{\n bool isPoor = other.gameObject.GetComponent<Poor>().isPoor;\n if (isPoor) {\n // isPoor == true here\n gameManager.GameOver();\n } else {\n // isPoor == false here\n gameManager.GameWon();\n }\n\n Destroy(other.gameObject);\n Spawner.GetComponent<Spawner>().Spawn();\n}\n\nNote that C# has the concept of the \"assignment expression\" which - besides doing the assignment - yields the assigned value, which is always true in your first if and always false in your second if.\n",
"using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class accept : MonoBehaviour\n{\n public LayerMask grabbable;\n public GameObject Spawner;\n bool isPoor;\n public GameManager gameManager;\n\n public void OnTriggerEnter2D(Collider2D other)\n {\n\n if (other.gameObject.GetComponent<Poor>().isPoor)\n gameManager.GameOver();\n else\n gameManager.GameWon();\n\n Destroy(other.gameObject);\n\n Spawner.GetComponent<Spawner>().Spawn();\n\n }\n\n}\n\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"2d",
"c#",
"unity3d"
] |
stackoverflow_0074667777_2d_c#_unity3d.txt
|
Q:
Change form input field value with jquery within a bootstrap modal
I have a form within a bootstrap modal. I would like the input fields to display the past values that the user entered the first time they filled out the form, which I am retrieving from a cloudant database. I would like these input fields to be editable so that the user can resubmit the form with any changes they may have. However, I am stuck when trying to display the past information in the input fields. I can't find any reason why these value of the input fields are not being changed.
The javascript that adds my buttons to my boostrap list-group:
var loadIotPanel = function(iotsJSON)
{
for(var iot in iotsJSON)
{
var button = $('<button/>').text(iotsJSON[iot].appID).addClass('list-group-item iot').attr({name:iotsJSON[iot].appID, "aria-label": "Quick View IoT", "data-toggle": "modal", "data-target": "#quick-view-iot-modal", type: "button"});
$('#iot-list').append(button);
}
};
The html where my button will be placed within my list-group:
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12 col-sm-12 dash-col">
<button name="edit-iots" aria-label="Edit IoTs" data-toggle="modal" data-target="#edit-iots-modal" type="button" class="icon"><span class="glyphicon glyphicon-edit gray"></span></button>
<p class="fancy-font dash-item-title">Your IoTs</p>
<button name="add-iot" aria-label="Add IoT" data-toggle="modal" data-target="#connect-iot-modal" type="button" class="icon"><span class="glyphicon glyphicon-plus gray"></span></button>
<div class="list-group iot" id="iot-list"><!-- buttons will be placed here --></div>
</div>...
The modal that pops up when clicking a button:
<div class="modal fade" id="quick-view-iot-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="quick-view-iot-h4"></h4>
</div>
<div class="modal-body">
<form id="edit-iot-form" method="post">
IoT Name: <br>
<input type="text" name="iot-name" class="iot-value" required><br>
Organization ID: <br>
<input type="text" name="org-id" class="iot-value" readonly required><br>
Authentication Method: <br>
<input type="text" name="auth-method" class="iot-value" value="apikey" readonly><br>
API Key: <br>
<input type="text" name="api-key" class="iot-value" readonly required><br>
Authentication Token: <br>
<input type="text" name="auth-token" class="iot-value" readonly required><br>
</form>
<button name="more" type="button" class="fancy-font page-button">More</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The javascript that adds the content to modal. It is within a main method that is called when document is ready:
$('.iot').click(
function()
{
var iotName = event.target.name;
getIots(loadIotQuickView, iotName);
$('h4#quick-view-iot-h4.modal-title').text(event.target.name);
});
The getIots() function: (it includes parameter variable=null because I also use it in another part of code where the varaible parameter is not used. This method sends an ajax post to a servlet, which then responds with an array of iot objects)
var getIots = function(callback, variable=null)
{
var iotsJSON = null;
$.post("DashboardServlet", {loadIotPanel: "true"}, function(response)
{
iotsJSON = response;
callback(response, variable);
});
The loadIotQuickView() function: (This is where I believe I am getting problems)
var loadIotQuickView = function(iotsJSON, iotName)
{
var currentIoT = null;
for(var iot in iotsJSON)
{
if(iotsJSON[iot].appID = iotName)
currentIoT = iotsJSON[iot];
}
if(currentIoT == null)
return;
$('.iot-value[name="iot-name"]').attr("value",currentIoT.appId);
};
I've tried numerous jquery selectors but none of the input field values within the form will change. I've stepped through the code and all of my variables have the correct values that its just the last line that's not executing how I want. I am unsure if there is an issue with my jquery selector or if it is something else. Thanks in advance!
UPDATE:
I've tried the following selectors:
$('.iot-value[name="iot-name"]')
$('input[name="iot-name"]')
$('.iot-value')
$('#connect-iot-modal').find('input[name="iot-name"]')
I've also tried adding an id of "edit-iot-name" to my input field:
$('#edit-iot-name')
$('#connect-iot-modal #edit-iot-name')
But none of these have worked, which leads me to believe that it must not be an issue with my selector.
UPDATE:
I've also tried using .val(currentIoT.appID) with all of the previous selectors. Still not working.
A:
I'm not sure why, but adding the id of the modal that my form is in, which is #quick-view-iot-modal, to my selector worked. However for some reason it only works when I use .val() and not when I use .attr(). So the final result is:
$('#quick-view-iot-modal #edit-iot-name').val(currentIoT.appID);
I'm not sure why it is required to add the id of the modal, and I'm not sure why it doesn't work like this:
$('#quick-view-iot-modal #edit-iot-name').attr("value",currentIoT.appID);
But it works! If anyone knows why it only works with this combination, please let me know!
A:
try:
$('.iot-value[name="iot-name"]').val(currentIoT.appId);
Your selector is pretty weird as well. why not just refer to the input by name?
$('input[name="iot-name"]').val(currentIoT.appId);
A:
In your code here:
$('.iot-value[name="iot-name"]')
"iot-name" is a string literal, and it will not evaluate to the value of your iot-name variable.
I'm guessing that you are looking to use the variable's value in your selector, which would look like this:
$('.iot-value[name="' + iot-name + '"]')
A:
I have been struggling with this problem for 3 hours. The realisation that you must reference the object through the modal div is the winner.
I was trying to do 2 things
populate the href in an button on my modal
set the value of another field using an onChange()
so I end up with
$("#modal-form #linkbtn").attr("href", url)
$('#modal-form #inputfield").val(newVal)
Thanks so much for this hint.
|
Change form input field value with jquery within a bootstrap modal
|
I have a form within a bootstrap modal. I would like the input fields to display the past values that the user entered the first time they filled out the form, which I am retrieving from a cloudant database. I would like these input fields to be editable so that the user can resubmit the form with any changes they may have. However, I am stuck when trying to display the past information in the input fields. I can't find any reason why these value of the input fields are not being changed.
The javascript that adds my buttons to my boostrap list-group:
var loadIotPanel = function(iotsJSON)
{
for(var iot in iotsJSON)
{
var button = $('<button/>').text(iotsJSON[iot].appID).addClass('list-group-item iot').attr({name:iotsJSON[iot].appID, "aria-label": "Quick View IoT", "data-toggle": "modal", "data-target": "#quick-view-iot-modal", type: "button"});
$('#iot-list').append(button);
}
};
The html where my button will be placed within my list-group:
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12 col-sm-12 dash-col">
<button name="edit-iots" aria-label="Edit IoTs" data-toggle="modal" data-target="#edit-iots-modal" type="button" class="icon"><span class="glyphicon glyphicon-edit gray"></span></button>
<p class="fancy-font dash-item-title">Your IoTs</p>
<button name="add-iot" aria-label="Add IoT" data-toggle="modal" data-target="#connect-iot-modal" type="button" class="icon"><span class="glyphicon glyphicon-plus gray"></span></button>
<div class="list-group iot" id="iot-list"><!-- buttons will be placed here --></div>
</div>...
The modal that pops up when clicking a button:
<div class="modal fade" id="quick-view-iot-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="quick-view-iot-h4"></h4>
</div>
<div class="modal-body">
<form id="edit-iot-form" method="post">
IoT Name: <br>
<input type="text" name="iot-name" class="iot-value" required><br>
Organization ID: <br>
<input type="text" name="org-id" class="iot-value" readonly required><br>
Authentication Method: <br>
<input type="text" name="auth-method" class="iot-value" value="apikey" readonly><br>
API Key: <br>
<input type="text" name="api-key" class="iot-value" readonly required><br>
Authentication Token: <br>
<input type="text" name="auth-token" class="iot-value" readonly required><br>
</form>
<button name="more" type="button" class="fancy-font page-button">More</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The javascript that adds the content to modal. It is within a main method that is called when document is ready:
$('.iot').click(
function()
{
var iotName = event.target.name;
getIots(loadIotQuickView, iotName);
$('h4#quick-view-iot-h4.modal-title').text(event.target.name);
});
The getIots() function: (it includes parameter variable=null because I also use it in another part of code where the varaible parameter is not used. This method sends an ajax post to a servlet, which then responds with an array of iot objects)
var getIots = function(callback, variable=null)
{
var iotsJSON = null;
$.post("DashboardServlet", {loadIotPanel: "true"}, function(response)
{
iotsJSON = response;
callback(response, variable);
});
The loadIotQuickView() function: (This is where I believe I am getting problems)
var loadIotQuickView = function(iotsJSON, iotName)
{
var currentIoT = null;
for(var iot in iotsJSON)
{
if(iotsJSON[iot].appID = iotName)
currentIoT = iotsJSON[iot];
}
if(currentIoT == null)
return;
$('.iot-value[name="iot-name"]').attr("value",currentIoT.appId);
};
I've tried numerous jquery selectors but none of the input field values within the form will change. I've stepped through the code and all of my variables have the correct values that its just the last line that's not executing how I want. I am unsure if there is an issue with my jquery selector or if it is something else. Thanks in advance!
UPDATE:
I've tried the following selectors:
$('.iot-value[name="iot-name"]')
$('input[name="iot-name"]')
$('.iot-value')
$('#connect-iot-modal').find('input[name="iot-name"]')
I've also tried adding an id of "edit-iot-name" to my input field:
$('#edit-iot-name')
$('#connect-iot-modal #edit-iot-name')
But none of these have worked, which leads me to believe that it must not be an issue with my selector.
UPDATE:
I've also tried using .val(currentIoT.appID) with all of the previous selectors. Still not working.
|
[
"I'm not sure why, but adding the id of the modal that my form is in, which is #quick-view-iot-modal, to my selector worked. However for some reason it only works when I use .val() and not when I use .attr(). So the final result is:\n$('#quick-view-iot-modal #edit-iot-name').val(currentIoT.appID);\n\nI'm not sure why it is required to add the id of the modal, and I'm not sure why it doesn't work like this:\n$('#quick-view-iot-modal #edit-iot-name').attr(\"value\",currentIoT.appID);\n\nBut it works! If anyone knows why it only works with this combination, please let me know!\n",
"try:\n$('.iot-value[name=\"iot-name\"]').val(currentIoT.appId);\nYour selector is pretty weird as well. why not just refer to the input by name?\n$('input[name=\"iot-name\"]').val(currentIoT.appId);\n",
"In your code here:\n$('.iot-value[name=\"iot-name\"]')\n\n\"iot-name\" is a string literal, and it will not evaluate to the value of your iot-name variable.\nI'm guessing that you are looking to use the variable's value in your selector, which would look like this:\n$('.iot-value[name=\"' + iot-name + '\"]')\n\n",
"I have been struggling with this problem for 3 hours. The realisation that you must reference the object through the modal div is the winner.\nI was trying to do 2 things\n\npopulate the href in an button on my modal\nset the value of another field using an onChange()\n\nso I end up with\n$(\"#modal-form #linkbtn\").attr(\"href\", url)\n$('#modal-form #inputfield\").val(newVal)\nThanks so much for this hint.\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"ajax",
"bootstrap_modal",
"javascript",
"jquery",
"twitter_bootstrap"
] |
stackoverflow_0038961333_ajax_bootstrap_modal_javascript_jquery_twitter_bootstrap.txt
|
Q:
Foreground Service with a Silent Notification
Context:
I have been using Google's LocationUpdatesForegroundService example project to learn a bit more about services.
I have downloaded the project via Github desktop and ran it on my phone, everything is great and the project does what it's intended to do.
My phone is Android 8.0.0, API 26
Problem:
The foreground service notification shows up on the status bar once the app is terminated, as soon as that happens I hear a notification sound(default sound).
However, I would like the notification to be silent, like in some location-based apps(eg: Life360)
What I've tried so far:
in LocationUpdatesService.java at added159 tried mChannel.setSound(null,null);
in LocationUpdatesService.java at line 296 changed .setPriority(Notification.PRIORITY_HIGH) to
.setPriority(Notification.PRIORITY_LOW)
in LocationUpdatesService.java at line 158changed NotificationManager.IMPORTANCE_DEFAULT to NotificationManager.IMPORTANCE_LOW)
in LocationUpdatesService.java at line 300 added setSound(null)
None of the above have worked for me, I would really appreciate if someone could shed some light on this situation.
A:
The solution is to use NotificationManager.IMPORTANCE_LOW and create a new channel for it. Once a channel is created, you can't change the importance (well, you can, but the new importance is ignored). The channel information appears to get stored permanently by the system and any channel created is only deleted when you uninstall the app. you can delete the channel as
nm.deleteNotificationChannel(nChannel.getId());
and recreate it with
nm.createNotificationChannel(nChannel);
via stack overflow answer here Disable sound from NotificationChannel
A:
In the LocationUpdatesForegroundService, when the service is onUnbind, it will invoke 'startForeground(NOTIFICATION_ID, getNotification())', then the Notification will show with sound. So you need to change the NotificationChannel follow the below code
mChannel.setSound(null, null);
mChannel.setImportance(NotificationManager.IMPORTANCE_LOW);
A:
mChannel.setSound(null,null) will do it, but you need to uninstall/reinstall the app for it to take effect. Or changing CHANNEL_ID to a different value will also recreate channel with updated setting.
A:
I might be a little late with answer, but did you try reinstalling the app? It's simple and it may fix problem.
A:
Maybe I am late to answer this question
but for other seaker for an answer, i will add my answer:
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSilent(true);
|
Foreground Service with a Silent Notification
|
Context:
I have been using Google's LocationUpdatesForegroundService example project to learn a bit more about services.
I have downloaded the project via Github desktop and ran it on my phone, everything is great and the project does what it's intended to do.
My phone is Android 8.0.0, API 26
Problem:
The foreground service notification shows up on the status bar once the app is terminated, as soon as that happens I hear a notification sound(default sound).
However, I would like the notification to be silent, like in some location-based apps(eg: Life360)
What I've tried so far:
in LocationUpdatesService.java at added159 tried mChannel.setSound(null,null);
in LocationUpdatesService.java at line 296 changed .setPriority(Notification.PRIORITY_HIGH) to
.setPriority(Notification.PRIORITY_LOW)
in LocationUpdatesService.java at line 158changed NotificationManager.IMPORTANCE_DEFAULT to NotificationManager.IMPORTANCE_LOW)
in LocationUpdatesService.java at line 300 added setSound(null)
None of the above have worked for me, I would really appreciate if someone could shed some light on this situation.
|
[
"The solution is to use NotificationManager.IMPORTANCE_LOW and create a new channel for it. Once a channel is created, you can't change the importance (well, you can, but the new importance is ignored). The channel information appears to get stored permanently by the system and any channel created is only deleted when you uninstall the app. you can delete the channel as \nnm.deleteNotificationChannel(nChannel.getId());\n\nand recreate it with \nnm.createNotificationChannel(nChannel);\n\nvia stack overflow answer here Disable sound from NotificationChannel\n",
"In the LocationUpdatesForegroundService, when the service is onUnbind, it will invoke 'startForeground(NOTIFICATION_ID, getNotification())', then the Notification will show with sound. So you need to change the NotificationChannel follow the below code\nmChannel.setSound(null, null);\nmChannel.setImportance(NotificationManager.IMPORTANCE_LOW);\n\n",
"mChannel.setSound(null,null) will do it, but you need to uninstall/reinstall the app for it to take effect. Or changing CHANNEL_ID to a different value will also recreate channel with updated setting.\n",
"I might be a little late with answer, but did you try reinstalling the app? It's simple and it may fix problem.\n",
"Maybe I am late to answer this question\nbut for other seaker for an answer, i will add my answer:\nNotificationCompat.Builder notificationBuilder = new \n NotificationCompat.Builder(this, CHANNEL_ID)\n.setPriority(NotificationCompat.PRIORITY_LOW)\n .setSilent(true);\n\n"
] |
[
4,
3,
1,
1,
0
] |
[] |
[] |
[
"android",
"foreground_service",
"java",
"notifications"
] |
stackoverflow_0054728368_android_foreground_service_java_notifications.txt
|
Q:
Can I abort MessageEvent in Symfony from one of the attached listeners?
Is it possible to prevent sending a message from one of the listeners attached for MessageEvent?
In the specific case I have a listener that filters the recipients.
There is a black list and it is possible the message to remain without recipients - in this case my app fails with error app.ERROR: An envelope must have at least one recipient.
A:
You should be able to throw an UnrecoverableMessageHandlingException when you detect that the message has no more recipients, and so the message will not be retried and it will be aborted. You may have to catch that in your own code to discard it, but it would be under your control.
|
Can I abort MessageEvent in Symfony from one of the attached listeners?
|
Is it possible to prevent sending a message from one of the listeners attached for MessageEvent?
In the specific case I have a listener that filters the recipients.
There is a black list and it is possible the message to remain without recipients - in this case my app fails with error app.ERROR: An envelope must have at least one recipient.
|
[
"You should be able to throw an UnrecoverableMessageHandlingException when you detect that the message has no more recipients, and so the message will not be retried and it will be aborted. You may have to catch that in your own code to discard it, but it would be under your control.\n"
] |
[
0
] |
[] |
[] |
[
"php",
"symfony"
] |
stackoverflow_0074642861_php_symfony.txt
|
Q:
Dict to DataFrame: Value instead of list in DataFrame
How when i convert a dictionary to a dataframe do i stop each value being within a list.
i tried to converting with the pandas from_dict
A:
You can use orient='records'.
all_kpi.to_dict(orient='records')
Check out the pandas documentation for different orientation.
|
Dict to DataFrame: Value instead of list in DataFrame
|
How when i convert a dictionary to a dataframe do i stop each value being within a list.
i tried to converting with the pandas from_dict
|
[
"You can use orient='records'.\nall_kpi.to_dict(orient='records')\n\nCheck out the pandas documentation for different orientation.\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074668474_dataframe_pandas_python.txt
|
Q:
Error while applying a patch in git
I have a shallow clone, on which i made three commits.
Here is the log:
$ git log --oneline --graph --decorate --all
* d3456fd (HEAD, master) patch 3
* 9713822 patch 2
* 6f380a6 patch 1
* 8a1ce1e (origin/master, origin/HEAD) from full clone
* 7c13416 added from shallow
* 3b3ed39 removed email
* cfbed6c further modifications
* a71254b added for release 2.1
* 7347896 (grafted) changes for release 2
now i create a patch from here:
$ git format-patch -k --stdout origin > ../format_since_origin.patch
I want to apply this patch in another clone, which is a full clone.
Here is the log:
$ git log --oneline --graph --decorate --all
* 8a1ce1e (HEAD, origin/master, master) from full clone
* 7c13416 added from shallow
* 3b3ed39 removed email
* cfbed6c further modifications
* a71254b added for release 2.1
* 7347896 changes for release 2
* b1a8797 changes to ttwo files
* 603710c changed test report
* 16b20b3 added test_report.txt
* f0871ea modified file1.xml
* dd94bfc added file1.xml
* 00758aa second commit
* 49f9968 first commit
I am unable to apply the patch created from the shallow clone above. I get the following error.
$ git am -3 /c/temp/git/format_since_origin.patch
Applying: patch 1
Using index info to reconstruct a base tree...
error: patch failed: file1.c:6
error: file1.c: patch does not apply
Did you hand edit your patch?
It does not apply to blobs recorded in its index.
Cannot fall back to three-way merge.
Patch failed at 0001 patch 1
When you have resolved this problem run "git am --resolved".
If you would prefer to skip this patch, instead run "git am --skip".
To restore the original branch and stop patching run "git am --abort".
Any idea why this patch is failing? Or is my method totally wrong?
Update:
It works with the following
$ git am -3 --ignore-whitespace /c/temp/git/format_since_origin.patch
Applying: patch 1
Applying: patch 2
Applying: patch 3
Now, as suggested by Charles - if i try the git diff, i get the error as below.
$ git diff -p origin > ../dif_origin.patch
On applying,
$ git apply --ignore-whitespace --inaccurate-eof /c/temp/git/dif_origin.patch
c:/temp/git/dif_origin.patch:9: trailing whitespace.
patch change for file1.c
c:/temp/git/dif_origin.patch:18: trailing whitespace.
patch this xml guy
c:/temp/git/dif_origin.patch:29: trailing whitespace.
fsdfsd
c:/temp/git/dif_origin.patch:30: trailing whitespace.
patch this report
error: patch failed: file1.c:6
error: file1.c: patch does not apply
error: patch failed: file1.xml:2
error: file1.xml: patch does not apply
error: patch failed: tr/test_report.txt:2
error: tr/test_report.txt: patch does not apply
A:
When git apply is working normally, you get no output at all:
$ git apply example.patch
[nothing returned]
If you want to see what's going on behind the scenes, you can use the -v (verbose) flag:
$ git apply -v example.patch
Checking patch includes/common.inc...
Applied patch includes/common.inc cleanly.
However, if running git apply from within your own local git working copy, it's possible that even with the -v (verbose) flag, git apply will do nothing, and give no output. If this happens, please check your location in the directory tree - git apply may work from another location.
An alternative to git apply is to use the patch command:
$ patch -p1 < example.patch
Here is other output the git apply command can generate, and what it means.
Patch does not apply
$ git apply example.patch
error: patch failed: includes/common.inc:626
error: includes/common.inc: patch does not apply``
Git couldn't apply the changes in the patch because it wasn't able to find the line(s) of code in question; they must have been changed or removed by another commit. Try these things:
Make sure the patch hasn't already been applied. Look for it in git-log or simply examine the code to see if the change(s) are already present. If they are, you're done. If they aren't or if only some of them are, try something else:
Use patch -p1 < filename.patch. Whereas git-apply altogether rejects a patch with any errors, patch -p1 works hunk by hunk, applying as many individual changes as it can. It backs up each file as filename.ext.orig before modifying it and saves rejected hunks in filename.ext.rej. Discard the .orig files and manually apply the changes left in the .rej. This is an easy strategy for small patches.
A:
Note that one rationale for having to ignore whitespace was (June 2010):
What it does is enable the GMail -> download -> git-am workflow.
GMail (and doubtless countless other) E-Mail providers introduce whitespace at the beginning of raw E-Mail messages, while otherwise leaving them intact.
As mentioned in "git am/format-patch: control format of line endings", you can try a:
git am --keep-cr
That wouldn't require you to ignore whitespace (warning only).
The OP maxmelbin confirms in the comments that the following works:
git am -3 --keep-cr --committer-date-is-author-date /c/temp/git/format_since_origin.patch
A:
ok. the following worked .
$ git am -3 --ignore-whitespace /c/temp/git/format_since_origin.patch
Applying: patch 1
Applying: patch 2
Applying: patch 3
A:
If you're using intellij idea, just go to toolbar->git->patch->create/apply patch, this is the simplest idea and it won't throw any error while applying the patch.
|
Error while applying a patch in git
|
I have a shallow clone, on which i made three commits.
Here is the log:
$ git log --oneline --graph --decorate --all
* d3456fd (HEAD, master) patch 3
* 9713822 patch 2
* 6f380a6 patch 1
* 8a1ce1e (origin/master, origin/HEAD) from full clone
* 7c13416 added from shallow
* 3b3ed39 removed email
* cfbed6c further modifications
* a71254b added for release 2.1
* 7347896 (grafted) changes for release 2
now i create a patch from here:
$ git format-patch -k --stdout origin > ../format_since_origin.patch
I want to apply this patch in another clone, which is a full clone.
Here is the log:
$ git log --oneline --graph --decorate --all
* 8a1ce1e (HEAD, origin/master, master) from full clone
* 7c13416 added from shallow
* 3b3ed39 removed email
* cfbed6c further modifications
* a71254b added for release 2.1
* 7347896 changes for release 2
* b1a8797 changes to ttwo files
* 603710c changed test report
* 16b20b3 added test_report.txt
* f0871ea modified file1.xml
* dd94bfc added file1.xml
* 00758aa second commit
* 49f9968 first commit
I am unable to apply the patch created from the shallow clone above. I get the following error.
$ git am -3 /c/temp/git/format_since_origin.patch
Applying: patch 1
Using index info to reconstruct a base tree...
error: patch failed: file1.c:6
error: file1.c: patch does not apply
Did you hand edit your patch?
It does not apply to blobs recorded in its index.
Cannot fall back to three-way merge.
Patch failed at 0001 patch 1
When you have resolved this problem run "git am --resolved".
If you would prefer to skip this patch, instead run "git am --skip".
To restore the original branch and stop patching run "git am --abort".
Any idea why this patch is failing? Or is my method totally wrong?
Update:
It works with the following
$ git am -3 --ignore-whitespace /c/temp/git/format_since_origin.patch
Applying: patch 1
Applying: patch 2
Applying: patch 3
Now, as suggested by Charles - if i try the git diff, i get the error as below.
$ git diff -p origin > ../dif_origin.patch
On applying,
$ git apply --ignore-whitespace --inaccurate-eof /c/temp/git/dif_origin.patch
c:/temp/git/dif_origin.patch:9: trailing whitespace.
patch change for file1.c
c:/temp/git/dif_origin.patch:18: trailing whitespace.
patch this xml guy
c:/temp/git/dif_origin.patch:29: trailing whitespace.
fsdfsd
c:/temp/git/dif_origin.patch:30: trailing whitespace.
patch this report
error: patch failed: file1.c:6
error: file1.c: patch does not apply
error: patch failed: file1.xml:2
error: file1.xml: patch does not apply
error: patch failed: tr/test_report.txt:2
error: tr/test_report.txt: patch does not apply
|
[
"When git apply is working normally, you get no output at all:\n$ git apply example.patch\n[nothing returned]\n\nIf you want to see what's going on behind the scenes, you can use the -v (verbose) flag:\n$ git apply -v example.patch\nChecking patch includes/common.inc...\nApplied patch includes/common.inc cleanly.\n\nHowever, if running git apply from within your own local git working copy, it's possible that even with the -v (verbose) flag, git apply will do nothing, and give no output. If this happens, please check your location in the directory tree - git apply may work from another location.\nAn alternative to git apply is to use the patch command:\n$ patch -p1 < example.patch\n\nHere is other output the git apply command can generate, and what it means.\nPatch does not apply\n$ git apply example.patch\nerror: patch failed: includes/common.inc:626\nerror: includes/common.inc: patch does not apply``\n\nGit couldn't apply the changes in the patch because it wasn't able to find the line(s) of code in question; they must have been changed or removed by another commit. Try these things:\nMake sure the patch hasn't already been applied. Look for it in git-log or simply examine the code to see if the change(s) are already present. If they are, you're done. If they aren't or if only some of them are, try something else:\nUse patch -p1 < filename.patch. Whereas git-apply altogether rejects a patch with any errors, patch -p1 works hunk by hunk, applying as many individual changes as it can. It backs up each file as filename.ext.orig before modifying it and saves rejected hunks in filename.ext.rej. Discard the .orig files and manually apply the changes left in the .rej. This is an easy strategy for small patches. \n",
"Note that one rationale for having to ignore whitespace was (June 2010):\n\nWhat it does is enable the GMail -> download -> git-am workflow.\n GMail (and doubtless countless other) E-Mail providers introduce whitespace at the beginning of raw E-Mail messages, while otherwise leaving them intact. \n\nAs mentioned in \"git am/format-patch: control format of line endings\", you can try a:\n git am --keep-cr\n\nThat wouldn't require you to ignore whitespace (warning only).\nThe OP maxmelbin confirms in the comments that the following works:\n git am -3 --keep-cr --committer-date-is-author-date /c/temp/git/format_since_origin.patch\n\n",
"ok. the following worked .\n\n$ git am -3 --ignore-whitespace /c/temp/git/format_since_origin.patch \nApplying: patch 1\nApplying: patch 2\nApplying: patch 3\n\n",
"If you're using intellij idea, just go to toolbar->git->patch->create/apply patch, this is the simplest idea and it won't throw any error while applying the patch.\n"
] |
[
20,
18,
9,
0
] |
[] |
[] |
[
"git"
] |
stackoverflow_0013190679_git.txt
|
Q:
Fail to overwrite a 2D numpy.ndarray in a loop
I found my program failed to overwrite an np.ndarray (the X variable) in the for loop by assignment statement like "X[i] = another np.ndarray with matched shape". I have no idea how this could happen...
Codes:
import numpy as np
def qr_tridiagonal(T: np.ndarray):
m, n = T.shape
X = T.copy()
Qt = np.identity(m)
for i in range(n-1):
ai = X[i, i]
ak = X[i+1, i]
c = ai/(ai**2 + ak**2)**.5
s = ak/(ai**2 + ak**2)**.5
# Givens rotation
tmp1 = c*X[i] + s*X[i+1]
tmp2 = c*X[i+1] - s*X[i]
print("tmp1 before:", tmp1)
print("X[i] before:", X[i])
X[i] = tmp1
X[i+1] = tmp2
print("tmp1 after:", tmp1)
print("X[i] after:", X[i])
print()
print(X)
return Qt.T, X
A = np.array([[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]])
Q, R = qr_tridiagonal(A)
Output (the first 4 lines):
tmp1 before: [1.41421356 1.41421356 0.70710678 0. ]
X[i] before: [1 1 0 0]
tmp1 after: [1.41421356 1.41421356 0.70710678 0. ]
X[i] after: [1 1 0 0]
Though X[i] is assigned by tmp1, the values in the array X[i] or X[i, :] remain unchanged. Hope somebody help me out....
Other info: the above is a function to compute QR factorization for tridiagonal matrices using Givens Rotation.
I did check that assigning constant values to X[i] work, e.g. X[i] = 10 then the printed results fit this statement. But if X[i] = someArray then in my codes it would fail. I am not sure whether this is a particular issue triggered by the algorithm I was implementing in the above codes, because such scenarios never happen before.
I did try to install new environments using conda to make sure that my python is not problematic. The above strange outputs should be able to re-generate on other devices.
A:
Many thanks to @hpaulj
It turns out to be a problem of datatype. The program is ok but the input datatype is int, which results in intermediate trancation errors.
A lesson learned: be aware of the dtype of np.ndarray!
|
Fail to overwrite a 2D numpy.ndarray in a loop
|
I found my program failed to overwrite an np.ndarray (the X variable) in the for loop by assignment statement like "X[i] = another np.ndarray with matched shape". I have no idea how this could happen...
Codes:
import numpy as np
def qr_tridiagonal(T: np.ndarray):
m, n = T.shape
X = T.copy()
Qt = np.identity(m)
for i in range(n-1):
ai = X[i, i]
ak = X[i+1, i]
c = ai/(ai**2 + ak**2)**.5
s = ak/(ai**2 + ak**2)**.5
# Givens rotation
tmp1 = c*X[i] + s*X[i+1]
tmp2 = c*X[i+1] - s*X[i]
print("tmp1 before:", tmp1)
print("X[i] before:", X[i])
X[i] = tmp1
X[i+1] = tmp2
print("tmp1 after:", tmp1)
print("X[i] after:", X[i])
print()
print(X)
return Qt.T, X
A = np.array([[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]])
Q, R = qr_tridiagonal(A)
Output (the first 4 lines):
tmp1 before: [1.41421356 1.41421356 0.70710678 0. ]
X[i] before: [1 1 0 0]
tmp1 after: [1.41421356 1.41421356 0.70710678 0. ]
X[i] after: [1 1 0 0]
Though X[i] is assigned by tmp1, the values in the array X[i] or X[i, :] remain unchanged. Hope somebody help me out....
Other info: the above is a function to compute QR factorization for tridiagonal matrices using Givens Rotation.
I did check that assigning constant values to X[i] work, e.g. X[i] = 10 then the printed results fit this statement. But if X[i] = someArray then in my codes it would fail. I am not sure whether this is a particular issue triggered by the algorithm I was implementing in the above codes, because such scenarios never happen before.
I did try to install new environments using conda to make sure that my python is not problematic. The above strange outputs should be able to re-generate on other devices.
|
[
"Many thanks to @hpaulj\nIt turns out to be a problem of datatype. The program is ok but the input datatype is int, which results in intermediate trancation errors.\nA lesson learned: be aware of the dtype of np.ndarray!\n"
] |
[
0
] |
[] |
[] |
[
"multidimensional_array",
"numpy",
"python"
] |
stackoverflow_0074668253_multidimensional_array_numpy_python.txt
|
Q:
Freetype2 not linking on Windows correctly
I've been fighting freetype2 for a week trying to get it to work on Windows 32 bit but it just won't. My CMakeLists.txt is as follows:
cmake_minimum_required(VERSION 3.0.0)
set(CMAKE_CXX_STANDARD 17)
project(template-project) # change the name here
file(GLOB_RECURSE SOURCE_FILES src/*.cpp)
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES})
list(APPEND CMAKE_PREFIX_PATH "D:/Installs/ProgFiles/glew")
find_package( OpenGL REQUIRED )
include_directories( ${OPENGL_INCLUDE_DIRS} )
# this is so stupid
set(CMAKE_SIZEOF_VOID_P 4)
if (${CMAKE_CXX_COMPILER_ID} STREQUAL Clang)
# ensure 32 bit on clang
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target i386-pc-windows-msvc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target i386-pc-windows-msvc")
add_definitions("--target=i386-pc-windows-msvc")
endif()
set(FT_DISABLE_HARFBUZZ TRUE)
target_include_directories(${PROJECT_NAME} PRIVATE
libraries/minhook/include
libraries/gd.h/include
libraries/gd.h/
libraries/imgui
libraries/glad/include
libraries/stb
libraries/freetype2/include
)
add_subdirectory(libraries/minhook)
add_subdirectory(libraries/cocos-headers)
add_subdirectory(libraries/glfw)
add_subdirectory(libraries/glm)
add_subdirectory(libraries/freetype2)
target_link_libraries( ${PROJECT_NAME} ${OPENGL_LIBRARIES} glfw )
if( MSVC )
if(${CMAKE_VERSION} VERSION_LESS "3.6.0")
message( "\n\t[ WARNING ]\n\n\tCMake version lower than 3.6.\n\n\t - Please update CMake and rerun; OR\n\t - Manually set 'GLFW-CMake-starter' as StartUp Project in Visual Studio.\n" )
else()
set_property( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT GLFW-CMake-starter )
endif()
endif()
target_link_libraries(${PROJECT_NAME} opengl32.lib minhook cocos2d rpcrt4.lib glm ${PROJECT_SOURCE_DIR}/libraries/freetype2/objs/Win32/Release/freetype.lib)
The biggest issue in the output are these lines:
[cmake] -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE)
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
[cmake] -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR)
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
[cmake] -- Could NOT find BZip2 (missing: BZIP2_LIBRARIES BZIP2_INCLUDE_DIR)
[cmake] -- Could NOT find BrotliDec (missing: BROTLIDEC_INCLUDE_DIRS BROTLIDEC_LIBRARIES)
I am on windows and completely unsure how to fix these. I've tried installing zlib via mingw32, and I've tried linking it the same way I do things like minhook and glad to no avail.
A:
I recommend a different approach than manual downloading of opensource dependencies when using MinGW. Instead of searching for individual binary downloads switch to use msys2 to install MinGW and use the package management of msys2 to all of your dependent open source libraries.
The first step is to remove your current MinGW install so you have no conflicting / possibly incompatible MinGW dlls in your PATH that may cause you problems in the future when executing your programs.
After that install msys2: How to install MinGW-w64 and MSYS2?
Then to install your dependencies for 32 bit open the mingw32 terminal which by default is installed in "C:\msys64\mingw32.exe" and use the package manager of msys2 pacman to install the dependent packages.
The web page for msys2 has a convenient package search feature at the top center of this page: https://packages.msys2.org/queue
Lets start with zlib from your dependencies. Type in zlib in the search box and press search. Type mingw-w64-zlib then look for i686 packages for mingw to find the correct package for 32 bit mingw. I found the following link for zlib for mingw32 has the following page: https://packages.msys2.org/package/mingw-w64-i686-zlib?repo=mingw32
The install instructions for that are listed in the center of the page: pacman -S mingw-w64-i686-zlib
so copy this command to the mingw32 terminal:
JMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~
# pacman -S mingw-w64-i686-zlib
resolving dependencies...
looking for conflicting packages...
Packages (1) mingw-w64-i686-zlib-1.2.13-2
Total Download Size: 0.10 MiB
Total Installed Size: 0.39 MiB
:: Proceed with installation? [Y/n]
Press Y to install this package.
:: Proceed with installation? [Y/n] y
:: Retrieving packages...
mingw-w64-i686-zlib-1.2.13... 102.8 KiB 126 KiB/s 00:01 [###############################] 100%
(1/1) checking keys in keyring [###############################] 100%
(1/1) checking package integrity [###############################] 100%
(1/1) loading package files [###############################] 100%
(1/1) checking for file conflicts [###############################] 100%
(1/1) checking available disk space [###############################] 100%
:: Processing package changes...
(1/1) installing mingw-w64-i686-zlib [###############################] 100%
JMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~
Continue a similar process for the other dependent packages.
|
Freetype2 not linking on Windows correctly
|
I've been fighting freetype2 for a week trying to get it to work on Windows 32 bit but it just won't. My CMakeLists.txt is as follows:
cmake_minimum_required(VERSION 3.0.0)
set(CMAKE_CXX_STANDARD 17)
project(template-project) # change the name here
file(GLOB_RECURSE SOURCE_FILES src/*.cpp)
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES})
list(APPEND CMAKE_PREFIX_PATH "D:/Installs/ProgFiles/glew")
find_package( OpenGL REQUIRED )
include_directories( ${OPENGL_INCLUDE_DIRS} )
# this is so stupid
set(CMAKE_SIZEOF_VOID_P 4)
if (${CMAKE_CXX_COMPILER_ID} STREQUAL Clang)
# ensure 32 bit on clang
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target i386-pc-windows-msvc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target i386-pc-windows-msvc")
add_definitions("--target=i386-pc-windows-msvc")
endif()
set(FT_DISABLE_HARFBUZZ TRUE)
target_include_directories(${PROJECT_NAME} PRIVATE
libraries/minhook/include
libraries/gd.h/include
libraries/gd.h/
libraries/imgui
libraries/glad/include
libraries/stb
libraries/freetype2/include
)
add_subdirectory(libraries/minhook)
add_subdirectory(libraries/cocos-headers)
add_subdirectory(libraries/glfw)
add_subdirectory(libraries/glm)
add_subdirectory(libraries/freetype2)
target_link_libraries( ${PROJECT_NAME} ${OPENGL_LIBRARIES} glfw )
if( MSVC )
if(${CMAKE_VERSION} VERSION_LESS "3.6.0")
message( "\n\t[ WARNING ]\n\n\tCMake version lower than 3.6.\n\n\t - Please update CMake and rerun; OR\n\t - Manually set 'GLFW-CMake-starter' as StartUp Project in Visual Studio.\n" )
else()
set_property( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT GLFW-CMake-starter )
endif()
endif()
target_link_libraries(${PROJECT_NAME} opengl32.lib minhook cocos2d rpcrt4.lib glm ${PROJECT_SOURCE_DIR}/libraries/freetype2/objs/Win32/Release/freetype.lib)
The biggest issue in the output are these lines:
[cmake] -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE)
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
[cmake] -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR)
[cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
[cmake] -- Could NOT find BZip2 (missing: BZIP2_LIBRARIES BZIP2_INCLUDE_DIR)
[cmake] -- Could NOT find BrotliDec (missing: BROTLIDEC_INCLUDE_DIRS BROTLIDEC_LIBRARIES)
I am on windows and completely unsure how to fix these. I've tried installing zlib via mingw32, and I've tried linking it the same way I do things like minhook and glad to no avail.
|
[
"I recommend a different approach than manual downloading of opensource dependencies when using MinGW. Instead of searching for individual binary downloads switch to use msys2 to install MinGW and use the package management of msys2 to all of your dependent open source libraries.\nThe first step is to remove your current MinGW install so you have no conflicting / possibly incompatible MinGW dlls in your PATH that may cause you problems in the future when executing your programs.\nAfter that install msys2: How to install MinGW-w64 and MSYS2?\nThen to install your dependencies for 32 bit open the mingw32 terminal which by default is installed in \"C:\\msys64\\mingw32.exe\" and use the package manager of msys2 pacman to install the dependent packages.\nThe web page for msys2 has a convenient package search feature at the top center of this page: https://packages.msys2.org/queue\nLets start with zlib from your dependencies. Type in zlib in the search box and press search. Type mingw-w64-zlib then look for i686 packages for mingw to find the correct package for 32 bit mingw. I found the following link for zlib for mingw32 has the following page: https://packages.msys2.org/package/mingw-w64-i686-zlib?repo=mingw32\nThe install instructions for that are listed in the center of the page: pacman -S mingw-w64-i686-zlib\nso copy this command to the mingw32 terminal:\nJMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~\n# pacman -S mingw-w64-i686-zlib\nresolving dependencies...\nlooking for conflicting packages...\n\nPackages (1) mingw-w64-i686-zlib-1.2.13-2\n\nTotal Download Size: 0.10 MiB\nTotal Installed Size: 0.39 MiB\n\n:: Proceed with installation? [Y/n]\n\nPress Y to install this package.\n:: Proceed with installation? [Y/n] y\n:: Retrieving packages...\n mingw-w64-i686-zlib-1.2.13... 102.8 KiB 126 KiB/s 00:01 [###############################] 100%\n(1/1) checking keys in keyring [###############################] 100%\n(1/1) checking package integrity [###############################] 100%\n(1/1) loading package files [###############################] 100%\n(1/1) checking for file conflicts [###############################] 100%\n(1/1) checking available disk space [###############################] 100%\n:: Processing package changes...\n(1/1) installing mingw-w64-i686-zlib [###############################] 100%\n\nJMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~\n\nContinue a similar process for the other dependent packages.\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"cmake",
"freetype2",
"mingw"
] |
stackoverflow_0074660389_c++_cmake_freetype2_mingw.txt
|
Q:
Need android.permission.BLUETOOTH_CONNECT permission error
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutterbluetooth">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:label="flutterbluetooth"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
...
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
I am trying to get bluetooth permission in flutter. But I am getting the error in the title.
A:
You might need to declare these additional permissions which are newly added, along with legacy bluettoth permission.
You can choose only specific permission based on your requirement.
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
Read more here.
A:
It looks like you're missing the <uses-feature> tag in your AndroidManifest.xml file. This tag is required in order to declare that your app uses the Bluetooth feature:
<uses-feature android:name="android.hardware.bluetooth" android:required="true" />
|
Need android.permission.BLUETOOTH_CONNECT permission error
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutterbluetooth">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:label="flutterbluetooth"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
...
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
I am trying to get bluetooth permission in flutter. But I am getting the error in the title.
|
[
"You might need to declare these additional permissions which are newly added, along with legacy bluettoth permission.\nYou can choose only specific permission based on your requirement.\n<uses-permission android:name=\"android.permission.BLUETOOTH_SCAN\" />\n\n<uses-permission android:name=\"android.permission.BLUETOOTH_ADVERTISE\" />\n\n<uses-permission android:name=\"android.permission.BLUETOOTH_CONNECT\" />\n\nRead more here.\n",
"It looks like you're missing the <uses-feature> tag in your AndroidManifest.xml file. This tag is required in order to declare that your app uses the Bluetooth feature:\n<uses-feature android:name=\"android.hardware.bluetooth\" android:required=\"true\" />\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dart",
"flutter"
] |
stackoverflow_0074668410_dart_flutter.txt
|
Q:
End conversation in chatbot
def send():
send = "You: " + e.get()
txt.insert(END, "\n" + send)
user = e.get().lower()
if (user == "hello" or user == "hi" or user == "hey" or user == "oi" or user == "halo"):
txt.insert(END, "\n" + "Rob: Hi there, how can I help you? \n 0.Contact seller directly \n 1.Order Tracking \n 2.Refund and Return \n 3.HELP \n Please enter a number.")
elif (user == "whats your name?" or user == "what is your name" or user == "name" or user == "you called" or user == "what is your name?"):
txt.insert(END, "\n" + "Rob: My name is Rob.")
elif (user == "0"): ** **
elif (user == "1"):
txt.insert(END, "\n" + "Rob: Your bag has arrived. \n 00. Homepage \n 01. ** \n 0. ** **")
elif (user == "4"):
txt.insert(END, "\n" + "Rob: Damage and Broken \n Sorry for the inconvenient. Please take a photo of your item and send it to seller as soon as possible. Thank you.\n 00. Homepage \n 01. ** \n 0. ** **")
I am learning to creating a simple Tkinter GUI chatbot
Problems I am facing:
** ** = I want to end the conversation when user enters 0, and it will close this conversation and move to another python file.
** = when the user enter 01, chatbot will say goodbye and close the conversation.
Thank you.
A:
If you want a method to end in python you can just use return. In your ** ** case just type return under the if statement and it will ends. And in your ** case you just print goodbye or so and then use return.
|
End conversation in chatbot
|
def send():
send = "You: " + e.get()
txt.insert(END, "\n" + send)
user = e.get().lower()
if (user == "hello" or user == "hi" or user == "hey" or user == "oi" or user == "halo"):
txt.insert(END, "\n" + "Rob: Hi there, how can I help you? \n 0.Contact seller directly \n 1.Order Tracking \n 2.Refund and Return \n 3.HELP \n Please enter a number.")
elif (user == "whats your name?" or user == "what is your name" or user == "name" or user == "you called" or user == "what is your name?"):
txt.insert(END, "\n" + "Rob: My name is Rob.")
elif (user == "0"): ** **
elif (user == "1"):
txt.insert(END, "\n" + "Rob: Your bag has arrived. \n 00. Homepage \n 01. ** \n 0. ** **")
elif (user == "4"):
txt.insert(END, "\n" + "Rob: Damage and Broken \n Sorry for the inconvenient. Please take a photo of your item and send it to seller as soon as possible. Thank you.\n 00. Homepage \n 01. ** \n 0. ** **")
I am learning to creating a simple Tkinter GUI chatbot
Problems I am facing:
** ** = I want to end the conversation when user enters 0, and it will close this conversation and move to another python file.
** = when the user enter 01, chatbot will say goodbye and close the conversation.
Thank you.
|
[
"If you want a method to end in python you can just use return. In your ** ** case just type return under the if statement and it will ends. And in your ** case you just print goodbye or so and then use return.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0074668415_python_tkinter.txt
|
Q:
How do I write a list of dicts in yaml?
How can I achieve a list of dicts in yaml for Ansible? I'm trying to access an API for ZeroTier and update my network
The API Documentation says
ipAssignmentPools
Array of objects (IPRange) Nullable
Range of IP addresses for the auto assign pool
Below is what I want to achieve
{
"ipAssignmentPools": [
{
"ipRangeEnd": "172.17.0.100",
"ipRangeStart": "172.17.0.1"
},
{
"ipRangeEnd": "172.18.0.254",
"ipRangeStart": "172.18.0.1"
}
]
}
My code:
ipAssignmentPools:
ipRangeStart:
- 172.16.0.1
ipRangeEnd:
- 172.16.0.254
The result
{
"ipAssignmentPools": {
"ipRangeEnd": [
"172.16.0.254"
],
"ipRangeStart": [
"172.16.0.1"
]
}
}
How do I transform my expected json to a yaml structure?
A:
yaml is a superset of json. You can use any json to yaml convertor like https://www.json2yaml.com/
---
ipAssignmentPools:
- ipRangeEnd: 172.17.0.100
ipRangeStart: 172.17.0.1
- ipRangeEnd: 172.18.0.254
ipRangeStart: 172.18.0.1
|
How do I write a list of dicts in yaml?
|
How can I achieve a list of dicts in yaml for Ansible? I'm trying to access an API for ZeroTier and update my network
The API Documentation says
ipAssignmentPools
Array of objects (IPRange) Nullable
Range of IP addresses for the auto assign pool
Below is what I want to achieve
{
"ipAssignmentPools": [
{
"ipRangeEnd": "172.17.0.100",
"ipRangeStart": "172.17.0.1"
},
{
"ipRangeEnd": "172.18.0.254",
"ipRangeStart": "172.18.0.1"
}
]
}
My code:
ipAssignmentPools:
ipRangeStart:
- 172.16.0.1
ipRangeEnd:
- 172.16.0.254
The result
{
"ipAssignmentPools": {
"ipRangeEnd": [
"172.16.0.254"
],
"ipRangeStart": [
"172.16.0.1"
]
}
}
How do I transform my expected json to a yaml structure?
|
[
"yaml is a superset of json. You can use any json to yaml convertor like https://www.json2yaml.com/\n---\nipAssignmentPools:\n - ipRangeEnd: 172.17.0.100\n ipRangeStart: 172.17.0.1\n - ipRangeEnd: 172.18.0.254\n ipRangeStart: 172.18.0.1\n\n"
] |
[
1
] |
[] |
[] |
[
"ansible",
"zerotier"
] |
stackoverflow_0074668180_ansible_zerotier.txt
|
Q:
Updating programmatically set colors on Mode change (dark mode, light mode) on macOS (objective-c)
i am on macOS, objective-c, not iOS. XCode 12.
In a lot of views i set colors like this:
self.menuIconBar.wantsLayer = YES;
self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;
Whenever the user changes the Appeareance, e.g. to Dark mode, i expect my colors to change according to the Asset setup:
Unfortunately, nothing happens. BUT: The same color applied in IB directly changes as expected. Still i'd need them to change programmatically too.
Then i tried to hook on notifications:
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(appleInterfaceThemeChangedNotification:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
I receive the notifications, but when i then call the same code like above again, still the wrong color is loaded.
self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;
Any help appreciated
A:
The following example will change the background color of a custom view depending on the Appearance setting in System Preferences. It may be run in Xcode by creating an objc project, deleting the pre-existing App Delegate, and replacing the code in 'main.m' with the code below:
#import <Cocoa/Cocoa.h>
@interface CustomView : NSView
@end
@implementation CustomView
- (id)initWithFrame:(NSRect)frameRect {
if ((self = [super initWithFrame:frameRect]) != nil) {
// Add initialization code here
}
return self;
}
- (void)drawRect:(NSRect)rect {
}
- (void)viewDidChangeEffectiveAppearance {
NSLog (@"appearance did change.");
NSAppearance *changedAppearance = NSApp.effectiveAppearance;
NSAppearanceName newAppearance = [changedAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
NSLog (@"new appearance name = %@", newAppearance);
if([newAppearance isEqualToString:NSAppearanceNameDarkAqua]){
[[self layer] setBackgroundColor:CGColorCreateGenericRGB( 1.0, 0.0, 0.0, 1.0 )];
} else {
[[self layer] setBackgroundColor:CGColorCreateGenericRGB( 0.0, 0.0, 1.0, 1.0 )];
}
}
// Use this if you want 0,0 (origin) to be top, left
// Otherwise origin will be at bottom, left (Unflipped)
-(BOOL)isFlipped {
return YES;
}
@end
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
}
- (void) buildMenu;
- (void) buildWindow;
@end
@implementation AppDelegate
- (void) buildMenu {
NSMenu *menubar = [NSMenu new];
NSMenuItem *menuBarItem = [NSMenuItem new];
[menubar addItem:menuBarItem];
[NSApp setMainMenu:menubar];
NSMenu *appMenu = [NSMenu new];
NSMenuItem *quitMenuItem = [[NSMenuItem alloc] initWithTitle:@"Quit"
action:@selector(terminate:) keyEquivalent:@"q"];
[appMenu addItem:quitMenuItem];
[menuBarItem setSubmenu:appMenu];
}
- (void) buildWindow {
#define _wndW 600
#define _wndH 550
window = [[NSWindow alloc] initWithContentRect: NSMakeRect( 0, 0, _wndW, _wndH )
styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable
backing: NSBackingStoreBuffered defer: NO];
[window center];
[window setTitle: @"Test window"];
[window makeKeyAndOrderFront: nil];
// **** CustomView **** //
CustomView *view = [[CustomView alloc]initWithFrame:NSMakeRect( 20, 60, _wndW - 40, _wndH - 80 )];
[view setWantsLayer:YES];
[[view layer] setBackgroundColor:CGColorCreateGenericRGB( 0.0, 0.0, 1.0, 1.0 )];
[[window contentView] addSubview:view];
// **** Quit btn **** //
NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 50, 10, 40, 40 )];
[quitBtn setBezelStyle:NSBezelStyleCircular ];
[quitBtn setTitle: @"Q" ];
[quitBtn setAction:@selector(terminate:)];
[[window contentView] addSubview: quitBtn];
}
- (void) applicationWillFinishLaunching: (NSNotification *)notification {
[self buildMenu];
[self buildWindow];
}
- (void) applicationDidFinishLaunching: (NSNotification *)notification {
}
@end
int main() {
NSApplication *application = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[application setDelegate:appDelegate];
[application run];
return 0;
}
A:
This worked for me in my NSView subclass:
- (void)awakeFromNib {
self.wantsLayer = YES;// might be unnecessary
}
- (void)viewDidChangeEffectiveAppearance {
self.needsDisplay = YES;
}
- (void)updateLayer {
self.layer.backgroundColor = NSColor.unemphasizedSelectedContentBackgroundColor.CGColor;
}
A:
As of macOS 11 one should use the performAsCurrentDrawingAppearance: instance method and add anything to apply after an appearance change into the given block.
|
Updating programmatically set colors on Mode change (dark mode, light mode) on macOS (objective-c)
|
i am on macOS, objective-c, not iOS. XCode 12.
In a lot of views i set colors like this:
self.menuIconBar.wantsLayer = YES;
self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;
Whenever the user changes the Appeareance, e.g. to Dark mode, i expect my colors to change according to the Asset setup:
Unfortunately, nothing happens. BUT: The same color applied in IB directly changes as expected. Still i'd need them to change programmatically too.
Then i tried to hook on notifications:
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(appleInterfaceThemeChangedNotification:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
I receive the notifications, but when i then call the same code like above again, still the wrong color is loaded.
self.menuIconBar.layer.backgroundColor = [NSColor colorNamed:@"color_gradient_right"].CGColor;
Any help appreciated
|
[
"The following example will change the background color of a custom view depending on the Appearance setting in System Preferences. It may be run in Xcode by creating an objc project, deleting the pre-existing App Delegate, and replacing the code in 'main.m' with the code below:\n#import <Cocoa/Cocoa.h>\n\n@interface CustomView : NSView\n@end\n\n@implementation CustomView\n\n- (id)initWithFrame:(NSRect)frameRect {\n if ((self = [super initWithFrame:frameRect]) != nil) {\n // Add initialization code here\n }\n return self;\n}\n \n- (void)drawRect:(NSRect)rect {\n}\n\n- (void)viewDidChangeEffectiveAppearance {\n NSLog (@\"appearance did change.\");\n NSAppearance *changedAppearance = NSApp.effectiveAppearance;\n NSAppearanceName newAppearance = [changedAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];\n NSLog (@\"new appearance name = %@\", newAppearance);\n if([newAppearance isEqualToString:NSAppearanceNameDarkAqua]){\n [[self layer] setBackgroundColor:CGColorCreateGenericRGB( 1.0, 0.0, 0.0, 1.0 )];\n } else {\n [[self layer] setBackgroundColor:CGColorCreateGenericRGB( 0.0, 0.0, 1.0, 1.0 )];\n }\n}\n\n // Use this if you want 0,0 (origin) to be top, left\n // Otherwise origin will be at bottom, left (Unflipped)\n-(BOOL)isFlipped {\n return YES;\n}\n@end\n \n@interface AppDelegate : NSObject <NSApplicationDelegate> {\n NSWindow *window;\n}\n\n - (void) buildMenu;\n - (void) buildWindow;\n@end\n \n@implementation AppDelegate\n \n- (void) buildMenu {\n NSMenu *menubar = [NSMenu new];\n NSMenuItem *menuBarItem = [NSMenuItem new];\n [menubar addItem:menuBarItem];\n [NSApp setMainMenu:menubar];\n NSMenu *appMenu = [NSMenu new];\n NSMenuItem *quitMenuItem = [[NSMenuItem alloc] initWithTitle:@\"Quit\"\n action:@selector(terminate:) keyEquivalent:@\"q\"];\n [appMenu addItem:quitMenuItem];\n [menuBarItem setSubmenu:appMenu];\n}\n \n- (void) buildWindow {\n #define _wndW 600\n #define _wndH 550\n \n window = [[NSWindow alloc] initWithContentRect: NSMakeRect( 0, 0, _wndW, _wndH )\n styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable\n backing: NSBackingStoreBuffered defer: NO];\n \n [window center];\n [window setTitle: @\"Test window\"];\n [window makeKeyAndOrderFront: nil];\n \n // **** CustomView **** //\n CustomView *view = [[CustomView alloc]initWithFrame:NSMakeRect( 20, 60, _wndW - 40, _wndH - 80 )];\n [view setWantsLayer:YES];\n [[view layer] setBackgroundColor:CGColorCreateGenericRGB( 0.0, 0.0, 1.0, 1.0 )];\n [[window contentView] addSubview:view];\n \n // **** Quit btn **** //\n NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 50, 10, 40, 40 )];\n [quitBtn setBezelStyle:NSBezelStyleCircular ];\n [quitBtn setTitle: @\"Q\" ];\n [quitBtn setAction:@selector(terminate:)];\n [[window contentView] addSubview: quitBtn];\n}\n \n- (void) applicationWillFinishLaunching: (NSNotification *)notification {\n [self buildMenu];\n [self buildWindow];\n}\n \n- (void) applicationDidFinishLaunching: (NSNotification *)notification {\n}\n@end\n \nint main() {\n NSApplication *application = [NSApplication sharedApplication];\n AppDelegate *appDelegate = [[AppDelegate alloc] init];\n [application setDelegate:appDelegate];\n [application run];\n return 0;\n}\n\n\n",
"This worked for me in my NSView subclass:\n- (void)awakeFromNib {\n self.wantsLayer = YES;// might be unnecessary\n}\n\n- (void)viewDidChangeEffectiveAppearance {\n self.needsDisplay = YES;\n}\n\n- (void)updateLayer {\n self.layer.backgroundColor = NSColor.unemphasizedSelectedContentBackgroundColor.CGColor;\n}\n\n",
"As of macOS 11 one should use the performAsCurrentDrawingAppearance: instance method and add anything to apply after an appearance change into the given block.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"macos_darkmode",
"objective_c"
] |
stackoverflow_0064511602_macos_darkmode_objective_c.txt
|
Q:
Why does the wrong EJS tag cause this specific error: SyntaxError: Unexpected token ')'
Goal: I am trying to understand an error which occurred while trying to render a list of "secrets" (strings passed from JSON objects) in a simple Node app serving EJS files.
Code
app.js
const express = require('express');
const ejs = require('ejs');
const app = express();
app.set('view engine', 'ejs');
app.get("/secrets", (req, res) => {
const user1 = { "username": "jon", "secret": "blue blue blue"};
const user2 = { "username": "paul", "secret": "red red red"};
const users = [user1, user2];
res.render("secrets", {usersWithSecrets: users});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});
secrets.ejs
<body>
<html>
<h1>Secrets List:</h1>
<%= usersWithSecrets.forEach((user) => { %>
<p class="secret-text"><%=user.secret%></p>
<%})%>
<hr>
</body>
</html>
Error: SyntaxError: Unexpected token ')' in C:\Users\Owner\Desktop\Sams\scode\Learning\Authentication_and_Redux\code\starting_code\Secrets-Starting_Code\views\secrets.ejs while compiling ejs
I was able to fix the error by changing the 5th line of secrets.ejs to
<% usersWithSecrets.forEach((user) => { %>
but I don't understand why I got the error that I did. I spent a very long time reviewing my code looking for a missing open parenthesis "(" before I even considered that the EJS tags were wrong. Admittedly I am a bit new to EJS, but this error was still very misleading.
Can someone please help me understand why this error was presented instead of an error stating that the EJS tags were wrong?
A:
This happens because to EJS <%= usersWithSecrets.forEach((user) => { %> simply means to insert usersWithSecrets.forEach((user) => { in the <body> element. This is perfectly valid. EJS doesn't assume what you are wanting to do. In other words, that statement is no different than <%= hello world! %> and EJS will happily put that as the text in the <body> tag.
However, when you use the <% %> tag in <% }) %>, it tells EJS that everything here is a script and should be interpreted as javascript. Since there is only a closing bracket and parentheses and no valid javascript earlier to open these, there is now a syntax error. Changing the earlier from an output tag (<%= %>) to a script tag (<% %>) made it a valid javascript script with no error.
In short, just like the javascript interpreter can't assume your intentions, neither can the EJS parser. It couldn't possibly know that you were meaning to start a javascript script and not output usersWithSecrets.forEach((user) => { in the <body> tag. For more information on EJS see the documentation
|
Why does the wrong EJS tag cause this specific error: SyntaxError: Unexpected token ')'
|
Goal: I am trying to understand an error which occurred while trying to render a list of "secrets" (strings passed from JSON objects) in a simple Node app serving EJS files.
Code
app.js
const express = require('express');
const ejs = require('ejs');
const app = express();
app.set('view engine', 'ejs');
app.get("/secrets", (req, res) => {
const user1 = { "username": "jon", "secret": "blue blue blue"};
const user2 = { "username": "paul", "secret": "red red red"};
const users = [user1, user2];
res.render("secrets", {usersWithSecrets: users});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});
secrets.ejs
<body>
<html>
<h1>Secrets List:</h1>
<%= usersWithSecrets.forEach((user) => { %>
<p class="secret-text"><%=user.secret%></p>
<%})%>
<hr>
</body>
</html>
Error: SyntaxError: Unexpected token ')' in C:\Users\Owner\Desktop\Sams\scode\Learning\Authentication_and_Redux\code\starting_code\Secrets-Starting_Code\views\secrets.ejs while compiling ejs
I was able to fix the error by changing the 5th line of secrets.ejs to
<% usersWithSecrets.forEach((user) => { %>
but I don't understand why I got the error that I did. I spent a very long time reviewing my code looking for a missing open parenthesis "(" before I even considered that the EJS tags were wrong. Admittedly I am a bit new to EJS, but this error was still very misleading.
Can someone please help me understand why this error was presented instead of an error stating that the EJS tags were wrong?
|
[
"This happens because to EJS <%= usersWithSecrets.forEach((user) => { %> simply means to insert usersWithSecrets.forEach((user) => { in the <body> element. This is perfectly valid. EJS doesn't assume what you are wanting to do. In other words, that statement is no different than <%= hello world! %> and EJS will happily put that as the text in the <body> tag.\nHowever, when you use the <% %> tag in <% }) %>, it tells EJS that everything here is a script and should be interpreted as javascript. Since there is only a closing bracket and parentheses and no valid javascript earlier to open these, there is now a syntax error. Changing the earlier from an output tag (<%= %>) to a script tag (<% %>) made it a valid javascript script with no error.\nIn short, just like the javascript interpreter can't assume your intentions, neither can the EJS parser. It couldn't possibly know that you were meaning to start a javascript script and not output usersWithSecrets.forEach((user) => { in the <body> tag. For more information on EJS see the documentation\n"
] |
[
1
] |
[] |
[] |
[
"debugging",
"ejs",
"node.js"
] |
stackoverflow_0074667925_debugging_ejs_node.js.txt
|
Q:
How to make it re-enter when user login fail
I have login information in my list. I am trying to match login id and password with list. My code only allow to test correct id and password. If id or password is not matched then my code is not allow me to re enter the id and password.
Here is my code:
System.out.println("*** Welcome back Student ***");
System.out.println("Please enter your Student Id :");
studentID = br.readLine();
System.out.println("Please enter your password :");
password = br.readLine();
// Iterate through list of students to see if we have a match
for (Student student : listOfStudents) {
if (student.getStudentID().equals(studentID)) {
if (student.getPassword().equals(password)) {
loggedInStudent = student;
break;
}
}
}
for (Student student : listOfStudents) {
if (loggedInStudent != null) {
System.out.println("Successfully Login");
break;
} else if (!student.getStudentID().equals(studentID)) {
System.out.println("Wrong Student ID, please check and re-enter your Student ID");
break;
} else {
System.out.println("Wrong password, please check and re-enter your password");
break;
}
}
A:
Easiest way would be to set the code here in a do-while loop. Have a boolean that you can set to true when you need to get out of the loop.
do{
//code you have
//if condition is met, set boolean to true
}while(!booleanName)
A:
In your code, You done a several mistakes. You need to use while loop for re insert the studentId and password. Instead of storing matched studentId and password data into loggedInStudent, I will take a one integer variable loginMatcher. By default it's initialized with a 0.
If loginMatcher == 0, studentId and password is matched.
If loginMatcher == 1, studentId is matched but password is not matched.
If loginMatcher == 2, password is matched but studentId is not matched.
Here is a code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student {
private String studentID;
private String password;
public Student(String studentID, String password) {
this.studentID = studentID;
this.password = password;
}
public Student() {
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int loginMatcher = 0;
while(true)
{
List<Student> listOfStudents = new ArrayList<>();
listOfStudents.add(new Student("1", "123456"));
listOfStudents.add(new Student("2", "1234"));
listOfStudents.add(new Student("3", "123"));
System.out.println("*** Welcome back Student ***");
System.out.println("Please enter your Student Id :");
String studentID = sc.next();
System.out.println("Please enter your password :");
String password = sc.next();
for (Student student : listOfStudents) {
if (student.getStudentID().equals(studentID) && student.getPassword().equals(password)) {
loginMatcher = 0;
break;
} else if (student.getStudentID().equals(studentID) && !student.getPassword().equals(password)) {
loginMatcher = 1;
break;
} else if (!student.getStudentID().equals(studentID) && student.getPassword().equals(password)) {
loginMatcher = 2;
break;
}
}
if (loginMatcher == 2) {
System.out.println("Wrong password, please check and re-enter your password");
} else if (loginMatcher == 1) {
System.out.println("Wrong Student ID, please check and re-enter your Student ID");
} else {
System.out.println("Successfully Login");
break;
}
}
}
}
A:
Perhaps try an validate each entry as you move along. Prompt for the Student ID first then validate it. If it's valid then and only then prompt or the Password related to that Student ID. If it is not valid then allow the User to enter another Student ID before even asking for a password. The same should apply for the password. Once a valid Student ID is acquired, prompt for the password related to that Student ID. If the password is entered incorrectly, then allow the User to try again.
In the runnable demo below, the User can only make three (3) attempts at entering a valid password. This of course can be changed to whatever you like or removed altogether. Read the Comments in code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentLoginDemo {
final Scanner userInput = new Scanner(System.in); // Auto closed when App closes.
final String ls = System.lineSeparator(); // Ensure proper newline in OS Terminal
private List<Student> listOfStudents = new ArrayList<>(); // To hold student instances.
private Student loggedInStudent;
public static void main(String[] args) {
// Started this way to avoid the need for statics.
new StudentLoginDemo().startApp(args);
}
private void startApp(String[] args) {
// Some data for the listOfStudents List for the sake of this demo.
listOfStudents.add(new Student("A1234", "Bill Williams", "foodRunner"));
listOfStudents.add(new Student("C6032", "Tracey Johnson", "FoodEater"));
listOfStudents.add(new Student("A8883", "Jane Smith", "SmithRules01"));
listOfStudents.add(new Student("D3172", "Fred Flintstone", "yabadabadooo"));
System.out.println("*** Welcome Back Student ***" + ls);
String studentID = "";
while (studentID.isEmpty()) {
System.out.print("Please enter your Student ID (q to quit): -> ");
studentID = userInput.nextLine().trim();
// Is quit desired?
if (studentID.equalsIgnoreCase("q")) {
System.out.println("Quiting... Bye Bye");
return; // Exit method.
}
// Validate entry...
if (!doesIdExist(studentID)) {
System.out.println("The Student ID (" + studentID
+ ") you entrered can not be found!"
+ ls + "Try again..." + ls);
studentID = "";
}
}
int passCount = 0;
String password = "";
while (password.isEmpty()) {
passCount++;
System.out.print("Please enter your password (q to quit): -> ");
password = userInput.nextLine().trim();
// Is quit desired?
if (password.equalsIgnoreCase("q")) {
System.out.println("Quiting... Bye Bye");
return; // Exit method.
}
// Validate entry...
loggedInStudent = doesPasswordExist(studentID, password);
if (loggedInStudent == null) {
System.out.println("Invalid Password! (" + password
+ ") Student related password can not be found!"
+ ls + (passCount < 3 ? "Remember, passwords are case sensitive. "
+ "Try again..." + ls : ""));
password = "";
}
if (passCount == 3) {
System.out.println("You have failed to enter a valid Student Password for "
+ "the" + ls + "Student ID of \"" + studentID + "\" within 3 attempts. "
+ "Quiting...");
return;
}
}
// If we have passed through the `while` loops then all is successfull.
String studentName = loggedInStudent.getStudentName();
System.out.println(ls + "Welcome " + (studentName.isEmpty() ? "Student" : studentName)
+ ", You have successfully logged in.");
}
/**
* Returns boolean true if the supplied Student ID exists within
* the listOfStudents List, false if not.<br>
*
* @param id (String) The Student ID. The ID can be alphanumeric.
* Not letter case sensitive.<br>
*
* @return (boolean) Boolean true is returned if the ID exists within
* the listOfStudents List and false if not.
*/
private boolean doesIdExist(String id) {
boolean found = false;
// Iterate through list of students to see if we have the ID
for (Student student : listOfStudents) {
if (student.getStudentID().equalsIgnoreCase(id)) {
found = true;
break;
}
}
return found;
}
/**
* Returns a Student object if the password is valid for the
* supplied ID.<br>
*
* @param id (String) The Student ID.<br>
*
* @param passwrd (String) The Password related to the Student ID.
* The password is letter case sensitive.<br>
*
* @return (Student) Returns the Student instance related to the Student
* ID and Student Password.
*/
private Student doesPasswordExist(String id, String passwrd) {
Student stud = null;
/* Iterate through list of students to see if we have
a match to the Student ID and related Password. */
for (Student student : listOfStudents) {
if (student.getStudentID().equalsIgnoreCase(id)) {
if (student.getPassword().equals(passwrd)) {
stud = student;
break;
}
}
}
return stud;
}
/**
* Student class: Used here as an inner class for demo purposes only.
* This should really be a class file (.java) of its own.
*/
public class Student {
private String studentID;
private String studentName = "";
private String password;
// Contructor #1:
public Student() { }
// Contructor #2:
public Student(String studentID, String password) {
this.studentID = studentID;
this.password = password;
}
// Contructor #3:
public Student(String studentID, String studentName, String password) {
this.studentID = studentID;
this.studentName = studentName;
this.password = password;
}
// Getters & Setters
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
|
How to make it re-enter when user login fail
|
I have login information in my list. I am trying to match login id and password with list. My code only allow to test correct id and password. If id or password is not matched then my code is not allow me to re enter the id and password.
Here is my code:
System.out.println("*** Welcome back Student ***");
System.out.println("Please enter your Student Id :");
studentID = br.readLine();
System.out.println("Please enter your password :");
password = br.readLine();
// Iterate through list of students to see if we have a match
for (Student student : listOfStudents) {
if (student.getStudentID().equals(studentID)) {
if (student.getPassword().equals(password)) {
loggedInStudent = student;
break;
}
}
}
for (Student student : listOfStudents) {
if (loggedInStudent != null) {
System.out.println("Successfully Login");
break;
} else if (!student.getStudentID().equals(studentID)) {
System.out.println("Wrong Student ID, please check and re-enter your Student ID");
break;
} else {
System.out.println("Wrong password, please check and re-enter your password");
break;
}
}
|
[
"Easiest way would be to set the code here in a do-while loop. Have a boolean that you can set to true when you need to get out of the loop.\n do{\n//code you have \n//if condition is met, set boolean to true\n}while(!booleanName)\n\n",
"In your code, You done a several mistakes. You need to use while loop for re insert the studentId and password. Instead of storing matched studentId and password data into loggedInStudent, I will take a one integer variable loginMatcher. By default it's initialized with a 0.\n\nIf loginMatcher == 0, studentId and password is matched.\nIf loginMatcher == 1, studentId is matched but password is not matched.\nIf loginMatcher == 2, password is matched but studentId is not matched.\n\nHere is a code:\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\nclass Student {\n private String studentID;\n private String password;\n\n public Student(String studentID, String password) {\n this.studentID = studentID;\n this.password = password;\n }\n\n public Student() {\n\n }\n\n public String getStudentID() {\n return studentID;\n }\n\n public void setStudentID(String studentID) {\n this.studentID = studentID;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}\n\npublic class Main {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int loginMatcher = 0;\n while(true)\n {\n List<Student> listOfStudents = new ArrayList<>();\n listOfStudents.add(new Student(\"1\", \"123456\"));\n listOfStudents.add(new Student(\"2\", \"1234\"));\n listOfStudents.add(new Student(\"3\", \"123\"));\n\n System.out.println(\"*** Welcome back Student ***\");\n\n System.out.println(\"Please enter your Student Id :\");\n String studentID = sc.next();\n\n System.out.println(\"Please enter your password :\");\n String password = sc.next();\n\n for (Student student : listOfStudents) {\n if (student.getStudentID().equals(studentID) && student.getPassword().equals(password)) {\n loginMatcher = 0;\n break;\n } else if (student.getStudentID().equals(studentID) && !student.getPassword().equals(password)) {\n loginMatcher = 1;\n break;\n } else if (!student.getStudentID().equals(studentID) && student.getPassword().equals(password)) {\n loginMatcher = 2;\n break;\n }\n }\n\n if (loginMatcher == 2) {\n System.out.println(\"Wrong password, please check and re-enter your password\");\n } else if (loginMatcher == 1) {\n System.out.println(\"Wrong Student ID, please check and re-enter your Student ID\");\n } else {\n System.out.println(\"Successfully Login\");\n break;\n }\n }\n }\n}\n\n",
"Perhaps try an validate each entry as you move along. Prompt for the Student ID first then validate it. If it's valid then and only then prompt or the Password related to that Student ID. If it is not valid then allow the User to enter another Student ID before even asking for a password. The same should apply for the password. Once a valid Student ID is acquired, prompt for the password related to that Student ID. If the password is entered incorrectly, then allow the User to try again.\nIn the runnable demo below, the User can only make three (3) attempts at entering a valid password. This of course can be changed to whatever you like or removed altogether. Read the Comments in code:\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\n\npublic class StudentLoginDemo {\n\n final Scanner userInput = new Scanner(System.in); // Auto closed when App closes.\n final String ls = System.lineSeparator(); // Ensure proper newline in OS Terminal\n \n private List<Student> listOfStudents = new ArrayList<>(); // To hold student instances.\n private Student loggedInStudent;\n \n public static void main(String[] args) {\n // Started this way to avoid the need for statics.\n new StudentLoginDemo().startApp(args);\n }\n \n private void startApp(String[] args) {\n // Some data for the listOfStudents List for the sake of this demo.\n listOfStudents.add(new Student(\"A1234\", \"Bill Williams\", \"foodRunner\"));\n listOfStudents.add(new Student(\"C6032\", \"Tracey Johnson\", \"FoodEater\"));\n listOfStudents.add(new Student(\"A8883\", \"Jane Smith\", \"SmithRules01\"));\n listOfStudents.add(new Student(\"D3172\", \"Fred Flintstone\", \"yabadabadooo\"));\n \n System.out.println(\"*** Welcome Back Student ***\" + ls);\n\n String studentID = \"\";\n \n while (studentID.isEmpty()) {\n System.out.print(\"Please enter your Student ID (q to quit): -> \");\n studentID = userInput.nextLine().trim();\n // Is quit desired?\n if (studentID.equalsIgnoreCase(\"q\")) {\n System.out.println(\"Quiting... Bye Bye\");\n return; // Exit method.\n }\n // Validate entry...\n if (!doesIdExist(studentID)) {\n System.out.println(\"The Student ID (\" + studentID \n + \") you entrered can not be found!\"\n + ls + \"Try again...\" + ls);\n studentID = \"\";\n }\n }\n \n int passCount = 0;\n String password = \"\";\n while (password.isEmpty()) {\n passCount++;\n System.out.print(\"Please enter your password (q to quit): -> \");\n password = userInput.nextLine().trim();\n // Is quit desired?\n if (password.equalsIgnoreCase(\"q\")) {\n System.out.println(\"Quiting... Bye Bye\");\n return; // Exit method.\n }\n // Validate entry...\n loggedInStudent = doesPasswordExist(studentID, password);\n if (loggedInStudent == null) {\n System.out.println(\"Invalid Password! (\" + password \n + \") Student related password can not be found!\"\n + ls + (passCount < 3 ? \"Remember, passwords are case sensitive. \"\n + \"Try again...\" + ls : \"\"));\n password = \"\";\n }\n if (passCount == 3) {\n System.out.println(\"You have failed to enter a valid Student Password for \"\n + \"the\" + ls + \"Student ID of \\\"\" + studentID + \"\\\" within 3 attempts. \"\n + \"Quiting...\");\n return;\n }\n }\n \n // If we have passed through the `while` loops then all is successfull.\n String studentName = loggedInStudent.getStudentName();\n System.out.println(ls + \"Welcome \" + (studentName.isEmpty() ? \"Student\" : studentName)\n + \", You have successfully logged in.\");\n }\n \n /**\n * Returns boolean true if the supplied Student ID exists within \n * the listOfStudents List, false if not.<br>\n * \n * @param id (String) The Student ID. The ID can be alphanumeric. \n * Not letter case sensitive.<br>\n * \n * @return (boolean) Boolean true is returned if the ID exists within \n * the listOfStudents List and false if not.\n */\n private boolean doesIdExist(String id) {\n boolean found = false;\n // Iterate through list of students to see if we have the ID\n for (Student student : listOfStudents) {\n if (student.getStudentID().equalsIgnoreCase(id)) {\n found = true;\n break;\n }\n }\n return found;\n }\n \n /**\n * Returns a Student object if the password is valid for the \n * supplied ID.<br>\n * \n * @param id (String) The Student ID.<br>\n * \n * @param passwrd (String) The Password related to the Student ID. \n * The password is letter case sensitive.<br>\n * \n * @return (Student) Returns the Student instance related to the Student \n * ID and Student Password.\n */\n private Student doesPasswordExist(String id, String passwrd) {\n Student stud = null;\n /* Iterate through list of students to see if we have \n a match to the Student ID and related Password. */\n for (Student student : listOfStudents) {\n if (student.getStudentID().equalsIgnoreCase(id)) {\n if (student.getPassword().equals(passwrd)) {\n stud = student;\n break;\n }\n }\n }\n return stud;\n }\n \n /**\n * Student class: Used here as an inner class for demo purposes only. \n * This should really be a class file (.java) of its own.\n */\n public class Student {\n\n private String studentID;\n private String studentName = \"\";\n private String password;\n\n // Contructor #1:\n public Student() { }\n \n // Contructor #2:\n public Student(String studentID, String password) {\n this.studentID = studentID;\n this.password = password;\n }\n \n // Contructor #3:\n public Student(String studentID, String studentName, String password) {\n this.studentID = studentID;\n this.studentName = studentName;\n this.password = password;\n }\n\n \n // Getters & Setters\n public String getStudentID() {\n return studentID;\n }\n\n public void setStudentID(String studentID) {\n this.studentID = studentID;\n }\n\n public String getStudentName() {\n return studentName;\n }\n\n public void setStudentName(String studentName) {\n this.studentName = studentName;\n }\n \n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n }\n\n}\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"java"
] |
stackoverflow_0074664542_java.txt
|
Q:
Workers not applied I've just added a Worker on the Cloudflare Dashboard for my website
Subject: Workers not applied
I've just added a Worker on the Cloudflare Dashboard for my website: it works in debugger but doesn't work when I query site. Why is that? Is there anything to activate or anything I could check?
Subject: Workers not applied
I've just added a Worker on the Cloudflare Dashboard for my website:
A:
There could be several reasons why your Worker is not being applied on your website when querying. Here are a few things to check and try:
Make sure that the Worker is activated and published on the
Cloudflare Dashboard. You can check this by going to the Workers tab
on the Dashboard and checking the status of the Worker. If it is not
activated or published, click on the Worker and go to the "Overview"
tab to activate and publish it.
Check the route that the Worker is attached to. The route is a URL
pattern that determines which requests the Worker will run on. Make
sure that the route is correct and matches the URL of your website
when querying. You can check and edit the route by going to the
"Settings" tab of the Worker on the Dashboard.
If you have multiple Workers attached to the same route, make sure
that the order of the Workers is correct. The order determines which
Worker will run first and which will run last. You can check and
edit the order by going to the "Overview" tab of the Worker on the
Dashboard.
Clear your browser cache and try querying your website again.
Sometimes the browser cache can cause issues with the Worker not
being applied.
If you still have issues with the Worker not being applied, you can try reaching out to Cloudflare support for further assistance.
|
Workers not applied I've just added a Worker on the Cloudflare Dashboard for my website
|
Subject: Workers not applied
I've just added a Worker on the Cloudflare Dashboard for my website: it works in debugger but doesn't work when I query site. Why is that? Is there anything to activate or anything I could check?
Subject: Workers not applied
I've just added a Worker on the Cloudflare Dashboard for my website:
|
[
"There could be several reasons why your Worker is not being applied on your website when querying. Here are a few things to check and try:\n\nMake sure that the Worker is activated and published on the\nCloudflare Dashboard. You can check this by going to the Workers tab\non the Dashboard and checking the status of the Worker. If it is not\nactivated or published, click on the Worker and go to the \"Overview\"\ntab to activate and publish it.\nCheck the route that the Worker is attached to. The route is a URL\npattern that determines which requests the Worker will run on. Make\nsure that the route is correct and matches the URL of your website\nwhen querying. You can check and edit the route by going to the\n\"Settings\" tab of the Worker on the Dashboard.\nIf you have multiple Workers attached to the same route, make sure\nthat the order of the Workers is correct. The order determines which\nWorker will run first and which will run last. You can check and\nedit the order by going to the \"Overview\" tab of the Worker on the\nDashboard.\nClear your browser cache and try querying your website again.\nSometimes the browser cache can cause issues with the Worker not\nbeing applied.\n\nIf you still have issues with the Worker not being applied, you can try reaching out to Cloudflare support for further assistance.\n"
] |
[
1
] |
[] |
[] |
[
"cloudflare"
] |
stackoverflow_0074668483_cloudflare.txt
|
Q:
contract has not been deployed to detected network (network/artifact mismatch) on Rinkeby Network
I have been running into the specified in the title.
I have developed a smart contract and have successfully compiled and deployed it to the network as follows:
1. Run testrpc
2. truffle compile
3. truffle migrate
However, the error above is still being shown.
I then tried deleting the build file and followed the steps below:
1. Run testrpc
2. truffle compile
3. truffle migrate --network rinkeby
The error was still being shown.
Below is the truffle.js file
module.exports = {
migrations_directory: "./migrations",
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},
rinkeby: {
host: "localhost", // Connect to geth on the specified
port: 8545,
network_id: "*",
}
}
};
If anybody has faced any similar issues and have resolved it, I would greatly appreciate it if you could share how you have resolved it.
Thanks in advance
A:
For me, the following steps worked: create the file 2_deploy_contract.js in the migration folder with the code
var myContract = artifacts.require("myContract");
module.exports = function(deployer){
deployer.deploy(myContract);
}
And run on terminal
$ truffle migrate --reset
I didn't need to change any settings in the truffle-config.js
A:
I had the same issue and created the file 2_deploy_contract.js in the migration folder with the code:
var myContract = artifacts.require("myContract");
module.exports = function(deployer){
deployer.deploy(myContract);
}
I also checked the truffle-config.js at the root of the folder with the default settings:
rinkeby: {
host: "localhost",
port: 8545,
from: "0x0085f8e72391Ce4BB5ce47541C846d059399fA6c", // default address to use for any transaction Truffle makes during migrations
network_id: 4,
gas: 4612388 // Gas limit used for deploys
}
A:
Tl;dr:
Add a new migration to your migration folder and name it as following:
2_deploy_contract.js
PS: you can name it whatever. 2_deploy_yourmomsdonuts.js would work too. Just pay attention to the number - it has to correspond with the order.
2. Add this code snipper to this file:
Replace HelloWorld with the name of your contract that didn't get deployed (see in your console what contract has thrown an error)
var HelloWorld = artifacts.require('HelloWorld');
module.exports = function (deployer) {
deployer.deploy(HelloWorld);
};
Run truffle migrate --reset or truffle deploy --reset - These are aliases and do the same thing. You can also run both of them to be on the safe side.
You should see that your contract got deployed to your network.
Finally truffle console and invoke your function again. Voila.
Why did you have to manually add a migration?
The problem was that your smart contract didn't get deployed/did't get recognized so by manually adding your migration, you are telling Truffle which file should get deployed.
A:
There are a lot of different error messages through the original post and the comments. I think the best thing is to provide a step-by-step guide to deploying to Rinkeby using Truffle:
Geth
To start, create the account you want to use for this test. It looks like you've already done this, but including this for completeness. Note, that I am using a custom keystore directory because I like to keep my keystores separate across different networks.
geth --rinkeby --keystore ./eth/accounts/rinkeby/keystore account new
After entering your password, you will get back your new address. Once the account is created, create a new text file called pass.txt and put the password you used to create the account inside the file and save it.
Obviously this is not the preferred way of keeping passwords safe. Do not do this in a live environment
You'll also need to add some ether to your account. Use faucet.rinkeby.io.
Next, make sure you are properly starting starting Geth and it's in the correct state. I use custom data and keystore directories. You can use the default if you choose.
geth --rpc --datadir ./eth/geth/data/rinkeby --keystore ./eth/accounts/rinkeby/keystore --rinkeby --rpccorsdomain '*' --rpcapi 'web3,eth,net,personal' --unlock '0x25e6C81C823D4e15084F8e93F4d9B7F365C0857d' --password ./pass.txt --syncmode="full" --cache=1024
Replace my address with the one you created. When started, you should see something like this:
INFO [02-13|17:47:24] Starting peer-to-peer node instance=Geth/TrustDevTestNode/v1.7.3-stable-4bb3c89d/windows-amd64/go1.9
INFO [02-13|17:47:24] Allocated cache and file handles database=C:\\cygwin\\home\\adamk\\eth\\geth\\data\\rinkeby\\geth\\chaindata cache=1024 handles=1024
INFO [02-13|17:47:47] Initialised chain configuration config="{ChainID: 4 Homestead: 1 DAO: <nil> DAOSupport: true EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 1035301 Engine: clique}"
INFO [02-13|17:47:47] Initialising Ethereum protocol versions="[63 62]" network=4
INFO [02-13|17:47:47] Loaded most recent local header number=1766839 hash=6d71ad…ca5a95 td=3285475
INFO [02-13|17:47:47] Loaded most recent local full block number=1766839 hash=6d71ad…ca5a95 td=3285475
INFO [02-13|17:47:47] Loaded most recent local fast block number=1766839 hash=6d71ad…ca5a95 td=3285475
INFO [02-13|17:47:47] Loaded local transaction journal transactions=0 dropped=0
INFO [02-13|17:47:47] Regenerated local transaction journal transactions=0 accounts=0
INFO [02-13|17:47:48] Starting P2P networking
2018/02/13 17:47:50 ssdp: got unexpected search target result "upnp:rootdevice"
2018/02/13 17:47:50 ssdp: got unexpected search target result "uuid:2f402f80-da50-11e1-9b23-001788409545"
2018/02/13 17:47:50 ssdp: got unexpected search target result "urn:schemas-upnp-org:device:basic:1"
2018/02/13 17:47:50 ssdp: got unexpected search target result "upnp:rootdevice"
2018/02/13 17:47:50 ssdp: got unexpected search target result "uuid:2f402f80-da50-11e1-9b23-001788409545"
INFO [02-13|17:47:51] UDP listener up self=enode://751bc7825c66f9ab5b87f933d6b6302fd14434b7ed4d7c921c3f39684915843078eda4e995c927561067946b4f856ca2a35ea7285c27439c0f535338aaca80e9@172.88.30.226:30303
INFO [02-13|17:47:51] RLPx listener up self=enode://751bc7825c66f9ab5b87f933d6b6302fd14434b7ed4d7c921c3f39684915843078eda4e995c927561067946b4f856ca2a35ea7285c27439c0f535338aaca80e9@172.88.30.226:30303
INFO [02-13|17:47:51] IPC endpoint opened: \\.\pipe\geth.ipc
INFO [02-13|17:47:51] HTTP endpoint opened: http://127.0.0.1:8545
INFO [02-13|17:47:52] Unlocked account address=0x25e6C81C823D4e15084F8e93F4d9B7F365C0857d
Confirm that network=4.
Confirm that the last line showing the account being unlocked succeeds without error.
Once your node starts, make sure it is fully synced.
Truffle
truffle.js (or truffle-config.js if Windows):
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},
rinkeby: {
host: "localhost",
port: 8545,
from: "0x25e6c81c823d4e15084f8e93f4d9b7f365c0857d",
network_id: "4"
}
}
};
Use Truffle console to confirm your node and account:
$ truffle console --network rinkeby
truffle(rinkeby)> web3.eth.blockNumber
1767136 // Confirm latest block number on https://rinkeby.etherscan.io/
truffle(rinkeby)> web3.eth.getBalance('0x25e6c81c823d4e15084f8e93f4d9b7f365c0857d');
{ [String: '2956062100000000000'] s: 1, e: 18, c: [ 29560, 62100000000000 ] }
Exit the console and run your compile/migrations (this will take about a minute to run):
$ truffle migrate --network rinkeby
Compiling .\contracts\LoopExample.sol...
Writing artifacts to .\build\contracts
Using network 'rinkeby'.
Running migration: 1_initial_migration.js
Deploying Migrations...
... 0xf377be391a2eaff821c0405256c6a1f50389650ea9754bdc2711296b02533e02
Migrations: 0x9cef8d8959d0611046d5144ec0439473ad842c7c
Saving successful migration to network...
... 0x4cf989973ea56a9aa4477effaccd9b59bfb80cc0e0e1b7878ff25fa5cae328db
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying LoopExample...
... 0x4977c60fd86e1c4ab09d8f970be7b7827ee25245575bfbe206c19c6b065e9031
LoopExample: 0x56b9c563f287cdd6a9a41e4678ceeeb6fc56e104
Saving successful migration to network...
... 0x5628d64dc43708ccb30d7754a440e8e420a82a7b3770539cb94302fe7ad9098f
Saving artifacts...
Confirm the deployment on etherscan: https://rinkeby.etherscan.io/address/0x56b9c563f287cdd6a9a41e4678ceeeb6fc56e104
A:
I came across the same problem and the following solved it for me:
...configuring the 1_initial_migration.js to deploy the TodoList contract for this to work. When doing the truffle init it deploys a Migration.sol contract, so you have to change that:
var TodoList = artifacts.require('../contracts/TodoList.sol');
module.exports = function(deployer) {
deployer.deploy(TodoList);
}
source: https://medium.com/@addibro/i-had-to-fiddle-around-with-truffle-compile-and-migrate-first-and-also-configuring-the-9bc7a6ea8e3e
A:
I found the solution for this problem.
i change my migration file name from AdvancedStorage_migrate.js to 2_AdvancedStorage_migrate.js
truffle can't able find a migration file if you didn't save your migration file without number so, you must be save your migration file like this(2_AdvancedStorage_migrate.js )
this problem is not rise from truffle configuration so don't touch truffle configuration.js file
A:
Solution :
In My case I am using truffle-contract to load contract abi .
By default truflle-contract network id is 1.
But I am using goreli network id 5. We need to setNetwork while loading contract
`
const contract = require('truffle-contract');
const MyContract = contract(MyContract);
MyContract.setProvider(web3.currentProvider);
MyContract.setNetwork(5)
`
|
contract has not been deployed to detected network (network/artifact mismatch) on Rinkeby Network
|
I have been running into the specified in the title.
I have developed a smart contract and have successfully compiled and deployed it to the network as follows:
1. Run testrpc
2. truffle compile
3. truffle migrate
However, the error above is still being shown.
I then tried deleting the build file and followed the steps below:
1. Run testrpc
2. truffle compile
3. truffle migrate --network rinkeby
The error was still being shown.
Below is the truffle.js file
module.exports = {
migrations_directory: "./migrations",
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},
rinkeby: {
host: "localhost", // Connect to geth on the specified
port: 8545,
network_id: "*",
}
}
};
If anybody has faced any similar issues and have resolved it, I would greatly appreciate it if you could share how you have resolved it.
Thanks in advance
|
[
"For me, the following steps worked: create the file 2_deploy_contract.js in the migration folder with the code\nvar myContract = artifacts.require(\"myContract\");\n\nmodule.exports = function(deployer){\n deployer.deploy(myContract);\n}\n\nAnd run on terminal\n$ truffle migrate --reset\n\nI didn't need to change any settings in the truffle-config.js\n",
"I had the same issue and created the file 2_deploy_contract.js in the migration folder with the code:\nvar myContract = artifacts.require(\"myContract\");\n\nmodule.exports = function(deployer){\n deployer.deploy(myContract);\n}\n\nI also checked the truffle-config.js at the root of the folder with the default settings:\nrinkeby: {\n host: \"localhost\", \n port: 8545, \n from: \"0x0085f8e72391Ce4BB5ce47541C846d059399fA6c\", // default address to use for any transaction Truffle makes during migrations\n network_id: 4,\n gas: 4612388 // Gas limit used for deploys\n}\n\n",
"Tl;dr:\n\nAdd a new migration to your migration folder and name it as following:\n2_deploy_contract.js\n\nPS: you can name it whatever. 2_deploy_yourmomsdonuts.js would work too. Just pay attention to the number - it has to correspond with the order.\n2. Add this code snipper to this file:\nReplace HelloWorld with the name of your contract that didn't get deployed (see in your console what contract has thrown an error)\n\n\nvar HelloWorld = artifacts.require('HelloWorld');\n\nmodule.exports = function (deployer) {\n deployer.deploy(HelloWorld);\n};\n\n\n\n\nRun truffle migrate --reset or truffle deploy --reset - These are aliases and do the same thing. You can also run both of them to be on the safe side.\n\nYou should see that your contract got deployed to your network.\n\nFinally truffle console and invoke your function again. Voila.\n\n\nWhy did you have to manually add a migration?\nThe problem was that your smart contract didn't get deployed/did't get recognized so by manually adding your migration, you are telling Truffle which file should get deployed.\n",
"There are a lot of different error messages through the original post and the comments. I think the best thing is to provide a step-by-step guide to deploying to Rinkeby using Truffle:\nGeth\nTo start, create the account you want to use for this test. It looks like you've already done this, but including this for completeness. Note, that I am using a custom keystore directory because I like to keep my keystores separate across different networks.\ngeth --rinkeby --keystore ./eth/accounts/rinkeby/keystore account new\nAfter entering your password, you will get back your new address. Once the account is created, create a new text file called pass.txt and put the password you used to create the account inside the file and save it.\nObviously this is not the preferred way of keeping passwords safe. Do not do this in a live environment\nYou'll also need to add some ether to your account. Use faucet.rinkeby.io.\nNext, make sure you are properly starting starting Geth and it's in the correct state. I use custom data and keystore directories. You can use the default if you choose.\ngeth --rpc --datadir ./eth/geth/data/rinkeby --keystore ./eth/accounts/rinkeby/keystore --rinkeby --rpccorsdomain '*' --rpcapi 'web3,eth,net,personal' --unlock '0x25e6C81C823D4e15084F8e93F4d9B7F365C0857d' --password ./pass.txt --syncmode=\"full\" --cache=1024\n\nReplace my address with the one you created. When started, you should see something like this:\nINFO [02-13|17:47:24] Starting peer-to-peer node instance=Geth/TrustDevTestNode/v1.7.3-stable-4bb3c89d/windows-amd64/go1.9\nINFO [02-13|17:47:24] Allocated cache and file handles database=C:\\\\cygwin\\\\home\\\\adamk\\\\eth\\\\geth\\\\data\\\\rinkeby\\\\geth\\\\chaindata cache=1024 handles=1024\nINFO [02-13|17:47:47] Initialised chain configuration config=\"{ChainID: 4 Homestead: 1 DAO: <nil> DAOSupport: true EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 1035301 Engine: clique}\"\nINFO [02-13|17:47:47] Initialising Ethereum protocol versions=\"[63 62]\" network=4\nINFO [02-13|17:47:47] Loaded most recent local header number=1766839 hash=6d71ad…ca5a95 td=3285475\nINFO [02-13|17:47:47] Loaded most recent local full block number=1766839 hash=6d71ad…ca5a95 td=3285475\nINFO [02-13|17:47:47] Loaded most recent local fast block number=1766839 hash=6d71ad…ca5a95 td=3285475\nINFO [02-13|17:47:47] Loaded local transaction journal transactions=0 dropped=0\nINFO [02-13|17:47:47] Regenerated local transaction journal transactions=0 accounts=0\nINFO [02-13|17:47:48] Starting P2P networking\n2018/02/13 17:47:50 ssdp: got unexpected search target result \"upnp:rootdevice\"\n2018/02/13 17:47:50 ssdp: got unexpected search target result \"uuid:2f402f80-da50-11e1-9b23-001788409545\"\n2018/02/13 17:47:50 ssdp: got unexpected search target result \"urn:schemas-upnp-org:device:basic:1\"\n2018/02/13 17:47:50 ssdp: got unexpected search target result \"upnp:rootdevice\"\n2018/02/13 17:47:50 ssdp: got unexpected search target result \"uuid:2f402f80-da50-11e1-9b23-001788409545\"\nINFO [02-13|17:47:51] UDP listener up self=enode://751bc7825c66f9ab5b87f933d6b6302fd14434b7ed4d7c921c3f39684915843078eda4e995c927561067946b4f856ca2a35ea7285c27439c0f535338aaca80e9@172.88.30.226:30303\nINFO [02-13|17:47:51] RLPx listener up self=enode://751bc7825c66f9ab5b87f933d6b6302fd14434b7ed4d7c921c3f39684915843078eda4e995c927561067946b4f856ca2a35ea7285c27439c0f535338aaca80e9@172.88.30.226:30303\nINFO [02-13|17:47:51] IPC endpoint opened: \\\\.\\pipe\\geth.ipc\nINFO [02-13|17:47:51] HTTP endpoint opened: http://127.0.0.1:8545\nINFO [02-13|17:47:52] Unlocked account address=0x25e6C81C823D4e15084F8e93F4d9B7F365C0857d\n\n\nConfirm that network=4.\nConfirm that the last line showing the account being unlocked succeeds without error.\nOnce your node starts, make sure it is fully synced.\n\nTruffle\ntruffle.js (or truffle-config.js if Windows):\nmodule.exports = {\n networks: {\n development: {\n host: \"localhost\",\n port: 8545,\n network_id: \"*\" // Match any network id\n },\n rinkeby: {\n host: \"localhost\",\n port: 8545,\n from: \"0x25e6c81c823d4e15084f8e93f4d9b7f365c0857d\",\n network_id: \"4\"\n }\n }\n};\n\nUse Truffle console to confirm your node and account:\n$ truffle console --network rinkeby\ntruffle(rinkeby)> web3.eth.blockNumber\n1767136 // Confirm latest block number on https://rinkeby.etherscan.io/\ntruffle(rinkeby)> web3.eth.getBalance('0x25e6c81c823d4e15084f8e93f4d9b7f365c0857d');\n{ [String: '2956062100000000000'] s: 1, e: 18, c: [ 29560, 62100000000000 ] }\n\nExit the console and run your compile/migrations (this will take about a minute to run):\n$ truffle migrate --network rinkeby\nCompiling .\\contracts\\LoopExample.sol...\nWriting artifacts to .\\build\\contracts\n\nUsing network 'rinkeby'.\n\nRunning migration: 1_initial_migration.js\n Deploying Migrations...\n ... 0xf377be391a2eaff821c0405256c6a1f50389650ea9754bdc2711296b02533e02\n Migrations: 0x9cef8d8959d0611046d5144ec0439473ad842c7c\nSaving successful migration to network...\n ... 0x4cf989973ea56a9aa4477effaccd9b59bfb80cc0e0e1b7878ff25fa5cae328db\nSaving artifacts...\nRunning migration: 2_deploy_contracts.js\n Deploying LoopExample...\n ... 0x4977c60fd86e1c4ab09d8f970be7b7827ee25245575bfbe206c19c6b065e9031\n LoopExample: 0x56b9c563f287cdd6a9a41e4678ceeeb6fc56e104\nSaving successful migration to network...\n ... 0x5628d64dc43708ccb30d7754a440e8e420a82a7b3770539cb94302fe7ad9098f\nSaving artifacts...\n\nConfirm the deployment on etherscan: https://rinkeby.etherscan.io/address/0x56b9c563f287cdd6a9a41e4678ceeeb6fc56e104\n",
"I came across the same problem and the following solved it for me:\n...configuring the 1_initial_migration.js to deploy the TodoList contract for this to work. When doing the truffle init it deploys a Migration.sol contract, so you have to change that:\nvar TodoList = artifacts.require('../contracts/TodoList.sol');\nmodule.exports = function(deployer) {\n deployer.deploy(TodoList);\n\n}\n\nsource: https://medium.com/@addibro/i-had-to-fiddle-around-with-truffle-compile-and-migrate-first-and-also-configuring-the-9bc7a6ea8e3e\n",
"I found the solution for this problem.\ni change my migration file name from AdvancedStorage_migrate.js to 2_AdvancedStorage_migrate.js\ntruffle can't able find a migration file if you didn't save your migration file without number so, you must be save your migration file like this(2_AdvancedStorage_migrate.js )\nthis problem is not rise from truffle configuration so don't touch truffle configuration.js file\n",
"Solution :\nIn My case I am using truffle-contract to load contract abi .\nBy default truflle-contract network id is 1.\nBut I am using goreli network id 5. We need to setNetwork while loading contract\n`\n const contract = require('truffle-contract'); \n const MyContract = contract(MyContract); \n \n MyContract.setProvider(web3.currentProvider); \n MyContract.setNetwork(5) \n\n`\n"
] |
[
12,
6,
4,
0,
0,
0,
0
] |
[
"\n\n const conract = artifacts.require('conractArtifact');\n\n//update this\nmodule.exports = function (deployer) {}\n//to this\nmodule.exports = async (deployer) => {}\n//or to this\nmodule.exports = fucntion (deployer) {}\n\n\n\n"
] |
[
-3
] |
[
"consensys_truffle",
"ethereum",
"smartcontracts",
"truffle"
] |
stackoverflow_0048694192_consensys_truffle_ethereum_smartcontracts_truffle.txt
|
Q:
How to run express server on Shared Hosting?
My shared hosting doesn't allow me customization. But, I anyhow installed nodejs. I also wrote an express server code inside /var/www/test-server directory.
const express = require('express')
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
• But, I cannot access express server
• I can't use port 80.
• When I use some other ports like 8080, then I can see console output on Terminal as below:
example.work@example:/var/www/test-server$ node index.js
Example app listening on port 8080
Now, my question is —
"Is it possible to access express server with or without port through browser?"
Like: http://example.com/test-server
A:
You must set up NGINX for the express server to be available on a Domain.
Alternatively, you can access the server at http://ipofthemachine:port
Make sure the port you are using is exposed if you have any firewall in place.
|
How to run express server on Shared Hosting?
|
My shared hosting doesn't allow me customization. But, I anyhow installed nodejs. I also wrote an express server code inside /var/www/test-server directory.
const express = require('express')
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
• But, I cannot access express server
• I can't use port 80.
• When I use some other ports like 8080, then I can see console output on Terminal as below:
example.work@example:/var/www/test-server$ node index.js
Example app listening on port 8080
Now, my question is —
"Is it possible to access express server with or without port through browser?"
Like: http://example.com/test-server
|
[
"You must set up NGINX for the express server to be available on a Domain.\nAlternatively, you can access the server at http://ipofthemachine:port\nMake sure the port you are using is exposed if you have any firewall in place.\n"
] |
[
0
] |
[] |
[] |
[
"express",
"hosting",
"node.js",
"server"
] |
stackoverflow_0074668272_express_hosting_node.js_server.txt
|
Q:
How set up Vue 3 main.js file with extra imports
Hi I'm trying to start a new project using vue 3,I'm trying to do the vue 3 version of main.js file that works in vue 2
import GlobalMethods from './utils/globalMethods';
Vue.prototype.$GlobalMethods = GlobalMethods;
I try this:
app.config.$GlobalMethods = GlobalMethods;
but the screen is blank and I have this error in console:
Cannot read properties of undefined (reading 'use')
A:
In Vue 3, the app.config object has been removed and you can use the app.use() function to add global plugins to your application. The code you provided would be updated to look like this:
import { createApp } from 'vue';
import GlobalMethods from './utils/globalMethods';
const app = createApp({
// app options here
});
app.use(GlobalMethods);
This will add the GlobalMethods plugin to your application and make it available on the app instance.
You can also add the GlobalMethods plugin directly to the createApp call like this:
import { createApp } from 'vue';
import GlobalMethods from './utils/globalMethods';
const app = createApp({
// app options here
setup() {
return {
GlobalMethods,
};
},
});
|
How set up Vue 3 main.js file with extra imports
|
Hi I'm trying to start a new project using vue 3,I'm trying to do the vue 3 version of main.js file that works in vue 2
import GlobalMethods from './utils/globalMethods';
Vue.prototype.$GlobalMethods = GlobalMethods;
I try this:
app.config.$GlobalMethods = GlobalMethods;
but the screen is blank and I have this error in console:
Cannot read properties of undefined (reading 'use')
|
[
"In Vue 3, the app.config object has been removed and you can use the app.use() function to add global plugins to your application. The code you provided would be updated to look like this:\nimport { createApp } from 'vue';\nimport GlobalMethods from './utils/globalMethods';\n\nconst app = createApp({\n // app options here\n});\n\napp.use(GlobalMethods);\n\nThis will add the GlobalMethods plugin to your application and make it available on the app instance.\nYou can also add the GlobalMethods plugin directly to the createApp call like this:\nimport { createApp } from 'vue';\nimport GlobalMethods from './utils/globalMethods';\n\nconst app = createApp({\n // app options here\n setup() {\n return {\n GlobalMethods,\n };\n },\n});\n\n"
] |
[
2
] |
[] |
[] |
[
"vue.js",
"vuejs3"
] |
stackoverflow_0074668526_vue.js_vuejs3.txt
|
Q:
why does flutter app have bad performance when launching them
I'm trying to make my app performant.
I'm using dart devtools and when i check the graph I see that there is some shader compilation detected when launching the app for the first time, I thought that my app has a problem but i tried to run the code that flutter provides us when creating a new project and boom the result was the same.
I want to know if there is someone that encountred the same problem ?
Ps : i tested the app on a real device with os Android 12 and CPU ARM X64.
there is my code :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: MyHomePage(
title: 'App',
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
children: const [
Text('hello'),
],
),
),
);
}
}
A:
As I understand your problem, you want to reduce the time your app needs to start and found the shader compilation to be a big part of it. If that understanding is correct, this might help:
First, you can not "disable" shader compilation, every flutter application needs to compile the shaders for rendering, but it heavily depends on your application, how much time that takes (many animations for example are bad here)
Second, since Flutter 1.20, you can use the SkSL warmup to reduce the startup time for compiling your shaders. The idea being, that you compile the shader once and save it for faster startup times.
You can test this feature while in development with
flutter run --cache-sksl
this will take more time than before, but afterwards, your flutter run commands will be faster.
If you want to build your application with SkSL warmup, you have to write the SkSL shaders into a file by pressing "M" while in the command line of flutter run, then you can use:
flutter build ios --bundle-sksl-path flutter_01.sksl.json
to build the application. More information can be found here.
I tested this with the small program you sent, for normal startup it needed 25.9ms for the shader compilation, caching the sksl file needed 225.9ms, and flutter run afterwards needed 9.6ms for the shaders. Therefore caching sksl made it about 63% faster (it was only one short test, so the results are no medians or anything, so the meaningfulness of this test is debatable).
Lastly, you should always test your performance in release builds, not in debug mode. Debugging your application has a large overhead and much worse performance than released applications. Have a look at Flutter build modes for more information.
|
why does flutter app have bad performance when launching them
|
I'm trying to make my app performant.
I'm using dart devtools and when i check the graph I see that there is some shader compilation detected when launching the app for the first time, I thought that my app has a problem but i tried to run the code that flutter provides us when creating a new project and boom the result was the same.
I want to know if there is someone that encountred the same problem ?
Ps : i tested the app on a real device with os Android 12 and CPU ARM X64.
there is my code :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: MyHomePage(
title: 'App',
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
children: const [
Text('hello'),
],
),
),
);
}
}
|
[
"As I understand your problem, you want to reduce the time your app needs to start and found the shader compilation to be a big part of it. If that understanding is correct, this might help:\nFirst, you can not \"disable\" shader compilation, every flutter application needs to compile the shaders for rendering, but it heavily depends on your application, how much time that takes (many animations for example are bad here)\nSecond, since Flutter 1.20, you can use the SkSL warmup to reduce the startup time for compiling your shaders. The idea being, that you compile the shader once and save it for faster startup times.\nYou can test this feature while in development with\nflutter run --cache-sksl\n\nthis will take more time than before, but afterwards, your flutter run commands will be faster.\nIf you want to build your application with SkSL warmup, you have to write the SkSL shaders into a file by pressing \"M\" while in the command line of flutter run, then you can use:\nflutter build ios --bundle-sksl-path flutter_01.sksl.json\n\nto build the application. More information can be found here.\nI tested this with the small program you sent, for normal startup it needed 25.9ms for the shader compilation, caching the sksl file needed 225.9ms, and flutter run afterwards needed 9.6ms for the shaders. Therefore caching sksl made it about 63% faster (it was only one short test, so the results are no medians or anything, so the meaningfulness of this test is debatable).\nLastly, you should always test your performance in release builds, not in debug mode. Debugging your application has a large overhead and much worse performance than released applications. Have a look at Flutter build modes for more information.\n"
] |
[
0
] |
[] |
[] |
[
"dart",
"devtools",
"flutter",
"performance"
] |
stackoverflow_0074668245_dart_devtools_flutter_performance.txt
|
Q:
'Multiple commands produce' error not resolving
I'm getting these errors when trying to archive my app for the App Store. During testing these never resent themselves. I found a similar post here but the solution doesn't work for me as I don't have the offending files in that build phase. I am using pods to install, so I don't know if that would make the solution different.
1) Target 'Realm-iOS11.0' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Realm.framework'
2) Target 'Realm-iOS12.2' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Realm.framework'
Second error
1) Target 'RealmSwift-iOS11.0' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/RealmSwift.framework'
2) Target 'RealmSwift-iOS12.2' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/RealmSwift.framework'
A:
As I was typing this out I poked around some more and eventually figured it out. I tried to deintegrate and reinstall pods, but it failed because there are different targets of the project that were using different versions of Swift. After I matched all targets to the same version of Swift and installed, everything was fine.
A:
Clear your Derived Data folder.
You can go to File > Workspace Settings if you are in a workspace environment or File > Project Settings for a regular project environment.
Then click over the little grey arrow under Derived data section and select your project folder to delete it.
A:
Please specify a platform for this target in your Podfile. See https://guides.cocoapods.org/syntax/podfile.html#platform.
Example:
target 'theProject' do
platform :ios, '12.0'
use_frameworks!
# some pod
end
target 'theWidgetExtension' do
platform :ios, '12.0'
use_frameworks!
# some pod
end
You must using the same version of Pod library. Please read more in your terminal.
|
'Multiple commands produce' error not resolving
|
I'm getting these errors when trying to archive my app for the App Store. During testing these never resent themselves. I found a similar post here but the solution doesn't work for me as I don't have the offending files in that build phase. I am using pods to install, so I don't know if that would make the solution different.
1) Target 'Realm-iOS11.0' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Realm.framework'
2) Target 'Realm-iOS12.2' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Realm.framework'
Second error
1) Target 'RealmSwift-iOS11.0' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/RealmSwift.framework'
2) Target 'RealmSwift-iOS12.2' has create directory command with output '/Users/user/Library/Developer/Xcode/DerivedData/.../IntermediateBuildFilesPath/UninstalledProducts/iphoneos/RealmSwift.framework'
|
[
"As I was typing this out I poked around some more and eventually figured it out. I tried to deintegrate and reinstall pods, but it failed because there are different targets of the project that were using different versions of Swift. After I matched all targets to the same version of Swift and installed, everything was fine.\n",
"Clear your Derived Data folder.\nYou can go to File > Workspace Settings if you are in a workspace environment or File > Project Settings for a regular project environment.\nThen click over the little grey arrow under Derived data section and select your project folder to delete it.\n",
"Please specify a platform for this target in your Podfile. See https://guides.cocoapods.org/syntax/podfile.html#platform.\nExample:\ntarget 'theProject' do\n platform :ios, '12.0'\n use_frameworks!\n# some pod\nend\n\ntarget 'theWidgetExtension' do\n platform :ios, '12.0'\n use_frameworks!\n# some pod\nend\n\nYou must using the same version of Pod library. Please read more in your terminal.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"ios",
"xcode"
] |
stackoverflow_0059978645_ios_xcode.txt
|
Q:
pyspark concatonate multiple columns where the column name is in a list
I am trying to concatonate multiple columns to just one column, but only if the column name is in a list.
so issue = {'a','b','c'} is my list and would need to concatonate it as issue column with ; seperator.
I have tried:
1.
df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue}))))
Which returns invalid syntax error
2.
df_issue = df.withColumn('issue', lit(issue))
this just returnd a b c and not their value
Thank you
I have tried:
1.
df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue}))))
Which returns invalid syntax error
2.
df_issue = df.withColumn('issue', lit(issue))
this just returnd a b c and not their value
Thank you
A:
To concatenate multiple columns to one column, you can use the concat_ws() function in combination with the collect_list() function. The concat_ws() function concatenates the values of multiple columns into one column, using a specified separator. The collect_list() function collects the values of a specified column into a list.
Here is an example of how to use these functions to concatenate the values of the columns in the list issue into one column:
from pyspark.sql.functions import concat_ws, collect_list
df_issue = df.withColumn('issue', concat_ws(';', collect_list(issue)))
This code uses the concat_ws() and collect_list() functions to concatenate the values of the columns in the issue list into one column, using a semicolon as the separator. The resulting column will contain the concatenated values of the specified columns.
A:
You can simply use concat_ws:
from pyspark.sql import functions as F
columns_to_concat = ['a', 'b', 'c']
df.withColumn('issue', F.concat_ws(';', *columns_to_concat))
So, if your input DataFrame is:
+---+---+---+----------+----------+-----+
| a| b| c| date1| date2|value|
+---+---+---+----------+----------+-----+
| k1| k2| k3|2022-11-11|2022-11-14| 5|
| k4| k5| k6|2022-11-15|2022-11-19| 5|
| k7| k8| k9|2022-11-15|2022-11-19| 5|
+---+---+---+----------+----------+-----+
The previous code will produce:
+---+---+---+----------+----------+-----+--------+
| a| b| c| date1| date2|value| issue|
+---+---+---+----------+----------+-----+--------+
| k1| k2| k3|2022-11-11|2022-11-14| 5|k1;k2;k3|
| k4| k5| k6|2022-11-15|2022-11-19| 5|k4;k5;k6|
| k7| k8| k9|2022-11-15|2022-11-19| 5|k7;k8;k9|
+---+---+---+----------+----------+-----+--------+
|
pyspark concatonate multiple columns where the column name is in a list
|
I am trying to concatonate multiple columns to just one column, but only if the column name is in a list.
so issue = {'a','b','c'} is my list and would need to concatonate it as issue column with ; seperator.
I have tried:
1.
df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue}))))
Which returns invalid syntax error
2.
df_issue = df.withColumn('issue', lit(issue))
this just returnd a b c and not their value
Thank you
I have tried:
1.
df_issue = df.withColumn('issue', concat_ws(';',map_values(custom.({issue}))))
Which returns invalid syntax error
2.
df_issue = df.withColumn('issue', lit(issue))
this just returnd a b c and not their value
Thank you
|
[
"To concatenate multiple columns to one column, you can use the concat_ws() function in combination with the collect_list() function. The concat_ws() function concatenates the values of multiple columns into one column, using a specified separator. The collect_list() function collects the values of a specified column into a list.\nHere is an example of how to use these functions to concatenate the values of the columns in the list issue into one column:\nfrom pyspark.sql.functions import concat_ws, collect_list\n\ndf_issue = df.withColumn('issue', concat_ws(';', collect_list(issue)))\n\nThis code uses the concat_ws() and collect_list() functions to concatenate the values of the columns in the issue list into one column, using a semicolon as the separator. The resulting column will contain the concatenated values of the specified columns.\n",
"You can simply use concat_ws:\nfrom pyspark.sql import functions as F\n\ncolumns_to_concat = ['a', 'b', 'c']\ndf.withColumn('issue', F.concat_ws(';', *columns_to_concat))\n\nSo, if your input DataFrame is:\n+---+---+---+----------+----------+-----+\n| a| b| c| date1| date2|value|\n+---+---+---+----------+----------+-----+\n| k1| k2| k3|2022-11-11|2022-11-14| 5|\n| k4| k5| k6|2022-11-15|2022-11-19| 5|\n| k7| k8| k9|2022-11-15|2022-11-19| 5|\n+---+---+---+----------+----------+-----+\n\nThe previous code will produce:\n+---+---+---+----------+----------+-----+--------+\n| a| b| c| date1| date2|value| issue|\n+---+---+---+----------+----------+-----+--------+\n| k1| k2| k3|2022-11-11|2022-11-14| 5|k1;k2;k3|\n| k4| k5| k6|2022-11-15|2022-11-19| 5|k4;k5;k6|\n| k7| k8| k9|2022-11-15|2022-11-19| 5|k7;k8;k9|\n+---+---+---+----------+----------+-----+--------+\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"apache_spark_sql",
"concatenation",
"list",
"pyspark"
] |
stackoverflow_0074653466_apache_spark_sql_concatenation_list_pyspark.txt
|
Q:
Blazor Web Site keeps reloading randomly every few seconds
I have a Blazor Web Site that keeps reloading every few sconds. this occurs on the customer server prod env. but not in the local development env. also the problem didn't appear right from the begining. it was stable until one of the recent version updates. any ideas ?
I've read that sometimes this a Chrome beheaviour that sends releoad request
A:
Problem solved
EventAggregator.Blazor was it.
crazy bug and missused 3th part component.
I used it to send events from diffrent pages/components to top area of the view like status messages etc.
It seems to work well.
But then when in prodution we opened the site to many users, it turns out that every request a user sends, is notified to the rest of the current active users and causes their browser to refres.
|
Blazor Web Site keeps reloading randomly every few seconds
|
I have a Blazor Web Site that keeps reloading every few sconds. this occurs on the customer server prod env. but not in the local development env. also the problem didn't appear right from the begining. it was stable until one of the recent version updates. any ideas ?
I've read that sometimes this a Chrome beheaviour that sends releoad request
|
[
"Problem solved\nEventAggregator.Blazor was it.\ncrazy bug and missused 3th part component.\nI used it to send events from diffrent pages/components to top area of the view like status messages etc.\nIt seems to work well.\nBut then when in prodution we opened the site to many users, it turns out that every request a user sends, is notified to the rest of the current active users and causes their browser to refres.\n"
] |
[
0
] |
[] |
[] |
[
"asp.net",
"blazor",
"iis"
] |
stackoverflow_0074640312_asp.net_blazor_iis.txt
|
Q:
Sort list based on time in Optaplanner constraint
I have a use case where I want to assign a salesperson to a list of appointments. Now, these salespeople have to travel from one point to another to reach the appointment location.
I am using Optaplanner to schedule a list of salesperson to a bunch of appointments. I have a constraint defined:
Next appointment start time should be after previous appointment's end time + travel time to reach the next appointment + Grace time
Constraint nextApptConflict(ConstraintFactory constraintFactory) {
return constraintFactory
// Select each pair of 2 different appointments ...
.forEachUniquePair(Appointment.class,
Joiners.equal((appt) -> appt.getRep().getUuid()))
//Sort the result based on appointment start time
//Check for time gap is feasible or not
// ... and penalize each pair with a hard weight.
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("SalesRep conflict");
}
The idea is to first get all the appointments assigned to each sales rep and then sort the result based on appointment start time and then check violations (if any) and penalize accordingly.
However, I am not sure how can we sort the appointments in constraint class and whether should I group the appointment or Joiners.equal((appt) -> appt.getRep().getUuid()) is also correct?
A:
You don't need to sort anything. You do need to better specify your unique pairs:
Select the first appointment (forEach).
Select the second appointment such that it starts after the first one ends (join with some lessThan/greaterThan joiners).
Make sure there is no third appointment between the two (ifNotExists).
This will give you all pairs of consecutive appointments.
What remains is to penalize based on the difference between the end of the first and the start of the next.
|
Sort list based on time in Optaplanner constraint
|
I have a use case where I want to assign a salesperson to a list of appointments. Now, these salespeople have to travel from one point to another to reach the appointment location.
I am using Optaplanner to schedule a list of salesperson to a bunch of appointments. I have a constraint defined:
Next appointment start time should be after previous appointment's end time + travel time to reach the next appointment + Grace time
Constraint nextApptConflict(ConstraintFactory constraintFactory) {
return constraintFactory
// Select each pair of 2 different appointments ...
.forEachUniquePair(Appointment.class,
Joiners.equal((appt) -> appt.getRep().getUuid()))
//Sort the result based on appointment start time
//Check for time gap is feasible or not
// ... and penalize each pair with a hard weight.
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("SalesRep conflict");
}
The idea is to first get all the appointments assigned to each sales rep and then sort the result based on appointment start time and then check violations (if any) and penalize accordingly.
However, I am not sure how can we sort the appointments in constraint class and whether should I group the appointment or Joiners.equal((appt) -> appt.getRep().getUuid()) is also correct?
|
[
"You don't need to sort anything. You do need to better specify your unique pairs:\n\nSelect the first appointment (forEach).\nSelect the second appointment such that it starts after the first one ends (join with some lessThan/greaterThan joiners).\nMake sure there is no third appointment between the two (ifNotExists).\n\nThis will give you all pairs of consecutive appointments.\nWhat remains is to penalize based on the difference between the end of the first and the start of the next.\n"
] |
[
0
] |
[] |
[] |
[
"java",
"optaplanner",
"optaweb_employee_rostering",
"sorting"
] |
stackoverflow_0074665372_java_optaplanner_optaweb_employee_rostering_sorting.txt
|
Q:
How to customize arrow buttons in Swiper
How can I customize the arrow buttons below from swipers?
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
I did it crudely but it does not seem to be the right way because I get some margin on the right of the button.
<div class="swiper-button-next hide-for-small-only hide-for-medium-only" style="border: 1px solid red; background-color: yellow; padding: 30px; ></div>
The entire code:
.swiper-container {
width: 100%;
height: 450px;
}
.swiper-slide {
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide {
font-size: 18px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.swiper-banner-slide {
-webkit-background-size: cover;
background-size: cover;
background-position: center;
}
.swiper-slide .title {
font-family: 'Bellefair', serif;
font-size: 41px;
line-height: 40px;
font-weight: 300;
}
.swiper-slide .subtitle {
font-size: 21px;
}
.swiper-slide .text {
font-size: 21px;
letter-spacing: 1px;
}
.slide-info-container {
color: #000;
}
.swiper-block {
padding: 40px 0 40px;
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
/*padding: 0;*/
}
.swiper-block .swiper-container {
width: 100%;
height: 300px;
margin: 20px auto;
}
.swiper-block .swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
<!-- CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Zurb - CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/js/foundation.min.js"></script>
<!-- Swiper - CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.jquery.min.js"></script>
<main>
<div class="row" id="banner">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/1.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 1</h3>
<div class="text">
<p>Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. Integer laoreet magna nec elit suscipit, ac laoreet nibh euismod. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/2.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 2</h3>
<div class="text">
<p>Aliquam hendrerit lorem at elit facilisis rutrum. Ut at ullamcorper velit. Nulla ligula nisi, imperdiet ut lacinia nec, tincidunt ut libero. Aenean feugiat non eros quis feugiat.</p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/3.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 3</h3>
<div class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus felis iaculis nec. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/4.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 4</h3>
<div class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/5.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 5</h3>
<div class="text">
<p>Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo.</p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next hide-for-small-only hide-for-medium-only" style="border: 1px solid red; background-color: yellow; padding: 30px; ></div>
<div class=" swiper-button-prev hide-for-small-only hide-for-medium-only "></div>
</div>
<!-- Swiper -->
</div>
<!-- row block -->
<div class="row swiper-block ">
<div class="grid-container ">
<div class="grid-x grid-padding-x ">
<div class="small-12 cell ">
<!-- Swiper -->
<div class="swiper-container ">
<div class="swiper-wrapper ">
<div class="swiper-slide ">Slide 1</div>
<div class="swiper-slide ">Slide 2</div>
<div class="swiper-slide ">Slide 3</div>
<div class="swiper-slide ">Slide 4</div>
<div class="swiper-slide ">Slide 5</div>
<div class="swiper-slide ">Slide 6</div>
<div class="swiper-slide ">Slide 7</div>
<div class="swiper-slide ">Slide 8</div>
<div class="swiper-slide ">Slide 9</div>
<div class="swiper-slide ">Slide 10</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination "></div>
</div>
</div>
</div>
</div>
</div>
</main>
<script>
$(function() {
$(document).foundation();
var swiper = new Swiper('#banner .swiper-container', {
pagination: '#banner .swiper-pagination',
slidesPerView: 1,
paginationClickable: true,
centeredSlides: true,
spaceBetween: 30,
loop: true,
keyboardControl: true,
nextButton: '#banner .swiper-button-next',
prevButton: '#banner .swiper-button-prev',
});
var swiper2 = new Swiper('.swiper-block .swiper-container', {
pagination: '.swiper-block .swiper-pagination',
slidesPerView: 5,
paginationClickable: true,
spaceBetween: 30,
freeMode: true,
keyboardControl: false,
});
});
</script>
I don't want the margin.
Any ideas?
EDIT:
How do I change the colour blue on the arrow to black?
.swiper-button-next,
.swiper-button-prev {
background-color: white;
background-color: rgba(255, 255, 255, 0.5);
right:10px;
padding: 30px;
color: #000 !important;
fill: black !important;
stroke: black !important;
}
Does not work of course!
A:
Add this to style the prev / next arrows:
.swiper-button-prev {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%234c71ae'%2F%3E%3C%2Fsvg%3E") !important;
}
.swiper-button-next {
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%234c71ae'%2F%3E%3C%2Fsvg%3E") !important;
}
Where "4c71ae" is the color you want to use in HEX.
A:
:root {
--swiper-theme-color: #000;
}
Try this instead of !important to change color.
A:
With the current version of SwiperJS (v.5.3.8) you can change the color of the arrows in css without any issues. Just define color.
.swiper-button-prev {
color: red;
}
.swiper-button-next {
color: #000;
}
A:
Those who want to change the default arrows just set you custom SVG etc in the elements the HTML; mine is next & prev
<div class="swiper-button-next">Next</div>
<div class="swiper-button-prev">Prev</div>
And remove the default icons in CSS
.swiper-button-next::after, .swiper-button-prev::after {
content: "";
}
A:
For anyone looking to change the color etc of various buttons etc for Swiper, be sure to inspect the CSS of what you are trying to change and see if the property you are trying to change is using a CSS variable.
In the case were a CSS variable has been used, you need to re-define it in order to change it.
Example for changing the color of the swiper next/prev buttons:
Underlying CSS:
.swiper-button-next, .swiper-button-prev {
position: absolute;
top: 50%;
width: calc(var(--swiper-navigation-size)/ 44 * 27);
height: var(--swiper-navigation-size);
margin-top: calc(0px - (var(--swiper-navigation-size)/ 2));
z-index: 10;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
color: var(--swiper-navigation-color,var(--swiper-theme-color));
}
Add this to the styles.css (or globals.css in NextJS)
:root {
--swiper-navigation-color: #E49A38;
}
A:
"I don't want the margin. Any ideas?"
If the margin is really the margin, not the result of right property, try to overwrite default "swipers" styles using !important, like this:
.class {
margin: 0 !important;
}
Otherwise set right property to 0:
.class {
right: 0;
}
Or
.class {
right: 0 !important;
}
If it doesn't work without !important.
"How do I change the colour blue on the arrow to black?"
If you just want to make them black, you can simply use one of the built-in classes (swiper-button-black in your case) - thanks to this comment.
A:
If you're using Angular, you can simply use ::ng-deep to override the color.
For example :
::ng-deep .swiper-button-prev,
::ng-deep .swiper-button-next {
color: white;
}
A:
.swiper-button-next::after, .swiper-button-prev::after{
content: "";
}
A:
If you use JavaScript, you can also change --swiper-navigation-color inside the page/component instead of changing :root in the CSS file. I found it more convenient in React/Next.js. Just add this to your code.
document.documentElement.style.setProperty("--swiper-theme-color", "#000")
If you are going with this solution and you are building a React/Next.js app, remember to include the code from above in useEffect to load the document in the appropriate moment (more about it here).
useEffect(() => {
document.documentElement.style.setProperty("--swiper-theme-color", "#000")
}, [])
A:
If you're using React, another approach apart from @Jakub’s is to pass a style prop to Swiper like this
<Swiper style={{"--swiper-navigation-color": "#FFF", "--swiper-pagination-color": "#FFF"}}>
.....
</Swiper>
A:
.swiper-button-next {
--swiper-navigation-color:white;
}
.swiper-button-prev {
--swiper-navigation-color:white;
}
A:
Very simple
.main__swiper_left {
background-image: url("../img_2/main__swiper_left.png");
width: 58px;
height: 58px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
.main__swiper_left::after {
display: none;
}
Source
A:
For the color, edit the swiper-bundle.min.css on line 13, change the :root attribute to this:
:root {
--swiper-theme-color: #FFFFFF;
}
A:
.swiper-button-prev {
color: green !important;
}
.swiper-button-next {
color: green !important;
}
A:
For those who want to replace default arrows with custom SVG icon. I'm using Swiper version 8.3.2.
Here is a demo example project.
Place <img> tag into both elements.
<!-- Navigation arrows -->
<div class="swiper-button-prev">
<img src="@/assets/icons/svg/right-arrow.svg" />
</div>
<div class="swiper-button-next">
<img src="@/assets/icons/svg/right-arrow.svg" />
</div>
Then, remove the default icons in CSS.
.swiper-button-prev::after,
.swiper-button-next::after {
display: none;
}
.swiper-button-prev img {
transform: rotate(180deg);
}
A:
This solution worked for me:
// use the `useState` hook instead of `useRef`
const [prevEl, setPrevEl] = useState<HTMLElement | null>(null)
const [nextEl, setPrevEl] = useState<HTMLElement | null>(null)
<Swiper navigation={{ prevEl, nextEl }}>
// some slides
</Swiper>
<div ref={(node) => setPrevEl(node)}>prev</div>
<div ref={(node) => setNextEl(node)}>next</div>
A:
.swiper.swiper-button-next {color: black; --swiper-navigation-size: 30px;}
.swiper.swiper-button-prev{color: black; --swiper-navigation-size: 30px;}
Try this one! to Increase and Decrease Size and Change Color.
Don't forget to use !important after the color property.
A:
There are many ways to customize these arrows. You just need to specify your proper parameters in the :root of your CSS file.
:root {
--swiper-navigation-size: 16px; /* To edit the size of the arrows */
--swiper-navigation-color: #000; /* To edit the color of the arrows */
}
|
How to customize arrow buttons in Swiper
|
How can I customize the arrow buttons below from swipers?
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
I did it crudely but it does not seem to be the right way because I get some margin on the right of the button.
<div class="swiper-button-next hide-for-small-only hide-for-medium-only" style="border: 1px solid red; background-color: yellow; padding: 30px; ></div>
The entire code:
.swiper-container {
width: 100%;
height: 450px;
}
.swiper-slide {
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide {
font-size: 18px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.swiper-banner-slide {
-webkit-background-size: cover;
background-size: cover;
background-position: center;
}
.swiper-slide .title {
font-family: 'Bellefair', serif;
font-size: 41px;
line-height: 40px;
font-weight: 300;
}
.swiper-slide .subtitle {
font-size: 21px;
}
.swiper-slide .text {
font-size: 21px;
letter-spacing: 1px;
}
.slide-info-container {
color: #000;
}
.swiper-block {
padding: 40px 0 40px;
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
/*padding: 0;*/
}
.swiper-block .swiper-container {
width: 100%;
height: 300px;
margin: 20px auto;
}
.swiper-block .swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
<!-- CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Zurb - CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/js/foundation.min.js"></script>
<!-- Swiper - CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.jquery.min.js"></script>
<main>
<div class="row" id="banner">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/1.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 1</h3>
<div class="text">
<p>Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo. Integer laoreet magna nec elit suscipit, ac laoreet nibh euismod. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/2.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 2</h3>
<div class="text">
<p>Aliquam hendrerit lorem at elit facilisis rutrum. Ut at ullamcorper velit. Nulla ligula nisi, imperdiet ut lacinia nec, tincidunt ut libero. Aenean feugiat non eros quis feugiat.</p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/3.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 3</h3>
<div class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus felis iaculis nec. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/4.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 4</h3>
<div class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dictum mattis velit, sit amet faucibus felis iaculis nec. Nulla laoreet justo vitae porttitor porttitor. </p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
<div class="swiper-slide swiper-banner-slide" style="background-image: url('images/5.jpg')">
<!-- grid container -->
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="small-12 medium-10 large-8 cell slide-info-container">
<h3 class="title">Aliquam dictum mattis velit 5</h3>
<div class="text">
<p>Nulla laoreet justo vitae porttitor porttitor. Suspendisse in sem justo.</p>
</div>
<a href="#features" class="hollow button button-details">More Details</a>
</div>
</div>
</div>
<!-- grid container -->
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next hide-for-small-only hide-for-medium-only" style="border: 1px solid red; background-color: yellow; padding: 30px; ></div>
<div class=" swiper-button-prev hide-for-small-only hide-for-medium-only "></div>
</div>
<!-- Swiper -->
</div>
<!-- row block -->
<div class="row swiper-block ">
<div class="grid-container ">
<div class="grid-x grid-padding-x ">
<div class="small-12 cell ">
<!-- Swiper -->
<div class="swiper-container ">
<div class="swiper-wrapper ">
<div class="swiper-slide ">Slide 1</div>
<div class="swiper-slide ">Slide 2</div>
<div class="swiper-slide ">Slide 3</div>
<div class="swiper-slide ">Slide 4</div>
<div class="swiper-slide ">Slide 5</div>
<div class="swiper-slide ">Slide 6</div>
<div class="swiper-slide ">Slide 7</div>
<div class="swiper-slide ">Slide 8</div>
<div class="swiper-slide ">Slide 9</div>
<div class="swiper-slide ">Slide 10</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination "></div>
</div>
</div>
</div>
</div>
</div>
</main>
<script>
$(function() {
$(document).foundation();
var swiper = new Swiper('#banner .swiper-container', {
pagination: '#banner .swiper-pagination',
slidesPerView: 1,
paginationClickable: true,
centeredSlides: true,
spaceBetween: 30,
loop: true,
keyboardControl: true,
nextButton: '#banner .swiper-button-next',
prevButton: '#banner .swiper-button-prev',
});
var swiper2 = new Swiper('.swiper-block .swiper-container', {
pagination: '.swiper-block .swiper-pagination',
slidesPerView: 5,
paginationClickable: true,
spaceBetween: 30,
freeMode: true,
keyboardControl: false,
});
});
</script>
I don't want the margin.
Any ideas?
EDIT:
How do I change the colour blue on the arrow to black?
.swiper-button-next,
.swiper-button-prev {
background-color: white;
background-color: rgba(255, 255, 255, 0.5);
right:10px;
padding: 30px;
color: #000 !important;
fill: black !important;
stroke: black !important;
}
Does not work of course!
|
[
"Add this to style the prev / next arrows:\n.swiper-button-prev {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%234c71ae'%2F%3E%3C%2Fsvg%3E\") !important;\n}\n\n.swiper-button-next {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%234c71ae'%2F%3E%3C%2Fsvg%3E\") !important;\n}\n\nWhere \"4c71ae\" is the color you want to use in HEX.\n",
":root {\n --swiper-theme-color: #000;\n}\n\nTry this instead of !important to change color.\n",
"With the current version of SwiperJS (v.5.3.8) you can change the color of the arrows in css without any issues. Just define color.\n.swiper-button-prev {\n color: red; \n}\n\n.swiper-button-next {\n color: #000; \n}\n\n",
"Those who want to change the default arrows just set you custom SVG etc in the elements the HTML; mine is next & prev\n\n\n<div class=\"swiper-button-next\">Next</div>\n<div class=\"swiper-button-prev\">Prev</div>\n\n\n\nAnd remove the default icons in CSS\n\n\n.swiper-button-next::after, .swiper-button-prev::after {\n content: \"\";\n}\n\n\n\n",
"For anyone looking to change the color etc of various buttons etc for Swiper, be sure to inspect the CSS of what you are trying to change and see if the property you are trying to change is using a CSS variable.\nIn the case were a CSS variable has been used, you need to re-define it in order to change it.\nExample for changing the color of the swiper next/prev buttons:\nUnderlying CSS:\n.swiper-button-next, .swiper-button-prev {\n position: absolute;\n top: 50%;\n width: calc(var(--swiper-navigation-size)/ 44 * 27);\n height: var(--swiper-navigation-size);\n margin-top: calc(0px - (var(--swiper-navigation-size)/ 2));\n z-index: 10;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--swiper-navigation-color,var(--swiper-theme-color));\n}\n\nAdd this to the styles.css (or globals.css in NextJS)\n:root {\n --swiper-navigation-color: #E49A38;\n}\n\n",
"\"I don't want the margin. Any ideas?\"\nIf the margin is really the margin, not the result of right property, try to overwrite default \"swipers\" styles using !important, like this:\n.class {\n margin: 0 !important;\n}\n\nOtherwise set right property to 0:\n.class {\n right: 0;\n}\n\nOr\n.class {\n right: 0 !important;\n}\n\nIf it doesn't work without !important.\n\n\"How do I change the colour blue on the arrow to black?\"\nIf you just want to make them black, you can simply use one of the built-in classes (swiper-button-black in your case) - thanks to this comment.\n",
"If you're using Angular, you can simply use ::ng-deep to override the color.\nFor example :\n::ng-deep .swiper-button-prev,\n::ng-deep .swiper-button-next {\n color: white;\n}\n\n",
".swiper-button-next::after, .swiper-button-prev::after{\n content: \"\";\n}\n\n",
"If you use JavaScript, you can also change --swiper-navigation-color inside the page/component instead of changing :root in the CSS file. I found it more convenient in React/Next.js. Just add this to your code.\ndocument.documentElement.style.setProperty(\"--swiper-theme-color\", \"#000\")\n\nIf you are going with this solution and you are building a React/Next.js app, remember to include the code from above in useEffect to load the document in the appropriate moment (more about it here).\n useEffect(() => {\n document.documentElement.style.setProperty(\"--swiper-theme-color\", \"#000\")\n }, [])\n\n",
"If you're using React, another approach apart from @Jakub’s is to pass a style prop to Swiper like this\n<Swiper style={{\"--swiper-navigation-color\": \"#FFF\", \"--swiper-pagination-color\": \"#FFF\"}}>\n .....\n</Swiper>\n\n",
".swiper-button-next {\n --swiper-navigation-color:white;\n}\n\n.swiper-button-prev {\n --swiper-navigation-color:white;\n}\n\n",
"Very simple\n.main__swiper_left {\nbackground-image: url(\"../img_2/main__swiper_left.png\");\nwidth: 58px;\nheight: 58px; \nbackground-repeat: no-repeat;\nbackground-position: center;\nbackground-size: cover;\n}\n\n.main__swiper_left::after {\ndisplay: none;\n}\n\nSource\n",
"For the color, edit the swiper-bundle.min.css on line 13, change the :root attribute to this:\n :root {\n --swiper-theme-color: #FFFFFF;\n }\n\n",
"\n\n.swiper-button-prev {\n color: green !important;\n}\n\n.swiper-button-next {\n color: green !important;\n}\n\n\n\n",
"For those who want to replace default arrows with custom SVG icon. I'm using Swiper version 8.3.2.\nHere is a demo example project.\nPlace <img> tag into both elements.\n<!-- Navigation arrows -->\n<div class=\"swiper-button-prev\">\n <img src=\"@/assets/icons/svg/right-arrow.svg\" />\n</div>\n<div class=\"swiper-button-next\">\n <img src=\"@/assets/icons/svg/right-arrow.svg\" />\n</div>\n\nThen, remove the default icons in CSS.\n.swiper-button-prev::after,\n.swiper-button-next::after {\n display: none;\n}\n\n.swiper-button-prev img {\n transform: rotate(180deg);\n}\n\n",
"This solution worked for me:\n// use the `useState` hook instead of `useRef`\nconst [prevEl, setPrevEl] = useState<HTMLElement | null>(null)\nconst [nextEl, setPrevEl] = useState<HTMLElement | null>(null)\n<Swiper navigation={{ prevEl, nextEl }}>\n// some slides\n</Swiper>\n<div ref={(node) => setPrevEl(node)}>prev</div>\n<div ref={(node) => setNextEl(node)}>next</div>\n\n",
".swiper.swiper-button-next {color: black; --swiper-navigation-size: 30px;}\n\n.swiper.swiper-button-prev{color: black; --swiper-navigation-size: 30px;}\n\nTry this one! to Increase and Decrease Size and Change Color.\nDon't forget to use !important after the color property.\n",
"There are many ways to customize these arrows. You just need to specify your proper parameters in the :root of your CSS file.\n:root {\n--swiper-navigation-size: 16px; /* To edit the size of the arrows */\n--swiper-navigation-color: #000; /* To edit the color of the arrows */\n}\n\n"
] |
[
45,
17,
8,
7,
4,
3,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] |
[
"If you want to change the color, you can simply do the following and it will overwrite the current color to white... Hope this will be useful!\nNote: You can specify any color you want to change! Thanks\n.swiper-button-prev,.swiper-button-next{ \n color:white !important;\n}\n\n",
"This worked for me.\n.swiper-button-prev {\n color: red !important;\n}\n\n.swiper-button-next {\n color: red !important;\n}\n\n"
] |
[
-1,
-1
] |
[
"css",
"html",
"javascript",
"swiper.js"
] |
stackoverflow_0045381871_css_html_javascript_swiper.js.txt
|
Q:
Have a div moving (dynamicly) with CSS or JS?
Is it possible with css to have a div move with the screen while the user is scrolling (e.g. fixed)
but then stopt if it hits another one and jump over it if the user scrolls further.
To make it imaginable...
for example if you have 3 divs with a lot of text is it possible that i have div jumping into slots under each of those as the user reads forward?
A:
I would suggest you to use https://github.com/brandonaaron/jquery-overlaps and then do something like this to slot the moving div:
$(window).scroll(function() {
var movingDiv = $('.moving-div');
if (movingDiv.overlaps('.static-div')
&& !movingDiv.hasClass('slotted')) {
$('.static-div').before(movingDiv);
movingDiv.css('position', 'static');
movingDiv.addClass('slotted');
}
});
The code is just a hint and you also need to bind a function for "unslotting" the moving div.
A:
Make the math using a transparent dummy object that have the same propierties than the fixed one.
$(window).scroll(function(){
var b1_fo = $("#dummy").offset().top + $("#dummy").height();
var b2_fo = $("#b2").offset().top + $("#b2").height();
if( b1_fo > $("#b2").offset().top && b1_fo < b2_fo + $("#dummy").height()){
$("#b1").css({top:$("#b2").offset().top - $("#b2").height(),position:'absolute'})
} else {
$("#b1").removeAttr('style')
}
})
Working example: http://jsfiddle.net/LpULy/
A:
I would suggest you to use https://github.com/brandonaaron/jquery-overlaps and then do something like this to slot the moving div:
The code is just a hint and you also need to bind a function for "unslotting" the moving div.
I hope this would be helpfull
Thank you
|
Have a div moving (dynamicly) with CSS or JS?
|
Is it possible with css to have a div move with the screen while the user is scrolling (e.g. fixed)
but then stopt if it hits another one and jump over it if the user scrolls further.
To make it imaginable...
for example if you have 3 divs with a lot of text is it possible that i have div jumping into slots under each of those as the user reads forward?
|
[
"I would suggest you to use https://github.com/brandonaaron/jquery-overlaps and then do something like this to slot the moving div:\n$(window).scroll(function() {\n var movingDiv = $('.moving-div');\n\n if (movingDiv.overlaps('.static-div') \n && !movingDiv.hasClass('slotted')) {\n $('.static-div').before(movingDiv);\n movingDiv.css('position', 'static');\n movingDiv.addClass('slotted');\n }\n});\n\nThe code is just a hint and you also need to bind a function for \"unslotting\" the moving div.\n",
"Make the math using a transparent dummy object that have the same propierties than the fixed one.\n$(window).scroll(function(){\n var b1_fo = $(\"#dummy\").offset().top + $(\"#dummy\").height();\n var b2_fo = $(\"#b2\").offset().top + $(\"#b2\").height();\n if( b1_fo > $(\"#b2\").offset().top && b1_fo < b2_fo + $(\"#dummy\").height()){\n $(\"#b1\").css({top:$(\"#b2\").offset().top - $(\"#b2\").height(),position:'absolute'})\n } else {\n $(\"#b1\").removeAttr('style')\n }\n})\n\nWorking example: http://jsfiddle.net/LpULy/\n",
"I would suggest you to use https://github.com/brandonaaron/jquery-overlaps and then do something like this to slot the moving div:\nThe code is just a hint and you also need to bind a function for \"unslotting\" the moving div.\nI hope this would be helpfull\nThank you\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"css",
"html",
"javascript",
"position"
] |
stackoverflow_0009011002_css_html_javascript_position.txt
|
Q:
How to force collapse all expansion panels?
I want to force close my expansion panel when I clicked Update
How do I programmatically do that ?
This is what I have in my update().
update(index) {
console.log("index", index);
let vehicle = {};
vehicle.VIN = this.savedVehicles[index].VIN;
vehicle.ModelYear = this.savedVehicles[index].ModelYear;
vehicle.Make = this.savedVehicles[index].Make;
vehicle.Model = this.savedVehicles[index].Model;
this.savedVehicles[index] = vehicle;
localStorage.setItem("savedVehicles", JSON.stringify(this.savedVehicles));
this.alert = true;
this.alertColor = "green";
this.alertMessage = `${vehicle.VIN} updated`;
// hope to collapse all expansion panels
},
A:
Expansion panels can be controlled externally by modifying the
v-model. Its value corresponds to a zero-based index of the currently
opened expansion panel content. If multiple props are used then it is an
array containing the indices of the open items.
To control the opening and closing status of multiple panels
https://codepen.io/pen?&editors=101
If need to control only a single expansion panel then use this-
<template>
<v-expansion-panels v-model="panel">
// any code here
</v-expansion-panels>
<button @click="closePanel()">Close</button>
</template>
<script>
export default {
data() {
return {
panel: 0 // This means should open by default
}
},
methods: {
closePanel() {
this.panel = null; // null is to close the panel
}
}
}
</script>
|
How to force collapse all expansion panels?
|
I want to force close my expansion panel when I clicked Update
How do I programmatically do that ?
This is what I have in my update().
update(index) {
console.log("index", index);
let vehicle = {};
vehicle.VIN = this.savedVehicles[index].VIN;
vehicle.ModelYear = this.savedVehicles[index].ModelYear;
vehicle.Make = this.savedVehicles[index].Make;
vehicle.Model = this.savedVehicles[index].Model;
this.savedVehicles[index] = vehicle;
localStorage.setItem("savedVehicles", JSON.stringify(this.savedVehicles));
this.alert = true;
this.alertColor = "green";
this.alertMessage = `${vehicle.VIN} updated`;
// hope to collapse all expansion panels
},
|
[
"\nExpansion panels can be controlled externally by modifying the\nv-model. Its value corresponds to a zero-based index of the currently\nopened expansion panel content. If multiple props are used then it is an\narray containing the indices of the open items.\n\n\nTo control the opening and closing status of multiple panels\nhttps://codepen.io/pen?&editors=101\n\nIf need to control only a single expansion panel then use this-\n\n\n<template>\n <v-expansion-panels v-model=\"panel\">\n // any code here\n </v-expansion-panels>\n <button @click=\"closePanel()\">Close</button>\n</template>\n<script>\nexport default {\n data() {\n return {\n panel: 0 // This means should open by default\n }\n },\n methods: {\n closePanel() {\n this.panel = null; // null is to close the panel\n }\n }\n}\n</script>\n\n"
] |
[
1
] |
[] |
[] |
[
"javascript",
"vue.js",
"vuejs2",
"vuetify.js"
] |
stackoverflow_0074668384_javascript_vue.js_vuejs2_vuetify.js.txt
|
Q:
How to hide a specific indicator in other timeframes?
s2 = request.security(syminfo.tickerid, tfD2, outD2, gaps=barmerge.gaps_on)
plot(s2, title="Daily 20 EMA", color=color.purple,linewidth=2)
I want to display this only on "Daily" TF, in weekly, monthly or lower than Daily TF, I want to hide this or not plot it at all. Can I do it via script?
I have tried using timeframe.isdaily on plot stmt but it didn't work.
A:
drawEMA2 = timeframe.isintraday and timeframe.isweekly and timeframe.ismonthly
s2 = request.security(syminfo.tickerid, tfD3, outD3, gaps=barmerge.gaps_on)
plot(series=drawEMA2 ? s2 :na, title="Daily 50 EMA",color=color.fuchsia,linewidth=2)
This works, just figured out after posting!
|
How to hide a specific indicator in other timeframes?
|
s2 = request.security(syminfo.tickerid, tfD2, outD2, gaps=barmerge.gaps_on)
plot(s2, title="Daily 20 EMA", color=color.purple,linewidth=2)
I want to display this only on "Daily" TF, in weekly, monthly or lower than Daily TF, I want to hide this or not plot it at all. Can I do it via script?
I have tried using timeframe.isdaily on plot stmt but it didn't work.
|
[
"drawEMA2 = timeframe.isintraday and timeframe.isweekly and timeframe.ismonthly\ns2 = request.security(syminfo.tickerid, tfD3, outD3, gaps=barmerge.gaps_on)\nplot(series=drawEMA2 ? s2 :na, title=\"Daily 50 EMA\",color=color.fuchsia,linewidth=2)\n\nThis works, just figured out after posting!\n"
] |
[
0
] |
[] |
[] |
[
"pine_script",
"time"
] |
stackoverflow_0074668358_pine_script_time.txt
|
Q:
How to update PATH in GitHub Actions
I'm trying to update the path variable in Linux VM in GitHub CI.
What I'm trying are:
export PATH="${PATH}:$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools/bin"
export PATH=$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools/bin:$PATH
But nothing seems to working, as when I'm trying to echo, it doesn't return me what I was expecting. What it lists is:
/home/runner/.local/bin
/opt/pipx_bin
/home/runner/.cargo/bin
/home/runner/.config/composer/vendor/bin
/usr/local/.ghcup/bin
/home/runner/.dotnet/tools
/snap/bin
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
/usr/games
/usr/local/games
/snap/bin
It should have contained (or at least something like this):
/usr/lib/android-sdk/cmdline-tools/cmdline-tools/bin
Full job details: https://github.com/maifeeulasad/unmukto/actions/runs/3590283087/jobs/6043518013
A:
It does get added to the $PATH, but you can't use it in subsequent steps because GitHub Actions isolates steps from one another. If you ran sdkmanager --version in the same step that you update the $PATH in, it would work. Use the GitHub Actions syntax for Adding a system path to append to $PATH and have it persist across the rest of steps in the job:
Prepends a directory to the system PATH variable and automatically makes it available to all subsequent actions in the current job; the currently running action cannot access the updated path variable.
An abbreviated version of your build.yml using $GITHUB_PATH:
name: build Android
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: 'Exporting android sdk'
run: echo "ANDROID_SDK_ROOT=/usr/lib/android-sdk" >> $GITHUB_ENV
- name: 'Download and extract android-cli tools'
run: |
curl https://dl.google.com/android/repository/commandlinetools-linux-9123335_latest.zip --output commandlinetools-linux-9123335_latest.zip
sudo mkdir /usr/lib/android-sdk/cmdline-tools
sudo unzip -o commandlinetools-linux-9123335_latest.zip -d /usr/lib/android-sdk/cmdline-tools
- name: 'Exporting android-cli (sdkmanager) ,'
run: echo "${{ env.ANDROID_SDK_ROOT }}/cmdline-tools/cmdline-tools/bin" >> $GITHUB_PATH
Also note how instead of exporting ANDROID_SDK_ROOT, it's added to the $GITHUB_ENV and accessed in a subsequent step with ${{ env.ANDROID_SDK_ROOT}}.
|
How to update PATH in GitHub Actions
|
I'm trying to update the path variable in Linux VM in GitHub CI.
What I'm trying are:
export PATH="${PATH}:$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools/bin"
export PATH=$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools/bin:$PATH
But nothing seems to working, as when I'm trying to echo, it doesn't return me what I was expecting. What it lists is:
/home/runner/.local/bin
/opt/pipx_bin
/home/runner/.cargo/bin
/home/runner/.config/composer/vendor/bin
/usr/local/.ghcup/bin
/home/runner/.dotnet/tools
/snap/bin
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
/usr/games
/usr/local/games
/snap/bin
It should have contained (or at least something like this):
/usr/lib/android-sdk/cmdline-tools/cmdline-tools/bin
Full job details: https://github.com/maifeeulasad/unmukto/actions/runs/3590283087/jobs/6043518013
|
[
"It does get added to the $PATH, but you can't use it in subsequent steps because GitHub Actions isolates steps from one another. If you ran sdkmanager --version in the same step that you update the $PATH in, it would work. Use the GitHub Actions syntax for Adding a system path to append to $PATH and have it persist across the rest of steps in the job:\n\nPrepends a directory to the system PATH variable and automatically makes it available to all subsequent actions in the current job; the currently running action cannot access the updated path variable.\n\nAn abbreviated version of your build.yml using $GITHUB_PATH:\nname: build Android\n\non:\n push:\n branches: [ main ]\n pull_request:\n branches: [ main ]\n\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - name: 'Exporting android sdk' \n run: echo \"ANDROID_SDK_ROOT=/usr/lib/android-sdk\" >> $GITHUB_ENV\n - name: 'Download and extract android-cli tools' \n run: |\n curl https://dl.google.com/android/repository/commandlinetools-linux-9123335_latest.zip --output commandlinetools-linux-9123335_latest.zip\n sudo mkdir /usr/lib/android-sdk/cmdline-tools\n sudo unzip -o commandlinetools-linux-9123335_latest.zip -d /usr/lib/android-sdk/cmdline-tools\n - name: 'Exporting android-cli (sdkmanager) ,' \n run: echo \"${{ env.ANDROID_SDK_ROOT }}/cmdline-tools/cmdline-tools/bin\" >> $GITHUB_PATH\n\nAlso note how instead of exporting ANDROID_SDK_ROOT, it's added to the $GITHUB_ENV and accessed in a subsequent step with ${{ env.ANDROID_SDK_ROOT}}.\n"
] |
[
1
] |
[] |
[] |
[
"github",
"github_actions",
"linux",
"ubuntu"
] |
stackoverflow_0074638139_github_github_actions_linux_ubuntu.txt
|
Q:
kubebuilder debug web-hooks locally
We have a kubebuilder controller which is working as expected, now we need to create a webhooks ,
I follow the tutorial
https://book.kubebuilder.io/reference/markers/webhook.html
and now I want to run & debug it locally,
however not sure what to do regard the certificate, is there a simple way to create it , any example will be very helpful.
BTW i've installed cert-manager and apply the following sample yaml but not sure what to do next ...
I need the simplest solution that I be able to run and debug the webhooks locally as Im doing already with the controller (Before using webhooks),
https://book.kubebuilder.io/cronjob-tutorial/running.html
Cert-manager
I've created the following inside my cluster
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: example-com
namespace: test
spec:
# Secret names are always required.
secretName: example-com-tls
# secretTemplate is optional. If set, these annotations and labels will be
# copied to the Secret named example-com-tls. These labels and annotations will
# be re-reconciled if the Certificate's secretTemplate changes. secretTemplate
# is also enforced, so relevant label and annotation changes on the Secret by a
# third party will be overwriten by cert-manager to match the secretTemplate.
secretTemplate:
annotations:
my-secret-annotation-1: "foo"
my-secret-annotation-2: "bar"
labels:
my-secret-label: foo
duration: 2160h # 90d
renewBefore: 360h # 15d
subject:
organizations:
- jetstack
# The use of the common name field has been deprecated since 2000 and is
# discouraged from being used.
commonName: example.com
isCA: false
privateKey:
algorithm: RSA
encoding: PKCS1
size: 2048
usages:
- server auth
- client auth
# At least one of a DNS Name, URI, or IP address is required.
dnsNames:
- example.com
- www.example.com
uris:
- spiffe://cluster.local/ns/sandbox/sa/example
ipAddresses:
- 192.168.0.5
# Issuer references are always required.
issuerRef:
name: ca-issuer
# We can reference ClusterIssuers by changing the kind here.
# The default value is Issuer (i.e. a locally namespaced Issuer)
kind: Issuer
# This is optional since cert-manager will default to this value however
# if you are using an external issuer, change this to that issuer group.
group: cert-manager.io
Still not sure how to sync it with the kubebuilder to work locally
as when I run the operator in debug mode I got the following error:
setup problem running manager {"error": "open /var/folders/vh/_418c55133sgjrwr7n0d7bl40000gn/T/k8s-webhook-server/serving-certs/tls.crt: no such file or directory"}
What I need is the simplest way to run webhooks locally
A:
Let me walk you through the process from the start.
create webhook like it's said in the cronJob tutorial - kubebuilder create webhook --group batch --version v1 --kind CronJob --defaulting --programmatic-validation . This will create webhooks for implementing defaulting logics and validating logics.
Implement the logics as instructed - Implementing defaulting/validating webhooks
Install cert-manager. I find the easiest way to install is via this commmand - kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.10.1/cert-manager.yaml
Edit the config/default/kustomization.yaml file by uncommenting everything that have [WEBHOOK] or [CERTMANAGER] in their comments. Do the same for config/crd/kustomization.yaml file also.
Build Your Image locally using - make docker-build IMG=<some-registry>/<project-name>:tag. Now you dont need to docker-push your image to remote repository. If you are using kind cluster, You can directly load your local image to your specified kind cluster:
kind load docker-image <your-image-name>:tag --name <your-kind-cluster-name>
Now you can deploy it to your cluster by - make deploy IMG=<some-registry>/<project-name>:tag.
You can also run cluster locally using make run command. But, that's a little tricky if you have enabled webooks. I would suggest you running your cluster using KIND cluster in this way. Here, you don't need to worry about injecting certificates. cert-manager will do that for you. You can check out the /config/certmanager folder to figure out how this is functioning.
A:
I assume you can use the openssl commands there:
First, generate a private key for the certificate:
openssl genrsa -out webhook.key 2048
Then, generate a certificate signing request (CSR) using the private key:
openssl req -new -key webhook.key -out webhook.csr
Next, create a self-signed certificate using the private key and CSR:
openssl x509 -req -in webhook.csr -signkey webhook.key -out webhook.crt
So finally you can use the webhook.crt and webhook.key files in your kubebuilder configuration to run and debug the webhook locally.
|
kubebuilder debug web-hooks locally
|
We have a kubebuilder controller which is working as expected, now we need to create a webhooks ,
I follow the tutorial
https://book.kubebuilder.io/reference/markers/webhook.html
and now I want to run & debug it locally,
however not sure what to do regard the certificate, is there a simple way to create it , any example will be very helpful.
BTW i've installed cert-manager and apply the following sample yaml but not sure what to do next ...
I need the simplest solution that I be able to run and debug the webhooks locally as Im doing already with the controller (Before using webhooks),
https://book.kubebuilder.io/cronjob-tutorial/running.html
Cert-manager
I've created the following inside my cluster
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: example-com
namespace: test
spec:
# Secret names are always required.
secretName: example-com-tls
# secretTemplate is optional. If set, these annotations and labels will be
# copied to the Secret named example-com-tls. These labels and annotations will
# be re-reconciled if the Certificate's secretTemplate changes. secretTemplate
# is also enforced, so relevant label and annotation changes on the Secret by a
# third party will be overwriten by cert-manager to match the secretTemplate.
secretTemplate:
annotations:
my-secret-annotation-1: "foo"
my-secret-annotation-2: "bar"
labels:
my-secret-label: foo
duration: 2160h # 90d
renewBefore: 360h # 15d
subject:
organizations:
- jetstack
# The use of the common name field has been deprecated since 2000 and is
# discouraged from being used.
commonName: example.com
isCA: false
privateKey:
algorithm: RSA
encoding: PKCS1
size: 2048
usages:
- server auth
- client auth
# At least one of a DNS Name, URI, or IP address is required.
dnsNames:
- example.com
- www.example.com
uris:
- spiffe://cluster.local/ns/sandbox/sa/example
ipAddresses:
- 192.168.0.5
# Issuer references are always required.
issuerRef:
name: ca-issuer
# We can reference ClusterIssuers by changing the kind here.
# The default value is Issuer (i.e. a locally namespaced Issuer)
kind: Issuer
# This is optional since cert-manager will default to this value however
# if you are using an external issuer, change this to that issuer group.
group: cert-manager.io
Still not sure how to sync it with the kubebuilder to work locally
as when I run the operator in debug mode I got the following error:
setup problem running manager {"error": "open /var/folders/vh/_418c55133sgjrwr7n0d7bl40000gn/T/k8s-webhook-server/serving-certs/tls.crt: no such file or directory"}
What I need is the simplest way to run webhooks locally
|
[
"Let me walk you through the process from the start.\n\ncreate webhook like it's said in the cronJob tutorial - kubebuilder create webhook --group batch --version v1 --kind CronJob --defaulting --programmatic-validation . This will create webhooks for implementing defaulting logics and validating logics.\n\nImplement the logics as instructed - Implementing defaulting/validating webhooks\n\n\n\nInstall cert-manager. I find the easiest way to install is via this commmand - kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.10.1/cert-manager.yaml\nEdit the config/default/kustomization.yaml file by uncommenting everything that have [WEBHOOK] or [CERTMANAGER] in their comments. Do the same for config/crd/kustomization.yaml file also.\nBuild Your Image locally using - make docker-build IMG=<some-registry>/<project-name>:tag. Now you dont need to docker-push your image to remote repository. If you are using kind cluster, You can directly load your local image to your specified kind cluster:\nkind load docker-image <your-image-name>:tag --name <your-kind-cluster-name>\nNow you can deploy it to your cluster by - make deploy IMG=<some-registry>/<project-name>:tag.\n\nYou can also run cluster locally using make run command. But, that's a little tricky if you have enabled webooks. I would suggest you running your cluster using KIND cluster in this way. Here, you don't need to worry about injecting certificates. cert-manager will do that for you. You can check out the /config/certmanager folder to figure out how this is functioning.\n",
"I assume you can use the openssl commands there:\nFirst, generate a private key for the certificate:\nopenssl genrsa -out webhook.key 2048\n\nThen, generate a certificate signing request (CSR) using the private key:\nopenssl req -new -key webhook.key -out webhook.csr\n\nNext, create a self-signed certificate using the private key and CSR:\nopenssl x509 -req -in webhook.csr -signkey webhook.key -out webhook.crt\n\nSo finally you can use the webhook.crt and webhook.key files in your kubebuilder configuration to run and debug the webhook locally.\n"
] |
[
0,
0
] |
[] |
[] |
[
"certificate",
"go",
"google_cloud_platform",
"kubebuilder",
"kubernetes"
] |
stackoverflow_0074581276_certificate_go_google_cloud_platform_kubebuilder_kubernetes.txt
|
Q:
Notifications permission pop-up will always appear in flutter app
I have been trying for days to get rid of Notifications Permission pop-up that appears in my Flutter app on first app run.
My code is the following:
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
check_internet_connection();
super.initState();
}
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Myapp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Text('test')
);
}
}
In general, I am using firebase and firebase messaging in my app.
While trying to disable the permission request, I wanted to see what causes the appearance of the pop-up window, hence I deleted almost everything (trial & error) from my main, leaving just the code above.
I am still getting the notifications permissions request on my iOS real device.
In my pubspec.yaml I have this: firebase_messaging: ^11.1.0
How can I disable the pop-up?
A:
I think I have found why I have this behaviour.
It is because of my AppDelegate.swift file where I have added this:
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
application.registerForRemoteNotifications()
By removing the requestAuthorization() I don't get the pop-up anymore.
|
Notifications permission pop-up will always appear in flutter app
|
I have been trying for days to get rid of Notifications Permission pop-up that appears in my Flutter app on first app run.
My code is the following:
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
check_internet_connection();
super.initState();
}
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Myapp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Text('test')
);
}
}
In general, I am using firebase and firebase messaging in my app.
While trying to disable the permission request, I wanted to see what causes the appearance of the pop-up window, hence I deleted almost everything (trial & error) from my main, leaving just the code above.
I am still getting the notifications permissions request on my iOS real device.
In my pubspec.yaml I have this: firebase_messaging: ^11.1.0
How can I disable the pop-up?
|
[
"I think I have found why I have this behaviour.\nIt is because of my AppDelegate.swift file where I have added this:\nUNUserNotificationCenter.current().delegate = self\n\nlet authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]\nUNUserNotificationCenter.current().requestAuthorization(\n options: authOptions,\n completionHandler: { _, _ in }\n)\n\napplication.registerForRemoteNotifications()\n\nBy removing the requestAuthorization() I don't get the pop-up anymore.\n"
] |
[
0
] |
[] |
[] |
[
"firebase",
"firebase_cloud_messaging",
"flutter"
] |
stackoverflow_0074668039_firebase_firebase_cloud_messaging_flutter.txt
|
Q:
How to scrape video url using puppeteer?
I'm trying to scrape video url of Instagram videos using puppeteer but unable to do it. it is returning null as a response
here is my code
async function getVideo(){
const launch = await puppeteer.launch({headless: true});
const page = await launch.newPage();
await page.goto('https://www.instagram.com/p/CfW5u5UJmny/?hl=en');
const video = await page.evaluate(() => {
return document.querySelector('video').src;
});
console.log(video); returns null
await launch.close();
}
example ur: https://instagram.fluh1-1.fna.fbcdn.net/v/t50.16885-16/290072800_730588251588660_5005285215058589375_n.mp4?efg=eyJ2ZW5jb2RlX3RhZyI6InZ0c192b2RfdXJsZ2VuLjcyMC5pZ3R2LmJhc2VsaW5lIiwicWVfZ3JvdXBzIjoiW1wiaWdfd2ViX2RlbGl2ZXJ5X3Z0c19vdGZcIl0ifQ&_nc_ht=instagram.fluh1-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=ROJWkaOqkQcAX_z-_Ls&edm=AP_V10EBAAAA&vs=440468611258459_2442386419&_nc_vs=HBksFQAYJEdPQW9TaEUwaURaVmQ1Z0NBTC0yRkV0aVdIWkZidlZCQUFBRhUAAsgBABUAGCRHTEdvVHhGMWFjUUpsMzhDQUZNT0c1cV8wT3c1YnZWQkFBQUYVAgLIAQAoABgAGwGIB3VzZV9vaWwBMRUAACaa%2BO%2FYnLPeQBUCKAJDMywXQCDdsi0OVgQYEmRhc2hfYmFzZWxpbmVfMV92MREAdewHAA%3D%3D&ccb=7-5&oh=00_AfCBrACQlXOqmbGSWRk_6Urv_fmHJUFDIt-8w6EO0_UcHQ&oe=638D6CBD&_nc_sid=4f375e
A:
You are loading the Instagram page. Since it takes a little while to load, I used setTimeout function to wait. Puppeteer also has many inbuilt functions you can use to obtain the src, such as the following.
async function getVideo(){
const launch = await puppeteer.launch({headless: false});
const page = await launch.newPage();
await page.goto('https://www.instagram.com/p/CfW5u5UJmny/?hl=en');
setTimeout(async () => {
let src = await page.$eval("video", n => n.getAttribute("src"))
console.log(src);
await launch.close();
}, 1000)
}
|
How to scrape video url using puppeteer?
|
I'm trying to scrape video url of Instagram videos using puppeteer but unable to do it. it is returning null as a response
here is my code
async function getVideo(){
const launch = await puppeteer.launch({headless: true});
const page = await launch.newPage();
await page.goto('https://www.instagram.com/p/CfW5u5UJmny/?hl=en');
const video = await page.evaluate(() => {
return document.querySelector('video').src;
});
console.log(video); returns null
await launch.close();
}
example ur: https://instagram.fluh1-1.fna.fbcdn.net/v/t50.16885-16/290072800_730588251588660_5005285215058589375_n.mp4?efg=eyJ2ZW5jb2RlX3RhZyI6InZ0c192b2RfdXJsZ2VuLjcyMC5pZ3R2LmJhc2VsaW5lIiwicWVfZ3JvdXBzIjoiW1wiaWdfd2ViX2RlbGl2ZXJ5X3Z0c19vdGZcIl0ifQ&_nc_ht=instagram.fluh1-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=ROJWkaOqkQcAX_z-_Ls&edm=AP_V10EBAAAA&vs=440468611258459_2442386419&_nc_vs=HBksFQAYJEdPQW9TaEUwaURaVmQ1Z0NBTC0yRkV0aVdIWkZidlZCQUFBRhUAAsgBABUAGCRHTEdvVHhGMWFjUUpsMzhDQUZNT0c1cV8wT3c1YnZWQkFBQUYVAgLIAQAoABgAGwGIB3VzZV9vaWwBMRUAACaa%2BO%2FYnLPeQBUCKAJDMywXQCDdsi0OVgQYEmRhc2hfYmFzZWxpbmVfMV92MREAdewHAA%3D%3D&ccb=7-5&oh=00_AfCBrACQlXOqmbGSWRk_6Urv_fmHJUFDIt-8w6EO0_UcHQ&oe=638D6CBD&_nc_sid=4f375e
|
[
"You are loading the Instagram page. Since it takes a little while to load, I used setTimeout function to wait. Puppeteer also has many inbuilt functions you can use to obtain the src, such as the following.\nasync function getVideo(){\n const launch = await puppeteer.launch({headless: false});\n const page = await launch.newPage();\n await page.goto('https://www.instagram.com/p/CfW5u5UJmny/?hl=en');\n setTimeout(async () => {\n let src = await page.$eval(\"video\", n => n.getAttribute(\"src\"))\n console.log(src);\n await launch.close();\n }, 1000)\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"node.js",
"puppeteer",
"web_scraping"
] |
stackoverflow_0074668394_javascript_node.js_puppeteer_web_scraping.txt
|
Q:
How can I get the proper factorial numbers of the user inputs?
I want to get the factorial of each number correctly that the user inputted. The factorial of the first input is correct but the factorial of the next inputs are incorrect.
This is what I get: the output of my code
The output/factorial should be like this: correct factorial of numbers
Here is my code:
public class Factor {
public static void main(String[] args) {
Scanner type = new Scanner(System.in);
int i, fact = 1;
System.out.println("<------ FACTORIAL CALCULATOR ------>");
while (true) {
System.out.print("Enter a positive integer: ");
int num = type.nextInt();
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
System.out.print(i);
if(i != num) {
System.out.print(" x ");
}
}
for (i = 1; i <= num; i++) {
fact = fact * i;
}
System.out.println("\nThe factorial of " + num + " is: " + fact);
}
else {
System.out.println("Invalid input! Program stopped!");
break;
}
}
}
}
A:
The answer is quite simple, you are never resetting your factorial variable after succeeding once.
Simply move the fact variable declaration into your while loop and it will work.
|
How can I get the proper factorial numbers of the user inputs?
|
I want to get the factorial of each number correctly that the user inputted. The factorial of the first input is correct but the factorial of the next inputs are incorrect.
This is what I get: the output of my code
The output/factorial should be like this: correct factorial of numbers
Here is my code:
public class Factor {
public static void main(String[] args) {
Scanner type = new Scanner(System.in);
int i, fact = 1;
System.out.println("<------ FACTORIAL CALCULATOR ------>");
while (true) {
System.out.print("Enter a positive integer: ");
int num = type.nextInt();
if (num > 0) {
System.out.print(num + "! = ");
for (i = 1; i <= num; i++) {
System.out.print(i);
if(i != num) {
System.out.print(" x ");
}
}
for (i = 1; i <= num; i++) {
fact = fact * i;
}
System.out.println("\nThe factorial of " + num + " is: " + fact);
}
else {
System.out.println("Invalid input! Program stopped!");
break;
}
}
}
}
|
[
"The answer is quite simple, you are never resetting your factorial variable after succeeding once.\nSimply move the fact variable declaration into your while loop and it will work.\n"
] |
[
1
] |
[] |
[] |
[
"java",
"loops",
"while_loop"
] |
stackoverflow_0074668453_java_loops_while_loop.txt
|
Q:
Why is SQL Server converting my decimal parameter 12.50 to 12.49999999
I am passing a decimal value from C# to a SQL Server stored procedure.
The parameter in the stored procedure is defined as @latitude decimal. Right before going into the stored procedure, the value is 25.631230
When running the profiler I can see that SQL Server sees the value as: 25.631229999999999
This is obviously a much different value when you are dealing with longitude/latitude.
SqlParameter lat = new SqlParameter { SqlDbType = System.Data.SqlDbType.Decimal, Value = 25.631230, ParameterName = "@latitude" };
cmd.Parameters.Add(lat);
cmd.CommandText = storedProcName;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.ExecuteReader()
Hope it's just a setting somewhere ;)
A:
Adding the precision in the stored procedure "decimal(18, 15)" was the correct solution. After I did that another error popped up that was confusing me but turns out it was unrelated to this specific question.
Thanks all that pointed me in the right direction.
|
Why is SQL Server converting my decimal parameter 12.50 to 12.49999999
|
I am passing a decimal value from C# to a SQL Server stored procedure.
The parameter in the stored procedure is defined as @latitude decimal. Right before going into the stored procedure, the value is 25.631230
When running the profiler I can see that SQL Server sees the value as: 25.631229999999999
This is obviously a much different value when you are dealing with longitude/latitude.
SqlParameter lat = new SqlParameter { SqlDbType = System.Data.SqlDbType.Decimal, Value = 25.631230, ParameterName = "@latitude" };
cmd.Parameters.Add(lat);
cmd.CommandText = storedProcName;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.ExecuteReader()
Hope it's just a setting somewhere ;)
|
[
"Adding the precision in the stored procedure \"decimal(18, 15)\" was the correct solution. After I did that another error popped up that was confusing me but turns out it was unrelated to this specific question.\nThanks all that pointed me in the right direction.\n"
] |
[
0
] |
[
"The issue you are experiencing is a common one when working with decimal values in programming. The cause of the problem is that decimal numbers are represented in binary, and many decimal values cannot be represented exactly in binary. As a result, some decimal values are approximated when they are converted to binary, which can lead to the kind of precision loss you are seeing.\nIn your case, it sounds like the value 25.631230 is being approximated when it is converted to binary, causing it to be represented as 25.631229999999999 in SQL Server. This is a common problem when working with decimal values, and it can be difficult to avoid entirely.\nOne way to address this issue is to use a higher-precision decimal data type, such as decimal(38, 18), which provides 38 digits of precision and allows for 18 digits to the right of the decimal point. This will allow for more accurate representation of decimal values, but it may not always be sufficient to avoid precision loss entirely.\nAnother approach you can try is to round the decimal value to a certain number of decimal places before passing it to the stored procedure. For example, you could round the value 25.631230 to 25.631231, which can be represented exactly in binary and will not suffer from precision loss. This will not always be possible, as rounding a value can sometimes introduce other issues, but it can be a useful technique in some cases.\nOverall, it is important to be aware of the limitations of decimal values when working with them in programming, and to take steps to avoid precision loss when necessary.\n"
] |
[
-1
] |
[
"decimal",
"parameter_passing",
"sql_server_2012",
"stored_procedures"
] |
stackoverflow_0074664022_decimal_parameter_passing_sql_server_2012_stored_procedures.txt
|
Q:
Combing "previous row" of same table and JOIN from different table in Sqlite
I have the following table
CREATE TABLE "shots" (
"player" INTEGER,
"tournament" TEXT,
"year" INTEGER,
"course" INTEGER,
"round" INTEGER,
"hole" INTEGER,
"shot" INTEGER,
"text" TEXT,
"distance" REAL,
"x" TEXT,
"y" TEXT,
"z" TEXT
);
With a sample of the data:
28237 470 2015 717 1 1 1 Shot 1 302 yds to left fairway, 257 yds to hole 10874 11451.596 10623.774 78.251
28237 470 2015 717 1 1 2 Shot 2 234 yds to right fairway, 71 ft to hole 8437 12150.454 10700.381 86.035
28237 470 2015 717 1 1 3 Shot 3 70 ft to green, 4 ft to hole 838 12215.728 10725.134 88.408
28237 470 2015 717 1 1 4 Shot 4 in the hole 46 12215.1 10729.1 88.371
28237 470 2015 717 1 2 1 Shot 1 199 yds to green, 29 ft to hole 7162 12776.03 10398.086 91.017
28237 470 2015 717 1 2 2 Shot 2 putt 26 ft 7 in., 2 ft 4 in. to hole 319 12749.444 10398.854 90.998
28237 470 2015 717 1 2 3 Shot 3 in the hole 28 12747.3 10397.6 91.027
28237 470 2015 717 1 3 1 Shot 1 296 yds to left intermediate, 204 yds to hole 10651 12596.857 9448.27 94.296
28237 470 2015 717 1 3 2 Shot 2 208 yds to green, 15 ft to hole 7478 12571.0 8825.648 94.673
28237 470 2015 717 1 3 3 Shot 3 putt 17 ft 6 in., 2 ft 5 in. to hole 210 12561.831 8840.539 94.362
I want to get for each shot the previous location (x, y, z). I wrote the below query.
SELECT cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot, cur.x, cur.y, cur.z, prev.x, prev.y, prev.z
FROM shots cur
INNER JOIN shots prev
ON (cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot) =
(prev.player, prev.tournament, prev.year, prev.course, prev.round, prev.hole, prev.shot - 1)
This query takes forever basically. How can I rewrite it to make it faster?
In addition, I need to make an adjustment for the first shot on a hole (shot = 1). This shot is made from tee_x, tee_y and tee_z. These values are available in table holes
CREATE TABLE "holes" (
"tournament" TEXT,
"year" INTEGER,
"course" INTEGER,
"round" INTEGER,
"hole" INTEGER,
"tee_x" TEXT,
"tee_y" TEXT,
"tee_z" TEXT
);
With data:
470 2015 717 1 1 11450 10625 78.25
470 2015 717 1 2 12750 10400 91
470 2015 717 1 3 2565 8840.5 95
Thanks
A:
First, you need a composite index to speed up the operation:
CREATE INDEX idx_shots ON shots (player, tournament, year, course, round, hole, shot);
With that index, your query should run faster:
SELECT cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot, cur.x, cur.y, cur.z,
prev.x AS prev_x, prev.y AS prev_y, prev.z AS prev_z
FROM shots cur LEFT JOIN shots prev
ON (cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot) =
(prev.player, prev.tournament, prev.year, prev.course, prev.round, prev.hole, prev.shot + 1);
The changes I made:
the join should be a LEFT join so that all rows are included and
not only the ones that have a previous row
-1 should be +1 because the previous row's shot is 1 less than the current row's shot
added aliases for the previous row's x, y and z
But, if your version of SQLite is 3.25.0+ it would be better to use window function LAG() instead of a self join:
SELECT *,
LAG(x) OVER w AS prev_x,
LAG(y) OVER w AS prev_y,
LAG(z) OVER w AS prev_z
FROM shots
WINDOW w AS (PARTITION BY player, tournament, year, course, round, hole ORDER BY shot);
See the demo (I include the query plan for both queries where you can see the use of the composite index).
|
Combing "previous row" of same table and JOIN from different table in Sqlite
|
I have the following table
CREATE TABLE "shots" (
"player" INTEGER,
"tournament" TEXT,
"year" INTEGER,
"course" INTEGER,
"round" INTEGER,
"hole" INTEGER,
"shot" INTEGER,
"text" TEXT,
"distance" REAL,
"x" TEXT,
"y" TEXT,
"z" TEXT
);
With a sample of the data:
28237 470 2015 717 1 1 1 Shot 1 302 yds to left fairway, 257 yds to hole 10874 11451.596 10623.774 78.251
28237 470 2015 717 1 1 2 Shot 2 234 yds to right fairway, 71 ft to hole 8437 12150.454 10700.381 86.035
28237 470 2015 717 1 1 3 Shot 3 70 ft to green, 4 ft to hole 838 12215.728 10725.134 88.408
28237 470 2015 717 1 1 4 Shot 4 in the hole 46 12215.1 10729.1 88.371
28237 470 2015 717 1 2 1 Shot 1 199 yds to green, 29 ft to hole 7162 12776.03 10398.086 91.017
28237 470 2015 717 1 2 2 Shot 2 putt 26 ft 7 in., 2 ft 4 in. to hole 319 12749.444 10398.854 90.998
28237 470 2015 717 1 2 3 Shot 3 in the hole 28 12747.3 10397.6 91.027
28237 470 2015 717 1 3 1 Shot 1 296 yds to left intermediate, 204 yds to hole 10651 12596.857 9448.27 94.296
28237 470 2015 717 1 3 2 Shot 2 208 yds to green, 15 ft to hole 7478 12571.0 8825.648 94.673
28237 470 2015 717 1 3 3 Shot 3 putt 17 ft 6 in., 2 ft 5 in. to hole 210 12561.831 8840.539 94.362
I want to get for each shot the previous location (x, y, z). I wrote the below query.
SELECT cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot, cur.x, cur.y, cur.z, prev.x, prev.y, prev.z
FROM shots cur
INNER JOIN shots prev
ON (cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot) =
(prev.player, prev.tournament, prev.year, prev.course, prev.round, prev.hole, prev.shot - 1)
This query takes forever basically. How can I rewrite it to make it faster?
In addition, I need to make an adjustment for the first shot on a hole (shot = 1). This shot is made from tee_x, tee_y and tee_z. These values are available in table holes
CREATE TABLE "holes" (
"tournament" TEXT,
"year" INTEGER,
"course" INTEGER,
"round" INTEGER,
"hole" INTEGER,
"tee_x" TEXT,
"tee_y" TEXT,
"tee_z" TEXT
);
With data:
470 2015 717 1 1 11450 10625 78.25
470 2015 717 1 2 12750 10400 91
470 2015 717 1 3 2565 8840.5 95
Thanks
|
[
"First, you need a composite index to speed up the operation:\nCREATE INDEX idx_shots ON shots (player, tournament, year, course, round, hole, shot);\n\nWith that index, your query should run faster:\nSELECT cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot, cur.x, cur.y, cur.z, \n prev.x AS prev_x, prev.y AS prev_y, prev.z AS prev_z\nFROM shots cur LEFT JOIN shots prev \nON (cur.player, cur.tournament, cur.year, cur.course, cur.round, cur.hole, cur.shot) =\n (prev.player, prev.tournament, prev.year, prev.course, prev.round, prev.hole, prev.shot + 1);\n\nThe changes I made:\n\nthe join should be a LEFT join so that all rows are included and\nnot only the ones that have a previous row\n-1 should be +1 because the previous row's shot is 1 less than the current row's shot\nadded aliases for the previous row's x, y and z\n\nBut, if your version of SQLite is 3.25.0+ it would be better to use window function LAG() instead of a self join:\nSELECT *,\n LAG(x) OVER w AS prev_x,\n LAG(y) OVER w AS prev_y,\n LAG(z) OVER w AS prev_z\nFROM shots\nWINDOW w AS (PARTITION BY player, tournament, year, course, round, hole ORDER BY shot);\n\nSee the demo (I include the query plan for both queries where you can see the use of the composite index).\n"
] |
[
1
] |
[] |
[] |
[
"join",
"left_join",
"sqlite",
"window_functions"
] |
stackoverflow_0074666920_join_left_join_sqlite_window_functions.txt
|
Q:
Perform an action when Firebase Notification is not received by the device
I am trying to check if a function or method is being invoked in the server and act accordingly.
I am creating a basic app that notifies people about their financial transactions. I am using Flutter for the app, NodeJS for the server side of things, Firebase Cloud Messaging for Push Notification and React in order to send the data. So far, I've been successful in sending the Notification and displaying a list of notification for the user when using the mobile application.
The whole system works something like this:
The message is composed and sent from the react website,
The website calls a POST request from the server to send a notification,
The POST request then calls the getMessaging() function from the Firebase API that sends the notification to that device
The mobile application listens for a notification using onMessage() as well as onBackgroundMessage(). When a notification is received it again calls the server to store some notification data to the database.
The reason I am storing the notification in the database after it is received by the device is so that I know the status of the message I've sent i.e. "delivered". Now, I am aiming to send an SMS to the device if the notification is not "delivered" after a certain period of time. However, looking at the workflow, sending the notification and storing notification are two complete separate methods and thus, I am out of ideas. Is there any way to know if a method/function is being invoked and act accordingly. Or should I take some other approach to this scenario? (If yes, could you give some ideas?)
A:
I am just trying to aid my future self in need.
Thanks GrahamD for providing me with some ideas. The process of how my code manages it is below:
sendNotification():
This is a POST method that sends notification to the mobile application as well as store the data from that notification to a database. When storing to database, I modify my data model to take two more fields:
status: with values like sent & delivered
messageID: unique ID for each message generated by uuid.
The action is still running with getMessaging.send().then() below.
updateNotificationStatus()
Instead of saving the notification data after being received by the application, I update just the status field using this function. Inside the Flutter app, whenever the application receives a message (onMessage or onBackgroundMessage), I call this function as a PUT method to update the status from sent to delivered by using the messageId that was sent with the notification.
getMessaging().send().then()
Inside the sendNotification(), the callback .then() calls another method after a set period of time to check the status of the messageId. If the status has been changed to delivered, no action is taken. However, if the status remains unchanged (i.e: sent), then I can code the action I want to perform.
The back and forth of function invocation is still a headache for me to explain as well as understand. Hopefully, this is understandable and can help out others looking for the answers.
|
Perform an action when Firebase Notification is not received by the device
|
I am trying to check if a function or method is being invoked in the server and act accordingly.
I am creating a basic app that notifies people about their financial transactions. I am using Flutter for the app, NodeJS for the server side of things, Firebase Cloud Messaging for Push Notification and React in order to send the data. So far, I've been successful in sending the Notification and displaying a list of notification for the user when using the mobile application.
The whole system works something like this:
The message is composed and sent from the react website,
The website calls a POST request from the server to send a notification,
The POST request then calls the getMessaging() function from the Firebase API that sends the notification to that device
The mobile application listens for a notification using onMessage() as well as onBackgroundMessage(). When a notification is received it again calls the server to store some notification data to the database.
The reason I am storing the notification in the database after it is received by the device is so that I know the status of the message I've sent i.e. "delivered". Now, I am aiming to send an SMS to the device if the notification is not "delivered" after a certain period of time. However, looking at the workflow, sending the notification and storing notification are two complete separate methods and thus, I am out of ideas. Is there any way to know if a method/function is being invoked and act accordingly. Or should I take some other approach to this scenario? (If yes, could you give some ideas?)
|
[
"I am just trying to aid my future self in need.\nThanks GrahamD for providing me with some ideas. The process of how my code manages it is below:\nsendNotification():\nThis is a POST method that sends notification to the mobile application as well as store the data from that notification to a database. When storing to database, I modify my data model to take two more fields:\n\nstatus: with values like sent & delivered\nmessageID: unique ID for each message generated by uuid.\n\nThe action is still running with getMessaging.send().then() below.\nupdateNotificationStatus()\nInstead of saving the notification data after being received by the application, I update just the status field using this function. Inside the Flutter app, whenever the application receives a message (onMessage or onBackgroundMessage), I call this function as a PUT method to update the status from sent to delivered by using the messageId that was sent with the notification.\ngetMessaging().send().then()\nInside the sendNotification(), the callback .then() calls another method after a set period of time to check the status of the messageId. If the status has been changed to delivered, no action is taken. However, if the status remains unchanged (i.e: sent), then I can code the action I want to perform.\nThe back and forth of function invocation is still a headache for me to explain as well as understand. Hopefully, this is understandable and can help out others looking for the answers.\n"
] |
[
0
] |
[] |
[] |
[
"firebase_cloud_messaging",
"flutter",
"mongodb",
"nodejs_server",
"push_notification"
] |
stackoverflow_0074664659_firebase_cloud_messaging_flutter_mongodb_nodejs_server_push_notification.txt
|
Q:
How to re-start my Hexo blog from existing github repository after no blogging for long time?
I created a blog using github page and Hexo around 5 years ago, it's hosted using github page and I published a few blogs. But in recent years I did not use it, the repository of my blog and my blog(xxx.github.io) are still there.
I want to restart my blog with it, now I only have the repository, how can I continue to add new blog to it?
I tried to git clone the repo to my local(a new computer), but...I don't know what's the next step?
A:
To continue adding new blog posts to your Hexo-powered GitHub Pages blog, you can follow these steps:
First, make sure you have the latest version of Hexo installed on
your local machine. You can do this by running the following
command:
npm install hexo-cli -g
This will install the Hexo command-line interface (CLI) globally on your system, which you can use to manage your Hexo blog.
Next, clone your blog's repository to your local machine using Git. This will download a copy of your blog's source code and content to your local machine. You can do this by running the following command:
git clone https://github.com/<your-username>/<your-username>.github.io.git
Replace with your actual GitHub username.
After cloning the repository, navigate to the directory where your blog's source code is located. This is where you will manage and create new blog posts.
Install the dependencies for your blog by running the following command:
npm install
This will install all the Node.js packages and libraries that your blog requires.
Once the dependencies are installed, you can create a new blog post by running the following command:
hexo new "<post-title>"
Replace with the actual title of your blog post. This will create a new Markdown file in the source/_posts directory, where you can write your blog post using Markdown syntax.
After writing your blog post, you can generate the HTML files for your blog by running the following command:
hexo generate
This will convert your Markdown files into HTML files, which you can then deploy to GitHub Pages.
Finally, you can deploy your blog to GitHub Pages by running the following command:
hexo deploy
This will push the generated HTML files to the gh-pages branch of your repository, which will automatically be published on GitHub Pages.
After following these steps, your new blog post should be live on your GitHub Pages blog. You can repeat this process to add more blog posts in the future.
|
How to re-start my Hexo blog from existing github repository after no blogging for long time?
|
I created a blog using github page and Hexo around 5 years ago, it's hosted using github page and I published a few blogs. But in recent years I did not use it, the repository of my blog and my blog(xxx.github.io) are still there.
I want to restart my blog with it, now I only have the repository, how can I continue to add new blog to it?
I tried to git clone the repo to my local(a new computer), but...I don't know what's the next step?
|
[
"To continue adding new blog posts to your Hexo-powered GitHub Pages blog, you can follow these steps:\nFirst, make sure you have the latest version of Hexo installed on\nyour local machine. You can do this by running the following\ncommand:\nnpm install hexo-cli -g\nThis will install the Hexo command-line interface (CLI) globally on your system, which you can use to manage your Hexo blog.\nNext, clone your blog's repository to your local machine using Git. This will download a copy of your blog's source code and content to your local machine. You can do this by running the following command:\ngit clone https://github.com/<your-username>/<your-username>.github.io.git\nReplace with your actual GitHub username.\nAfter cloning the repository, navigate to the directory where your blog's source code is located. This is where you will manage and create new blog posts.\nInstall the dependencies for your blog by running the following command:\nnpm install\nThis will install all the Node.js packages and libraries that your blog requires.\nOnce the dependencies are installed, you can create a new blog post by running the following command:\nhexo new \"<post-title>\"\nReplace with the actual title of your blog post. This will create a new Markdown file in the source/_posts directory, where you can write your blog post using Markdown syntax.\nAfter writing your blog post, you can generate the HTML files for your blog by running the following command:\nhexo generate\nThis will convert your Markdown files into HTML files, which you can then deploy to GitHub Pages.\nFinally, you can deploy your blog to GitHub Pages by running the following command:\nhexo deploy\nThis will push the generated HTML files to the gh-pages branch of your repository, which will automatically be published on GitHub Pages.\nAfter following these steps, your new blog post should be live on your GitHub Pages blog. You can repeat this process to add more blog posts in the future.\n"
] |
[
1
] |
[] |
[] |
[
"blogs",
"github_pages",
"hexo"
] |
stackoverflow_0074666878_blogs_github_pages_hexo.txt
|
Q:
Why my headers are ignored on compiling?
I'm trying to compile dahdi-linux on Centos 7.
I've installed gcc-9 and latest kernel (i need dahdi-echocan-oslec and standard kernel is too old)
This is the error
c/x86_64-redhat-linux/9/include/'/bin/gcc LDFLAGS='-I/opt/rh/devtoolset-9/root/usr/lib/gcc
make -C drivers/dahdi/firmware firmware-loaders
make[1]: Entering directory `/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/firmware'
make[1]: Leaving directory `/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/firmware'
make -C /lib/modules/6.0.11-1.el7.elrepo.x86_64/build M=/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi DAHDI_INCLUDE=/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/include DAHDI_MODULES_EXTRA=" " HOTPLUG_FIRMWARE=yes modules DAHDI_BUILD_ALL=m
make[1]: Entering directory `/usr/src/kernels/6.0.11-1.el7.elrepo.x86_64'
CC [M] /home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.o
/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.c:45:10: fatal error: stdbool.h: File o directory non esistente
45 | #include <stdbool.h>
| ^~~~~~~~~~~
compilation terminated.
make[4]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.o] Errore 1
make[3]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp] Errore 2
make[2]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi] Errore 2
make[1]: *** [__sub-make] Errore 2
make[1]: Leaving directory `/usr/src/kernels/6.0.11-1.el7.elrepo.x86_64'
make: *** [modules] Errore 2
the header requested is here
ls /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/stdbool.h
/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/stdbool.h
I have tried..
make CC=/opt/rh/devtoolset-9/root/bin/gcc LDFLAGS'-I/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/'
make CC=/opt/rh/devtoolset-9/root/bin/gcc CFLAGS'-I/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/'
make CC=/opt/rh/devtoolset-9/root/bin/gcc CFLAGS="-Wall -O2 -pipe -fPIE" LDFLAGS="-z now -pie -I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr" CPPFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
and also
export CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
export CPPLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
export LDFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
then
make CC...
and also
export EXTRA_CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
make CC=/opt/rh/devtoolset-9/root/bin/gcc EXTRA_CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
but fail
A:
Solution found.
On new kernels to compile dahdi we need some patches, one is that for latest dahdi "14-dahdi-do-not-use-stdbool.h-in-kernel-modules.patch" you can found on Debian dahdi package sources.
|
Why my headers are ignored on compiling?
|
I'm trying to compile dahdi-linux on Centos 7.
I've installed gcc-9 and latest kernel (i need dahdi-echocan-oslec and standard kernel is too old)
This is the error
c/x86_64-redhat-linux/9/include/'/bin/gcc LDFLAGS='-I/opt/rh/devtoolset-9/root/usr/lib/gcc
make -C drivers/dahdi/firmware firmware-loaders
make[1]: Entering directory `/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/firmware'
make[1]: Leaving directory `/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/firmware'
make -C /lib/modules/6.0.11-1.el7.elrepo.x86_64/build M=/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi DAHDI_INCLUDE=/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/include DAHDI_MODULES_EXTRA=" " HOTPLUG_FIRMWARE=yes modules DAHDI_BUILD_ALL=m
make[1]: Entering directory `/usr/src/kernels/6.0.11-1.el7.elrepo.x86_64'
CC [M] /home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.o
/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.c:45:10: fatal error: stdbool.h: File o directory non esistente
45 | #include <stdbool.h>
| ^~~~~~~~~~~
compilation terminated.
make[4]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp/base.o] Errore 1
make[3]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi/wct4xxp] Errore 2
make[2]: *** [/home/user/rpmbuild/BUILD/dahdi-linux-20221203git/drivers/dahdi] Errore 2
make[1]: *** [__sub-make] Errore 2
make[1]: Leaving directory `/usr/src/kernels/6.0.11-1.el7.elrepo.x86_64'
make: *** [modules] Errore 2
the header requested is here
ls /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/stdbool.h
/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/stdbool.h
I have tried..
make CC=/opt/rh/devtoolset-9/root/bin/gcc LDFLAGS'-I/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/'
make CC=/opt/rh/devtoolset-9/root/bin/gcc CFLAGS'-I/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/include/'
make CC=/opt/rh/devtoolset-9/root/bin/gcc CFLAGS="-Wall -O2 -pipe -fPIE" LDFLAGS="-z now -pie -I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr" CPPFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
and also
export CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
export CPPLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
export LDFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
then
make CC...
and also
export EXTRA_CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
make CC=/opt/rh/devtoolset-9/root/bin/gcc EXTRA_CFLAGS="-I/opt/rh/devtoolset-9/root/usr/include/c++/9/tr"
but fail
|
[
"Solution found.\nOn new kernels to compile dahdi we need some patches, one is that for latest dahdi \"14-dahdi-do-not-use-stdbool.h-in-kernel-modules.patch\" you can found on Debian dahdi package sources.\n"
] |
[
0
] |
[] |
[] |
[
"gcc"
] |
stackoverflow_0074668408_gcc.txt
|
Q:
Is there a Digital Signage Program with Cached Credentials for Browser View?
I'm trying to find a digital signage program that can display an ongoing powerpoint on half the screen, and a live view of Outlook calendars on the other half. We want a certain group of employees to be able to see what they're doing for the day, and for them to be able to see changes happen.
Here's an example of how Outlook Calendar would be displayed
I was looking into PiSignage, as well as Galaxy Signage. However, none of them seem to have the capability of displaying the calendar properly, or they don't store credentials.
I was looking for something relatively simple to use for the users that will be updating the content of the rotating powerpoint.
Having that live view of Outlook is mainly what is desired though.
A:
There is no "relatively simply" solution, as you need a combination of features and some web-app developing.
PowerPoint:
I do not know any Digital Signage Player who plays PowerPoint files directly. In most cases, you have to convert ppt as videos or images.
Outlook Calendar with credentials:
This is possible via digital signage widgets.
Widgets are websites/web-app which are run locally on the player. This way, you can handle credentials and use every web API/service you want via ordinary HTML and JavaScript. In your case, it is not complex, but you will need some JS-developing.
Multiple Zones:
You require a software which can display these widgets and websites in multiple zones.
The player hardware from IAdea which base on W3C-SMIL language, features multiple zones and widgets. As an alternative, there is an open source SMIL-Player developed by me.
You can use both player solutions on any SMIL compatible SaaS. IAdea includes a Windows software for creating playlists. You can also create SMIL-indexes manually like HTML or XML.
|
Is there a Digital Signage Program with Cached Credentials for Browser View?
|
I'm trying to find a digital signage program that can display an ongoing powerpoint on half the screen, and a live view of Outlook calendars on the other half. We want a certain group of employees to be able to see what they're doing for the day, and for them to be able to see changes happen.
Here's an example of how Outlook Calendar would be displayed
I was looking into PiSignage, as well as Galaxy Signage. However, none of them seem to have the capability of displaying the calendar properly, or they don't store credentials.
I was looking for something relatively simple to use for the users that will be updating the content of the rotating powerpoint.
Having that live view of Outlook is mainly what is desired though.
|
[
"There is no \"relatively simply\" solution, as you need a combination of features and some web-app developing.\nPowerPoint:\nI do not know any Digital Signage Player who plays PowerPoint files directly. In most cases, you have to convert ppt as videos or images.\nOutlook Calendar with credentials:\nThis is possible via digital signage widgets.\nWidgets are websites/web-app which are run locally on the player. This way, you can handle credentials and use every web API/service you want via ordinary HTML and JavaScript. In your case, it is not complex, but you will need some JS-developing.\nMultiple Zones:\nYou require a software which can display these widgets and websites in multiple zones.\nThe player hardware from IAdea which base on W3C-SMIL language, features multiple zones and widgets. As an alternative, there is an open source SMIL-Player developed by me.\nYou can use both player solutions on any SMIL compatible SaaS. IAdea includes a Windows software for creating playlists. You can also create SMIL-indexes manually like HTML or XML.\n"
] |
[
0
] |
[] |
[] |
[
"display",
"web_services"
] |
stackoverflow_0073282386_display_web_services.txt
|
Q:
django rest framework translation does not work for me
I tried django rest framework internationalization.
doc drf internationalization
From official drf documentation a set this code in settings.py
from django.utils.translation import gettext_lazy as _
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
LANGUAGE_CODE = "it"
LANGUAGES = (
('en', _('English')),
('it', _('Italian')),
('fr', _('French')),
('es', _('Spanish')),
)
TIME_ZONE = 'UTC'
USE_I18N = True
but when I try out POST api rest
curl -X 'POST' \
'http://172.18.0.1:7000/appjud/api/v1/reset-password/' \
-H 'accept: application/json' \
-H 'Authorization: Token 014cb7982f31767a8ce07c9f216653d4674baeaf' \
-H 'Content-Type: application/json' \
-d '{
"new_password": "",
"confirm_password": ""
}'
Response body
[
{
"newpassword": [
"This field is required."
],
"confirmpassword": [
"This field is required."
]
}
]
Response headers
allow: POST,OPTIONS
content-language: en
content-length: 91
content-type: application/json
cross-origin-opener-policy: same-origin
date: Sat,03 Dec 2022 16:14:16 GMT
referrer-policy: same-origin
server: WSGIServer/0.2 CPython/3.9.15
vary: Accept,Accept-Language,Origin
x-content-type-options: nosniff
x-frame-options: DENY
UPDATE
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
As we can see it print "This field is required." but I would like "Questo campo è obbligatorio."
What Does I miss in config settings.py file?
A:
Looks like you added LocaleMiddleware to the end of middlewares list. But order is matter here. From the docs:
Because middleware order matters, follow these guidelines:
Make sure it’s one of the first middleware installed.
It should come after SessionMiddleware, because LocaleMiddleware makes use of session data. And it should come before CommonMiddleware
because CommonMiddleware needs an activated language in order to
resolve the requested URL.
If you use CacheMiddleware, put LocaleMiddleware after it.
Try to change order according to this note.
|
django rest framework translation does not work for me
|
I tried django rest framework internationalization.
doc drf internationalization
From official drf documentation a set this code in settings.py
from django.utils.translation import gettext_lazy as _
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
LANGUAGE_CODE = "it"
LANGUAGES = (
('en', _('English')),
('it', _('Italian')),
('fr', _('French')),
('es', _('Spanish')),
)
TIME_ZONE = 'UTC'
USE_I18N = True
but when I try out POST api rest
curl -X 'POST' \
'http://172.18.0.1:7000/appjud/api/v1/reset-password/' \
-H 'accept: application/json' \
-H 'Authorization: Token 014cb7982f31767a8ce07c9f216653d4674baeaf' \
-H 'Content-Type: application/json' \
-d '{
"new_password": "",
"confirm_password": ""
}'
Response body
[
{
"newpassword": [
"This field is required."
],
"confirmpassword": [
"This field is required."
]
}
]
Response headers
allow: POST,OPTIONS
content-language: en
content-length: 91
content-type: application/json
cross-origin-opener-policy: same-origin
date: Sat,03 Dec 2022 16:14:16 GMT
referrer-policy: same-origin
server: WSGIServer/0.2 CPython/3.9.15
vary: Accept,Accept-Language,Origin
x-content-type-options: nosniff
x-frame-options: DENY
UPDATE
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
As we can see it print "This field is required." but I would like "Questo campo è obbligatorio."
What Does I miss in config settings.py file?
|
[
"Looks like you added LocaleMiddleware to the end of middlewares list. But order is matter here. From the docs:\n\nBecause middleware order matters, follow these guidelines:\nMake sure it’s one of the first middleware installed.\nIt should come after SessionMiddleware, because LocaleMiddleware makes use of session data. And it should come before CommonMiddleware\nbecause CommonMiddleware needs an activated language in order to\nresolve the requested URL.\nIf you use CacheMiddleware, put LocaleMiddleware after it.\n\nTry to change order according to this note.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_rest_framework",
"internationalization",
"python"
] |
stackoverflow_0074668527_django_django_rest_framework_internationalization_python.txt
|
Q:
Automatic native and managed DLLs extracting from Nuget Package
This is driving me crazy for several months now and I'm still not able to achieve it. My managed libraries are extracted from the Nuget package but not the natives ones.
We have a bunch of managed and native libraries provided by another company.
We have both x86 and x64 version of them. In order to use them in an ASP.NET Core project I have to create an Nuget Package.
My architecture is:
an ASP.NET Core class library that I changed to target full .NET Framework only. This project references my Nuget Package
an ASP.NET Core website also targeting full .NET Framework and referencing the class library
Of course, at the end, I need my native libraries being extracted to the proper runtime folder of the Website (eg: \bin\Debug\net461\win7-x64).
For the moment my solution was:
to put the native libs inside the build folder
create a targets file that copies them to the $(OutputPath) (which is even not the runtime folder)
add some MsBuild commands to the xproj of my website to get the targets file in my $(USERPROFILE)\.nuget\packages\ folder and execute it
copy by hand the native DLLs now extracted in bin folder to the runtime one
I've tried to copy them directly to the runtime folder using some configuration in project.json (I honestly don't remember all the things I've tried for this part) but this was always failing. Also even though I specified SkipUnchangedFiles="true" in my targets file, this is just ignored and my DLLs are copied to my bin folder during each build.
This is an heavy process just to achieve a DLLs extracting, now I really want to get rid of all that MsBuild and get a much simpler solution.
I know with newer versions of Nuget, it's now capable of extracting them natively without any help of adding custom MsBuild commands. As written here, C# projects don't even need a targets file
Next, C++ and JavaScript projects that might consume your NuGet package need a .targets file to identify the necessary assembly and winmd files. (C# and Visual Basic projects do this automatically.)
I kept a tab opened in my browser for several month (original link) and realize this resource has been recently removed from Nuget website. It was explaining how to use the runtimes folder to automatically extract natives DLLs. However I've never been able to get a successful result as it was explained. Now this page has been deleted and replaced by this one with so few explanations and not talking about this runtimes folder at all.
My guess is that I should use runtimes folder for native DLLs and the lib one for managed but I'm not 100% sure of that. (also should I use the build folder?)
I've tried several things (I can't recall number of attempts, as I said several months of headache...) like this architecture (I don't understand here what's the point of having build/native and also natives folders under runtimes)
I also tried to use the .NET framework version structure as described here for my managed libraries.
This seems to be also part of the solution
The architecture is ignored by the compiler when creating an assembly reference. It's a load time concept. The loader will prefer an architecture specific reference if it exists.
One trick you can use to produce an AnyCPU assembly is to use corflags to remove the architecture from your x86 assembly. EG: corflags /32BITREQ- MySDK.dll. Corflags is part of the .NET SDK and can be found in VS's developer command prompt.
That's what I did, converting both x86 and x64 DLLs to AnyCPU (don't know if it does something for x64 DLLs but I didn't get errors) and then tried several different architectures in my Nuget package but still not working.
The default runtime without any entry in project.json is win7-x64, so I decided to explicitly specify it just in case
"runtimes": {
"win7-x64": {}
},
So this is the Runtime Identifier I'm using for all my attempts in my Nuget package. However I don't care about the windows version. I would actually prefer having win-x86 or win-x64 but it seems to be an invalid value according to this page
Windows RIDs
Windows 7 / Windows Server 2008 R2
win7-x64
win7-x86
Windows 8 / Windows Server 2012
win8-x64
win8-x86
win8-arm
Windows 8.1 / Windows Server 2012 R2
win81-x64
win81-x86
win81-arm
Windows 10 / Windows Server 2016
win10-x64
win10-x86
win10-arm
win10-arm64
However this Github source is describing more RID so which source is right?
As you can see, there is so many mysteries here, mostly because of the lack of documentation or even contradictions between different docs.
If at least I could have a working example, then I could perform my tests to answer other questions like trying generic win-x64 RID or see if I can include once my managed libs whatever the .NET Framework version.
Please pay attention to my special context: I have an ASP.NET Core project targeting the full .NET Framework
Thanks for your answers, I'm desperate to get this simple thing working.
A:
I will try to explain all the pain and solutions I've been through as detailed as possible. In my example I use simple text files AAA86.txt, AAA64.txt and AAAany.txt instead of native DLLs to simply demonstrate the extraction process.
First thing you need to know:
If you try to mix the native NuGet's architecture with a lib folder containing some managed libraries, IT WILL NOT WORK
In that case your managed DLLs will be copied to your project's output directory but NOT your native ones.
Thanks to Jon Skeet who pointed me in the good direction, advising me to take a look at the Grpc.Core package. The trick is to create a targets file that will handle the DLL extraction.
Your targets file should contain something like this
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition=" '$(Platform)' == 'x64' ">
<Content Include="$(MSBuildThisFileDirectory)..\runtimes\win-x64\native\AAA64.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>AAA64.txt</Link>
</Content>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'x86' OR '$(Platform)' == 'AnyCPU' ">
<Content Include="$(MSBuildThisFileDirectory)..\runtimes\win-x86\native\AAA86.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>AAA86.txt</Link>
</Content>
</ItemGroup>
</Project>
Also make sure your .targets file is named the same as your AssemblyName. So if the name of your assembly is DemoPackage, your targets file should be named DemoPackage.targets. Otherwise, the .targets file might not be applied when referencing the package in another project.
Now few other things you need to know:
1) Visual Studio doesn't care at all about the settings you choose, it will always use a dummy RID. (In my case I always end up with a win7-x64 folder even though I'm on Windows 10...)
2) The platform setting in your project.json is also totally useless
{
"buildOptions": {
"platform": "x64"
}
}
3) In the runtimes settings if you set only win and/or win-x64
"runtimes": {
"win": {},
"win-x64": {}
}
Visual Studio will instead use win7-x64. But if you add win10-x64 while you are on a Windows 10 machine then this will be used
4) If you compile your application with a generic RID like this
dotnet build -c debug -r win
Then your targets file will receive the architecture of your machine (x64 in my case) instead of AnyCPU as I was expecting
5) With only native libraries without any managed ones, the extraction will work without a target file if you follow the architecture runtimes/RID/native
6) With only native libraries in my package, the chosen RID will always be win-x64 building with Visual Studio as I told you the runtime folder always created is win7-x64, no matter the configuration I select. If I only had one single win RID in my package then it would successfully be picked.
EDIT:
As a last useful note, when working on such tasks, you might find it convenient to print out the current directory from which your .targets file is being executed like this
<Target Name="TestMessage" AfterTargets="Build" >
<Message Text="***********************************************************" Importance="high"/>
<Message Text="$(MSBuildThisFileDirectory)" Importance="high"/>
<Message Text="***********************************************************" Importance="high"/>
</Target>
Your directory will be printed out in the Build output in Visual Studio
A:
The problem of native DLLs not being copied to the output directory is gone nowadays when you use dotnet restore instead of nuget.exe restore.
The issue was solved in my case when using specifically dotnet restore --runtime win-x64 <path_to_the_solution.sln>.
A:
As a continuation to the answer of @Jérôme MEVEL,
GeneratePathProperty is a new feature which is available with NuGet 5.0 or above and with Visual Studio 2019 16.0 or above.
Using this feature, you can know the exact path of the installed package in the consumer of the package.
If the package is named Mypackage.ID, then you can refer to its path as: $(PkgMypackage_id) with replacing dot '.' with underscore '_'.
In the package consumer
Add GeneratePathProperty="true" attribute to the PackageReference
<ItemGroup>
<PackageReference Include="Some.Package" Version="1.0.0" GeneratePathProperty="true" />
</ItemGroup>
In the package creator:
Path of the package can be reached as given below:
<ItemGroup Condition=" '$(Platform)' == 'x64' ">
<Content Include="$(PkgMyPackage_Id)\runtimes\win-x64\native\AAA64.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>AAA64.txt</Link>
</Content>
</ItemGroup>
Notice the path is: "$(PkgMyPackage_Id)\runtimes\win-x64\native\AAA64.txt
For more details read: GeneratePathProperty
|
Automatic native and managed DLLs extracting from Nuget Package
|
This is driving me crazy for several months now and I'm still not able to achieve it. My managed libraries are extracted from the Nuget package but not the natives ones.
We have a bunch of managed and native libraries provided by another company.
We have both x86 and x64 version of them. In order to use them in an ASP.NET Core project I have to create an Nuget Package.
My architecture is:
an ASP.NET Core class library that I changed to target full .NET Framework only. This project references my Nuget Package
an ASP.NET Core website also targeting full .NET Framework and referencing the class library
Of course, at the end, I need my native libraries being extracted to the proper runtime folder of the Website (eg: \bin\Debug\net461\win7-x64).
For the moment my solution was:
to put the native libs inside the build folder
create a targets file that copies them to the $(OutputPath) (which is even not the runtime folder)
add some MsBuild commands to the xproj of my website to get the targets file in my $(USERPROFILE)\.nuget\packages\ folder and execute it
copy by hand the native DLLs now extracted in bin folder to the runtime one
I've tried to copy them directly to the runtime folder using some configuration in project.json (I honestly don't remember all the things I've tried for this part) but this was always failing. Also even though I specified SkipUnchangedFiles="true" in my targets file, this is just ignored and my DLLs are copied to my bin folder during each build.
This is an heavy process just to achieve a DLLs extracting, now I really want to get rid of all that MsBuild and get a much simpler solution.
I know with newer versions of Nuget, it's now capable of extracting them natively without any help of adding custom MsBuild commands. As written here, C# projects don't even need a targets file
Next, C++ and JavaScript projects that might consume your NuGet package need a .targets file to identify the necessary assembly and winmd files. (C# and Visual Basic projects do this automatically.)
I kept a tab opened in my browser for several month (original link) and realize this resource has been recently removed from Nuget website. It was explaining how to use the runtimes folder to automatically extract natives DLLs. However I've never been able to get a successful result as it was explained. Now this page has been deleted and replaced by this one with so few explanations and not talking about this runtimes folder at all.
My guess is that I should use runtimes folder for native DLLs and the lib one for managed but I'm not 100% sure of that. (also should I use the build folder?)
I've tried several things (I can't recall number of attempts, as I said several months of headache...) like this architecture (I don't understand here what's the point of having build/native and also natives folders under runtimes)
I also tried to use the .NET framework version structure as described here for my managed libraries.
This seems to be also part of the solution
The architecture is ignored by the compiler when creating an assembly reference. It's a load time concept. The loader will prefer an architecture specific reference if it exists.
One trick you can use to produce an AnyCPU assembly is to use corflags to remove the architecture from your x86 assembly. EG: corflags /32BITREQ- MySDK.dll. Corflags is part of the .NET SDK and can be found in VS's developer command prompt.
That's what I did, converting both x86 and x64 DLLs to AnyCPU (don't know if it does something for x64 DLLs but I didn't get errors) and then tried several different architectures in my Nuget package but still not working.
The default runtime without any entry in project.json is win7-x64, so I decided to explicitly specify it just in case
"runtimes": {
"win7-x64": {}
},
So this is the Runtime Identifier I'm using for all my attempts in my Nuget package. However I don't care about the windows version. I would actually prefer having win-x86 or win-x64 but it seems to be an invalid value according to this page
Windows RIDs
Windows 7 / Windows Server 2008 R2
win7-x64
win7-x86
Windows 8 / Windows Server 2012
win8-x64
win8-x86
win8-arm
Windows 8.1 / Windows Server 2012 R2
win81-x64
win81-x86
win81-arm
Windows 10 / Windows Server 2016
win10-x64
win10-x86
win10-arm
win10-arm64
However this Github source is describing more RID so which source is right?
As you can see, there is so many mysteries here, mostly because of the lack of documentation or even contradictions between different docs.
If at least I could have a working example, then I could perform my tests to answer other questions like trying generic win-x64 RID or see if I can include once my managed libs whatever the .NET Framework version.
Please pay attention to my special context: I have an ASP.NET Core project targeting the full .NET Framework
Thanks for your answers, I'm desperate to get this simple thing working.
|
[
"I will try to explain all the pain and solutions I've been through as detailed as possible. In my example I use simple text files AAA86.txt, AAA64.txt and AAAany.txt instead of native DLLs to simply demonstrate the extraction process.\nFirst thing you need to know:\nIf you try to mix the native NuGet's architecture with a lib folder containing some managed libraries, IT WILL NOT WORK\n\nIn that case your managed DLLs will be copied to your project's output directory but NOT your native ones.\nThanks to Jon Skeet who pointed me in the good direction, advising me to take a look at the Grpc.Core package. The trick is to create a targets file that will handle the DLL extraction.\n\nYour targets file should contain something like this\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\n <ItemGroup Condition=\" '$(Platform)' == 'x64' \">\n <Content Include=\"$(MSBuildThisFileDirectory)..\\runtimes\\win-x64\\native\\AAA64.txt\">\n <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n <Link>AAA64.txt</Link>\n </Content>\n </ItemGroup>\n\n <ItemGroup Condition=\" '$(Platform)' == 'x86' OR '$(Platform)' == 'AnyCPU' \">\n <Content Include=\"$(MSBuildThisFileDirectory)..\\runtimes\\win-x86\\native\\AAA86.txt\">\n <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n <Link>AAA86.txt</Link>\n </Content>\n </ItemGroup>\n\n</Project>\n\nAlso make sure your .targets file is named the same as your AssemblyName. So if the name of your assembly is DemoPackage, your targets file should be named DemoPackage.targets. Otherwise, the .targets file might not be applied when referencing the package in another project.\n\nNow few other things you need to know:\n1) Visual Studio doesn't care at all about the settings you choose, it will always use a dummy RID. (In my case I always end up with a win7-x64 folder even though I'm on Windows 10...)\n\n2) The platform setting in your project.json is also totally useless\n{\n \"buildOptions\": {\n \"platform\": \"x64\"\n }\n}\n\n3) In the runtimes settings if you set only win and/or win-x64\n\"runtimes\": {\n \"win\": {},\n \"win-x64\": {}\n}\n\nVisual Studio will instead use win7-x64. But if you add win10-x64 while you are on a Windows 10 machine then this will be used\n4) If you compile your application with a generic RID like this\ndotnet build -c debug -r win\n\nThen your targets file will receive the architecture of your machine (x64 in my case) instead of AnyCPU as I was expecting\n5) With only native libraries without any managed ones, the extraction will work without a target file if you follow the architecture runtimes/RID/native\n6) With only native libraries in my package, the chosen RID will always be win-x64 building with Visual Studio as I told you the runtime folder always created is win7-x64, no matter the configuration I select. If I only had one single win RID in my package then it would successfully be picked.\nEDIT:\nAs a last useful note, when working on such tasks, you might find it convenient to print out the current directory from which your .targets file is being executed like this\n<Target Name=\"TestMessage\" AfterTargets=\"Build\" >\n <Message Text=\"***********************************************************\" Importance=\"high\"/>\n <Message Text=\"$(MSBuildThisFileDirectory)\" Importance=\"high\"/>\n <Message Text=\"***********************************************************\" Importance=\"high\"/>\n</Target>\n\nYour directory will be printed out in the Build output in Visual Studio\n",
"The problem of native DLLs not being copied to the output directory is gone nowadays when you use dotnet restore instead of nuget.exe restore.\nThe issue was solved in my case when using specifically dotnet restore --runtime win-x64 <path_to_the_solution.sln>.\n",
"As a continuation to the answer of @Jérôme MEVEL,\nGeneratePathProperty is a new feature which is available with NuGet 5.0 or above and with Visual Studio 2019 16.0 or above.\nUsing this feature, you can know the exact path of the installed package in the consumer of the package.\nIf the package is named Mypackage.ID, then you can refer to its path as: $(PkgMypackage_id) with replacing dot '.' with underscore '_'.\nIn the package consumer\nAdd GeneratePathProperty=\"true\" attribute to the PackageReference\n <ItemGroup>\n <PackageReference Include=\"Some.Package\" Version=\"1.0.0\" GeneratePathProperty=\"true\" />\n </ItemGroup>\n\nIn the package creator:\nPath of the package can be reached as given below:\n<ItemGroup Condition=\" '$(Platform)' == 'x64' \">\n <Content Include=\"$(PkgMyPackage_Id)\\runtimes\\win-x64\\native\\AAA64.txt\">\n <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n <Link>AAA64.txt</Link>\n </Content>\n </ItemGroup>\n\nNotice the path is: \"$(PkgMyPackage_Id)\\runtimes\\win-x64\\native\\AAA64.txt\nFor more details read: GeneratePathProperty\n\n"
] |
[
64,
0,
0
] |
[] |
[] |
[
".net_core",
"asp.net_core",
"c#",
"nuget",
"nuget_package"
] |
stackoverflow_0040104838_.net_core_asp.net_core_c#_nuget_nuget_package.txt
|
Q:
Spring boot: view unable to reach controller and having "400 BAD_REQUEST"
I try to do a java web application using:
SpringBoot
Mysql
JDBC
Design pattern: MVC, DAO
And Thymeleaf
And I'm trying to send a data from one of my views:
<td th:text="${Inj.sleepTest}"></td>
<td th:text="${Inj.sleepDose}"></td>
<td th:text="${Inj.nightTest}"></td>
<td th:text="${Inj.comment}"></td>
<td>
<form th:action="@{/delInj}" method="post">
<input type="hidden" id="id_injection" name="id_injection" value="${Inj.id_injection}">
<input class="btn btn-danger" type="submit" value="Submit">
</form>
</td>
to my controler:
@RequestMapping(value="/delInj", method= RequestMethod.POST)
public ModelAndView delinject(Injection inj){
ModelAndView mv = new ModelAndView();
mv.setViewName("userOnly/MyInjections");
int i = inj.getId_injection();
System.out.println(i);
return mv;
}
but i have the error "400 BAD_REQUEST - Bad Request" in my browser.
I tried with "@RequestMapping" and "PostMapping" but neither of them seams to work
A:
You have not added @RequestBody annotation to the method.
Like,
public ModelAndView delinject(@RequestBody Injection inj){
ModelAndView mv = new ModelAndView();
mv.setViewName("userOnly/MyInjections");
int i = inj.getId_injection();
System.out.println(i);
return mv;
}
A:
Bad Request In general means: that the structure of your Request Body does not match the JSON sent (may be Types, constraints, structure ...)
check the JSON you sent in the request and the expected Request Body "Model"
A:
I ran into this sort of an issue using Java record classes. In my case I wasn't passing all of the record fields. Two ways to fix this. 1. Pass all the fields
2. Add a constructor to the record that defaults optional fields to a default value. It sure would be nice if spring would enable you to turn on some response body or logging to let you know what actually was wrong with the request.
|
Spring boot: view unable to reach controller and having "400 BAD_REQUEST"
|
I try to do a java web application using:
SpringBoot
Mysql
JDBC
Design pattern: MVC, DAO
And Thymeleaf
And I'm trying to send a data from one of my views:
<td th:text="${Inj.sleepTest}"></td>
<td th:text="${Inj.sleepDose}"></td>
<td th:text="${Inj.nightTest}"></td>
<td th:text="${Inj.comment}"></td>
<td>
<form th:action="@{/delInj}" method="post">
<input type="hidden" id="id_injection" name="id_injection" value="${Inj.id_injection}">
<input class="btn btn-danger" type="submit" value="Submit">
</form>
</td>
to my controler:
@RequestMapping(value="/delInj", method= RequestMethod.POST)
public ModelAndView delinject(Injection inj){
ModelAndView mv = new ModelAndView();
mv.setViewName("userOnly/MyInjections");
int i = inj.getId_injection();
System.out.println(i);
return mv;
}
but i have the error "400 BAD_REQUEST - Bad Request" in my browser.
I tried with "@RequestMapping" and "PostMapping" but neither of them seams to work
|
[
"You have not added @RequestBody annotation to the method.\nLike,\npublic ModelAndView delinject(@RequestBody Injection inj){\n ModelAndView mv = new ModelAndView();\n mv.setViewName(\"userOnly/MyInjections\");\n int i = inj.getId_injection();\n System.out.println(i);\n\n return mv;\n\n}\n\n",
"Bad Request In general means: that the structure of your Request Body does not match the JSON sent (may be Types, constraints, structure ...)\ncheck the JSON you sent in the request and the expected Request Body \"Model\"\n",
"I ran into this sort of an issue using Java record classes. In my case I wasn't passing all of the record fields. Two ways to fix this. 1. Pass all the fields\n2. Add a constructor to the record that defaults optional fields to a default value. It sure would be nice if spring would enable you to turn on some response body or logging to let you know what actually was wrong with the request.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"spring",
"spring_boot",
"spring_mvc",
"thymeleaf"
] |
stackoverflow_0072603236_spring_spring_boot_spring_mvc_thymeleaf.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.