text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Display BigInt DataType of length 10 in Excel Sheet using PHP I want to make a excel file by fetching data from database. Every thing works fine but the phone number field return unknown value in excel sheet but it displays correct value in browser.
<?php
include('connection.php');
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
$q = mysql_query("select * from members order by id desc");
echo 'First Name' . "\t" . 'email' . "\t" . 'Phone' . "\t". 'address' . "\t". 'Membership Number' . "\t". 'Membership Category' . "\n";
while($r = mysql_fetch_array($q))
{
$name = $r['name'];
$email = $r['email'];
$phone = $r['phone'];
$address = $r['address'];
$mem_num = $r['mem_num'];
$mem_cat = $r['mem_category'];
echo "$name"."\t"."$email"."\t"."$phone"."\t"."$address"."\t"."$mem_num"."\t"."$mem_cat"."\n";
}
mysql_close($con);
?>
A: I believe you are confusing data-types here. A phone number for instance, is not a number. But it's called a number! Yeah I know, because it has a lot of numbers in it, but still, it isn't a number... Why?
A phone number is indeed constructed of a set of numerals - the symbols that represent a number - but that doesn't make it a number yet. Compare letters and words; a word is constructed of a set of letters, but not every set of letters is a word. For example: dfslkwpdjkcnj is not a word, not in a language I know of at least... And if it would be a number, how would you add-up two phone numbers? Or how would you divide a phone number by another one? Would that be something like [grandma's phonenumber] / [mom's phonenumber] = [my phonenumber]?
So, to store a phone number in a database, a varchar would be a more suitable column type. For example international phone numbers start with either a + sign, or double zero (00). Both of them can not be stored in a numeral field type. The + isn't a numeral sign, or is used to designate a positive number, and will be cut off. Leading zero's in a number have no function at all, and will be cut off as well...
So bottom line; in your database, use a varchar to store a phone number, and use conversion functions to format a phone number to your liking. There are almost certainly a dozen of algorithms to be found to format a phone number to some kind of a standardized format.
Then back to your excel: your aren't creating an excel file, but a csv file, and you're giving it an excel mime-type. But that would be the same to give someone a cd and say it is a dvd. If you put the cd in a dvd player, it will almost certainly be able to play it, but it is mere luck then wisdom that it does.
Creating an excel file isn't as easy as setting the mime-type, as you can't expect the browser to know how to convert text to an excel file, as it does not know about excel's internals. So if you reaaally want to create an excel file, and set the data types of certain columns, use a library like phpExcel or any other available, if you don't want to create a library yourself that is.
A: have you tried expanding(stretching) phone column in your excel file? sometime if column is small and numbers are big, excel displays number like(1.23+09) this.
If stretching column does not work. you can convert numbers into string and then put them in excel file
sorry i can't add this in comment as i don't have privilege to comment yet.
A: If with your API you are able to format cells, that's what you would need to do. You are storing your phone number as a BigInt instead of as a String. I have always stored phone numbers as Strings.
Excel is interpreting your data correctly--as a number, not as text. If you wish to continue to store your phone number as a BigInt (which I don't recommend), you would need to convert it to a String before writing it out to Excel. Or, if your API permits, write it out to Excel as a number, but then apply cell formatting to bring it to the formatting you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28074222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Don't show Title FlyoutItem Shell in Drawer - xamarin forms I want to have a Tab Bar and a Drawer in the form
In this form I use Shell
I do not intend to display any Tabbar items in Drawer
now
I created the Tabbar at the bottom of the page once with the following code:
<TabBar Title="Tab bar FlyoutItem" FlyoutDisplayOptions="AsSingleItem" >
<Tab Title="T1" Icon="T1.png" >
<ShellContent ContentTemplate="{DataTemplate views: page1}" />
</Tab>
<Tab Title="T2" Icon="T2.png" >
<ShellContent ContentTemplate="{DataTemplate views: page2}"/>
</Tab>
<Tab Title="T3" Icon="T3.png" >
<ShellContent ContentTemplate="{DataTemplate views: page3}"/>
</Tab>
<Tab Title="T4" Icon="T4.png" >
<ShellContent ContentTemplate="{DataTemplate views: page4}"/>
</Tab>
<Tab Title="T5" Icon="Home.png" >
<ShellContent ContentTemplate="{DataTemplate views: page5}"/>
</Tab>
</TabBar>
Output :
View image
And once again I used Flyout instead of tabbar (code below):
< FlyoutItem Title=”Tab bar FlyoutItem” FlyoutDisplayOptions=”AsSingleItem” >
<Tab Title=”T1” Icon=”T1.png” >
<ShellContent ContentTemplate=”{DataTemplate views: page1}” />
</Tab>
<Tab Title=”T2” Icon=”T2.png” >
<ShellContent ContentTemplate=”{DataTemplate views: page2}”/>
</Tab>
<Tab Title=”T3” Icon=”T3.png” >
<ShellContent ContentTemplate=”{DataTemplate views: page3}”/>
</Tab>
<Tab Title=”T4” Icon=”T4.png” >
<ShellContent ContentTemplate=”{DataTemplate views: page4}”/>
</Tab>
<Tab Title=”T5” Icon=”Home.png” >
<ShellContent ContentTemplate=”{DataTemplate views: page5}”/>
</Tab>
</ FlyoutItem >
OUTPUT :
View image
I created the Drawer using the following code :
<FlyoutItem FlyoutDisplayOptions="AsMultipleItems">
<Tab Title="T6" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:page6}" />
</Tab>
<Tab Title="T7" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:page7}"/>
</Tab>
<Tab Title="T8" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:page8}"/>
</Tab>
<Tab Title="T9" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:page9}"/>
</Tab>
</FlyoutItem>
This time Drawer is displayed but its Title Of Tabbar is also displayed in Drawer as shown in the figure.
OUTPUT :
View image
Please help me how I can not display the Title in Drawer.
Thank
A: I'M find
The
Shell.FlyoutBehavior="Flyout"
must be added to the TabBar
I share the code below :
<TabBar Title="Tab bar FlyoutItem" Shell.FlyoutBehavior="Flyout" FlyoutDisplayOptions="AsSingleItem" >
<Tab Title="T1" Icon="T1.png" >
<ShellContent ContentTemplate="{DataTemplate views:T1}" />
</Tab>
<Tab Title="T2" Icon="T2.png" >
<ShellContent ContentTemplate="{DataTemplate views:T2}"/>
</Tab>
<Tab Title="T3" Icon="T3.png" >
<ShellContent ContentTemplate="{DataTemplate views:T3}"/>
</Tab>
<Tab Title="T4" Icon="T4.png" >
<ShellContent ContentTemplate="{DataTemplate views:T4}"/>
</Tab>
<Tab Title="T5" Icon="Home.png" >
<ShellContent ContentTemplate="{DataTemplate views:HomePage}"/>
</Tab>
</TabBar>
<FlyoutItem FlyoutDisplayOptions="AsMultipleItems" Shell.TabBarIsVisible="True">
<Tab Title="T6" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T6}" />
</Tab>
<Tab Title="T7" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T7}"/>
</Tab>
<Tab Title="T8" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T8}"/>
</Tab>
<Tab Title="T9" Icon="email.png" >
<ShellContent ContentTemplate="{DataTemplate views:T9}"/>
</Tab>
</FlyoutItem>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64229556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Azure portal bash file structure for ssh file I ran a bash command from my azure subscription on portal.azure to create a ssh key and it asked me to give the name of the new file but at a location that I am not able to find on my machine. It gave a default path as /home/username/.ssh/id_rsa
I cant seem to find a home directory on my machine.
It went ahead and created it but I am so confused as to where it placed it.
Can someone shed some light on this. Do the bash commands run on portal.azure know the file structure of my machine and if it didnt put it under my machine, where did it place it?
ssh-keygen -m PEM -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa):
A: When using the bash command line in the Azure portal, it means you use the Azure Cloud Shell, not your local machine. So the SSH key you created is stored in the cloud shell with the path /home/username/.ssh/, not the local machine.
Here is a screenshot that creates the SSH key in the Azure Cloud Shell:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59941017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is JApplet showing a blank gray screen? So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
A: You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27048996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Views not laying out properly for iPhone 4 I have laid out my ViewControllers in Storyboard using Auto Layout, and everything looks perfect on an iPhone 5. Now I'm testing for iPhone 4 and things are not in their correct position. For example, I placed a UIView at the bottom of its parent UIView. It's width is the screen width and its height is 100. It shows up nicely on an iPhone 5 but doesn't appear at all on an iPhone 4 (I think it's because it's drawn at the height it should for an iPhone 5 which is too far below the screen for a 4)
If I'm using Auto Layout, do I still need to make adjustments to my Views? If so, what's the point of using Auto Layout at all?
A: Here is the approach to make your layouts fit to retina & non retina form factors.
I am not saying these are the rules, but I follow this approach & hardly get any conflicts which is difficult to resolve.
*
*First & foremost : Always try to design your storyboard on non-retina form factor (I mean in your case design it on iPhone4 size & then apply retina-Form Factor & verify how it fits on iPhone5 size.).
*Definitely your view at the bottom of its parent will be having a fix constraint for "Y" position. Usually, you need to make a relative constraint. So when you show it up on iPhone4, the Y & the height might be going beyond the maximum Y axis value.
*Try checking these values for your layout in Assistant Editor like topSpace, leadingSpace, trailingSpace, bottomSpace .
*AutoLayout doesn't mean that it will fit to your needs, however it adjusts the component accordingly.
*In case of any warning in Storyboard, try using the help & suggestion provided like, add missing constraint or adjust frame to suggested
Storyboard will never behave in the same manner for each & every screen or view your design. You need to practise it more & more & you get to know how to add constraints.
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23769002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Print inner text of a HtmlContent in a razor view (MVC4) Using MVC, look at this example where we have the following HTML code:
<p>Duma</p><img url='..' /><p>Duma</p>
I would like that print only the content of the tags, as: Duma Duma, removing the image, tags and showing only the text (as innerText)
I tried using Html.Raw() but it's not worked. Also I was reading about the class TabBuilder and creating a Html extension method, but I don't have idea about how to implemeted in my razor view.
A: You could make a string extension to strip the Html tags.
public static class StringExtensions
{
public static string StripHtml (this string inputString)
{
return Regex.Replace
(inputString, "<.*?>", string.Empty);
}
}
Then use it in your view
@myHtmlString.StripHtml()
You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder
@using My.Extensions.Namespace
OR
<system.web>
<pages>
<namespaces>
<add namespace="My.Extensions.Namespace" />
</namespaces>
</pages>
</system.web>
You could also make a Html Helper Extension
public static class HtmlExtensions
{
public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
{
return Regex.Replace
(htmlString, "<.*?>", string.Empty);
}
}
You can use this in your view like this
@Html.StripHtml(myHtmlString)
You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16345787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding end-date of last sickness incident in R I have a file which records when someone was sick, and when they recovered. Some records have several incidents of sickness, and I am trying to add a new column to each row which is "date last sickness ended" (or "date record began" if NA). There are 10,000s of records, and there can be 10+ incidents of sickness. But in the simplest example, I am trying to go from this:
| ID | RecordBegins | SickStartDate | SickEndDate |
| person1 | 1990-01-01 | 2017-03-04 | 2017-07-01 |
| person1 | 1990-01-01 | 2018-11-01 | 2019-02-04 |
to this:
| ID | RecordBegins | SickStartDate | SickEndDate | EndLastSick
| person1 | 1990-01-01 | 2017-03-04 | 2017-07-01 | 1990-01-01
| person1 | 1990-01-01 | 2018-11-01 | 2019-02-04 | 2017-07-01
I'm new to R, and self-taught. I've been trying to stay in the tidyverse world, but am open to other approaches.
I can code for what I want when there's only one unique person in the dataset using the code below. I've tried extending it using group_by() when I expand the dataset to more than one person, but I can't think of a way to make it work.
sick <-tribble(
~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
"person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
"person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
)
var1 <- sick$SickEndDate %>% sort(decreasing = TRUE) # place date of last sick at position [1]
var1[1] = sick$`RecordBegins`[1] # replace date of last sick with record start date
var1 <- sort(var1) # re-sort so in date order
sick <- mutate(sick, startExposure = var1)
However that feels pretty clunky, and I can't think of a way to get it to work for when scaling up to more than one person, for example:
sick <-tribble(
~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
"person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
"person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
"person2", as.Date("1995-01-01"), as.Date("2014-10-07"), as.Date("2017-01-04"),
"person2", as.Date("1995-01-01"), as.Date("2017-11-01"), as.Date("2017-11-23"),
)
A: You can group by ID, and make use of lag, if I'm interpreting your question correctly!
library(dplyr)
sick %>%
arrange(ID, SickStartDate) %>%
group_by(ID) %>%
mutate(EndLastSick = case_when(
# if this is the first record for this person, use RecordBegins
is.na(lag(SickEndDate)) ~ RecordBegins,
# otherwise, get the most recent SicKEndDate
TRUE ~ lag(SickEndDate)
))
## A tibble: 4 x 5
## Groups: ID [2]
# ID RecordBegins SickStartDate SickEndDate EndLastSick
# <chr> <date> <date> <date> <date>
#1 person1 1990-01-01 2017-03-04 2017-07-01 1990-01-01
#2 person1 1990-01-01 2018-11-01 2019-02-04 2017-07-01
#3 person2 1995-01-01 2014-10-07 2017-01-04 1995-01-01
#4 person2 1995-01-01 2017-11-01 2017-11-23 2017-01-04
Data:
sick <-tribble(
~ID, ~RecordBegins, ~SickStartDate, ~SickEndDate,
"person1", as.Date("1990-01-01"), as.Date("2017-03-04"), as.Date("2017-07-01"),
"person1", as.Date("1990-01-01"), as.Date("2018-11-01"), as.Date("2019-02-04"),
"person2", as.Date("1995-01-01"), as.Date("2014-10-07"), as.Date("2017-01-04"),
"person2", as.Date("1995-01-01"), as.Date("2017-11-01"), as.Date("2017-11-23"),
)
A: This is similar to @heds1's answer but using only lag function.
library(dplyr)
sick %>%
arrange(ID, SickStartDate, SickEndDate) %>%
group_by(ID) %>%
mutate(EndLastSick = lag(SickEndDate, default = first(RecordBegins))) %>%
ungroup
# ID RecordBegins SickStartDate SickEndDate EndLastSick
# <chr> <date> <date> <date> <date>
#1 person1 1990-01-01 2017-03-04 2017-07-01 1990-01-01
#2 person1 1990-01-01 2018-11-01 2019-02-04 2017-07-01
#3 person2 1995-01-01 2014-10-07 2017-01-04 1995-01-01
#4 person2 1995-01-01 2017-11-01 2017-11-23 2017-01-04
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68790050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error: [$injector:unpr] Unknown provider: GetOrdersProvider <- GetOrders <- OrderController I want to do get post actions on different URLs. When I tried to write different factories I guess it could recogine the other factory.
Service.js
var app = angular.module("ServiceApp", ["ngResource"]);
app.factory('GetPortfolios', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/", {}, {
});
app.factory('GetOrders', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
});
});
App.js
var app = angular.module("UiApp", ["ServiceApp"]);
app.controller("PortFolioController", function ($scope, GetPortfolios) {
$scope.Portfolios = GetPortfolios.query({ pmid: 2 });
console.log($scope.Portfolios);
});
app.controller("OrderController", function ($scope, GetOrders) {
$scope.Orders = GetOrders.query({ id: 25 });
console.log(Orders);
});
A: Inside your Service.js, first factory is missing the closing }) paranthesis, check the updated Service.js
var app = angular.module("ServiceApp", ["ngResource"]);
app.factory('GetPortfolios', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/", {}, {});
});
app.factory('GetOrders', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43390014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Generics: Can you instantiate an object of type parameter inside class constructor? In the code segment below, I want to create the array object inside the GenericStack class constructor.
I understand why this is a problem. As per my understanding, "T" can be any class as far as the compiler is concerned. This class T can be an abstract class and hence cannot be instantiated. For example, java.lang.Number class is an abstract class and I could very well pass java.lang.Number for T.
My question now is the following:
Is there a way to tell the compiler (by some bounded parameters or perhaps something else) that the class that I am going to pass in place of T will be a concrete class that can be instantiated ? I know that I could easily create the array inside the main and then pass a reference but I find that to be a bit cluttered approach to implementing such requirement.
public class GenericStack<T> {
//Data for the stack is an array but can be changed to list.
public static final int stackSize = 10;
private T[] stackData;
private int tos;
public GenericStack(int size) {
stackData = new T[size]; // This line will error out
tos = -1;
}
public T pop() {
try {
return stackData[tos--];
} catch (Exception e) {
System.out.println("Stack empty.Cannot POP from an empty stack.");
return null;
}
}
public void push(T stackObj) {
try {
stackData[++tos] = stackObj;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Stack is full. Cannot push a element into a full stack.");
}
}
public static void main(String[] args) {
GenericStack<Integer> intStack = new GenericStack<Integer>(GenericStack.stackSize);
GenericStack<String> stringStack = new GenericStack<String>(GenericStack.stackSize);
}
}
A: You have to do something like this.
public GenericStack(int size) {
stackData = new Object[size];
tos = -1;
}
Then later
@SuppressWarning("unchecked")
public T pop() {
// check stack state
return (T)stackData[++tos];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64614930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java regex extract information out of brackets i cant figure out how i manage to solve the problem of getting information out of square brackets as well as the normal ones. I want the content of them both.
i tried:
Pattern p = Pattern.compile("\\[[^\\]]*\\]");
Pattern p1 = Pattern.compile("\\[|\\([^\\)]*|[^\\]]*\\]|\\)");
Pattern p2 = Pattern.compile("\\[|\\([^{\\]|\\)}]*\\]|\\)");
p works perfectly for the squared ones only and then i tried to add the normal braces, but no success. a sample of a string would be
"(info1) something-uninteresting [info2] s.u. [info3] s.u. (info4)"
A: Try the following:
[\\[(][^\\])]*[\\])]
A: Try the following:
(\\(.*?\\)|\\[.*?\\])*?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20124866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC Database to list with id reference I'm writing an MVC application and want to query my database with a search parameter and put all of the results into a list. Right now my code to try this looks like:
Character character = db.Characters.ToList().Find(User.Identity.GetUserId());
Which is throwing up a error. Is there a way I can do this? Break it down into two statements for example? I tried
Character character = db.Characters.Find(User.Identity.GetUserId());
character = character.ToList();
but that isn't working either.
A: When using the extension method Find() you must be sure that in your model you have the attribute [Key] in the property representing your Id (primary key in your table).
And you can try like this:
Character character = db.Characters.Find(User.Identity.GetUserId());
The line above will work but not this one character= character.ToList(); because you declare character as an object and you can't assign it to a list of object in your case Character
If you want it to work, you can do something like this:
var myCharacters =db.Characters.Where(c=>c.someField=="someValue");
List<Character> myList = myCharacters.ToList();
Hope it will help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23544004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: knitted markdown displayed correctly on browser/viewer but not shown properly inside shiny I have learnt to write markdown in RStudio and able to preview using browser/viewer by compiling the code. But when the same MD is shown inside a shiny app, although most of them shown correctly (including plots), some features like tab, TOC, plot captions etc are not shown inside shiny app.
The minimal code is produced here:
---
title: "Title"
output:
html_document:
toc: TRUE
toc_float:
collapsed: FALSE
smooth_scroll: FALSE
---
# Data Analysis {.tabset .tabset-fade .tabset-pills}
## Sub data Analysis
This section provides ...
I display the above code inside a shiny app server using:
output$markdown <- renderUI({
HTML(markdown::markdownToHTML('mymd.md'))
#HTML(rmarkdown::render(knit('mymd.Rmd')))
#includeHTML("shinybody.html")
})
and in ui, I am using uiOutput:
mainPanel(
uiOutput('markdown'))
Although shiny app display plots and text correctly, features like toc, tabs are not appearing properly. I cross checked by directly compiling md inside viewer/browser it displays correctly.
Any hand please..
A: ---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/) <img src=''www/ENG.jpg''
width=''24'' align=''center'' valign=''middle''> <img src=''www/my-passport-size-photo.jpg''
width=''24'' align=''center'' valign=''middle''>®'
date: "10/22/1984"
output:
html_document:
number_sections: yes
toc: yes
toc_depth: 4
toc_float:
collapsed: yes
smooth_scroll: yes
code_folding: hide
---
Changed yaml to below :
---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/) <img src=''www/ENG.jpg''
width=''24'' align=''center'' valign=''middle''> <img src=''www/my-passport-size-photo.jpg''
width=''24'' align=''center'' valign=''middle''>®'
date: "10/22/1984"
output:
html_document:
number_sections: yes
toc: yes
toc_depth: 4
code_folding: hide
---
figure 1 shows the collapsable menu as a line
figure 2 shows the tittle content at top
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48910548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove VIM as my Mac editor vs sublime How to remove VIM (completely) and change my mac command line editor to sublime?
I've spent the last three hours reading the same links on "how to remove VIM" only to get "how to remove MacVIM and reinstall it fresh" Or "How to remove Vim so I can reinstall it on Ubuntu"
My old laptop was fortunate to have a friend remove it but my new machine still has it installed.
I wish VIM would die in "words redacted to excessive profanity" dumpster fire while a hobo "words redacted to excessive profanity" to put out the fire
I've lost way too many hours trying to learn that outdated neckbeard elvish piece of UX trash so I want it gone. No, I'm not touching emacs.
Please tell me there is a way I can switch to sublime or am I permanently cursed to have this confusing black screen of death pop up when I try to git push or git tag stuff?
My original goal was to tag a git and push it but vim comes up and I can't figure out how to speak elvish.
I've been using PyCharm for a few years and love the interface but I need to dig deeper and a TDD Django book for class uses the terminal, it wants me to git -a "comments" so I need your advice.
So now I can't learn TDD Django because vim, MacVim and eMacs users flood the internet but I can't remove it nor figure out how to work it.
I've tried brew uninstall macvim which doesn't work because I have vim not macvim
I also tried sudo uninstall vim no luck as this is zsh mac not ubuntu
I tried brew uninstall vim to get No available formula or cask with the name "vim"
I've searched SO five times and keep getting the same links.
Alternates I've tried
brew uninstall ruby vim
per this post https://superuser.com/questions/1096438/brew-upgrade-broke-vim-on-os-x-dyld-library-not-loaded I tried, no luck.
brew uninstall --ignore-dependencies perl
brew uninstall vim
brew install vim
I'm not installing an app to remove another one, thanks but no thanks Nektony.
I don't know how to sidestep VIM, my solution for most things is to google it for a while and try a few things. If that doesn't work I unwind the changes in git with PyCharm and look for more help on StackOverflow.
Unless you know how to solve this it's like telling someone to get to a village following the Hindi roadsigns when they speak Russian.
I per the comments I clicked How can I make Sublime Text the default editor for Git? I also tried git config --global core.editor "subl -n -w" which kinda helps as it flashes scrolls past a bunch of menus but it didn't open sublime.
A: You don't have to remove Vim from your machine. Instead, tell your system and your tools to use Sublime Text as default editor. After you have followed that tutorial, which I must point out is part of Sublime Text's documentation, you should have a system-wide subl command that you can use instead of vim. For that, you need to add those lines to your shell configuration file:
export EDITOR=subl
export VISUAL=subl
which will be honoured by basically every CLI program susceptible to open a file in a text editor.
You can even add the following for good measure:
export GIT_EDITOR=subl
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67977280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
}
|
Q: How do you decrement time for minutes seconds hundredths? Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
A: Three issues appear to need attention.
*
*"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
*using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
*Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34234540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OCaml's let polymorphism implementation I'm confused about let polymorphism in OCaml.
Consider the following code:
A:
let f = (fun v -> v) in
((f 3), (f true))
B:
let f = (fun v -> v) in
((fun g ->
let f = g in
f) f)
C:
let f = (fun v -> v) in
((fun g ->
let f = g in
((f 3), (f true))) f)
For A and B, there is no problem. But for C, OCaml reports error:
Error: This expression has type bool but an expression was expected of type
int
So for A, when evaluating ((f 3), (f true)), f's type is 'a -> 'a,
for B, when evaluating let f = g in f, f's type is 'a -> 'a.
But for C, when evaluating ((f 3), (f true)), f's type is int -> int.
Why C's f doesn't have type 'a -> 'a?
I have difficulty in understanding the implementation of OCaml's
let polymorphism, I'll appreciate it a lot if anyone can give a concise
description of it with respect to the question.
A: Your code is unnecessarily confusing because you're using the same name f for two different things in B and also two different things in C.
Inside C you have this function:
fun g -> let f = g in (f 3, f true)
Again this is unnecessarily complicated; it's the same as:
fun g -> (g 3, g true)
The reason this isn't allowed is that it only works if g is a polymorphic function. This requires rank 2 polymorphism, i.e., it requires the ability to define function parameters that are polymorphic.
I'm not exactly sure what you're trying to do, but you can have a record type whose field is a polymorphic function. You can then use this record type to define something like your function:
# type r = { f : 'a . 'a -> 'a };;
type r = { f : 'a. 'a -> 'a; }
# (fun { f = g } -> (g 3, g true)) { f = fun x -> x };;
- : int * bool = (3, true)
# let myfun { f = g } = (g 3, g true);;
val myfun : r -> int * bool = <fun>
# myfun { f = fun x -> x };;
- : int * bool = (3, true)
The downside is that you need to pack and unpack your polymorphic function.
As a side comment, your example doesn't seem very compelling, because the number of functions of type 'a -> 'a is quite limited.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21011349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Flutter Provider/Consumer UI not Updating with Data Change I am new to Flutter and working on developing my first application. I an having trouble updating my UI based on data changes. I followed this tutorial: https://www.filledstacks.com/post/flutter-architecture-my-provider-implementation-guide/ (and added extra features with https://www.filledstacks.com/post/flutter-provider-architecture-sharing-data-across-your-models/), which walks through a MVVM setup using the GetIt library.
I have successfully passed the data through the viewmodels and services, but I can't get my UI to update. Essentially, I want a user to be able to tap the movie on their watchlist and remove it. This works in a data sense, but my Watchlist UI isn't updating when I pop back to it. My entire project is available at https://github.com/n0ahth0mas/movie_night, but the core files to this problem are listed here:
locator.dart
...
...
GetIt locator = GetIt.instance;
void setupLocator() {
locator.registerLazySingleton(() => AuthenticationService());
locator.registerLazySingleton(() => WatchlistService());
locator.registerLazySingleton(() => Api());
locator.registerLazySingleton(() => LoginModel());
locator.registerFactory(() => HomeModel());
locator.registerFactory(() => RemoveButtonModel());
locator.registerFactory(() => WatchlistModel());
}
watchlist_service.dart
...
...
class WatchlistService {
Api _api = locator<Api>();
List<Movie> _watchlist = [];
List<Movie> get watchlist => _watchlist;
Future getUserWatchlist(User user) async {
for (String id in user.watchlistId) {
_watchlist.add(await _api.getMovie(id));
}
}
bool inList(Movie movie) {
return _watchlist.contains(movie);
}
void editList(Movie movie, bool remove) {
if (remove) {
_watchlist.remove(movie);
print("removed " + movie.title + " from list in watchlist service");
} else {
_watchlist.add(movie);
print("added " + movie.title + " to list in watchlist service");
}
}
}
watchlist_model.dart
...
...
class WatchlistModel extends BaseModel {
WatchlistService _watchlistService = locator<WatchlistService>();
List<Movie> get watchlist => _watchlistService.watchlist;
Future getWatchlist(User user) async {
setState(ViewState.Busy);
await _watchlistService.getUserWatchlist(user);
setState(ViewState.Idle);
}
}
watchlist_view.dart
...
...
class WatchlistView extends StatelessWidget {
Widget _createMovieCard(Movie movie, BuildContext context) {
return CupertinoButton(
onPressed: () => _getInfo(movie, context),
child: Image.network(movie.getPoster(185)),
);
}
_getInfo(Movie movie, BuildContext context) {
Navigator.pushNamed(
context,
"details",
arguments: movie,
);
}
@override
Widget build(BuildContext context) {
return BaseView<WatchlistModel>(
onModelReady: (model) => model.getWatchlist(Provider.of<User>(context)),
builder: (context, model, child) => Scaffold(
body: model.state == ViewState.Idle
? CustomScrollView(
primary: false,
slivers: <Widget>[
CupertinoSliverNavigationBar(
largeTitle: Text("My Watchlist"),
trailing: Material(
color: Colors.transparent,
child: IconButton(
icon: Icon(CupertinoIcons.add_circled_solid),
onPressed: () =>
Navigator.pushNamed(context, 'search'))),
),
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio:
MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 1.7)),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return _createMovieCard(
model.watchlist[index], context);
}, childCount: model.watchlist.length),
),
],
)
: Center(child: CircularProgressIndicator())));
}
}
removebtn_model.dart
...
...
class RemoveButtonModel extends BaseModel {
WatchlistService _watchlistService = locator<WatchlistService>();
//bool watchlistStatus()
void removeMovie(Movie movie) {
print("removed " + movie.title + " from list in remove button model");
_watchlistService.editList(movie, true);
notifyListeners();
}
void addMovie(Movie movie) {
print("added " + movie.title + " to list in remove button model");
_watchlistService.editList(movie, false);
notifyListeners();
}
}
details_view.dart
...
...
class DetailsView extends StatelessWidget {
_makeStars(double voteAverage) {
double trueRating = voteAverage / 2;
print(trueRating);
return GFRating(
color: Colors.yellowAccent[700],
value: trueRating,
size: GFSize.SMALL,
allowHalfRating: true,
);
}
_backdrop(String link) {
if (link != null) {
return Image.network("http://image.tmdb.org/t/p/w780/$link");
} else
return Image.asset("assets/images/transparent.png");
}
@override
Widget build(BuildContext context) {
Movie movie = ModalRoute.of(context).settings.arguments;
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
CupertinoSliverNavigationBar(
largeTitle: Text(movie.title),
trailing:
Material(color: Colors.transparent, child: RemoveButton(movie)),
),
SliverToBoxAdapter(
child: Column(
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 20)),
Center(child: Image.network(movie.getPoster(342))),
Center(
child: Container(
padding: EdgeInsets.all(10),
child: Center(
child: Text(movie.title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 40, fontWeight: FontWeight.w800))),
)),
Container(
padding: EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_makeStars(movie.voteAverage),
Text("platform",
style: Theme.of(context).textTheme.headline5),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(20, 0, 10, 50),
child: Text(movie.overview),
),
_backdrop(movie.backdropPath)
],
))
],
),
);
}
}
remove_btn.dart
...
...
class RemoveButton extends StatelessWidget {
final Movie movie;
RemoveButton(this.movie);
_showDialog(String id, bool inWatchlist, BuildContext context,
RemoveButtonModel model) {
if (inWatchlist) {
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text("Remove from your watchlist?"),
actions: <Widget>[
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: Text("Cancel"),
),
CupertinoDialogAction(
textStyle: TextStyle(color: Colors.red),
onPressed: () => _deletelist(id, context, model),
child: Text("Remove"),
)
]));
} else {
showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text("Add to your watchlist?"),
actions: <Widget>[
CupertinoDialogAction(
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: Text("Cancel"),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _addList(id, context, model),
child: Text("Add"),
)
]));
}
}
_deletelist(String id, BuildContext context, RemoveButtonModel model) {
model.removeMovie(movie);
Provider.of<User>(context).deleteFromWatchlist(id);
//Navigator.pushNamed(context, 'watchlist');
Navigator.popUntil(context, ModalRoute.withName('watchlist'));
}
_addList(String id, BuildContext context, RemoveButtonModel model) {
model.addMovie(movie);
Provider.of<User>(context).addToWatchList(id);
Navigator.popUntil(context, ModalRoute.withName('watchlist'));
}
Widget _rightBtn(Movie movie, BuildContext context, RemoveButtonModel model) {
if (Provider.of<User>(context).inWatchlist(movie)) {
return IconButton(
icon: Icon(Icons.remove_circle),
color: Colors.blue,
onPressed: () =>
_showDialog(movie.id.toString(), true, context, model));
} else {
return IconButton(
icon: Icon(Icons.add_circle),
color: Colors.blue,
onPressed: () =>
_showDialog(movie.id.toString(), false, context, model));
}
}
@override
Widget build(BuildContext context) {
return BaseView<RemoveButtonModel>(
builder: (context, model, child) => _rightBtn(movie, context, model),
);
}
}
Thanks for your help! I've been stuck on this for the past 3 days and cannot figure out what I'm doing wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63081191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you reuse mapping functions on Nested entities in Entity Framework? I have seen multiple questions that are similar to this one but I think my case is slightly different. I'm using EF6 to query the database and I'm using data projection for better queries.
Given that performance is very important on this project I have to make sure to just read the actual fields that I will use so I have very similar queries that are different for just a few fields as I have done this I have noticed repetition of the code so I'm been thinking on how to reuse code this is currently what I Have:
public static IEnumerable<FundWithReturns> GetSimpleFunds(this DbSet<Fund> funds, IEnumerable<int> fundsId)
{
IQueryable<Fund> query = GetFundsQuery(funds, fundsId);
var results = query
.Select(f => new FundWithReturns
{
Category = f.Category,
ExpenseRatio = f.ExpenseRatio,
FundId = f.FundId,
Name = f.Name,
LatestPrice = f.LatestPrice,
DailyReturns = f.FundDailyReturns
.Where(dr => dr.AdjustedValue != null)
.OrderByDescending(dr => dr.CloseDate)
.Select(dr => new DailyReturnPrice
{
CloseDate = dr.CloseDate,
Value = dr.AdjustedValue.Value,
}),
Returns = f.Returns.Select(r => new ReturnValues
{
Daily = r.AdjDaily,
FiveYear = r.AdjFiveYear,
MTD = r.AdjMTD,
OneYear = r.AdjOneYear,
QTD = r.AdjQTD,
SixMonth = r.AdjSixMonth,
ThreeYear = r.AdjThreeYear,
YTD = r.AdjYTD
}).FirstOrDefault()
})
.ToList();
foreach (var result in results)
{
result.DailyReturns = result.DailyReturns.ConvertClosingPricesToDailyReturns();
}
return results;
}
public static IEnumerable<FundListVm> GetFundListVm(this DbSet<Fund> funds, string type)
{
return funds
.Where(f => f.StatusCode == MetisDataObjectStatusCodes.ACTIVE
&& f.Type == type)
.Select(f => new FundListVm
{
Category = f.Category,
Name = f.Name,
Symbol = f.Symbol,
Yield = f.Yield,
ExpenseRatio = f.ExpenseRatio,
LatestDate = f.LatestDate,
Returns = f.Returns.Select(r => new ReturnValues
{
Daily = r.AdjDaily,
FiveYear = r.AdjFiveYear,
MTD = r.AdjMTD,
OneYear = r.AdjOneYear,
QTD = r.AdjQTD,
SixMonth = r.AdjSixMonth,
ThreeYear = r.AdjThreeYear,
YTD = r.AdjYTD
}).FirstOrDefault()
}).OrderBy(f=>f.Symbol).Take(30).ToList();
}
I'm trying to reuse the part where I map the f.Returns so I tried created a Func<> like the following:
private static Func<Return, ReturnValues> MapToReturnValues = r => new ReturnValues
{
Daily = r.AdjDaily,
FiveYear = r.AdjFiveYear,
MTD = r.AdjMTD,
OneYear = r.AdjOneYear,
QTD = r.AdjQTD,
SixMonth = r.AdjSixMonth,
ThreeYear = r.AdjThreeYear,
YTD = r.AdjYTD
};
and then use like this:
public static IEnumerable<FundListVm> GetFundListVm(this DbSet<Fund> funds, string type)
{
return funds
.Where(f => f.StatusCode == MetisDataObjectStatusCodes.ACTIVE
&& f.Type == type)
.Select(f => new FundListVm
{
Category = f.Category,
Name = f.Name,
Symbol = f.Symbol,
Yield = f.Yield,
ExpenseRatio = f.ExpenseRatio,
LatestDate = f.LatestDate,
Returns = f.Returns.Select(MapToReturnValues).FirstOrDefault()
}).OrderBy(f=>f.Symbol).Take(30).ToList();
}
The compiler is ok with it but at runtime, it crashes and says: Internal .NET Framework Data Provider error 1025
I tried to convert the Func into Expression like I read on some questions and then using compile() but It didn't work using AsEnumerable is also not an option because It will query all the fields first which is what I want to avoid.
Am I trying something not possible?
Thank you for your time.
A: It definitely needs to be Expression<Func<...>>. But instead of using Compile() method (not supported), you can resolve the compile time error using the AsQueryable() method which is perfectly supported (in EF6, the trick doesn't work in current EF Core).
Given the modified definition
private static Expression<Func<Return, ReturnValues>> MapToReturnValues =
r => new ReturnValues { ... };
the sample usage would be
Returns = f.Returns.AsQueryable().Select(MapToReturnValues).FirstOrDefault()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47210244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Powershell - CreateFromDirectory with excluding some types of file I am using a compress method
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
but i need to exclude some specific file types - like .mp3, .mkv, .avi and such. Unfortunately i wasn't able to find a way how to do that :-(. Does anybody know how to do that?
A: Use an application which allows you more flexible archiving from the command line, such as 7-Zip.
Alternately, if you insist on scripting your own solution, use Get-ChildItem, filter out the undesireables, and then iterate over the results and build the archive manually using System.IO.Compression.ZipFileExtensions. That seems potentially pretty error prone to me, however.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31386264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Karate check if a phrase available in the response I've a response
{ errors: [
{
code: 123,
reason: "this is the reason1 is dynamically generated"
} ,
{
code: 234,
reason: "this is the reason2 for another random reason"
}
...
...
}
Now when I validate this response
I use following
...
...
And match response.errors[*].reason contains "this is the reason"
This validation fails, because there is an equality check for complete String for every reason with the phrase mentioned in the condition. this is reason1
I tried few wild cards but didn't work either, how to do it ?
A: You missed each:
And match each response.errors[*].reason contains "this is reason"
Refer: https://github.com/karatelabs/karate#match-each
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73391284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When add a column to a data.table, what's then best way to add if else conditions? For example, I would like to do something like:
dt[isFlag, newCol:= A]
dt[!isFlag, newCol:=B]
Or should I do this?
dt[, newCol:= B]
dt[isFlag, newCol:=A]
Or this?
dt[, newCol:= if (isFlag) then A else B] # this only works if isFlag is a scalar
Or
dt[, newCol:= ifelse(isFlag, A, B)] # this only works if isFlag is a vector
What is the best way?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18413324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to combine two sql queries result I have designed the following two queries and i can join them with the left outer join to get the required results, but is there any way to just write one query to get the same results? How can i simplify it.
First Query brings total number of prople who have worked on the project and the second query is showing only those people who have worked on the project but belongs to different office.
First Query
SELECT
VisitDate = LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalUsed
FROM Visits v
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID
WHERE a.ClientID IN (22,33)
Group by Datename(month,v.VisitDate)
Second query
SELECT
VisitDate = LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalContractorUsed
FROM Visits v
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID
WHERE a.ClientID IN (22,33)
**AND i.OfficeID IN (5)**
Group by Datename(month,v.VisitDate)
A: You can use conditional aggregation in a single query:
SELECT VisitDate = LEFT(Datename(month,v.VisitDate),3),
COUNT( distinct i.InspectorID) AS TotalUsed,
COUNT(distinct case when i.OfficeID IN (5) then i.InspectorID end) AS TotalContractorUsed
FROM Visits v
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID
WHERE a.ClientID IN (22,33)
Group by Datename(month,v.VisitDate);
A: I have not executed the query. Pls check.
;WITH CTE (VisitDate, TotalUsed) AS
(SELECT
VisitDate = LEFT(Datename(month,v.VisitDate),3)
,COUNT( distinct i.InspectorID) AS TotalUsed
FROM Visits v
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID
WHERE a.ClientID IN (22,33)
Group by Datename(month,v.VisitDate))
SELECT
CTE.VisitDate
,CTE.TotalUsed
,ISNULL(COUNT(distinct i.InspectorID),0) AS TotalContractorUsed
FROM CTE
LEFT JOIN Visits v ON CTE.VisitDate = v.VisitDate
INNER JOIN InspectionScope insp ON insp.AssignmentID = v.AssignmentID
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
INNER JOIN Inspectors i ON i.InspectorID = insp.InspectorID
WHERE a.ClientID IN (22,33) AND i.OfficeID IN (5)
Group by Datename(month,v.VisitDate)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21385733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I check.js not working in firefox icheck.js working in chrome and IE but not working in firefox
<script type="text/javascript">
$(document).ready(function () {
$('.check').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green',
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.check').on('ifChecked', function () {
$("#butt").attr("disabled", false);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.check').on('ifUnchecked', function () {
$("#butt").attr("disabled", true);
});
});
</script>
above script not working in firefox
please help me
A: Try to check if $('.check') element is not inside of button or other HTML attribute.
For me the problem was:
<button type="button" class="btn btn-default icheck-button">
<input id="check-all" type="checkbox" aria-label="...">
</button>
So i removed button attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30087373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Managing List of objects using PrimeFaces 5 I have trouble "managing" List of objects using Primefaces 5.0.8.
I want to create "form" with functionality:
*
*add new objects to list
*remove objects from list
*edit any object from the list
All functionality should be in one page without any dialogs. For list representation I am using primeface "dataTable" component. And I have problem to update/process only part of dataTable then remove button is clicked.
Simplified jsf view, I have come up with:
<p:dataGrid id="myObjectList"
value="#{myManagedBean.myObjectList}"
var="obj"
rowIndexVar="dataGridRowIndex"
columns="1">
<p:outputLabel value="row number: #{dataGridRowIndex}"/>
<h:panelGrid id="parentGrid" columns="2">
<p:outputLabel value="property1" for="property1Input"/>
<p:inputText id="property1Input" value="#{obj.property1}" required="true"/>
<p:outputLabel value="property2" for="property2Input"/>
<p:inputText id="property2Input" value="#{obj.property2}"/>
</h:panelGrid>
<p:commandButton id="removeButton"
icon="ui-icon-minus"
update="myObjectList"
process="@this"
actionListener="#{myManagedBean.myObjectList.remove(obj)}"
rendered="#{myManagedBean.myObjectList.size() > 1}"/>
<p:commandButton id="addButton"
icon="ui-icon-plus"
update="myObjectList"
process="myObjectList"
actionListener="#{myManagedBean.addNewObjectToList()}"
rendered="#{myManagedBean.myObjectList.size() == dataGridRowIndex +1}"/>
<p:separator/>
</p:dataGrid>
Simplified managed bean:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
@Named
@Scope(value = "view")
public class MyManagedBean {
private final List<MyObject> myObjectList = new ArrayList<>();
@PostConstruct
public void init() {
myObjectList.add(new MyObject("test1"));
myObjectList.add(new MyObject("test2"));
myObjectList.add(new MyObject(""));
}
public void addNewObjectToList() {
myObjectList.add(new MyObject());
}
public List<MyObject> getMyObjectList() {
return myObjectList;
}
}
And simplified “business” object:
public class MyObject {
private String property1;
private String property2;
public MyObject() {
}
public MyObject(String property1) {
this.property1 = property1;
}
public String getProperty1() {
return property1;
}
public void setProperty1(String property1) {
this.property1 = property1;
}
public String getProperty2() {
return property2;
}
public void setProperty2(String property2) {
this.property2 = property2;
}
}
This code has one major problem:
If user enters some text to “property1Input” in first row and then clicks “removeButton” on second row, value entered to the first row disappears (because all “myObjectList” is updated and “removeButton” does not submit values)
I cannot submit values on “removeButton” because I do not want show validations/conversion errors then user clicks “removeButton” (“business” object in example are simplified).
I cannot add ‘immediate=”true” + ‘process=”myObjectList”’ for “removeButton” because of “removed” value “stays” input component, so if after “remove” user clicks “add” he will see removed value.
The only working workaround I found is on “removeButton” click not remove object from list, but hide row in dataTable, but this workaround requires lots of additional coding and looks really ugly.
So is there any other simple solution for this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25918700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pass a Folder and a Variable to Next Macro with Excel VBA I'm using Excel VBA.
In the first macro, I have
Sub SearchReport()
'code here
Report FileSystem.getFolder(HostFolder)
End Sub
Report is the second macro name and I am able to pass the "folder" into this macro
Sub Report (Folder)
'code here
End Sub
How if I want to pass another variable p which is an integer? I need something like this in the second macro
Sub Report (Folder, p)
I have no idea on how to declare it in the first macro, so I am here to seek for help. Any effort is appreciated! Thanks!
A: Sub SearchReport()
Dim p As Integer
p = 25
Report FileSystem.getFolder(HostFolder), p
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45538565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How will a browser differentiate between XHTML 1.0 and XHTML 5? By my understanding, neither XHTML (1.0, 1.1) nor XHTML 5 required a DTD. If this is true, how will a browser differentiate between the two?
I can only assume that when the browser vendors support (X)HTML 5, all XHTML will be interpreted under XHTML 5 rules (assuming XHTML 5 is a superset of XHTML 1.0). Is this how it's going to work?
A: From http://hsivonen.iki.fi/xhtml2-html5-q-and-a/ :
If I can use any doctype for XHTML5, how can browsers tell XHTML 1.0 and XHTML5 apart?
They can’t and they don’t need to. By design, a user agent that implements XHTML5 will process inputs authored as XHTML 1.0 appropriately.
A: There is no XHTML 5. Currently there is HTML 4.01 and XHTML 1.0. There will be no XHTML 2.0. There will only be HTML 5. HTML 5 is not an XML standard (meaning an HTML 5 document is not an XML document).
Perhaps you're looking at HTML 5 + XML = XHTML 5. I guess you can express HTML 5 as XML but as far as I know this is non-standard. More specifically, this is just a serialization method for the document tree rather than a standard.
To clarify this issue, take a look at HTML 5 and XHTML 5 - one vocabulary, two serializations. Even from the title it says "one vocabulary, two serializations". And Conversation With X/HTML 5 Team:
The XHTML 5 spec says that "generally speaking, authors are
discouraged from trying to use XML on
the Web". Why write an XML spec like
XHTML 5 and then discourage authors
from using it? Why not just drop
support for XML (XHTML 5)?
Some people are going to use XML with
HTML 5 whatever we do. It's a simple
thing to do — XML is a metalanguage
for describing tree structures, HTML 5
is a tree structure, it's obvious that
XML can be used to describe HTML 5.
The problem is that if we don't
specify it, then everyone who thinks
it is obvious and goes ahead and does
it will do it in a slightly different
way, and we'll have an
interoperability nightmare. So instead
we bite the bullet and define how it
must work if people do it.
XHTML 1.0 was a standard. It differed to HTML 4. XHTML 5, if you can call it that, is nothing more than representing HTML 5 documents in XML form.
A: Browsers won't. The elements exist in the same namespace, and have the same meaning, except where the WHATWG have decided to change them — such as the b element — where browsers are just going to have to muddle through.
A: It would be possible to distinguish by DOCTYPE (which is different for HTML5 and XHTML 1.x), but its presence is specifically non-mandatory in XHTML5; and element namespace is the same. So, in general, there's no good way to distinguish them. If you want to write portable XHTML5, I guess providing DOCTYPE is your best bet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1149337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Use column field inside Django filter method I have a field in the database which comes as a string (x). I need to convert it in a format to be used inside filter() method. How is this possible?
Also when field is none i want to use something to return True. Like filter(1=1) to get rid of the error
def DeviceDetailView(request,device_id):
View_filtering = Applications.objects.values_list('view_filtering').filter(pk=2)
#x gives data_type=1
x= View_filtering[0][0]
#should be DeviceData.objects.filter(data_type=1) but x is a string
DeviceData.objects.filter(x)
A: Considering that the value of x is an expression that should be used inside the filter method, i.e x can be something like x = 'device_id=5', then you can do the following:
x = 'device_id=5'
temp_list = x.split('=')
Now that you have separated the keyword and the value from the expression, then you can use temp_list inside the filter method as follows, unpacking a dictionary created in-place:
DeviceData.objects.filter(**{temp_list[0]: temp_list[1]})
For the case x equals None or there's some other problem with the value of the keywords inside x, you can handle those exceptions as follows (following EAFP approach):
x = 'device_id=5'
try:
temp_list = x.split('=')
qs = DeviceData.objects.filter(**{temp_list[0]: temp_list[1]})
except (ValueError, TypeError, AttributeError) as e:
qs = DeviceData.objects.all()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60169630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write PIL image filter for plain pgm format? How can I write a filter for python imaging library for pgm plain ascii format (P2). Problem here is that basic PIL filter assumes constant number of bytes per pixel.
My goal is to open feep.pgm with Image.open(). See http://netpbm.sourceforge.net/doc/pgm.html or below.
Alternative solution is that I find other well documented ascii grayscale format that is supported by PIL and all major graphics programs. Any suggestions?
feep.pgm:
P2
# feep.pgm
24 7
15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 3 3 3 3 0 0 7 7 7 7 0 0 11 11 11 11 0 0 15 15 15 15 0
0 3 0 0 0 0 0 7 0 0 0 0 0 11 0 0 0 0 0 15 0 0 15 0
0 3 3 3 0 0 0 7 7 7 0 0 0 11 11 11 0 0 0 15 15 15 15 0
0 3 0 0 0 0 0 7 0 0 0 0 0 11 0 0 0 0 0 15 0 0 0 0
0 3 0 0 0 0 0 7 7 7 7 0 0 11 11 11 11 0 0 15 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
edit: Thanks for the answer, It works... but I need a solution that uses Image.open(). Most of python programs out there use PIL for graphics manipulation (google: python image open). Thus, I need to be able to register a filter to PIL. Then, I can use any software that uses PIL. I now think mostly scipy, pylab, etc. dependent programs.
edit Ok, I think I got it now. Below is the wrapper pgm2pil.py:
import Image
import numpy
def pgm2pil(filename):
try:
inFile = open(filename)
header = None
size = None
maxGray = None
data = []
for line in inFile:
stripped = line.strip()
if stripped[0] == '#':
continue
elif header == None:
if stripped != 'P2': return None
header = stripped
elif size == None:
size = map(int, stripped.split())
elif maxGray == None:
maxGray = int(stripped)
else:
for item in stripped.split():
data.append(int(item.strip()))
data = numpy.reshape(data, (size[1],size[0]))/float(maxGray)*255
return numpy.flipud(data)
except:
pass
return None
def imageOpenWrapper(fname):
pgm = pgm2pil(fname)
if pgm is not None:
return Image.fromarray(pgm)
return origImageOpen(fname)
origImageOpen = Image.open
Image.open = imageOpenWrapper
There is a slight upgrade to misha's answer. Image.open has to be saved in order to prevent never ending loops. If pgm2pil returns None wrapper calls pgm2pil which returns None which calls pgm2pil...
Below is the test function (feep_false.pgm is a malformed pgm e.g. "P2" -> "FOO" and lena.pgm is just the image file):
import pgm2pil
import pylab
try:
pylab.imread('feep_false.pgm')
except IOError:
pass
else:
raise ValueError("feep_false should fail")
pylab.subplot(2,1,1)
a = pylab.imread('feep.pgm')
pylab.imshow(a)
pylab.subplot(2,1,2)
b = pylab.imread('lena.png')
pylab.imshow(b)
pylab.show()
A: The way I currently deal with this is through numpy:
*
*Read image into a 2D numpy array. You don't need to use numpy, but I've found it easier to use than the regular Python 2D arrays
*Convert 2D numpy array into PIL.Image object using PIL.Image.fromarray
If you insist on using PIL.Image.open, you could write a wrapper that attempts to load a PGM file first (by looking at the header). If it's a PGM, load the image using the steps above, otherwise just hands off responsibility to PIL.Image.open.
Here's some code that I use to get a PBM image into a numpy array.
import re
import numpy
def pbm2numpy(filename):
"""
Read a PBM into a numpy array. Only supports ASCII PBM for now.
"""
fin = None
debug = True
try:
fin = open(filename, 'r')
while True:
header = fin.readline().strip()
if header.startswith('#'):
continue
elif header == 'P1':
break
elif header == 'P4':
assert False, 'Raw PBM reading not implemented yet'
else:
#
# Unexpected header.
#
if debug:
print 'Bad mode:', header
return None
rows, cols = 0, 0
while True:
header = fin.readline().strip()
if header.startswith('#'):
continue
match = re.match('^(\d+) (\d+)$', header)
if match == None:
if debug:
print 'Bad size:', repr(header)
return None
cols, rows = match.groups()
break
rows = int(rows)
cols = int(cols)
assert (rows, cols) != (0, 0)
if debug:
print 'Rows: %d, cols: %d' % (rows, cols)
#
# Initialise a 2D numpy array
#
result = numpy.zeros((rows, cols), numpy.int8)
pxs = []
#
# Read to EOF.
#
while True:
line = fin.readline().strip()
if line == '':
break
for c in line:
if c == ' ':
continue
pxs.append(int(c))
if len(pxs) != rows*cols:
if debug:
print 'Insufficient image data:', len(pxs)
return None
for r in range(rows):
for c in range(cols):
#
# Index into the numpy array and set the pixel value.
#
result[r, c] = pxs[r*cols + c]
return result
finally:
if fin != None:
fin.close()
fin = None
return None
You will have to modify it slightly to fit your purposes, namely:
*
*Deal with P2 (ASCII, greyscale) instead of P1 (ASCII, bilevel).
*Use a different container if you're not using numpy. Normal Python 2D arrays will work just fine.
EDIT
Here is how I would handle a wrapper:
def pgm2pil(fname):
#
# This method returns a PIL.Image. Use pbm2numpy function above as a
# guide. If it can't load the image, it returns None.
#
pass
def wrapper(fname):
pgm = pgm2pil(fname)
if pgm is not None:
return pgm
return PIL.Image.open(fname)
#
# This is the line that "adds" the wrapper
#
PIL.Image.open = wrapper
I didn't write pgm2pil because it's going to be very similar to pgm2numpy. The only difference will be that it's storing the result in a PIL.Image as opposed to a numpy array. I also didn't test the wrapper code (sorry, a bit short on time at the moment) but it's a fairly common approach so I expect it to work.
Now, it sounds like you want other applications that use PIL for image loading to be able to handle PGMs. It's possible using the above approach, but you need to be sure that the above wrapper code gets added before the first call to PIL.Image.open. You can make sure that happens by adding the wrapper source code to the PIL source code (if you have access).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4270700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: how do you make a request from client to server locally using fetch without getting an opaque response? I'm running a react app on localhost:3000, and a go server on localhost:8000.
When I make a request from the client using fetch - the response is opaque so I'm not able to access the data.
How do I make a valid cross-origin request?
client:
componentWillMount() {
const url = 'https://localhost:8000/api/items'
fetch(url, { mode: 'cors' })
.then(results => {
return results.json()
}).then(data => {
let items = data;
this.setState({items})
})
}
server:
func GetItems(w http.ResponseWriter, r *http.Request) {
items := getItems()
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(items)
}
From what I've read - it's expected that requests made across resources should be opaque - but for local development - how do you get access to the JSON?
After looking at the definitions for request types I found this:
cors: Response was received from a valid cross-origin request. Certain
headers and the body may be accessed.
I think I need to set up a valid cross-origin request.
I got it!
This question helped resolve how to set up CORS in golang: Enable CORS in Golang
3 key things here:
*
*Set the mode in the client request to cors
*Set the Access-Control-Allow-Origin header on the server to *
*Call .json() on the result in the client, and in a
following promise you can access the data.
A: w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("content-type", "application/json")
You can try to add them in the handleFunc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51297077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simple threading question, locking non local changes Ok first I must preface this question with a disclaimer, I'm really new to threading so this may be a 'newbie' question but I searched google and couldn't find an answer. As I understand it a critical section is code that can be accessed by two or more threads, the danger being one thread will overwrite a value before the other is finished and vice versa. What can you do about changes made outside of your class for example, I have a line monitoring program:
int currentNumber = provider.GetCurrentNumber();
if(provider.CanPassNumber(false, currentNumber))
{
currentNumber++;
provider.SetNumber(currentNumber);
}
and on another thread I have something like this:
if(condition)
provider.SetNumber(numberToSet);
Now I'm afraid that in the first function I get currentNumber which is 5, right after that on another thread the number is set to 7 and then it rewrites the 7 to 6, ignoring the change made by the thread that set it to 7.
Is there anyway to lock provider.SetNumber until the first function finishes? The critical section is basically the currentNumber which can be changed by many places in the program.
I hope I made myself clear, if not let me know and I will try to explain myself better.
EDIT:
Also I made the functions really short for the example. In reality the function is much longer and makes changes to currentNumber many times so I don't really want to put a lock around the entire function. If I lock every call to provider.SetNumber and release it after I finish it can change during the time it is released before I lock it again to call provider.SetNumber. Honestly I'm also worried about locking the entire function because of performance and deadlock.
A: Rather than using the lock() keywords I'd suggested seeing if you can use the Interlocked class which is designed for small operations. It's got much less overhead than lock, in fact can be down to a single CPU instruction on some CPUs.
There are a couple of methods of interest for you, Exchange and Read, both of which are thread safe.
A: You want to look into the Lock keyword. Also you might want to this tutorial to Threading in C#.
A: As Filip said, lock is useful here.
Not only should you lock on provider.SetNumber(currentNumber), you also need to lock on any conditional that the setter depends on.
lock(someObject)
{
if(provider.CanPassNumber(false, currentNumber))
{
currentNumber++;
provider.SetNumber(currentNumber);
}
}
as well as
if(condition)
{
lock(someObject)
{
provider.SetNumber(numberToSet);
}
}
If condition is reliant on numberToSet, you should take the lock statement around the whole block. Also note that someObject must be the same object.
A: You can use the lock statement, to enter a critical section with mutual exclusion. The lock will use the object's reference to differentiate one critical section from another, you must have the same reference for all your lock if it accesses to the same elements.
// Define an object which can be locked in your class.
object locker = new object();
// Add around your critical sections the following :
lock (locker) { /* ... */ }
That will change your code to :
int currentNumber = provider.GetCurrentNumber();
lock (locker)
{
if(provider.CanPassNumber(false, currentNumber))
{
currentNumber++;
provider.SetNumber(currentNumber);
}
}
And :
if(condition)
{
lock (locker)
{
provider.SetNumber(numberToSet);
}
}
A: Well first of im not so good with threading but a critical section is a part of your code that can only be accessed my one thread at a time not the other way around..
To create a critical section is easy
Lock(this)
{
//Only one thread can run this at a time
}
note: that this should be replaced with some internal object...
A: In your SetNumber method you can simply use a lock statement:
public class MyProvider {
object numberLock = new object();
...
public void SetNumber(int num) {
lock(numberLock) {
// Do Stuff
}
}
}
Also, note that in your example currentNumber is a primitive (int), which means that variable's value won't be overwritten should your provider's actual data member's value change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4814808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue with Q.all where it won't wait for all promises to complete I have put up a small example of my use case, see below (jsfiddle: https://jsfiddle.net/BWNba/165/):
Basically Q.all would only work correctly when the biggest job is processed first. Is there anything I am doing here to get this to work correctly ?
function findPersonWithId(id) {
var deffered = Q.defer();
setTimeout(function(){
var newPerson = {id: 123}
deffered.resolve(newPerson)
},300)
return deffered.promise;
}
function loadHobbies(person) {
var deffered = Q.defer();
setTimeout(function(){
person.hobbies = ['programming', 'surfing', 'cooking']
deffered.resolve(person)
},100)
return deffered.promise;
}
function loadAddress(person) {
var deffered = Q.defer();
setTimeout(function(){
person.address = 'Melbourne, Australia'
deffered.resolve(person)
},200)
return deffered.promise;
}
function loadPersonalDetails(person) {
var deffered = Q.defer();
setTimeout(function(){
person.name = 'Bob'
person.age = 99
person.gender = 'male'
deffered.resolve(person)
},300)
return deffered.promise;
}
function loadRand(person) {
var deffered = Q.defer();
var rand = ~~(Math.random() * 1000)
setTimeout(function(){
person[rand] = rand
deffered.resolve(person)
},rand)
return deffered.promise;
}
function getPersonChain() {
return findPersonWithId(123)
.then(loadHobbies)
.then(loadAddress)
.then(loadPersonalDetails)
}
function getPersonQAllSmFirst() {
return findPersonWithId(123)
.then(function(person){
return Q.all(
loadHobbies(person),
loadAddress(person),
loadPersonalDetails(person)
)
})
}
function getPersonQAllLgFirst() {
return findPersonWithId(123)
.then(function(person){
return Q.all(
loadPersonalDetails(person),
loadHobbies(person),
loadAddress(person)
)
})
}
getPersonChain()
.done(function(person){
$('.person').append(JSON.stringify(person))
})
getPersonQAllSmFirst()
.done(function(person){
$('.person2').append(JSON.stringify(person))
})
getPersonQAllLgFirst()
.done(function(person){
$('.person3').append(JSON.stringify(person))
})
A: Q.all accepts an array of promises and returns Promise which is resolved if all promises are resolved or rejected if one of them is rejected.
Your calls to Q.all(promise, promise, promise) are not valid. It has to be Q.all([promise, promise, promise]).
Returned promise is resolved with an array of results from promises, in your case it will be 3 same persons.
Little example (will print 1, 2, 3 to console):
Q.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]).then(function(numbers) { console.log(numbers); };
To make it work, you need to change your code like this https://jsfiddle.net/g8sgqrof/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35681999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: new API key for Filecoin Lotus node I'm trying to generate a new API-KEY for a Lotus node (existing one may have been compromised), but when I run lotus auth create-token --perm read it simply returns the existing key. The docs seem to suggest there is also an authnew command, but lotus authnew create-token --perm read throws an error "No help topic for 'authnew'". Does anyone know how to generate a new api key, assuming this is possible? Thanks so much for any assistance!
edit: it looks like lotus auth create-token --perm read just generates a key from the value in ~/.lotus/token, so the real question may be how to refresh or update this value...
A: try to use:
lotus auth create-token --perm read
I guess you should change your token to use those perms
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70699929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Parameter access with in a groovy script in jenkins throws exception I have a string parameter called VERSION which is set to example - 0000
Below is what i am trying in groovy pipeline in jenkins
import hudson.model.*
/*// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction
}?.parameters
parameters.each {
println "parameter ${it.name}:"
println it.dump()
}
*/
print ("VERSION is ${VERSION}")
def version_value = build.buildVariableResolver.resolve("VERSION")
It throws the below exception what is wrong with accessing "build"?
[Pipeline] echo
VERSION is 0000
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: build for class: WorkflowScript
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:34)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:12)
at ___cps.transform___(Native Method)
A: I think you are trying to access hudson.model.build, but I believe that is a class and not an object. It is also not a property of the current object - WorkflowScript. So it simply does not exist.
In a pipeline script you should have access to "currentBuild". Go to your.jenkins.server.url/pipeline-syntax/globals to see what global variables scripts run via that server can access.
That same page should also show that you have access to a variable called "params" Perhaps what you are looking for is there?
From your question, it is unclear what your end goal is. You already have access to VERSION as demonstrated by the echo statement. So why are you trying to get at it from a build object? You may get more help if you update to explain what the end goal is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48551401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Authentication against VDS LDAP I want to authenticate user against VDS(virtual directory server) using Java.
*
*How VDS is different from LDAP? Or VDS is also working on LDAP
protocol?
Please help with any sample Java code for authentication against VDS
A sample code to authenticate against LDAP is as below
String userName = "John P R-Asst General Manager";
String passWord = "asdfgh123";
String base ="OU=SOU,DC=example,DC=com";
String dn = "cn=" + userName + "," + base;
String ldapURL = "ldap://mdsdc3.example.com:389";
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, ldapURL);
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, dn);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(authEnv);
return true;
} catch (NamingException namEx) {
return false;
}
To authenticate against VDS, is a complete dn required. Because as per experts only username and password needs to be send to VDS. It will automatically find its DN and do the authentication.
Will be thankful if anyone provide nice reference material regarding ldap and vds
A: A virtual directory server is a type of server that provides a unified view of identities regardless of how they are stored. (Or you may prefer Wikipedia's definition: "a software layer that delivers a single access point for identity management applications and service platforms"
LDAP is a protocol (hence the "P") for communicating with directory servers.
There isn't a necessary link between LDAP and a VDS, but it is likely that a VDS provides and LDAP interface and, potentially, other programmatic interfaces (Kerberos in particular comes to mind). The details of how you communicate with the VDS are going to be dependent on the configuration you are trying to talk to, but LDAP is a good bet.
Regarding needing a full DN, you don't even need a full DN to authenticate against plain Active Directory. The more usual mode would be to supply something like DOMAIN\username (using the sAMAccountName) or username@dc.example.com (that is, the user principal name) as the SECURITY_PRINCIPAL. In your example, the user would need to type John P R-Asst General Manager rather than anything they are likely to regard as their "user name."
You do, however, need to work out what the VDS you are trying to communicate with requires as the user name. Does it need DOMAIN\username, something else? These are details that whoever runs the VDS you are communicating with should be able to provide you.
In code, you should wind up with something like this (assuming you can use LDAP):
String userName = "DOMAIN\johnp";
String passWord = "asdfgh123";
String ldapURL = "ldaps://vds.example.com";
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, ldapURL);
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, username);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(authEnv);
return true;
} catch (NamingException namEx) {
return false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33388306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: binary masks in CAPL CAPL allows bitwise operations. Since writing parsers is becoming a tedious operation these days, I'm wandering if there is a way to write binary numbers for masks, e.g.
variables
{
byte a = 0x03;
}
on key 'a'
{
a &= 0b11; // <- invalid, how can we write this?
a &= 0x03;
a &= 3;
}
A: It is not supported by CAPL.
You just have to add the bits and use the obtained number in Hex or Dec format.
Alternatively you can create a function to display it in your report as a binary if you really want to
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61639260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS CGImage leak
I used Instruments Leak, and found something.In my project, I do some stitching job.Then resave with photo's exif. But I don't know where leaks?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48698016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to set up Karate browser capabilities acceptInsecureCerts:true for geckodriver I tried this way to set up the capabilities of my geckodriver for my karate tests.
I am using karate.version 0.9.6
Here is the geckodriver driver: 64bit windows: https://github.com/mozilla/geckodriver/releases/tag/v0.29.1
firefox Version 89.0.2 (64-bit)
*
*def session = { capabilities: { acceptInsecureCerts:true, browserName: 'firefox', proxy: { proxyType: 'manual', httpProxy: '127.0.0.1:8080' } } }
*configure driver = { type: 'geckodriver', showDriverLog: true , executable: 'driver/geckodriver.exe', webDriverSession: '#(session)' }
However, it obviously not picking up my settings.
Here is my log:
1 > User-Agent: Apache-HttpClient/4.5.12 (Java/1.8.0_41)
{"capabilities":{"acceptInsecureCerts":true,"browserName":"firefox","proxy":{"proxyType":"manual","httpProxy":"127.0.0.1:8080"}}}
13:25:13.121 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - 1626121513121 mozrunner::runner INFO Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "--marionette" "-foreground" "-no-remote" "-profile" "C:\\Users\\xxxxx\\AppData\\Local\\Temp\\rust_mozprofiledFOSxn"
13:25:16.428 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - 1626121516428 Marionette INFO Marionette enabled
13:25:20.065 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at C:\\Users\\xxxxx\\AppData\\Local\\Temp\\rust_mozprofiledFOSxn\\search.json.mozlz4", (void 0)))
13:25:20.368 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - console.error: Region.jsm: "Error fetching region" (new TypeError("NetworkError when attempting to fetch resource.", ""))
13:25:20.369 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - console.error: Region.jsm: "Failed to fetch region" (new Error("NO_RESULT", "resource://gre/modules/Region.jsm", 419))
13:25:20.960 [geckodriver_1626121511819-out] DEBUG c.i.k.d.geckodriver_1626121511819 - 1626121520961 Marionette INFO Listening on port 58400
13:25:21.071 [ForkJoinPool-1-worker-1] DEBUG com.intuit.karate - response time in milliseconds: 7997.52
1 < 200
1 < cache-control: no-cache
1 < content-length: 712
1 < content-type: application/json; charset=utf-8
1 < date: Mon, 12 Jul 2021 20:25:13 GMT
{"value":{"sessionId":"b17123ef-1426-45d2-827b-adbc35b02e46","capabilities":{"acceptInsecureCerts":false,"browserName":"firefox","browserVersion":"89.0.2","moz:accessibilityChecks":false,"moz:buildID":"20210622155641","moz:geckodriverVersion":"0.29.1","moz:headless":false,"moz:processID":36360,"moz:profile":"C:\\Users\\wli2\\AppData\\Local\\Temp\\rust_mozprofiledFOSxn","moz:shutdownTimeout":60000,"moz:useNonSpecCompliantPointerOrigin":false,"moz:webdriverClick":true,"pageLoadStrategy":"normal","platformName":"windows","platformVersion":"10.0","setWindowRect":true,"strictFileInteractability":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"unhandledPromptBehavior":"dismiss and notify"}}}
My purpose is to circle around this security check page.
enter image description here
Also, even if I tried to click that button in that security check page, my script is not able to get the buttons from the dom tree when I do the following.
And click('button[id=advancedButton]')
And click('button[id=exceptionDialogButton]')
A: it might be related with this : KarateUI: How to Handle SSL Certificate during geckodriver configuration? I added the alwaysMatch in and it is able to pick up the capabilities.
* def session = { capabilities: {alwaysMatch:{ acceptInsecureCerts:true, browserName: 'firefox' }}}
* configure driver = { type: 'geckodriver', showDriverLog: true , executable: 'driver/geckodriver.exe', webDriverSession: '#(session)' }
A: This is an area that may require you to do some research and contribute findings back to the community. Finally Karate passes the capabilities you define "as-is" to the driver. One thing that you should look at is if any command-line sessions should be passed to geckodriver - for example for Chrome, I remember there is some flag for ignoring these security errors. Note that you can use the addOptions flag in the Karate driver options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68360780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I need to make a reference to a JLabel based off a string So I have numbered JLabels declared like so (In the class)
OP_1
OP_2
OP_3
etc..
And I have a number and a string.
What I want is that when, for example, the number is 2. I want to change the label text to the content of the string. This is part of a method that is supposed to take a string, put it into the last available JLabel, and then increment the number.
I am very confused, and help would be appreciated.
A: Instead of / additional to naming your labels by specific names you can later match them on, I'd think a Map of JLabels with Strings or Integers as keys might be a better approach:
Map<String,JLabel> labelMap = new HashMap<String,JLabel>();
labelMap.put("1", OP_1);
labelMap.put("2", OP_2);
This will allow later access of "The label for key 2" as well as "list me all that labels and find the one with text 2" as well
A: Here I created an array of JLabels and a method, updateNextLabel(String), which will update the next JLabel with whatever you enter for str.
public class Example {
static int count = 0; //Create a count
static JLabel[] array = new JLabel[3]; //Create an array to hold all three JLabels
public static void main(String[] args) {
//Set the default text for each JLabel
array[0] = new JLabel("This is OP1");
array[1] = new JLabel("This is OP2");
array[2] = new JLabel("This is OP3");
//Here is an example if you wanted to use a for-loop to update the JLabels
for (int x = 0; x < array.length; x++) {
updateNextLabel("This is the new text for OP" + (count + 1));
System.out.println(array[x].getText());
}
}
public static void updateNextLabel(String str) {
array[count].setText(str);
count++;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34243604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React multiple criteria filtering I created like a shop, it's not for production, just for practice. I want to filter by criteria(size, model), it works when I add model, click filter, then add size, click filter to filter sizes..
Problem is, for example, when I remove all sizes and click filter on size filtering it returns all products, which would be okay if there are no filter criteria at all but there is still brand criteria..
Here is Stackblitz project: https://stackblitz.com/edit/react-jevhb9
A: your issue can be found with
{filterArray.length > 0 ? (
<ProductGrid products={filterArray} />
) : (
<ProductGrid products={products} />
)}
when the app render's the content after clicking the size filter, your filterArray is empty and therefore returns the products array which contains all your data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52382455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: To pass only incremented value to listview on nextpage I am able to send data on listview in nextpage.But problem is that items with quantity 0 is also passed.I want to show items whose quantity is incremented and not all items present in listview.Here is my code-
MainActivity.java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{
Button show;
ListView list_item;
ArrayList<Items> itemsArrayList;
SearchView searchview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
intent.putExtra("data", itemsArrayList);
startActivity(intent);
}
});
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
}
public void setupSearchView()
{
searchview.setOnQueryTextListener(this);
searchview.setQueryHint("Search Here");
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)) {
list_item.clearTextFilter();
} else {
list_item.setFilterText(s);
}
return true;
}
}
Custom.java
public class Custom extends BaseAdapter implements Filterable{
Activity a;
ArrayList<Items> itemsArrayList;
ArrayList<Items> filtered;
public Custom(Activity a, ArrayList<Items> itemsArrayList) {
this.a = a;
this.itemsArrayList = itemsArrayList;
}
@Override
public int getCount() {
return itemsArrayList.size();
}
@Override
public Object getItem(int i) {
return itemsArrayList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results=new FilterResults();
ArrayList<Items> data=new ArrayList<Items>();
if (filtered==null)
filtered=itemsArrayList;
if (filtered != null && filtered.size() > 0) {
for (final Items g : filtered) {
if (g.getItemname().toLowerCase()
.contains(charSequence.toString()))
data.add(g);
}
results.values=data;
}
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsArrayList=(ArrayList<Items>)filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public class Holder{
TextView sr,item,qty,price,pl,min,rate;
}
@Override
public View getView(final int position, final View view, ViewGroup viewGroup) {
final Holder holder=new Holder();
LayoutInflater li=a.getLayoutInflater();
final View view1=li.inflate(R.layout.customlist,viewGroup,false);
holder.sr=(TextView)view1.findViewById(R.id.s_no);
holder.item=(TextView)view1.findViewById(R.id.i_name);
holder.qty=(TextView)view1.findViewById(R.id.qty);
holder.price=(TextView)view1.findViewById(R.id.pr);
holder.rate=(TextView)view1.findViewById(R.id.frate);
holder.pl=(TextView) view1.findViewById(R.id.pl);
holder.min=(TextView) view1.findViewById(R.id.min);
final Items model = itemsArrayList.get(position);
holder.sr.setText(String.valueOf(itemsArrayList.get(position).getSrno()));
holder.item.setText(String.valueOf(itemsArrayList.get(position).getItemname()));
holder.rate.setText(String .valueOf(itemsArrayList.get(position).getFixedrate()));
holder.qty.setText(String.valueOf(itemsArrayList.get(position).getQuantity()));
holder.price.setText(String .valueOf(itemsArrayList.get(position).getRate()));
holder.pl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
model.setQuantity(model.getQuantity() + 1);
model.setRate(model.getQuantity()*model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
});
holder.min.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(model.getQuantity()>0) {
model.setQuantity(model.getQuantity() - 1);
model.setRate(model.getQuantity() * model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
}
});
return view1;
}
}
Items.java
public class Items implements Serializable {
int srno,fixedrate,quantity,rate;
String itemname;
public Items(int srno, String itemname, int fixedrate, int quantity, int rate) {
this.srno = srno;
this.itemname = itemname;
this.fixedrate = fixedrate;
this.quantity = quantity;
this.rate = rate;
}
public int getSrno() {
return srno;
}
public void setSrno(int srno) {
this.srno = srno;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public int getFixedrate() {
return fixedrate;
}
public void setFixedrate(int fixedrate) {
this.fixedrate = fixedrate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
Custom_Trial.java
public class Custom_Trial extends BaseAdapter {
Activity a;
private ArrayList<Items> data = new ArrayList<>();
public Custom_Trial(Activity a, ArrayList<Items> data) {
this.a = a;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView sr, it, qty, amt;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
LayoutInflater li = a.getLayoutInflater();
View view = li.inflate(R.layout.customtrial, parent, false);
holder.sr = (TextView) view.findViewById(R.id.head1);
holder.it = (TextView) view.findViewById(R.id.head2);
holder.qty = (TextView) view.findViewById(R.id.head3);
holder.amt = (TextView) view.findViewById(R.id.head4);
Items m = data.get(position);
holder.sr.setText(String.valueOf(m.getSrno()));
holder.it.setText(m.getItemname());
holder.qty.setText(String.valueOf(m.getQuantity()));
holder.amt.setText(String.valueOf(m.getRate()));
return view;
}
}
Trial.java
public class Trial extends Activity{
ListView listnew;
private ArrayList<Items> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trial);
listnew = (ListView) findViewById(R.id.newlist);
data.addAll((ArrayList<Items>) getIntent().getSerializableExtra("data"));
Custom_Trial ct = new Custom_Trial(this,data);
listnew.setAdapter(ct);
}
}
A: It's because you passing original list. You're updating values inside adapter and passing not updated list fromadapter, but original. Write method inside adapter to return your updated list.
Inside Custom.java adapter:
public ArrayList<Items> getItems(){
ArrayList<Items> quantityArrayList;
Items item;
for (int i = 0; i < itemsArrayList.size(); i++){
item = itemsArrayList.get(i);
if (item.getQuantity() > 0)
quantityArrayList.add(item);
}
return quantityArrayList;
}
And inside MainActivity onCreate() should look like this. After clicking show button you're going to get Items from Custom Adapter whose quantity >0.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
List<Items> quantityList = c.getItems();
intent.putExtra("data", quantityList);
startActivity(intent);
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43370771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xpath Newb Needs Help Printing Parent/Path Tags in Output I'm parsing XML files and paring the results down to a specific set of tags, but the output isn't valid XML.
Here's the command I'm running to extract a small subset of tags under the path "joblist/job:"
xpath -q -e '/joblist/job/*[self::uuid or self::group or self::name or self::description or self::tags]'
Here's the output. Note that it's just printing the requested tags, and nothing "encasing" them:
<description>Validate a service by selecting an endpoint.</description>
<group>Validations/MyService</group>
<name>Transaction</name>
<tags>validations,MyService</tags>
<uuid>a6a32547-61ec-24bb-a424-faf4bc34f171</uuid>
xmllint doesn't parse this output:
-:4: parser error : Extra content at the end of the document
<group>Validations/MyService</group>
^
So I wonder then if I can include the parent tags, which would be:
<joblist>
<job>
<description>Validate a service by selecting an endpoint.</description>
<group>Validations/MyService</group>
<name>Transaction</name>
<tags>validations,MyService</tags>
<uuid>a6a32547-61ec-24bb-a424-faf4bc34f171</uuid>
</job>
</joblist>
Is this possible, or is there a better solution for what I'm trying to accomplish? Thanks!
A: XPath is designed for locating information in existing documents, not for constructing new documents. You want XSLT or XQuery for that job.
A: The problem, as Michael has pointed out, is that XPath, the language, is just not sufficiently expressive to perform the task you need. (It would I think be possible in XPath 3 but only awkwardly, and I think you are not running XPath 3 here).
On the bright side, this task is easily performed e.g. in XSLT, simply by embedding your existing XPath into a very simple XSLT stylesheet
<joblist xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<job>
<xsl:copy-of select="
/joblist/job/*[
self::uuid or self::group or self::name or self::description or self::tags
]
"/>
</job>
</joblist>
See section 2.3 "Literal Result Element as Stylesheet" of the XSLT spec for the details of how this works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75563052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: error with multiple dlookup criteria This code produces a runtime error 3464 for dlookup with matchstr_t. I can't understand why as matchstr_v seems to work fine. Any offers? At the moment all I'm trying to do is use the dlookup to flag duplicate start times for appointments.
Dim i, j, clientid, therid As Integer
Dim origin_date, apptdate As Date
Dim slotday, apptype, venue, matchstr_v, matchstr_t As String
Dim slottime As Date
Dim appt(25) As Date
Dim db As Database
Dim rst As Recordset
Dim test As Variant
origin_date = Date
slotday = Me.slot_day.Value
slottime = Me.slot_time.Value
clientid = Me.Client_ID.Value
therid = Me.Therapist_ID.Value
venue = Me.venue.Value
apptype = "continuation"
slottime = Format(slottime, "Short Time")
For i = 1 To 7
apptdate = Date + i
If Weekday(apptdate, 2) = slotday Then
'set up stuff
For j = 0 To 25
appt(j) = apptdate + (j * 7)
Set db = CurrentDb()
Set rst = db.OpenRecordset("Dummy")
Debug.Print "[therapist ID] = " & therid
matchstr_v = "[appt date]= #" & appt(j) & "# AND [appt time] = #" & slottime & "# AND [venue] = '" & venue & "'"
matchstr_t = "[appt date]= #" & appt(j) & "# AND [appt time] = #" & slottime & "# AND [therapist ID] = " & therid
Debug.Print matchstr_t
If Not IsNull(DLookup("[dummy ID]", "Dummy", matchstr_v)) Then
' do more stuff
ElseIf Not IsNull(DLookup("[dummy ID]", "Dummy", matchstr_t)) Then
' do more stuff
Else
rst.AddNew
rst.Fields("appt date") = appt(j)
rst.Fields("appt time") = slottime
rst.Fields("Client ID") = clientid
rst.Fields("Therapist ID") = therid
rst.Fields("appt type") = "continuation"
rst.Fields("attendance") = "scheduled"
rst.Fields("venue") = venue
'Debug.Print rst.Fields("appt date")
rst.Update
test = (DLookup("[dummy ID]", "Dummy", matchstr_v))
Debug.Print test
End If
rst.Close
db.Close
Next j
Else
End If
Next i
A: What is the datatype of [therapist ID]?
There seems to be a datatype mismatch with the value of therid.
A: In that case maybe you are just missing a #
matchstr_t = "[appt date]= #" & appt(j) & "# AND [appt time] = #" & slottime & "# AND [therapist ID] = #" & therid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16668401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can I use ggplot2 to visualize this data? data frame
first_name last_name party vote
Ralph Abraham R Yea
Alma Adams D Nay
Robert Aderholt R Nay
I want to display this data in a plot using ggplot2. How would you suggest I do that? I keep trying things like
ggplot(data = voters) + stat_count(mapping = aes(x=party, y = vote))
but it gives me the error
stat_count requires the following missing aesthetics: x
Any guidance is appreciated!
A: Is this what you want?
voters <- data.frame(party = c("R", "D", "R", "D", "R", "R", "R", "R", "R", "R", "R", "R", "R", "D", "R"),
vote = c("Y", "N", "Y", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y"))
ggplot(voters, aes(x = party, fill = vote)) + geom_bar()
You can't tell from this plot (because everyone voted based on party lines) but using the same code, if there were both "Yea" and "Nay" votes coming from the same party, you would get a stacked bar plot showing multiple colors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42127467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Get body content from custom react component (Sorry if it's a noob question, I just started using React for a week, and didn't find the answer to this question in internet).
I have React component with two properties which is rendering one of this property into text body of <p>
function Item({ value, text }) {
return (
<div>
{/* not relevant code here */}
<p>{text}</p>
<div>
);
}
And I'm using it with this code:
<Item text="Foo" value="foo"/>
<Item text="Bar" value="bar"/>
<Item text="Baz" value="baz"/>
But I want to use it like this:
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
So how can I access the body of React Item element and how to pass it to properties?
A: My simple explanation of what props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.
change your function component to
function Item(props) {
return (
<div>
{props.children}
<div>
);
}
Reference : react's props children
A: @Kirill I hope this will help you .
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
{children}
<div>
);
}
Then you can call your Item like this:
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
also you can pass other element as children to your Item Component also:
<Item value="foo">
<p>Foo</p>
</Item>
A: You can destructure the component children from props.
function Item({ value, children }) {
return <div><p>{children}: {value}</p></div>;
}
function Example() {
return (
<div>
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById("react")
);
p { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Additional documentation
*
*Destructuring assignment
A: I guess this should work.
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
<p>{children}</p>
<div>
);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68767797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Impossible to find the function setBackground on a object I'm trying to do something like: If the column E has the word ok, column D gets formated as red. Seens preety easy, but something is wrong as I'm not entenring the if. Do u guys know what is wrong? I have read some other topics, but seens preety much the same
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
Browser.msgBox(myRangeValues);
for (var i = 0; i < myRangeValues.length; i++){
if(myRangeValues[i][0] == 'ok'){
myRangeValues[i][0].setBackground('red');
}
}
}
Thanks for the attention.
EDIT:
new code not working. I tried to put the logger.log in other lines as well. even without the logger, the error I get is that the function setBackground is impossible to find in the object.
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
for (var i = 0; i < myRangeValues.length; i++)
{
if(myRangeValues[i][1] == 'ok')
{
myRangeValues[i][0].setBackground('red');
//Logger.log("myRangeValues[i][1]: " + myRangeValues[i][1]);
}
}
}
A: You are mixing up methods.
value arrays don't have setBackground() method, this is a spreadsheet range method
use the code below to do what you want :
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
var myRangeColors = ss.getRange('D7:E').getBackgrounds();// get the colors
for (var i = 0; i < myRangeValues.length; i++)
{
if(myRangeValues[i][1] == 'ok')
{
myRangeColors[i][0]='#F00';
}
}
ss.getRange('D7:E').setBackgrounds(myRangeColors); //set the modified colors
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35446020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does one log all exceptions from an ASP.net MVC app How does one log all exceptions from an ASP.net MVC app? Should one use logging to a text file? If so, should this text file be saved to the computer disk or to a table in the database?
A: I use log4net its simple to implement
https://www.nuget.org/packages/log4net/
in your webconfig you add this config you can refer to https://logging.apache.org/log4net/release/manual/configuration.html
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" /> <- this is where your log file will be
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
inside your controller you declare a variable to use for logging
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
now anywhere inside that controller you can call this
logger.Info("blablabla") or logger.Error("boom boom") you should check documentation for more.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32232856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I prioritize a radio selection across multiple questions using javascript? I'm trying to teach myself how to make a game where based on my selection I get a link to another page (but not send a form - I'm trying to make this show up on the same page). In this scenario I have three questions and what I'd like to do is have Link 1 show up if ANY of the questions are marked yes. Right now, if I select yes, yes, no, Link 2 shows up.
Also, is there a way to send the values to the function but have it only trigger the divs after the last selection is made? Something like a submit button that works onclick I guess. If I go that route, how do I send the values of the radio buttons to the function?
window.onload = function() {
document.getElementById('link1').style.display = 'none';
document.getElementById('link2').style.display = 'none';
};
function showdiv(x)
{
if (x==1){
document.getElementById('link1').style.display='block';
document.getElementById('link2').style.display='none';
}
else {
document.getElementById('link1').style.display='none';
document.getElementById('link2').style.display='block';
}
return;
}
<body>
<label>Do you need equipment?</label>
<input type="radio" onclick="showdiv(1)" name="q1">Yes
<input type="radio" onclick="showdiv(0)" name="q1">No
</br>
<label>Do you need food?</label>
<input type="radio" onclick="showdiv(1)" name="q2">Yes
<input type="radio" onclick="showdiv(0)" name="q2">No
</br>
<label>Do you need help?</label>
<input type="radio" onclick="showdiv(1)" name="q3">Yes
<input type="radio" onclick="showdiv(0)" name="q3">No
</br>
<div id="link1">
Show Link 1
</div>
<div id="link2">
Show Link 2
</div>
</body>
A: The problem occurs because the function triggers every time an answer is clicked. When you select "No" on question 3, the variable x equals 0, so the function does it's job and hides link 1 and shows link 2.
If you would like to use a button to submit the answer, your code would look like this:
window.onload = function() {
document.getElementById('link1').style.display = 'none';
document.getElementById('link2').style.display = 'none';
};
var x, y, z;
function a1(answer1){
x = answer1;
console.log(x);
};
function a2(answer2){
y = answer2;
console.log(y);
};
function a3(answer3){
z = answer3;
console.log(z);
};
function showdiv()
{
if (x==1 | y==1 | z==1){
console.log("One of the questions is 1");
document.getElementById('link1').style.display='block';
document.getElementById('link2').style.display='none';
}
else {
console.log("None of the questions is 1");
document.getElementById('link1').style.display='none';
document.getElementById('link2').style.display='block';
}
return;
}
<body>
<label>Do you need equipment?</label>
<input type="radio" onclick="a1(1)" name="q1">Yes
<input type="radio" onclick="a1(0)" name="q1">No
</br>
<label>Do you need food?</label>
<input type="radio" onclick="a2(1)" name="q2">Yes
<input type="radio" onclick="a2(0)" name="q2">No
</br>
<label>Do you need help?</label>
<input type="radio" onclick="a3(1)" name="q3">Yes
<input type="radio" onclick="a3(0)" name="q3">No
</br>
<button onclick="showdiv()">Submit</button>
<div id="link1">
Show Link 1
</div>
<div id="link2">
Show Link 2
</div>
</body>
Hope this is useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48875269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Searchview widget : move search icon to right I have this searchView and i want to move the search icon to the right(if possible)
my xml code:
<android.widget.SearchView
android:id="@+id/searchBox"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="7dp"
android:layout_below="@+id/header"
android:iconifiedByDefault="false"
android:background="@drawable/searchrectangle"
android:queryHint="@string/search_message">
</android.widget.SearchView>
A: I hope this work. It works for me.
android:layoutDirection="rtl"
A: If I am correct this is source for searchview https://android.googlesource.com/platform/frameworks/support.git/+/jb-mr2-release/v7/appcompat/res/layout/abc_search_view.xml .
From what it looks like, it uses linear layout and that mentioned icon is in front of text. That means there is not a nice way to put it on right side.
There are basically 3 options left, or at least which came to my mind.
*
*use custom made layout with drawable and edittext, I think some of the effects can be done using CollapsibleActionView or/and custom animations (really depends on what you need from it)
*use search view, style it without text icon:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:searchViewStyle">@style/appTheme.SearchView</item>
</style>
<style name="AppTheme.SearchView" parent="Widget.AppCompat.SearchView">
<item name="android:searchIcon" tools:targetApi="lollipop">@null</item>
</style>
And then basically add icon to right as a normal drawable.
*extend search view and inflate custom layout in constructor (haven't tested this one)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32914469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Running multiple XMLHttpRequests in a loop from an array only returns last request Let me start by saying I'm fairly new to JS (more familiar with looping languages like C), so I have not been able to understand various examples well enough to implement into my code.
Essentially what I am trying to do is request YouTube APIs in a loop using an array of channel ID's. From that request, parse out the video count and return it into an array.
(End goal is to save said array and then compare it next time code is run to be able to display a list of channels with new videos)
The below code is the part of my program that handles the API requests for new videos, but it only returns the value from the LAST request.
To fix this, I have tried implementing various forms of promise, async/await, and re-writing the code to run in a different order.
So far all attempts have either failed to rectify the issue, or broke the code altogether.
//(example) channel list declared in a separate .js file
const lists = [
{"value": "UC5f5IV0Bf79YLp_p9nfInRA", "name": "How Ridiculous ", "group": "1", "count": ""},
{"value": "UCRijo3ddMTht_IHyNSNXpNQ", "name": "Dude Perfect ", "group": "1", "count": ""},
{"value": "UCY1kMZp36IQSyNx_9h4mpCg", "name": "Mark Rober ", "group": "2", "count": ""}];
//vars declared at start of script
const ApiKey = "AIzaSyDlb2NRFdp61zp28aXGzXBCgQQTSkjAK2I";
var countdata = new XMLHttpRequest();
var Api2Url;
const URLstart2 = "https://www.googleapis.com/youtube/v3/channels?id=";
const URLend2 = "&fields=items(,statistics(,videoCount))&part=statistics";
var API2Response;
var newlists;
var newlistoutput;
//eventually this function is called
for (let index = 0; index < lists.length; index++) {
Api2Url = URLstart2 + lists[index].value+"&key="+ApiKey+ URLend2;
countdata.onload = function() {
API2Response = JSON.parse(this.responseText);
lists[index].count = API2Response.items[0].statistics.videoCount;
}
countdata.open("GET", Api2Url, true);
countdata.send();
}
console.log(lists);
// code missing here to filter contents of "lists" by items with new values, and place into "newlists"
// write data to Count property
// create new difference property with count - old count properties
// filter to only objects with difference property >0
// this code will run once values have been compared (into HTML <div id=chaninfo><div>)
for (let X in newlists) {
newlistoutput += newlists[X].name + " ---> " + newlists[X].difference + " New Videos <br>";
};
document.getElementById("chaninfo").innerHTML = newlistoutput;
// shift values from count to old count properties
// save object for next time - localStorage?
Code for comparing new vs old values has not been written yet, since this depends on how I have to format the output of this function.
I would have expected this to add the video count to each of the channel object "count" properties.
However, it only adds the value to the last object in the array.
Additionally, console shows 'XHR failed loading: GET "".' for each item except the last one.
I am assuming the request is getting modified too fast for the results to come back and be added back to the array, but I have not been able to figure out how to force the code to wait on completion before moving on to the next request.
A: You should use a new XHR object for each request
for (let index = 0; index < lists.length; index++) {
let countdata = new XMLHttpRequest();
Api2Url = URLstart2 + lists[index].value+"&key="+ApiKey+ URLend2;
countdata.onload = function() {
API2Response = JSON.parse(this.responseText);
lists[index].count = API2Response.items[0].statistics.videoCount;
}
countdata.open("GET", Api2Url, true);
countdata.send();
}
Since you want to use lists after the for loop I suggest taking a look at fetch and await/async.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73088361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: For Loop through text file only outputs last line I think I am about to have an a brain aneurysm. I am trying to print the lines of a text file to a new file, but it only outputs the last line. I have done this a dozen times, now I am not sure what I am doing wrong.
for /F "tokens=*" %%A in (results.txt) do (
echo %%A
) > imsofrustrated.txt
PAUSE
Am I literally retarded? This is in reference to a previous question I posted.
FINDSTR - Stop on last string match
A: > is to redirect output and overwrite whatever is in the file.
>> is to redirect output and append to the file.
for /F "tokens=*" %%A in (results.txt) do (
echo %%A
) >> imsofrustrated.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48717338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: coldfusion requesttimeout I have a ColdFusion template that executes a long running query. I have increased the request timeout from 3600 to 6600 but my template continues to timeout. I would like to increase the request timeout again from 6600 to 9600 but before doing so I would like to know if there are any disadvantages or risks from increasing the request timeout so much?
Basically, what my cfm file does is. It has to take records from a table and insert them into an excel sheet. The table consists of around 30,000 records. The cfm file takes every 1000 records at a time and inserts them into Excel, then it takes the next 1000 and so on. To complete this entire process it sometimes stops abruptly because of the timeout problem. So before I increase the "requesttimeout" I want to know, would there be any problem (ram usage, performance) if I increase requesttimeout tremendously.
A: Upping the timeout is fine where it's needed. You should use cfsetting requestTimeOut="xxx" to up the timeout just where it's needed, not upping it in the administrator, as that will affect all templates.
The disadvantages are that there's a pool of threads to handle requests and whilst one is handling your long-running request, it's not available to do other things. This is fine as long as you're confident that the long-running request will only be run by one or two people at a time, but problematic if lots of people could be running it. If CF will run 8 requests concurrently and all 8 are hadnling your long-running request, then your site is effectively offline. CF will queue requests up to a certain point, but you don't want to get to this state in the first place.
I've worked on apps where there are background admin-only tasks which can take up to an hour, but we were confident that no more that 2 people would ever run them.
You could also look at using cfthread in order to run your query without blocking the page, but then it's harder to provide feedback to the user.
A: I think it would help if we understood the situation a little better. Is this something like a nightly job that is run? Or is this a page that a user might navigate to which generates a report while they wait for it? Give us some basic information about what your page is doing.
Also, there are different ways to increase the request timeout; system wide via the administrator or page specific via the <cfsetting requestTimeOut=""> tag. Which one are you increasing? I would suggest that you not increase the system wide setting but it is okay to increase the page level setting when needed.
There is also a timeout attribute for the <cfquery> tag. Are you using that?
Can you tell us if the <cfquery> is timing out or if the timeout is happening after the cfquery and during the data output?
I would also suggest attempting to optimize your query as much as possible. Can an index be setup (if one is not already)? Do you really only need a subset of the records being returned?
Perhaps you could split this one page up into multiple pages that would each run faster.
A: Rather than just increase your timeout limit, IF the user who initiates the request doesn't need to wait for the results (i.e an end of day or overnight report) then I would use a cfthread with its timeout set to 0 (never times-out) and leave it running in the background until it has finished, or set an extremly long timeout, like 1 hour. I would also use cflock to prevent the thread being able to proccess more than once otherwise you could grind your system to a halt with many heavy threads.
read this -docs- and see what you think
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12405642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Many laravel apps in one server. How to organize? I'll be setting up a server that will host several laravel applications. There will be a few ones at the beginning, but with time we can end up having dozens of them. Most of which (if not all) will be laravel projects.
I'm not sure how to organize all this. I have several choices:
*
*Use a different laravel project for each application. Every application would be placed in a different directory. That would mean lots of files and space taken up by apps.
*Use a single laravel project, having a src folder inside the project where I would be placing each application in a separate subfolder. Each of these subfolders would contain only the service provider(s) of each app, as well as their own routes, controllers, rules, etc.
*I've been told lately of an approach similar to the second one, but instead of placing the apps in src directory, each app would be developed as a library, and the main laravel project would require each one of them. That way, apps would be in vendor dir, and could easily be required or unrequired.
*I can also group applications across a few laravel projects, using either approach 2 or 3.
What are the advantages and inconvenients of each one of these approaches? Is there an optimal approach to this problem?
Thanks!
A: If they are different and not connected in anyway, the best thing in my opinion is to have their own seperate projects because it would be easier to deal with the webserver (like nginx) and the other options would just make everything more complicated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70095882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Subsetting a data set and plotting means I have a data set including Year, Site, and Species Count. I am trying to write a code that reflects in some years, the counts were done twice. For those years I have to find the mean count at each site for each species (there are two different species), and plot those means. This is the code I have generated:
DataSet1 <- subset(channel_islands,
channel_islands$SpeciesName=="Hypsypops ubicundus, adult" |
channel_islands$SpeciesName=="Paralabrax clathratus,adult")
years<-unique(DataSet1$Year)
Hypsypops_mean <- NULL
Paralabrax_mean <- NULL
Mean <- NULL
years <- unique(DataSet1$Year)
for(i in 1:length(years)){
data_year <- DataSet1[which(DataSet1$Year == years[i]), ]
Hypsypops<-data_year[which(data_year$SpeciesName=="Hypsypops rubicundus,adult"), ]
Paralabrax<-data_year[which(data_year$SpeciesName=="Paralabrax clathratus,adult"), ]
UNIQUESITE<-unique(unique(data_year$Site))
for(m in 1:(length(UNIQUESITE))){
zz<-Hypsypops[Hypsypops$Site==m,]
if(length(zz$Site)>=2){
Meanp <- mean(Hypsypops$Count[Hypsypops$Site==UNIQUESITE[m]])
Hypsypops_mean <- rbind(Hypsypops_mean,
c(UNIQUESITE[m], years[i], round(Meanp,2),
'Hypsypops rubicundus,adult'))
}
kk <- Paralabrax[Paralabrax$Site==m, ]
if(length(kk$Site)>=2){
Meane <- mean(Paralabrax$Count[Paralabrax$Site==UNIQUESITE[m]])
Paralabrax_mean <- rbind(Paralabrax_mean,
c(UNIQUESITE[m], years[i], round(Meane, 2),
'Paralabrax clathratus,adult'))
}
}
if(i==1){
Mean<-rbind(Hypsypops_mean, Paralabrax_mean)
}
if(i>1){
Mean<-rbind(DataMean, Hypsypops_mean, Paralabrax_mean)
}
Hypsypops_mean<-NULL
Paralabrax_mean<-NULL
}
Mean <- as.data.frame(Mean,stringsAsFactors=F)
names(Mean) <- c('Site','Year','mean_count','SpeciesName')
Mean$Site <- as.integer(Mean$Site)
Mean$Year <- as.integer(Mean$Year)
Mean$mean_count <- as.numeric(Mean$mean_count)
par(mfrow=c(5,5), oma=c(4,2,4,2), mar=c(5.5,4,3,0))
for(i in 1:length(years)){
if(any(Mean$Year==years[i])) {
year1<-Mean[which(Mean$Year==years[i]),]
Species<-unique(as.character(year1$SpeciesName))
Colors<-c("pink","purple")[Species]
Data_Hr<-year1[year1$SpeciesName=="Hypsypops rubicundus,adult",]
Data_Pc<-year1[year1$SpeciesName=="Paralabrax clathratus,adult",]
plot(Data_Hr$mean_count~Data_Pc$mean_count,
xlab=c("Hypsypops rubicundus"),
ylab=c("Paralabrax clathratus"),main=years[i],pch=16)
}
}
It's a lot I'm sorry, I'm not sure of a way to streamline the process. But I keep getting an error:
Error in names(Mean) <- c("Site", "Year", "mean_count", "SpeciesName")
: 'names' attribute [4] must be the same length as the vector [0]
Not sure how I can debug this.
A: Not sure why you want to do this with an elaborate loop code. It sounds like you are trying to summarise your data.
This can be done in different ways. Here is a solution using dplyr:
DataSet1 %>%
group_by(Year, SpeciesName, Site) %>%
summarise(nrecords = n(),
Count = mean(Count))
To get a better answer, it might be helpful to post a subset of the data and the intended result you are after.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57967975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why this function is not working without adding double quotes around the arguments? function symbols(shape) {
alert ("This is a " + shape)
}
symbols (circle)
symbols (star)
A: You might be knowing data types in JS.
If you pass circle or star as argument without quotes then the argument will be interpreted as object (which is not your intension).
As per you function definition it is expecting string, means you should pass string literal e.g. symbols('star') or you should have a variable containing string value e.g. var circle = 'circle';
symbols(circle);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42117548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: App crash while setting Box APi key I register by app on box.com and get API key and start using it in my xcode project,but app get crash while setting BoxAPI at line:
[Box setBoxAPIKey:@"insert_key_here"];.
The error:
-[NSURL initFileURLWithPath:]: nil string parameter
No idea how to solve this issue.
A: This is pretty simple. Follow these steps
1) Go to your target build setting
2) Click on Add Build Phase (at buttom right corner) and choose Add Run Script
3) In the Edit Text Box copy paste this script
#!/bin/bash
echo "Copy Box database schema into bundle"
cp -fr ./Box.framework/Resources/BoxCoreDataStore.momd "${BUILT_PRODUCTS_DIR}/${CONTENTS_FOLDER_PATH}/BoxCoreDataStore.momd"
After Doing this click on build and you are done.
Happy coding
A: If someone faces the same problem than here is the fix:
You need to add files in Box.framework/Resources/BoxCoreDataStore.momd folder to your application package.
Add "Copy Files" phase and specify Destination = Executables, Subpath = ./BoxCoreDataStore.momd then add all files from above mentioned folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15241046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ros: how to track changes in agents movement I'm a noob in this matter so this question might be a bit dumb but I'm trying to launch a multi agent world file where each agent need to know wHo is closest to it.
What I have by now: multi agent system where each agent has a laser sensor and they all move randomly and change direction when they are close to an obstacle which can be another agent or a wall defined in the world file
I'm trying to find a way not just to realize when I hit an obstacle but also to know if it is a moving one and if so where is it moving and how fast.
Thanks guys for any suggestion
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29628302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make an auto-complete textbox in a winforms desktop application I have a list of words. The list contains about 100-200 text strings (it's names of metro stations actually).
I want to make an auto-complete textbox. For an example, user press 'N' letter, then an (ending of) appropriate option appear (only one option). The ending must be selected.
How to do that?
PS1: I guess, there is a textbox control with a Property something like this:
List<string> AppropriateOptions{/* ... */}
PS2: sorry for my english. If you didn't understand -> ask me and I will try to explain!
A: Use a ComboBox instead of a TextBox. The following example will autocomplete, matching any piece of the text, not just the starting letters.
This should be a complete form, just add your own data source, and data source column names. :-)
using System;
using System.Data;
using System.Windows.Forms;
public partial class frmTestAutocomplete : Form
{
private DataTable maoCompleteList;
private const string MC_DISPLAY_COL = "name";
private const string MC_ID_COL = "id";
public frmTestAutocomplete()
{
InitializeComponent();
}
private void frmTestAutocomplete_Load(object sender, EventArgs e)
{
maoCompleteList = GetDataTableFromDatabase();
maoCompleteList.CaseSensitive = false; //turn off case sensitivity for searching
testCombo.DisplayMember = MC_DISPLAY_COL;
testCombo.ValueMember = MC_ID_COL;
testCombo.DataSource = maoCompleteList;
testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
testCombo.KeyUp += testCombo_KeyUp;
}
private void testCombo_KeyUp(object sender, KeyEventArgs e)
{
//use keyUp event, as text changed traps too many other evengts.
ComboBox oBox = (ComboBox)sender;
string sBoxText = oBox.Text;
DataRow[] oFilteredRows = maoCompleteList.Select(MC_DISPLAY_COL + " Like '%" + sBoxText + "%'");
DataTable oFilteredDT = oFilteredRows.Length > 0
? oFilteredRows.CopyToDataTable()
: maoCompleteList;
//NOW THAT WE HAVE OUR FILTERED LIST, WE NEED TO RE-BIND IT WIHOUT CHANGING THE TEXT IN THE ComboBox.
//1).UNREGISTER THE SELECTED EVENT BEFORE RE-BINDING, b/c IT TRIGGERS ON BIND.
oBox.SelectedIndexChanged -= testCombo_SelectedIndexChanged; //don't select on typing.
oBox.DataSource = oFilteredDT; //2).rebind to filtered list.
oBox.SelectedIndexChanged += testCombo_SelectedIndexChanged;
//3).show the user the new filtered list.
oBox.DroppedDown = true; //this will overwrite the text in the ComboBox, so 4&5 put it back.
//4).binding data source erases text, so now we need to put the user's text back,
oBox.Text = sBoxText;
oBox.SelectionStart = sBoxText.Length; //5). need to put the user's cursor back where it was.
}
private void testCombo_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox oBox = (ComboBox)sender;
if (oBox.SelectedValue != null)
{
MessageBox.Show(string.Format(@"Item #{0} was selected.", oBox.SelectedValue));
}
}
}
//=====================================================================================================
// code from frmTestAutocomplete.Designer.cs
//=====================================================================================================
partial class frmTestAutocomplete
{
/// <summary>
/// Required designer variable.
/// </summary>
private readonly System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.testCombo = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// testCombo
//
this.testCombo.FormattingEnabled = true;
this.testCombo.Location = new System.Drawing.Point(27, 51);
this.testCombo.Name = "testCombo";
this.testCombo.Size = new System.Drawing.Size(224, 21);
this.testCombo.TabIndex = 0;
//
// frmTestAutocomplete
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.testCombo);
this.Name = "frmTestAutocomplete";
this.Text = "frmTestAutocomplete";
this.Load += new System.EventHandler(this.frmTestAutocomplete_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox testCombo;
}
A: Just in case @leniel's link goes down, here's some code that does the trick:
AutoCompleteStringCollection allowedTypes = new AutoCompleteStringCollection();
allowedTypes.AddRange(yourArrayOfSuggestions);
txtType.AutoCompleteCustomSource = allowedTypes;
txtType.AutoCompleteMode = AutoCompleteMode.Suggest;
txtType.AutoCompleteSource = AutoCompleteSource.CustomSource;
A: The answer link by Leniel was in vb.net, thanks Joel for your entry. Supplying my code to make it more explicit:
private void InitializeTextBox()
{
AutoCompleteStringCollection allowedStatorTypes = new AutoCompleteStringCollection();
var allstatortypes = StatorTypeDAL.LoadList<List<StatorType>>().OrderBy(x => x.Name).Select(x => x.Name).Distinct().ToList();
if (allstatortypes != null && allstatortypes.Count > 0)
{
foreach (string item in allstatortypes)
{
allowedStatorTypes.Add(item);
}
}
txtStatorTypes.AutoCompleteMode = AutoCompleteMode.Suggest;
txtStatorTypes.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtStatorTypes.AutoCompleteCustomSource = allowedStatorTypes;
}
A: Use combo box, sets its datasource or give hard coded entries but set the following properties:
AutoCompleteMode = Suggest;
AutoCompleteSource = ListItems;
A: You want to set the TextBox.AutoCompleteSource to CustomSource and then add all of your strings to its AutoCompleteCustomSource property, which is a StringCollection. Then you should be good to go.
A: I want to add that the standard autocomplete for TextBox does only work from the beginning of your strings, so if you hit N only strings starting with N will be found. If you want to have something better, you have to use some different control or implement the behavior for yourself (i.e. react on TextChanged Event with some timer to delay execution, than filter your tokenlist searching with IndexOf(inputString) and then set your AutoCompleteSource to the filtered list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4629909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Developer Studio BPEL project doesn't recognize analytics extension Using wso2bps-3.5.1, wso2das-3.0.1 and Developer Studio 3.8.0
I'm following a guideline for Monitoring a BPEL Process with WSO2 DAS. I recieve this from inside Developer Studio and my .bpel file:
Error: Extension "http://wso2.org/bps/monitoring/publisher" is not supported by this implementation.
<bpel:extensions>
<bpel:extension namespace="http://wso2.org/bps/monitoring/publisher" mustUnderstand="yes"/>
</bpel:extensions>
A: WSO2 Developer Studio uses Eclipse bpel plugin to add support for bpel creation for WSO2 BPS. This BAM publishing bpel extension activity that you are referring to, is a custom extension developed by WSO2 and default bpel editor is not aware of this extension. This is why it gives syntax errors when you add this extension activity from the source view.
However, you should be able to export and deploy the CAR file without any issues regardless of the syntax errors.
According to this, there's a possibility to add support for custom extension activities in bpel editor.
Hence, I have raised a jira in WSO2 BPS Tooling jira for this feature.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37226685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I build easily a static binary to be used inside fakeroot and how? fakeroot seems to build some libfakeroot.a (but inside a .lib directory).
But I am not sure, that the static linker can indeed replace/rename symbols as the dynamic linker can.
A: Fakeroot uses the dynamic linker in order to do its magic (specifically, LD_PRELOAD). Unfortunately, the dynamic linker is not involved in loading statically linked binaries (which is how the dynamic linker itself is invoked: /lib/ld-linux.so.2 is statically compiled).
As answered above, your only option, as far as I'm aware, is to use fakeroot-ng, which uses a completely different mechanism to inject into the process, and is, thus, able to work on statically linked libraries without a problem.
In fact, statically linked libraries was part of the reason I set out to write fakeroot-ng in the first place. At the time, there was no way to tell ldconfig to run on a subtree, and ldconfig is statically linked.
Shachar
A: seems the solution is to use fakeroot-ng, which works for statically linked binaries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8243518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I restrict jQuery UI connected lists drag and drop to single direction I am using jQuery UI Connectedlist
Here drag and drop is working fine with both side from left to right and right to left.
How can I disable right to left ? It has to work only one way, from left to right.
I need also sorting to still work inside ul yellow items like in grey items.
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable"
}).disableSelection();
});
#sortable1, #sortable2 {
border: 1px solid #eee;
width: 142px;
min-height: 20px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
}
#sortable1 li, #sortable2 li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 120px;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<body>
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight">Item 1</li>
<li class="ui-state-highlight">Item 2</li>
<li class="ui-state-highlight">Item 3</li>
<li class="ui-state-highlight">Item 4</li>
<li class="ui-state-highlight">Item 5</li>
</ul>
</body>
</html>
A: You could cancel the drag event in the right list sortable2 using receive event in sortable1 to prevent receiving any item from second list.
To drag grey lis back to the left side we will add helper class e.g s2 that will identify the sortable2 original items and cancel the drag only on them :
$("#sortable1").sortable({
receive: function(ev, ui) {
if(ui.item.hasClass("s2"))
ui.sender.sortable("cancel");
}
});
Hope this helps.
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable"
}).disableSelection();
$("#sortable1").sortable({
receive: function(ev, ui) {
if(ui.item.hasClass("s2"))
ui.sender.sortable("cancel");
}
});
});
#sortable1, #sortable2 {
border: 1px solid #eee;
width: 142px;
min-height: 20px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
}
#sortable1 li, #sortable2 li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 120px;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<body>
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight s2">Item 1</li>
<li class="ui-state-highlight s2">Item 2</li>
<li class="ui-state-highlight s2">Item 3</li>
<li class="ui-state-highlight s2">Item 4</li>
<li class="ui-state-highlight s2">Item 5</li>
</ul>
</body>
</html>
A: Currently your connectWith selector matches both the sortable, i.e it's a two way connection. If you only want one way connection from left to right, just connect the left sortable to right sortable using a more specific selector (#sortable2) than a common one:
$(function() {
$("#sortable1").sortable({
connectWith: "#sortable2"
}).disableSelection();
$("#sortable2").sortable({}).disableSelection();
});
The demo below has the shorter code that does the same thing:
$(function() {
$(".connectedSortable").sortable({
connectWith: "#sortable2"
//----------^---------- #sortable2 connectWith #sortable2 has no effect
}).disableSelection();
});
#sortable1,
#sortable2 {
border: 1px solid #eee;
width: 142px;
min-height: 20px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
}
#sortable1 li,
#sortable2 li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 120px;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight">Item 1</li>
<li class="ui-state-highlight">Item 2</li>
<li class="ui-state-highlight">Item 3</li>
<li class="ui-state-highlight">Item 4</li>
<li class="ui-state-highlight">Item 5</li>
</ul>
A: The options you are looking for are cancel and update (s2 inspired by the post above), it will disable the drag on matched elements.
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable",
cancel: ".ui-state-highlight, .s2",
update: function( event, ui ) {ui.item.addClass("s2");}
}).disableSelection();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35477750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to manage contiguous memory chunks in modern C++? I've been doing some low level C++ programming these days and it involes a lot of memory management issue. For example, I may need to maintain a chunk of contiguous memory:
char* ptr = static_cast<char*>(malloc(sizeof(char)*512*1024));
....
do_something(ptr); // pass to other functions
....
do_something(ptr+sizeof(int)*4); // random access may be needed
....
free(ptr);
However, many books say that we should avoid using any raw pointer in modern C++ programing and smart pointers are preferred. Thus, what's the best practice for contiguous memory chunk management in modern C++? Should I use something like std::unique_ptr or std::allocator?
A:
"many books say that we should avoid using any raw pointer in modern C++"
It is only owning raw pointers that should be avoided. In your case you need to std::free() the pointer so you own it. Therefore you should definitely put it in a std::unique_ptr but with a custom deleter to call std::free().
// some type aliases to make life shorter...
struct malloc_deleter{void operator()(void* vp) const { std::free(vp); }};
using malloc_uptr = std::unique_ptr<char, malloc_deleter>;
auto ptr = malloc_uptr(static_cast<char*>(std::malloc(sizeof(char)*512*1024)));
....
do_something(ptr.get()); // pass to other functions
....
do_something(ptr.get()+sizeof(int)*4); // random access may be needed
....
// no need to free, gets done when ptr` goes out of scope.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52902713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Python open() function without variable initialization. Is close() method needed? I trying to understand file operations in Python 2.7. Script bellow is writing contents of input_file into output_file.
from sys import argv
script, input_file, output_file = argv
open(output_file, 'w').write(open(input_file).read())
Should I call close() method on files opened in example? (and how to reference object that isn't referenced by variable?) Are opened file objects kept in memory even when not referenced by variable?
English is not my native language; please excuse errors.
A: A better approach would be to use context managers:
with open(inputfile, 'r') as inf:
with open(outputfile, 'w') as outf:
out.write(in.read())
close will then be called implicitly on leaving the with block even if an exception is encountered.
However, for that specific example, why not just copy the file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34064573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: String Format with undefined number of characters c# So I'm working on formatting a string and I need to line it up in a table, but this string has an undetermined number of characters. Is there anyway to have the string be in the same spot for each column? so far I have:
ostring += "Notes\t\t"
+ " : "
+ employees[number].Notes
+ "\t\t"
+ employees[number].FirstNotes
+ "\t\t"
+ employees[number].SecondNotes;
I use a similar fashion on the other rows, but they have a pre-determined number of digits, this however doesn't so I can't use the string modifiers like I would like.
Any ideas on what I need to do?
A: You can use String.PadRight() to force the string to a specific size, rather than using tabs.
A: When you are using String.Format item format has following syntax:
{ index[,alignment][ :formatString] }
Thus you can specify alignment which indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).
Also it's better to use StringBuilder to build strings:
var builder = new StringBuilder();
var employee = employees[number];
builder.AppendFormat("Notes {0,20} {1,10} {2,15}",
employee.Notes, employee.FirstNotes, employee.SecondNotes);
A: You would first have to loop over every entry to find the largest one so you know hoe wide to make the columns, something like:
var notesWidth = employees.Max(Notes.Length);
var firstNotesWidth = employees.Max(FirstNotes.Length);
// etc...
Then you can pad the columns to the correct width:
var output = new StringBuilder();
foreach(var employee in employees)
{
output.Append(employee.Notes.PadRight(notesWidth+1));
output.Append(employee.FirstNotes.PadRight(firstNotesWidth+1));
// etc...
}
And please don't do a lot of string "adding" ("1" + "2" + "3" + ...) in a loop. Use a StringBuilder instead. It is much more efficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14023103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Python Module Not Found Error: First function found, but second is not I have a simple dir structure:
project/
__init__.py
main.py
dir1/
__init__.py
foo.py
dir2/
dir3/
Inside of main.py:
from dir1.foo import function1, function2
function1 is imported, but function2 is not, and the following error is thrown.
No module named dir1.foo found.
I have no idea how this is possible.
Edit: I am able to use function1 in main(), but when function2 is called the error is thrown.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36271938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you get Endeca to search on a particular target field rather than across all indexed fields? We have an Endeca index configured across multiple fields of email content - subject and body. But we only want searches to be performed on the subject lines. Endeca is returning matches within the bodies too. How do you limit the search to the subject?
A: You can search a specific field or fields by specifying it (them) with the Ntk parameter.
Or if you wish to search a specific group of fields frequently you can set up an interface (also specified with the Ntk parameter), that includes that group of fields.
A: This is how you can do it using presentation API.
final ENEQuery query = new ENEQuery();
final DimValIdList dimValIdList = new DimValIdList("0");
query.setNavDescriptors(dimValIdList);
final ERecSearchList searches = new ERecSearchList();
final StringBuilder builder = new StringBuilder();
for(final String productId : productIds){
builder.append(productId);
builder.append(" ");
}
final ERecSearch eRecSearch = new ERecSearch("product.id", builder.toString().trim(), "mode matchany");
searches.add(eRecSearch);
query.setNavERecSearches(searches);
Please see this post for a complete example.
A: Use Search Interfaces in Developer Studio.
Refer - http://docs.oracle.com/cd/E28912_01/DeveloperStudio.612/pdf/DevStudioHelp.pdf#page=209
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15500710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Build failure while trying to update to "org.jooq:jooq-codegen-maven:3.15.1" [ERROR] Failed to execute goal org.jooq:jooq-codegen-maven:3.15.1:generate (default) on project event-dao-jooq: Execution default of goal org.jooq:jooq-codegen-maven:3.15.1:generate failed: Unable to load the mojo 'generate' in the plugin 'org.jooq:jooq-codegen-maven:3.15.1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/jooq/codegen/maven/Plugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
A: jOOQ 3.15 requires Java 11 (class file version 55) and you are using Java 8 (class file version 52) in your build. You either need to upgrade to Java 11, downgrade to jOOQ 3.14, or purchase a license for jOOQ 3.15 as all of the commercial editions still support Java 8.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68447084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS and HTML doesn't shows properly in iOS and MacOS Safari even Chrome I have the following issue:
I have this under construction state website, https://endertainment.com, it was build with PHP and MySQL from scratch, like any other I did. The issue is when you access the website from Mobile Safari or Safari the website doesn't show all the elements must show. When you access from Android (Any Browser) or Windows or even in Linux the website shows any element well. I already run test in BrowserStack and CrossBrowserTesting... in both shows the same result; the web didn't show properly. I already remove every flexbox property and use inline-block instead. For example, this other website (https://tuticketazo.com) is under construction state too and use the same structure of https://endertainment.com.
I already made tests changing the server folder the domain points; upload a simple html page from scratch, without PHP ; use without SSL... I think already test everything but in iOS Safari, Mac OS Safari and even in Chrome in MacOS shows the elements but not in the right way.
A: You should set line-height of your heading titles.
#MainTitles h1 { line-height: 50px }
#LangSelect a { line-height: 20px; }
But the problem is not inside these 2 rules. I didn't determinate full code of CSS, I just check small fixes for places which I saw broken
A: I found the problem and resolve the Issue.
OS X have a rendering issue with some fonts.
I start my research searching a common pattern, I has this issue with 3 websites:
*
*Adjusting the line-height didn't work properly.
*Change the ul from inline-block to flexbox, didn't work
*The issue is present in any browser in Mac OS (I test Chrome,
Firefox and Safari)
Continue researching an I found some documentation about the issue.
I found this article
OS X type rendering - text baseline is shifted upwards, effectively no-longer centered vertically within the line-height
I test in the 3 different websites have the issue and VOILA!
Everything works fine now.
I used in the 3 websites the same fonts (the common pattern):
*
*Gotham Book
*Gotham Black
I can confirm this two fonts evoke the rendering issue in Mac Os.
The problem is solved right now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61767607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get a UTF8 encoded string from a Base64 encoded string in Javascript? AEEAQgBDAGEAYgBj is Base64 for ABCabc however when I run this code:
let a = Buffer.from('AEEAQgBDAGEAYgBj', 'base64').toString('utf-8');
console.log(Buffer.from(a, 'utf8'));
the printed result in the console is <Buffer 00 41 00 42 00 43 00 61 00 62 00 63> which is UTF16 (LE).
I would assume that since I am creating a Buffer from a UTF8 encoded string the result would be <Buffer 41 42 43 61 62 63>.
So how can I get an actual UTF8 encoded string from Base64?
A: The problem is that your original data is Base64 encoded UTF16-BE. If you look at a after your first line, you'll see that it has those zero bytes that you see in the final buffer:
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").toString("utf-8");
console.log(a.length);
// 12
console.log([...a].map(ch => ch.charCodeAt(0).toString(16).padStart(2, "0")).join(" "));
// 00 41 00 42 00 43 00 61 00 62 00 63
So the question becomes: How to read the UTF16-BE text you have in the buffer from Buffer.from("AEEAQgBDAGEAYgBj", "base64"). Node.js's Buffer doesn't support UTF16-BE directly (there is no "utf16be" encoding in its standard library), but you can get there via swap16 and then reading the buffer as UTF16-LE ("utf16le", which is in Node.js's standard library):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
Now a is a normal string. If you want a buffer containing its contents in UTF8, you can use Buffer.from(a).toString("utf8"):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
let b = Buffer.from(a); // (Default is `"utf8"` but you could supply that explicitly)
console.log(b);
// <Buffer 41 42 43 61 62 63>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68358552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check if PDFTOHTML is installed on server I'm trying to check before running a php script if pdftohtml is installed on server.
Is there a way to check if pdftohtml is installed on server (linux or mac) from within the code.
I'm looking for something similar to function_exists()
A:
Perhaps, the following will solve your case:
$isInstalled = (bool) shell_exec('which pdftohtml');
which returns nothing if the program isn't found. But it will only work if it's installed globally (without specifying an absolute path). And returns a full path if it's there
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65197813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does every operation need to be a single Command?
What I want to know:
Does every single operation provided on the list in the background paragraph need to be a single command? What do the single commands do?
Background:
I need to write a program which gets started from the cmd and performs operations on a string you can enter as argument to the command line. You also need to pass the operations to be performed as CLA.
For example: myprogram.exe /es "This is the string" /ds /rs .
Es = Enter string, ds = display string, rs= reverse string.
It is not necessary to implement Undo/Redo.
Possible Operations are:
• Enter string
• Display string
• Reverse string
• Upperace all letters
• Lowercase all letters
• Uppercase specific letters
• Lowercase specific letters
• Eliminate consecutive duplicates
• Rotate left
• Rotate right
• Run-length encoding
• Run-length decoding
• Drop every n'th character
• Split by string and take first
• Split by string and take last
What did I do / What is my approach:
I recognized after some research that the optimal way of implementing this example would be to use the Command Pattern and Chain Of Responsibility. I'm reading the book written by the Gang of Four : Design Patterns.
But I think I do not understand perfectly the concept. I know, that using Command Pattern there is a: Invoker, Receiver, Command, CommandInterface etc. I know that the Invoker (here my ProgramHandler.cs class) generates the single Commands, equips them with a receiver and an Action. And the single Command calls the receiver to execute the action. The receiver is a class called StringManipulator which holds all the methods to manipulate a string. My idea is also, that the parser parses the CLA and "tells" the ProgramHandler which Commands need to be created.
(Please have a look on my first design approach, picture at the end!)
But:
Additional Questions:
Isn't that quite a bit of an overhead of having an abstract class SimpleCommand which holds the receiver and action and afterwards the concrete commands inherit from SimpleCommand?
It feels a bit wrong, but on the other hand: Each command needs an action and a receiver, so giving each concrete command these fields separately would be against the "rules" of object oriented Programming.
How is this designed correctly?
Class Diagram
Class Diagram
Thank you for your time and help!
Best regards!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54183000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to click automatically on "Content" button This is element HTML:
<button class="search-vertical-filter__filter-item-button button-tertiary-medium-muted" data-ember-action="" data-ember-action-5975="5975"> Content </button>
Code:
driver.find_element_by_link_text('Content').click()
Even i also tried:
driver.find_element_by_class_name('search-vertical-filter__filter-item-button button-tertiary-medium-muted').click()
I want to click on "Content" button on LinkedIn automatically and I am using Selenium and Python for that.
A: As per the HTML provided to click on the button with text as Content you can use the following line of code :
driver.find_element_by_xpath("//button[@class='search-vertical-filter__filter-item-button button-tertiary-medium-muted' and normalize-space()='Content']").click()
A: Try to use the following code:
driver.find_element_by_css_selector(".search-vertical-filter__filter-item-button.button-tertiary-medium-muted").click()
Hope it helps you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48851955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get body of request in ASP.NET Web Api I faced problem like this.
I have method in controller, that receive data in body of POST request.
Here is method.
// POST: api/StartWorkingDays
[ResponseType(typeof(StartWorkingDay))]
public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.StartWorkingDays.Add(startWorkingDay);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully"});
//return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
}
How I can see body of request that I receive?
Thank's for help.
A: [HttpPost]
public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay)
{
//here above startWorkingDay is body your mobile developer will send
//you and data can be viewed while debugging ,
//tell mobile developer to set content-type header should be JSON.
return Request.CreateResponse(HttpStatusCode.Created, "Success");
}
Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45161946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Cloud Endpoint do not receive a request coming from ORANGE money API I have an endpoint that receives get or post requests from postman or a browser. but when the ORANGE service sends me the request in post I receive nothing.
anxious to believe that the problem comes from the ORANGE service, I went to this site https://webhook.site which generates an end point and listens to the requests made on this one, and to my surprise this endpoint receives many requests from ORANGE.
I don't understand where the problem could come from.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72976124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQLException Error Says Existing Column Doesn't Exist When running a searchQuery, I get a SQLException error saying that one of my columns cannot be found. This is very confusing, as I reference that column earlier in the code, and the program can find the column just fine at that point. do I have something wrong in the syntax? Thank you!
public void createDB(){
String createCharTableSQL = "CREATE TABLE CosplayCharacter (" +
"CharacterID int NOT NULL primary key GENERATED ALWAYS " +
"AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
"name varchar(60) not null," +
"gender varchar(10)," +
"genreID int, " +
"universeID int, " +
"mediaID int, " +
"description varchar(60))";
statement.executeUpdate(createCharTableSQL);
}
public void insertCharacter(){
String fetchAllDataSQL = "SELECT * from CosplayCharacter";
//Code can find the universeID column here
resultSet = statement.executeQuery(fetchAllDataSQL);
while (resultSet.next()) {
String name = resultSet.getString("name");
int universeCharID = resultSet.getInt("universeID");
System.out.println("Character Name : " + name +
" UniverseID : " + universeCharID);
}
}
//But returns error here
public void searchCharacter(String characterName){
String fetchAllDataSQL = "SELECT * from CosplayCharacter where name = '" + characterName +"'";
resultSet = statement.executeQuery(fetchAllDataSQL);
while (resultSet.next()) {
String gender = resultSet.getString("gender");
int genreID = resultSet.getInt("genreID");
//Method to search a column in a joined table; no error
String genreName = getGenreName(genreID);
int universeID = resultSet.getInt("universeID");
}
}
Stack Trace:
java.sql.SQLException: Column 'universeID' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown
Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)
A: ResultSet was used globally. ResultSet used in getGenreName method override the resultSet in the main searchCharacter method. Solution: set ResultSet variable individually in each method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30020380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to return value from addEventListener and use it out When I want to access to variable det out of addEventListener I get undefined.
ElementInfo = function(element) {
var myVar;
this.tagName = element.tagName;
document.addEventListener('Mylistener', function(e) {
myVar = e.detail.workspaceName;
});
this.injected = myVar;
}
How can I get the value of myVar out of addEventListener? I don't use JQuery.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39021300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get all pom.xml present under maven repo Is there any way to get all the pom.xmls which are under http://repo.maven.apache.org/maven2
Thanks,
Vijay
A: As a best practice, you should not scan and parse poms neither in remote nor local repository. On maven central they already scanned and parsed for you.
Just download nexus-maven-repository-index.gz from index dir (you need that big file 700M length, other files named nexus-maven-repository-index.XXX.gz are incremental updates)
Then use Maven Indexer to unpack index, maven indexer is available as java library and CLI program
As a result of running Maven indexer you'll get ordinary Apache Lucene index, with abitility to update it incrementally.
Here is a documentation, which explains how to unpack index and query data from it.
Most probably, index contain all the data you need.
A: For people still having the same question, I have developed a much simpler way to extract maven index indexes that works for most Nexus-based Maven repositories: the Maven Index Exporter.
From there you could simply get a list of poms and download them, if that's what you aim for.
Note however that it's huge: roughly 20 million documents are indexed for Maven Central and the text export is 14GB. There are as of today approximately 6.5 million pom files on Maven Central.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59047125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Set credentials on an Android Webview using secured HTTPS connection I would like to create an Android Webview that connects to a website via a secured HTTPS connection with the use of credentials.
First difficulty was to accept the certificate (private), it was solved with this very useful post.
Second difficulty is to use credentials, I found this post.
(first answer from dparnas) which seems to deal pretty well with it, but it talks about HTTP connection and not HTTPS. I ve tried it, but it doesnt work, I just reach the sign-in form page without any error message, just the normal blank form.
Here is my code:
import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ConnectorWebView extends Activity {
WebView mWebView;
String mUsrName;
String mPassC;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connwebview);
// Getting info from Intent extras
// Get it if it s different from null
Bundle extras = getIntent().getExtras();
mUsrName = extras != null ? extras.getString("username") : null;
mPassC = extras != null ? extras.getString("passcode") : null;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setHttpAuthUsernamePassword("myhost.com", "myrealm", mUsrName, mPassC);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm){
handler.proceed(mUsrName, mPassC);
}
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed() ;
}
});
mWebView.loadUrl("https://myhost.com/secured_area");
}
}
A: The WebView class doesn't provide as much flexibility in its connectivity as using the low level classes (such as HttpPost or the like) directly.
If you need to fully control the connection to the server -- or deal with complicated authorization scenarios such as this one -- use the low level classes, retrieve the data, then use WebView.loadData() to load and show the HTML.
Here is a good example of loading content using SSL and a BasicCredentialProvider. The result of this could be loaded into the WebView as described above.
A: As it seems that WebView cannot natively handle Basic authentication when using HTTPS, I started toying with the idea of setting the Authorization header (containing the encoded username/password) manually.
Here's how I think this can be done:
import org.apache.commons.codec.binary.Base64;
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connwebview);
// Getting info from Intent extras
// Get it if it s different from null
Bundle extras = getIntent().getExtras();
mUsrName = extras != null ? extras.getString("username") : null;
mPassC = extras != null ? extras.getString("passcode") : null;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
// mWebView.setHttpAuthUsernamePassword("myhost.com",
// "myrealm",
// mUsrName,
// mPassC);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler,
String host,
String realm){
handler.proceed(mUsrName, mPassC);
}
public void onReceivedSslError(WebView view,
SslErrorHandler handler,
SslError error) {
handler.proceed() ;
}
});
String up = mUserName +":" +mPassC;
String authEncoded = new String(Base64.encodeBase64(up.getBytes()));
String authHeader = "Basic " +authEncoded;
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", authHeader);
mWebView.loadUrl("https://myhost.com/secured_area", headers);
}
This takes advantage of the WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method and for this example I'm using the Base64Encoder from Apache Commons. The Base64Encoder part is quite trivial and if you didn't want to include external libraries in your application (for whatever reason), you could always write your own (reference).
Also note that the aforementioned WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method is only available in API 8+. For reference, see also the Wikipedia article on Basic Authentication (which discusses the headers, etc).
A: Alternative Scenario:
If willing to write roundabout 10 lines of javascript using jQuery, this scenario is rather simple.
Inject your javascript code into the webview or in case you're controlling the html page you are displaying, include it there.
If you need to interface back from javascript, you can do that. For heavier command exchange, use the CordovaWebView-Interface which has a lower delay depending on api level.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4540972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Draw on desktop (windows/ubuntu) using python I am doing a project in which I need to show lines on window. Also I want to move cursor along the line. I am looking forward to work in python.
How can I do this using python or other languages. Please help me
A: i only just found this out and here you go.
import win32gui
def DRAW_LINE(x1, y1, x2, y2):
hwnd=win32gui.WindowFromPoint((x1,y1))
hdc=win32gui.GetDC(hwnd)
x1c,y1c=win32gui.ScreenToClient(hwnd,(x1,y1))
x2c,y2c=win32gui.ScreenToClient(hwnd,(x2,y2))
win32gui.MoveToEx(hdc,x1c,y1c)
win32gui.LineTo(hdc,x2c,y2c)
win32gui.ReleaseDC(hwnd,hdc)
x1 = 640
y1 = 400
x2 = 840
y2 = 600
DRAW_LINE(x1, y1, x2, y2)
as for moving your mouse underneath the lines i cant figure that out
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32203205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 'Group by' is not grouping by in the order that I need it to I want to 'group by' beers so that they are grouped together, with the respect aggregate rating and tasters (people who review the beers) listed in separate columns.
Here is my code:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
;
Yet my output looks like this:
beers=# select * from tasters_avg_ratings1;
taster | beer | rating
--------+------------------------+--------
Peter | XXXX | 5.0
Sarah | James Squire Pilsener | 3.0
Raghu | Sierra Nevada Pale Ale | 3.0
Hector | Fosters | 3.0
John | Chimay Red | 3.0
John | Sierra Nevada Pale Ale | 5.0
Geoff | James Squire Pilsener | 4.0
Ramez | Sierra Nevada Pale Ale | 4.0
John | 80/- | 4.0
John | Rasputin | 4.0
Adam | Old | 4.0
John | Crown Lager | 2.0
Jeff | Sierra Nevada Pale Ale | 4.0
Sarah | Burragorang Bock | 4.0
Sarah | Scharer's Lager | 3.0
Sarah | New | 2.0
Geoff | Redback | 4.0
Adam | Victoria Bitter | 1.0
Sarah | Victoria Bitter | 1.0
Raghu | Rasputin | 3.0
Ramez | Bigfoot Barley Wine | 3.0
Hector | Sierra Nevada Pale Ale | 4.0
Sarah | Old | 3.0
Jeff | Burragorang Bock | 3.0
John | Empire | 3.0
Sarah | James Squire Amber Ale | 3.0
Rose | Redback | 5.0
Geoff | Empire | 3.0
Adam | New | 1.0
Jeff | Rasputin | 1.0
Raghu | Old Tire | 5.0
John | Victoria Bitter | 1.0
(32 rows)
As you can see, the beers are NOT grouped together. Ideally for example, the 'Victoria Bitter' beers should be displayed as a group, not separated.
The desired result is achieved using 'order by'. For example:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
order by a.beer
;
OUTPUT:
beers=# select * from tasters_avg_ratings1;
taster | beer | rating
--------+------------------------+--------
John | 80/- | 4.0
Ramez | Bigfoot Barley Wine | 3.0
Jeff | Burragorang Bock | 3.0
Sarah | Burragorang Bock | 4.0
John | Chimay Red | 3.0
John | Crown Lager | 2.0
Geoff | Empire | 3.0
John | Empire | 3.0
Hector | Fosters | 3.0
Sarah | James Squire Amber Ale | 3.0
Geoff | James Squire Pilsener | 4.0
Sarah | James Squire Pilsener | 3.0
Adam | New | 1.0
Sarah | New | 2.0
Adam | Old | 4.0
Sarah | Old | 3.0
Raghu | Old Tire | 5.0
Jeff | Rasputin | 1.0
John | Rasputin | 4.0
Raghu | Rasputin | 3.0
Geoff | Redback | 4.0
Rose | Redback | 5.0
Sarah | Scharer's Lager | 3.0
Hector | Sierra Nevada Pale Ale | 4.0
Jeff | Sierra Nevada Pale Ale | 4.0
John | Sierra Nevada Pale Ale | 5.0
Raghu | Sierra Nevada Pale Ale | 3.0
Ramez | Sierra Nevada Pale Ale | 4.0
Adam | Victoria Bitter | 1.0
John | Victoria Bitter | 1.0
Sarah | Victoria Bitter | 1.0
Peter | XXXX | 5.0
(32 rows)
So while I know order by achieves my result, why doesn't 'group by' do the same thing? It is frustrating because I have seen numerous examples on the internet using 'group by' and succeeding especially in cases similar to mine with non-aggregate and aggregate columns. For example: https://learnsql.com/blog/error-with-group-by/ , at tip #3.
Any help would be appreciated, thanks!
A: GROUP BY is only being used to compute the aggregate value (average rating in this case). It doesn't have anything to do with the ordering of the results when they are displayed. As you have mentioned, you need to use ORDER BY to get the desired ordering.
A: Group By should be used to group rows that have the same value for the specified column,
Full explanation here https://stackoverflow.com/a/2421441.
In your case, you want to group beers with the respect to aggregate rating and tasters, so you need to GROUP BY a.beers and order by the first and the third column.
Thus the view should be like this:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by a.beer
order by 1,3;
1 and 3 are the ordinal positions of columns that appear in the select list.
A: The SQL standard defines that a SELECT statement without an ORDER BY may return the resulting rows in an arbitrary order. There is a good explanation of why it might look different at first.
GROUP BY is for grouping and aggregating related tuples together. A trivial implementation for grouping is of course sorting the data first and then working your way from top to bottom and aggregate related tuples. If your database chooses to use such an implementation chances are high you will receive an ordered result set. But there are other implementations possible and your database may change to using one of those at any time. And if it does you will receive the same rows but in a different order.
So in short, if you want your result set to be ordered use an ORDER BY.
Regarding the example you mentioned it is perhaps a bit misleading. The result is ordered by the columns it is also grouped by. This is a possible ordering and given the thoughts before probably quite a likely one. But since the query is without an ORDER BY this is just coincidence and not guaranteed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74533579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When is the screenshot taken for the app drawer? I have an app with a login page. In the login page, I have a switch to allow the user to show the password they are entering in plain text to ensure they are entering it correctly. However, when I pause the app and the app goes into the background, a screenshot is taken and the plain text password can be seen in the app drawer.
I tried adding a statement in the onPause() method of the activity to turn off the Hide/Show switch before pausing. You can see the password revert back to a masked password before the app pauses, but the screenshot still shows the plain text password.
So I'm wondering when the screenshot for the app drawer is taken and whether I can get the password switched back to masked before that happens.
I know about the FLAG_SECURE window flags but that creates a black app drawer screenshot and I would prefer to give something more user-friendly to the user.
Thanx in advance.
A: Unfortunately, what you want is not supported. There is a method in Activity called onCreateThumbnail() that can be overridden to provide a custom thumbnail, but according to a post from Dianne Hackborn in 2009, this method is never actually called:
https://groups.google.com/d/msg/android-developers/J5uBtHzhG8E/bX43j_GAm4gJ
I've tried it relatively recently myself to no effect, so I have to assume that's still the case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25169787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retaining a value obtained from file within the return value of a method Assuming I will need to access the values contained within a given file a small number of times, from different methods, can I include some sort of boolean value within a method to determine whether or not it is appropriate to call the file?
Lets say I have the file config.cfg. In that file, there are three values:
string/name>max|
bool/adult>yes|
int/age>20|
The method getUserName() returns the value of "max". It does this by calling the file:
using (StreamReader reader = new StreamReader(path))
{
//get line beginning with string/name here
return //string value containing name
}
Let's assume I need to use the value of name several times, as well as the values isAdult and clientAge. Rather than accessing the file over and over again, it could be much easier to save the requested value in some form of static variable. However, this variable still needs to be changed in value at least once, when the method is first called.
Can I do this inside the method getUserName()?
Furthermore, is this idea even possible within the bounds of OOP? Is it a similar concept to Prefetch?
A: Create a static class. Something like this:
public static class ClientConfig{
public static string Name{get;set;}
public static bool IsAdult{get;set;}
public static int Age{get;set;}
public static void Load(){
// load your values
// ClientConfig.Name = name from file etc.
}
public static void Save(string newName, int age, bool value){
// save your values to the config file
}
}
And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)
A: It really looks to me that you need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());
Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44474978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook JavaScript SDK help 1002 I am using the jQuery library for authenticating the user, using this script:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// Initialize the library with the API key
FB.init({ apiKey: 'SECRET_KEY' });
// Fetch the status on load
FB.getLoginStatus(handleSessionResponse);
dojo.connect(dojo.byId('login'), 'click', function() {
FB.login(handleSessionResponse);
});
dojo.connect(dojo.byId('logout'), 'click', function() {
FB.logout(handleSessionResponse);
});
dojo.connect(dojo.byId('disconnect'), 'click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
It is showing
An error has occured please try again. followed by an OK button.
When I click that OK button it says:
Sorry, something went wrong.
We're working on getting this fixed as soon as we can.
A: This is wrong:
FB.init({ apiKey: 'SECRET_KEY' });
Not secret key, just the application id.
A: From the documentation for the JavaScript SDK:
You can see that your secret key is not needed, as the JavaScript is available for anyone to read. Facebook's authentication uses the domain of your request to verify that it is, in fact, your application.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9547380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: whitelist allowed hosts, block everything else using the chrome.declarativeWebRequest, it is possible to execute actions if some conditions apply. The only available Condition is an Instance of declarativeWebRequest.RequestMatcher which is useful to test if the url has some features. I am searching for a way to test if an url does not have some features For instance:
chrome.declarativeWebRequest.onRequest.addRules([
{
conditions: [
new chrome.declarativeWebRequest.RequestMatcher({
url: { hostSuffix: 'google.com' } })
],
actions: [
new chrome.declarativeWebRequest.CancelRequest()
]
}
]);
Will block all Requests to the host google.com. But I am interested in a rule that does the opposite, block everything but google.com.
A: According to documentation, you can use the rules' priorities to achieve your goal: create one rule to cancel all requests and another rule, with higher priority, to ignore the first rule if the host is google.com.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52148330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to list out all the api in an Django application? I have an Django application which is around 4 years old.
I want list out all the api in order to remove all inactive api's from the codebase.
Is there any way to figure out all the API?
The application is based on Djnago. We are using javascript for the frontend part.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54860970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: YAML issue when knitting to pdf I have a paper written in rnotebook, which I want to knit to pdf.
this is the beginning of it, including the YAML:
---
title: "Are shifts between points of view challenging for readers? An examination of readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*"
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
html_notebook:
fig_caption: yes
force_captions: yes
#highlight: pygments
number_sections: false
theme: readable
# csl: sage-harvard.csl
csl: apa.csl
bibliography: library.bib
link-citations: yes
nocite: |
@Grisot2018
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```
```{r, include=F}
library(tidyverse)
library(ggpubr)
```
# Abstract
The emergence of empirical approaches within stylistics has increased interest in how literary texts are processed by readers. Techniques of speech and thought representation represent an area ripe for empirical investigation in this respect, especially when these cause interpretative ambiguities.
I have installed tinytex, and I have got miktex installed and pandoc.
I have tried to just use the "knit to pdf" command in RStudio but it gives me this error and i don't know what to do
Error in yaml::yaml.load(..., eval.expr = TRUE) :
Scanner error: while scanning for the next token at line 4, column 31 found character that cannot start any token at line 4, column 31
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted
A: I think this is down to the formatting in your yaml. When I knitted your code R Studio did some re-formatting of the title, but in the process replaced the ' with " in your date, causing the error. I don't have your .bib file so I can't test your exact code, but the following worked for me:
---
title: Are shifts between points of view challenging for readers? An examination of
readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
pdf_document: default
html_notebook:
fig_caption: yes
force_captions: yes
number_sections: no
theme: readable
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```
```{r, include=F}
library(tidyverse)
#library(ggpubr)
```
# Abstract
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56968265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using string.prototype.replace with a regexp and a function The following returns 'entiy'. I want it to return 'entity'. How can I achieve this?
'entities '.replace(/\w(ies)(?:[\W|$|_])+/g, 'y');
A: You could change the \w to \B to verify that there is not a word boundary.
console.log('entities '.replace(/\Bies\b/g, 'y'));
A: Just capture the character before the "ies":
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, '$1y');
Now your question asked about using a function; you can do that too:
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, function(_, before, repl) {
return before + "y";
});
I don't know what you want to do with the subsequent stuff after "ies"; you can either capture it and glue it back into the replacement, or else use positive look-ahead. Portions of the input text matched by look-ahead are not part of the match involved with the replacement operation. In other words, the look-ahead does succeed or fail based on the pattern, but the characters matched are not made part of the "to be replaced" grouping.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40534885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to serve static images in nodejs server using absolute path in Angular 10 img tag? I have been searching here and not finding a solution, so I am asking. How can I serve my static images located in the nodejs server:
public/img
Nodejs (before app.listen()):
app.use("/api", routesIndex);
app.use(express.static(__dirname + '/public/img'));
Angular 10 template:
<img class="center" [src]="quizService.rootUrl+'/public/img/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'">
The [src] resolves to the absolute correct path of:
http://localhost:5000/api/public/img/shark.jpg
But it shows 404 still. Any ideas?
Thanks
A: There is no need to add path of statically served directory. Just remove '/public/img/'
<img class="center" [src]="quizService.rootUrl + quizService.questions[quizService.questionProgress].imageName+'.jpg'">
You can access the all file of your served directory directly. like:
http://localhost:5000/shark.jpg
A: Follow the below steps,
your image is at path Public/img/shark.jpg
in your app.js, this should be before any route is created
app.use(express.static(__dirname + '/public/img'));
create a route as below
app.get('/Image/:id', function (req, res) {
// logic to find image based on id passed, we will assume it results in shark.jpg
const filepath = `${__dirname}/public/img/shark.jpg`;
res.sendFile(filepath);
});
Now consume this endpoint from your angular code
localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}
A: I got it working by doing the following:
Nodejs added path:
const path = require("path");
app.use(express.static(path.join(__dirname, 'public/img')));
Then in Angular created a separate assetUrl that omits the "/api" part of the baseUrl:
[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"
and now my images are served.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63633871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filter Data in Shiny by Clicking on Plot Data Point I Want to filter data by click on data points of plot in Shiny, like we have in powerbi.
i have developed a dashboard in powerbi i want to have a same effect in shiny,
like if i click the data point of plot in shiny dashboard the other plots should drill down in response to that point, i have build a complete dashboard in shiny but i need to add these function.
there can also be multiple data points drill down like if i want to know the february(datapoint) month sales of John(datapoint).
A: In the UI, you should add, click,doubleclick or hover:
plotOutput("plot1", click = "plot_click")
And in the Server will be input$plot_click, X and Y coordinates
Here a Shiny explanation:
https://shiny.rstudio.com/articles/plot-interaction.html
And I wrote for you a simple example:
library(shiny)
library(ggplot2)
library(MASS)
ui<- shinyUI(
fluidPage(
plotOutput("grafica", hover="clickGrafica"),
tableOutput("miverbatini")
)
)
server<- shinyServer(function(input,output) {
output$grafica <- renderPlot({
ggplot(mpg,aes(x=cty, y=hwy)) +
geom_point()
})
output$miverbatini <- renderTable({
nearPoints(mpg,input$clickGrafica, threshold = 10) # near points 20
})
})
shinyApp(ui, server)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53060163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why Radio button selects multiple options when label values are different Having a reusable Radio button component, when the options are using the same value for name it works fine:
const drinks = [
{
label: "Coffee",
name: "a"
},
{
label: "Tea",
name: "a"
},
{
label: "Water",
name: "a",
disabled: true
}
];
But when they are different values, it doesn't work fine, it lets the user select multiple options:
const drinks = [
{
label: "Coffee",
name: "1"
},
{
label: "Tea",
name: "2"
},
{
label: "Water",
name: "3",
disabled: true
}
];
Here is a working sandbox of it as it's complicated to create a working example here: https://codesandbox.io/s/custom-radio-button-group-forked-1do5u4?file=/src/App.tsx
A: As i mentioned in comment,
the code is working as expected
const drinks = [
{
label: "Coffee",
name: "a"
},
{
label: "Tea",
name: "a"
},
{
label: "Water",
name: "a",
disabled: true
}
];
the name attribute is used to group radio buttons,and only one radio button in the group can be selected at a time.
A: It is working as expected. If it's a radio button, then it's ONE name and multiple possible values. Only one of them can be selected at a time.
const drinks = [
{
label: "Coffee",
name: "drinkType"
},
{
label: "Tea",
name: "drinkType"
},
{
label: "Water",
name: "drinkType",
disabled: true
}
];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74996452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to correctly use two DatePickerSingle in a Dash Application Hope you all doing well.
I have two DatePickerSingle that I want to integer in a dash application to use them as a filter further. The problem is that my Dash app only returns values of the first DatePickerSingle, but not the second one ..
from datetime import date
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc
Min_d =datetime.strptime(str(df_sub['From'].min()), "%Y-%m-%d %H:%M:%S")
Max_d = datetime.strptime(str(df_sub['From'].max()), "%Y-%m-%d %H:%M:%S")
app = dash.Dash(__name__)
app.layout = html.Div([
html.H2("Date for the First period"),
dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed = date(2021,4,1),
max_date_allowed = date(2021,9,30)
),
html.H2("Date for the Second period"),
dcc.DatePickerRange(
id='my-date-picker-range2',
min_date_allowed = date(2021,4,1),
max_date_allowed = date(2021,9,30)
),
html.Div(id='output-container-date-picker-range')
])
@app.callback(
Output('output-container-date-picker-range', 'children'),
Input('my-date-picker-range', 'start_date'),
Input('my-date-picker-range', 'end_date'),
Input('my-date-picker-range2', 'start_date2'),
Input('my-date-picker-range2', 'end_date2')
)
def update_output(start_date , end_date , start_date2 , end_date2):
return ( str(start_date) + ' ' + str(end_date)+ ' ' +str(start_date2)+ ' ' + str(end_date2))
if __name__ == '__main__':
app.run_server(debug=False)
Here is what I got when I run the app :
A: The problem is with these lines:
Input('my-date-picker-range2', 'start_date2'),
Input('my-date-picker-range2', 'end_date2')
start_date2 and end_date2 are not valid properties of dcc.DatePickerRange, so change these instances to start_date and end_date.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69944527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VB 2008 Express edition vs VB 6 Can any tell me what are the advantages of VB.NET(2008 Express Edition) over VB 6?
Thank you
A: Good comparison you can find in Wiki:
VB.NET
In short: the greatest feature in VB.NET is Managed Code. It also contains a little difference between Long and Integer in VB6 and VB.NET. There are also many small syntax changes (for example, VB.NET support structured exception handling).
A: VB6 is a old fashioned programming software from microsoft. It doesn't use as a base .NET framework which is used on every machine. Also visit Wkipedia VB
A: .NET have multithreading and more functional components (for work with network for example).
A: Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its Component Object Model (COM) programming model first released in 1991, final release was version 6 in 1998 (VB6) and declared legacy during 2008.
Visual Basic.net is part of the .net framework (like C# or F#), first released in 2002, with constant Microsoft updates.
You can use VB.Net in Visual Studio 2008 Express (free) or in any Visual Studio IDE, like the Visual Studio 2017 Community edition (also free).
https://en.wikipedia.org/wiki/Comparison_of_Visual_Basic_and_Visual_Basic_.NET
VB6 uses legagy frameworks like Dynamic Data Exchange (DDE) and DAO. The VB6 IDE is hard to install on new operating system (original setup gives errors on Windows 7, 8 or 10).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12769676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: VNC feed from a remote server I want to measure the performance of the VNC feed from a remote server. The use case is, there will be a user login to the remote server and doing some operations. There will be many other users viewing these operations through the VNC viewer (ssh connection). Based on the different network speed I want to measure the performance of the VNC feeds of the users who are viewing. How to achieve this through JMeter?
Note that the users who are viewing are not doing any operations on the remote server.
A: VNC and SSH are different beasts so your VNC viewer (ssh connection) stanza doesn't make a lot of sense, VNC is a separate protocol and JMeter doesn't support it either via its samplers or via plugins
If you still want to use JMeter for load testing your VNC server you will need to implement the client login and getting initial image using some form of VNC Java client library like Vernacular VNC from JSR223 Sampler or come up with your own JMeter plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70595866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set a Sharepoint lookup field when inserting a new record in PowerApps I am using the Collect function to insert a new record into a Sharepoint list using PowerApps. There is a Gallery with a list of values from another Sharepoint List. I want to use the Selected value from the Gallery to set one of the fields in the Insert List.
I thought it would be as easy as this:
Collect('Concert Log List',{Attendee: BrowseGallery1.Selected});
Essentially I want to add a new record to the Content Log List and reference the Attendee (which is the lookup list) every time the Attendee is referenced. Now the field just ends up being blank.
A: Hm. Gallery1.Selected represents the entire record in the Sharepoint List. Can you add another . to Selected to get to the actual field you want to write?
Gallery1.Selected.Attendee (or the like)
A: Got it:
Patch('Child List',
Defaults('Child List'),
{
Title:"test",
ParentItem:
{
Id:Gallery1.Selected.ID,
Value:Gallery1.Selected.Title
}
}
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58572685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gseapy: how to get gene list used for each pathway I am running an enrichment analysis with gseapy enrichr on a list of genes.
I am using the following code:
enr_res = gseapy.enrichr(gene_list = glist[:5000],
organism = 'Mouse',
gene_sets = ['GO_Biological_Process_2021'],
description = 'pathway',
#cutoff = 0.5
)
The result looks like this:
enr_res.results.head(10)
The question I have is, how do I get the full set of Genes (very right column in the picture) used for the individual pathways?
If I try the following code, it will just give me the already displayed genes. I added some correction to have a list that I then could further use for the analysis.
x = 'fatty acid beta-oxidation (GO:0006635)'
g_list = enr_res.results[enr_res.results.Term == x]['Genes'].to_string()
deliminator = ';'
g_list = [section + deliminator for section in g_list.split(deliminator) if section]
g_list = [s.replace(';', '') for s in g_list]
g_list = [s.replace(' ', '') for s in g_list]
g_list = [s.replace('.', '') for s in g_list]
first_gene = g_list[0:1]
first_gene = [sub[1 : ] for sub in first_gene]
g_list[0:1] = first_gene
for i in range(len(g_list)):
g_list[i] = g_list[i].lower()
for i in range(len(g_list)):
g_list[i] = g_list[i].capitalize()
g_list
I think my approach might be wrong to get all the Genes and I just get the displayed genes. Does somebody has an idea, how it is possible to get all genes?
A: pd.set_option('display.max_colwidth', 3000)
This increases the number of displayed characters and somehow this solves the problem for me. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72802665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable a command box in Databricks notebook I have a Databricks Notebook. My notebook has several command. some of them is just for my test and I do not want ran them on production.
Is there any way to just disable a command. I do not want to delete them permanently.
A: Late ... but ... my solution is to set %md as first line. So no command would be executet.
David
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63731174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Canceling pending sends errors I am running Selenium WebDriver scripts on Chrome Browser, version 23.
The tests run successfully without any error but there is a message:
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
And because of the above error, the result of the test is FAILED.
Here is how I instantiate a chrome browser session:
public static boolean setup(String browserType){
if(browserType.equals("IE")){
webdriver1 = new InternetExplorerDriver();
} else if(browserType.equals("Chrome")){
System.setProperty("webdriver.chrome.driver","path to chromedriver.exe");
webdriver1 = new ChromeDriver();
}
Appreciate any feedback from anyone who has resolved this issue.
A: According to https://code.google.com/p/chromedriver/issues/detail?id=159 it has something to do with your browser has not yet finished loading a page, while selenium closes and quits the driver.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14148521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Deleting table data from tablespace in Oracle I tried to delete the data from tablespace using the command
DROP USER xyz CASCADE;
I found that user was dropped but size of my tablespace did not decreased.
Is my data fom the tablespace have been deleted? If yes, how can I confirm that? And why was the space not deallocated?
A: Oracle does not automatically shrink datafiles, which is what a tablespace is made of. Oracle simply marked the space which had been used by user XYZ's segments (tables, indexes, and the like) as free for some other user's segments to use.
SELECT * FROM DBA_OBJECTS WHERE OWNER = 'XYZ'; should demonstrate that user XYZ no longer owns any physical (tables, indexes, clusters) or logical (sequences, procedures, packages, triggers, types) objects in the database.
A: You can shrink datafile, under certain circumstances, with following command:
ALTER DATABASE DATAFILE 'filename2' RESIZE new_size;
Datafile size can be reduced if there is no data at the end of file. See "Managing Tablespaces" for detailed information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3459533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Influxdb python write_api not write specific fields I am trying to write several points into influxdb by using the python client.
Most of them are working but some specific fields of points are not saving.
Here's my code.
def getPoints(p_zones):
# Writing max values to p_zones and then add to write_api
points = []
for p_zone in p_zones:
point = Point("mem") \
.tag("zone", p_zone.zone) \
.field("historic", p_zone.historic) \
.field("current", float(p_zone.current)) \
.field("hourMaxValue", p_zone.hourMaxValue) \
.time(p_zone.timestamp.astimezone(eastern), WritePrecision.NS)
# .tag("label", p_zone.label) \
points.append(point)
return points
points = getPoints(p_zones)
# Writing to influx
with client.write_api(write_options=WriteOptions(retry_interval=15, max_retries=2, write_type=SYNCHRONOUS)) as write_api:
write_api.write(bucket=bucket, org=org, record=points)
And here is the log of points before writing to influxdb.
mem,zone=Pool\ Deck current=0,historic=25,hourMaxValue=25 1653931921000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931920000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931915000000000
mem,zone=Game\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Pool\ Club\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=TV\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Weight\ Room current=2,historic=2,hourMaxValue=2 1653931920000000000
mem,zone=Movie\ Theater current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Business\ Conference\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Cardio\ Room current=1,historic=1,hourMaxValue=1 1653931920000000000
mem,zone=TV\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000
But in online influxdb, I can see every points are looking good but the Pool Deck point's current andhourMaxValue fields are not saving.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72438149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: regex excluding time from text I would like to extract time from the text below using regex.
Text: "Media: a few minutes ago, 3:25 pm uts"
Regex pattern to select only time (ex: 3:25) from the above text?
A: Use regex /\b[0-9]+:[0-9]+\b/. Explanation:
*
*\b - word boundary
*[0-9]+ - 1+ digits
*: - literal colon
*[0-9]+ - 1+ digits
*\b - word boundary
I do not know your specific use in selenium, but here is an example:
src = 'Media: a few minutes ago, 3:25 pm uts'
pattern = re.compile(r'(\\b[0-9]+:[0-9]+\\b)')
match = pattern.search(src)
print match.groups()[0]
Output:
3:25
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66362996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Zend_Log with multiple writers in application.ini i have a logger in my config like this:
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/err.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = 3
But i want to use it for only error logs. For another logs wanna use another log file. For that reason i added these lines to app.ini
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority[] = 7
resources.log.stream.filterParams.priority[] = 5
But this is not working i wanna use differetn files for different priorities. But logger overrides the first logger. How ?
A: Example of application.ini:
resources.log.err.writerName = "Stream"
resources.log.err.writerParams.stream = APPLICATION_PATH "/../data/logs/ERR.log"
;resources.log.stream.formatterParams.format = "%priority%:%message% %timestamp% %priorityName% %info% PHP_EOL"
resources.log.err.filterName = "Priority"
resources.log.err.filterParams.priority = 3
resources.log.err.filterParams.operator = "=="
resources.log.warn.writerName = "Stream"
resources.log.warn.writerParams.stream = APPLICATION_PATH "/../data/logs/WARN.log"
;resources.log.warn.formatterParams.format = "%priority%:%message%:%ip%:%userid% %timestamp% %priorityName% %info% PHP_EOL"
resources.log.warn.filterName = "Priority"
resources.log.warn.filterParams.priority = 4
resources.log.warn.filterParams.operator = "=="
In bootstrap:
protected function _initLog() {
$options = $this->getOption('resources');
$partitionConfig = $this->getOption('log');
$logOptions = $options['log'];
$logger = Zend_Log::factory($logOptions);
$logger->addPriority('USERACTION', 8);
$logger->addPriority('DBLOG', 9);
Zend_Registry::set('logger', $logger);
}
Then in codes:
$this->logger = Zend_Registry::get('logger');
$this->logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']);
$this->logger->setEventItem('userid', $this->userId);
Use this way:
$this->logger->log('Test error', Zend_Log::WARN);
Or this way:
$this->logger->warn('Test error');
Or this way:
$this->logger->log('Test error', 4);
A: You can use filters to accomplish this. Just let higher priority events pass through the filters until you want to log them.
http://framework.zend.com/manual/en/zend.log.filters.html
What's wrong in your setup is that you are trying to use the same writer which you should not. Use the filters to choose the writers and associate certain log files with certain writers, as shown in the second part of the example.
I think something like that should do the trick:
resources.log.stream.writerName = "myDebugWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::WARN
resources.log.stream.writerName = "myInfoWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::INFO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7335482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there any Number recognition SDK or frameworks or libraries for iPhone I need number recognition for my project, as i will write the number using touches. i want that to be recognized.
Can anyone Please Help me, provide me any ideas or frameworks or libraries related to this.
A: this might get you started http://code.google.com/p/dollar-touch/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6235758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.