text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Will Rundeck kill scripts that it thinks are taking too long? I have a rundeck job with a script workflow step that has some simple commands, like the following.
echo "Some text"
pwd
ls -la
echo "Starting script now . . ."
# This script can take a while, maybe 20 to 30 minutes
php ./some_long_running_script.php arg1 arg2
echo "Finished!"
The issue I'm having is that when the job runs it kills this bash script after some time. It is usually after 8 to 10 minutes, but it is not consistent.
When it kills, the following is output to the log:
/var/lib/rundeck/tmp-jobs/372376-1775772-my-server-com-staging2-dispatch-script.tmp.sh: line 13: 15425 Killed
Where line 13 corresponds to the line number of the long running PHP script.
When I manually run the script on the same server node, I do not see this issue and the script runs to completion.
Does Rundeck kill jobs/scripts that it thinks are taking too long? The job level timeout is currently set to blank, which according to the documentation means no timeout.
A: I assume you didn't set timeout in your job definition.
There is another timeout setting in Rundeck SSH plguin. You can set it in different level(node,project,rundeck)
For node level:
ssh-connection-timeout connection timeout
ssh-command-timeout command timeout
The default value is 0 (no timeout)
The config file is framework.properties under rundeck base dir
Specifying SSH Timeout options
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45038624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add additional source files in Makefile I have a Makefile that I use to build executable on mac os x, using mpicc compiler, linking mkl_lapack.h library.
Now this Makefile is perfectly working, the only problem is that I don't know what to add if I want to compile Eigenvalues.c linking other .c files, if I want to link myfile.c where do I have to write it in Makefile?
MKL_INCLUDE=/opt/intel/mkl/include
MKLROOT=/opt/intel/mkl/lib
CC = mpicc
LD = mpicc
IFLAGS = -I$(MKL_INCLUDE)
CFLAGS = -Wall -O2 $(IFLAGS) -std=c99
LFLAGS = $(MKLROOT)/libmkl_intel_lp64.a $(MKLROOT)/libmkl_sequential.a $(MKLROOT)/libmkl_core.a -lpthread -lm
PROGRAMS = Eigenvalues
all: $(PROGRAMS)
Eigenvalues:
$(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)
%.o: %.c
@echo C compiling $@
$(CC) -c $(CFLAGS) -o $@ $<
clean:
rm -rf *.o $(PROGRAMS)
Eigenvalues: Eigenvalues.c
A: Simply have the Eigenvalues target depend on all the .o files (not the .c files, as you have!) that make up the application. Conventionally, the list of these objects is put in a variable:
PROGRAMS = Eigenvalues
Eigenvalues_OBJS = Eigenvalues.o foo.o bar.o #etc
all: $(PROGRAMS)
Eigenvalues: $(Eigenvalues_OBJS)
$(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)
# delete the "Eigenvalues: Eigenvalues.c" line,
# leave everything else as you have it
By the way, since you are using the standard variable names $(CC) and $(CFLAGS), you can leave out the %.o: %.c rule entirely; Make has a built-in rule that does the same thing.
A: Try this mate!
PROGRAMS = Eigenvalues
MKL_INCLUDE=/opt/intel/mkl/include
MKLROOT=/opt/intel/mkl/lib
IFLAGS = -I$(MKL_INCLUDE)
CFLAGS = -Wall -O2 $(IFLAGS) -std=c99
LFLAGS = $(MKLROOT)/libmkl_intel_lp64.a $(MKLROOT)/libmkl_sequential.a
$(MKLROOT)/libmkl_core.a -lpthread -lm
all: $(PROGRAMS).c
OBJS = \
Eigenvalues.o \
myfile.o\
##############################################################################
.SUFFIXES : .c .o
CC = mpicc
LD = mpicc
RM = rm -rf
$(PROGRAMS).c : $(OBJS)
$(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)
clean:
$(RM) *.o $(OBJS) $(PROGRAMS)
.c.o :
$(CC) -c $(CFLAGS) -o $@ $<
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8808368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: 1 error with an array "missing return statement" import javax.swing.JOptionPane;
public class Mate {
double suma (double x1,double x2)
{return x1+x2;}
double suma (double x1,double x2,double x3)
{return x1+x2+x3;}
double suma (int num [ ])
{int i=num.length;
int j=0;
int s=0;
for(j=0;j < i;j++)
{return (double)(s);}}} // here appears the error "missing return statement"
class AplicacionMate
{public static void main (String arg [])
{int n[ ]={5,4,3,2,1};
double r=0.0;
Mate m=new Mate ( );
r=m.suma(5,4);
JOptionPane.showMessageDialog(null,"La suma 1="+r);
r=m.suma(5,5,4);
JOptionPane.showMessageDialog(null,"La suma 2="+r);
r=m.suma(n);
JOptionPane.showMessageDialog(null,"La suma del arreglo="+r);
System.exit(0);}}
A: I took the liberty of formatting your code. This is how the method looks:
double suma (int num [ ]) {
int i=num.length;
int j=0;
int s=0;
for(j=0;j < i;j++) {
return (double)(s);
}
}
I suspect you attempted to write a sum-method, started with a stub, and didn't get it to compile. This is probably what you had in mind:
double suma (int num [ ]) {
int i=num.length;
int j=0;
int s=0;
for(j=0;j < i;j++) {
// here you probably want s += num[j];
}
return (double)(s);
}
The Java compiler can only deduce that a statement (such as a return) is reachable in very simple cases. (To illustrate: this method does compile. Still not very useful though!)
double suma (int num [ ]) {
int i=num.length;
int j=0;
int s=0;
for(j=0; true; j++) {
return (double)(s);
}
}
A: for(j=0;j < i;j++)
{return (double)(s);}}} // here appears the error "missing return statement"
There might be case when it doesn't get into loop so it won't return anything.
You need to make sure that it should return for all the case
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5164522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change the background color with a sticky element I would like to change the body color background on scroll with a sticky element.
body {
margin: 0;
background: lightblue;
}
.blue-container {
height: 70vh;
}
.blue {
height: 40vh;
position: sticky;
width: 70%;
top: 0;
background: blue;
margin: auto;
}
.pink {
height: 500px;
position: relative;
width: 70%;
margin-right: auto;
margin-left: auto;
background: pink;
text-align: center;
}
<div class='blue-container'>
<div class='blue'></div>
</div>
<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
Here's my jsFiddle to understand what I want.
A: You could calculate the empty space between blue div and pink div with a difference ($('.blue-container').height() - $('.blue').height()), then when the document scrolled till that misure you know that the pink div has touch the blue one.
$(function(){
$(window).scroll(function(){
var margin = $('.blue-container').height() - $('.blue').height();
if($(this).scrollTop()>=margin){
$("body").addClass("orange")
} else{
$("body").removeClass("orange")
}
});
});
body {
margin:0;
background:lightblue;}
.blue-container {
height:70vh;
}
.blue {
height:40vh;
position:sticky;
width:70%;
top:0;
background:blue;
margin:auto;
}
.pink {
height:500px;
position:relative;
width:70%;
margin-right:auto;
margin-left:auto;
background:pink;
text-align:center;
}
.orange{
background:orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='blue-container'>
<div class='blue'></div>
</div>
<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
A: I dont know if you can to that in pure CSS, but here is a vanillaJS solution:
*
*We trigger an event on scroll
*We check blue's bottom position and pink's top position
*If they are equals, we trigger the logic.
var blue = document.querySelector('.blue')
var pink = document.querySelector('.pink')
var onTouch = false;
//http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#event-type-scroll
function onScrollEventHandler(ev) {
var bottom = blue.getBoundingClientRect().bottom
var top = pink.getBoundingClientRect().top
// we set
if (bottom == top && !onTouch) {
document.body.style.backgroundColor = 'orange'
onTouch = true
}
// we reset
if (bottom != top && onTouch) {
document.body.style.backgroundColor = 'lightblue'
onTouch = false
}
}
var el=window;
if(el.addEventListener)
el.addEventListener('scroll', onScrollEventHandler, false);
else if (el.attachEvent)
el.attachEvent('onscroll', onScrollEventHandler);
body {
margin:0;
background:lightblue;}
.blue-container {
height:70vh;
}
.blue {
height:40vh;
position:sticky;
width:70%;
top:0;
background:blue;
margin:auto;
}
.pink {
height:500px;
position:relative;
width:70%;
margin-right:auto;
margin-left:auto;
background:pink;
text-align:center;
}
<div class='blue-container'>
<div class='blue'></div>
</div>
<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
This code is a work in progress. All inputs are welcome.
A: You can use an intersection observer to detect when enough .pink element is inside the viewport touch the .blue element:
const body = document.querySelector('body');
const blue = document.querySelector('.blue');
const target = document.querySelector('.pink');
const getHeight = (el) => el.getBoundingClientRect().height;
// get the threshold in which enough of the pink elment would be inside the viewport to touch the blue element
const threshold = (window.innerHeight - getHeight(blue)) / getHeight(target);
const options = {
rootMargin: '0px',
threshold
};
let prevRatio = 0;
const handleIntersect = (entries, observer) => {
entries.forEach(function(entry) {
// if going up (above the previous threshold & above the threshold
if (entry.intersectionRatio >= threshold && entry.intersectionRatio > prevRatio) {
body.classList.add('body--intersected');
} else {
body.classList.remove('body--intersected');
}
prevRatio = entry.intersectionRatio;
});
}
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(target);
body {
margin: 0;
background: lightblue;
}
.body--intersected {
background: pink;
}
.blue-container {
height: 70vh;
}
.blue {
height: 40vh;
position: sticky;
width: 70%;
top: 0;
background: blue;
margin: auto;
}
.pink {
height: 500px;
position: relative;
width: 70%;
margin-right: auto;
margin-left: auto;
background: pink;
text-align: center;
}
<div class='blue-container'>
<div class='blue'></div>
</div>
<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52569358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: blockinfile keeps adding the block I'd like to add a block of text to my ElasticSearch configuration using blockinfile, but every time I run my playbook, the block gets added to the file -- even when it already exists. This is a problem because ElasticSearch doesn't just take the last value, it chokes on startup saying "you have multiple entries for this value" (or something similar).
My play looks like this:
- name: configure elasticsearch
blockinfile:
dest: /etc/elasticsearch/elasticsearch.yml
marker: "## added by ansible configuration"
block: |
network.host: 0.0.0.0
path.data: /var/lib
path.logs: /var/log/elasticsearch
path.repo: /home/chris/elastic-backups
state: present
But after running my playbook a second time, my elasticsearch.yml file looks like:
## added by ansible configuration
network.host: 0.0.0.0
path.data: /var/lib
path.logs: /var/log/elasticsearch
path.repo: /home/chris/elastic-backups
## added by ansible configuration
network.host: 0.0.0.0
path.data: /var/lib
path.logs: /var/log/elasticsearch
path.repo: /home/chris/elastic-backups
## added by ansible configuration
Is there a way to only add the block if it does not exist yet?
A: The accepted answer is correct and straightforward.
But also marker string should not contain line breaks like \n, otherwise, Ansible will keep adding the block. Sounds like a bug for me
A: You should specify {mark} keyword in the marker parameter:
marker: "## {mark} added by ansible (configuration elasticsearch)"
This will cause Ansible to insert a line at the beginning and at the end of the block replacing {mark} accordingly with BEGIN and END:
## BEGIN added by ansible (configuration elasticsearch)
network.host: 0.0.0.0
path.data: /var/lib
path.logs: /var/log/elasticsearch
path.repo: /home/chris/elastic-backups
## END added by ansible (configuration elasticsearch)
Otherwise Ansible has no clue, where the block starts and where it ends, so on every run it considers the block is not present and inserts a new one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41284602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Define filter parameters dynamically in django queryset Suppose we have such a model:
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
Can we put x as a variable inside the filter so that we can have different querysets by giving different args when calling the get_queryset function?
def get_queryset(x, y):
queryset = Membership.objects.filter(x=y)
return queryset
A: A Q object [Django-doc] can take a 2-tuple with as first item a string that specifies the "key" and as second item the "value", so you can filter with:
from django.db.models import Q
x = 'person_id'
y = 14
Membership.objects.filter(Q((x, y)))
to obtain the Memberships with person_id=14.
It however does not make much sense to use this in get_queryset in a class-based view, because that function has to respect its code contract, and adding extra parameters will not work: it simply expects a self, and an optional queryset. You can add extra optional parameters, but when the view calls the get_queryset it will not use these parameters, or at least not if you do not alter the boilerplate logic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65265137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Onclick is being called several times even when i have called it only once I have put this code inside the resize function in jQuery. But this click function is called multiple times. When i click on the desired link the toggle takes place many times
if ($(window).width() <=768){
if ($('body').hasClass('page-search-ads')){
if ($('#-clasifika-results-simple-search-form img').hasClass('funnel')) {
} else {
$('#-clasifika-results-simple-search-form').append("<img class='funnel' src='" + Drupal.settings.basePath + "sites/all/themes/clasifika/images/filter.png'/>");
}
$('.funnel').click(function(){
$('.vehicle-cat, .vehicle-brand, .city-name-filter, .vehicle-mileage,.overall-cat,.city-name,.boat-bed,.boat-type,.boat-brand,.nautical-length,.overall-year,.airplane-type,.fashion-cat,.airplane-brand,.airframe-time,.propeller-hours,.monthly-salary,.amount-slider,.area-slider').slideToggle();
console.log("funnel click");
});
}
}
A: The issue is because the resize() event is fired once for every pixel the window is resized. Therefore you're attaching multiple click handlers when the resize occurs. You just need to move the click outside the resize handler, and use a delegated event handler. Try this:
$(window).resize(function() {
if ($(window).width() <= 768 && $('body').hasClass('page-search-ads') && !$('#-clasifika-results-simple-search-form img').hasClass('funnel')) {
$('#-clasifika-results-simple-search-form').append("<img class='funnel' src='" + Drupal.settings.basePath + "sites/all/themes/clasifika/images/filter.png'/>");
}
});
$('#-clasifika-results-simple-search-form').on('click', '.funnel', function(){
$('.vehicle-cat, .vehicle-brand, .city-name-filter, .vehicle-mileage, .overall-cat, .city-name, .boat-bed, .boat-type, .boat-brand, .nautical-length, .overall-year, .airplane-type, .fashion-cat, .airplane-brand, .airframe-time, .propeller-hours, .monthly-salary, .amount-slider, .area-slider').slideToggle();
console.log("funnel click");
});
I'd also suggest you look at using a common class or single containing element to group all the elements in the click handler, as that's about the biggest selector I've ever seen. Also, CSS media queries may be a better solution for the resize() logic too, assuming you're able to just show/hide the relevant element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35057334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Adding condition based on Data Validation List in Microsoft Excel I am having trouble with a small excel formula problem. I am trying to use AVERGEIFS. The setup of this function is
AVERAGEIFS(average_range,criteria_range1,criteria1,criteria_range2,criteria2,...)
The catch is that I want the inclusion of a criteria and its range [criteria_range1,criteria1] to be based on whether a data validation list is Yes or No. So for example if the list is currently set to Yes return:
AVERAGEIFS(average_range,criteria_range1,criteria1)
If no then return
AVERAGEIFS(average_range,criteria_range1,criteria1,criteria_range2,criteria2)
I would use an IF function to handle this if I had only one data validation list with Yes and No, but I have several, three to be exact. So I want to set up a formula that will include a [criteria_range,criteria] based on whether its corresponding data validation list is Yes or No.
I hope that makes sense. I am using OSX. Thanks!
EDIT:
In my problem a name is chosen and with it the corresponding attributes from the dataset below. In the average box below I would love to see the average value for rows with the same attributes in John's case its any rows with blue, type1 = 1, AND type2 = 100. This is easy if I just use a regular AVERAGEIFS function.
What I am trying to figure out is how I could ignore one of the attributes and find the average for that group. So if I select ignore yes for type1 then average would return the average value for rows with color = red AND type2 = 100
A: From your sample screenshot it looks like your criteria1 might look like:
"=" & B3
I would replace it with:
IF(D3="yes","<>ABCDEF","=" & B3)
Where ABCDEF is any string that does not exist in the criteria_range1, so the <>ABCDEF condition is always true. This trick should work for every type of data (strings, numbers, dates, blanks).
The full formula for your sample screenshot would be:
=AVERAGEIFS(E7:E15,C7:C15,IF(D3="yes","<>ABCDEF","=" & B3),D7:D15,
IF(D4="yes","<>ABCDEF","=" & B4),B7:B15,"=" & B2,A7:A15,"=" & B1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28614453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I display the sale from the country? The question asks to display the total sale which is group by sales person and filter for only sales made within Asia.
Here is my code I have tried:
var reqtwo = list1
.GroupBy(p => p.salesPerson)
.Select(s => new {
salesperson= s.Key,
totalSale = s.Sum(p => p.qty*p.price),
asia = s.Where(c => c.country =="China" && c.country == "Hongkong" && c.country == "Malaysia" && c.country =="Indonesia" && c.country =="India")
})
.OrderByDescending(p => p.totalSale)
.ToList();
grid2.DataSource = reqtwo;
The result is displaying the total sales of all country not in Asia.
A: The Where needs to be before the GroupBy
var reqtwo = list1
.Where(c => c.country =="Chiana" || c.country == "Hongkong" || c.country == "Malaysia" || c.country =="Indonesia" || c.country =="India")
.GroupBy(p => p.salesPerson)
.Select(s => new {
salesperson= s.Key,
totalSale = s.Sum(p => p.qty*p.price)
})
.OrderByDescending(p => p.totalSale)
.ToList();
Ive also changed your && to || as a country cannot be China & India at the same time (for example)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70711038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: How to check the Language in which Exe is made We were studying about compilers at college so this raised me curiosity that when we use the compilers and they form assemblies so is there any way you could know that ,if you are given any exe, which compiler was used to build it?or atleast which language was this exe made with c++,c# or what?
A: There are various ways of doing this, but I don't think you can guarantee a valid result depending on what steps people go through to hide it.
Check out PEiD, it can to do this automatically (along with detecting packers, etc).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5453706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WPF: change binding properties for multiple controls I'd like that all the Text bindings for the TextBoxes in my UserControl to have UpdateSourceTrigger=PropertyChanged, and ValidatesOnDataErrors=True
How to do it ?
I can think of a solution: use another class for bindings (a class inheriting Binding) but maybe there is another solution, maybe using a style or template ?
A: You can't do it with a style or template, since a binding is not a FrameworkElement. But your idea of a class inheriting Binding should work fine, I've done the same before for a similar problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2509601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using RegEx to extract digital number from the innertext of a webpage element I used the regex of (?:\[+\.)?\d+ to extract the digits from the innertext of the website element, the innertext was $94.99/mo.
This worked and I can create a variable equal to 105.66. When I apply this regex to innertext which has different digital values contained in it, than all the digital values are selected.
e.g.
Total Monthly Payment: $94.99 + $9.49 (for ASP) = $104.48/month (plus
tax) • Total Cost of Ownership: $104.48 x 12 Months = $1,253.76 (plus
tax) • Cost of Lease Services: $350.77
It finds all the values;
How do I modify the regex so that it only finds the 9.49 price?
A: I would try to extract this: + $9.49
You can use following regex:
@"(?<=\+\s\$)(\d+\.?\d*)
*
*(?<=\+\s\$) match but don't include a + followed by a whitespace, followed by a $
*(\d+\.?\d*) match and put in a group at least one digit, followed by an optional . followed by any number of digits.
The + . $ signs are special regex characters which have to be escaped with a backslash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35455918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Permission denied (publickey) CloudControl I always get this error with cloudcontrol. Help.
Using Windows with Git installed.
Permission denied (publickey). fatal: Could not read from remote
repository.
Please make sure you have the correct access rights and the repository
exists. Command '['C:\Program Files (x86)\Git\bin\git.exe',
'push', u'ssh://phpapiya sh@cloudcontrolled.com/repository.git',
'master']' returned non-zero exit status 128
A: Have you added your public key to cloudControl? If not, please do this:
cctrluser key.add
For full context please visit our documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29288865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Dynamically Change CSS with Javascript or jQuery I have a snippet of code in which I would like to change the css dynamically based on the values being greater than 0. For a value of '0' the class = 'cart-summary__count'. For a value greater than '0' class = 'cart-summary__count_full'.
<span class="cart-summary__count" data-v-observable="cart-count">0</span>
<span class="cart-summary__count" data-v-observable="cart-count">1</span>
*edit:
<div id="cart-summary">
<span class="cart-summary__count" data-v-observable="cart-count">0</span>
<a href class="cart">example.com</a>
</div>
change to:
<a href class="cart-full">example.com</a>
I am still learning Js and any help would be greatly appreciated. The cart value can change on the page when adding an item.
A: Please use this Code
$(document).ready(function() {
$("span").each(function(){
if (parseInt($(this).text()) > 0){
$(this).removeClass("cart-summary__count");
$(this).addClass("cart-summary__count_full");
}
});
});
Refer this Fiddle
Edit
Based on your edit, use the following code.
HTML
<div id="cart-summary">
<div class="cartContainer">
<span class="cart-summary__count" data-v-observable="cart-count">0</span>
<a href class="cart">example.com</a>
</div>
<div class="cartContainer">
<span class="cart-summary__count" data-v-observable="cart-count">1</span>
<a href class="cart">example1.com</a>
</div>
</div>
JS
$(document).ready(function() {
$("span").each(function(){
if (parseInt($(this).text()) > 0){
$(this).parent().find('a').removeClass("cart");
$(this).parent().find('a').addClass("cart-full");
}
});
});
CSS
.cart-full {
border : 2px solid red
}
.cartContainer {
padding-top : 5px;
}
Refer New Fiddle
A: Hope this is what you are looking for.I have removed id in your code as the id should be unique and i have added a class cart-summary for all the spans.Once you run the below code it will append the required classes.
$('#cart .cart-summary').each(function(){
var span_value = parseInt($(this).text());
if(span_value == 0){
$(this).addClass('cart-summary__count');
}
else{
$(this).addClass('cart-summary__count_full');
}
})
.cart-summary__count{
color:green;
}
.cart-summary__count_full{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cart">
<span class="cart-summary" data-v-observable="cart-count">0</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39368502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stateful bean passivation fails because of Stateless beans references I am using Weblogic 12c (12.1.3 to be specific) to deploy my (EJB 3.1) application.
In my application, I have a @Stateful bean, which holds references to an EntityManager and other @Stateless beans, injected using @PersistenceContext and @EJB annotations respectively.
My issue is that when my stateful bean is being passivated and serialized to disk, Weblogic tries to serialize the references to the stateless beans as well, and throws a NotSerializableException referring to the bean's proxy that was injected by Weblogic. For comparison - the EntityManager reference is passivated and reactivated without issue at all. It is only the stateless beans who cause issues.
I know I can define @PrePassivate and @PostActivate methods to make my code work, but is there any way I can make the container handle the Stateless beans references on its own?
Attaching sample code which reproduces the problem for me.
Remote bean interface:
import javax.ejb.Remote;
@Remote
public interface Passivate {
public void doSomething();
}
Stateful Bean implementation:
import javax.ejb.EJB;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Stateful;
@Stateful(mappedName = "PassivateBean")
public class PassivateBean implements Passivate {
@EJB(mappedName = "NoStateBean")
private NoState noStateBean;
@Override
public void doSomething() {
System.out.println("Hello world");
}
@PrePassivate
public void prePassivate() {
// as a workaround - can set noStateBean to null here
}
@PostActivate
public void postActivate() {
// as a workaround - can lookup and set noStateBean here manually
}
}
NoState Local interface:
import javax.ejb.Local;
@Local
public interface NoState {
public void foo();
}
NoState bean implementation:
import javax.ejb.Stateless;
@Stateless(mappedName = "NoStateBean")
public class NoStateBean implements NoState {
@Override
public void foo() {
System.out.println("foo");
}
}
And finally, the exception I am getting when PassivateBean is being passivated to disk:
<Jul 14, 2015 2:36:20 PM IDT> <Error> <EJB> <BEA-010024> <Error occurred during passivation: java.io.NotSerializableException: passivateTest.NoStateBean_i02rk_Impl
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at weblogic.ejb.container.utils.Serializer.writeObject(Serializer.java:52)
at passivateTest.PassivateBean_dmn8u8_Impl.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at weblogic.ejb.container.swap.PassivationUtils.write(PassivationUtils.java:84)
at weblogic.ejb.container.swap.DiskSwap.write(DiskSwap.java:173)
at weblogic.ejb.container.manager.StatefulSessionManager.swapOut(StatefulSessionManager.java:1246)
at weblogic.ejb.container.cache.LRUCache.passivateNode(LRUCache.java:199)
at weblogic.ejb.container.cache.LRUCache.timerExpired(LRUCache.java:187)
at weblogic.timers.internal.TimerImpl.run(TimerImpl.java:304)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
A: As of now, this seems like an actual bug/limitation in Weblogic 12.1.3 so I am posting my workaround as a possible solution.
To make the Stateful bean go through passivation successfully, one needs to implement methods annotated with javax.ejb.PrePassivate and javax.ejb.PostActivate. The @PrePassivate method will make the stateless bean reference point to null, and the @PostActivate method will perform a lookup for that bean when the bean is being activated again.
@PrePassivate
public void prePassivate() {
noStateBean = null;
}
@PostActivate
public void postActivate() {
// The lookup string is correct assuming the ejb module is deployed within an ear. If your setup is different the JNDI lookup name may be slightly different.
noStateBean = InitialContext.doLookup("java:module/NoStateBean!NoState");
}
If there are no comments or other answers in the next couple of weeks or so, I will mark this answer as the solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31405591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Laravel5 Eloquent method All returning unexpected results I am trying to learn Laravel and I was really liking it until I got stumped!
I created a table called suggestions and seeded it with some fake data.
It looks like this:
I have a model file called Suggestion.php that has this code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suggestion extends Model
{
//
}
In my routes.php file I have this:
use App\Suggestion;
Route::get('/', function () {
$suggestions = Suggestion::all();
return '<pre>' . var_dump($suggestions) . '</pre>';
});
I'm expecting to get an array of the records in my database, but instead I am getting a Illuminate\Database\Eloquent\Collection object that has two arrays, a macros array and an items array. The beginning of the var_dump looks like this:
The data I want to access actually appears to be in attributes array, but it doesn't seem that this is how Laravel is supposed to work.
This really confuses me as I've been trying to follow a number of tutorials (like this one) and it seems that I should be getting a simple collection that I can loop over.
I did do some research on this issue and I did find other Stack Overflow posts like this one but it doesn't really address my question.
I'm sort of figuring that I somehow messed up my Suggestions model or didn't do it correctly, but beyond that I'm lost.
Thanks, in advance, for any guidance you can give me. I actually intend to use a Controller and a View but for simplicity in presenting my problem here, I put the necessary code in the routes file.
A:
Eloquent methods like all and get which retrieve multiple results, an
instance of Illuminate\Database\Eloquent\Collection will be returned.
The Collection class provides a variety of helpful methods for working
with your Eloquent results. Of course, you may simply loop over this
collection like an array
from the docs
so you are right eloquent return a collection.
it have a section in the documents how to work with it https://laravel.com/docs/5.2/collections
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35257561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a command that triggers executable file of your gem? For example, I have a gem called mygem and I want to start executable file with a command mygem.
How can I do this?
A: Here is the RubyGems guide for how to add an executable.
The primary steps are:
*
*Add your script to the gem's /bin directory
*Your script must be executable in the filesystem chmod a+x bin/<yourfile>
*Make sure your script starts with a proper shebang
*Add the script to the .executables section of your gemspec
Note you will still have to build and install your gem locally to run the command without a path as you are trying to do in the screenshot.
More info in building executable gems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37475627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unpack function return tuple into key value pair Suppose I have a function that returns a tuple:
def foo(x):
return (x, x*100)
I have a list of values that I'd like to apply the function on and then turn the results into a dictionary:
list_of_vals = [2, 4, 6]
result = {...magic comprehension...}
print(result)
# {2: 200, 4: 400, 6: 600}
I've come up with two ways to do this:
{ k: v for k, v in map(foo, list_of_vals)}
{ k: v for k, v in (foo(val) for val in list_of_vals} # equivalently
or:
def helper_bar(vals):
for val in vals:
yield(foo(val))
{k: v for k, v in helper_bar(vals)}
However, none of these is very readable. Furthermore, if the list_of_vals is humongous I don't want to create extra copies. Is there any better (efficient?) way to do this assuming I have very long list of values and foo is an expensive function?
A: You can also use the dict initializator that takes an iterable of key-value tuples. So this would be perfect for your function that already returns a tuple:
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}
In general though, having a function that returns a key-value tuple with the identical key seems somewhat rare. Most commonly, you would just have a function that returns the value. In those cases you would use a dictionary comprehension like this:
{ x: foo(x) for x in list_of_vals }
A: Just convert the result of map to dict directly
>>> list_of_vals = [2, 4, 6]
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51855167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Drawing an arc, depending on the input time I need to draw a part of the circle, depending on the input time. For example, from 6:00 to 9:00, the site of the circle is:
Blue area I need draws. Accordingly, from 00:10 to 3:20 schedule part of the circle will be elsewhere.
I thought I'd use the GD library, but I do not know how (Maybe the question here with geometry and with sin and cos. Thank you.
P.S. I do not know if there is a way to do it via JavaScript and/or CSS.
A: That's the most important bit to solve this problem:
x = r * Math.cos(t) + offsetX;
y = r * Math.sin(t) + offsetY;
which is parametric form of circle equation... "r" is radius and "t" is 'progress' from 0 to 2π, (wiki)
You can easily do that in JavaScript using either "canvas" or SVG (check Raphael.js library)
A: Here's a great link :)
arc
I hope it works for you :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19088803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to allow to use case sensitive row ids in jqGrid If jqGrid row ids (passed as separate id property from json data in server) are different only by case, inline edit is not started properly:
double clicking in second row puts first row in inline edit mode.
How to make jqgrid row ids case sensitive ?
Data read from server is:
{"total":1,"page":1,"records":2,"rows":[
{"id":"arvelduste_20seis","cell":[null,"arvelduste seis"]},
{"id":"Arvelduste_20seis","cell":[null,"Arvelduste seis"]}
]}
A: It seems for me as a bug in Internet Explorer. In the official Document Object Model HTML standard I could found the following description about the namedItem method intensively used by jqGrid:
This method retrieves a Node using a name. With [HTML 4.01] documents,
it first searches for a Node with a matching id attribute. If it
doesn't find one, it then searches for a Node with a matching name
attribute, but only on those elements that are allowed a name
attribute. With [XHTML 1.0] documents, this method only searches for
Nodes with a matching id attribute. This method is case insensitive in
HTML documents and case sensitive in XHTML documents.
So the namedItem method should works case sensitive in XHTML documents. On the other side like you can test in the demo, which use only pure DOM without jQuery or jqGrid, the method work case insensitive in Internet Explorer.
The HTML code of the demo is following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>http://stackoverflow.com/questions/7230179/how-to-allow-to-use-case-sensitive-row-ids-in-jqgrid/7236985#7236985</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table id="t">
<tbody>
<tr id="x"><td>1</td></tr>
<tr id="X"><td>2</td></tr>
</tbody>
</table>
<script type="text/javascript">
'use strict';
var mytable = document.getElementById("t"),
tr1 = mytable.rows.namedItem("x"),
tr2 = mytable.rows.namedItem("X"),
tr3 = document.getElementById("x"),
tr4 = document.getElementById("X");
alert("getElementById works " + (tr3.id === tr4.id ? "case insensitive (BUG!!!)": "case sensitive") +
"\nnamedItem works " + (tr1.id === tr2.id ? "case insensitive (BUG!!!)": "case sensitive"));
</script>
</body>
</html>
The Internet Explorer shows that namedItem("X") returns the row with the id="x" instead of the row having id="X". The same bug not exist in all other (non-Microsoft) web browsers where I tested it.
I can't suggest you currently no workaround. You should just organize you program so that you will not use case sensitive ids inside of tables (and with jqGrid).
UPDATED: Just a little more additional information.
I made an official support request to Microsoft about the described subject. Microsoft confirmed that it was a bug in Internet Explorer, but the bug will be not fixed in the current Internet Explorer versions, but it will be probably fixed in IE10. As a workaround :-) it was suggested not to use ids which distinguish only in case. So just not use the ids which can reproduce the bug. So we have at the end results as I supposed before in my previously comments.
Nevertheless, because the response confirmed that it was a bug, the request to Microsoft was for free for me (:-)).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7230179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NoSql Design, AWS (DynamoDB) or Azure(DocumentDB)? I am planning on moving our people/address/telephone database from Sql Server into a NoSQL db for scalability reasons.
We currently have all our infrastructure on AWS and Azure and we are planning on keeping it that way. Hence, I started researching the tools provided by both AWS and Azure but I am in doubt and wish I could get some help.
Here's the basic structure of our tables:
Person
ID,
Name,
Surname,
DOB,
Job,
EmailAddress,
Nationality,
CityOfBirth,
Etc...
Address
PersonId,
Street,
Number,
ZipCode,
City,
etc...
Telephone
PersonId,
Number,
AreaCode,
Carrier,
etc...
Queries:
The main query that we perform is to obtain people based on columns from Person (DOB, Job, etc), Address (ZipCode Range, State, City, etc) and Telefone (Carrier, Telefone Type, etc) tables. We filter need to select millions of records on a daily basis to generate the data to be processed by our app.
My typical query returns the following columns:
Person Table: ID, Name, Surname, DOB, Job, EmailAddress, Nationality, CityOfBirth
Address Table: Street, Number, ZipCode, City, State
Telephone Table (5 phone numbers per person): Number, AreaCode, Carrier
Queries usually return from 5k~15k records, and we need to obtain the full resultset.
We also perform updates on the telephone data on a weekly basis, adding/removing/updating phone numbers. We do it on the weekend to avoid impacting performance on the production application.
I understand that I would have to denormalize this structure to facilitate querying and improve read performance. So I starting assessing both cloud providers for the possible solutions:
AWS DynamoDB
From what I could understand I cannot implement queries on multiple attributes and there is a limit on Indexes that can be created. I couldn't think of a way to model the data to allow for fast querying using the filters mentioned.
It seems to me that I could perform query on the most important fields and then apply filtering on the rest. I am not sure if it would be optimal, given that I have 50 million + records.
Or is there another AWS Service that could assist me on achieving the desired behavior?
Azure DocumentDB
Since it stores JSON objects which are indexed by all attributes I could be the way to go. I is supposed to be less performant than KEY/Value Tables and I am not aware of the actual performance when querying for millions of records on a daily basis.
Again, I am not sure if is there another service that could prive better results on Azure.
Conclusion:
I would like to get some insight that could lead me into the right direction. I've seem some questions regarding Elasticsearch and etc that could assist in this, but I am not sure if it would give the performance I was hoping for and if it is actually its purpose.
Objective
What is driving us to look for alternatives is to take advantage of cloud's flexibility. Nowadays we keep a large SQL Server 24/7 to host this core data of our application. We are hoping to improve query performance and reduce server costs.
Not sure what if NoSQL is the way to go, or remaining on SQL Server with changes on the data structure.
Any help would be appreciated!
Thanks in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43576711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Codeception - HTML report generation seems slow? I am using Codeception to run three acceptance tests which basically are as follows:-
*
*Check the email address 'admin@admin.com' exists
*Create a new user account
*Login to the website
Obviously this requires the database so I have added 'Db' to the list of modules in the acceptance.suite.yml, however the generation of the report takes sometime, is this normal or do I have something wrong with my setup?
Below is the report (and time taken for each according to the html file it is generating)
*
*check admin@admin.com account exists (AdminCept.php) (0.01s)
*create new user account (CreateUserCept.php) (19.1s)
*log in to the website (LoginCept.php) (21.72s)
Approx 40 seconds in total (although the command line states 1:02 - I guess as it replaces the mock database dump.sql back into the database as well)
Can anybody shed any light on the matter?
A: Not really an answer but closing this off - simply put the report generation takes time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17109256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: compass vanishes when MKMap is oriented to north in iOS I am displaying a map on the iPhone using MKMapView. The Map can rotate so that it is oriented with respect to the iPhone orentation using the magnetic heading information.
I like to present the compass but it vanishes each time the map is oriented to north! It reappears when the phone is rotated a little bit further but this is distracting.
The rotation functionality is switched on when some conditions are met like so:
@IBOutlet weak var mapView: MKMapView!
// here comes some other code
if settings.useMagneticHeading && validUserLocation
{
mapView.isRotateEnabled = true
mapView.showsCompass = true
locationService.startUpdatingHeading()
}
The rotation is performed by a delegate:
func tracingHeading(currentHeading: CLLocationDirection)
{
if settings.useMagneticHeading && validUserLocation
{
mapView.camera.heading = currentHeading
mapView.setCamera(mapView.camera, animated: true)
}
}
The CoreLocation stuff is encapsulated in the locationService singleton.
How can one force to show the compass also when the map is oriented exactly to north? I guess this behavior is a feature not a bug which seems to be undocumented. (found in iOS 9 and iOS 10)
A: You're right. This behavior is a feature not a bug.
In iOS 11 you can use compassVisibility.
let compass = MKCompassButton(mapView: mapView)
compass.compassVisibility = .visible
https://developer.apple.com/documentation/mapkit/mkcompassbutton/2890262-compassvisibility
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45790045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using Django's ifchanged template tag with forloop.counter Django's template tags include an {% ifchanged %} test for use within loops to check if a value has changed. I'm using it to output a new <div> tag every time a variable changes.
I want every 4th <div> to have a specific class, but Django's forloop.counter variable isn't helpful here as it increments every time the loop runs, even when the {% ifchanged %} test doesn't run, so it outputs irregularly.
Does anyone know of a way to get around this? Obviously I can't set my own counter inside a Django view, so I have no way of checking when the 'inner' loop has changed.
Thanks,
Matt
A: You can simply use the divisibleby filter:
{% if forloop.counter|divisibleby:"4" %}
....
{% endif %}
Update:
You have to use a counter+divisibleby filter in your template. Look at this template tag: Counter, it can help you.
Or
Filter out duplicate items (if possible) in the view before passing them to the template and use the divisibleby filter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6257648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DocuSign Connect - Uploaded DOCX, Returned DOCX I have been working on a listener application for receiving HTTP POST requests from DocuSign Connect. It is coded as a ASP.NET MVC4 web application.
By using the sandbox environment, I have been able to send and receive documents in a variety of different file formats with the expected behavior outlined by DocuSign...except for docx types.
The scenario I am encountering is as follows:
*
*Attach and send a test docx file for signing via the "send envelope" interface in the sandbox environment (for simplicity, I am just adding a signature overlay).
*Logged into the recipient email account and go through the steps of signing the document.
*Wait a few minutes for the listener application to respond and extract the signed document from the XML.
*Verified that the filename of the extracted signed document is not a PDF, but the same as the uploaded file (name and file extension). Attempting to open it in Word results in Word complaining that the file is corrupted and cannot be opened.
*When checking for the same signed document (as an attachment) in the "completed" email notification, I see it as a PDF and was able to open it with no issues.
My question is why is DocuSign Connect not returning a signed PDF version of the docx file that was sent?
DocuSign's documentation has indicated that signed versions of any file format will be in PDF. As verification, I had tried using doc and jpg files with no issues.
What makes this even more strange is that if I manually change the file extension of the signed document to PDF, I can view the contents of the file as expected. So is it just a case of an incorrect file extension being returned back? Or is there a step or two that I am missing?
I have attached the XML from a couple of requests from DocuSign Connect. One is correct with no issues; and one that is problematic.
Correct XML from DocuSign Connect
(Files Sent: 1 PDF, 1 doc)
Problematic XML from DocSign Connect
(Files Sent: 1 docx)
If anyone knows why this is happening, I would appreciate any help I can get. It's not a deal-breaker that this is happening, as I can program in an exception to rename the file extension for docx files. It is just a minor annoyance that it has to be done.
A: Regarding:
My question is why is DocuSign Connect not returning a signed PDF version of the docx file that was sent?
DocuSign did return a PDF document to you. Your conclusion that the file was not a PDF file is not correct.
The filename field is just informational, the file extension in the filename field is also not significant.
What is significant:
*
*DocuSign needs to know the file type of the input / uploaded files. It uses the fileExtension field to learn from the submittor what the filetype is.
*If the file type is anything other than pdf, it will always be converted to pdf. There are no exceptions.
*If the file type is pdf, the pdf file will be "flattened" (rasterized) to ensure that no malware within the pdf can harm a signer or other recipient. (PDF files are actually programs. The programs usually just produce a printed page, but they can do far more, both for good and for evil. But I digress.)
*If you choose to have the webhook system (Connect or eventNotifications) send you files, those files will always be in pdf format.
*The fileExtension field is referring to the file type that was sent to DocuSign. The correct file extension for a file downloaded from DocuSign is always .pdf.
In your case, I opened your "problematic" XML notification message and copied the PDFBytes content to an online base64 decoder. I then opened the output using a pdf viewer and was shown your signed document.
It doesn't matter what the "name" of the document is/was. Output from DocuSign is always in the form of a PDF document.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39647048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ObjectBox / ToMany - Is there a way to query() the absence of a relationship? I have two ObjectBox entities (Attribute and Delivery) that are linked by a ToMany relationship.
I'd like to use Box.query to select all Attribute with no linked Delivery.
Current code requires to fetch all objects and cycle through them, which is kinda cumbersome.
List<Attribute> attrs = attributeBox.getAll();
for (Attribute attr : attrs) {
if (attr.delivery.isEmpty()) { // ToMany relationship from Attribute to Delivery
Timber.i("Attribute without delivery: %s", attr.getName());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68949307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: laravel Route::resource() is using show() instead of create() at the /create route Ok, I have a resource where the show($id = create) is taking over create()
The page I'm visiting
http://localhost/admin/packages/create
my error is: Error
ModelNotFoundException {#306 ▼
#model: "Me\Subscriptions\Package"
#ids: []
#message: "No query results for model [Me\Subscriptions\Package]."
#code: 0
#file: "C:\Users\Me\Code\bb2\vendor\laravel\framework\src\Illuminate\Routing\ImplicitRouteBinding.php"
#line: 36
trace: {▶}
}
my resources file: routes/admin.php
// I commented out every other line...
Route::resource('/packages', 'PackagesController');
My controller has all the resource methods populated... PackagesController
...
public function show(Package $package) {
$meals = Meal::all();
return view('admin.packages.show')
->with(compact('package', 'meals'));
}
public function create() {
return view('admin.packages.create');
}
...
when I run route:list
| | GET|HEAD | admin/packages | packages.index | App\Http\Controllers\Admin\PackagesController@index | admin |
| | POST | admin/packages | packages.store | App\Http\Controllers\Admin\PackagesController@store | admin |
| | GET|HEAD | admin/packages/create | packages.create | App\Http\Controllers\Admin\PackagesController@create | admin |
| | DELETE | admin/packages/{package} | packages.destroy | App\Http\Controllers\Admin\PackagesController@destroy | admin |
| | PUT|PATCH | admin/packages/{package} | packages.update | App\Http\Controllers\Admin\PackagesController@update | admin |
| | GET|HEAD | admin/packages/{package} | packages.show | App\Http\Controllers\Admin\PackagesController@show | admin |
| | GET|HEAD | admin/packages/{package}/edit | packages.edit | App\Http\Controllers\Admin\PackagesController@edit | admin
I've checked my RouteServiceProvider too...
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
parent::boot();
}
public function map()
{
$this->mapAdminRoutes();
}
protected function mapAdminRoutes()
{
Route::group([
'middleware' => 'admin',
'namespace' => $this->adminNamespace,
'prefix' => 'admin',
], function ($router) {
require base_path('routes/admin.php');
});
}
What the heck am I missing?????
A: Doing composer update fixed this for me.
Apparently there is an issue in version 5.5.7 of laravel/framework
Update to 5.5.8^ to fix this.+
https://github.com/laravel/framework/pull/21261
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46678591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why are KD-trees so damn slow for nearest neighbor search in point sets? I am using CGAL's (the latest) KD-tree implementation for searching nearest neighbors in point sets. And also Wikipedia and other resources seem to suggest that KD-trees are the way to go. But somehow they are too slow and Wiki also suggests their worst-case time of O(n), which is far from ideal.
[BEGIN-EDIT]
I am now using "nanoflann", which is about 100-1000 times faster than the equivalent in CGAL for K-neighbor search. And I am using "Intel Embree" for raycasting, which is about 100-200 times faster than CGAL's AABB trees.
[END-EDIT]
My task looks like this:
I have a HUGE point set, say like up to a few 100 mio. points!! and their distribution is on surfaces of triangulated geometry (yes, a photon tracer). So one could say that their distribution is 2D in 3D space, because it is sparse in 3D but dense when looking at the surfaces... This could be the problem right? Because to me this seems to trigger the worst-case performance of a KD-tree which probably could deal much better with 3D dense point sets...
CGAl is quite good at what it does, so I have a bit doubt that their implementation just sucks. Their AABB tree I am using for raytracing burns a straight billion raytraces in a few mintues in the ground... That is remarkable I guess. But their KD-tree on the other hand can't even deal with a mio. points and 250k samples (point queries) in any reasonable time...
I came up with two solutions which kick the crap out of KD-trees:
1) Use texture maps to store the photons in a linked list on the geometry. This is always an O(1) operation, since you have to do the raycast anyway...
2) Use view dependent sliced hashsets. That is the farther away you get, the more coarse the hashsets get. So basically you can think of a 1024x1024x1024 raster in NDC coordinates, but with hashsets, to save memory in sparse areas. This basically has O(1) complexity and can be parallelized efficiently, both for inserts (micro-sharding) and queries (lock-free).
The former solution has the disadvantage that it is close to impossible to average over neighboring photon lists, which is important in darker regions to avoid noise.
The latter solution doesn't have this problem and should be on par feature wise with KD-trees, just that it has O(1) worst case performance, lol.
So what do you think? Bad KD-tree implementation? If not, is there something "better" than a KD-tree for bounded nearest neighbor queries? I mean I have nothing against my second solution above, but a "proven" data-structure that delivers similar performance would be nicer!
Thanks!
Here is the code (not compilable though) that I used:
#include "stdafx.h"
#include "PhotonMap.h"
#pragma warning (push)
#pragma warning (disable: 4512 4244 4061)
#pragma warning (disable: 4706 4702 4512 4310 4267 4244 4917 4820 4710 4514 4365 4350 4640 4571 4127 4242 4350 4668 4626)
#pragma warning (disable: 4625 4265 4371)
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Orthogonal_incremental_neighbor_search.h>
#include <CGAL/basic.h>
#include <CGAL/Search_traits.h>
#include <CGAL/point_generators_3.h>
#pragma warning (pop)
struct PhotonicPoint
{
float vec[3];
const Photon* photon;
PhotonicPoint(const Photon& photon) : photon(&photon)
{
vec[0] = photon.hitPoint.getX();
vec[1] = photon.hitPoint.getY();
vec[2] = photon.hitPoint.getZ();
}
PhotonicPoint(Vector3 pos) : photon(nullptr)
{
vec[0] = pos.getX();
vec[1] = pos.getY();
vec[2] = pos.getZ();
}
PhotonicPoint() : photon(nullptr) { vec[0] = vec[1] = vec[2] = 0; }
float x() const { return vec[0]; }
float y() const { return vec[1]; }
float z() const { return vec[2]; }
float& x() { return vec[0]; }
float& y() { return vec[1]; }
float& z() { return vec[2]; }
bool operator==(const PhotonicPoint& p) const
{
return (x() == p.x()) && (y() == p.y()) && (z() == p.z()) ;
}
bool operator!=(const PhotonicPoint& p) const
{
return ! (*this == p);
}
};
namespace CGAL
{
template <>
struct Kernel_traits<PhotonicPoint>
{
struct Kernel
{
typedef float FT;
typedef float RT;
};
};
}
struct Construct_coord_iterator
{
typedef const float* result_type;
const float* operator()(const PhotonicPoint& p) const
{
return static_cast<const float*>(p.vec);
}
const float* operator()(const PhotonicPoint& p, int) const
{
return static_cast<const float*>(p.vec+3);
}
};
typedef CGAL::Search_traits<float, PhotonicPoint, const float*, Construct_coord_iterator> Traits;
typedef CGAL::Orthogonal_incremental_neighbor_search<Traits> NN_incremental_search;
typedef NN_incremental_search::iterator NN_iterator;
typedef NN_incremental_search::Tree Tree;
struct PhotonMap_Impl
{
Tree tree;
PhotonMap_Impl(const PhotonAllocator& allocator) : tree()
{
int counter = 0, maxCount = allocator.GetAllocationCounter();
for(auto& list : allocator.GetPhotonLists())
{
int listLength = std::min((int)list.size(), maxCount - counter);
counter += listLength;
tree.insert(std::begin(list), std::begin(list) + listLength);
}
tree.build();
}
};
PhotonMap::PhotonMap(const PhotonAllocator& allocator)
{
impl = std::make_shared<PhotonMap_Impl>(allocator);
}
void PhotonMap::Sample(Vector3 where, float radius, int minCount, std::vector<const Photon*>& outPhotons)
{
NN_incremental_search search(impl->tree, PhotonicPoint(where));
int count = 0;
for(auto& p : search)
{
if((p.second > radius) && (count > minCount) || (count > 50))
break;
count++;
outPhotons.push_back(p.first.photon);
}
}
A: I have done some research into fast KD-tree implementations a few months ago, and I agree with Anony-Mousse that quality (and "weight" of libraries) varies strongly. Here are some of my findings:
kdtree2 is a little known and pretty straightforward KD-tree implementation I found to be quite fast for 3D problems, especially if you allow it to copy and re-sort your data. Also, it is small and very easy to incorporate and adapt. Here is a paper on the implementation by the author (don't be put off by the mentioning of Fortran in the title). This is the library I ended up using. My colleagues benchmarked its speed for 3D points against VLFeat's KD-trees and another library I don't remember (many FLANN, see below) and it won.
FLANN has a reputation of being fast, and is used and recommended quite often recently. It aims at the higher dimensional case, where it offers approximate algorithms, but is also used in the Point Cloud Library which deals with 3D problems.
I did not experiment with CGAL since I found the library to be too heavyweight. I agree that CGAL has a good reputation, but I feel it occasionally suffers from oversophistication.
A: From my experience, implementation quality varies widely, unfortunately. I have, however, never looked at the CGAL implementation.
The worst case for the k-d-tree usually is when due to incremental changes it becomes too unbalanced, and should be reloaded.
However, in general such trees are most efficient when you don't know the data distribution.
In your case it sounds as if a simple grid-based approach may be the best choice. If you want, you can consider a texture to be a dense 2d grid. So maybe you can find a 2d projection where a grid works good, and then intersect with this projection.
A: Answers are not the place to ask questions, but your question is not a question, but a statement that the kd-tree of CGAL sucks.
Reading 1.8mio points of a geological data model, and computing the 50 clostest points for each of these points has the following performance on my Dell Precision, Windows7, 64bit, VC10:
*
*reading the points from a file: 10 sec
*Construction of the tree 1.3 sec
*1.8 mio queries reporting the 50 closest points: 17 sec
Do you have similar performances. Would you expect a kd-tree to be faster?
Also I am wondering where your query points are, that is close to the surface, or close to the skeleton.
A: Take a look at ApproxMVBB library under the MPL licence:
https://github.com/gabyx/ApproxMVBB:
The kdTree implementation should be comparable to PCL(FLANN) and might be even faster. (tests with PCL seemed to be faster with my implementation!)
Diclaimer: I am the owner of this library and by no means this library claims to be any faster and serious performance tests have not been conducted yet, but I am using this library sucessfully in granular rigid body dynamics where speed is king!
However, this library is very small, and the kdTree implementation is very generic (see the examples) and lets you have custom splitting heurstics and other fancy stuff :-).
Similar improvements and considerations as in the nanoflann (direct data access etc., generic data, n-dimensional ) are implemented ... (see the KdTree.hpp) header.
Some Updates on Timing:
The example kdTreeFilteringcontains some small benchmarks:
The standord bunny with 35947 points is loaded (fully working example in the repo out of the box) :
The results:
Bunny.txt
Loaded: 35947 points
KDTree:: Exotic point traits , Vector3* + id, start: =====
KdTree build took: 3.1685ms.
Tree Stats:
nodes : 1199
leafs : 600
tree level : 11
avg. leaf data size : 29.9808
min. leaf data size : 0
max. leaf data size : 261
min. leaf extent : 0.00964587
max. leaf extent : 0.060337
SplitHeuristics Stats:
splits : 599
avg. split ratio (0,0.5] : 0.5
avg. point ratio [0,0.5] : 0.22947
avg. extent ratio (0,1] : 0.616848
tries / calls : 599/716 = 0.836592
Neighbour Stats (if computed):
min. leaf neighbours : 6
max. leaf neighbours : 69
avg. leaf neighbours : 18.7867
(Built with methods: midpoint, no split heuristic optimization loop)
Saving KdTree XML to: KdTreeResults.xml
KDTree:: Simple point traits , Vector3 only , start: =====
KdTree build took: 18.3371ms.
Tree Stats:
nodes : 1199
leafs : 600
tree level : 10
avg. leaf data size : 29.9808
min. leaf data size : 0
max. leaf data size : 306
min. leaf extent : 0.01
max. leaf extent : 0.076794
SplitHeuristics Stats:
splits : 599
avg. split ratio (0,0.5] : 0.448302
avg. point ratio [0,0.5] : 0.268614
avg. extent ratio (0,1] : 0.502048
tries / calls : 3312/816 = 4.05882
Neighbour Stats (if computed):
min. leaf neighbours : 6
max. leaf neighbours : 43
avg. leaf neighbours : 21.11
(Built with methods: midpoint, median,geometric mean, full split heuristic optimization)
Lucy.txt model with 14 million points:
Loaded: 14027872 points
KDTree:: Exotic point traits , Vector3* + id, start: =====
KdTree build took: 3123.85ms.
Tree Stats:
nodes : 999999
leafs : 500000
tree level : 25
avg. leaf data size : 14.0279
min. leaf data size : 0
max. leaf data size : 159
min. leaf extent : 2.08504
max. leaf extent : 399.26
SplitHeuristics Stats:
splits : 499999
avg. split ratio (0,0.5] : 0.5
avg. point ratio [0,0.5] : 0.194764
avg. extent ratio (0,1] : 0.649163
tries / calls : 499999/636416 = 0.785648
(Built with methods: midpoint, no split heuristic optimization loop)
KDTree:: Simple point traits , Vector3 only , start: =====
KdTree build took: 7766.79ms.
Tree Stats:
nodes : 1199
leafs : 600
tree level : 10
avg. leaf data size : 11699.6
min. leaf data size : 0
max. leaf data size : 35534
min. leaf extent : 9.87306
max. leaf extent : 413.195
SplitHeuristics Stats:
splits : 599
avg. split ratio (0,0.5] : 0.297657
avg. point ratio [0,0.5] : 0.492414
avg. extent ratio (0,1] : 0.312965
tries / calls : 5391/600 = 8.985
Neighbour Stats (if computed):
min. leaf neighbours : 4
max. leaf neighbours : 37
avg. leaf neighbours : 12.9233
(Built with methods: midpoint, median,geometric mean, full split heuristic optimization)
Take care about the interpretation! and look at the settings used in the example File.
However comparing with results from other people: ~3100ms for 14*10⁶ points is quite slick :-)
Processor used: Intel® Core™ i7 CPU 970 @ 3.20GHz × 12 , 12GB Ram
A: If the kdtree is fast for small sets, but "slow" for large (>100000?) sets, you may be suffering from flushing the processor caches. If the top few nodes are interleaved with rarely used leaf nodes then you will fit fewer heavily used nodes in the processor cache(s). This can be improved by minimising the size of the nodes and careful layout of the nodes in memory.. but eventually you will be flushing a fair number of nodes anyway. You can end up with access to main memory being the bottle-neck.
Valgrind tells me one version of my code is 5% fewer instructions, but I believe the stopwatch when it tells me it is about 10% slower for the same input. I suspect valgrind doing a full cache simulation would tell me the right answer.
If you are multi-threaded, you may want to encourage the threads to be doing searches in similar areas to reuse the cache... that assumes a single multi-core processor - multiple processors might want the opposite approach.
Hint: You pack more 32bit indexes in memory than 64bit pointers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15124900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Nant property cannot be overwritten eventhough not marked as readonly I am using nant 0.85 version. I have defined a property in a file and have not specified like'read only=true". But where ever I try to change the value of the property , I get the warning saying that, property cannot be overwritten.
I have tried setting readonly="false" overwrite="true".But nothing seems to work. Any help would be greatly appreciated .
A: You can totally do this in NAnt 0.85. Let's say for example you have a property with the name "myvalue" that you want to be able to be passed in from the command line. You would first define the property in your NAnt script like this:
<property name="myvalue" value="0" overwrite="false" />
When you call NAnt you just need to use the -D parameter to pass in your new value like this:
nant.exe buildfile:myfile.build -logfile:mylog.log -D:myvalue=16
And your new value of "16" will be recognized in your build script which you can test by simply echoing the value like this:
<echo message="myvalue: ${myvalue}" />
For further information you can read the documentation and look at example "iv":
http://nant.sourceforge.net/release/0.85/help/tasks/property.html
A: use unless attribute, it works.
<property name="msbuild.path" value="CONFIGURABLE" unless="${property::exists('msbuild.path')}" />
then as usual nant -D:msbuild.path=...
A: Need more details, especially if you "change the value of the property" from command line.
One thing that I have seen that causes some confusion is that when the property is overridden from command line ( -D:prop=value ), and if the same property is defined in the file (<property name="prop" value="value"/> ) it will say read only property cannot be overridden because the property set from command line is read only and it cannot be overridden by the property defined in the file.
It is not the other way around, which causes some confusion and people thinking that despite having no readonly set to true etc. still saying cannot be overridden.
So try to see if the property you set is actually using the value you wanted, if you are overriding from command line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6106237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ copy elision of fields I am trying to get copy elision to work for fields of the object that is to be returned.
Example code:
#include <iostream>
struct A {
bool x;
A(bool x) : x(x) {
std::cout << "A constructed" << std::endl;
}
A(const A &other) : x(other.x) {
std::cout << "A copied" << std::endl;
}
A(A &&other) : x(other.x) {
std::cout << "A moved" << std::endl;
}
A &operator=(const A &other) {
std::cout << "A reassigned" << std::endl;
if (this != &other) {
x = other.x;
}
return *this;
}
};
struct B {
A a;
B(const A &a) : a(a) {
std::cout << "B constructed" << std::endl;
}
B(const B &other) : a(other.a) {
std::cout << "B copied" << std::endl;
}
B(B &&other) : a(other.a) {
std::cout << "B moved" << std::endl;
}
B &operator=(const B &other) {
std::cout << "B reassigned" << std::endl;
if (this != &other) {
a = other.a;
}
return *this;
}
};
B foo() {
return B{A{true}};
}
int main() {
B b = foo();
std::cout << b.a.x << std::endl;
}
I compile with:
g++ -std=c++17 test.cpp -o test.exe
output:
A constructed
A copied
B constructed
1
B is constructed in-place. Why is A not? I would at least expect it to be move-constructed, but it is copied instead.
Is there a way to also construct A in-place, inside the B to be returned? How?
A: Constructing a B from an A involves copying the A - it says so in your code. That has nothing to do with copy elision in function returns, all of this happens in the (eventual) construction of B. Nothing in the standard allows eliding (as in "breaking the as-if rule for") the copy construction in member initialization lists. See [class.copy.elision] for the handful of circumstances where the as-if rule may be broken.
Put another way: You get the exact same output when creating B b{A{true}};. The function return is exactly as good, but not better.
If you want A to be moved instead of copied, you need a constructor B(A&&) (which then move-constructs the a member).
A: You will not succeed at eliding that temporary in its current form.
While the language does try to limit the instantiation ("materialisation") of temporaries (in a way that is standard-mandated and doesn't affect the as-if rule), there are still times when your temporary must be materialized, and they include:
[class.temporary]/2.1: - when binding a reference to a prvalue
You're doing that here, in the constructor argument.
In fact, if you look at the example program in that paragraph of the standard, it's pretty much the same as yours and it describes how the temporary needn't be created in main then copied to a new temporary that goes into your function argument… but the temporary is created for that function argument. There's no way around that.
The copy to member then takes place in the usual manner. Now the as-if rule kicks in, and there's simply no exception to that rule that allows B's constructor's semantics (which include presenting "copied" output) to be altered in the way you were hoping.
You can check the assembly output for this, but I'd guess without the output there will be no need to actually perform any copy operations and the compiler can elide your temporary without violating the as-if rule (i.e. in the normal course of its activities when creating a computer program, from your C++, which is just an abstract description of a program). But then that's always been the case, and I guess you know that already.
Of course, if you add a B(A&& a) : a(std::move(a)) {} then you move the object into the member instead, but I guess you know that already too.
A: I have figured how to do what I wanted.
The intent was to return multiple values from a function with the minimal amount of "work".
I try to avoid passing return values as writable references (to avoid value mutation and assignment operators), so I wanted to do this by wrapping the objects to be returned in a struct.
I have succeeded at this before, so I was surprised that the code above didn't work.
This does work:
#include <iostream>
struct A {
bool x;
explicit A(bool x) : x(x) {
std::cout << "A constructed" << std::endl;
}
A(const A &other) : x(other.x) {
std::cout << "A copied" << std::endl;
}
A(A &&other) : x(other.x) {
std::cout << "A moved" << std::endl;
}
A &operator=(const A &other) {
std::cout << "A reassigned" << std::endl;
if (this != &other) {
x = other.x;
}
return *this;
}
};
struct B {
A a;
};
B foo() {
return B{A{true}};
}
int main() {
B b = foo();
std::cout << b.a.x << std::endl;
}
output:
A constructed
1
The key was to remove all the constructors of B. This enabled aggregate initialization, which seems to construct the field in-place. As a result, copying A is avoided. I am not sure if this is considered copy elision, technically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59756657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to Display my output in Php with return in a loop? I want to output my code. When I use return then it breaks up after 1time and
(when I use echo my content will be displayed on the top of the page. And I think that I should not use here echo because I want to call functions in the loop later)
Here are pictures that will show how it looks like:
My code with return:
function allmyshortcodesloopfunction() {
$alltheshortcodes = '';
$alltheshortcodes = 'thistextshouldbehere4times';
for($i=0; $i < 4; $i++) {
echo '<p></p>';
return $alltheshortcodes;
}
}
How this looks:
enter image description here
how it looks with echo: enter image description here
Maybe you can post a Thread which I could not find to solve this problem.
Some Tags for People in the future with this problem. That they can find this:
loop, while, if, return, statement, content, breaks up, just one time, only 1 time
A: Return exits the function, you can't have it in the loop. Store it separately and then reuse the function.
function allmyshortcodesloopfunction() {
$output = '';
$alltheshortcodes = 'thistextshouldbehere4times';
for ($i=0; $i < 4; $i++) {
$output .= "<p>$alltheshortcodes</p>";
}
return $output;
}
A: function allmyshortcodesloopfunction() {
$alltheshortcodes = 'thistextshouldbehere4times';
for ($i = 0; $i < 4; $i++) {
echo "<p>$alltheshortcodes</p>";
}
}
allmyshortcodesloopfunction();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58662618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use ffmpeg to save only the last 60 secs recorded? I'm trying to figure out a way to use ffmpeg command to save only the last 60 seconds recorded.
The way I'm doing it now is using a thread to record 60 seconds videos, and then merge the last two videos and cut the last 60 seconds (using the -t command), the method I'm trying to achieve should not save multiple videos and then merge and cut.
Below the command I'm using:
ffmpeg -sseof 60 -i "\PATH\TO\VIDEO" -c copy "\PATH\TO\OUTPUT"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69178757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Test instrumentation process crashed - where is the .txt file? Sometimes, while Espresso testing, I see the following exception.
Test instrumentation process crashed. Check package_name.TestName#methodName.txt for details
Where is this .txt file stored? I can't seem to find it anywhere.
Use Case
In Jenkins (CI), I want the logs to see exactly what stacktrace caused the crash.
A: In my case, it was simpler to just check Logcat, rather than listen to that recommendation
A: For others encountering this issue, as @antek pointed out the files might not be accessible on a non-rooted device. You might try using an emulator running a non-Google Play API where you can obtain a root shell.
adb root
adb shell
ls /data/data/androidx.test.orchestrator/files
Alternatively, you could try running the tests using the debugger.
A: I could not find the text file, but I was able to get logcat and view the fatal that caused the orchestrator to crash
first I clear the logcat
adb logcat -c
then I run the test, then I grab the logcat
adb logcat > ~/Desktop/logcat
then I open logcat file and search for string FATAL
A: If you are working with an emulator, in A.S open Device File Explorer and go to:
/data/user_de/0/android.support.test.orchestrator/files/, then you can look for a particular file there
EDIT: June 25 - 2019 >> If you have updated to AndroidX dependencies, then the .txt file is located in
/data/user_de/0/androidx.test.orchestrator/files/
A: *
*I just did wipe data in Android studio for my emulator using Device manager.
*Restarted the emulator and run the test works for me
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49985720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: m2e default lifecycle when adding webapp to tomcat server I'm using m2eclipse for a while, and I suddenly ask myself this very basic question:
Which maven phases are part of the lifecycle when I drag and drop a webapp into my tomcat server?
I assume it must be something like "clean package" PLUS a deployment of the package into the tomcat webapp directory.
But I can't find an article defining it precisely.
Also, is this default behaviour overridable?
Am I totaly wrong?
Thanks in advance!
A: You're right - you will typicaly go through (regardless of whether you use the m2eclipse or the commandline version)
*
*the clean lifeycle (refer to the standard phases in this lifecycle here)
*the default lifeycle, particularly the phases from validate thru package (again, refer to the standard phases in this lifecycle here)
by running
mvn clean package
Quoting the doc further (emphasis mine),
Some phases have goals bound to them by default. And for the default
lifecycle, these bindings depend on the packaging value (which in your
case should be war).
So the maven-war-plugin handles the packaging for you to deploy (not to be confused with the Maven deploy) it to a tomcat instance in your case.
Although you will usually want to install it to your local m2 repository and deploy it to a remote m2 repository for the artifact (*.war) to be available in environments other than your local. For that, you will want to go further into the default lifecycle depending on your need.
Also, the tomcat7-maven-plugin can help you deploy the artifact on any tomcat server, you will just need to attach the right goal to the appropriate phase. Read more about the use of the plugin here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30403197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is Auth::attempt always returns false in Laravel 5.3? I'm new in Laravel. I try to use Multiple Auth in Laravel 5.3 and my auth.php file is:
<?php
return [
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'courier' => [
'driver' => 'session',
'provider' => 'couriers',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
]
],
'providers' => [
'couriers' => [
'driver' => 'eloquent',
'model' => App\Courier::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
]
],
'passwords' => [
'couriers' => [
'provider' => 'couriers',
'table' => 'password_resets',
'expire' => 60,
],
'clients' => [
'provider' => 'clients',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, when I store Clients or Couriers in the DB, I use bcrypt for password (Bring also use the function Hash::make() for passwords). For example, my model Courier is:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Courier extends Authenticatable
{
[..]
public function setPasswordAttribute($pass){
$this->attributes['password'] = bcrypt($pass);
}
[..]
}
And when update a courier, in my controller I have:
public function update(Request $request, $id) {
$fieldsCourier = $request->all();
$courier = Courier::find($id);
if( isset($fieldsCourier['password']) )
$fieldsCourier['password'] = bcrypt($fieldsCourier['password']);
if( $courier->update($fieldsCourier) )
$courier = Courier::find($id);
}
I have a method called authenticate but the method attempt always return false (invalid_credentials). Even so send valid credentials.. This is my code:
public function authenticate(Request $request) {
$credentials = $request->only('email', 'password');
try {
if ( auth()->guard('courier')->attempt($credentials) ){
$user = Auth::guard('courier')->user();
} else {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('user'));
}
I not know what I'm doing wrong. Anything am I doing wrong?
A: you have encrypt the password twice, on your model and controller.
just remove one of them
e.g: don't use bcrypt on your controller, because you have already use bcrypt on your model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40537013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JQuery - Iterate a collection of value I have a collection of data:
q: "5,1,3,4"
I need to get those values and so I can have checkbox preselected
$('input[data-value=5]').prop('checked', true);
$('input[data-value=1]').prop('checked', true);
$('input[data-value=3]').prop('checked', true);
$('input[data-value=4]').prop('checked', true);
I know using index like q[0] could work, but is there any way that no need to hardcode it? Because I don't know how many values will be in this collection.
Can anyone help me with this??
Thanks a lot!!
A: Split q to an array with comma and loop through each value to select the input you want and change the prop
q.split(",").forEach(function(value){
$('input[data-value='+ value +']').prop('checked', true);
})
A: You can use a simple .each() loop to achieve this with jQuery, or Array.prototype.foreach() in vanilla JavaScript.
If you actually have a string of numbers to start off with, you'll need to split them out into an array by running .split() on the comma.
This can be seen in the following example:
// If you have a string rather than an array
const q = "5,1,3,4";
const values = q.split(",");
// If you start with an array
//const values = [5, 1, 3, 4];
$(values).each(function(index, value) {
$('input[data-value=' + value + ']').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-value="1">
<input type="checkbox" data-value="2">
<input type="checkbox" data-value="3">
<input type="checkbox" data-value="4">
<input type="checkbox" data-value="5">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49972979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to implement PaintCode project into SKScene In my app I'd like to implement a circle made with PaintCode (Stylekit) in SKScene.
This is my code:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
StyleKit.drawCanvas1()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
}
}
How can I resolve this problem?
A: you might build the SKSpriteNode in this way:
func makeCircle(width:CGFloat = 200, height:CGFloat = 200) -> SKSpriteNode? {
let size = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
StyleKit.drawCircle(frame: CGRect(origin: .zero, size: size), resizing: .AspectFit)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let safeImage = image {
return SKSpriteNode(texture: SKTexture(image: safeImage))
} else {
return nil
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47871075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Spotipy Audio Features - get track name from uri Spotify's audio features endpoint returns requests like so:
{ audio_features:
[ { "danceability": 0.808,
"energy": 0.626,
"key": 7,
"loudness": -12.733,
"mode": 1,
"speechiness": 0.168,
"acousticness": 0.00187,
"instrumentalness": 0.159,
"liveness": 0.376,
"valence": 0.369,
"tempo": 123.99,
"type": "audio_features",
"id": "4JpKVNYnVcJ8tuMKjAj50A",
"uri": "spotify:track:4JpKVNYnVcJ8tuMKjAj50A",
"track_href": "https://api.spotify.com/v1/tracks/4JpKVNYnVcJ8tuMKjAj50A",
"analysis_url": "http://echonest-analysis.s3.amazonaws.com/TR/WhpYUARk1kNJ_qP0AdKGcDDFKOQTTgsOoINrqyPQjkUnbteuuBiyj_u94iFCSGzdxGiwqQ6d77f4QLL_8=/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1458063189&Signature=JRE8SDZStpNOdUsPN/PoS49FMtQ%3D",
"duration_ms": 535223,
"time_signature": 4
},
I would like to print tracks names along with a given feature under a condition, like so:
features = show_audio_features(artist)
low_energy_songs = [x['energy'] for x in features if x < 0.5]
how do I print song names + parameters, instead of printing its url?
must I make a request to another endpoint?
thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38839866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Single page calendarview I am trying to develop a calendar application which displays all the months in a year in a single activity .I am having troubles with it . This is the view that i want to make . I am so lost :/
ListViewAdapter:
package com.example.calendar15;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class CalendarListAdapter extends BaseAdapter {
private Context mContext;
String[] months;
public String[] numbers;
// Constructor
public CalendarListAdapter(Context c,String[] months) {
mContext = c;
this.months=months;
}
public int getCount() {
return months.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid, parent, false);
}
// Lookup view for data population
TextView tvTitle = (TextView) convertView.findViewById(R.id.date);
Log.d("months[position]",""+months[position]);
tvTitle.setText(months[position]);
/**/
String[] numbers = { "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12"};
/*TextView tvDate1 = (TextView) convertView.findViewById(R.id.text1);
Log.d("numbers[position]",""+numbers[position]);
tvDate1.setText(numbers[position]);*/
GridView gridview = (GridView)convertView.findViewById(R.id.gridview);
CalendarGridAdapter calendarGridAdapter = new CalendarGridAdapter(mContext, numbers);
gridview.setAdapter(calendarGridAdapter);
return convertView;
}
}
GridViewAdapter:
package com.example.calendar15;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CalendarGridAdapter extends BaseAdapter {
Context mContext;
String[] number;
CalendarGridAdapter(Context context, String[] numbers) {
this.mContext = context;
this.number = numbers;
Log.d("number.length",""+number.length);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return number.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return number[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.calendar_item, parent, false);
}
// Lookup view for data population
TextView tvTitle = (TextView) convertView.findViewById(R.id.date);
Log.d("number[position]",""+number[position]);
tvTitle.setText(number[position]);
return convertView;
}
}
Grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textSize="16sp"
android:gravity="center"
android:text="date"
android:textStyle="normal" />
<GridView
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:listSelector="@android:color/transparent"
android:numColumns="7"
android:stretchMode="columnWidth" />
</GridLayout>
calendar_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Datelayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center"
android:orientation="vertical"
android:padding="2dip" >
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="date"
android:textColor="#727272"
android:textSize="16sp"
android:textStyle="normal" >
</TextView>
</LinearLayout>
A: Solution
I changed the height of Gridview from wrap_content and set it about 200dp - the height of elements to be inflated multiplied by total no of rows. (you could set it dynamically or in the xml as per your requirements ). I hope this helps others as well
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27982509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to ignore lines starting with a string with diff? How can I diff two files and ignore lines starting with a sequence.
E.g
File1:
abc
def
time:123
File2:
igh
def
time:345
With unix diff it will report
<time:123
>time:345
I want to ignore this diff. Any ideas?
A: How about: diff -I '^time.*' file1 file2?
Please note it doesn't always work as expected as per diffutils manual:
However, -I only ignores the insertion or deletion of lines that contain the regular expression if every changed line in the hunk (every insertion and every deletion) matches the regular expression.
In other words, for each non-ignorable change, diff prints the complete set of changes in its vicinity, including the ignorable ones. You can specify more than one regular expression for lines to ignore by using more than one -I option. diff tries to match each line against each regular expression, starting with the last one given.
A: What about this?
diff <(grep -v '^time:' file1) <(grep -v '^time:' file2)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2747091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: How to join surfaces together to form a 3D image in Python? I wish to achieve something very similar to this question: How to join these two 3D lines together with a surface in Python's matplotlib
There is an answer towards the bottom which is exactly the picture I would like to obtain, however, the surfaces I am dealing with are arbitrary and as a result I am unable to parametrize them. I have multiple 2D curves (each at a specific z level) and I wish to "connect" these, in part so it is visually obvious when the "width" of one closed surface is increasing as z increases.
Does anyone know how I might achieve this? Thanks.
A: I'm not sure if this is want you want but if you want to project two 2d-profiles of the 3d-surface you can use offset=z in the contour plot, where z is where in the z-axes you want to plot the profiles. Here is an example: https://matplotlib.org/3.3.1/gallery/mplot3d/contour3d_3.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64730731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass pendingInent in Intent.putExtra; to start pendingIntent from anotherActivty I'm trying a start a UI activity from the NotificationListiner service,Then In UI
when user clicks on yes: perform pendingIntent();else: finish()
I tried to achieve the above with Dialog,AlertDialog but since NotificationListiner was a background service it didn't work.
Then made a new Activity;
Tried with Gson
SbnContainer.kt
class SbnContainer {
lateinit var notification: Notification
lateinit var title: String
lateinit var desc: String
constructor(){
Log.d("TAG", "Salaam")
}
constructor(notification: Notification, title:String, desc:String){
this.notification = notification
this.title= title
this.desc = desc
}
}
Calling From NotificationService
var i = Intent(this,CAlertWindow::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val gson = Gson()
var a = SbnContainer(sbn.notification, title, desc)
val myJson = gson.toJson(a)
i.putExtra("PACKAGE", myJson)
startActivity(i)
Receiving from CAlertWindow(AppCompatActivity)
val gson = Gson()
val ob: SbnContainer = gson.fromJson(intent.getStringExtra("PACKAGE"), SbnContainer::class.java)
pendingIntent = ob.notification.contentIntent
alertWindowLayoutBinding.alrTitle.text = ob.title
alertWindowLayoutBinding.alrDesc.text = ob.desc
Log.d("Abdx79/AlertWindow", "In Alert Window")
alertWindowLayoutBinding.alrOpnB.setOnClickListener {
pendingIntent.send()
}
alertWindowLayoutBinding.alrDntB.setOnClickListener {
finish()
}
Error on calling startActivity(i)
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abdx79.notifications_manager/com.abdx79.notifications_manager.CAlertWindow}: java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.CharSequence. Registering an InstanceCreator with Gson for this type may fix this problem.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.CharSequence. Registering an InstanceCreator with Gson for this type may fix this problem.
So how can I solve this.?
A: You can use Serializable for passing a object like ->
class Shop(
val name: String,
val details: String?,
val id: Int,
):Serializable
now pass this Shop class like
var shop = Shop("name","details",1)
val intent = Intent(this, AnotherActivity::class.java).putExtra(
"SHOP",
shop
)
startActivity(intent)
now receive this shop class from another activity
val shope = intent.getSerializableExtra("SHOP") as Shop
you can also use Parcelable instead of Serializable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70254569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do zipkin do to merge span for search trace request? In the zipkin web ui, when the request url is http://10.19.138.169:9411/zipkin/api/v1/trace/ae60bd175a61e820
I find the return response is
[
{
"traceId": "ae60bd175a61e820",
"id": "ae60bd175a61e820",
"name": "client",
"timestamp": 1511858133224433,
"duration": 508444,
"binaryAnnotations": [
{
"key": "lc",
"value": "",
"endpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "19d69c3e93bc9040",
"name": "post",
"parentId": "ae60bd175a61e820",
"timestamp": 1511858133239803,
"duration": 490921,
"annotations": [
{
"timestamp": 1511858133239803,
"value": "cs",
"endpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133383290,
"value": "sr",
"endpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133609368,
"value": "ss",
"endpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133730724,
"value": "cr",
"endpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
}
],
"binaryAnnotations": [
{
"key": "ca",
"value": true,
"endpoint": {
"serviceName": "",
"ipv4": "127.0.0.1",
"port": 43928
}
},
{
"key": "http.path",
"value": "/security/gateway",
"endpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"key": "http.path",
"value": "/security/gateway",
"endpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
},
{
"key": "sa",
"value": true,
"endpoint": {
"serviceName": "",
"ipv4": "127.0.0.1",
"port": 8090
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "16eefe087852af41",
"name": "ennmonitorsecuritygatewayserver/put",
"parentId": "19d69c3e93bc9040",
"timestamp": 1511858133393425,
"duration": 212916,
"annotations": [
{
"timestamp": 1511858133393425,
"value": "cs",
"endpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133588237,
"value": "sr",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133593907,
"value": "ss",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133606341,
"value": "cr",
"endpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "8ef78f0edefe3a4b",
"name": "data enqueue",
"parentId": "16eefe087852af41",
"timestamp": 1511858133592958,
"duration": 129,
"binaryAnnotations": [
{
"key": "lc",
"value": "",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "97c637bcc891b86a",
"name": "data dequeue, send to kafka",
"parentId": "16eefe087852af41",
"timestamp": 1511858133593147,
"duration": 2416,
"binaryAnnotations": [
{
"key": "lc",
"value": "",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "f193c7f4193f2879",
"name": "",
"parentId": "16eefe087852af41",
"timestamp": 1511858133594113,
"duration": 7575,
"annotations": [
{
"timestamp": 1511858133594113,
"value": "ms",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133601688,
"value": "ws",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
}
],
"binaryAnnotations": [
{
"key": "kafka.topic",
"value": "rdkafka",
"endpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
}
]
},
{
"traceId": "ae60bd175a61e820",
"id": "54a3f6268df0aaee",
"name": "",
"parentId": "f193c7f4193f2879",
"timestamp": 1511858133600067,
"duration": 5,
"annotations": [
{
"timestamp": 1511858133600067,
"value": "wr",
"endpoint": {
"serviceName": "monitor-kafka-consumer",
"ipv4": "10.19.138.169"
}
},
{
"timestamp": 1511858133600072,
"value": "mr",
"endpoint": {
"serviceName": "monitor-kafka-consumer",
"ipv4": "10.19.138.169"
}
}
],
"binaryAnnotations": [
{
"key": "kafka.topic",
"value": "rdkafka",
"endpoint": {
"serviceName": "monitor-kafka-consumer",
"ipv4": "10.19.138.169"
}
}
]
}
]
It can easy to find that there are 8 spans.
When I use the api to get the trace with the same traceId
ElasticsearchStorage storage = ElasticsearchStorage.newBuilder()
.hosts(Arrays.asList("http://10.19.138.169:9200")).build();
List<Span> trace = null;
try {
trace = storage.spanStore().getTrace(traceId).execute();
} catch (IOException e) {
e.printStackTrace();
}
I get
[
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "97c637bcc891b86a",
"name": "data dequeue, send to kafka",
"timestamp": 1511858133593147,
"duration": 2416,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"id": "ae60bd175a61e820",
"name": "client",
"timestamp": 1511858133224433,
"duration": 508444,
"localEndpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "f193c7f4193f2879",
"id": "54a3f6268df0aaee",
"kind": "CONSUMER",
"timestamp": 1511858133600067,
"duration": 5,
"localEndpoint": {
"serviceName": "monitor-kafka-consumer",
"ipv4": "10.19.138.169"
},
"tags": {
"kafka.topic": "rdkafka"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "ae60bd175a61e820",
"id": "19d69c3e93bc9040",
"kind": "SERVER",
"name": "post",
"timestamp": 1511858133383290,
"duration": 226078,
"localEndpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
},
"remoteEndpoint": {
"ipv4": "127.0.0.1",
"port": 43928
},
"tags": {
"http.path": "/security/gateway"
},
"shared": true
},
{
"traceId": "ae60bd175a61e820",
"parentId": "19d69c3e93bc9040",
"id": "16eefe087852af41",
"kind": "CLIENT",
"name": "ennmonitorsecuritygatewayserver/put",
"timestamp": 1511858133393425,
"duration": 212916,
"localEndpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "19d69c3e93bc9040",
"id": "16eefe087852af41",
"kind": "SERVER",
"name": "ennmonitorsecuritygatewayserver/put",
"timestamp": 1511858133588237,
"duration": 5670,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
},
"shared": true
},
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "f193c7f4193f2879",
"kind": "PRODUCER",
"timestamp": 1511858133594113,
"duration": 7575,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
},
"tags": {
"kafka.topic": "rdkafka"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "ae60bd175a61e820",
"id": "19d69c3e93bc9040",
"kind": "CLIENT",
"name": "post",
"timestamp": 1511858133239803,
"duration": 490921,
"localEndpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
},
"remoteEndpoint": {
"ipv4": "127.0.0.1",
"port": 8090
},
"tags": {
"http.path": "/security/gateway"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "ae60bd175a61e820",
"id": "19d69c3e93bc9040",
"kind": "SERVER",
"name": "post",
"timestamp": 1511858133383290,
"duration": 226078,
"localEndpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
},
"remoteEndpoint": {
"ipv4": "127.0.0.1",
"port": 43928
},
"tags": {
"http.path": "/security/gateway"
},
"shared": true
},
{
"traceId": "ae60bd175a61e820",
"parentId": "19d69c3e93bc9040",
"id": "16eefe087852af41",
"kind": "SERVER",
"name": "ennmonitorsecuritygatewayserver/put",
"timestamp": 1511858133588237,
"duration": 5670,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
},
"shared": true
},
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "97c637bcc891b86a",
"name": "data dequeue, send to kafka",
"timestamp": 1511858133593147,
"duration": 2416,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "f193c7f4193f2879",
"kind": "PRODUCER",
"timestamp": 1511858133594113,
"duration": 7575,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
},
"tags": {
"kafka.topic": "rdkafka"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "19d69c3e93bc9040",
"id": "16eefe087852af41",
"kind": "CLIENT",
"name": "ennmonitorsecuritygatewayserver/put",
"timestamp": 1511858133393425,
"duration": 212916,
"localEndpoint": {
"serviceName": "monitor-gw-web",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "ae60bd175a61e820",
"id": "19d69c3e93bc9040",
"kind": "CLIENT",
"name": "post",
"timestamp": 1511858133239803,
"duration": 490921,
"localEndpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
},
"remoteEndpoint": {
"ipv4": "127.0.0.1",
"port": 8090
},
"tags": {
"http.path": "/security/gateway"
}
},
{
"traceId": "ae60bd175a61e820",
"id": "ae60bd175a61e820",
"name": "client",
"timestamp": 1511858133224433,
"duration": 508444,
"localEndpoint": {
"serviceName": "monitor-gw-http-c",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "f193c7f4193f2879",
"id": "54a3f6268df0aaee",
"kind": "CONSUMER",
"timestamp": 1511858133600067,
"duration": 5,
"localEndpoint": {
"serviceName": "monitor-kafka-consumer",
"ipv4": "10.19.138.169"
},
"tags": {
"kafka.topic": "rdkafka"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "8ef78f0edefe3a4b",
"name": "data enqueue",
"timestamp": 1511858133592958,
"duration": 129,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
},
{
"traceId": "ae60bd175a61e820",
"parentId": "16eefe087852af41",
"id": "8ef78f0edefe3a4b",
"name": "data enqueue",
"timestamp": 1511858133592958,
"duration": 129,
"localEndpoint": {
"serviceName": "monitor-gw-s",
"ipv4": "10.19.138.169"
}
}
]
It is easy to find that there are 18 spans.
It seems that some of spans are merged in the web request, I want to know to where is the cource code deal this.
Thanks!
A: The first request uses v1 of the Zipkin api while the second uses v2 (see https://github.com/openzipkin/zipkin/issues/1499 for the v2 specification). Spans are broken up by kind (SERVER and CLIENT) instead of having client receive, server receive, client send, and server send annotations (hence why there are more spans).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48160588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Web-scraping for a specific class of tag I am attempting to draw financial data from the Australian stock exchange (ASX). Specifically, the share registry for a particular company.
The website would be something like this (I say something because the ticker in the URL would change from firm to firm).
The HTML snippet I am looking at is:
<td class="ng-binding">COMPUTERSHARE INVESTOR SERVICES PTY LIMITED
<br>Yarra Falls, 452 Johnston Street, ABBOTSFORD, VIC, AUSTRALIA, 3067</td>
My overarching goal is to create a spreadsheet whereby I would have a list of Ticker Symbols and a macro would take that symbol, place it in the url and draw the adjacent Share Registry value into Excel. (In this case, COMPUTERSHARE INVESTOR SERVICES PTY LIMITED)
I tried to figure out how to use a variable url (I believe it involves Concatenation) and draw financial tables from websites.
I've settled on this tutorial that doesn't post the results into Excel, just presents it in a box. If I can results to post in the box that'll be a great first step.
Many tutorials use the IE object and from what I can gather, the use of XMLHttpRequest is far more efficient and nimble and considering I would have a large number of ticker symbols, would probably be best to use with regards to time.
Sub Get_Web_Data()
' TeachExcel.com
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim price As Variant
' Website to go to.
website = "https://www.asx.com.au/asx/share-price-research/company/BFG/details"
' Create the object that will make the webpage request.
Set request = CreateObject("MSXML2.XMLHTTP")
' Where to go and how to go there - probably don't need to change this.
request.Open "GET", website, False
' Get fresh data.
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
' Send the request for the webpage.
request.send
' Get the webpage response data into a variable.
response = StrConv(request.responseBody, vbUnicode)
' Put the webpage into an html object to make data references easier.
html.body.innerHTML = response
' Get the price from the specified element on the page.
price = html.getElementsByClassName("disclaimer disclaimer-company-info").Item(0).innerText
' Output the price into a message box.
MsgBox price
End Sub
I edited the code to present the only HTML class element that seems to be working for me, which is the disclaimer info at the bottom of the page. I gather that the use of html.getElementsByClassName is wrong in my scenario.
I have read that CSS Selectors might be applicable in this case and the use of 'children' (I think) as the info I am after (ng-binding) occurs numerous times throughout the table, so I gather I would need to direct the macro to select the nth instance.
I do not expect a completely written extract. Any hints and tips to point me in the right direction?
A: How about this?
Sub Web_Table_Option_Two()
Dim HTMLDoc As New HTMLDocument
Dim objTable As Object
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long
Dim objIE As InternetExplorer
Set objIE = New InternetExplorer
objIE.Navigate "https://www.asx.com.au/asx/share-price-research/company/BFG/details"
Do Until objIE.ReadyState = 4 And Not objIE.Busy
DoEvents
Loop
Application.Wait (Now + TimeValue("0:00:03")) 'wait for java script to load
HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
With HTMLDoc.body
Set objTable = .getElementsByTagName("table")
For lngTable = 0 To objTable.Length - 1
For lngRow = 0 To objTable(lngTable).Rows.Length - 1
For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
ThisWorkbook.Sheets("Sheet1").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
Next lngCol
Next lngRow
ActRw = ActRw + objTable(lngTable).Rows.Length + 1
Next lngTable
End With
objIE.Quit
End Sub
If you want to specify the row, you can do that, and just grab the row number that you want/need.
Finally, if you want to loop through an array of stock tickers, use the code below.
Sub Web_Table_Option_Two()
Dim HTMLDoc As New HTMLDocument
Dim objTable As Object
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long
Dim objIE As InternetExplorer
Set objIE = New InternetExplorer
Dim c As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Set sht = wb.Sheets("Stocks")
'find last used row in ColumnA
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
For Each c In Range("A2:A" & LastRow)
mystock = c.Value
objIE.Navigate "https://www.asx.com.au/asx/share-price-research/company/" & mystock & "/details"
Do Until objIE.ReadyState = 4 And Not objIE.Busy
DoEvents
Loop
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = mystock
ActRw = 1
Application.Wait (Now + TimeValue("0:00:01")) 'wait for java script to load
HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
With HTMLDoc.body
Set objTable = .getElementsByTagName("table")
For lngTable = 0 To objTable.Length - 1
For lngRow = 0 To objTable(lngTable).Rows.Length - 1
For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
ThisWorkbook.ActiveSheet.Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
Next lngCol
Next lngRow
ActRw = ActRw + objTable(lngTable).Rows.Length + 1
Next lngTable
End With
Next c
objIE.Quit
End Sub
Before:
After:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61928306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot send email in perl For some reason I cannot send an email in perl. I checked my env path and sendmail path everything is correct. But I am not receiving the email.I am not entirely sure if I am missing something.
#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
print header;
print start_html("Results");
$ENV{PATH} = "/usr/sbin" ;
open (MAIL, "|/usr/sbin/sendmail -oi -t") or
&dienice("Can't fork for sendmail: $!\n");
my $recipient = "myusername\@gmail.com";
print MAIL "To: $recipient\n";
print MAIL "From: nobody\@cgi101.com\n" ;
print MAIL "Subject: Form Data\n\n";
foreach my $p (param()) {
print MAIL "$p = ", param($p), "\n";
}
close(MAIL);
print <<EndHTML;
<h2>Thank You</h2>
<p>Thank you for writing!</p>
<p>Return to our <a href="index.html">home page</a>.</p>
EndHTML
print end_html;
A: It's extremely hard to tell what the issue might be. I'm assuming mail works normally from the command prompt?
That said, have you tried MIME::Lite?
use MIME::Lite;
my $body = <<EndHTML;
<h2>Thank You</h2>
<p>Thank you for writing!</p>
<p>Return to our <a href="index.html">home page</a>.</p>
EndHTML
my $msg = MIME::Lite->new(
Type => 'text/html',
From => 'nobody@cgi101.com',
To => 'myusername@gmail.com',
Subject => 'Form Data',
Data => $body
);
$msg->send;
A: Impossible to give much help without knowing what errors you are getting. But it's 2014 and we can probably do a little better than talking directly to sendmail to send an email.
For email handling, you should probably be looking in the Email::* namespace on CPAN. In particular, Email::Sender is the recommended approach for sending email.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24521329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql server status change time THENUMBER NUMBER SYSMODTIME TYPE
ACTIM2816332 IM0540202 2014-11-18 09:17:53.000 Closed
ACTIM2806050 IM0540202 2014-11-13 15:11:29.000 Update
ACTIM2806051 IM0540202 2014-11-13 15:11:29.000 External Vendor Assignment
ACTIM2806049 IM0540202 2014-11-13 15:11:29.000 Status Change
ACTIM2806046 IM0540202 2014-11-13 15:10:34.000 Assignment
ACTIM2804167 IM0540202 2014-11-13 09:31:12.000 Status Change
ACTIM2804166 IM0540202 2014-11-13 09:31:12.000 Assignment
ACTIM2802130 IM0540202 2014-11-12 17:09:57.000 Open
Could You please help me to create a select to calculate time difference between type change from open to close ?
I need to be a universal for different NUMBER.
A: Minutes
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (mi, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER
Hours
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (hh, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27124711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to make hover effect only on hamburger button, not on close button? I have a problem with the following code :
.btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
How to make this hover code only work in the state of the hamburger button, not on the close button?
$('.btn-menu').on('click', function() {
$('body').toggleClass('menu-open');
});
.btn-menu {
display: flex;
align-items: center;
justify-content: center;
min-height: 38px;
padding-left: 0;
padding-right: 0;
border: none;
background-color: transparent;
color: inherit;
cursor: pointer;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
position: relative;
width: 40px;
height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
transform: translate(0, -5px);
}
.btn-menu__bars:after {
transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
transform: rotate(-45deg);
}
/* How to make this only on burger, not on close */
.btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-menu" type="button" style="background-color: red;">
<i class="btn-menu__bars" aria-hidden="true"></i>
</button>
A: Because you add .menu-open to the body, you need to apply the hover effect when the body doesn't have the class with :not.
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
$('.btn-menu').on('click', function() {
$('body').toggleClass('menu-open');
});
.btn-menu {
display: flex;
align-items: center;
justify-content: center;
min-height: 38px;
padding-left: 0;
padding-right: 0;
border: none;
background-color: transparent;
color: inherit;
cursor: pointer;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
position: relative;
width: 40px;
height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
transform: translate(0, -5px);
}
.btn-menu__bars:after {
transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
transform: rotate(-45deg);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-menu" type="button" style="background-color: red;">
<i class="btn-menu__bars" aria-hidden="true"></i>
</button>
Also your script without JQuery :
document.querySelector(".btn-menu").addEventListener("click", () => {
document.querySelector("body").classList.toggle("menu-open")
})
document.querySelector(".btn-menu").addEventListener("click", () => {
document.querySelector("body").classList.toggle("menu-open")
})
.btn-menu {
display: flex;
align-items: center;
justify-content: center;
min-height: 38px;
padding-left: 0;
padding-right: 0;
border: none;
background-color: transparent;
color: inherit;
cursor: pointer;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
position: relative;
width: 40px;
height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
transform: translate(0, -5px);
}
.btn-menu__bars:after {
transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
transform: rotate(-45deg);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
transform: translateY(0.5875rem);
}
<button class="btn-menu" type="button" style="background-color: red;">
<i class="btn-menu__bars" aria-hidden="true"></i>
</button>
Note that if you only have 1 element with a class, you can use an id (and then use getElementById() instead).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72911325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Support for ',' in input type="number" in IE 11 using Angular + material I need to accept 10,12 as a valid number in IE 11 because the users only have a German number pad as an input device which only has a comma as a decimal separator.
The current behavior is (userinput -> value used)
10,12 -> 10
The desired behavior is
10,12 -> 10.12
10.12 -> 10.12
As it is currently in Chrome.
My current idea is to implement a ControlValueAccessor for an input type="text" which parses the value into a number, but my attempts for that failed.
The input has to work with reactiveForms and has to be a numeric value
A: I encountered the same problem and was not able to get a comma as the decimal separator with <input type="number"> even when setting the language to a different locale and using a step smaller than 1:
<input type="number" step="0.01" lang="en-US">
So I opted for a custom solution based on <input type="text"> with a custom filtering mechanism to only allow numbers in.
See this stackblitz for a complete demo.
The most important part is filtering what the user inputs in the field. I suggest you write a directive that listens to input/keydown/paste events and that uses a regex to only allow float/integer numbers.
The following regex (/^-?\d*(,|\.)?\d*$/) allows a number to begin with an optional - followed by digits, then a comma or dot and more digits.
If the new value (current value + key pressed) does not match the regex, simply prevent the event from happening with event.preventDefault(). Otherwise, do nothing and let the value go to the input.
Note that you also have to take care of the copy/cut/paste/undo/redo special keys. And also take into account the cursor position and the selection if any.
Once the filtering is done, you can implement the ControlValueAccessor interface and bind it to your input via its change/input events. Do the string to number conversions in these handlers and do the number to string conversion in a getter or a pipe that you bind to the value attribute.
Here is an example of such a directive, you could generalize it by giving the regex as an input parameter.
import { Directive, Input, HostListener, forwardRef } from '@angular/core';
@Directive({
selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
@HostListener('keydown', ['$event'])
public onKeydown(event: KeyboardEvent): void {
const { key } = event;
if (this.isSpecialOperation(event) || !this.isKeyPrintable(event)) {
return;
}
const newValue = this.getNewValue(event.target as HTMLInputElement, key);
if (!this.valueIsValid(newValue)) {
event.preventDefault();
}
}
@HostListener('paste', ['$event'])
public onPaste(event: ClipboardEvent): void {
const pastedText = event.clipboardData.getData('text');
const newValue = this.getNewValue(event.target as HTMLInputElement, pastedText);
if (!this.valueIsValid(newValue)) {
event.preventDefault();
}
}
private getNewValue(target: HTMLInputElement, str: string): string {
const { value = '', selectionStart, selectionEnd } = target;
return [
...value.split('').splice(0, selectionStart),
str,
...value.split('').splice(selectionEnd)].join('');
}
private valueIsValid(value: string): boolean {
return /^-?\d*(,|\.)?\d*$/.test(value);
}
private isSpecialOperation(event: KeyboardEvent): boolean {
const { keyCode, ctrlKey, metaKey } = event;
// allow ctr-A/C/V/X/Y/Z
const keysACVXYZ = [65, 67, 86, 88, 89, 90];
if ((ctrlKey || metaKey) && keysACVXYZ.indexOf(keyCode) >= 0) {
return true;
}
return false;
}
private isKeyPrintable(event: KeyboardEvent): boolean {
const { keyCode } = event;
return (
(keyCode > 47 && keyCode < 58) || // number keys
keyCode === 32 || keyCode === 13 || // spacebar & return key(s)
(keyCode > 64 && keyCode < 91) || // letter keys
(keyCode > 95 && keyCode < 112) || // numpad keys
(keyCode > 185 && keyCode < 193) || // ;=,-./` (in order)
(keyCode > 218 && keyCode < 223)); // [\]' (in order)
}
}
And a custom input-number component implementing ControlValueAccessor:
import { Component, ViewChild, forwardRef, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Component({
selector: 'app-input-number',
template: `
<input
type="text"
#input
appNumberOnly
[placeholder]="placeholder"
[value]="_stringifiedValue"
(input)="_onInput($event.target.value)"
(change)="_onChange($event.target.value)"
(blur)="input.value = _stringifiedValue">
`,
styles: [`
:host { width: 100%; display: block; }
input { width: 100%; }
`],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputNumberComponent),
multi: true
}
]
})
export class InputNumberComponent implements ControlValueAccessor {
private onChange = [(_: number) => {}];
private onTouch = [() => {}];
@Input() placeholder;
@ViewChild('input') _input: ElementRef;
@Input()
get value(): number {
return this._value;
}
set value(value: number) {
const safeValue = this.safeValue(value);
if (safeValue !== this._value) {
this._value = safeValue;
this.onChange.forEach(fn => fn(safeValue));
}
}
private _value: number = undefined;
@Output() valueChange = new EventEmitter<number>();
get _stringifiedValue(): string {
const val = (this._input.nativeElement.value || '').replace('.', ',');
if (val === '-' || val === ',') return val;
const safeValue = this.safeValue(this.value);
return this.stringify(safeValue).replace('.', ',');
}
_onInput(value: string): void {
this.value = this.safeValue(value);
}
_onChange(value: string): void {
this.value = this.safeValue(value);
this.valueChange.emit(this.value);
}
private safeValue(val: string | number): number {
const safeValue = parseFloat(this.stringify(val).replace(',', '.'));
return isNaN(safeValue) ? undefined : safeValue;
}
private stringify(val: string | number): string {
return val === undefined || val === null ? '' : `${val}`;
}
public registerOnChange(fn: any): void {
this.onChange.push(fn);
}
public registerOnTouched(fn: any): void {
this.onTouch.push(fn);
}
public writeValue(inputValue: number): void {
this.value = this.safeValue(inputValue);
}
}
The component can then be used with two-way binding with [(ngModel)] or with [(value)]. It will work with reactive-forms too:
<app-input-number [(ngModel)]="value"></app-input-number>
<app-input-number [(value)]="value"></app-input-number>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55194822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove portion of text using GetElementsByClassName I'm trying to use the following script to remove ".00" from all prices on a page I'm working on. The ".00" is built in automatically by the WP theme I'm working with.
Here's the script I'm using:
<script>
window.onload = function() {
var str = document.getElementsByClassName("hungry-menu-item-price").innerHTML;
var res = str.replace(".00", "");
document.getElementsByClassName("hungry-menu-item-price").innerHTML = res;
}
</script>
The prices are formatted as such:
<h4 class="hungry-menu-item-price">$24.00</p>
...but it's not working. What am I missing?
A: getElementsByClassName returns a HTMLCollection. You must iterate it:
var elements = document.getElementsByClassName("hungry-menu-item-price");
for(var i=0; i<elements.length; ++i)
elements[i].textContent = elements[i].textContent.replace(".00", "");
<p class="hungry-menu-item-price">$24.00</p>
A: document.getElementsByClassName() function returns a nodeList, not an element
so it must be :
document.getElementsByClassName('hungry-menu-item-price')[0].innerHTML
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30263267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Do I need to send the data in $.ajax as json? I have an $.ajax request that's sending the data in a serialize() and gets a json array in return. It works perfectly without any issues on Chrome develop's tools and Firefox's firebug. My question is, do I HAVE to send the data(user inputs) as json? I need json for the response but not for the request.
A: No, you send the data however you like but keep in mind how you send it will affect how you can retrieve it.
Also you aren't sending JSON in your request as .serialize() does not return JSON it returns a text string in standard URL-encoded notation.
A: No, you don't need to send it as JSON. You can send it in any other format, but your receiver will need to know how to interpret it. Usually people use JSON or XML since your receiver can easily parse these types of data.
You'll need to set the content-type, then you can tell the receiver how to process this content-type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19128682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Activity crashes when paused I have an activity that keeps crashing onPause. Theres a looped thread that draws on a canvas. And When I paused the application or try to move to another activity it crashes.
I have it so it closes out onPause, because I don't want it to post a force close. But I want to be able to go back to the activity
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
boolean retry = true;
_canDraw = false;
while(retry) {
try {
DrawThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
android.os.Process.killProcess(android.os.Process.myPid());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.face_button:
_canDraw = false;
try {
DrawThread.join();
whack.this.startActivity(selectFace);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
A: @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
android.os.Process.killProcess(android.os.Process.myPid());
}
You're wondering why it crashes onPause? You're crashing it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5541835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Histogram computational efficiency I am trying to plot a 2 GB matrix using MATLAB hist on a computer with 4 GB RAM. The operation is taking hours. Are there ways to increase the performance of the computation, by pre-sorting the data, pre-determining bin sizes, breaking the data into smaller groups, deleting the raw data as the data is added to bins, etc?
Also, after the data is plotted, I need to adjust the binning to ensure the curve is smooth. This requires starting over and re-binning the raw data. I assume the strategy involving the least computation would be to first bin the data using very small bins and then manipulate the bin size of the output, rather than re-binning the raw data. What is the best way to adjust bin sizes post-binning (assuming the bin sizes can only grow and not shrink)?
A: I don't like answers to StackOverflow Questions of the form "well even though you asked how to do X, you don't really want to do X, you really want to do Y, so here's a solution to Y"
But that's what i am going to do here. I think such an answer is justified in this rare instance becuase the answer below is in accord with sound practices in statistical analysis and because it avoids the current problem in front of you which is crunching 4 GB of datda.
If you want to represent the distribution of a population using a non-parametric density estimator, and you wwish to avoid poor computational performance, a kernel density estimator (KDE) will do the job far better than a histogram.
To begin with, there's a clear preference for KDEs versus histograms among the majority of academic and practicing statisticians. Among the numerous texts on this topic, ne that i think is particularly good is An introduction to kernel density estimation )
Reasons why KDE is preferred to histogram
*
*the shape of a histogram is strongly influenced by the choice of
total number of bins; yet there is no authoritative technique for
calculating or even estimating a suitable value. (Any doubts about this, just plot a histogram from some data, then watch the entire shape of the histogram change as you adjust the number of bins.)
*the shape of the histogram is strongly influenced by the choice of
location of the bin edges.
*a histogram gives a density estimate that is not smooth.
KDE eliminates completely histogram properties 2 and 3. Although KDE doesn't produce a density estimate with discrete bins, an analogous parameter, "bandwidth" must still be supplied.
To calculate and plot a KDE, you need to pass in two parameter values along with your data:
kernel function: the most common options (all available in the MATLAB kde function) are: uniform, triangular, biweight, triweight, Epanechnikov, and normal. Among these, gaussian (normal) is probably most often used.
bandwith: the choice of value for bandwith will almost certainly have a huge effect on the quality of your KDE. Therefore, sophisticated computation platforms like MATLAB, R, etc. include utility functions (e.g., rusk function or MISE) to estimate bandwith given oother parameters.
KDE in MATLAB
kde.m is the function in MATLAB that implementes KDE:
[h, fhat, xgrid] = kde(x, 401);
Notice that bandwith and kernel are not supplied when calling kde.m. For bandwitdh: kde.m wraps a function for bandwidth selection; and for the kernel function, gaussian is used.
But will using KDE in place of a histogram solve or substantially eliminate the very slow performance given your 2 GB dataset?
It certainly should.
In your Question, you stated that the lagging performance occurred during plotting. A KDE does not require mapping of thousands (missions?) of data points a symbol, color, and specific location on a canvas--instead it plots a single smooth line. And because the entire data set doesn't need to be rendered one point at a time on the canvas, they don't need to be stored (in memory!) while the plot is created and rendered.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9725401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Collapse pandas DataFrame based on daily column value I have a pandas DataFrame with multiple measurements per day (for example hourly measurements, but that is not necessarily the case), but I want to keep only the hour for which a certain column is the daily minimum.
My one day in my data frame looks somewhat like this
DATE Value Distance
17 1979-1-2T00:00:00.0 15.5669870447436 34.87
18 1979-1-2T01:00:00.0 81.6306803714536 31.342
19 1979-1-2T02:00:00.0 83.1854759740486 33.264
20 1979-1-2T03:00:00.0 23.8659679630303 32.34
21 1979-1-2T04:00:00.0 63.2755504429306 31.973
22 1979-1-2T05:00:00.0 91.2129044773733 34.091
23 1979-1-2T06:00:00.0 76.493130052689 36.837
24 1979-1-2T07:00:00.0 63.5443183375785 34.383
25 1979-1-2T08:00:00.0 40.9255407683688 35.275
26 1979-1-2T09:00:00.0 54.5583051827551 32.152
27 1979-1-2T10:00:00.0 26.2690011881422 35.104
28 1979-1-2T11:00:00.0 71.3059740399097 37.28
29 1979-1-2T12:00:00.0 54.0111262724049 38.963
30 1979-1-2T13:00:00.0 91.3518048568241 36.696
31 1979-1-2T14:00:00.0 81.7651763485069 34.832
32 1979-1-2T15:00:00.0 90.5695814525067 35.473
33 1979-1-2T16:00:00.0 88.4550315358515 30.998
34 1979-1-2T17:00:00.0 41.6276969038137 32.353
35 1979-1-2T18:00:00.0 79.3818377264749 30.15
36 1979-1-2T19:00:00.0 79.1672568582629 37.07
37 1979-1-2T20:00:00.0 1.48337999844262 28.525
38 1979-1-2T21:00:00.0 87.9110385474789 38.323
39 1979-1-2T22:00:00.0 38.6646421460678 23.251
40 1979-1-2T23:00:00.0 88.4920153764757 31.236
I would like to keep all rows that have the minimum "distance" per day, so for the one day shown above, one would have only one row left (the one with index value 39). I know how to collapse the data frame so that I only have the Distance column left. I can do that - if I first set the DATE as index - with
df_short = df.groupby(df.index.floor('D'))["Distance"].min()
But I also want the Value column in my final result. How do I keep all columns?
It doesn't seem to work if I do
df_short = df.groupby(df.index.floor('D')).min(["Distance"])
This does keep all the columns in the final result, but it seems like the outcome is wrong, so I'm not sure what this does.
Maybe this is already posted somewhere, but I have trouble finding it.
A: You can use aggregate
df_short = df.groupby(df.index.floor('D')).agg({'Distance': min, 'Value': max})
If you want the kept Value column is the same with minimum of Distance column:
df_short = df.loc[df.groupby(df.index.floor('D'))['Distance'].idxmin(), :]
A: Make a datetime Index:
df.DATE = pd.to_datetime(df.DATE) # If not already datetime.
df.set_index('DATE', inplace=True)
Resample and find the min Distance's location:
df.loc[df.resample('D')['Distance'].idxmin()]
Output:
Value Distance
DATE
1979-01-02 22:00:00 38.664642 23.251
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72242097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: flutter web alternates/reduce size of canvaskit.wasm My flutter web initial page load is slow(10-15 secs),
Found that large amount of time is spent in downloading "https://unpkg.com/canvaskit-wasm@0.24.0/bin/canvaskit.wasm" which is around 2.5 MB as per browser logs.
Is there a way to reduce this time/alternate file path/ minification which can be done?
(package is built using flutter build web)
A: Changed web renderer to html renderer
flutter build web --web-renderer html
which resulted in significant reduction in initial load time
A: For the moment there is no solution for this, anyways the Flutter team is working on that and there should be a solution as soon as possible.
You can check the status of this in this link:
Flutter github issue
A: There is a possibility to integrate the canvaskit at build process and host it with your web app for offline support.
Therefore you need to define the url like:
flutter build web --dart-define=FLUTTER_WEB_CANVASKIT_URL=/canvaskit/
This may could also reduce loading time. (direct network connection, no dns lookup...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67417810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Python Script Erroring with argparse.ArgumentError I am running a python selenium script but it's getting an error of
https://i.stack.imgur.com/oQdvx.png
argparse.ArgumentError: argument --screenshot/--save_screenshot/--save-screenshot/--ss: conflicting option string: --screenshot
From reading, there seems to be a pytest-argument being defined in multiple locations. My install dependency step looks like this:
https://i.stack.imgur.com/XmXoe.png
Any recommendations on how to get rid of this to then execute the test?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73952253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome screen keyboard blocking content at bottom of page on mobile Here, I recorded video about problem.
https://www.youtube.com/watch?v=WZbKix3XGTE
Problem is when keyboard on screen. The content is behind of keyboard not reachable. If there is input end of page user can't see what is typing in it.
I have this issue only with chrome, other browsers work normal.
All solutions in my mind about this contains javascript. But I am not sure javascript handle this perfectly. I wanted to ask you knowledge before start. Is there any other option for this only with CSS or something else?
Code in example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=1" />
<title></title>
<style type="text/css">
#top {
background-color: lightgreen;
width: 100%;
height: 600px;
}
#bottom {
background-color: green;
height: auto;
padding: 20px;
margin-top: 10px;
}
#bottom > input {
display: block;
padding: 5px;
width: 100%;
}
</style>
</head>
<body>
<div id="top">Top</div>
<div id="bottom">
<input type="text" />
</div>
</body>
</html>
Codepen Link
https://codepen.io/hllktlhndd/pen/yZKzyZ
A: Did you get answer for this ?
This worked before okay, but now the android-chrome comes on top of the page and does not push it up anymore.
I'm using webview, maybe they have some option for it?
Quick fix is to add padding at the bottom of the screen, maybe 200 - 300px
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54619312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MongoDB StitchClient cannot be accessed inside a js function I have already called stClient.login function inside "addUser()" and "loginUser()" and they worked pretty well. I am able to add the user to my MongoDB database and find the user when login clicked. (dont bother with delete one) After finding a logged user in DB, i am loading a new HTML page where i pass the name of the logged user and profil photo retrieved from MongoDB. Besides, i also want to display the comments of the logged user along with the name and profil photo. Here the issue comes: in showComments method, i am not able to access the stitch Client. Any help is so much appreciated.
Below is the code:
Html 1:
<!DOCTYPE html>
<html>
<head>
<title>myFb</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig02.js"></script>
</head>
<body onload="onLoadConnectDB()">
<p>Hello My App</p>
<div id="wlcom" align="center">
<button name="adding" onclick="addUser()">Add User</button><br>
<button name="deleting" onclick="deleteUser()">Delete User</button> <br>
<button name="logging" onclick="loginUser()">Login</button><br>
</div>
</body>
</html>
Common JS for 2 HTMLs:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoadConnectDB(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
});
}
function addUser(){
var n= prompt("Your username: ")
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
// });
alert("added");
}
function deleteUser(){
var d= prompt("Username to delete: ");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.deleteOne({ userName: "Messi" })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
alert("User "+d+ " deleted.");
}
function loginUser(){
var n= prompt("Your username: ");
globalName=n;
const userId = stClient.authedId();
try{
stClient.login().then(()=>
itemsCollection.find({ userName : n }).execute()
).then(docs=>
loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
);
}catch(err){
alert("not found a user");
}
// });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
//document.getElementById("name").value=name;
}else{
//no user in db
alert(name+ " is not found");
}
}
function onLoad () {
//onLoadConnectDB();
var pic;
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
// document.getElementById('pp').value=data.pp;
}
function showComments(globalName){
//ISSUE IS HERE!!
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments + "</div>").join("")
);
};
HTML2
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="assig02.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments" onclick ="showComments()">
Show comments
</div>
</body>
</html>
A: The issue is relating to async/sync communication. After separating js for html2, i was calling onLoad2() function inside onLoad() function after assuming the connection is established, but no. Should 'wait' till the connection is established and then call another function. js2:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoad(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
onLoad2(); //if you call outside then, wont work. onLoad2() will be interpreted before establishing connection to db
});
}
function onLoad2 () {
var pic;
var url = window.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
}
function showComments(globalName){
console.log("i am here");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments.msg + "</div>").join(" ")
);
}
function addComment(){
var n=document.getElementById("name").value;
var com= document.getElementById("comment").value
stClient.login().then(()=>
itemsCollection.updateOne({userName : n}, {$push:{comments:{msg:com,time:"22:30",like:4}}})
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
}
HTML for the js2:
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig022.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments">
</div>
<br>
<input type="text" name="comment" id="comment" placeholder="Type comment">
<button onclick="addComment()">Send</button>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49840692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I cant import the ucf 101 dataset (torchvision), 'list index out of range' error dataset = torchvision.datasets.UCF101(r'my_directory', annotation_path=r'my_directory2', frames_per_clip=16, step_between_clips=1, frame_rate=None, fold=1, train=True, transform=transforms.Compose([transforms.ToTensor()]), _precomputed_metadata=None, num_workers=1, _video_width=64, _video_height=64, _video_min_dimension=0, _audio_samples=0)
This line works, the problem is when I try to do any kind of operation using 'dataset', in particular this one:
data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)
I get the error, so i can't work on the video data because I can't use the dataLoader, the error is:
IndexError: list index out of range
Complete error message:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-16-dc3631481cb3> in <module>
----> 1 data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)
~\anaconda3\lib\site-packages\torch\utils\data\dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context)
211 else: # map-style
212 if shuffle:
--> 213 sampler = RandomSampler(dataset)
214 else:
215 sampler = SequentialSampler(dataset)
~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in __init__(self, data_source, replacement, num_samples)
90 "since a random permute will be performed.")
91
---> 92 if not isinstance(self.num_samples, int) or self.num_samples <= 0:
93 raise ValueError("num_samples should be a positive integer "
94 "value, but got num_samples={}".format(self.num_samples))
~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in num_samples(self)
98 # dataset size might change at runtime
99 if self._num_samples is None:
--> 100 return len(self.data_source)
101 return self._num_samples
102
~\anaconda3\lib\site-packages\torchvision\datasets\ucf101.py in __len__(self)
96
97 def __len__(self):
---> 98 return self.video_clips.num_clips()
99
100 def __getitem__(self, idx):
~\anaconda3\lib\site-packages\torchvision\datasets\video_utils.py in num_clips(self)
241 Number of subclips that are available in the video list.
242 """
--> 243 return self.cumulative_sizes[-1]
244
245 def get_clip_location(self, idx):
IndexError: list index out of range
A: Problem:
This problem occurs when you run your code on windows because windows paths use backslash ("\") instead of forward slash ("/").
As you see in the code:
https://github.com/pytorch/vision/blob/7b9d30eb7c4d92490d9ac038a140398e0a690db6/torchvision/datasets/ucf101.py#L94
So, this line of code reads the file path from label file as “action\video_name” and merge it with “root” path using backslash therefore full path becomes like “root\action/video_name”. Such paths doesn’t match with the video lists at line#97 and returns empty list for indices variable.
Solution:
Two of possible solutions can be:
*
*Replace the forwardslashes “/” in the label files with backslashes “\”.
*Override the _select_fold(…) function of class UCF101 and fix the backslashes inside the function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61522539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get devise custom User columns to save? I am reading that the application controller needs to have a before filter: before_filter :configure_permitted_parameters, if: :devise_controller?
however, I am receiving this error:
undefined method `before_filter' for ApplicationController:Class Did
you mean? before_action
How can I get the new User fields added with a migration to save with devise?
A: Add new column in to your database
after In your ApplicationController.rb Add
before_action :configure_permitted_parameters, if: :devise_controller?
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys:[:profile_pic,:fname,:mobile,:gender])
end
Here use keys => your added fields
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45602331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why need to decrease clientHeight from windowHeight while calculating scrollPercent? I am trying to show how much a user has scrolled through the page a with progress bar and I have done it. But I have a little confusion here.
Here is the code that I found to calculate scrollPercent which works well
windowHeight = Math.max(
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
body.scrollHeight,
body.offsetHeight
);
const scrolledPercent =
((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
100;
Initially, I thought, to get the scrollPercent , I need to get the current scrollPosition and divide that number with the total height of the page and multiply by 100% . which is like normally how we get % of something.
const scrolledPercent =
((html.scrollTop || body.scrollTop) / windowHeight) * 100;
but this line doesnot worked as I expected . If I do this the progress bar wont reach 100% even if I scroll to end of the page. I don't understand why am I wrong here !
So, my question is why do we need to decrease the html.clientHeight from windowHeight ?
Thank you.
Demo here:
// --------------------------------------------
// variables
// --------------------------------------------
const html = document.documentElement,
body = document.body,
countryList = document.querySelector(".country__list");
scrollNavigated = document.querySelector(".scroll__navigated");
let windowHeight;
// --------------------------------------------
// function
// --------------------------------------------
async function prepareListOfCountries() {
let list = await fetch("https://restcountries.eu/rest/v2/all");
list = Array.from(await list.json());
let markup = list
.map((country, index) => {
return `<li class="country__item card">
<span class="country__name">${country.name}</span
><span class="country__capital">${country.capital}</span>
<a href="javascript:;" class="country__flag">
<img src= '${country.flag}'> </a>
</li>`;
})
.slice(0, 30)
.join(" ");
countryList.innerHTML = markup;
}
function updateScrolledStatus(e) {
windowHeight = Math.max(
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
body.scrollHeight,
body.offsetHeight
);
const scrolledPercent =
((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
100;
// const scrolledPercent =
// ((html.scrollTop || body.scrollTop) / windowHeight) * 100; // this line doesnot work
scrollNavigated.style.width = scrolledPercent + "%";
}
prepareListOfCountries();
// --------------------------------------------
// event-handler
// --------------------------------------------
window.addEventListener("scroll", updateScrolledStatus);
*::after,
*::before,
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #fff;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
.container {
max-width: 980px;
margin: 0 auto;
}
.justify-between {
display: flex;
align-items: center;
justify-content: space-between;
}
.items-center {
display: flex;
align-items: center;
}
.card {
background-color: #fff;
box-shadow: 0 0 12px 12px rgba(0, 0, 0, 0.054);
border-radius: 4px;
padding: 16px;
}
.country__flag img {
height: 100%;
width: 100%;
}
.header {
padding: 24px 0;
background-color: #333;
color: #f1f1f1;
position: -webkit-sticky;
position: sticky;
}
.content {
padding: 50px 0;
}
.content__form {
margin: 0 auto;
margin-bottom: 32px;
}
.content__search {
width: 50%;
padding: 12px 16px;
border-radius: 20px;
border: 1px solid #ddd;
transition: 0.2s;
}
.content__search:hover {
box-shadow: 0 1px 6px 0 rgba(32, 33, 36, 0.28);
}
.content__search:focus {
outline: none;
}
.country__list {
margin-top: 50px;
margin: 10px auto;
}
.country__item {
display: flex;
justify-content: space-between;
margin-bottom: 16px;
}
.country__name, .country__capital, .country__flag {
width: 33.33%;
}
.country__flag {
width: 32px;
height: 24px;
}
.scroll__navigator {
height: 2px;
margin: 0 auto 32px;
background-color: #333;
position: -webkit-sticky;
position: sticky;
top: 0;
}
.scroll__navigated {
display: block;
height: 100%;
width: 0;
background: orangered;
transition: 0.3s linear;
}
<body>
<header class="header">
<div class="container">
All countries list
</div>
</header>
<main class="content">
<div class="container">
<form class="content__form">
<input class="content__search" />
</form>
<div class="scroll__navigator">
<span class="scroll__navigated"></span>
</div>
<section class="country">
<ul class="country__list">
<li class="country__item card">
<span class="country__name">Nepal</span
><span class="country__capital">Kathmandu</span>
<a href="javascript:;" class="country__flag"></a>
</li>
</ul>
</section>
</div>
</main>
</body>
A: As an example, say that the height of your client is 100px and the height of your whole page is 500px.
When the scroll position is 0px, you're able to see the first 100px of your site, so from 0px to 100px.
At scroll position 100px, you can see the range 100px to 200px, because you've moved the page, and therefore the visible range, on by 100px.
At scroll position 400px, you can therefore see the range 400px to 500px – in other words, you've scrolled to the bottom.
This demonstrates that the scrollable height of the page (400px) is less than the actual height of the page (500px), namely by the height of the client.
To get the percentage scrolled, you need to use the scrollable height, so it is necessary to subtract the height of the client from the height of the page to get a correct value, or you'll never be able to scroll to the bottom. It's not possible to scroll by 500px on a site that is only 500px long!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61478766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: makefile fails - implicit rule compiles one object file but doesn't compile the rest Makefile isn't using implicit rules correctly. I am following this guide here.
Here's my makefile:
objects = main.o hello.o
hello : $(objects)
cc -o hello $(objects)
hello.o : defs.h
main.o : defs.h hello.h
.PHONY : clean
clean :
-rm hello $(objects)
I get the following error:
cc: error: main.o: No such file or directory
It creates the object code hello.o, but does not do it for main.c. If I swap lines and main is above, it'll create main.o but not hello.o.
Here's my main.c file:
#include "defs.h"
#include "hello.h"
int main(int argc, char** argv) {
display_hello();
return (EXIT_SUCCESS);
}
Here's my hello.c file:
#include "defs.h"
void display_hello()
{
printf("Hello!\n");
}
My hello.h file:
#ifndef HELLO_H
#define HELLO_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* HELLO_H */
void display_hello();
Here's my defs.h file:
#ifndef DEFS_H
#define DEFS_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* DEFS_H */
#include <stdio.h>
#include <stdlib.h>
A: Works fine for me, I created the files as https://gist.github.com/boyvinall/f23420215707fa3e73e21c3f9a5ff22b
$ make
cc -c -o main.o main.c
cc -c -o hello.o hello.c
cc -o hello main.o hello.o
Might be the version of make like @Beta said, but even an old version of GNU make should work just fine for this.
Otherwise, ensure you're using tabs to indent in the makefile, not spaces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52305098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: GridControl Navigation In VFP9 I have a grid control ,witch show the records from a database table. And also I have a command button wherewith I want to navigate from a row to another. I tried with thisform.grid1.ActiveRow = thisform.grid1.ActiveRow +1 ,but this doesn't work. Thanks in advance.
A: Per the VFP documentation, the ActiveRow Property "Specifies the row that contains the active cell in a Grid control. Not available at design time; read-only at run time".
I would do something like this.
IF EOF("TableAlias) = .F.
SKIP 1 IN "TableAlias"
ENDIF
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10716356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will JS be aligned with the ECMAScript specs regarding the "typeof null"? In the ECMAScript specs, it is clearly stated that Null is a type whose one and only value is null:
4.3.12 null value
primitive value that represents the intentional absence of any object value
4.3.13 Null type
type whose sole value is the null value
My question is very simple: why on earth we've got the below:
typeof null
>"object"
Is there any intent to correct/amend this? (either the specs or the JS language)
A: JS does align with the ECMAScript spec. null values may have a Null type, but that does not mean that typeof is supposed to return "null". You can see the spec behavior in section 12.5.5.1, which defines the runtime behavior of typeof, that Null-type objects return "object" from typeof.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52348021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: What's the result of an integer list plus an integer in C? I should post the complete code.
int f(int x, int *y) {
static int a =0;
int b =0;
while(b<x) {
a =a +y[b];
b =b +1;
}
return a;
}
int main(int argc, char **argv){
int z[5] ={1,2,3,4,5};
int r1, r2;
r1 =f(3, z);
r2 =f(1, z+1);
}
The value of r2 is 8. What is z+1 here?
A: The expression z+1 is an example of pointer arithmetic.
The array z decays to a pointer to the first element of the array, i.e. &z[0]. z+1 means "take the address contained at z and add 1 array element to that address". This is the same as &z[1].
So this function call:
r1 =f(3, z);
Passes in the address of the first element of z, resulting in the array z being visible in the function.
In this function call:
r2 =f(1, z+1);
It passes in the address of the second element of z. So the function is able to see the array starting from the second element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47398165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: How to apply alternating background color to divs which are not siblings I'd like aaaa and bbbb to have red background. How can I do this , the usual answers dont seem to work since the target divs are not siblings
Here is my CSS/HTML:
div.rules-container>div.ng-star-inserted>div.rules-form:nth-of-type(odd) {
background: red;
}
<div class="rules-container">
<div class="ng-star-inserted">
<div class="rules-form">
aaaaaaaaaaaa
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
bbbbbbbbbb
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
ccccccccccccc
</div>
</div>
</div>
A: Use :nth-child(odd).
Answer 1:
If you want all the odd numbers, then do this:
.rules-container .ng-star-inserted:nth-child(odd) {
background-color: red;
}
<div class="rules-container">
<div class="ng-star-inserted">
<div class="rules-form">
aaaaaaaaaaaa
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
bbbbbbbbbb
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
ccccccccccccc
</div>
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
dddddddddddddd
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
eeeeeeeeeeeeee
</div>
</div>
Answer 2:
If you only want 1 & 3, not 5 , then change the css to:
.rules-container .ng-star-inserted:nth-child(1), .rules-container .ng-star-inserted:nth-child(3) {
background-color: red;
}
<div class="rules-container">
<div class="ng-star-inserted">
<div class="rules-form">
aaaaaaaaaaaa
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
bbbbbbbbbb
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
ccccccccccccc
</div>
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
dddddddddddddd
</div>
</div>
<div class="ng-star-inserted">
<div class="rules-form">
eeeeeeeeeeeeee
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62926683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Give every question in a Google-Form an unique id I want to make a Google Form using Google Apps Scripts. The questions in the form comes from a Google Sheet which includes the id and text of a question. When the form is submitted and I export the questions to a sheet the column names are the questions as text. I would rather replace them using an unique ID based on a column from my own Google Sheet where the questions are also stored as text.
How can I solve this?
A: Build a Question Text to ID hash table
function hashtable() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
let texttoid = {};
sh.getDataRange().getDisplayValues().forEach(r => texttoid[r[1]]=r[0]);
Logger.log(JSON.stringify(texttoid));
}
Execution log
11:58:17 AM Notice Execution started
11:58:18 AM Info {"text1":"id0","text2":"id1","text3":"id2","text4":"id3","text5":"id4","text6":"id5","text7":"id6","text8":"id7","text9":"id8","text10":"id9","text11":"id10"}
11:58:18 AM Notice Execution completed
Sheet0:
id0
text1
id1
text2
id2
text3
id3
text4
id4
text5
id5
text6
id6
text7
id7
text8
id8
text9
id9
text10
id10
text11
You can goto to Google Apps Script Reference and using the search box find any function that you don't understand. If it's a pure JavaScript function the go here
You could store the hash table in cache if wish to use it repeatedly to save the time of building it each time from a spreadsheet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70250360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Oracle PL/SQL set column names using other table I'm struggling with naming columns in one table, using a reference table containing these names. I'm sure it should be possible, but I can't seem to find the right solution or think of the correct logic to achieve it...
Situation: I got 2 tables, one with data, columns having descriptive names, and one with a translation of these column names to meaningful names (reference table, or 'codebook').
I'm looking for a way to return the data of the first table, with the names of the columns given in the second column of the second table.
Tables look like:
dataTable:
q1,q2,q3
1,2,3
4,5,6
and
translationTable:
descName, meanName
q1, meaning1
q2, meaning2
q3, meaning3
Result should be:
meaning1,meaning2,meaning3
1,2,3
4,5,6
Help would be highly appreciated!
A: You can not directly do it, because you need a query whose columns are variable, based on some value.
Slightly different, what you can do is build a dynamic SQL to have your query created by Oracle:
SETUP:
SQL> create table dataTable(q1,q2,q3) as
2 select 1,2,3 from dual union all
3 select 4,5,6 from dual
4 ;
Table created.
SQL> create table translationTable(descName, meanName) as
2 select 'q1', 'meaning1' from dual union all
3 select 'q2', 'meaning2' from dual union all
4 select 'q3', 'meaning3' from dual ;
Table created.
This will create and print your query:
SQL> declare
2 vSQL varchar2(1000);
3 begin
4 select listagg (column_name || ' AS "' || meanName || '"', ', ') within group (order by column_name)
5 into vSQL
6 from user_tab_columns col
7 inner join translationTable tr
8 on (upper(tr.descName) = col.column_name)
9 where table_name = upper('dataTable');
10 --
11 vSQL := 'select ' || vSQL || ' from dataTable';
12 dbms_output.put_line(vSQL);
13 end;
14 /
select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable
PL/SQL procedure successfully completed.
If you copy the statement and run it:
SQL> select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable;
meaning1 meaning2 meaning3
---------- ---------- ----------
1 2 3
4 5 6
SQL>
This way you have your query, but you can not fetch it, because it still has variable columns.
You can easily edit this code to make it build a query that returns strings, composed by concatenating the felds; this way you will always have a single field, but it's different from what you asked:
SQL> select 'meaning1, meaning2, meaning3' from dual
2 union all
3 select Q1 || ',' || Q2 || ',' || Q3 from dataTable;
'MEANING1,MEANING2,MEANING3'
--------------------------------------------------------------------------------
meaning1, meaning2, meaning3
1,2,3
4,5,6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37394417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server query to Postgres Please help me to convert this SQL Server Query to a Postgres query. I am using Postgresql 9.3.I am not able to get the desired output in postgres
If object_ID(N'tempdb.dbo.#tmp') is not NULL
Drop table #tmp;
create table #tmp
(
variable_int_col int,
timestamp_int_col int,
value_col int
)
insert into #tmp values
(8,1449486435,25),
(8,1449486436,26),
(9,1449486435,40),
(9,1449486436,44),
(9,1449486440,52)
select * from #tmp
Declare @sql varchar(max);
Declare @sql2 varchar(max);
set @sql= STUFF((select distinct ','+ QUOTENAME(variable_int_col) from #tmp FOR XML PATH('')) ,1,1,'');
set @sql2= STUFF((select distinct ','+ 'ISNULL(' + QUOTENAME(variable_int_col) + ',0)' + ' AS ' + QUOTENAME('variable_' + cast(variable_int_col as varchar) + '_value') from #tmp FOR XML PATH('')) ,1,1,'');
set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';
-- print @sql
If object_ID(N'dbo.newTable') is not NULL
Drop table newTable;
set @sql='select * into newTable from (' + @sql + ') s';
exec(@sql);
select * from newTable;
I have tried But failed to convert this line
set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';
Please Help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34155216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get confusion matrix and ROC curve when using flow_from_directory? I've trained a model using:
train_datagen = ImageDataGenerator(rescale = 1/255,
zoom_range=0.3,
shear_range=0.3,
horizontal_flip=True,
rotation_range=30,
fill_mode="nearest",
validation_split = 0.2)
test_datagen = ImageDataGenerator(rescale = 1./255
)
train_dataset = train_datagen.flow_from_directory(directory = './train',
target_size = tsize,
class_mode = 'categorical',
subset = 'training',
batch_size = BS)
valid_dataset = train_datagen.flow_from_directory(directory = './train',
target_size = tsize,
class_mode = 'categorical',
subset = 'validation',
batch_size = BS)
test_dataset = test_datagen.flow_from_directory(directory = './test',
target_size = tsize,
class_mode = 'categorical',
batch_size = BS)
and also:
hist = model.fit(train_dataset,validation_data=valid_dataset,epochs=30,callbacks=[vgg_step_1])
How can i plot confusion matrix?, im confused, i only have the validation vs train plot.
A: To get a confusion matrix you need to make predictions on the test set. Then you need to provide the predicted values and the associated true values to the confusion matrix. Note -- in your code for the test_dataset you MUST set shuffle=False in flow_from_directory!!
Code below should generate an adaptable confusion matrix plot and classification report. model is your trained model.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import seaborn as sns
sns.set_style('darkgrid')
def cm_cr(test_gen, model):
preds=model.predict(test_gen)
labels=test_gen.labels
classes=list(test_gen.class_indices.keys()) # ordered lst of class names
pred_list=[ ] # will store the predicted classes here
true_list=[]
for i, p in enumerate (preds):
index=np.argmax(p)
pred_list.append(classes[index])
true_list.append(classes[labels[i]])
y_pred=np.array(pred_list)
y_true=np.array(true_list)
clr = classification_report(y_true, y_pred, target_names=classes)
print("Classification Report:\n----------------------\n", clr)
cm = confusion_matrix(y_true, y_pred )
length=len(classes)
if length<8:
fig_width=8
fig_height=8
else:
fig_width= int(length * .5)
fig_height= int(length * .5)
plt.figure(figsize=(fig_width, fig_height))
sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False)
plt.xticks(np.arange(length)+.5, classes, rotation= 90, fontsize=16)
plt.yticks(np.arange(length)+.5, classes, rotation=0, fontsize=16)
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()
cm_cr(test_dataset, model)
I did not do the ROC curve but there is a good tutorial here for that activity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69239296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make the calendar using the TimeGridWeek view show me only the name of the day I am making a generic weekly calendar so i want to only show the name of the day no the number but a i didn't find how to do it.
I am using fullcalendar v6
https://fullcalendar.io/
How it look
How it should be
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74904923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: element onChange javascript not working <select name='cmg_select' onChange="javascript:window.location.href='index.php?'+this.value">
<option value='pening'> pening </option>
<option value='complete'> complete </option>
<option value='pening'> pening </option>
</select>
The concatenation is not working.
A: *
*Remove the javascript: portion
*Remove the href portion
The result :
< select name='cmg_select' onchange="window.location='index.php?'+this.value" >
A: Try this instead
<select name='cmg_select' onChange="window.location.href='index.php?'+this.options[this.selectedIndex].value">
<option value='pening' > pening </option>
<option value='complete' > complete </option>
<option value='pening' > pening </option>
</select>
A: Remove the javascript: from the onchange attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3173979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I click on a drop down menu that is hidden using Selenium? I'm trying to click on a drop down menu, but since it is hidden, I'm getting the error:
could not be scrolled into view
I've done some digging and I see that using some JavaScript could help, but I'm not sure how to implement that into my Python script.
<div class="MuiSelect-root MuiSelect-select MuiSelect-selectMenu MuiSelect-outlined MuiInputBase-input MuiOutlinedInput-input jss987" tabindex="0" role="button" aria-haspopup="listbox" aria-labelledby="input-label-idTeam1Desktop select-idTeam1Desktop" id="select-idTeam1Desktop"><span></span></div>
<input name="idTeam1Desktop" type="hidden" id="idTeam1Desktop" value="">
This is what I have so far:
driver = webdriver.Firefox(profile, options=options)
driver.get("https://tradenba.com/trade-machine")
element = driver.find_element_by_xpath("//*[@id='idTeam1Desktop']")
element.click()
A: To click on the drop down menu and select the menu item with text as MIL you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following xpath based Locator Strategies:
*
*Using XPATH:
driver.get('https://tradenba.com/trade-machine')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='select-idTeam1Desktop']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='MuiListItemText-root MuiListItemText-inset']/span/div/p[text()='MIL']"))).click()
*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
*Browser Snapshot:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65034645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display a Popup Goal:
When you rightclick one of the row in the table, a popup with links should display, close to the row and cursor. A similiar concept is gmail's functionality.
Problem:
I cannot find a demo version in order to use it.
Information:
I'm using Bootstrap and jQuery..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30075326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best practice to use Oauth2, React, Node.js and Passport.js to authenticate user with Google sign on button? I want to have a login button in my website so when a user clicks on it, the user can use their Google credentials. I'd like to ideally perform the authentication server side using Express.js and Passport.js.
I implemented authentication server-side but the problem is that I can't make an AJAX request from the website to the server to start authentication because Google or Oauth don't support CORS. So I need to use a href element in my website which would call the server authentication endpoint. However, I can't catch server response in this way.
If I perform the authentication client-side (I'm using React) I could store login state in Redux and allow the user to access the website's resources. However, when the user logs out I need to make sure that server endpoints stop serving the same user which feels like implementing authentication twice: client-side and server-side.
In addition when authenticating client-side, Google opens a popup for the user to authenticate which I think is worse user experience then just a redirect when authenticating server-side.
I'm wondering what the best practice in terms of authenticating using Oauth2/Google. For example, stackoverflow.com also has Google button but just makes a redirect, without any popup, so I guess they figured out a way to perform server-side authentication and to bypass CORS issue.
A: I faced the same issue. This article is Gold link
1.In auth route File I had following code
const CLIENT_HOME_PAGE_URL = "http://localhost:3000";
// GET /auth/google
// called to authenticate using Google-oauth2.0
router.get('/google', passport.authenticate('google',{scope : ['email','profile']}));
// GET /auth/google/callback
// Callback route (same as from google console)
router.get(
'/google/callback',
passport.authenticate("google", {
successRedirect: CLIENT_HOME_PAGE_URL,
failureRedirect: "/auth/login/failed"
}));
// GET /auth/google/callback
// Rest Point for React to call for user object From google APi
router.get('/login/success', (req,res)=>{
if (req.user) {
res.json({
message : "User Authenticated",
user : req.user
})
}
else res.status(400).json({
message : "User Not Authenticated",
user : null
})
});
2.On React Side After when user click on button which call the above /auth/google api
loginWithGoogle = (ev) => {
ev.preventDefault();
window.open("http://localhost:5000/auth/google", "_self");
}
3.This will redirect to Google authentication screen and redirect to /auth/google/callback which again redirect to react app home page CLIENT_HOME_PAGE_URL
4.On home page call rest end point for user object
(async () => {
const request = await fetch("http://localhost:5000/auth/login/success", {
method: "GET",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
});
const res = await request.json();
//In my case I stored user object in redux store
if(request.status == 200){
//Set User in Store
store.dispatch({
type: LOGIN_USER,
payload : {
user : res.user
}
});
}
})();
5.last thing add cors package and following code in server.js/index.js in node module
// Cors
app.use(
cors({
origin: "http://localhost:3000", // allow to server to accept request from different origin
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true // allow session cookie from browser to pass through
})
);
A: Your authentication should be done server side. Here is how it works.
*
*You make a fetch or axios call to your authentication route.
*Your authentication route sends a request to Google's Authentication servers. This is important to have on the backend because you will need to provide your clientSecret. If you were to store this on the frontend, it would make it really easy for someone to find that value and compromise your website.
*Google authenticates the user and then sends you a set of tokens to your callback url to use for that user (refresh, auth, etc...). Then you would use the auth token for any additional authorization until it expires.
*Once that expires, you would use the refresh token to get a new authorization token for that client. That is a whole other process though.
Here is an example of what that looks like with Passport.js: https://github.com/jaredhanson/passport-google-oauth2
EDIT #1:
Here is an example with comments of the process in use with Facebook, which is the same OAuth codebase:
https://github.com/passport/express-4.x-facebook-example/blob/master/server.js
A: Redux can really help with achieving this and this follows the same logic as Nick B already explained...
*
*You set up oauth on the server side and provide an endpoint that makes that call
*You set up the button on you react frontend and wire that through an action to the endpoint you already setup
*The endpoint supplies a token back which you can dispatch via a reducer to the central redux store.
*That token can now be used to set a user to authenticated
There you have it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55079181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Set VisualState of combobox when a item is selected in Xaml (Silverlight) When my combobox expands and I select an item, I want the combobox to change visual state(it is highlighted). This will signify something is selected. I tried various VisualStates but none of them would trigger in this scenario. How can I achieve this? Thanks.
A: The standard ComboBox simply doesn't have states to distinguish between having something selected and having nothing selected.
There are a number of ways to go about solving the underlying problem, and it depends mostly on the answer to the following question:
Do you really need to change the visual appearance of the ComboBox itself or does it suffice to style the selected item more prominently?
If it's the latter, you're best served with the rather easy way of using a custom control template for the ComboBoxItems.
If you really want to style the ComboBox itself that way, there are two options I can think of:
A) Add custom states to a ComboBox with a custom template.
Copy your ComboBox's control template and add another state group to the already present states. Both of this is typically done in Expression Blend.
After that you can update the new states in code with
VisualStateManager.GoToState(this, "Selected", true);
for example. You will have to set those states yourself when the first item is chosen. This could be done on the SelectionChanged event.
B) Derive from ComboBox
If you want to use the control in this way often, it might be worthwhile to derive from ComboBox to make your own custom control.
It would look somthing like this:
[TemplateVisualState(Name = "SelectedStates", GroupName = "Unselected")]
[TemplateVisualState(Name = "SelectedStates", GroupName = "Selected")]
// ... (more attributes copied from the ComboBox ones)
public class MyComboBox : ComboBox
{
public MyComboBox()
{
SelectionChanged += HandleSelectionChanged;
DefaultStyleKey = typeof(MyComboBox);
}
void HandleSelectionChanged(object sender, SelectionChangedEventArgs e)
{
VisualStateManager.GoToState(this, SelectedItem != null ? "Selected" : "Unselected", true);
}
}
And you would then need a default style based on the default ComboBox style (or whatever you usually use).
Note that I didn't test this in any way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20861723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP array_key_exists and is not empty Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional array...
function array_key_exists_r($needle, $haystack) {
$result = array_key_exists($needle, $haystack);
if ($result)
return $result;
foreach ($haystack as $v) {
if (is_array($v) || is_object($v))
$result = array_key_exists_r($needle, $v);
if ($result)
return $result;
}
return $result;
}
I am checking like this...
if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}
But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function?
Or should I be using isset instead?
A: Whether you do this inside the function or not it's fully up to you. Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. Anyhow I found a solution within the same function:
function array_key_exists_r($needle, $haystack){
$result = array_key_exists($needle, $haystack);
if ($result && $haystack[$needle]){
return $result;
}
foreach ($haystack as $v)
{
if (is_array($v) || is_object($v)){
$result = array_key_exists_r($needle, $v);
if ($result) {
return $result;
}
}
}
return false;
}
So basically I added a validation on your ifs and that did it also change the default return value to false just in case. I think it can still be enhanced but this does the job.
A: Try this approach instead. Easier!
function array_key_exists_r($needle, $haystack) {
$found = [];
array_walk_recursive($haystack, function ($key, $value) use (&$found) {
# Collect your data here in $found
});
return $found;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44835740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple Uploads Rails Paperclip not Saving I have a rails model 'Guitar' and a rails model 'Photo.' I wanted to be able to attach multiple photos so I watched the railscasts for Paperclip, read the docs, etc. I've used Paperclip in the past to attach a single photo, but I wanted to do multiples this time. I don't have a problem updating the model, and it doesn't error out when I attach sample photos, but when I rails console to Photos.all, nothing comes back. My ultimate goal is to a polymorphic association with an 'Amps' model, but I really just wanted to get 'Guitars' working first.
I have paperclip added to the Gemfile and I've bundle installed, restarted the server, etc. I think I'm missing something stupid and I'm new to rails so please be gentle...
guitar.rb
class Guitar < ActiveRecord::Base
belongs_to :user
has_many :photos
accepts_nested_attributes_for :photos
end
photo.rb
class Photo < ActiveRecord::Base
belongs_to :guitars
has_attached_file :photo, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>',
large: '600x600#' }
end
guitars_controller.rb
class GuitarsController < ApplicationController
before_action :set_guitar, only: [:show, :edit, :update, :destroy]
# GET /guitars
# GET /guitars.json
def index
@guitars = Guitar.all
end
# GET /guitars/1
# GET /guitars/1.json
def show
end
# GET /guitars/new
def new
@guitar = Guitar.new
3.times { @guitar.photos.build }
end
# GET /guitars/1/edit
def edit
@guitar = Guitar.find(params[:id])
3.times { @guitar.photos.build }
end
# POST /guitars
# POST /guitars.json
def create
@guitar = Guitar.new(guitar_params)
@guitar.user_id = current_user.id if current_user
respond_to do |format|
if @guitar.save
format.html { redirect_to @guitar, notice: 'Guitar was successfully created.' }
format.json { render action: 'show', status: :created, location: @guitar }
else
format.html { render action: 'new' }
format.json { render json: @guitar.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /guitars/1
# PATCH/PUT /guitars/1.json
def update
respond_to do |format|
if @guitar.update(guitar_params)
format.html { redirect_to @guitar, notice: 'Guitar was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @guitar.errors, status: :unprocessable_entity }
end
end
end
# DELETE /guitars/1
# DELETE /guitars/1.json
def destroy
@guitar.destroy
respond_to do |format|
format.html { redirect_to guitars_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_guitar
@guitar = Guitar.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def guitar_params
params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id)
end
end
guitars show.html.erb
<p>
<strong>Make:</strong>
<%= @guitar.make %>
</p>
<p>
<strong>Model:</strong>
<%= @guitar.model %>
</p>
<p>
<strong>Year:</strong>
<%= @guitar.year %>
</p>
<p>
<strong>Color:</strong>
<%= @guitar.color %>
</p>
<p>
<strong>Serial:</strong>
<%= @guitar.serial %>
</p>
<p>
<strong>Price:</strong>
<%= @guitar.price %>
</p>
<p>
<strong>Condition:</strong>
<%= @guitar.condition %>
</p>
<p>
<strong>Kind:</strong>
<%= @guitar.kind %>
</p>
<p>
<strong>Bodykind:</strong>
<%= @guitar.bodykind %>
</p>
<p>
<strong>Frets:</strong>
<%= @guitar.frets %>
</p>
<p>
<strong>One owner:</strong>
<%= @guitar.one_owner %>
</p>
<p>
<strong>User:</strong>
<%= @guitar.user_id %>
</p>
<div class="thumb">
<% for asset in @guitar.photos %>
<%= link_to image_tag(photo.photos.url(:thumb)), photo.photo.url(:original) %>
<% end %>
</div>
<%= link_to 'Edit', edit_guitar_path(@guitar) %> |
<%= link_to 'Back', guitars_path %>
guitars _form.html.erb
<%= simple_form_for(@guitar, html: { class: 'form-horizontal', :multipart => true}) do |f| %>
<% if @guitar.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@guitar.errors.count, "error") %> prohibited this guitar from being saved:</h2>
<ul>
<% @guitar.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :make, label: 'Make of the Guitar', placeholder: 'Gibson' %>
<%= f.input :model, label: 'Model of the Guitar', placeholder: 'Les Paul' %>
<%= f.input :year, label: 'Year Made', placeholder: '1957' %>
<%= f.input :color, label: 'Color', placeholder: 'GoldTop' %>
<%= f.input :serial, label: 'Serial', placeholder: '#7-8789' %>
<%= f.input :price, label: 'Price' %>
<%= f.input :condition, label: 'Condition, 1-10' %>
<%= f.input :kind, label: 'Kind of Guitar', placeholder: '6-String-Electric' %>
<%= f.input :bodykind, label: 'Body Type', placeholder: 'Solid String Electric' %>
<%= f.input :frets, label: 'Number of Frets', placeholder: '22' %>
<%= f.input :one_owner, label: 'Original Owner' %>
<%= f.fields_for :photos do |photo| %>
<% if photo.object.new_record? %>
<%= photo.file_field :photo %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
A: def guitar_params
params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id, photos_attributes: [:photo])
end
A: You're running into mass assignment protection which is preventing the photos from being saved. Add this line to your Guitar model:
attr_accessible :photos_attributes
A: in my case I need create a document.
# config/initializer/paperclip.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
This document is necessary create in config > initializers. If your SO is windows, you need add this line in config/environments/development.rb:
Paperclip.options[:comand_path] = "/ImageMagick-6.8.9-Q16/"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19335698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android service fails after onRebind() with a DeadObjectException I am having a problem with my Android service and client apps who rebind to it. Everything works fine when a client app initially binds to my service, after which messages can be sent from service to client. However, if the client app is killed and then binds agains, onRebind() is correctly called in the service, but my messenger in the intent is invalid, causing a DeadObjectException, as noted in the code below. Any ideas?
Here is my code for the service:
@Override
public IBinder onBind(Intent intent)
{
getMessenger(intent);
return _inputMessenger.getBinder();
}
@Override
public void onRebind(Intent intent)
{
getMessenger(intent);
}
@Override
public boolean onUnbind(Intent intent)
{
return true;
}
private void getMessenger(Intent intent)
{
Bundle extras = intent.getExtras();
if (extras != null)
{
// Get the messenger sent from the app.
// This is handled correctly after onBind() and onRebind().
_outputMessenger = (Messenger) extras.get("MESSENGER");
Log.i(TAG, "Got messenger from app: " + _outputMessenger);
}
}
private void sendMessageToClient(String key, String value)
{
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(key, value);
message.setData(bundle);
try
{
_outputMessenger.send(message); // EXCEPTION OCCURS HERE AFTER onRebind()
}
catch (Exception ex)
{
Log.e(TAG, "_outputMessenger.send() failed: " + ex);
}
}
And here is the code for the application:
Intent intent = new Intent("com.foobar.service");
// Create a new messenger for the communication from service to app.
_messenger = new Messenger(new ServiceToActivityHandler());
intent.putExtra("MESSENGER", _messenger);
_serviceConnection = new MyServiceConnection();
_isBoundToService = _context.bindService(intent,
_serviceConnection,
Context.BIND_AUTO_CREATE);
A: There is a note on bound services... The part under additional notes should be useful. I think trapping the exception is probably what you should do...
try {
// Do stuff
} catch(DeadObjectException e){
// Dead object
}
I read that object lifetimes should be reference counted by android across processes, so you should be OK, when the client dies I wonder if
_outputMessenger // needs to be unassigned in your service...?
I assume what is happening is that your binding to the service, it's pumping some data back to your client, your client goes away, the service continues running but then needs to pump some data to the client which has gone by this point?
Also this link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12149610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: postman only showing "This field is required" to ManyToMany field in django I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them.
When I use post request, raw-data works, but not form-data.
module/models.py -
class Module(models.Model):
module_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
desc = models.TextField()
room_list = models.CharField(max_length = 100, blank=True)
rooms = models.ManyToManyField(Rooms, blank=True)
rooms/models.py -
class Rooms(models.Model):
room_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
level = models.CharField(max_length=100)
desc = models.TextField()
module/serializers.py -
class ModuleSerializer(serializers.ModelSerializer):
rooms = RoomSerializer(many=True)
class Meta:
model = Module
fields = '__all__'
def create(self, validated_data):
rooms_data = validated_data.pop('rooms')
module = Module.objects.create(**validated_data)
for data in rooms_data:
room = Rooms.objects.get(**data)
module.rooms.add(room)
return module
def update(self, instance, validated_data):
# Updating rooms
rooms_data = validated_data.get('rooms')
instance.rooms.clear()
for room_data in rooms_data:
room = Rooms.objects.get(**room_data)
instance.rooms.add(room)
# Updating other fields
fields = [
'title',
'desc',
'thumbnail',
'is_deleted',
]
for field in fields:
setattr(instance, field, validated_data[field])
instance.save()
return instance
rooms/serialier.py -
class RoomSerialize(serializers.ModelSerializer):
room_id = serializers.IntegerField()
class Meta:
model = Rooms
fields = "__all__"
module/views.py -
class add_module(APIView):
def post(self, request, format=None):
# Adding the rooms to module from room_list
new_request = request.data.copy()
room_list=[]
if 'room_list' in new_request:
room_list_data = list(new_request['room_list'].split(" "))
for room in room_list_data:
room_object = Rooms.objects.get(room_id=room)
room_serializer = RoomSerializer(room_object)
room_list.append(room_serializer.data)
new_request.update({'rooms':room_list})
# creating the module
module_serializer = ModuleSerializer(data=new_request)
if module_serializer.is_valid():
module_serializer.save()
return Response(module_serializer.data['module_id'])
return Response(module_serializer.errors)
POST request body for updating a module in POSTMAN -
{
"module_id": 2,
"room_list": "1 2",
"title": "4",
"desc": "22",
}
Pls notice that while taking input of ManyToMany field - "rooms", I'm taking a string "room_list" as input that contains all the room_ids to be included. This works perfectly fine when I take input as raw-data in postman, but when I use form-data, it shows
{
"rooms": [
"This field is required."
]
}
What to do?
A: First of all, serializer fields with (many=True) create nested objects.
If you input data with Rooms as already serialized, then it means that you create other Rooms instances. It will be shown with if module_serializer.is_valid(): part. Therefore, if you intended to implement as just link already instantiated Rooms to Module, it's better to make it as primary key list.
Here are my example codes.
class ModuleSerializer(serializers.ModelSerializer):
rooms = RoomSerializer(many=True, read_only=True)
def create(self, validated_data):
rooms_data = validated_data['room_list']
module = Module.objects.create(**validated_data)
for data in rooms_data.split(' '):
room = Rooms.objects.get(room_id=data)
module.rooms.add(room)
return module
def update(self, instance, validated_data):
# Updating rooms
rooms_data = validated_data.get('rooms')
instance.rooms.clear()
for room_data in rooms_data:
room = Rooms.objects.get(**room_data)
instance.rooms.add(room)
# Updating other fields
fields = [
'title',
'desc',
'thumbnail',
'is_deleted',
]
for field in fields:
setattr(instance, field, validated_data[field])
instance.save()
return instance
class Meta:
model = Module
fields = '__all__'
class AddModule(APIView):
def post(self, request, format=None):
# creating the module
module_serializer = ModuleSerializer(data=request.data)
if module_serializer.is_valid():
module_serializer.save()
return Response(module_serializer.data['module_id'])
return Response(module_serializer.errors)
Any other parts are same as yours. Regardless of whether data are sent by form-data or json raw data, results are same as below.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69490752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome Devs tools - where's size and content? According to Chrome Dev Tools - "Size" vs "Content", I should be able to see Size (bytes on the wire) and Content (uncompressed size).
I remember seeing this at one time.
But now (Chrome 38), I only see one measurement, and I'm not sure which one it is.
Can I see the compressed and uncompressed sizes with the Chrome Dev Tools?
A: You should press "Use large resource rows." to see more data.
A: If you are using the latest version of Chrome (like 78+), you can check "Use large request rows" under the settings icon.
Doc: https://developer.chrome.com/docs/devtools/network/reference/#uncompressed
A: I was stuck because only the name of the file was showing up (no other columns), but I realized that you must close the "details" view that shows on the right side when you click a row to see any other columns. Posting the answer here since search brought me here, though it wasn't the OP's actual issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26445154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: format of returned result for .objects.filter(name__containe=data) without quotes sign I have written a code by django in which a user can search for a word in a table of database. My problem here is when I print the returned results, they contain quotations. How can I omit them?
def My_data_filed(request):
form = data_filed_Form(request.POST or None)
data = None
download_form = None
if request.method == 'POST':
if form.is_valid():
data_g = form.cleaned_data.get('g')
data = list(data_filed.objects.filter(g__contains=data_g).values())
print(data_filed.objects.all().values())
download_form = data_filed_DownloadForm(initial={
'g': data_g,
})
return render(request, 'search_report.html',
{
'form': form,
'data': data,
'download_form': download_form
})
The output of this code is like:
'Creator': 'Davide'
But I just want to have:
Davide
Whats wrong in my effort?
My code for writing the fetched result into a csv file: (Since from the comments I understood this part is related too)
def resultDownload(request):
try:
assert request.method == 'POST'
form = data_DownloadForm(request.POST)
assert form.is_valid()
data_g = form.cleaned_data.get('g')
data = list(data_filed.objects.filter(data__contains=g).values_list())
except AssertionError:
error = 'Your request has some problems.'
data = error
attachment = 'SearchedReport.csv'
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename="{}"'.format(attachment)
response.write(data)
return response
A: Whenever you run a queryset like data_filed.objects.filter(g__contains=data_g).values() it always returns a dictionary kind of output with keys and values. And when you passed that result to your template file using:
return render(request, 'search_report.html',
{
'form': form,
'data': data,
'download_form': download_form
})
It is still in that format. If you want to output only the value, you need to output it as such
{{ data.Creator }}
That will give you the output "Davide" without the quotes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62450363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I'm trying to set up a new SharePoint production server and getting an error creating an Open XML 2.5 document I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
This is what the code looks like in the function that is failing.
''' \<summary\>
'''
''' \</summary\>
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
Try
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
MainPart.Document = New Document()
Dim DocBody As New Body()
Return wpd
Catch ex As Exception
WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
Return Nothing
End Try
End Function
Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.
ERROR: Source: OpenXML Routine: WPDCreateFromStream User:
Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.
StackTrace: at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
Source: WindowsBase
Data: System.Collections.ListDictionaryInternal
InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer
ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
TargetSite: Void EasyTraceEvent(Keyword, Event)
I know this is not an issue with the code as the same code works in development. I assume it has to do with permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.
I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.
If anyone has run into this and can point me to a solution, I would appreciate it.
The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.
I am creating a new document, that is why it is coded using WordProcessingDocument.Create
Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.
The more I think about it, it just feels like a permission issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74753676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reporting Services: How To Fit PDF Export On One Page? I've built a report in Reporting Services and when we browse to the report in Internet Explorer we want to be able to export the report in PDF format. It works, but it was cutting off the columns to the right and displaying them on the next page (in PDF) because the page was too wide. I changed the orientation to landscape and it still cut off the columns on the right. Then I changed the page size to legal paper and it fits on one page, but we want the report on letter size paper. Is there a way to compress the report to fit on letter size landscape?
A: Here is how to get a report to fit on a letter page:
*
*Click on the blank space outside of your report
*Look at the properties and find interactive size. Set it to 11,8.5in. Set your Margins to 0.5in, 0.5in, 0.5in, 0.5in
*Click on the body and select properties. Set the width to 10in and something less than 7.5 for the height.
A: I was having this issue too. I set my margins to zero, which allowed me to print on 1 pdf page instead of 2.
A: When you develop report from SpagoBI Studio
change setting of Master Page (next to Layout).
No need to change orientation but you need to
increase the width of report according to your number of columns and column with.
make sure it is greater than sum of all column's width (table width)
This will solve the issues
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31857206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Because the plugin below does not work when used in the response of a getJSON (function ($) {
$.fn.reverse = function(fn) {
var i = this.length;
while(i--) {
fn.call(this[i], i, this[i])
}
};
}(jQuery));
Below the use of jquery code with alphabetical data
$.fn.reverse ($response, function (k, v) {
$("#selector").append('<tr><td>' + v.name + '</td></tr>');
});
A: You need to apply the plugin to any jQuery object, so you need to do something like this to use the plugin.
$($response).reverse(function (k, v) { /*.. code here ...*/ });
//-^^^- wrap using jQuery if it's not a jQuery object
Refer : How to Create a Basic Plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50141001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove layers and objects in FabricJS My question is, how to remove object and layer in same time using fabricJS delete function?
Here is my jQuery for deleting objects:
$('#remove').on('click', function () {
deleteObjects();
$(".deleteBtn").remove();
});
Here is my FabricJS example with layer control https://jsfiddle.net/peLcju2h/15/
Thank you :)
A: If you take a look through the Fabric JS documentation you'll notice that every object extends the Fabric.Object.
The Fabric.Object has a remove() method that you can call to remove any Fabric.Object or class that extends Fabric.Object, which is just about every class that can be rendered onto a canvas, with the exception of a handful of less commonly used classes.
Take a look at the documentation of the remove() function here:
http://fabricjs.com/docs/fabric.Object.html#remove
Also there is a hierarchy of classes on the main page of their documentation which can be found here:
http://fabricjs.com/docs/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40787234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Refresh UltraCombo Content I have to do some maintenance on an old VB.NET application (Visual Studio 2003) that uses Infragistics NetAdvantage 2006. I have a UltraCombo control binded to a DataView.
How can I refresh the content displayed after a change in the database?
A: It sounds like you'll need to repopulate the DataView from the database and refresh your databinding on the UltraCombo; probably pretty close to the same code you use to initially populate the DataView and set the UltraCombo databinding.
You may get a more complete answer if you post some code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/986969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: LINQ-to-SQL not submitting changes to local database I have a local, SQL Server Compact database in an application I am creating. I generated a .dbml file I can use for LINQ-to-SQL purposes using the SqlMetal.exe tool, which worked fine - I now have the table objects for use in my application.
I have a strange issue though. Even after calling SubmitChanges() on my DataContext, the data never commits. But strangely, after adding the rows, these rows do appear in the table object on the datacontext, but not in the table. What shocked me is even after stopping and starting my application, these rows still existed in the DataContext - but after a few minutes they seem to disappear.
Have I configured this correctly? Are there any more steps I need to do after using SqlMetal to allow the LINQ to commit changes?
A: I am assuming that you linked to the dbml file using the default properties. This means that, each time you start a debug session, the file will be copied into your output directory and changes made to it will only be seen for that session (i.e., "Copy -> Always").
If you want the changes to persist then right click the file -> properties -> Copy Never. By default the IDE assumes that you don't want to modify the original database, only a copy for debugging purposes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7490233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Not getting Form value, in java I have a form and bean. From bean I am retreiving values and setting in DTO. That is also setting in FORM. But getter property value is null. I don't know what is the problem here. Can anybody suggest on this?
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class LoginForm extends XFormBase {
private String title;
public void setTitle(String title) {
this.titleValue = title;
System.out.println(" Form set"+titleValue);
}
public String getTitle() {
this.title = titleValue;
System.out.println(" Form get"+titleValue);
return title;
}
}
A: It looks like there is an bug:
the setTitle method, does not set the title but the titleValue!
I would guess the correct implementation is:
public void setTitle(String title) {
this.title = title;
System.out.println(" Form set"+title);
}
A: Try using this. I suspect a mistake in your getter and setter implementation
public class LoginForm extends XFormBase {
private String title;
public void setTitle(String titleValue ) {
this.title= titleValue;
System.out.println(" Form set"+this.title);
}
public String getTitle() {
System.out.println(" Form get"+this.title);
return this.title;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8321724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unexpected result at summing numbers using a while loops in console application I am trying to make a program to sum numbers until the user enter OK.
The program make the sum, but return a bad result.
i'm not sure where is my error...
int sum = 0;
Console.WriteLine("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
sum += num;
}
Console.WriteLine(sum);
A: you don't keep the number the use enter in the while loop.
you need to input the readline to a variable.
var num = Console.Readline();
sum += num; //parse first
A: Inside your while loop you need to update num:
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
num = Int32.Parse(Console.ReadLine());
sum += num;
}
Also just as a note, if you need your program to be a little safer, you can you use the following:
int num;
if(Int32.TryParse(Console.ReadLine(), out num)) {
//do something..
}
else {
//do something else.. like end program, throw exception etc.
}
Int32.TryParse:
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded
This way you can do something in the instance that the input string was not a valid conversion. Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse.
A: You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK".
I think you're after this:
int sum = 0;
string input;
Console.WriteLine("Enter number: ");
while ((input = Console.ReadLine()) != "OK")
{
int inputNum = Convert.ToInt32(input);
sum += num;
Console.WriteLine("Enter number: ");
}
The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK.
An alternative way to get input, then check it is:
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
while (input != "OK")
{
...
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
}
A: int sum = 0;
Console.WriteLine("Enter number:");
int num = int.Parse(Console.ReadLine());
while (sum< num)
{
sum++;
}
Console.WriteLine(sum);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51087626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to capture Android Screen multiple times simultaneously? Is it possible to capture Android screen multiple times with different settings on Android 13? I've tried two approaches:
*
*Create two media projections using the same Activity.RESULT_OK and intent
*Create one media projection and two virtual displays by invoking the createVirtualDisplay method twice with the different parameters.
I need this because I need to cast one screen (virtual display, technically speaking) via the WebRTC with the ScreenCapturerAndroid and record on the device the second using the MediaRecorder API.
On devices with the API Level prior to 33 (Android 11), the approach #1 works fine, but not on devices with API Level 33.
Are there any ways to overcome this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75512848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git : Unable to unlink / cannot create directory, on ignored folder I'm using SourceTree, and when I try to checkout from one branch to another, I've got the following error message :
warning: unable to unlink sf2/web/bundles/mybundle: Permission denied
fatal: cannot create directory at 'sf2/web/bundles/mybundle': Permission denied
Though, on both branches, the folders in sf2/web/bundles/ are ignored, since many commits, as you can see in my .gitignore :
/sf2/web/bundles/*
That's pretty normal I guess, I'm on Windows, symlinks are sh*t.
As a workaround, I can remove the folder and then checkout, but that's not so great.
It seems that, because I commited this folder/symlink some times at the begining, it now has to redo all the modifications step by step, including the ignored folders ?!
EDIT : I confirm it's creating this folder, an old version of it, even if it's supposed to be ignored now. And if I remove this folder, it's showing the few old files inside as working copy changes...
A: Finally found the solution here :
Applying .gitignore to committed files
It's apparently because some files inside has been commited one time, so they are in the repo.
If I understand it right, that means it's very important to modify the .gitignore before commiting any file inside, otherwise it can be a mess !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18760097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Failed to create maven project with maven-archetype-webapp When I tried to create a Maven project with maven-archetype-webapp, some problems came out.
An internal error occurred during: "Creating maven-archetype-webapp".
org/apache/maven/shared/filtering/MavenFilteringException
An internal error occurred during: "Updating Maven Dependencies".
org/apache/maven/shared/filtering/MavenFilteringException
I have tried a lot of solutions related to this, nothing worked.
How can I solve this?Thanks!
ps:I was using eclipse 4.4.1 and m2e 1.5.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27273758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: "Invalid host in redirect target" using ACME on pfsense I've set up pfsense to manage my network, and I have the ACME plug in installed. I'm to correctly direct traffic to my secure webservers, but first I need to get the certificates onto PFSense.
At the moment, my certificates are using certbot on the webservers, but I want pfsense to manage all the certs.
When I use the stand alone method for the ACME plugin, I get this error, and I'm not sure where I went wrong in setting up pfsense. If someone could help me out, it would be great, thanks.
Renewing certificate
account: myaccount
server: letsencrypt-production-2
/usr/local/pkg/acme/acme.sh --issue -d 'domain.ca' --standalone --listen-v4 --httpport '80' --home '/tmp/acme/myaccount/' --accountconf '/tmp/acme/myaccount/accountconf.conf' --force --reloadCmd '/tmp/acme/myaccount/reloadcmd.sh' --log-level 3 --log '/tmp/acme/myaccount/acme_issuecert.log'
Array
(
[path] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
[PATH] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
[port] => 80
[ipv6] =>
)
[Fri Jul 10 10:53:49 MDT 2020] Standalone mode.
[Fri Jul 10 10:53:49 MDT 2020] Single domain='domain.ca'
[Fri Jul 10 10:53:49 MDT 2020] Getting domain auth token for each domain
[Fri Jul 10 10:53:51 MDT 2020] Getting webroot for domain='domain.ca'
[Fri Jul 10 10:53:51 MDT 2020] Verifying: domain.ca
[Fri Jul 10 10:53:51 MDT 2020] Standalone mode server
[Fri Jul 10 10:53:55 MDT 2020] domain.ca:Verify error:Fetching https://domain.ca.well-known/acme-challenge/VBYshVeuP8BQXWnuUMggKU3Rn_cD4k5Tg9FD0gS_-7k: **Invalid host in redirect target**
A: My problem was with AAAA DNS record. Ipv6 record pointed to another host.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62839208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php createimage does not output an image to browser can you help?
Using XAMPP I have localhost/drawrectangle.php containing the following code which does not render an image, ll I get is an image placeholder, can you help?
<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);
// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);
// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);
// Output and free from memory
header('Content-Type: image/jpeg');
imagejpeg($canvas);
imagedestroy($canvas);
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25515196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# Dates - Databases, Display and Localization What are some Date (& Time) format best practices when wanting to adhere to localization in a new application.
For example, what format do you use to write dates to the database.
How do you display the following to the user using their own locale settings once the date has been obtained from the database.
ShortDate
LongDate
DateTime
Any tips for punters appreciated.
A: Always store dates in UTC and when displaying them, calculate the local time based on the user's time zone (which you will have to ask for at some point and store).
A: DateTime2 (aka long date in MS SQL) is only going to be useful if you need that level of granularity or 10,000 year range. DateTime seems to be the norm. If you only need the date portion and can ignore the time, use the new Date datatype in SQL 2008. Ask your clients what granularity is necessary for the project.
UTC is the best way to store the date since your server or your client can be anywhere in the world (assuming a web-based deployment). Also, if you move your server or have a new co-located server you won't need to adjust for timezone since everyone is already running on UTC.
You should only convert from UTC to local time in the presentation later. If your client is using a web browser you can get the timezone offset from javascript. Then if you need that value on the server-side, either store the value in a cookie or in a hidden HTML field for easy access.
I've used a tweaked version of this javascript sample from CodeProject to do the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/437981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Nginx + Django + Gunicorn: 502 Bad Gateway upstream prematurely closed connection while reading response header from upstream I am creating (for the first time) a website.
More specifically, the user uploads an image and after some computations the website displays some result.
However, sometimes (not always, sometimes just retrying or changing image it works) during this process I get "502 Bad Gateway nginx/1.10.3 (Ubuntu)"
Looking at the error I get:
[error] 7836#7836: *16 upstream prematurely closed connection while reading response header from upstream, client: 131.175.147.1, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "165.227.170.231", referrer: "http://165.227.170.231/"
I tried this but it did not help much, while I think this is not my case.
The settings are:
/etc/nginx/sites-available/django :
upstream app_server {
server unix:/home/django/gunicorn.socket fail_timeout=0;
}
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# Your Django project's media files - amend as required
location /media {
alias /home/django/django_project/django_project/media;
}
# your Django project's static files - amend as required
location /static {
alias /home/django/django_project/django_project/static;
}
# Proxy the static assests for the Django Admin panel
location /static/admin {
alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
proxy_buffering off;
proxy_connect_timeout 75s;
proxy_read_timeout 300s;
proxy_pass http://app_server;
}
}
The /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
proxy_connect_timeout 75s;
proxy_read_timeout 300s;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#}
The /ect/gunicorn.d/gunicorn.py:
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ
def max_workers():
return cpu_count() * 2 + 1
max_requests = 1000
worker_class = 'gevent'
workers = max_workers()
TIMEOUT=120
And I start gunicorn in this way:
service gunicorn start --timeout 300
Basically, I tried everywhere to avoid timing out, but still encounter the same problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51337772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Optimising the query which has joins and unions in mysql I am using the laravel to build my web app. In that for listing all orders I have an query but it takes upto 40s in my localhost whereas in goddady shared hosting it takes upto 95s. Although I implemented the server side datatable yet the query takes bit long to execute. I need someone to suggest or help to make the query to excute more efficient. There are majorly two sets and I make that union.
select * from ((
select `subscription`.`id`,
`subscription`.`order_id`,
`users`.`name` as `user_name`,
`subscription`.`new_dated`,
`subscription`.`rescheduling_delivery_date` as expected_date,
COUNT(`subscription_items`.`product_id`) as items,
`subscription`.`od_dis_total` as `total`,
`subscription`.`order_discount`,
`area`.`area_name`,
`subscribe_orders`.`action` as ordertype,
driver.name as driver_name,
'NA' as payment_mode,
`payment_status`.`status_name` as payment_status,
`subscription_status`.`status_name` as order_status,
`subscription`.`od_payment_method`,
`subscription_items`.`product_id`,
subscription.delivered_dated
from `subscription`
left join `subscription_items` on `subscription`.`id` = `subscription_items`.`subscription_id`
left join `users` on `subscription`.`user_id` = `users`.`id`
left join `users` as `driver` on `subscription`.`driver_id` = `driver`.`id`
left join `ycias_address` on `subscription`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `subscribe_order_items` on `subscription`.`subscribe_order_id` = `subscribe_order_items`.`subscribe_order_id`
left join `subscribe_orders` on `subscription`.`subscribe_order_id` = `subscribe_orders`.`id`
left join `payment_status` on `subscription`.`payment_status` = `payment_status`.`id`
left join `subscription_status` on `subscription`.`od_status` = `subscription_status`.`id`
group by `subscription_items`.`subscription_id`)
union (
select `orders`.`id`,
`orders`.`order_id`,
`users`.`name` as `user_name`,
`orders`.`new_dated`,
`orders`.`expected_delivery_date` as expected_date,
COUNT(order_items.product_id) as items,
`orders`.`od_dis_total` as `total`,
`orders`.`order_discount`,
`area`.`area_name`,
'Instant Order' as ordertype,
driver.name as driver_name,
orders.payment_mode,
`payment_status`.`status_name` as payment_status,
`order_status`.`status_name` as order_status,
`orders`.`od_payment_method`,
`order_items`.`product_id`,
`orders`.`delivered_dated`
from `orders`
left join `order_items` on `orders`.`id` = `order_items`.`order_id`
left join `users` on `users`.`id` = `orders`.`user_id`
left join `users` as `driver` on `driver`.`id` = `orders`.`driver_id`
left join `ycias_address` on `orders`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `payment_status` on `orders`.`payment_status` = `payment_status`.`id`
left join `order_status` on `orders`.`od_status` = `order_status`.`id`
group by `order_items`.`order_id`)) as all_orders limit 10 offset 0
A: As per the suggestion given by Andy Lester I have added the index for the necessary columns. So the execution time is reduced to half that is 18 secs in localhost. I further investigated that the index columns are of datatype VARCHAR. So I changed that to INT and then executed, got results within 0.9 secs. Thanks to Andy Lester.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67475285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I place a Google recaptcha in my website successfully? I am having real trouble putting a Google recaptcha into my website. There seems to be no easy to follow tutorial. I am brand new to JavaScript, but am building a website which receives a huge amount of spam from the contact form. I'd like a Google recaptcha form, possibly v2 as that seems the 'easiest' but I am still having issues.
I have PHP, JS and HTML and I am not understanding how any of it links, and it is not working. The form submits successfully, however, there is no way of telling the form has submitted, nothing happens on the page. I would like a Bootstrap success alert to take place when I press submit.
Here is the PHP:
<?php
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$email = $_POST['email'];
$number = $_POST['number'];
$company = $_POST['company'];
$message = $_POST['message'];
$email_from = "Your website";
$email_subject = "You have a new submission form from Your website";
$email_body = "First Name: $Fname.\n".
"Last Name: $Lname.\n".
"Email Address: $email.\n".
"Telephone Number: $number.\n".
"Company Name: $company.\n".
"Message: $message.\n";
$to = "howdy@yourwebsite.co.uk";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the "I am not a robot" checkbox"</h2>';
exit;
}
$secretKey = 'acombinationoflettersandnumbers';
$ip = $_SERVER['REMOTE_ADDR'];
// post request to the server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
?>
Here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">
<div class="messages"></div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_name">First Name*</label>
<input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_lastname">Last name*</label>
<input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_email">Email address*</label>
<input id="form_email" type="email" class="form-control" name="email" placeholder="becks@example.com" required data-error="Please provide your email address">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_number">Contact number*</label>
<input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_company">Your company name</label>
<input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_message">Your message*</label>
<textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="I need the world's best website...HELP!" required></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="g-recaptcha" data-sitekey="acombinationoflettersandnumbers"></div>
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">
</div>
</div>
</form>
Here is the JavaScript:
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'acombinationoflettersandnumbers'
});
};
onloadCallback();
$('form').on('submit', function(e) {
if(grecaptcha.getResponse() == "") {
e.preventDefault();
alert("You can't proceed!");
} else {
alert("Thank you");
}
});
I have only got this far by following steps from lots of different tutorials and am not sure if any of it is correct. Hope someone is able to assist with a step by step process that allows me submit a contact form, with a success Bootstrap alert and form refresh once it has been submitted.
Thank you!
A: You could try something like this:
front-end
<div class="js-form-message form-group" style="text-align: center">
<div style="display: inline-block;" class="g-recaptcha" data-sitekey="yourkey"></div>
</div>
back-end
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
// not a robot
} else {
// robot
}
The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62148815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CanvasJS, issues with setting a user input Title for chart I am currently facing an issue with creating a user input title for a canvasJS chart. I am currently running through the tutorial over at canvasJS, and I thought it would make a neat small project to create a user input oriented pie chart.
The current issue I am facing is trying to get the text inputted from HTML to show up correctly.
[JSFiddle]https://jsfiddle.net/n3n0pssc/
var chart = new CanvasJS.Chart("chartContainer",{
title:{
document.getElementById("chartTitle").setAttribute("text")
}`
I understand that the title must be set by tying it together with the addDataPointsAndRender function, but I am confused as canvasJS only displays set text by title: {text : "title"} and I am trying to figure out how it would go together by fetching input text.
Thank you for any assistance.
A: You can set the user inputs to the chart by either using chart options or by using the set() methods of the CanvasJS API.
I have modified your jsfiddle, and its working now.
function addDataPointsAndRender(){
chart.options.title.text =document.getElementById("chartTitle").value;
chart.options.data[0].dataPoints.push({
y: parseFloat(document.getElementById("yValue1").value),
indexLabel: document.getElementById("indexLabel1").value
});
chart.render();
}
Also have a look at :
*
*Tutorial on Rendering chart from user Input
*Updating Chart Options
*CanvasJS Methods & Properties Documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43644484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java: Creating New Strings During Runtime to Edit I'm creating a Mad Lib generator in Java. If you know what a Mad Lib is, this will be easier to understand. Also, I'm new to Java, so bear with me here. I want to make it so that each Mad Lib only asks for the number of adjectives, nouns, etc. that are in that specific one. For example, Mad Lib 1 may have 3 nouns, while Mad Lib 2 has 5 nouns. Is there a way to write a separate method to be run X times, creating X new strings (for the player to enter X nouns), and giving each string a different name? Just giving the strings names like nounA, nounB, nounC, or noun1, noun2, noun3 would be perfect. I need the final story to be able to differentiate between them. It will be really nice if each time I decide to add another Mad Lib to my program to just be able to loop an addNoun() method 8 times instead of writing
String nounA = scan.next();
System.out.print("\f");
String nounB = scan.next();
System.out.print("\f");
...and so on every time for each part of speech. I have not yet learned about arrays, and I think this may have a solution involving that. Like I said, I'm new to Java, so if you try to show me anything advanced, please explain it in a way that I can understand it or find a simpler way to do it.
A: If I understand your problem correct then you need to use ArrayList and HashMap to achieve this:
First you can create ArrayList of String to store X nouns. An ex: of Arraylist is:
List<String> nouns = new ArrayList<String>();
nouns.add('nounA'); // add related noun
//or
String nounStr = 'new Noun'
nouns.add(nounStr);
Then you can categorise particular nouns by HashMap
HashMap<String, List<String> > nounCategory = new HashMap<String, List<String> >();
nounCategory.put('madLib1', 'nouns'); // add all list with a unique key madLib1 ...
To learn more about using List and HashMap read reference List:here and HashMap:here
A: If you have the count of nouns, say, in int nounCount, use arrays like this:
String[] nouns = new String[nounCount]; // Create an array
for (int i = 0; i < nouns.length; i++) {
nouns[i] = scan.next(); // Set each item
}
Then you would be able to access different words as noun[0], noun[1], etc. You're likely to use loops and store index of selected noun somewhere though.
See also: Java arrays tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18681151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.