text stringlengths 15 59.8k | meta dict |
|---|---|
Q: Send the active sheet as an email attachment from google sheets I have a google form that captures responses in a spreadsheet. It currently creates a new sheet everytime a new response is made.
I'm now trying to add a "mail the active sheet script" to the existing script that creates a new sheet.
However I get an error "Request failed for https://docs.google.com/spreadsheets/d/SS_ID/export?" around the following
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
I have used this article as a guide for the send email part.
This is the entire script I am using.
function onSubmit(e){
Logger.log('submit ran');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get last row of data
var lastRow = sheet.getLastRow();
var colB_Data = sheet.getRange(lastRow, 2).getValue();
//create sheet name with order no.
ss.insertSheet(colB_Data);
//order formula
var sheets = ss.getSheets()[1];
var cell = sheets.getRange("b2");
cell.setFormula("=TRANSPOSE('Form Responses 1'!B1:AR1)");
var cell = sheets.getRange("c2");
cell.setFormula("=sheetName()");
var cell = sheets.getRange("c3");
cell.setFormula("=transpose(FILTER('Form Responses 1'!C:AR,'Form Responses 1'!B:B=C2))");
var cell = sheets.getRange("d5:d44");
cell.setFormula("=C5*vlookup(B5,'RG Cost'!B:E,4,0)");
var cell = sheets.getRange("d5:d44");
cell.setNumberFormat("[$₹][>9999999]##\,##\,##\,##0;[$₹][>99999]##\,##\,##0;[$₹]##,##0")
var cell = sheets.getRange("c47");
cell.setFormula("=sum(C5:C44)");
var cell = sheets.getRange("d47");
cell.setFormula("=sum(D5:D44)");
var cell = sheets.getRange("b47");
cell.setValue('TOTAL');
//Send active sheet as email attachment
var ssID = SpreadsheetApp.getActiveSpreadsheet();
var email = Session.getUser().getEmail();
var subject = "Order no.";
var body = "Hello";
var token = ScriptApp.getOAuthToken();
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?" + "format=xlsx" + "&gid=" + "&portrait=true" + "&exportFormat=xlsx";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail("xyz@xyz.com",subject ,body, {attachments:[{fileName:colB_Data+".pdf", content:contents, mimeType:"application//pdf"}]});
};
A: As mentioned by @cooper before, the ssID wasn't properly added to the URL, and also there's a few changes to be made the url and your fetchapp
//Send active sheet as email attachment
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetgId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
var email = Session.getUser().getEmail();
var subject = "Order no.";
var body = "Hello";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url)
var contents = result.getContent();
MailApp.sendEmail("abc@abc.abc",subject ,body, {attachments:[{fileName:colB_Data+".pdf", content:contents, mimeType:"application//pdf"}]});
You're sending an HTTP GET directly to your same drive, so the user, I assume, is logged to a google account and has access to the spreadsheet, therefore you don't really need a token again.
Second you forgot to add the variables to the parameters in the export mode URL and I changed the export format to pdf.
A: It didn't work without token so I used this:
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "name@domain.com";
var subject = "Important Info!";
var body = "PFA the report \n\nCheers,\n Roportobot";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42282117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I store characters in flash memory STM32F4 HAL with C++? So I have a buffer:
uint32_t buff[2];
buff[0] = 12;
buff[1] = 13;
...
I can write this to the flash memory with the method:
HAL_FLASH_Program(TYPEPROGRAM_WORD, (uint32_t)(startAddress+(i*4)), *buff)
The definition of HAL_FLASH_Program is:
HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
That works perfectly. Now is there a way I can store chars instead or ints?
A: You can use HAL_FLASH_Program with TYPEPROGRAM_BYTE to write a single 1-byte char.
If your data is a bit long (a struct, a string...), you can also write the bulk with TYPEPROGRAM_WORD, or even TYPEPROGRAM_DOUBLEWORD (8 bytes at a time), and then either complete with single bytes as needed or pad the excess with zeros. That would certainly be a bit faster, but maybe it's not significant for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30777299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to refactor to remove the control statements from @ngrx effects? I have a if control statement in an effect to return an action in the case of data has been retrieved from a service, if not return another action to get data from another Web API. It is a chained effects operation where there is another effect to handle the LOADFROMWEBAPI action.
Is there a better way and avoid the if control statement, and return one action like LoadFromWebAPI only? Where the action SearchCompleteAction can be returned is the question - in effect or reducer?
@Effect()
search$: Observable<Action> = this.actions$
.ofType(book.SEARCH)
.debounceTime(300)
.map(toPayload)
.switchMap(query => {
if (query === '') {
return empty();
}
const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => {
if (data === undefined) {
return new book.LoadFromWebAPI(query);
} else {
return new book.SearchCompleteAction(books);
}
})
.catch(() => of(new book.SearchCompleteAction([])));
});
A: @Effect()
search$: Observable<Action> = this.actions$
.ofType(book.SEARCH)
.debounceTime(300)
.map(toPayload)
.filter(query => query !== '')
.switchMap(query => {
const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => data === undefined ? new book.LoadFromWebAPI(query) : new book.SearchCompleteAction(books))
.catch(() => of(new book.SearchCompleteAction([])));
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43597070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clicking Google reCAPTCHA checkmark does nothing on IE9 Google reCAPTCHA is not working on IE9 (compatibility view is disabled). It loads correctly but the checkmark is not clickable. After some seconds, the checkmark disappears and it shows:
Please upgrade to a supported browser to get a reCAPTCHA challenge.
Alternatively if you think you are getting this page in error, please
check your internet connection and reload.
It also throws the following error:
'MessageChannel' is undefined
It looks like Google reCAPTCHA is no longer supported on IE<10 since the Channel Messaging API is not supported.
Is there any way to make it work on IE9? Has anyone been able or at least tried to port the Channel Messaging API?
Thanks!
A: Did you installed any windows security updates?
Did you change any group policy like 'Turn off Data URI support'?
If yes, then try to enable this policy or for a testing purpose try to remove that security update may solve the issue.
Also try to make a test with other browsers and check whether you have same issue with those browsers or it works correctly.
It can help us to narrow down the issue.
You can let us know about your testing results. We will try to provide you further suggestions.
Regards
Deepak
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52267544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQLAlchemy: @event.listens_for(Engine, 'handle_error') always re-raises the error I need to catch errors such as "database does not exist" or "table does not exist".
Here's what I'm trying to do:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine
class MultiTenantSQLAlchemy(SQLAlchemy): # type: ignore
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@event.listens_for(Engine, 'handle_error')
def receive_handle_error(exception_context):
print("listen for the 'handle_error' event")
print(exception_context)
db = MultiTenantSQLAlchemy(flask_app)
db.session.execute('SELECT * FROM `table_that_does_not_exit`').fetchone()
Output:
listen for the 'handle_error' event
<sqlalchemy.engine.base.ExceptionContextImpl object at 0x1140c5710>
but I still get this exception:
ProgrammingError: (MySQLdb._exceptions.ProgrammingError) (1146, "Table 'somedb.some_fake_table' doesn't exist")
How can I suppress the exception?
A: you can use try except and catch the error
from sqlalchemy import exc
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine
class MultiTenantSQLAlchemy(SQLAlchemy): # type: ignore
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@event.listens_for(Engine, 'handle_error')
def receive_handle_error(exception_context):
print("listen for the 'handle_error' event")
print(exception_context)
db = MultiTenantSQLAlchemy(flask_app)
try:
db.session.execute('SELECT * FROM `table_that_does_not_exit`').fetchone()
except exc.SQLAlchemyError:
pass # do something intelligent here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70221399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Peak at the sys.stdin before piping it to a subprocess (e.g. gzip) Data is coming in from the sys.stdin, but it could be either compressed (gzip) or uncompressed.
To solve this mystery, one could take a peek at the first 4 bytes of the stream. If they equal "\x1f\x8b\x08\x04" it's a gzip compressed file.
If the file is indeed compressed, one could decompress it with:
p = subprocess.Popen(['pigz','--stdout','--decompress' , sys.stdin], stdout=subprocess.PIPE)
However, if the first 4 bytes have already been consumed, pigz is going to reject this stream as not-a-gzip-compressed-file.
How can one read a few bytes from the sys.stdin without .read()'ing from it?
Alternatively, how can one send pigz the correct first 4 bytes and then the rest of the stream without getting into a deadlock?
EDIT2: I tried using the Peeker() class suggested in python 3: reading bytes from stdin pipe with readahead , however it results in the error:
File "./subprocess.py", line 1155, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'Peeker' object has no attribute 'fileno'
Perhaps i need to create a named pipe, write my four bytes to it, then somehow redirect the sys.stdin to that named pipe. Note that there could be many gigabytes of compressed data coming in, so it would have to be somewhat automatic as Popen(stdin=file_obj) is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43398717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get ip address of forwarded domain using java Here i have problem in getting ip address of sub-domain so can any one help me to find ip. here is my code
import java.net.InetAddress;
public class NewTest {
public static void main(String[] args) {
String address = null;
try {
InetAddress giriAddress = java.net.InetAddress.getByName("x.x.x");//ex :: mail.vinoth.com
address = giriAddress.getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Ip Address :: "+address);
}
}
A: Try this i think it will work for you.
public class AnsTest {
public static void main(String[] args) {
try {
String url = "http://mail.google.com";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23988757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Load data from NSUserDefaults in ViewDidLoad In the start screen of my app you are able to choose language between English and Swedish by clicking on either the flag of UK or Sweden.
The problem is that the ViewDidLoad does not recognize changes in the NSUserDefaults when you click a button. But when you restart the app, the language is the latest flag you clicked! So it saves the NSUserDefault but it only loads it the first time in ViewDidLoad..
When you click the English flag, sprakval sets to 0, and if you click the swedish flag, sprakval sets to 1. When you click a flag, it changes to a image with a tick icon in front of the flag.
Code:
-(IBAction) sprakEN
{
sprakval=0;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:@"Sprak "];
[sprakvalet synchronize];
[super viewDidLoad];
}
-(IBAction) sprakSE
{
sprakval=1;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:@"Sprak "];
[sprakvalet synchronize];
[super viewDidLoad];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
sprakval2 = [sprakvalet integerForKey:@"Sprak "];
if (sprakval2==0)
{
spraklabel.text = [NSString stringWithFormat:@"Language:"];
[lhb setTitle:@"english" forState:UIControlStateNormal];
[hlb setTitle:@"english" forState:UIControlStateNormal];
[fhb setTitle:@"english." forState:UIControlStateNormal];
[blandatb setTitle:@"english.." forState:UIControlStateNormal];
UIImage *encheck = [UIImage imageNamed:@"United_Kingdomchecked.png"];
[enbutton setImage:encheck forState:UIControlStateNormal];
UIImage *seuncheck = [UIImage imageNamed:@"Sweden.png"];
[sebutton setImage:seuncheck forState:UIControlStateNormal];
self.title = @"Game";
}
else if(sprakval2==1)
{
spraklabel.text = [NSString stringWithFormat:@"Språk:"];
[lhb setTitle:@"swedish" forState:UIControlStateNormal];
[hlb setTitle:@"swedish" forState:UIControlStateNormal];
[flb setTitle:@"swedish" forState:UIControlStateNormal];
[fhb setTitle:@"swedish" forState:UIControlStateNormal];
[blandatb setTitle:@"swedish" forState:UIControlStateNormal];
self.title = @"Spel";
UIImage *secheck = [UIImage imageNamed:@"Swedenchecked.png"];
[sebutton setImage:secheck forState:UIControlStateNormal];
UIImage *enuncheck = [UIImage imageNamed:@"United_Kingdom.png"];
[enbutton setImage:enuncheck forState:UIControlStateNormal];
}
// Do any additional setup after loading the view, typically from a nib.
}
A: viewDidLoad is a method invoked after view has been loaded from nib file. You are not supposed to call it manually.
If you have written the code to refresh the controls in viewDidLoad move that into a different method and invoke that method from your button event handler.
- (void)adjustControlsForLanguage
{
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
sprakval2 = [sprakvalet integerForKey:@"Sprak "];
if (sprakval2==0)
{
spraklabel.text = [NSString stringWithFormat:@"Language:"];
[lhb setTitle:@"english" forState:UIControlStateNormal];
[hlb setTitle:@"english" forState:UIControlStateNormal];
[fhb setTitle:@"english." forState:UIControlStateNormal];
[blandatb setTitle:@"english.." forState:UIControlStateNormal];
UIImage *encheck = [UIImage imageNamed:@"United_Kingdomchecked.png"];
[enbutton setImage:encheck forState:UIControlStateNormal];
UIImage *seuncheck = [UIImage imageNamed:@"Sweden.png"];
[sebutton setImage:seuncheck forState:UIControlStateNormal];
self.title = @"Game";
}
else if(sprakval2==1)
{
spraklabel.text = [NSString stringWithFormat:@"Språk:"];
[lhb setTitle:@"swedish" forState:UIControlStateNormal];
[hlb setTitle:@"swedish" forState:UIControlStateNormal];
[flb setTitle:@"swedish" forState:UIControlStateNormal];
[fhb setTitle:@"swedish" forState:UIControlStateNormal];
[blandatb setTitle:@"swedish" forState:UIControlStateNormal];
self.title = @"Spel";
UIImage *secheck = [UIImage imageNamed:@"Swedenchecked.png"];
[sebutton setImage:secheck forState:UIControlStateNormal];
UIImage *enuncheck = [UIImage imageNamed:@"United_Kingdom.png"];
[enbutton setImage:enuncheck forState:UIControlStateNormal];
}
}
viewDidLoad
- (void)viewDidLoad{
[super viewDidLoad];
[self adjustControlsForLanguage];
}
Button Event Handlers
-(IBAction) sprakEN {
sprakval=0;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:@"Sprak "];
[sprakvalet synchronize];
[self adjustControlsForLanguage];
}
-(IBAction) sprakSE {
sprakval=1;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:@"Sprak "];
[sprakvalet synchronize];
[self adjustControlsForLanguage];
}
EDIT : Since you are using tabBar based app, it's better to use the viewWillAppear to reload the language specific controls
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self adjustControlsForLanguage];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
A: This is because you are calling ViewDidload method through its super class in -(IBAction) sprakSE
and -(IBAction) sprakEN
methods. So replace
[super viewDidLoad]; with
[self viewDidLoad]; in both methods. It will work properly.
Hope it helps you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16133868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 'SELECT IN' with item list containing duplicates I'm doing
SELECT Name WHERE Id IN (3,4,5,3,7,8,9)
where in this case the '3' Id is duplicated.
The query automatically excludes the duplicated items while for me would be important to get them all.
Is there a way to do that directly in SQL?
A: The query doesn't exclude duplicates, there just isn't any duplicates to exclude. There is only one record with id 3 in the table, and that is included because there is a 3 in the in () set, but it's not included twice because the 3 exists twice in the set.
To get duplicates you would have to create a table result that has duplicates, and join the table against that. For example:
select t.Name
from someTable t
inner join (
select id = 3 union all
select 4 union all
select 5 union all
select 3 union all
select 7 union all
select 8 union all
select 9
) x on x.id = t.id
A: Try this:
SELECT Name FROM Tbl
JOIN
(
SELECT 3 Id UNION ALL
SELECT 4 Id UNION ALL
SELECT 5 Id UNION ALL
SELECT 3 Id UNION ALL
SELECT 7 Id UNION ALL
SELECT 8 Id UNION ALL
SELECT 9 Id
) Tmp
ON tbl.Id = Tmp.Id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14511398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Populate a DataGridView correctly I'm writing a winforms application, with a datagrid, using some search field to filter the content of the dataGrid.
To fill my dataGrid, I load data using a query.
The result of the query is either a DataTable, or a List<Object> created with the dataTable.
I read that to use search field, I had to populate my dataGrid like this :
liste = Echange.GetListEchange(contextExecution.ChaineConnexion, criteres);
dataGridView1.DataSource = liste;
And building the query like this :
" AND UPPER(titre) like '%" + tbSearchTitre.Text.ToUpper() + "%' AND ";
Then adding as parameter in GetListEchange.
This works.
I got columns, binding of properties on the liste .
But the thing is, I got aside, a Select column (CheckBoxColumn) binding on a property.
And when I set the property to true, then, the checkBox should check, but nothing happened.
foreach (Echange itm in liste)
{
itm.IsSelect = false;
}
It seems the dataGrid don't update.
But when I go through all the Echange in the liste, and I checked 'graphically' the checkbox, then, IsSelect is true.
So why, when I set IsSelect to true, the checkBox is not checked?
Is there a better way to fill my dataGrid, using search fields, and that update the display of the dataGrid?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22353098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MYSQL Query matching column names to rows in another table I have two tables in MYSQL, one contain a list of options a customer can pick from and the other has the cost of the options. I would like a view that returns the cost of each customers option set. For my example I'll use the analogy of buying a new car.
Customers table
customer - sunroof - mag_wheels - spoiler
--------------------------------------------------
John - true - true - false
Steve - false - true - false
Lucy - false - false - false
Options table
option - price
-----------------
sunroof - 100
mag_wheels - 150
spoiler - 75
Desired results
customer - cost
-----------------
John - 250
Steve - 150
Lucy - 0
or this would do, as I good easily multiply selected by price and then group by customer
customer - option - selected - price
------------------------------------------
John - sunroof - true - 100
John - mag_wheels - true - 150
John - spoiler - false - 75
Steve - sunroof - false - 100
Steve - mag_wheels - true - 150
Steve - spoiler - false - 75
Lucy - sunroof - false - 100
Lucy - mag_wheels - false - 150
Lucy - spoiler - false - 75
I've been puzzling over this for hours now and I can't even figure out where to start, a join seems out of the question as there are no common elements to match. I wonder if using UNION is the answer but I can't figure out how to combine row values with column headings.
If anyone could point me in the right direction I'd be ever so grateful, double points if you come up with a solution that dynamically picks up the different options so I could add more in the future without rewriting the query.
Many thanks in advance.
The reason I wanted to have all the options as a single row is I was hoping to use Access to make a form for picking the options and I couldn't figure out how a single form could create multiple rows.
A: This is a horrible data layout. You should have an association table, with one row per customer and option.
But, you can do it:
select c.customer, sum(o.cost) as cost
from customers c left outer join
options o
on (c.sunroof = true and o.option = 'sunroof' or
c.mag_wheels = true and o.option = 'mag_wheels' or
c.spoiler = true and o.option = 'spoiler'
)
group by c.customer;
EDIT:
You do not want all options in a single record. Instead, you need an association table:
create table customer_options (
customer_optionid unsigned auto_increment,
customer varchar(255) references customer(name),
option varchar(255) references option(option)
);
Actually you should really have integer primary keys for all the tables, and use them for the foreign key references. If you need data in the output in the question, then just write a query to return it in that format.
A: Looking at the table structure, even I think it will not be possible to write joins because as you mentioned, the table structure doesn't have a relation between them.
I am assume you have just started the project, so it's time you first re-visit your DB structure and correct it.
Ideally, you should have a customer table with a customer id.
Then you should have products table with product id.
One table which will have data on what products customers have purchased - something like customer_products. This will be a one to many relation. So customer 1 can have product 1,3 and 5. Which would means in customer_product there will be three entries.
And then when you want to do a sum total, you can first join the table customer, product based on customer_product and then do a sum of the price also to get the total amount for individual customer.
A: Bad design. You must a have a customers table like this:
custumer_id
customer_name
other fileds...
On the other hand you should have an accesories table, where you usually describe each item-
accesory_id
accesory_name
supplier_id
country_of_origin
other stuff
Also an accesory_price table, where prices are added due the fact that prices change.
accesory_id
price
active_price
date_price_added
An finally you should relate all in a customer_accesory table:
customer_id
accesory_id
By having this, you can join tables and select both customer basket size and customer preferences of accesories. Basket size, or the amount purchased by each customer can be summarized SUM, AVG, COUNT or you can pivot data using GROUP_CONCAT in order to generate high quality reports.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21176884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cakephp MYSQL query: SELECT where date is greater than I have to run a MYSQL select query where the query returns all values that have the beginning date 10 days after today. I have tried these two methods none of which seem to work, where do I need to make a change?
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(['month(date_from)' => 03])
->andWhere(['date_from' >= date("Y-m-d",strtotime("+10 days"))])
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(['month(date_from)' => 03])
->andWhere(['date(date_from)' >= date("Y-m-d",strtotime("+10 days"))])
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
A: Try below one
$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(
function ($exp) {
return $exp->or_([
'date_from <=' => date('Y-m-d', strtotime("+10 days")),
'date_from >=' => date('Y-m-d')
]);
})
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
A: should be
'date_from >=' => date("Y-m-d",strtotime("+10 days"))
if you can rely on mysql server date you can use NOW() inside your query
->where(function($exp, $q) {
return $exp->gte($q->func()->dateDiff([
'date_from ' => 'identifier',
$q->func()->now() ]), 10);
});
this will give you the following SQL condition
WHERE
(
DATEDIFF(date_from , NOW())
) >= 10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49443212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use subqueries in MySQL I have two tables.
Table user:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(20) NOT NULL AUTO_INCREMENT,
`ud_id` varchar(50) NOT NULL,
`name` text NOT NULL,
`password` text NOT NULL,
`email` varchar(200) NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB
and mycatch:
CREATE TABLE IF NOT EXISTS `mycatch` (
`catch_id` int(11) NOT NULL AUTO_INCREMENT,
`catch_name` text NOT NULL,
`catch_details` text NOT NULL,
`longitude` float(10,6) NOT NULL,
`latitude` float(10,6) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`image` varchar(150) NOT NULL,
`user_id` int(20) NOT NULL,
PRIMARY KEY (`catch_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user) and catch_id (from mycatch) where ud_id = given ud_id and catch_id > given catch_id.
I used the query but fail to retrieve
SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)
The error is:
#1241 - Operand should contain 1 column(s)
A: First, try not to use subqueries at all, they're very slow in MySQL.
Second, a subquery wouldn't even help here. This is a regular join (no, Mr Singh, not an inner join):
SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id
A: Select m.longitude,m.latitude from user u left join mycatch m
on u.user_id =m.user_id
where u.ud_id=$ud_id and
m.catch_id >$catch_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4569964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I don't know what to do because an error occurs --> Uncaught TypeError: Cannot read property 'getContext' of null window.onload=function() {
c=document.getElementById('gc');
cc=c.getContext('2d')
setInterval(update,1000/30);
c.addEventListener('mousemove',function(e) {
p1y=e.clientY-ph/2;
});
}
I am creating a pingpong game but as am fixing it an error occurs and I can't solve it. I have an onload but it doesn't work..
A: HTML
Add below code in HTML body
<body>
<canvas id="gc"></canvas>
</body>
JS
<script>
window.onload=function() {
c=document.getElementById('gc');
cc=c.getContext('2d')
setInterval(update,1000/30);
c.addEventListener('mousemove',function(e) {
p1y=e.clientY-ph/2;
});
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43245798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update grouped records with sequence in sql I have following structure of data in sql table
COL1 COL2 COL2 GRP_ID
A A B 100
A A B 100
A A C 101
A A B 100
A D E 102
A D E 102
F G H 103
F G H 103
i have the code same this one but it is for oracle, in sql it is not possible to define a function for next value for. How to change this code for sql?
CREATE FUNCTION NEXT
RETURN NUMBER IS
v_nextval NUMBER;
BEGIN
v_nextval := NEW_SEQUENCE.nextval;
RETURN(v_nextval);
END;
/
UPDATE EXAMPLE
SET EXAMPLE.GroupID =
(
SELECT G.GroupID FROM
(
SELECT B.Column1, B.Column2, B.Column3, MY_SCHEMA.NEXT() AS GroupID
FROM EXAMPLE B
GROUP BY B.Column1, B.Column2, B.Column3
) G
Where G.Column1 = EXAMPLE.Column1 AND G.Column2 = EXAMPLE.Column2
AND G.Column3 = EXAMPLE.Column3);
SELECT *
FROM EXAMPLE
A: The GRP_ID can be calculated using DENSE_RANK():
select col1, col2, col3,
dense_rank() over (order by col1, col2, col3) as grp_id
from t;
If you want to update the value, one method is:
update t
set grp_id = (select count(distinct col1, col2, col3) + 1
from t t2
where t2.col1 < t.col1 or
(t2.col1 = t.col1 and t2.col2 < t.col2) or
(t2.col1 = t.col1 and t2.col2 = t.col2 and t2.col3 <= t.col3)
);
Note that not all database support count(distinct) on multiple columns. In those databases, you can concatenate the values together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65167251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: flash video smoothing I have a short flv I want to play on my website. I use the below actionscript 2 code to play the video, but the anti-aliasing of text is really poor quality. I added a line to introduce "smoothing" to the video, but it appears to have no visible effect.
var my_video:Video;
var my_nc:NetConnection = new NetConnection();
my_nc.connect(null);
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);
my_ns.setBufferTime(2);
my_ns.play("thevideo.flv");
my_video.smoothing = true; //does nothing
Incidentally, I am exporting the flv video from aftereffects, and when I export the movie as a (larger) "lossless" quicktime movie, the movie looks perfect when played in quicktime, but has the same poor anti-aliasing when viewed in adobe media player, VLC, or mplayer.
Any clue on what the problem is, or if there's a better way for me to go about doing this?
A: The smoothing attribute only affects how the video is scaled - that is, whether or not the video is smoothed if you play it at double size or the like. If your Video component is scaled the same size as the source video, this attribute won't do anything.
With that said, please understand that there's no such thing as anti-aliasing going on at the player end of things. Assuming that everything is the right size (so your video isn't being scaled up to 103% or anything), what you see in the Flash player is exactly the data in the source FLV. So any aliasing you see happened when the video was encoded, not at runtime.
So assuming your sizes are right, my guess would be that you should look at the encoding end of things to solve the problem. Is your FLV of a comparable size as the lossless quicktime? If it's a lot smaller, then you're probably compressing it a lot, and increasing the quality settings might help. Likewise, what codec did you use? If you're using the newest codec (H264), the quality ought to be very similar to a quicktime movie of similar size. But the older codecs can have significantly less quality. Especially the old Sorenson Sparc codecs (the ones that require player 6/7 or better to view) are pretty sad by today's standards. And especially the Sorenson codec was heavily customized for low-bandwidths, so even if you encode with very high quality settings you tend to get big increases in file size but very little increase in quality. For these reasons it's highly recommended to make sure you're using the newest codec available for the player version you're targeting.
If none of that helps, please update with some details about what codecs and encode settings you're using.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1299811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Retain colour but change transparency in photoshop How can I retain a specific colour of an object (or layer) but change the transparency?
I have 2 objects which I want to have a specific colour but currently the opacity is 100%. I need to maintain the current colours but with a opacity of 50%.
Obviously if I change the opacity the colours change (dependent on the background). I need to know how to get an original colour at 100% opacity to make my desired colour at 50% opacity.
A: Okay so couldn't find a specific way to do it with photoshop so I worked out the math based off the RGB values and came up with a formula to do the job.
For each colour channel I used this formula:
Colour value = Desired Colour + (Background Colour - Desired Colour)*(1-1/Desired Opacity)
eg. 30 = 120 + (255-120)*(1-1/0.6)
Obvious only values between 0-255 are applicable and you may need to round values. This also needs to be done 3 times for red, green and blue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31648709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple iterations of vector with structs "cannot move out of borrowed content" I need to iterate a vector with structs in each iteration in a loop. It works fine as long as the vector doesn't contain structs. I have tried many different solutions but always get some kind of ownership problem.
What am I doing wrong?
struct Element {
title: String,
}
impl Element {
pub fn get_title(self) -> String {
self.title
}
}
fn main() {
let mut items: Vec<Element> = Vec::new();
items.push(Element {
title: "Random".to_string(),
});
items.push(Element {
title: "Gregor".to_string(),
});
let mut i = 0;
while i < 10 {
for item in &items {
println!("Loop {} item {}", i, item.get_title());
}
i = i + 1;
}
}
playground
error[E0507]: cannot move out of borrowed content
--> src/main.rs:23:44
|
23 | println!("Loop {} item {}", i, item.get_title());
| ^^^^ cannot move out of borrowed content
A: The problem is, that your get_title method consumes the Element and therefore can only be called once.
You have to accept &self as parameter instead and can do the following:
Either return a &str instead of String:
pub fn get_title(&self) -> &str {
&self.title
}
or clone the String if you really want to return a String struct.
pub fn get_title(&self) -> String {
self.title.clone()
}
Also have a look at these questions for further clarification:
*
*What are the differences between Rust's `String` and `str`?
*What types are valid for the `self` parameter of a method?
A: Here is a solution to the problem, it required borrowing self object and lifetime specifications.
Moving from &String to &str is only for following better practices, thanks @hellow Playground 2
struct Element<'a> {
title: &'a str
}
impl <'a>Element<'a> {
pub fn get_title(&self) -> &'a str {
&self.title
}
}
fn main() {
let mut items: Vec<Element> = Vec::new();
items.push(Element { title: "Random" });
items.push(Element { title: "Gregor" });
let mut i = 0;
while i < 10 {
for item in &items {
println!("Loop {} item {}", i, item.get_title());
}
i = i + 1;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55468845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ant and sqlcmd - Different Outputs I have one .sql file that is execute using ant, when I execute it with the tag I recived a different output as when i used calling "sqlcmd".
sql tag output:
[sql] Executing resource: C:\SqlTesting\TestScriptDependencies\Executor.sql
[sql] Failed to execute: Use Library Exec CallSelectSP
[sql] com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name'Libraty.dbo.libraryDocumentType'.
[sql] 0 of 1 SQL statements executed successfully
exec tag output:
[exec] First SP
[exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure getFirstDocumentType, Line 3
[exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.
[exec] Second SP
[exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure badSP, Line 3
[exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.
And this is the .sql file.
Print 'First SP'
Exec getFirstDocumentType
Print 'Second SP'
Exec badSP
Go
I wonder if it is a way of the SQL tag reproduce the same output as the EXEC tag.
Thanks.
A: Looks like the first one is submitting the whole script as a single batch via jdbc. Whereas the second appears to be sending each sql statement via sqlcmd - hence the print statements succeed (and result in synchronized output - which is not always guaranteed with print - raiserror(str, 10, 1) with nowait; is the only guarantee of timely messaging) and both sp calls are attempted, each producing their own (sql) error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13763144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: log4j.properties file disappears in the project/Classes location I'm configuring log4j in my standalone Java project. I created the property file under project/classes folder but everyday when I run the my application I get errors like
log4j:WARN No appenders could be found for logger (cafcontroller.CAFController).
log4j:WARN Please initialize the log4j system properly.
Then when I check the project/classes folder I find the log4j.properties file missing. Then I create one manually in it. I don't understand why it goes missing.
Please help me to fix this .
A: Whenever you rebuild your project, classes folder gets completely refreshed, deleting and recreating all the class files. Put your log4j.properties file inside your project/src folder. It will be copied to your classes folder on rebuild.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60924780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: List available library - SQL Linked Server AS400 I'm using SQL server 2005 (64bit version) and have successfully connect to as400 using IBM DB2 UDB for iSeries IBMDA400 OLE DB Provider.
Anyone know how to list available library/table and get the field name & description?
already looking around, and have tried this query, but still no luck
select * from OpenQuery(AS400, 'select * from QSYS.qadbxatr');
A: The information is available through the catalog views in the SYSIBM schema.
Schema (library) information is available in SQLSCHEMAS.
Table (file) information is available in SQLTABLES.
Column (field) information is available in SQLCOLUMNS.
*
*V7R1: IBM i catalog tables and views
*V5R4: ODBC and JDBC catalog views
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17562378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using sqlite how can i update or insert to a table using a condition? Having a blank table with three columns
CREATE TABLE AssyData ( AID int NOT NULL PRIMARY KEY UNIQUE , MaxDef float , MaxDefLC int , MaxDefNID int , Comps text , SubAssys text )
I would like to Update or insert new values if the new MaxMag is larger than the current one and if the AID is the same. AID is a unique Primary key. Assuming an AID of 100 I have tried the following, but with no success:
INSERT INTO AssyData
(AID , MaxDef , MaxDefLC , MaxDefNID , Comps , SubAssys)
VALUES( 100 , 101 , 202 , 203 , "" , "")
ON CONFLICT(AID)
DO UPDATE
SET
MaxDef = excluded.MaxDef ,
MaxDefNID = excluded.MaxDefNID ,
MaxDefLC = excluded.MaxDefLC ,
Comps = excluded.Comps ,
SubAssys = excluded.SubAssys
WHERE excluded.MaxDef > 100
I get the error "near "ON": syntax error"
What is wrong with my statement?
Thanks Shawn for the Approach.
A: Assuming you're using a somewhat recent (3.24 or newer) version of sqlite, you can use what's known as UPSERT:
INSERT INTO AssyData(AID, MaxMag, MaxDefNID) VALUES (?, ?, ?)
ON CONFLICT(AID) DO UPDATE SET MaxMag = excluded.MaxMag
, MaxDefNID = excluded.MaxDefNID
WHERE excluded.MaxMag > MaxMag;
A: In case your vesrsion of SQLite does not allow the use of UPSERT you can achieve what you need in 2 steps:
INSERT OR IGNORE INTO AssyData
(AID, MaxDef, MaxDefLC, MaxDefNID, Comps, SubAssys)
VALUES(100, 111, 202, 203, '', '');
This INSERT OR IGNORE will fail without an error if you try to insert a row with an AID that already exists in the table.
Then:
UPDATE AssyData
SET
MaxDef = 111,
MaxDefLC = 202,
MaxDefNID = 203,
Comps = '',
SubAssys = ''
WHERE AID = 100 AND MaxDef < 111;
This will fail if the row to be updated contains MaxDef equal or greater than the value 111.
See the demo.
In general such code needs special care when implemented, because as you can see the value of MaxDef (111 in this example) must be set 3 times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58519963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding new server to Farm not firing event receivers Experts-
We have deployed WSP (with features and feature activation event receivers) in farm environment. Event receivers creates timer jobs to perform few changes to all servers in farm.
Issue:
When new server is added to farm, WSP is getting deployed automatically(can see deployed files), but event receivers are not being fired on newly added server. Hence missing our project related configuration changes in new server.
Please suggest .
Bala
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23904697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Oracle Apex Office Print: cannot generate excel report when source query returns null value I have a query very similar to this test query:
select
'file1' as "filename",
cursor (
select
cursor (
select
cursor (
select
'Test Customer' as CUSTOMER,
'Test Country' as COUNTRY,
'Test Port' as PORT
from
dual
where
1 = 2
) as "table_without_rows",
cursor (
select
'Test Customer' as CUSTOMER,
'Test Country' as COUNTRY,
'Test Port' as PORT
from
dual
where
1 = 1
) as "table_with_rows"
from
DUAL
) as "list"
from
DUAL
) as "data"
from
DUAL
Using AOP PLSQL api I am able to generating a report but with no data in it. If all the cursors return rows it works correctly. As its not throwing any errors I am not sure what is causing this behavior.
The template structure for excel file is given below:
{#list}{#table_without_rows}..(Column names)..{/table_without_rows}
... Some text and styles ...
{#table_with_rows}..(Column names)..{/table_with_rows}{/list}
(edited)
Apex Version: 5.1.3.00.05
AOP Version: 3.0
A: which version of AOP are you using? does the error occur if you set the AOP url to apexofficeprint.com/api?
if you set the debugging to local from the AOP components settings, you should receive a JSON, if you send it to support@apexofficeprint.com we would gladly help you out with this issue.
EDIT: Bug on version 3.0, issue was fixed from version 3.1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52475159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: macOS terminal asking for password every time I run copy command I'm running a bash command on mac that moves a file to private/etc/app_name/.
sudo cp my_file.cpp private/etc/app_name/
Every time the I want to run the bash file, the OS asks for my system password.
> ./run_copy.sh
Password: *******
Is there a way to by-pass this or configure in such way that I only have to enter the password once.
A: Apparently, on my Macbook, I see /etc directory having symlinks with the /private/etc directory which is owned by the wheel group & root is part of that group. So, you would need to use sudo to copy to that directory.
With that said on a Linux machine, you can work around this by adding your group to a new file in the /etc/sudoers.d/<group-name> path.
<grp-name> ALL=(ALL) NOPASSWD:ALL
I've just tried this on my mac, I could copy files onto /private/etc directory without entering the sudo password prompt.
Unfortunately, this comes up with some risks as users of your group get privileged access without entering any password prompt. You might accidentally delete important system files etc.,
A more niche approach could be to allow selectively like <group> ALL = (ALL) NOPASSWD: /usr/local/bin/copy-script. This way, they can't run all scripts/commands with sudo privileges.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72205130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MS-DOS delete with wildcards on ends What I want is a wildcard that means "contains"
So if I have a directory with
a.txt
b.param
b.param.config
I would like to delete only b.param and b.param.config
I have tried del *.param*, del *param* ... but nothing seems to match anything for the beginning and end of the file but containing param.
I am running the command from a batch file, so if the solution is in batch that will work as well.
A: I think del *param* should work for this...
c:\test>dir /w
Volume in drive C is HP
Volume Serial Number is 0EBF-B242
Directory of c:\test
[.] [..] a.txt b.param
b.param.config
3 File(s) 29 bytes
2 Dir(s) 185,518,833,664 bytes free
c:\test>dir /w *param*
Volume in drive C is HP
Volume Serial Number is 0EBF-B242
Directory of c:\test
b.param b.param.config
2 File(s) 20 bytes
0 Dir(s) 185,518,833,664 bytes free
c:\test>del *param*
c:\test>dir /w
Volume in drive C is HP
Volume Serial Number is 0EBF-B242
Directory of c:\test
[.] [..] a.txt
1 File(s) 9 bytes
2 Dir(s) 185,518,833,664 bytes free
What happened when you tried this? What version of MS-DOS are you running?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8812969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I allow multiple users to access the same amazon instance at the same time? I am new to Amazon Cloud, and trying to create an EC2 instance that can allow multiple users to access at the same time.
While there are plenty of documentations, I haven't found an answer to my question. Whenever those documentations say "user", it refers me. But I want to have an application installed in the instance, and allow more than one of my users to access it simultaneously.
How can I achieve this? Thank you very much!
A: The same way you would add multiple users to a normal instance. I am going to assume you are using linux and can login to the instance, if not, see this post. Now you just need to add a user, and setup the ssh keys.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11121370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get substring with code from different strings I'm working on a web scraper. Among the fields it scrapes there is a Description tag like this one, different for each product:
<div class="productDescription" style="overflow: hidden; display: block;">
Black Tshirt
<br>
<br>
REF.: V23T87C88EC
<br>
<br>
COMPOSIÇÃO:
<br>
90% Poliamida
</div>
I can get the content of the description tag without problems, but I also need to get the value of REF inside the description (V23T87C88EC for this example).
The problem is this description is always different for all products, HOWEVER there is ALWAYS a "REF.: XXXXXXXXX" substring in there.
The length of the REF id can change, and it can be anywhere in the string.
What's the best way to always get the REF id?
A: Possible solution is the following:
html = """<div class="productDescription" style="overflow: hidden;
display: block;">
Black Tshirt
<br>
<br>
REF.: V23T87C88EC
<br>
<br>
COMPOSIÇÃO:
<br>
90% Poliamida
</div>"""
import re
pattern = re.compile(r'REF\.: (.+?)$')
found = pattern.findall(html)
Returns ['V23T87C88EC']
REGEX DEMO
A: You can do this with a regex (read more about regex: https://docs.python.org/3/howto/regex.html) :
html = '''
<div class="productDescription" style="overflow: hidden; display: block;">
Black Tshirt
<br>
<br>
REF.: V23T87C88EC
<br>
<br>
COMPOSIÇÃO:
<br>
90% Poliamida
</div>
'''
import re
myref = re.search (r"(?<=REF.: )\w+", html)[0]
print(myref)
# V23T87C88EC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74226485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using VBS Script in AAE and getting 1024 Expect Statement I am new to coding in VBS and all the time I am getting 1024 Expect Statement Error in my VBScript. If anyone could point me where is a mistake I would be gratefull.
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
objExcel.Visible = True
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate
Till filtering part everything goes correct. When I try to run filtering part as a Macro in Excel it works but when I am implementing it into Script it throws me an error.
A: In VBScript, you don't have to mention the name of the parameters while calling a function/method. You just need to pass the values. The parameters names are required in excel-vba, not in VBScript.
So, try replaying,
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate
with
Worksheets("PO Buy Update").Range("H3").AutoFilter 8,"<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17,"<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16,">=" & BeginDate,1,"<=" & EndDate
Reference to the Autofilter Method
Reference to the enumerated constant xlAnd
A: VBScript can't handle named parameters. Change the last lines to
Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17, "<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16, ">=" & BeginDate, xlAnd, "<=" & EndDate
and it'll hopefully get you a step closer. You might need to define xlAnd and other constants as well.
A: VBScript, as the other answers state, does not handle the named parameters.
Therefore it doesn't know what you mean by Worksheets. They will need to be fully qualified as references belonging to the parent objWorkbook object.
objWorkbook.Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
will work just fine. You will need to replace any and all excel named values (such as xlAnd) with the enumerated value equivalent, or declare them as constants and set the value to match the enumerated value if you want to use the named parameter.
A: Thanks for your answers and pointing me, my mistakes. My final solution is below
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
Set c=objWorkBook.Worksheets("PO Buy Update") // Attached WorkbookSheet(name) into variable and then specified which row, column is a header
objExcel.Visible = True
c.cells(3,8).AutoFilter 8, "<>"
c.cells(3,17).AutoFilter 17, "<>"
c.cells(3,16).AutoFilter 16, ">=" & BeginDate, 1, "<=" & EndDate
I believe my main problem was that I have header in third row and when I did not specified that Script was searching for filtering option in first row.
Once again thanks for your time !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49853650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find certain value/element in two-dimensional ArrayList I have a two dimensional arraylist
List<List<String>> movies_info = new ArrayList<>();
which I populate creating new rows
movies_info.add(new ArrayList<String>());
and adding elements
movies_info.get(i).add(title);
.
I would like to be able to check if the element I'm adding already exist in the entire ArrayList. Is it possible to achieve this result without using the following for.loop?
boolean found = false;
for (int i = 0; i < movies_info.size(); i++) {
if(movies_info.get(i).contain(title)) {
found = true;
}
if (!found) {
movies_info.add(new ArrayList<String>());
movies_info.get(i).add(title);
}
A: You can replace your second ArrayList by a HashMap and check if it is already there.
movies_info.add(new HashMap<String,String>());
if (!movies_info.get(i).containsKey(title)){
movies_info.get(i).put(title,title);
}
Both the search for a key in the HashMap and also adding a new element have constant time complexity O(1)
To get the values afterwards you can use this code
for (String title : movie_info.get(i).keySet()){
// Use title
}
A: I would suggest a different approach. Instead of creating a list of lists of String-s, you can have a class called Movie and create a list of Movie objects. Then you can directly query the list by calling the contains method.
Note: you need to override two methods in the Movie class, hashCode and equals, for the contains method to work. By overriding these two methods, you will tell the list object how to compare two Movie objects.
UPDATE: you don't have to manually write the equals and hashCode methods (at least not if you are using the Eclipse IDE). You can just right-click anywhere inside the class's body and choose Source -> Generate hashCode and equals ..., it will prompt you on which fields of the class you want to compare two objects, select the fields, hit OK and off you go, these two methods will be automatically generated for you.
Here's a simple example:
public class Movie
{
String title;
public Movie(String t)
{
this.title = t;
}
public String getTitle()
{
return title;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (title == null)
{
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
You can test it like this:
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("Movie 1"));
movies.add(new Movie("Movie 2"));
System.out.println(movies.contains(new Movie("Movie 1")));
}
}
A: Something like this? it simplifies a bit..
for(List<String> mInfo : movies_info) {
if(!mInfo.contains(title)) {
//do stuff
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35370157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to make fast big circular buffer arrays for stream recording in Haskell? I'm considering converting a C# app to Haskell as my first "real" Haskell project. However I want to make sure it's a project that makes sense. The app collects data packets from ~15 serial streams that come at around 1 kHz, loads those values into the corresponding circular buffers on my "context" object, each with ~25000 elements, and then at 60 Hz sends those arrays out to OpenGL for waveform display. (Thus it has to be stored as an array, or at least converted to an array every 16 ms). There are also about 70 fields on my context object that I only maintain the current (latest) value, not the stream waveform.
There are several aspects of this project that map well to Haskell, but the thing I worry about is the performance. If for each new datapoint in any of the streams, I'm having to clone the entire context object with 70 fields and 15 25000-element arrays, obviously there's going to be performance issues.
Would I get around this by putting everything in the IO-monad? But then that seems to somewhat defeat the purpose of using Haskell, right? Also all my code in C# is event-driven; is there an idiom for that in Haskell? It seems like adding a listener creates a "side effect" and I'm not sure how exactly that would be done.
A: Look at this link, under the section "The ST monad":
http://book.realworldhaskell.org/read/advanced-library-design-building-a-bloom-filter.html
Back in the section called “Modifying array elements”, we mentioned
that modifying an immutable array is prohibitively expensive, as it
requires copying the entire array. Using a UArray does not change
this, so what can we do to reduce the cost to bearable levels?
In an imperative language, we would simply modify the elements of the
array in place; this will be our approach in Haskell, too.
Haskell provides a special monad, named ST, which lets us work
safely with mutable state. Compared to the State monad, it has some
powerful added capabilities.
We can thaw an immutable array to give a mutable array; modify the
mutable array in place; and freeze a new immutable array when we are
done.
...
The IO monad also provides these capabilities. The major difference between the two is that the ST monad is intentionally designed so that we can escape from it back into pure Haskell code.
So should be possible to modify in-place, and it won't defeat the purpose of using Haskell after all.
A: Yes, you would probably want to use the IO monad for mutable data. I don't believe the ST monad is a good fit for this problem space because the data updates are interleaved with actual IO actions (reading input streams). As you would need to perform the IO within ST by using unsafeIOToST, I find it preferable to just use IO directly. The other approach with ST is to continually thaw and freeze an array; this is messy because you need to guarantee that old copies of the data are never used.
Although evidence shows that a pure solution (in the form of Data.Sequence.Seq) is often faster than using mutable data, given your requirement that data be pushed out to OpenGL, you'll possible get better performance from working with the array directly. I would use the functions from Data.Vector.Storable.Mutable (from the vector package), as then you have access to the ForeignPtr for export.
You can look at arrows (Yampa) for one very common approach to event-driven code. Another area is Functional Reactivity (FRP). There are starting to be some reasonably mature libraries in this domain, such as Netwire or reactive-banana. I don't know if they'd provide adequate performance for your requirements though; I've mostly used them for gui-type programming.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9072964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: FileNotFoundException when calling C# dll from C++/CLI I have a C# dll, with some methods, which I am trying to access in my native project with /CLR support.
I reference this DLL using a #using directive, and the DLL is recognized and the project compiles.
However, during runtime, I get a FileNotFoundException, which is pretty weird since the DLL is present in the source directory of the project.
TheDLL is compiled inVS 2015 with .NET Version 4.5.2. Since I have CLR support on my C++ mixed, I have edited the project file to make TargetFrameworkVersion as 4.5.2, but still the runtime does not work.
Kindly advise on what could be the issue?
EIDT - ADDED SOME CODE
C#
namespace TestManagedLibrary
{
public class Class1
{
public int i;
public Class1()
{
i = 5;
}
public int returnValue()
{
return i;
}
}
}
C++/CLI
#using <TestManagedLibrary.dll>
using namespace System;
using namespace System::Runtime::InteropServices; // Marshal
using namespace TestManagedLibrary;
ref class ManagedFoo
{
public:
ManagedFoo()
{
Console::WriteLine(_T("Constructing ManagedFoo"));
Class1 ^testObject = gcnew Class1();
int a = testObject->returnValue();
}
};
A: First of all you need to ensure that the TestManagedLibrary.dll file is located in a place where Fusion could find it. Your first try should be the location of the executable you are running.
One way to handle this is via the reference properties. If the reference to your TestManagedLibrary.dll is set with the copy local flag than during the build the referenced library is going to be copied from the referenced location to the output directory.
You can enable the internal fusion logging to find out the details:
*
*Run Developer Command Prompt with administrative privileges.
*Run fuslogvw
*In the Assembly Binding Log Viewer hit settings and set either Log bind failures to disk or Log all binds to disk.
*Start your service
*Hit Refresh in the Assembly Binding Log Viewer, pick your executable and hit View Log
A: The compiled DLL should have been in the same location as the executable for the CLR to search for it. In my case, the .NET compiled DLL was in the solution folder and not searchable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39230290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting Index of an Object from NSArray? i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,
NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(@" %d",Aindex);
the value i get is something like 2323421. what am i possibly doing wrong??
A: NSNumber *num1 = [NSNumber numberWithInt:56];
NSNumber *num2 = [NSNumber numberWithInt:57];
NSNumber *num3 = [NSNumber numberWithInt:58];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
NSNumber *num=[NSNumber numberWithInteger:58];
NSInteger Aindex=[myArray indexOfObject:num];
NSLog(@" %d",Aindex);
Its giving the correct output, may be u have done something wrong with storing objects in ur array.
A: Try this:
NSArray's indexOfObject: method. Such as the following:
NSUInteger fooIndex = [someArray indexOfObject: someObject];
A: Folks,
When an object is not found in the array the indexOfObject method does NOT return a 'garbage' value. Many systems return an index of -1 if the item is not found.
However, on IOS - because the indexOfObject returns an UNSIGNED int (aka NSUInteger) the returned index must be greater than or equal to zero. Since 'zero' is a valid index there is no way to indicate to the caller that the object was not found -- except by returning an agreed upon constant value that we all can test upon. This constant agreed upon value is called NSNotFound.
The method:
- (NSUInteger)indexOfObject:(id)anObject;
will return NSNotFound if the object was not in the array. NSNotFound is a very large POSITIVE integer (usually 1 minus the maximum int on the platform).
A: The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :
NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
NSLog(@"not found");
}
or log the content of the array to be sure :
NSLog(@"%@", myArray);
A: If you're using Swift and optionals make sure they are unwrapped. You cannot search the index of objects that are optionals.
A: I just checked. Its working fine for me. Check if your array has the particular number. It will return such garbage values if element is not present.
A: indexOfObject methord will get the index of the corresponding string in that array if the string is like @"Test" and you find like @"TEST" Now this will retun an index like a long number
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7398141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
} |
Q: MKMapView zoom User Location and Annotation I want my MKMapView to zoom 'User Location' and the Annotation as close as possible.
The map already show both, but is zoomed out to the whole country.
How can I do that?
And I don’t know why the Annotation and Pin are not animated.
My Code:
//Coords User
CLLocationCoordinate2D user_location;
user_location.latitude = mapView.userLocation.location.coordinate.latitude;
user_location.longitude = mapView.userLocation.location.coordinate.longitude;
//Coords Annotation
CLLocationCoordinate2D club_location;
club_location.latitude = [self.clubInfo.latitude doubleValue];
club_location.longitude = [self.clubInfo.longitude doubleValue];
MKMapPoint userPoint = MKMapPointForCoordinate(user_location);
MKMapPoint annotationPoint = MKMapPointForCoordinate(club_location);
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];
// Add an annotation
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = club_location;
annotation.title = self.clubInfo.clubName;
annotation.subtitle = @"Pin!";
[mapView addAnnotation:annotation]; // This was missing
[mapView selectAnnotation:annotation animated:YES];
Logs:
userRect: {{134217728.0, 134217728.0}, {0.0, 0.0}}
annotationRect: {{99775488.0, 152579328.0}, {0.0, 0.0}}
unionRect: {{99775488.0, 134217728.0}, {34442240.0, 18361600.0}}
mapView.visibleMapRect: {{96025087.6, 116070015.1}, {41943040.7, 54657025.8}}
A: If I understand well, you want those two annotations to be visible with maximum possible zoom. I found this solution that does not reqire any calculations.
// You have coordinates
CLLocationCoordinate2D user = ...;
CLLocationCoordinate2D annotation = ...;
// Make map points
MKMapPoint userPoint = MKMapPointForCoordinate(user);
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation);
// Make map rects with 0 size
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
// Make union of those two rects
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
// You have the smallest possible rect containing both locations
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];
CoreLocation and MapKit structures are hell.
A: For anyone coming here later: The shortest way of doing this is (iOS7+) this:
Assuming you have a @property MKMapView *mapView, and an MKPointAnnotation *theAnnotation, call:
[self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];
Now this could cause some problems if called too early (i.e. when self.mapView.userLocation is not yet set). If so, you can call in viewWillAppear:
[self.mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL];
Then, implement:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"location"]) {
[self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];
}
}
That way you're sure it's set. Don't forget to remove the observer at viewWillDisappear:
[self.mapView.userLocation removeObserver:self forKeyPath:@"location"];
A: Use these 4 classes - it works like a charm!
//MapViewController.h file
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController <CLLocationManagerDelegate> {
IBOutlet UIButton *buttonBack;
IBOutlet MKMapView *mapView;
IBOutlet UILabel *labelTitle;
NSString *lon,*lat,*nickName;
BOOL isFirstLaunch;
}
@property(nonatomic,retain) NSString *lon,*lat,*nickName;
@property(nonatomic,retain) IBOutlet UIButton *buttonBack;
@property(nonatomic,retain) IBOutlet UILabel *labelTitle;
@property(nonatomic,retain) IBOutlet MKMapView *mapView;
-(IBAction)buttonBackAction:(UIButton *)_btn;
-(void)zoomToFitMapAnnotations;
@end
//
// MapViewController.m
//
#import "MapViewController.h"
#import "Annotation.h"
@implementation MapViewController
@synthesize buttonBack,mapView,labelTitle;
@synthesize lon,lat,nickName;
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
-(IBAction)buttonBackAction:(UIButton *)_btn{
[self.navigationController popViewControllerAnimated:1];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
CLLocationManager* locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
NSLog(@"MapViewController");
labelTitle.text = @"anscacorona.blogspot.in"
CLLocationCoordinate2D location;
location.latitude = [self.lat floatValue];
location.longitude = [self.lon floatValue];
Annotation *annotation = [[Annotation alloc] init];
annotation.theCoordinate = location;
annotation.theTitle = [NSString stringWithFormat:@"%@",labelTitle.text];
[mapView addAnnotation:annotation];
[annotation release];
mapView.showsUserLocation = 1;
[self zoomToFitMapAnnotations];
[super viewDidLoad];
}
// Shows the location of both users. called when the device location changes to move the map accordinly. necessary ONLY once when the window is opened. afterwards the user can move the map as he choises.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (isFirstLaunch) {
CLLocationCoordinate2D topLeftCoord;
CLLocationCoordinate2D bottomRightCoord;
topLeftCoord.longitude = fmin([self.lon floatValue], newLocation.coordinate.longitude);
topLeftCoord.latitude = fmax([self.lat floatValue], newLocation.coordinate.latitude);
bottomRightCoord.longitude = fmax([self.lon floatValue], newLocation.coordinate.longitude);
bottomRightCoord.latitude = fmin([self.lat floatValue], newLocation.coordinate.latitude);
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5; // Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
isFirstLaunch = NO;
}
}
-(void)zoomToFitMapAnnotations
{
if([mapView.annotations count] == 0)
return;
CLLocationCoordinate2D topLeftCoord;
CLLocationCoordinate2D bottomRightCoord;
topLeftCoord.longitude = fmin(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
topLeftCoord.latitude = fmax(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);
bottomRightCoord.longitude = fmax(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
bottomRightCoord.latitude = fmin(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
CLLocationCoordinate2D userCoord = {[self.lat floatValue],[self.lon floatValue]};
region.center = userCoord;
region.span.latitudeDelta = 0.05f;//fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = 0.05f;//fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
[mapView setRegion:region animated:YES];
[mapView regionThatFits:region];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
#pragma mark - View Lifecycle
-(void)viewWillAppear:(BOOL)animated{
isFirstLaunch=YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
//anotation classes- Annotation.h
#import <MapKit/MapKit.h>
@interface Annotation : NSObject <MKAnnotation>{
CLLocationCoordinate2D theCoordinate;
NSString *theTitle;
NSString *restId;
NSString *theSubtitle;
}
@property(nonatomic,retain) NSString *restId;
@property(nonatomic,retain) NSString *theTitle;
@property(nonatomic,retain) NSString *theSubtitle;
@property CLLocationCoordinate2D theCoordinate;
@end
//Annotation.m
#import "Annotation.h"
@implementation Annotation
@synthesize theCoordinate,theTitle,theSubtitle,restId;
- (CLLocationCoordinate2D)coordinate;
{
return theCoordinate;
}
// required if you set the MKPinAnnotationView's "canShowCallout" property to YES
- (NSString *)title
{
return theTitle;
}
// optional
- (NSString *)subtitle
{
return theSubtitle;
}
- (void)dealloc
{
[super dealloc];
}
@end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14760582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Datadog: How to automate configuring Log Archives How can I automate configuring Log Archives on GCP?
I can do it manually by following steps
https://docs.datadoghq.com/logs/archives/?tab=googlecloudstorage
I guess selenium can help this
but I looking for a more programmatic way like Terraform or REST API
Thank you.
A: I’m not sure if it is a recent addition, but the Datadog public API supports configuring Log Archives: https://docs.datadoghq.com/api/latest/logs-archives/
You can also use tools like Terraform to configure them: https://registry.terraform.io/providers/DataDog/datadog/latest/docs/resources/logs_archive (it uses the Datadog API internally)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61092487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JComboBox - out of bounds exception i have a small problem. I'm trying to import logins from my database to a vector and then to use that vector for JComboBox. My method for downloading logins :
public void loginReader (Vector<String> loginy, String tableName)
{
String query = "select login from " + tableName;
try {
Statement statement = mConnection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
Vector<String> vstring = new Vector<String>();
vstring.add(rs.getString("login"));
loginy.addAll(vstring);
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
That's in class DatabaseManagement. I made another class (GUI) and there's that JComboBox. Why it doesn't work ?
package DataBase_Hospital;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Properties;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Message extends JFrame implements ActionListener {
JButton SEND_MESSAGE;
JButton READ_MESSAGE;
public JLabel background;
JLabel NAME_LABEL;
JTextField NAME_FIELD;
JTextArea DATABASE_FIELD;
static Vector<String> loginy = new Vector<String>();
private static DatabaseManagement DATABASE;
public Message() {
setSize(290, 500);
setTitle("Message Panel");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JLabel background=new JLabel(new ImageIcon("/Users/Dominik/Desktop/messageFrame.png"));
add(background);
DATABASE_FIELD = new JTextArea(3,3);
JScrollPane scrollPane = new JScrollPane(DATABASE_FIELD);
scrollPane.setBounds(45, 50, 200, 200);
background.add(scrollPane);
DATABASE_FIELD.setEditable(true);
NAME_LABEL = new JLabel("Odbiorca :");
NAME_LABEL.setBounds(40, 380, 140, 20);
background.add(NAME_LABEL);
SEND_MESSAGE = new JButton();
SEND_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/sendMail.jpg"));
SEND_MESSAGE.setBounds(75, 270, 60, 60);
background.add(SEND_MESSAGE);
SEND_MESSAGE.addActionListener(this);
SEND_MESSAGE.setToolTipText("Send message");
READ_MESSAGE = new JButton();
READ_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/jwj.png"));
READ_MESSAGE.setBounds(150, 270, 60, 60);
background.add(READ_MESSAGE);
READ_MESSAGE.addActionListener(this);
READ_MESSAGE.setToolTipText("Read message");
JComboBox loginList = new JComboBox(loginy);
loginList.setSelectedIndex(loginy.capacity());
loginList.addActionListener(this);
loginList.setBounds(145, 380, 100, 20);
background.add(loginList);
}
public static void main(String[] args) {
Message window = new Message();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
DATABASE.loginReader(loginy,"uzytkownicy");
}
public void actionPerformed(ActionEvent e)
{
Object EVENT_SOURCE = e.getSource();
DATABASE = new DatabaseManagement("pacjent");
if (EVENT_SOURCE == SEND_MESSAGE)
{
DATABASE.sendMessage(DATABASE_FIELD.getText(), "uzytkownicy", NAME_FIELD.getText()) ;
}
}
}
A: After creating your JComboBox with your empty Vector, you set the selectedIndex to loginy.capacity (). The problem is that while the capacity of your Vector is 10 (as stated in the JavaDoc for the default constructor), it's actual size is 0. Hence the ArrayOutOfBoundsException. You should check for the size of your Vector before setting the selected index of your JComboBox.
A: I suspect the problem is you are trying to set the selected index of your combo box to the capacity of your vector.
loginList.setSelectedIndex(loginy.capacity());
From the docs .capacity():
Returns the current capacity of this vector.
Returns:
the current capacity (the length of its internal data array, kept in the field elementData of this vector)
This is not the size i.e. the number of logins in your database. this is the capacity of internal datastructure which will always be >= the number of elements in the vector.
Try using Vector#size() but you will still need to subtract one (provided there is actually data in the vector) from this so your code should be:
loginList.setSelectedIndex(loginy.size() - 1);
And this will set the last login in the comboBox. Which is not required in your case as you are populating the vector after creating the combobox so you could just remove this line from your code until you populate the vector.
Edit as per comments
All you should need to do to have the logins is reorder the execution order. I.e populate your vector then create your combo box, Change your main method to something like this:
public static void main(String[] args) {
//First initialise your database (dont do this in the action performed method)
// you should only need one and not need to create a new one on each action
DATABASE = new DatabaseManagement("pacjent");
// Read logins (I assume this is the method that does it)
DATABASE.loginReader(loginy,"uzytkownicy");
// Then create your message window...
Message window = new Message();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21243973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: problems with cookies i'm using restful-authentication plugin with rails 2.3.8
i've problems with cookies store
i've put a logger instruction in this function for check the cookie:
def send_remember_cookie!
cookies[:auth_token] = {
:value => @current_user.remember_token,
:expires => @current_user.remember_token_expires_at }
logger.error "--------------#{cookies[:auth_token].keys}"
end
But when i launch the program i receive this error:
undefined method `keys' for nil:NilClass
why?
How can i set the cookie?
thanks
A: The cookies object is an instance ApplicationController::CookieJar. It's almost like a Hash but the behavior of the [] and []= methods are not symmetric. The setter sets the cookie value for sending to the browser. The getter retrieves the value which comes back form the browser. Hence when you access it in your code having just set the outgoing value the incoming value will be unset. There some more info on this here
Also did you intentionally mean to say cookie[:auth_token].keys or did you mean cookie.keys?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3176340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Column not found: 1054 Field Field 'email' unknown in where I have 3 rubrics for now.
When, I login in the rubric Studentwith the email test.gmail.com I can see my informations private
Then, I LOGIN in the rubric Feedback always with the email test.gmail.com I have like error message:
SQLSTATE [42S22]: Column not found: 1054 Field Field 'email' unknown in where (SQL: select count (*) as aggregate fromreturnswhere email= test@gmail.com)
my fields on the table Feedbacks are:
protected $fillable = ['user_id','instruction', 'description', 'fk_eleve'];
My function index() is the following:
public function index(Request $request)
{
$user = $request->user();
$feedbacks = Feedback::query()
->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
$query->where('email', $user->email);
})
->when($request->has('search'), function (Builder $query) use ($request) {
$query->join('eleves', 'feedbacks.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->where('eleves.nom','like','%'.$request->input('search').'%');
})
->paginate(5);
return view('admin.feedbacks.index', compact('feedbacks'))
->with('display_search', $user->hasRole('admin'));
}
Thank you for your help.
A: You most likely need to add the email column to your fillable array:
protected $fillable = ['user_id','instruction', 'description', 'fk_eleve', 'email'];
Did you further create a proper migration for this, like does the table have the column email?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57581930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to use this. $ axios with Vuex constants What I want to come true
I use this.$axios many times, so I tried to put it in a constant, but it doesn't work.
I read the official docs but didn't understand.
Is it because this isn't available in the Nuxt.js lifecycle?
Code
url.js
export const AXIOS_POST = this.$axios.$post
export const POST_API = '/api/v1/'
export const POST_ITEMS_API = '/api/v1/post_items/'
Vuex
import * as api from './constants/url.js' // url.js in this.
export const state = () => ({
list: [],
hidden: false
})
export const mutations = {
add (state, response) {
state.list.push({
content: response.content,
status: response.status
})
},
remove (state, todo) {
state.list.splice(state.list.indexOf(todo), 1)
},
edit (state, { todo, text }) {
state.list.splice(state.list.indexOf(todo), 1, { text })
},
toggle (state, todo) {
todo.status = !todo.status
},
cancel (state, todo) {
todo.status = false
},
// アクション登録パネルフラグ
switching (state) {
state.hidden = !state.hidden
}
}
export const actions = {
post ({ commit }, text) {
//I want to use it here
this.$axios.$post(api.POST_ITEMS_API + 'posts', {
post_items: {
content: text,
status: false
}
})
.then((response) => {
commit('add', response)
})
}
}
Error
Uncaught TypeError: Cannot read property '$axios' of undefined
A: Since your file is located into a constants directory, you should probably use some .env file.
Here is a guide on how to achieve this in Nuxt: https://stackoverflow.com/a/67705541/8816585
If you really want to have access to it into a non .vue file, you can import it as usual with something like this
/constants/url.js
import store from '~/store/index'
export const test = () => {
// the line below depends of your store of course
return store.modules['@me'].state.email
}
PS: getters, dispatch and everything alike is available here.
Then call it in a page or .vue component like this
<script>
import { test } from '~/constants/url'
export default {
mounted() {
console.log('call the store here', test())
},
}
</script>
As for the lifecyle question, since the url.js file is not in a .vue file but a regular JS one, it has no idea about any Vue/Nuxt lifecycles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68705708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to upload an image to aws s3 bucket and get the saved url in Android studio using java I need to upload the image to the AWS s3 bucket in android. I implemented that the user has taken a photo from the gallery after having the image path I need to save that in a bucket and get the url from bucket in android.
I HAVE access key and secret key and bucket name. I am not clear how to implement this in android. Please help me out.
// This is the code of taking an image from the gallary
private void selectImage() {
final CharSequence[] options = {"Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Upload Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@SuppressLint("LongLogTag")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = this.getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
thumbnail = getResizedBitmap(thumbnail, 400);
Log.w("path of image from gallery......******************.........", picturePath + "");
imageView.setImageBitmap(thumbnail);
BitMapToString(thumbnail);
}
}
}
private void BitMapToString(Bitmap userImage1) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
userImage1.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Document_img1 = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(Document_img1 + "........IMAGE");
}
private Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
A: Please check out the Storage category in the AWS Amplify library.
There's some setup/configuration to do (as noted in that guide), but the actual upload will look like this:
Amplify.Storage.uploadFile(
"remoteS3Key",
localFile,
result -> Log.i("Demo", "Successfully uploaded: " + result.getKey()),
failure -> Log.e("Demo", "Upload failed", failure)
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62833395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configuring ASP.NET MVC app's IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 I am trying to use IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 so that my ASP.NET web app can connect to the database...
Using this approach worked fine on my local dev machine (IIS 7.5 and SQL Server 2008 R2 on same machine).
However, when I try to set up the same on production (IIS and SQL servers are separate) I am unable to add "IIS APPPOOL\MyAppAppPool" login to SQL Server 2008 R2.
Notice that in either case you cannot use "Browse..." when creating a login in SQL Server since "IIS APPPOOL\MyAppAppPool" user identity is dynamic (or "special")...
Any ideas?
Update:
For more info on Application Pool Identities see here.
From article:
Whenever a new Application Pool is
created, the IIS management process
creates a security identifier (SID)
that represents the name of the
Application Pool itself. For example,
if you create an Application Pool with
the name "MyNewAppPool," a security
identifier with the name
"MyNewAppPool" is created in the
Windows Security system. From this
point on, resources can be secured by
using this identity. However, the
identity is not a real user account;
it will not show up as a user in the
Windows User Management Console.
A: That articles states (under "Accessing the Network") you still use the <domainname>\<machinename>$ aka machine account in the domain.
So if both servers are in "foobar" domain, and the web box is "bicycle", the login used to the SQL Server Instance is foobar\bicycle$
If you aren't in a domain, then there is no common directory to authenticate against. Use a SQL login with username and password for simplicity
Edit, after comment
If the domains are trusted then you can use the machien account still (use domain local groups for SQL Server, into which add a global groups etc)
As for using app pool identities, they are local to your web server only as per article. They have no meaning to SQL Server. If you need to differentiate sites, then use proper domain accounts for the App Pools.
You can't have it both ways...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4463528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Django include template tag alternative in python class I know there is a Django template tag that allows to include other templates like so:
{% include 'template.html' %}
I am wondering if I could do the same, but in a separate python class (not in the HTML template)?
I know that for example the url tag has an equivalent, like so:
{% url 'some_url_name' %} -> reverse('some_url_name')
A: I think you might be looking for render_to_string.
from django.template.loader import render_to_string
context = {'foo': 'bar'}
rendered_template = render_to_string('template.html', context)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30853775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to clear a window in PySimpleGUI I am using PySimpleGUI to build a GUI. How do you clear all the widgets on the window? In tkinter you have the code:
widget.destroy()
If you attempt this in PySimpleGUI you get the error:
NameError: name 'RWG' is not defined
if my widget is called RWG. I tried making RWG a global variable but I got the same error. Can I have some help?
My code that gets the error:
def oof():
RWG.destroy()
import PySimpleGUI as sg
sg.theme("DarkAmber")
layout = [[sg.Text("Don't Even Try!!!")],
[sg.Button("RWG")]]
window = sg.Window("Don't Even Try It", layout).Finalize()
window.Maximize()
while True:
event, values = window.read()
if event == "RWG":
oof()
I would appreciate any help
A: You can clear elements with:
window.FindElement(key).Update('')
Have you tried this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61306986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 4: From which step in the boot process can I check the ActiveRecord::Base class? I would like to perform some checking on the database resources only when the app starts/restarts (if any new migrations happen in between) by calling:
resources = ActiveRecord::Base.send(:subclasses).map { |subclass| subclass.name }
I tried inserting this code at different steps of the initialization process without any success (getting an empty array as a result). Why? And where should I insert it?
If I perform this checking in the ApplicationController , it will be always be executed. I only need to run it once after boot.
Where can I insert it?
A: Compiling the gist of answers other people have given before:
In the development environment your model classes will not be eager loaded.
Only when you invoke some code that references a model class, the corresponding file will be loaded. (Read up on 'autoloading' for further detail.)
So if you need to do some checks upon startup of the rails server, you can manually invoke
Rails.application.eager_load!
and after that get a list of all model classes with
model_classes = ActiveRecord::Base.descendants
For a list of model names associated with their database tables, you might use
model_classes.map{ |clazz| [clazz.model_name.human, clazz.table_name] }.sort
You can put your code in an arbitrarily named file in the config/initializers directory. All ruby files in that directory will get loaded at startup in alphabethical order.
The eager loading will of course take some time and thus slow down server and console start-up in the development environment a bit.
Other approaches such as parsing a list of filenames in the app/models directory are not reliable in more complex Rails applications.
If in a Rake task, make sure your Application is properly initialized before you send eager_load!. To that end, let your rake task depend on :environment.
HTH!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33154848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HTTPHandler for all files in directory I have created an HTTPHandler to handle all files within a certain folder ("Files"). When i run it locally from Visual Studio it works fine. However when i deploy it on the server (IIS 7, Classic Mode), the handler is not firing for files of types such as pdf, jpg, gif...etc (although requests for files with extensions .aspx, .axd...etc do work).
How exactly should i configure web.config to handle these files as well. I placed a web.config file inside the Files folder with the following:
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
</httpHandlers>
</system.web>
</configuration>
Please help...
A: add one more element in your HTTPHandler tag for specific file type for example
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
<add path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" verb="*" type="NameofYourHandler" />
</httpHandlers>
</system.web>
</configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11518443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Integrating Angular 4 into ASP.NET Core MVC app - how to mix routing I'm trying to integrate my Angular 4 app into asp.net mvc core project. And I'd like to have Angular app available within my Core MVC project with this Url - mydomain.com/ngx.
Here's how I do it now (and it doesn't work):
I build Angular app with angular-cli and use ng build ... --base-href /ngx (notice the slash). Then I copy everything from dist folder (where the build is placed by CLI) and copy it into wwwroot/ngx folder into my Core MVC project. But when I open localhost/ngx/index.html I get 404 errors for main.bundle.js and other js files. I checked the requests and for some reason it tries to get it as localhost://main.bundle.js - why from root?
now, if I build it with --base-href ngx (no slash) and open the site, it gets redirected to /ngx/ngx (doubles the ngx). so... wtf? :)
Core MVC routing doesn't have anything special, I haven't touched that part.
So how can I make it work as localhost/ngx ASP.NET Core MVC project?
A: Works fine here with
ng build --base-href /ngx/ --output-path dist/ngx,
running http-server from the dist directory, and going to http://localhost:8080/ngx/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43452637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: typing effect in Arabic language appear disconnected So I used this tutorial to make a typing effect and it appears great in English, I tried
to use Arabic text (which is a connected letter language) and it appears good on my device.
when I sent the app prototype for the client to test it, the Arabic language letters appear disconnected in his device! so weird as I couldn't debug it because it does not happen on my laptop and mobile phone!
I found this library which has a test demo at the bottom of the page, I asked him to test Arabic words on it, it appears like this on his device (iPhone xs max, chrome browser):
but it appears like this on my device (Linux, chrome browser):
any idea why this happens and how to solve it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64733049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to safely create a file if it doesn't exist from concurrently-running processes without using locking? Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs. We want to protect ourselves against the possibility of multiple writer processes clobbering each other and/or reader processes reading an incomplete or inconsistent version of the file.
What we're currently doing to arbitrate this situation is to use Java NIO FileLocks. One process manages to acquire an exclusive lock on the file to be created using FileChannel.tryLock() and creates it, while the other concurrently-running processes fail to acquire a lock and fall back to using an in-memory version of the file for their runs.
Locking is causing various problems for us on our compute farm, however, so we're exploring alternatives. So my question to you is: is there a way to do this safely without using file locks?
Could, eg., the processes write to independent temporary files when they find a file doesn't exist, and then more or less "atomically" move the temp file(s) into place after they've been written? In this scenario, we might end up with multiple writer processes, but that would be ok provided that any processes reading from the file always read one version or another, and not a mix of two or more versions. However, I don't think all operating systems guarantee that if you have a file open for reading, you'll continue reading from the original version of the file even if it's overwritten mid-way through the read.
Any suggestions would be much appreciated!
A:
Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs.
I don't quite understand the create and read part of the question. If you are looking to make sure that you have a unique file then you could use new File(...).createNewFile() and check to make sure that it returns true. To quote from the Javadocs:
Atomically creates a new, empty file named by this abstract pathname if
and only if a file with this name does not yet exist. The check for the
existence of the file and the creation of the file if it does not exist
are a single operation that is atomic with respect to all other
filesystem activities that might affect the file.
This would give you a unique file that only that process (or thread) would then "own". I'm not sure how you were planning on letting the writer know which file to write to however.
If you are talking about creating a unique file that you write do and then moved into a write directory to be consumed then the above should work. You would need to create a unique name in the write directory once you were done as well.
You could use something like the following:
private File getUniqueFile(File dir, String prefix) {
long suffix = System.currentTimeMillis();
while (true) {
File file = new File(dir, prefix + suffix);
// try creating this file, if true then it is unique
if (file.createNewFile()) {
return file;
}
// someone already has that suffix so ++ and try again
suffix++;
}
}
As an alternative, you could also create a unique filename using UUID.randomUUID() or something to generate a unique name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16046073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Wrong file input I have to enter string x in reverse order, but it outputs null. Why and how to fix it?
Sorry in advance for the name of the variables, but also for the double loop (I know it's bad, but this is the only thing that came to my mind)
The main question is why null is entered in the file
public static void OutputOfFile(char[] x)throws IOException {
File file = new File("test");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for(int i = x1.length - 1; i < -1; i--) {
for (int k = 0; k > x1.length; k++) {
x2[i] = x1[k];
}
}
OutputOfFile(x2);
}
A: the problem is with your loop, you need to iterate in one loop instead of an inner loop:
public static void OutputOfFile(char[] x) throws IOException {
File file = new File(""test"");
PrintWriter out = new PrintWriter(file.getAbsoluteFile());
out.print(x);
out.close();
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String x = reader.readLine();
char[] x1 = x.toCharArray();
char[] x2 = new char[x1.length];
for (int i = x1.length - 1, k = 0; i >= 0; i--, k++) {
x2[k] = x1[i];
}
OutputOfFile(x2);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64821466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pymssql (python module) losing item when fetching data I have a database named "sina2013",and the columus is Title,Content
Now I want to use pymssql module to get the data.At the same time ,using the Title as the filename of a txt file,the Content as the content of the txt file.
The strange thing is the number of files is less than the items in database.
where is the error?
the code i have tried is:
import pymssql
conn = pymssql.connect(...)
cur = conn.cursor()
cur.execute('SELECT Title,Content FROM sina2013')
count=len(cur.fetchall()) #Will return the right number :5913
for Title,Content in cur:
filename=file(str(Title)+r'.txt',r'w')
filename.write(Content )
filename.close()
cur.close()
The number of txt file is less than it should be.
what is the reason?
A: Perhaps changing your for loop into this:
# cursor fetchall() method returns all rows from a query
for Title,Content in cur.fetchall():
... will fix the issue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17529670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get arrayMaxConsecutiveSum from CodeSignal more efficient? I am working through some problems on CodeSignal. I came across this one, arrayMaxConsecutiveSum. I got it to pass almost all tests, but it is timing out on the last one. If I move the test into custom tests, it passes there, so I'm not sure what to do. How do I code it better so that it doesn't time out?
Problem:
Given array of integers, find the maximal possible sum of some of its k consecutive elements.
Example: For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be
arrayMaxConsecutiveSum(inputArray, k) = 8. All possible sums of 2 consecutive elements are:
2 + 3 = 5;
3 + 5 = 8;
5 + 1 = 6;
1 + 6 = 7.
Thus, the answer is 8.
function arrayMaxConsecutiveSum(inputArray, k) {
let max = 0;
for(let i = 0; i < inputArray.length; i++){
let sum = 0;
let newArr = inputArray.slice(i, i + k);
sum = newArr.reduce((accumulator, currentVal) => accumulator + currentVal);
if(sum > max){
max = sum;
}
}
return max;
}
Error: Tests passed: 19/20. Execution time limit exceeded on test 20: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.
A: Your current algorithm is O(n ^ 2) because it requires a nested loop.
You can make it O(n) by using a rolling sum instead. Start with the sum of elements 0 to k, then on each iteration, subtract the earliest element that makes up the sum and add the next element not included in the sum yet.
For example, with a k of 2:
*
*start out with the sum of elements [0] and [1]
*subtract [0], add [2], compare the new sum
*subtract [1], add [3], compare the new sum
and so on.
function arrayMaxConsecutiveSum(inputArray, k) {
let rollingSum = inputArray.slice(0, k).reduce((a, b) => a + b);
let max = rollingSum;
for(let i = 0; i < inputArray.length - k; i++){
rollingSum += inputArray[i + k] - inputArray[i];
max = Math.max(max, rollingSum);
}
return max;
}
console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));
A:
function arrayMaxConsecutiveSum(inputArray, k) {
var max = inputArray.slice(0,k).reduce((a,b)=>a+b);
var cur = max;
for(var i = k; i < inputArray.length; i++) {
cur = cur + inputArray[i] - inputArray[i-k];
if(cur>max)
max = cur
}
return max
}
console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66202105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Make SliverAppBar have an image as a background instead of a color I have a SliverAppBar with a background image.
When collapsed it has a blue color as a background:
But instead of the blue color I want it to show the background image when collapsed:
How can I achieve this?
I've already tried to give the app bar a transparent background color,
but it did not work.
Code:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
var scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home());
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: DefaultTabController(
length: 2,
child: NestedScrollView(
headerSliverBuilder:
(BuildContext context, bool innerBoxIsScrolled) {
return [
SliverAppBar(
expandedHeight: 200.0,
floating: false,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
title: Text("Collapsing Toolbar",
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
)),
background: Image.network(
"https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
fit: BoxFit.cover,
)),
),
SliverPadding(
padding: new EdgeInsets.all(16.0),
sliver: new SliverList(
delegate: new SliverChildListDelegate([
TabBar(
labelColor: Colors.black87,
unselectedLabelColor: Colors.grey,
tabs: [
new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
new Tab(
icon: new Icon(Icons.lightbulb_outline),
text: "Tab 2"),
],
),
]),
),
),
];
},
body: Center(
child: Text("Sample text"),
),
),
));
}
}
A: Please check below code :
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
var scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home());
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: DefaultTabController(
length: 2,
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverAppBar(
expandedHeight: 200.0,
floating: true,
pinned: true,
snap: true,
actionsIconTheme: IconThemeData(opacity: 0.0),
flexibleSpace: Stack(
children: <Widget>[
Positioned.fill(
child: Image.network(
"https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
fit: BoxFit.cover,
))
],
),
),
SliverPadding(
padding: new EdgeInsets.all(16.0),
sliver: new SliverList(
delegate: new SliverChildListDelegate([
TabBar(
labelColor: Colors.black87,
unselectedLabelColor: Colors.grey,
tabs: [
new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
new Tab(
icon: new Icon(Icons.lightbulb_outline),
text: "Tab 2"),
],
),
]),
),
),
];
},
body: Center(
child: Text("Sample text"),
),
),
));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58970477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: SSE (Server Sent Events) Client library for Clojure? I would like to handle a Server Sent Events stream in Clojure.
Does anyone know a small client library to just do that please ?
I was expecting to find something like https://github.com/stalefruits/gniazdo, which is for Websockets, but for SSE.
I could not find anything though and the only lib that may have been a good candidate is not maintained anymore https://github.com/clojurewerkz/ssese
thanks in advance ...
A: Here are some overviews on the topic:
*
*https://sweetcode.io/using-html5-server-sent-events/
*https://juxt.pro/blog/posts/course-notes.html
*https://www.lucagrulla.com/posts/server-sent-events-with-ring-and-compojure/
*Server push of data from Clojure to ClojureScript
*https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
Here is a highly voted comparison on StackOverflow between Server Sent Events and WebSockets (my favorite):
*
*WebSockets vs. Server-Sent events/EventSource
And here is a nice comparison from IBM (2017):
*
*https://www.ibm.com/developerworks/library/wa-http-server-push-with-websocket-sse/index.html
A: immutant.web has support for SSE built in: http://immutant.org/documentation/current/apidoc/guide-web.html#h3155
There is also this middleware for other web servers: https://github.com/kumarshantanu/ring-sse-middleware, although I have not tried it myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53265737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to provide tunnel between my own app and my own server? I have implemented an Android App which connects my home server. I want to implement a tunnel between my app and the server. when ever app connects to server it will be connected through the secure tunnel. Tunnel might be anything. Is there any suggestion???
P.S.: I want to create tunnel just for this particular app not for all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8258985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony2 using jsroutingbundle and got login error I am using Jsroutingbundle and I add these two lines in my base.html.twig and it works fine.
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>
But when I login next time, it jumped to a page like this:
fos.Router.setData({"base_url":"\/Symfony\/web\/app_dev.php","routes":[],"prefix":"","host":"localhost","scheme":"http"});
And the url is:
http://localhost/Symfony/web/app_dev.php/My/Test/js/routing?callback=fos.Router.setData
I am actually logged in because I can jump to other pages. But it is just unfriendly. How should I handle this problem?
A: In the access_control of your security add:
- { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22142204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hi everyone! My question is about the Charles-proxy certificate My question is about the Charles-proxy certificate. I've already installed Charles on my laptop. The real problem is when I tried to install it on my mobile. I have a Xiaomi with the android 11 version, with this one is impossible. I did everything I could. I have another mobile a Moto G. When I try to link the mobile with Charles I couldn't see the connection between the mobile and the laptop. Can somebody help me?
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72554275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does isEqualToString not work for NSString? I am trying to code the login process for an iPhone app in XCode. The problem is with the NSString serverOutput below. When I print it using printf(serverOutput.UTF8String); it prints 'Yes' to the console. However when I compare serverOutput to "Yes" it doesn't work. Any help would be appreciated. Here's my code:
- (IBAction) loginButton: (id) sender
{
// TODO: spawn a login thread
indicator.hidden = FALSE;
[indicator startAnimating];
NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",userName.text, password.text];
NSString *hostStr = @"http://10.243.1.184/connectDB.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
printf(serverOutput.UTF8String);
if([serverOutput isEqualToString:@"Yes"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
//[self.navigationController pushViewController:DashboardViewController animated:YES];
loginbutton.enabled = TRUE;
}
loginbutton.enabled = FALSE;
}
A: Based on helping others with similar situations I would say the problem is that the response from the server isn't just the string "Yes". Most likely there is some whitespace before and/or after the text. Perhaps a stray newline or two.
Try this:
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16052199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php limit mail () this might be easy but I don´t see the way. I have a shopping cart at my side where user can buy things. for this the buyer can imput his email-adress into an input-form. the order is sent with php mail() to the shopowner and the buyer.
I´m looking for a way to limit mail to sent only two email, this for preventing spam.
I see the risk that spammers could input a semicolon string like this:
email@examplecom;email@xxyz.com;hans@jdkdl.com
A: Y can't you validate using .
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "Reply-to: $validemail\r\n";
}else
{
//redirect.
}
considering your actual question .
<?php
$emails = explode(';',$emailList);
if(count ($emails)<3)
{
if(filter_var_array($emails, FILTER_VALIDATE_EMAIL))
{
mail();
}
else
{
//die
}
}
?>
A: You could check the number of email in the string like this:
if(count(explode(';',$emailList))<3)
{
// send email
}
else
{
// Oh no, jumbo!
}
This code will explode your email string based on the ; characters into an array while at the same time use a count function on the array and execute one of two scenarios based on the number.
A: This should work to only pick maximum two emails (the first two):
$emailString = "email@examplecom;email@xxyz.com;hans@jdkdl.com";
$emails = explode(";", $emailString);
$emails = array_slice($emails, 0, 2);
$emailString = implode(";", $emails);
var_dump($emailString);
Outputs:
string(31) "email@examplecom;email@xxyz.com"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12636621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kinect Html5 Stream to web in existing C# Application For our university project we need the kinect video Stream accessible from another Device in the network. Preferable as a HTML5 Webserver. The Microsoft.Samples Webserver works only with the kinect1 and we need it for kinect 2. Another interesting solution is the one from intrael but we need to implement it in our own application.
Are there any solutions I didn't find or could anyone give us a working example or hint how to proceed?
A: If someone stumbles across this we solved this now with using a simple TCP Listener which listens for a connection:
TcpListener srv = new TcpListener(IPAddress.Any, 51530);
srv.Start(1);
client = srv.AcceptTcpClient();
Then we changed the Kinectpicture into a Bitmap and on every new picture we send the bitmap to the connected device:
NetworkStream ns = client.GetStream();
Graphics g = Graphics.FromImage(bitmap);
MemoryStream imageStream = new MemoryStream();
using (var ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(bitmap);
bmp.Save(imageStream, ImageFormat.Bmp);
}
// bitmap.Save(imageStream, ImageFormat.Bmp);
Console.WriteLine("Bild wird über Socket geschickt");
//reset the memory stream to start of stream
imageStream.Position = 0;
//copy memory stream to network stream
imageStream.CopyTo(ns);
//make sure copy is completed
imageStream.Flush();
imageStream.Close();
//Makes sure everything is sent before closing it
ns.Flush();
on the other side there is an android device which gets the network stream and translates it into a bitmap and shows it in an imageview.
Feel free to ask additional questions for needed clarification.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27926250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Response.Redirect not sending string i've got a bit of a problem trying to set up a general error page in MVC.
I am handling all app errors in Global.asax.cs with the following code ->
protected void Application_Error(object sender, EventArgs e)
{
//if (Request.Url.ToString().StartsWith("http://localhost:"))
// return;
string msg;
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Found");
sb.AppendLine("Timestamp: " + System.DateTime.Now.ToString());
sb.AppendLine("Error in: " + Request.Url.ToString());
sb.AppendLine("Browser Version: " + Request.UserAgent.ToString());
sb.AppendLine("User IP: " + Request.UserHostAddress.ToString());
sb.AppendLine("Error Message: " + ex.Message);
sb.AppendLine("Stack Trace: " + ex.StackTrace);
msg = sb.ToString();
Server.ClearError();
Response.Redirect(string.Format("~/Error/Error?w={0}", msg ));
}
My problem is that i'm not getting a redirect. I see the same page URL and a blank page when i'm creating an error.
If i remove "errorMsg" and add a SIMPLE STRING, it works, redirects with the required param. Ex:
string test = "testme";
Response.Redirect(string.Format("~/Error/Error?w={0}", test));
That does redirect me to the error page with param "testme". What am i doing wrong here?
A: You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52150026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display from database if 2 columns match I am new to Laravel and am currently I am working on a very basic private messaging system.
Currently I am trying to display a page which shows the messages between 2 users (sent and received), however I am only able to display the messages which the user has sent. Here is my viewMessage function in my MessageController file.
MessageController.php
public function viewMessage($recipient_id){
$user = auth()->user()->id;
$messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();
return view ('pages.messages.view', compact('user', 'messages'));
}
View Blade
<ul>
@foreach ($messages as $message)
<li>{{$message->body}}</li>
@endforeach
</ul>
As you can see from the $messages variable, i have a query builder which should match the sender ID with the ID of the current logged in user. It should also match the recipient ID with the ID of the user from the parameter, however this does not currently work.
I have used dd() and both sender id and recipient id is coming through correctly so I am at a loss as to why this is not working. I am assuming I am probably using the query builder incorrectly?
Thanks
A: You are only asking for messages the user sent. You need to also get messages that the user received.
$user = auth()->user()->id;
$messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();
$receivedMessages= Message::where('sender_id', recipient_id)->where('recipient_id', $user)->get();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50470035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to export strings from Java (Android) to MS Word I want to know how to export typed strings to a word document file.
The application I'm trying to make should be simple; User has his application on his Android phone and he types in some text.
It will have few PlainText and MultilineText text fields, in which the user will be able to type, whatever he wants.
So, when a user connects his mobile to the computer, he should be able to click some button and 'generate report'.
That way, all the text he typed in should be transformed into a word doc.
Is there a way of doing this?
A: You'll want to use some sort of java library for Microsoft Office. Take a look at Apache POI for this. Here's an example of using Apache POI.
As a side note, I would also recommend that the user doesn't have to actually connect their device to the computer, but rather make an export feature which will create the Word Document and they can e-mail it or share it in some other way. This would improve your User Experience :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13402768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Handling entities in react? I am very new to react, redux, prop-types and so on. I am coming from the Angular2 world with TypeScript support. There I had my own entity classes which I imported in the components where I need them. Now in react I only have prop-types which I define for each component.
All fine and good but how would you solve this data structure with prop-types:
{
"order": {
"date": "2018-03-20",
"customer": {
"firstName": "John",
"lastName": "Brown"
},
"product": {
"category": "book",
"name": "XYZ"
},
"price": 99
}
}
In Angular2 I would have made three entities, but how I will handle this in react with prop-types? Sure I can define the correct prop-types for this data structure in each component where I got an order entity passed via props but this looks like a huge code redundancy for me.
My question now: Is there any best practice solution for this problem? Maybe a central prop-types schema like this module: https://www.npmjs.com/package/react-entity?
(I don't want to use this module because it seems that it is not under development anymore)
A: If you want to use types in React that are richer than what PropTypes can provide you, you have two options:
*
*Use TypeScript. This does not come out of the box, so you have to change your build. There are a bunch of bootstrapper projects that can make your life easier.
*Use Flow. The standard bootstrappers such as CRA come with support for it out of the box.
Which one to use is a matter of preference at the end. Both have their advantages. Here you have a pretty good comparison of what both can do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49395378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get multiple input type hidden value row button click for column in table This is sample column for single row where i have tried to get hidden value by button action event
<td colspan="2">
<!-- the hidden value i want to retrieve "stockitemid" and "outletid" -->
<!-- value i have bind from controller through model like @item.ID= stockitemid and @item.OUTLET_ID=outletid -->
<input type="hidden" class="itemid" name="stockitemid" value="@item.ID"/>
<input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID"/>
<div class="btn-toolbar row-action">
<div class="btn-group pull-right">
<!-- button action given below what i have tried to display value in modal form controller. but every-time i click same value found from this event -->
<button class="btn btn-primary" id="btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item"></button>
</div>
</div>
</td>
Hhere is my retrieval jquery code every time i get same "stockitemid" and "outletid"
<script>
$('#btnitemaddtotray').click(function() {
// this is what i have tried to get row index with column index value
$('td').click(function () {
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
// here is itemid and outlet id i got every-time same value.
var itemid = $('input[name=stockitemid]').val();
var outletid =$('input[name=outletid]').val();
});
</script>
I want to get hidden value from table where i have multiple row.
A: ID should always be unique to each element, so I am using a class instead. Use of parents() will give you the the container to find() the hidden inputs in to retrieve the values.
$('.btnitemaddtotray').on('click',function() {
var btn = $(this),
row = btn.parents('td').first();
itemId = row.find('.itemid').val(),
oid = row.find('.oid').val();
console.log(itemId,oid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table><tr>
<td colspan="2">
<input type="hidden" class="itemid" name="stockitemid" value="@item.ID"/>
<input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID"/>
<div class="btn-toolbar row-action">
<div class="btn-group pull-right">
<button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button>
</div></div>
</td></tr>
<tr>
<td colspan="2">
<input type="hidden" class="itemid" name="stockitemid" value="@item.ID2"/>
<input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID2"/>
<div class="btn-toolbar row-action">
<div class="btn-group pull-right">
<button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button>
</div></div>
</td></tr>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42185913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I stop my backtracking algorithm once I find and answer? I have wrote this code for solving a problem given to me in class, the task was to solve the "toads and frogs problem" using backtracking. My code solves this problem but does not stop once it reaches the solution (it keeps printing "states" showing other paths that are not a solution to the problem), is there a way to do this?. This is the code:
def solution_recursive(frogs):
#Prints the state of the problem (example: "L L L L _ R R R R" in the starting case
#when all the "left" frogs are on the left side and all the "right" frogs are on
#the right side)
show_frogs(frogs)
#If the solution is found, return the list of frogs that contains the right order
if frogs == ["R","R","R","R","E","L","L","L","L"]:
return(frogs)
#If the solution isn't the actual state, then start (or continue) recursion
else:
#S_prime contains possible solutions to the problem a.k.a. "moves"
S_prime = possible_movements(frogs)
#while S_prime contains solutions, do the following
while len(S_prime) > 0:
s = S_prime[0]
S_prime.pop(0)
#Start again with solution s
solution_recursive(s)
Thanks in advancement!
A:
How do I stop my backtracking algorithm once I find an answer?
You could use Python exception facilities for such a purpose.
You could also adopt the convention that your solution_recursive returns a boolean telling to stop the backtrack.
It is also a matter of taste or of opinion.
A: I'd like to expand a bit on your recursive code.
One of your problems is that your program displays paths that are not the solutions. This is because each call to solution_recursive starts with
show_frogs(frogs)
regardless of whether frogs is the solution or not.
Then, you say that the program is continuing even after the solution has been found. There are two reasons for this, the first being that your while loop doesn't care about whether the solution has been found or not, it will go through all the possible moves:
while len(S_prime) > 0:
And the other reason is that you are reinitializing S_prime every time this function is called. I'm actually quite amazed that it didn't enter an infinite loop just checking the first move over and over again.
Since this is a problem in class, I won't give you an exact solution but these problems need to be resolved and I'm sure that your teaching material can guide you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64328470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In postgresql, which part of locale causes problems with LIKE operations? There's a lot of discussion around the net about locale other than C or POSIX causing performance problems in postgresql. I'm not clear though as to which part(s) of the locale setting cause problems and why.
In the manpage for initdb(1), we see:
--locale=locale
Sets the default locale for the database cluster. If this option is not specified, the locale is inherited from the environment that
initdb runs in. Locale support is described in Section 22.1, \u201cLocale Support\u201d, in the documentation.
--lc-collate=locale, --lc-ctype=locale, --lc-messages=locale, --lc-monetary=locale, --lc-numeric=locale, --lc-time=locale
Like --locale, but only sets the locale in the specified category.
We also see:
To alter the default collation order or character set classes, use the --lc-collate and --lc-ctype options. Collation orders other than C or
POSIX also have a performance penalty. For these reasons it is important to choose the right locale when running initdb.
Does this mean that I could use --lc-collate POSIX --lc-ctype UTF-8 and avoid performance penalties? Or are there other performance issues involved?
I'm not surprised that collation affects sort performance, but is that the same issue that arises with LIKE comparisons not using indexes? Can someone explain what the issue is with the LIKE operator?
A: It sounds like you're talking about the text_pattern_ops operator class and its application for databases that are in locales other than C.
The issue is not one of encoding, but of collation.
A b-tree index requires that everything have a single, stable sort order following some invariants, like the assumption that if a < b then b > a. Comparison operators are used to sort the tree when building and maintaining and index.
For text strings, the collation rules for the language get applied by the comparison operators when determining whether one string is greater than or less than another so that strings sort "correctly" as far as the user is concerned. These rules are locale-dependent, and can do things like ignore punctuation and whitespace.
The LIKE operator isn't interested in locales. It just wants to find a prefix string, and it can't just ignore punctuation. So it cannot use a b-tree index that was created with a collation that might ignore punctuation/whitespace, etc. LIKE walks down the index tree character by character to find a match, and it can't do that if the index might ignore characters.
That's why, if your DB uses a locale other than "C" (POSIX) you must create different indexes for use with LIKE.
Example of localised sorting, compare:
regress=> WITH x(v) AS (VALUES ('10'),('1'),('1.'),('2.'),('.2'),('.1'),('1-1'),('11')
)
SELECT v FROM x ORDER BY v COLLATE "en_AU";
v
-----
1
.1
1.
10
11
1-1
.2
2.
(8 rows)
regress=> WITH x(v) AS (VALUES ('10'),('1'),('1.'),('2.'),('.2'),('.1'),('1-1'),('11')
)
SELECT v FROM x ORDER BY v COLLATE "C";
v
-----
.1
.2
1
1-1
1.
10
11
2.
(8 rows)
The text_pattern_ops opclass serves this need. In newer PostgreSQL releases you can create an index with COLLATE "C" on the target column instead, serving the same need, e.g.:
CREATE INDEX idx_c ON t2(x COLLATE "C");
LIKE will use such an index, and it can also be used for faster sorting where you don't care about locale for a given operation, e.g.
SELECT x FROM t2 ORDER BY x COLLATE "C";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26458548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Trying to understand the differences across these promises and setTimeouts I'm learning about promises, setTimeout and async calls and have done a great job of confusing myself. I think I'm lacking some understanding around the callback and how setTimeout works. I've been looking at Mozilla documentation and the various Stackoverflow posts regarding these topics. I'm still having some trouble wrapping my head around why some of the functions I've created behave the way they do regarding the timeouts that are set.
Between wait0 and wait1 I don't understand why the timeout for wait0 works properly and wait1 doesn't adhere to it. With wait2 it is like wait1 except wrapped in an arrow function expression. Why does that make the timeout work properly? wait3 isn't actually using the callback so that makes sense why the promise and then functions don't do anything. But it stops wait4 from running. Is it blocking progression indefinitely or actually ending execution? For wait4 I'm also not passing a value into the callback like with wait0 but the timeout isn't being adhered to.
function wait0() {
return new Promise((resolve, failure)=>{
setTimeout(resolve, 2000);
});
}
function wait1() {
return new Promise((resolve, failure)=>{
setTimeout(resolve('resolved ' + new Date().toGMTString()), 2000);
});
}
function wait2() {
return new Promise((resolve, failure)=>{
setTimeout(()=>{
resolve('resolved ' + new Date().toGMTString());
}, 2000);
});
}
function wait3() {
return new Promise((resolve, failure)=>{
setTimeout(()=>{}, 2000);
});
}
function wait4() {
return new Promise((resolve, failure)=>{
setTimeout(resolve(), 2000);
});
}
async function test() {
await wait0().then((result)=>console.log(result)); // Works as expected
console.log(new Date().toGMTString());
await wait1().then((result)=>console.log(result)); // Doesn't adhere to timeout
console.log(new Date().toGMTString());
await wait2().then((result)=>console.log(result)); // Works as expected
console.log(new Date().toGMTString());
await wait3().then((result)=>console.log(result)); // Never resolves
console.log(new Date().toGMTString());
await wait4().then((result)=>console.log(result)); // Doesn't adhere to timeout
console.log(new Date().toGMTString());
}
test();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70674702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: modelsim script for compile all I have a modelsim project file (*.mpf), where it lists all the HDL files, and it provides a "compile_order" for each file.
So, when I load the (.mpf) file, I can see that each one of my HDL files have a compoile_order number next to it. So far so good.
Now, on the GUI, I can run "compile all", and it will compile all my files in correct order, since the orders are already pre-determined.
I want to know that what is the tcl command line that is equivalent to the "compile all" in the GUI?
In other words, I want to be able to type a command and it compiles all the files, rather than I do "compile all" through the GUI.
A: You're looking for the command project. You can use it in a "*.do" file this way :
project open MyProject.mpf
project compileall
For all others modelsim commands, you can look at the Modelsim Command Reference Manual. Project command is described in page 220.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49538638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Uploading files to node js using html form? var fs = require('fs'); // require file system module
var http = require('http'); // require http module
http.createServer(function(request,response){
var newFile = fs.createWriteStream("readme_copy.txt");
request.pipe(newFile);
request.on('end',function(){response.end('uploaded')});
}).listen(8888);
I am trying to use this piece of code.I am uploading a file to node server and I am creating a new copy of the uploaded file.
I mentioned My HTML file below.It is hitting the server and uploading the file but the copy of file is empty.
If I am using curl in command prompt for uploading the same file it is working fine.
Any idea what I am missing??
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-8">
</head>
<body>
<form action="http://localhost:8888/">
<input type="file" name="readme.txt" method="post" enctype="multipart/form-data">
<input type="submit">
</form>
<p><strong>Note:</strong> The accept attribute of the input tag is not supported in Internet Explorer 9 and earlier versions.</p>
<p><strong>Note:</strong> Because of security issues, this example will not allow you to upload files.</p>
</body>
</html>
A: Your Javascript is missing the actual piece that does the writing to the readme_copy file that you created by calling createWriteStream.
Here's an example of what you need to do:
http://www.html5rocks.com/en/tutorials/file/filesystem/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22577608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any way to list out all permissions and on which resources an IAM user have access? I am asked to list all users accesses in my company's aws account. Is there any way that I can list out the resources and respective permissions a user has? I feel it is difficult to get the details by looking into both IAM polices as well as Resource based policies. And it is much difficult if the user has cross account access.
A: There is no single command that you can list all the permission. if you are interested to use some tool then you can try a tool for quickly evaluating IAM permissions in AWS.
You can try this script as well, As listing permission with single command is not possible you can check with a combination of multiple commands.
#!/bin/bash
username=ahsan
echo "**********************"
echo "user info"
aws iam get-user --user-name $username
echo "***********************"
echo ""
# if [ $1=="test" ]; then
# all_users=$(aws iam list-users --output text | cut -f 6)
# echo "users in account are $all_users"
# fi
echo "get user groups"
echo "***********************************************"
Groups=$(aws iam list-groups-for-user --user-name ahsan --output text | awk '{print $5}')
echo "user $username belong to $Groups"
echo "***********************************************"
echo "listing policies in group"
for Group in $Groups
do
echo ""
echo "***********************************************"
echo "list attached policies with group $Group"
aws iam list-attached-group-policies --group-name $Group --output table
echo "***********************************************"
echo ""
done
echo "list attached policies"
aws iam list-attached-user-policies --user-name $username --output table
echo "-------- Inline Policies --------"
for Group in $Groups
do
aws iam list-group-policies --group-name $Group --output table
done
aws iam list-user-policies --user-name $username --output table
A: Kindly run below one liner bash script regarding to list all users with their policies, groups,attached polices.
aws iam list-users |grep -i username > list_users ; cat list_users |awk '{print $NF}' |tr '\"' ' ' |tr '\,' ' '|while read user; do echo "\n\n--------------Getting information for user $user-----------\n\n" ; aws iam list-user-policies --user-name $user --output yaml; aws iam list-groups-for-user --user-name $user --output yaml;aws iam list-attached-user-policies --user-name $user --output yaml ;done ;echo;echo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57555448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Download all m3u8 files AWS CLI Through Unknown options: --include,*.m3u8 Can the AWS CLI tool be used to only list/retrieve certain file types in S3? I was trying:
aws s3 ls --summarize --human-readable --recursive s3://cloudfront.abc.com/CDNSource/hls/ --include "*.m3u8"
but receiving "Unknown options: --include,*.m3u8"
I have tried to grep but it will just filter the return, so the sum will still be incorrect. I need to download all m3u8 files and then reupload them with a change.
what's the best way to do that? Any help would be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74392427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails - Strange characters pass through validation and break query I copy-pasted a string into a form field and a strange character broke my MySql query.
I could force the error on the console this way (the weird character is in the middle of the two words "Invalid" and "Character", you can also copy-paste it):
> dog.name = "Invalid Character"
> dog.save # -> false
Which returns the following error:
ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: '\xE2\x80\x8BCha...' for column 'name' at row 1: UPDATE `dogs` SET `name` = 'Invalid Character' WHERE `dogs`.`id` = 2227
It replaced the character by '\xE2\x80\x8B' as the error said.
Is there any validation that I could use to remove these kind of weird characters?
Obs: I also saw that
> "Invalid Character".unpack('U*')
Returns
[73, 110, 118, 97, 108, 105, 100, 32, 8203, 67, 104, 97, 114, 97, 99, 116, 101, 114]
The weird character must be the 8230 one.
Obs2: In my application.rb, I have: config.encoding = "utf-8"
EDIT
On my console, I got:
> ActiveRecord::Base.connection.charset # -> "utf8"
> ActiveRecord::Base.connection.collation # -> "utf8_unicode_ci"
I also ran (on the rails db mySql console):
> SELECT table_collation FROM INFORMATION_SCHEMA.TABLES where table_name = 'dogs';
and got "utf8_unicode_ci"
EDIT2
If I change the table's character set to utf8mb4 I don't get the error. But still, I have to filter those characters.
A: On the rails db MySql console, I used:
SHOW CREATE TABLE dogs;
To find out that the charset for the table was latin1.
I just added a migration with this query:
ALTER TABLE dogs CONVERT TO CHARACTER SET utf8mb4;
And it started to work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28325756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: checking for sting in pandas column and modifying another I am working on cleaning a dataframe. The dataframe contains three columns order_id 'order_item' and 'order_type. The order type can be: breakfast, lunch, or dinner. I want to compare each item in the order to confirm it matches the order type. If not, I would like to drop the tuple that contains the wrong item.
The menus are as follow:
breakfastMenu=['Pancake', 'Coffee', 'Eggs', 'Cereal']
dinnerMenu=['Salmon', 'Fish&Chips', 'Pasta', 'Shrimp']
lunchMenu=['Steak', 'Fries', 'Burger', 'Chicken', 'Salad']
For example you can see in the first line, the lunch order contains coffee which is not correct. And dinner include Egg.
sample of the dataframe:
order_id order_type order_items
0 ORDB10489 Lunch [('Coffee', 4), ('Salad', 10), ('Chicken', 8)]
1 ORDZ00319 Dinner [('Fish&Chips', 9), ('Pasta', 5), ('Eggs', 3)]
2 ORDB00980 Dinner [('Pasta', 6), ('Fish&Chips', 10)]
3 ORDY10003 Breakfast [('Coffee', 2), ('Cereal', 1)]
4 ORDK04121 Lunch [('Steak', 9), ('Chicken', 5)]
I don't have enough experience with pandas data frames. But my idea is to create a for loop with if conditions. The loop will compare the first item in each tuple to the order_type and the corresponding menu list. If the item is not in the corresponding list the tuple will be dropped.
This draft code is just a beginning but it is similar to what I want to achieve:
if dirtyData['order_type'].str.contains('Breakfast').any()\
and eval(dirtyData['order_items'][0])[0][0] not in breakfastMenu:
print(dirtyData['order_id'])
I add eval to convert the list of tuples from a string to a list.
any input is appreciated
Thank you,
A: Using apply with a custom function.
Ex:
import ast
breakfastMenu=['Pancake', 'Coffee', 'Eggs', 'Cereal']
dinnerMenu=['Salmon', 'Fish&Chips', 'Pasta', 'Shrimp']
lunchMenu=['Steak', 'Fries', 'Burger', 'Chicken', 'Salad']
check_val = {'Breakfast': breakfastMenu, 'Dinner': dinnerMenu, "Lunch": lunchMenu}
data = [['ORDB10489', 'Lunch', "[('Coffee', 4), ('Salad', 10), ('Chicken', 8)]"],
['ORDZ00319', 'Dinner', "[('Fish&Chips', 9), ('Pasta', 5), ('Egg', 3)]"],
['ORDB00980', 'Dinner', "[('Pasta', 6), ('Fish&Chips', 10)]"],
['ORDY10003', 'Breakfast', "[('Coffee', 2), ('Cereal', 1)]"],
['ORDK04121', 'Lunch', "[('Steak', 9), ('Chicken', 5)]"]]
df = pd.DataFrame(data, columns=['order_id', 'order_type', 'order_items'])
df["order_items"] = df["order_items"].apply(ast.literal_eval)
df["order_items"] = df.apply(lambda x: [i for i in x["order_items"] if i[0] in check_val.get(x["order_type"], [])], axis=1)
print(df)
Output:
order_id order_type order_items
0 ORDB10489 Lunch [(Salad, 10), (Chicken, 8)]
1 ORDZ00319 Dinner [(Fish&Chips, 9), (Pasta, 5)]
2 ORDB00980 Dinner [(Pasta, 6), (Fish&Chips, 10)]
3 ORDY10003 Breakfast [(Coffee, 2), (Cereal, 1)]
4 ORDK04121 Lunch [(Steak, 9), (Chicken, 5)]
A: So, I think there is a solution without any essential for loops. Just using some joins. But before we can achieve that, we have to bring the data to a more suitable shape.
flattened_items = df.order_items.apply(pd.Series).stack().reset_index().assign(
**{"order_item": lambda x:x[0].str[0], "item_count": lambda x:x[0].str[1]})
print(flattened_items.head())
level_0 level_1 0 order_item item_count
0 0 0 (Coffee, 4) Coffee 4
1 0 1 (Salad, 10) Salad 10
2 0 2 (Chicken, 8) Chicken 8
3 1 0 (Fish&Chips, 9) Fish&Chips 9
4 1 1 (Pasta, 5) Pasta 5
So essentially, I just flattened the list of tuple into two columns. Note, for your setup to work, you might need to run reset_index one on the original Dataframe df (otherwise it's like your sample from Dataframe)
Next we create a Dataframe that apps meals to items via
flattend_orders = pd.merge(df[["order_id", "order_type"]],
flattened_items[["level_0","order_item", "item_count"]],
left_index=True, right_on="level_0").drop("level_0", axis=1)
meal_dct = {"Breakfast": breakfastMenu, "Lunch": lunchMenu, "Dinner": dinnerMenu}
meal_df = pd.DataFrame.from_dict(meal_dct, orient="index").stack().reset_index(
).drop("level_1", axis=1).rename(columns={"level_0": "Meal", 0: "Item"})
which looks like
print(meal_df.head())
Meal Item
0 Breakfast Pancake
1 Breakfast Coffee
2 Breakfast Eggs
3 Breakfast Cereal
4 Lunch Steak
Now, we can just do an inner join on the order_type and order_item
merged = pd.merge(flattend_orders, meal_df, left_on=["order_type", "order_item"],
right_on=["Meal", "Item"]).drop(["Meal", "Item"], axis=1)
and we obtain
order_id order_type order_item item_count
0 ORDB10489 Lunch Salad 10
1 ORDB10489 Lunch Chicken 8
2 ORDK04121 Lunch Chicken 5
3 ORDZ00319 Dinner Fish&Chips 9
4 ORDB00980 Dinner Fish&Chips 10
5 ORDZ00319 Dinner Pasta 5
6 ORDB00980 Dinner Pasta 6
7 ORDY10003 Breakfast Coffee 2
8 ORDY10003 Breakfast Cereal 1
9 ORDK04121 Lunch Steak 9
Now, this is maybe already good enough, but you might prefer to have a list of tuples back. To this end:
merged.groupby(["order_id", "order_type"]).apply(lambda x: list(zip(x["order_item"],
x["item_count"]))).reset_index().rename(columns={0:"order_items"})
gives
order_id order_type order_items
0 ORDB00980 Dinner [(Fish&Chips, 10), (Pasta, 6)]
1 ORDB10489 Lunch [(Salad, 10), (Chicken, 8)]
2 ORDK04121 Lunch [(Chicken, 5), (Steak, 9)]
3 ORDY10003 Breakfast [(Coffee, 2), (Cereal, 1)]
4 ORDZ00319 Dinner [(Fish&Chips, 9), (Pasta, 5)]
Note that the ugliness here is due to converting data from (maybe) insufficient formats. Also all for loops and apples just come from data transformation.
Essentially, my answer can be summarized as:
pd.merge(df, df_meal)
if we assume just the right data format.
Btw, I just chose item_count as a name as a best guess.
A: This is something you probably want to do in an Apply-function. Given that the breakfastMenu, dinnerMenu and lunchMenu are defined on the top of the script, the following function would work:
def check_correct(x):
if x['order_type'] == 'lunch':
current_menu = lunchMenu
elif x['order_type'] == 'dinner':
current_menu = dinnerMenu
else:
current_menu= breakfastMenu
current_menu = [x.lower() for x in current_menu]
return_list = []
for item, _ in x['order_items']:
return_list.append(item.lower() in current_menu)
return return_list
You can create a new column inside the DataFrame with:
df.apply(check_correct, axis = 1). It will give you a list with the True and False mathes. The first line would result in the following output:
[False, True, True]
A: for index, row in df.iterrows():
new = []
if row["order_type"] == "Breakfast":
order_type = breakfastMenu
elif row["order_type"] == "Dinner":
order_type = dinnerMenu
elif row["order_type"] == "Lunch":
order_type = lunchMenu
else:
continue
a = row["order_items"][1:-1]
b = a.split(",")
for i in range(0,len(b),2):
meal = b[i].strip()[2:-1]
if meal in order_type:
new.append([meal, b[i+1]])
row["order_items_new"] = new
print(df["order_items_new"])
0 [[Salad, 10)], [Chicken, 8)]]
1 [[Fish&Chips, 9)], [Pasta, 5)]]
2 [[Pasta, 6)], [Fish&Chips, 10)]]
3 [[Coffee, 2)], [Cereal, 1)]]
4 [[Steak, 9)], [Chicken, 5)]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58183488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I perform an "or" operation in LINQ to objects? Looking up LINQ and Or in google is proving somewhat difficult so here I am.
I want to so the following:
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant())
**or creditCard.CardNumber.().Contains(txtFilter.Text)**
orderby creditCard.BillToName
select creditCard)
A: C# keywords supporting LINQ are still C#. Consider where as a conditional like if; you perform logical operations in the same way. In this case, a logical-OR, you use ||
(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(
txtFilter.Text.ToLowerInvariant())
|| creditCard.CardNumber.().Contains(txtFilter.Text)
orderby creditCard.BillToName
select creditCard)
A: You can use the .Where() function to accomplish this.
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
A: You should use the boolean operator that works in your language. Pipe | works in C#
Here's msdn on the single |
Here's msdn on the double pipe ||
The deal with the double pipe is that it short-circuits (does not run the right expression if the left expression is true). Many people just use double pipe only because they never learned single pipe.
Double pipe's short circuiting behavior creates branching code, which could be very bad if a side effect was expected from running the expression on the right.
The reason I prefer single pipes in linq queries is that - if the query is someday used in linq to sql, the underlying translation of both of c#'s OR operators is to sql's OR, which operates like the single pipe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/251433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: System.PlatformNotSupported Exception, no recognizer installed I'm making a program where I need speech recognition engine, but I ran into the problem that says "no recognizer installed". I've been searching for 2 days, what can i do about it, but found nothing useful. I red nearly all of the other question, here, who struggled with this similar problem, but links are outdated. I tried things like looking ofr installed recognizors but got nothing installed. I tried to figure out whats the difference between Microsoft.Speech and System.Speech, didnt get to far Here is my code, what am i missing?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace Essex
{
public partial class Essex : Form
{
SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
public Essex()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Choices commands = new Choices();
commands.Add(new string[] { "say hello", "print my name" });
GrammarBuilder gBuilder = new GrammarBuilder();
gBuilder.Append(commands);
Grammar grammar = new Grammar(gBuilder);
recEngine.LoadGrammarAsync(grammar);
recEngine.SetInputToDefaultAudioDevice();
recEngine.SpeechRecognized += RecEngine_SpeechRecognized;
}
private void button1_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsync(RecognizeMode.Multiple);
}
private void button2_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsyncStop();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void RecEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
switch (e.Result.Text)
{
case "say hello":
label1.Text = "Welcome sir";
break;
case "print my name":
label1.Text = "John Smith";
break;
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66629847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: combining data to 1 model attribute I have a calendar system in which the user enters date and time for an event in a seperate text_field. I store the date and time in one attribute (begin) in the Event model I have a hard time figuring out how to combine the date and time input and combine it into the begin attribute.
I preferably want to do this via a virtual attribute (:date and :time) so I can easily map my form against those virtual attributes without the need to do something in the controller.
Many thanks
A: You can make your own accessor methods for the date and time attributes like this:
def date
datetime.to_date
end
def date=(d)
original = datetime
self.datetime = DateTime.new(d.year, d.month, d.day,
original.hour, original.min, original.sec)
end
def time
datetime.to_time
end
def time=(t)
original = datetime
self.datetime = DateTime.new(original.year, original.month, original.day,
t.hour, t.min, t.sec)
end
A: You should use before_validation callback to combine data from two virtual attributes into one real attribute. For example, something like this:
before_validation(:on => :create) do
self.begin = date + time
end
Where date + time will be your combining logic of the two values.
Then you should write some attr_accessor methods to get individual values if necessary. Which would do the split and return appropriate value.
A: I think you have a datetime field in your model, rails allows you to read in the date part and time part separately in your forms (easily) and then just as easily combine them into ONE date time field. This works specially if your attribute is a datetime.
# model post.rb
attr_accessible :published_on # just added here to show you that it's accessible
# form
<%= form_for(@post) do |f| %>
<%= f.date_select :published_on %>
<%= f.time_select :published_on, :ignore_date => true %>
<% end %>
The Date Select line will provide you the date part of published_on
The Time Select line will provide you the time part of published_on. :ignore_date => true will ensure that the time select does not output 3 hidden fields related to published_at since you are already reading them in in the previous line.
On the server side, the date and time fields will be combined!
If you however you are reading the date as a text_box, then this solution doesnt work unfortunately. Since you are not using the composite attribute that rails provides for you built in on datetime.
In short, if you use date_select,time_select, rails makes it easy, otherwise you're free to look for other options.
A: You should use an open-source datetime picker widget that handles this for you, and not make the fields yourself as a text field.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6110210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: whats the use of shared mutex? Consider following example -
#include <boost/thread.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
boost::shared_mutex mutex;
std::vector<int> random_numbers;
void fill()
{
std::srand(static_cast<unsigned int>(std::time(0)));
for (int i = 0; i < 3; ++i)
{
boost::unique_lock<boost::shared_mutex> lock(mutex);
random_numbers.push_back(std::rand());
lock.unlock();
wait(1);
}
}
void print()
{
for (int i = 0; i < 3; ++i)
{
wait(1);
boost::shared_lock<boost::shared_mutex> lock(mutex);
std::cout << random_numbers.back() << std::endl;
}
}
int sum = 0;
void count()
{
for (int i = 0; i < 3; ++i)
{
wait(1);
boost::shared_lock<boost::shared_mutex> lock(mutex);
sum += random_numbers.back();
}
}
int main()
{
boost::thread t1(fill);
boost::thread t2(print);
boost::thread t3(count);
t1.join();
t2.join();
t3.join();
std::cout << "Summe: " << sum << std::endl;
}
In the given example, both print() and count() access random_numbers read-only. While the print() function writes the last number of random_numbers to the standard output stream, the count() function adds it to the variable sum. Since neither function modifies random_numbers, both can access it at the same time using a non-exclusive lock of type boost::shared_lock.
My question is : As the resource is read only why the shared mutex is needed at the first place in count and print function?' Cant we manage without it?
A:
As the resource is read only [...]
No, it is not : the fill() method proceed to writes through the following :
random_numbers.push_back(std::rand()); // write to random_numbers
So the shared mutex really is necessary to synchronize your access to the vector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25322271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alter the precision of an existing decimal column in SQL Server 2014 results in error I have a couple decimal columns in a couple tables that I need to expand from decimal(9, 4) to decimal(9, 5). Unfortunately I get the following error every way I try. So far I have tried changing it using design in SQL Server Management Studio and running the query:
alter table xxx
alter column xxx decimal (9,5) not null
The error is the same:
Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting numeric to data type numeric.
These are large, important tables that are used in dozens of stored procedures and applications so I want to avoid adding a new column and copying the data over. Each table has between 250K and 500K rows.
Any ideas would be appreciated.
Thanks!
A: This is because you have reduced the number of significant digits when you changed the datatype. If you have any rows with a value of 100,000 or greater it won't fit inside the new size. If you want to increase the number of decimal places (scale) you will also need to increase the precision by 1.
alter table xxx alter COLUMN xxx decimal (10,5) not null
Please note, this will increase the storage requirements of each row by 4 bytes. The storage requirement will increase from 5 bytes to 9 bytes.
https://msdn.microsoft.com/en-us/library/ms187746.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32122818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Count how many this word in the file but so many of them to separate I want to count how many of country that input in the program and show 3 at the most number on it like this
USA,USA,UK,UK,Canada,Canada,south park
and the result is Three of countries that have most number are USA,UK,Canada for example
but the problem is I need to create char and int for every country in the world(If you have better ideas, you can tell me too but I'm just a beginner so please explain or show the final code to me to understand it) like this
#include <stdio.h>
#include <string.h>
int main()
{
char * countrylist [] = {"Laotian / Lao","Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia"
,"Austria","Austrian Empire","Azerbaijan","Baden","Bahamas","Bahrain","Bangladesh","Barbados","Bavaria","Belarus","Belgium","Belize","Benin","Bolivia"
,"Bosnia and Herzegovina","Botswana","Brazil","Brunei","Brunswick and Luneburg","Bulgaria","Burkina Faso","Upper Volta","Burma","Burundi","Cabo Verde"
,"Cambodia","Cameroon","Canada","Cayman Islands","Central African Republic","Central American Federation","Chad","Chile","China","Colombia","Comoros"
,"Congo Free State","Costa Rica","Cote dIvoire","Ivory Coast","Croatia","Cuba","Cyprus","Czechia","Czechoslovakia","Democratic Republic of the Congo"
,"Denmark","Djibouti","Dominica","Dominican Republic","Duchy of Parma","East Germany","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea"
,"Estonia","Eswatini","Ethiopia","Federal Government of Germany","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Grand Duchy of Tuscany"
,"Greece","Grenada","Guatemala","Guinea","Guinea Bissau","Guyana","Haiti","Hanover","Hanseatic Republics","Hawaii","Hesse","Holy See","Honduras","Hungary"
,"Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kingdom of Serbia","Kingdom of Yugoslavia"
,"Kiribati","Korea","Kosovo","Kuwait","Kyrgyzstan","Latvia","Lebanon","Lesotho","Lew Chew","Loochoo","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg"
,"Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mecklenburg Schwerin","Mecklenburg Strelitz","Mexico"
,"Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Namibia","Nassau","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger"
,"Nigeria","North German Confederation","North German Union","North Macedonia","Norway","Oldenburg","Oman","Orange Free State","Pakistan","Palau","Panama","Papal States"
,"Papua New Guinea","Paraguay","Peru","Philippines","Piedmont Sardinia","Poland","Portugal","Qatar","Republic of Genoa","Republic of Korea","South Korea","Republic of the Congo"
,"Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia"
,"Schaumburg Lippe","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Sudan","Spain"
,"Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Tajikistan","Tanzania","Texas","Thailand","Timor Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey"
,"Turkmenistan","Tuvalu","Two Sicilies","Uganda","Ukraine","Union of Soviet Socialist Republics","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Vanuatu"
,"Venezuela","Vietnam","Wurttemberg","Yemen","Zambia","Zimbabwe"
};
int Afghanistan=0,Albania=0,Algeria=0,Andorra=0,Angola=0,AntiguaandBarbuda=0,Argentina=0,Armenia=0,Australia=0,Austria=0,AustrianEmpire=0,Azerbaijan=0,Baden=0,Bahamas=0,Bahrain=0,Bangladesh=0,Barbados=0,Bavaria=0,Belarus=0,Belgium=0,Belize=0,Benin=0,
Dahomey=0,Bolivia=0,BosniaandHerzegovina=0,Botswana=0,Brazil=0,Brunei=0,BrunswickandLuneburg=0,Bulgaria=0,BurkinaFaso=0,UpperVolta=0,Burma=0,Burundi=0,CaboVerde=0,Cambodia=0,Cameroon=0,Canada=0,CaymanIslands=0,CentralAfricanRepublic=0,CentralAmericanFederation=0,
Chad=0,Chile=0,China=0,Colombia=0,Comoros=0,CongoFreeState=0,CostaRica=0,CotedIvoire=0,IvoryCoast=0,Croatia=0,Cuba=0,Cyprus=0,Czechia=0,Czechoslovakia=0,DemocraticRepublicoftheCongo=0,Denmark=0,Djibouti=0,Dominica=0,DominicanRepublic=0,DuchyofParma=0,
EastGermany=0,GermanDemocraticRepublic=0,Ecuador=0,Egypt=0,ElSalvador=0,EquatorialGuinea=0,Eritrea=0,Estonia=0,Eswatini=0,Ethiopia=0,FederalGovernmentofGermany=0,Fiji=0,Finland=0,France=0,Gabon=0,Gambia=0,Georgia=0,Germany=0,Ghana=0,GrandDuchyofTuscany=0,
Greece=0,Grenada=0,Guatemala=0,Guinea=0,GuineaBissau=0,Guyana=0,Haiti=0,Hanover=0,HanseaticRepublics=0,Hawaii=0,Hesse=0,HolySee=0,Honduras=0,Hungary=0,Iceland=0,India=0,Indonesia=0,Iran=0,Iraq=0,Ireland=0,Israel=0,Italy=0,Jamaica=0,Japan=0,Jordan=0,Kazakhstan=0,Kenya=0,KingdomofSerbia=0,KingdomofYugoslavia=0,
Kiribati=0,Korea=0,Kosovo=0,Kuwait=0,Kyrgyzstan=0,Laos=0,Latvia=0,Lebanon=0,Lesotho=0,LewChew=0,Loochoo=0,Liberia=0,Libya=0,Liechtenstein=0,Lithuania=0,Luxembourg=0,Madagascar=0,Malawi=0,Malaysia=0,Maldives=0,Mali=0,Malta=0,MarshallIslands=0,Mauritania=0,Mauritius=0,MecklenburgSchwerin=0,MecklenburgStrelitz=0,
Mexico=0,Micronesia=0,Moldova=0,Monaco=0,Mongolia=0,Montenegro=0,Morocco=0,Mozambique=0,Namibia=0,Nassau=0,Nauru=0,Nepal=0,Netherlands=0,NewZealand=0,Nicaragua=0,Niger=0,Nigeria=0,NorthGermanConfederation=0,NorthGermanUnion=0,NorthMacedonia=0,Norway=0,Oldenburg=0,Oman=0,OrangeFreeState=0,Pakistan=0,Palau=0,
Panama=0,PapalStates=0,PapuaNewGuinea=0,Paraguay=0,Peru=0,Philippines=0,PiedmontSardinia=0,Poland=0,Portugal=0,Qatar=0,RepublicofGenoa=0,RepublicofKorea=0,SouthKorea=0,RepublicoftheCongo=0,Romania=0,Russia=0,Rwanda=0,SaintKittsandNevis=0,SaintLucia=0,SaintVincentandtheGrenadines=0,Samoa=0,
SanMarino=0,SaoTomeandPrincipe=0,SaudiArabia=0,SchaumburgLippe=0,Senegal=0,Serbia=0,Seychelles=0,SierraLeone=0,Singapore=0,Slovakia=0,Slovenia=0,SolomonIslands=0,Somalia=0,SouthAfrica=0,SouthSudan=0,Spain=0,SriLanka=0,Sudan=0,Suriname=0,Sweden=0,Switzerland=0,Syria=0,Tajikistan=0,Tanzania=0,Texas=0,Thailand=0,
TimorLeste=0,Togo=0,Tonga=0,TrinidadandTobago=0,Tunisia=0,Turkey=0,Turkmenistan=0,Tuvalu=0,TwoSicilies=0,Uganda=0,Ukraine=0,UnionofSovietSocialistRepublics=0,UnitedArabEmirates=0,UnitedKingdom=0,Uruguay=0,Uzbekistan=0,Vanuatu=0,Venezuela=0,Vietnam=0,Wurttemberg=0,Yemen=0,Zambia=0,Zimbabwe=0;
char * s []= {"Thailand","ab"};
int lencountry = sizeof(countrylist)/sizeof(countrylist[0]);
int lenprovince = sizeof(s)/sizeof(s[0]);
for(int i = 0; i < lencountry; ++i)
{
for(int j=0; j<lenprovince; j++)
{
if(!strcmp(countrylist[i], s[j]))
{
//I think I need to show do int++ here but I don't know how to do it
//maybe know the location of countrylist[i] and make the program know
//where to add 1 to int
}
}
}
}
but this is just what I think and try to do but my skill is not enough, If you can tell me how to do it please tell me and if you have the skills to make it done please show me how.
Thank you very much to every person that helps me.
A: You should definitely not use single variables for each country. Instead use an array.
This can be done in multiple flavors:
*
*Use a VLA matching your list of names:
...
int lencountry = sizeof(countrylist)/sizeof(countrylist[0]);
int countrycounts[lencountry]; // VLA cannot be initialized
for (int i = 0; i<lencountry; i++)
{
countrycounts[i] = 0;
}
Then you can simply increment the corresponding index in that array:
if(!strcmp(countrylist[i], s[j]))
{
countrycounts[i]++;
}
*Use a struct and store counter together with names.
typedef struct {
const char *name;
int count;
} country_t;
country_t countrylist[] = {
{ .name = "Laotian / Lao"},
{ .name = "Afghanistan"},
{ .name = "Albania"},
...
{ .name = "Zambia"},
{ .name = "Zimbabwe"}
};
The remaining fields (here: count) in the struct are automatically initialized to 0 if not all fields are specified.
Then you can compare like this:
if(!strcmp(countrylist[i].name, s[j]))
{
countrylist[i].count++;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69785315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unique question - Alien Invasion - Pygame I'm creating Alien Invasions from Chapter 12 in Python Crash Course. It's saying:
error Traceback (most recent call last)
<ipython-input-13-0a7dc30aa722> in <module>()
22 if __name__ == "__main__":
23 # Make a game instance, and run the game.
---> 24 ai = AlienInvasion()
25 ai.run_game()
<ipython-input-13-0a7dc30aa722> in __init__(self)
5 """initialize the game, and create game resources."""
6 pygame.init()
----> 7 self.screen = pygame.display.set_mode((1200, 800))
8 pygame.display.set_caption("Alien Invasion")
9
error: No available video device
Here's the code:
import pygame
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
"""Start the main loop for the game"""
while True:
#Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == "__main__":
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
(Colab)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62985393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what obj files can be added to nglview? I am making an iphone app according to this tutorial http://www.icodeblog.com/2012/09/07/3856/ however, when trying to replace the 3d obj(earth) with some obj file of mine, it does not work, is there any specific requirements for the obj file added to nglview?
This is the viewdidload part:
NGLView *tmpView = [[NGLView alloc] initWithFrame:CGRectMake(110, 110, 140, 140)];
// Set its delegate to self so the drawview method is used.
tmpView.delegate = self;
// Add the new view on top of our existing view.
[self.view addSubview:tmpView];
tmpView.contentScaleFactor = [[UIScreen mainScreen] scale];
// Setup some initial environment states to be applied to our mesh.
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
kNGLMeshOriginalYes, kNGLMeshKeyOriginal,
@"1", kNGLMeshKeyNormalize, nil];
// Initialize the mesh which includes the model file to import (.obj or .dae).
_mesh = [[NGLMesh alloc] initWithFile:@"PAN.obj" settings:settings delegate:nil];
// Initialize the camera used to render the scene.
_camera = [[NGLCamera alloc] initWithMeshes:_mesh, nil];
// If a trasparent background of the NGLView is needed
tmpView.backgroundColor = [UIColor clearColor];
nglGlobalColorFormat(NGLColorFormatRGBA);
nglGlobalFlush();
A: nglview is a part of NinevehGL framework .
NinevehGL is a 3D engine forged with pure Obj-C
Here is the community forum for beginners
You can find the basic lessons here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15401201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How To Define API Blueprint X-Auth-Token Header I have a number of services that require an X-Auth-Token header to be sent similar to the below:
X-Auth-Token: 2e5db4a3-c80f-4cfe-ad35-7e781928f7a2
I would like to be able to specify this in my API documentation following the API Blueprint standard. However, from what I can tell from the API Blueprint headers section definition, you can only specify literal values (e.g. Accept-Charset: utf-8) and not a schema for what the header should look like (e.g. something like X-Auth-Token (string)).
I get the impression that Traits might help with this problem but it's a little over my head at the moment. Can anyone tell me how to specify that all requests to a given action (or set of actions) require an X-Auth-Token header?
A: You are right about not being able to define a schema for headers. Unfortunately, API Blueprint doesn't support it yet.
Until something like that is supported, you can use the literal value for the header like the following:
+ Headers
X-Auth-Token: 2e5db4a3-c80f-4cfe-ad35-7e781928f7a2
API Blueprint also does not support any Traits currently. I am afraid you might have been confused by reading other feature requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29873140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to compare two column value in GridView? protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string[] Cardio = (string[])objDocter.getDocter_acc_prof();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text == "Heart problem")
{
DropDownList ddlAssignDoc
= (DropDownList)e.Row.FindControl("ddlAssignDoc");
ddlAssignDoc.DataSource = Cardio;
ddlAssignDoc.DataBind();
}
}
}
i want to compare two template column in grid view,
but it is not working ..............please give the right way to compare two columns of GridView. Thank You
A: Template columns render their own content. You would have to get each control and compare the two controls within the template, by using FindControl as you do and comparing the underlying value. Cell.Text is only useful for bound controls.
A: if (((Label)e.Row.FindControl("lblProblemName")).Text == "Heart problem")
{
DropDownList ddlAssignDoc
= (DropDownList)e.Row.FindControl("ddlAssignDoc");
ddlAssignDoc.DataSource = Cardio;
ddlAssignDoc.DataBind();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3686524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to distinguish Alt press and Alt + 3 press I have a problem how to distinguish Alt press and Alt + 3 press.
I have two diference action.
Alt - show menu bar
Alt + 3 - add 3th pane into my main window.
How do I distinguish between these two events? Problém is (in this moment) that when I press Alt + 3. Booth actions is called.
void cc::keyPressEvent(QKeyEvent * event)
{
switch (event->key())
{
case Qt::Key_3:
if(event->modifiers() == Qt::AltModifier)
{
if(ui->widget_3->isVisible())
ui->widget_3->hide();
else
ui->widget_3->show();
}
break;
case Qt::Key_Alt:
if(!menuBar()->isVisible())
ui->menuBar->show();
else
ui->menuBar->hide();
break;
default: QWidget::keyPressEvent(event);
}
}
I known, that I can use counter and wait some time and show menu when time is end (2s). If user press Alt+3 and if he was not pressed it for 2s, I show 3. pane only. If they press alt only for 3s, I show menu.
It seems kind of complicated. Can't I do something simpler?
A: You should put the code related to Alt-only shortcut in a void cc::keyReleaseEvent(QKeyEvent * event) event. this event happens once a key is released.
So when you press Alt, nothing happens, if you release it, the "show menu bar" will happen, but if you keep pressing and press 3, then the other code will happen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34490301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to show videos in gridview ! (Flutter) I am getting the video files from filepicker package now i want to show the videos on gridview when clicked on them video should be played (similar to gallery)
A: Found answer my self first I generated the thumbnail of the video by thumbnail package(https://pub.dev/packages/video_thumbnail) from then saved created a model of thumbnail path and video path saved the path of both and accessed them :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74641871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP - Efficient way to check if subdomain exists
Possible Duplicate:
PHP function to get the subdomain of a URL
Im looking for an efficient way to tell if a subdomain exists within a URL.
The domain name will always be fixed e.g. mydomin.com, however if a subdomain is not set, I need to redirect.
One thought I had is that if there is more than one period (.), a subdomain is set, but im not sure how to implement this.
Many thanks.
EDIT: Sorry for not being too clear. I do not have a current solution, but looking at other posts I can see several examples of how to get the subdomain e.g.
array_shift(explode(".",$_SERVER['HTTP_HOST']));
But i do not want the subdomain, just to check if one exists. The subdomain could be anything.
A: I would rather use apache rewrite engine (or any webserver rewrite process) :
# .htaccess file
RewriteCond %{HTTP_HOST} ^yourdomin\.com$
RewriteRule (.*) http://sub.yourdomin.com/$1 [R=301,L]
A: You can get the hostname with parse_url. Then you break it down with explode():
function hasSubdomain($url) {
$parsed = parse_url($url);
$exploded = explode('.', $parsed["host"]);
return (count($exploded) > 2);
}
On google you can find really easily how to redirect someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12759166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sleep function on php As a possible alternative to using cron jobs, I found the sleep function. I have never used this before.
If I tell my script to run inside a kind of loop, and inside that loop I have an instruction like this
# sleeps for 86400 seconds or one day
sleep(86400);
will my script be launched again after 1 day? even if don't access it on my web browser again within that period?
I think is not possible, but I'm here to ask an expert about it.
A: The script will timeout. You need to set it so that it won't timeout using set_time_limit.
A: I wouldn't do this I would either use a cron (that is a link) job if it is a regular task or an at (that is a link) job if the job is added at the run time of your script.
cron allows you to run a recurring job every day at 1pm for example whereas at allows you to schedule a job to run once for now +1day for example.
I have written a PHP 5.3 wrapper for the at queue if you choose to go down that route. It is available on GitHub https://github.com/treffynnon/PHP-at-Job-Queue-Wrapper
A: The main problem with using PHP this way is, in my experience, not web server timeouts (there are ways to handle that with difficulty varying on the server and the platform) but memory leaks.
Straightforward PHP code tends to leak a lot of memory; most of the scripts I wrote were able to do hundreds of times as many work after I did some analysis and placed some unsets. And I was never able to prevent all the leaks this way. I'm also told there are memory leaks in the standard library, which, if true, makes it impossible to write daemons that would run for a long time in loops.
A: There is also time_sleep_until(). Maybe more useful to wake up on a specific time...
A: If you access the script through a web browser, it will be terminated after 30 seconds.
If you start the PHP script on the command line, this could work.
A: It would work, but your "startup time" will be subject to drift. Let's say your job takes 10 seconds to run, then sleeps 86400, runs another 10, sleeps 86400, etc.. You start it exactly at midnight on day 1. On Day 2 it'll run at 12:00:10am, on day 3 it's 12:00:20am, etc...
You can do some fancy math internally to figure out how long the run took, and subtract that from the next sleep call, but at the point, why not use cron? With cron the script will exit after each run, cleaning up memory and resources used. With your sleep method, you'll have to be VERY careful that you're not leaking resources somewhere, or things will eventually grind to a halt.
A: I had a similar problem before and found a php cron parsing class that will allow you to execute php similar to running crons. You can tie it to a commonly accessed script on your site if you don't have access to run crons directly.
I actually use this script as part of a larger cron job script:
*
*a cron job runs every hour
*an xml file for each sub-cron with a cron-like time component(i.e.- * */2 * * * php /home..)
*the sub-cron script that will run if the current time meets the criteria of the sub-cron time component
*a user interface is setup so that I don't have to manually add/remove sub-crons from the main cron
The cronParser class is here.
A: Many correct answers, but: Using sleep() means your script keeps running, and keeps using memory. Raising the default timeout of 30s will work, but again, this is bad idea. I suggest you use crontasks.
A: This is why legitimate cron jobs were invented. Just use crontab. Using a PHP script to do it will be EXTRAORDINARILY unreliable, buggy, and poorly timed.
Hope this is insightful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4206226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Submit form with on another website They have a selector on example.com. And my Nodejs server is running on myserver.com
<form method="POST" name="formname">
<select name="selector" onchange="document.forms['formname'].submit();">
When you select an option it updates the content of the page.
How can I simulate selecting the First option on example.com from myserver.com to receive the page content (only nodejs).
(I think the best solution would be with the Request module)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46221374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display two strings next to each other in a single-line where the right string is always fully visible and left one truncated if too long? On my dynamically generated HTML page, I have a limited-width DIV container. Inside it, there are several rows (DIVs) which display "name" and "value" pairs (two SPANs next to each other). This is how it currently looks:
The "value" SPANs have "float:right" so that they are right aligned to the edge of the container.
I need your help with the following:
If the total width of "name" plus "value" SPANs is larger that the width of the container, I need the "value" to be always fully visible and "name" to be truncated (preferably by using ellipsis). And nothing should ever wrap to the next line.
So, for example, if the value of "occupancy_timeout" was "123456789", I need this line to be displayed as "occupancy_tim...123456789".
If this can be done easier in another way (i.e. without using two SPANs inside a single line DIV), that's perfectly acceptable too.
A: Since I used display: flex in my solution I used margin-left: auto instead of float: right and I assumed the max-width: 160px. You can use your own value.
.wrapper{
max-width: 160px;
}
.inner{
display: flex;
}
.right{
margin-left: auto;
}
.left{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div class='wrapper'>
<div class='inner'>
<span class='left'>Name</span>
<span class='right'>Value</span>
</div>
<div class='inner'>
<span class='left'>id:</span>
<span class='right'>123456789012345678</span>
</div>
<div class='inner'>
<span class='left'>occupancy_timeout</span>
<span class='right'>10000</span>
</div>
<div class='inner'>
<span class='left'>led_indication</span>
<span class='right'>true</span>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67332161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transform a column into variables in R My current dataset :
order product
1 a
1 b
1 c
2 b
2 d
3 a
3 c
3 e
what I want
product order
a 1,3
b 1,2
c 1,3
d 2
e 3
I have tried cast, reshape, but they didn't work
A: I recently spent way too much time trying to do something similar. What you need here, I believe, is a list-column. The code below will do that, but it turns the order number into a character value.
library(tidyverse)
df <- tibble(order=c(1,1,1,2,2,3,3,3), product=c('a','b','c','b','d','a','c','e')) %>%
group_by(product) %>%
summarise(order=toString(.$order)) %>%
mutate(order=str_split(order, ', ')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45247286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ViewPagerIndicator tabs loses content I am using Holoeverywhere and ViewPagerIndicator; using Holoeverywhere1 I implemented the slider and tabs in the Fragment using ViewPagerIndicator. Everything is working fine, Slider working, the menu in it, the tabs; the tabs works fine only the first time, when I move to other Fragment using the slider and come back to the tabs Fragment, the contents are no more available.
Code for the Fragment where tabs are created
public class SeconFrag extends Fragment {
ViewPager mViewPager;
FragmentAdapter mTabsAdapter;
PageIndicator mIndicator;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabsAdapter = new FragmentAdapter(getSupportFragmentManager());
View view = inflater.inflate(R.layout.second_frag);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mTabsAdapter);
TitlePageIndicator indicator = (TitlePageIndicator) view
.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
indicator.setFooterIndicatorStyle(IndicatorStyle.Triangle);
mIndicator = indicator;
return view;
}
@Override
public void onResume() {
super.onResume();
getSupportActionBar().setSubtitle("Create");
}
}
FragmentAdapter code
public class FragmentAdapter extends FragmentPagerAdapter{
protected static final String[] CONTENT = new String[] { "Choose", "Customise" };
private int mCount = CONTENT.length;
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return TabOne.newInstance();
} else if (position == 1) {
return TabTwo.newInstance();
}else if (position == 3 ) {
return TabOne.newInstance();
}else
return null;
}
@Override
public int getCount() {
return mCount;
}
@Override
public CharSequence getPageTitle(int position) {
return FragmentAdapter.CONTENT[position % CONTENT.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
on of the tab Fragment
public final class TabOne extends Fragment {
public static TabOne newInstance() {
TabOne fragment = new TabOne();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.tab_one, container,
false);
return myFragmentView;
}
}
in the SeconFrag OnPause() I removed the Fragment no luck, hide() it in the OnPause() and tried to show() in the OnResume() still not showing content after the Fragment is changed.
EDIT
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16687339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: STR_TO_DATE not working in my query I have date field in database having varchar datatype. Now I have to compare date with the current date but because of data type(varchar) result is not coming properly.
I don't want to change datatype in database so how can I query in codeigniter ?
In my database date is in this format 30/11/2015
My current query:
//here vd is table field(one column).
$cd = date('d/m/Y');//current date
$this->db->where("date_format(STR_TO_DATE(vd, '%d/%m/%Y'),'%d/%m/%Y') >",$cd); //comparing date with current date
$query =$this->db->get('warranty');
By using above query it is just comparing the date not month and year. So it is returning those record which date is greater than today's date.
But proper result is not coming....
A: Try this may be it will helps you :
$cd = date('Y-m-d');
$this->db->where("date_format(STR_TO_DATE(vd, '%d/%m/%Y'),'%Y-%m-%d') >",$cd);
$query =$this->db->get('warranty');
You need to change date format if you use date_format in your query you are changing in same format may be that is the reason it is not working. try to change and compare in Y-m-d format.
A: Can you check this query manually. Then try to add it in CodeIgniter
$cd = date('d/m/Y');//current date
select * FROM warranty WHERE DATE_FORMAT(STR_TO_DATE(vd, '%d/%m/%Y'), '%Y-%m-%d') > DATE_FORMAT(STR_TO_DATE($cd, '%d/%m/%Y'), '%Y-%m-%d')
A: In your code you are using two function to restructure the date format.
*
*date_format
*STR_TO_DATE
Use STR_TO_DATE
$now = date('d/m/Y'); //current date
$userdate = '2009-05-18 22:23:00'; //which get from user inputs
$dateModified = STR_TO_DATE($userdate,'%d/%m/%Y'); //output is 2009-05-18
So in function
$this->db->where('order_date >=', $dateModified);
$this->db->where('order_date <=', $now);
$query =$this->db->get('warranty');
or
$this->db->where('order_date BETWEEN '.$dateModified.' and '.$now);
This function will give you result of userSearch input and date to now. This function simply act like between in MySQL
A: **Hope this may help you...**
$cd = date('d/m/Y');
$data['project'] = $this->common_model->selectRecord("SELECT * from project where project_date = '.$cd.'");
in my project this is working ..
A: Try this:
$cd = date('d.m.Y');//current date
$this->db->where("STR_TO_DATE(vd, '%d.%m.%Y') >",$cd);
$query =$this->db->get('warranty');
To be sure that it comes out in the format you desire, use DATE_FORMAT:
$cd = date('d.m.Y');//current date
$this->db->where("DATE_FORMAT(STR_TO_DATE(vd, '%d.%m.%Y'),'%d.%m.%Y') >",$cd);
$query =$this->db->get('warranty');
A: Have you tried CAST ?
SELECT * FROM warranty WHERE CAST(vd AS DATE) ....;
Have you tried DATE ?
SELECT * FROM warranty WHERE DATE(vd) ....;
A: Change this
$this->db->where("date_format(STR_TO_DATE(vd, '%d/%m/%Y'),'%d/%m/%Y') >",$cd);
To
$this->db->where("STR_TO_DATE(vd, '%d/%m/%Y') > NOW()");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33968524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: 'Splitting' List into several Arrays I'm trying to complete a Project that will show total annual sales from an specific list contained in a .txt file.
The list is formatted this way:
-lastname, firstname (string)
-45.7 (float)
-456.4 (float)
-345.5 (float)
-lastname2, firstname2 (string)
-3354.7 (float)
-54.6 (float)
-56.2 (float)
-lastname3, firstname3 (string)
-76.6 (float)
-34.2 (float)
-48.2 (float)
And so on.... Actually, 7 different "employees" followed by 12 set of "numbers" (months of the year)....but that example should suffice to give an idea of what I'm trying to do.
I need to output this specific information of every "employee"
-Name of employee
-Total Sum (sum of the 12 numbers in the list)
So my logic is taking me to this conclusion, but I don't know where to start:
Create 7 different arrays to store each "employee" data.
With this logic, I need to split the main list into independent arrays so I can work with them.
How can this be achieved? And also, if I don't have a predefined number of employees (but a defined format :: "Name" followed by 12 months of numbers)...how can I achieve this?
I'm sure I can figure once I get an idea how to "split" a list in different sections -- Every 13 lines?
A: Yes, at every thirteenth line you'd have the information of an employee.
However, instead of using twelve different lists, you can use a dictionary of lists, so that you wouldn't have to worry about the number of employees.
And you can either use a parameter on the number of lines directed to each employee.
You could do the following:
infile = open("file.txt", "rt")
employee = dict()
name = infile.readline().strip()
while name:
employee[name] = list()
for i in xrange(1, 12):
val = float(infile.readline().strip())
employee[name].append(val)
name = infile.readline().strip()
Some ways to access dictionary entries:
for name, months in employee.items():
print name
print months
for name in employee.keys():
print name
print employee[name]
for months in employee.values():
print months
for name, months in (employee.keys(), employee.values()):
print name
print months
The entire process goes as follows:
infile = open("file.txt", "rt")
employee = dict()
name = infile.readline().strip()
while name:
val = 0.0
for i in xrange(1, 12):
val += float(infile.readline().strip())
employee[name] = val
print ">>> Employee:", name, " -- salary:", str(employee[name])
name = infile.readline().strip()
Sorry for being round the bush, somehow (:
A: Here is option.
Not good, but still brute option.
summed = 0
with open("file.txt", "rt") as f:
print f.readline() # We print first line (first man)
for line in f:
# then we suppose every line is float.
try:
# convert to float
value = float(line.strip())
# add to sum
summed += value
# If it does not convert, then it is next person
except ValueError:
# print sum for previous person
print summed
# print new name
print line
# reset sum
summed = 0
# on end of file there is no errors, so we print lst result
print summed
since you need more flexibility, there is another option:
data = {} # dict: list of all values for person by person name
with open("file.txt", "rt") as f:
data_key = f.readline() # We remember first line (first man)
data[data_key] = [] # empty list of values
for line in f:
# then we suppose every line is float.
try:
# convert to float
value = float(line.strip())
# add to data
data[data_key].append(value)
# If it does not convert, then it is next person
except ValueError:
# next person's name
data_key = line
# new list
data[data_key] = []
Q: let's say that I want to print a '2% bonus' to employees that made more than 7000 in total sales (12 months)
for employee, stats in data.iteritems():
if sum(stats) > 7000:
print employee + " done 7000 in total sales! need 2% bonus"
A: I would not create 7 different arrays. I would create some sort of data structure to hold all the relevant information for one employee in one data type (this is python, but surely you can create data structures in python as well).
Then, as you process the data for each employee, all you have to do is iterate over one array of employee data elements. That way, it's much easier to keep track of the indices of the data (or maybe even eliminates the need to!).
This is especially helpful if you want to sort the data somehow. That way, you'd only have to sort one array instead of 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13664768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to remove index.php in url while working on Codeigniter-WAMP i have seen many questions about my problem there are number of solutions i tried them all!i'm facing this problem from from 24 hours and not able to move forward.
these steps i have taken simply.
1)install codeigniter.
2)enable rewrite_mod by removing # sign.in appache httpd.conf file
3)these changings in confing.php file
$config['base_url'] = 'http://localhost/ciblog';
$config['index_page'] = '';
4)new .htaccess file in www/ciblog folder which have these lines
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|
uploads|favicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]
and it troughs an error that
"The requested URL /ciblog/welcome was not found on this server."
Please help me specifically i'm using WAMP server.
thnks in advance.
A: Set up a VHOST.
in /etc/hosts (or c:/windows/system32/drivers/etc/hosts) add:
127.0.0.1 dev.whatever.com
Then, in Apache's conf/extra/httpd-vhosts.conf, set up your VirtualHost, here's an example:
<VirtualHost *:80>
DocumentRoot "/var/www/bonemvc/public"
ServerName dev.whatever.com
FallbackResource index.php
<Directory "/var/www/bonemvc">
DirectoryIndex index.php
Options -Indexes +FollowSymLinks
AllowOverride none
Require all granted
</Directory>
BrowserMatch ".*MSIE.*" nokeepalive downgrade-1.0 force-response-1.0
</VirtualHost>
Finally, open Apache's httpd.conf and look for vhost, uncomment the line so the other conf file will load.
Close your browsers, restart apache, reopen your browser, and head to http://dev.whatever.com. You should get your home page without the index.php showing!
A: Try using following htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
And Also you need to search and replace
$config['uri_protocol'] ="AUTO"
by
$config['uri_protocol'] = "REQUEST_URI"
in config.php
A: Try with this code in .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
I Hope this working fine for xampp and wamp server
if you still have issue so please share details with me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46341038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting table Values in Jquery I have a small form which takes the values name (TextBox), age(textbox) , Education(select box with values"Bachelors" and "Masters").
So I have a Button with the "ADD" which adds the values to database and displays it in a table format.
Iam having the table with 10 rows and each row is identified . So I have two Buttons such as select and Cancel
When We say select the Values in the table should go their Respective boxes name value should go to name box and Age Value should go their age box and so on..
How can i acheive this using Jquery
A: For HTML like this:
...
<div>
<label for="NameTextBox">Name:</label>
<input type="text" id="NameTextBox" />
</div>
<div>
<label for="AgeTextBox">Age:</label>
<input type="text" id="AgeTextBox" />
</div>
<div>
<label for="EducationSelect">Education:</label>
<select id="EducationSelect">
<option value="Bachelors">Bachelors</option>
<option value="Masters">Masters</option>
</select>
</div>
<input type="button" value="Add" />
<table>
<tr>
<th></th>
<th>Name</th>
<th>Age</th>
<th>Education</th>
</tr>
<tr>
<td><input type="button" id="row1" value="Select" /></td>
<td>Name1</td>
<td>44</td>
<td>Bachelors</td>
</tr>
<tr>
<td><input type="button" id="row2" value="Select" /></td>
<td>Name2</td>
<td>32</td>
<td>Masters</td>
</tr>
</table>
...
The following jQuery expression will copy the values from the selected row into the form on 'Select' button click:
$(function()
{
$("table input").click(function(event)
{
$("#NameTextBox").val($("tr").has("#" + event.target.id).find("td:nth-child(2)").html());
$("#AgeTextBox").val($("tr").has("#" + event.target.id).find("td:nth-child(3)").html());
$("#EducationSelect").val($("tr").has("#" + event.target.id).find("td:nth-child(4)").html());
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3326872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are POST requests cached in Django? I want to get some view cached depending on the POST data sent to it.
Does the django.views.decorators.cache.cache_page decorator do that automatically or do I need to tweak it somehow? In the latter case, how should I do that?
I'm trying to cache GraphQL POST requests.
A: No, POST responses are never cached:
if request.method not in ('GET', 'HEAD'):
request._cache_update_cache = False
return None # Don't bother checking the cache.
(from FetchFromCacheMiddleware in django.middleware.cache).
You'll have to implement something yourself using the low-level cache API. It's most unusual to cache a response to a POST request, since a POST request is meant to change things in the database and the result is always unique to the particular request. You'll have to think about what exactly you want to cache.
A: I ended up creating a custom decorator which caches responses based on request path, query parameters, and posted data:
# myproject/apps/core/caching.py
import hashlib
import base64
from functools import wraps
from django.core.cache import cache
from django.conf import settings
def make_hash_sha256(o):
hasher = hashlib.sha256()
hasher.update(repr(make_hashable(o)).encode())
return base64.b64encode(hasher.digest()).decode()
def make_hashable(o):
if isinstance(o, (tuple, list)):
return tuple((make_hashable(e) for e in o))
if isinstance(o, dict):
return tuple(sorted((k,make_hashable(v)) for k,v in o.items()))
if isinstance(o, (set, frozenset)):
return tuple(sorted(make_hashable(e) for e in o))
return o
def cache_get_and_post_requests(duration=600):
def view_decorator(view):
@wraps(view)
def view_wrapper(request, *args, **kwargs):
# TODO: make the key also dependable on the user or cookies if necessary
cache_key = "-".join((
settings.CACHE_MIDDLEWARE_KEY_PREFIX,
make_hash_sha256((
request.path,
list(request.GET.items()),
list(request.POST.items()),
request.body,
)),
))
cached_response = cache.get(cache_key)
if cached_response:
return cached_response
response = view(request, *args, **kwargs)
cache.set(cache_key, response, duration)
return response
return view_wrapper
return view_decorator
Then I can use it in the URL configuration like so:
# myproject/urls.py
from django.urls import path
from django.conf.urls.i18n import i18n_patterns
from graphene_django.views import GraphQLView
from myproject.apps.core.caching import cache_get_and_post_requests
urlpatterns = i18n_patterns(
# …
path("graphql/", cache_get_and_post_requests(60*5)(GraphQLView.as_view(graphiql=True))),
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59373446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get a child window to send keys back down? I am almost certainly missing something completely obvious. I have a singleton main form with various menu items with shortcuts. I have child windows which can be embedded on the main form or floating on their own. The main form class has a static member that points to the one extant main form, so the child windows can access its public functions. I want the hotkeys normally linked to the toolbar entries to work from the child windows, and I'd prefer not to duplicate the code. I know I have to invoke a keypress event on the main form, but I am running a complete blank today.
To give a simple example, there are menu items to save the current file and to center the window on the point the mouse is at, triggered by Ctrl+S and Ctrl+E respectively. They're set up as keyboard shortcuts in my Main Form, but the actual heavy lifting is done by my child window for the latter command. I have it temporarily fixed by catching a KeyDown event in my child window, but that means two different places that the same shortcut shows up.
A: There seem to be few solutions to handle key shortcuts.
One of them could be installing keyboard hooks as suggested here.
You can also try to handle this by adding custom message filter, as suggested here, however, I haven't verified the code posted there.
The solution with hooks seems to be a little tricky, so You may want to try custom message filter first.
A: As per my comments to Lukasz M above, I needed to maintain the current menu structure for legacy reasons, namely that all of the engineers are accustomed to changing the Menu, and they want the menu shortcuts to automatically work. I could probably modify the central hotkey location using that custom message filter to generate Shortcut text for the Menu items, but that would add additional complexity that's likely to be undone the next time someone steps in to add a quick menu item. Thus, I went with the solution I alluded to in the comments with an invisible menu for the child windows.
Much to my surprise, if a menu has its Visible property set to false, the hotkeys work just fine. And the events associated with menu items in the main form work perfectly fine if invoked from a child form, as they're executed relative to the window where they are defined rather than by the window where they're invoked. Thus, my first solution was to fetch the MenuStrip from the main form and add it to the child form. That didn't work, as turning it invisible in the child form made it invisible in the main form as well. My next attempt involved creating a new hidden MenuStrip and adding the ToolStripMenuItem items from the main form's MenuStrip onto it. That broke the hotkey capability, possibly since the menu items now existed in more than one place. Finally, I created shallow copies of the menu items that contained only the shortcut key, the Tag property (necessary for a few menu items that made use of it), and the Event Handler (the last being done through the method described in How to clone Control event handlers at run time?). After a bit of fiddling, I came to realize that I didn't need to maintain the structure of the menus and I only needed the items with shortcuts. This is what I wound up with:
Main Form:
/// <summary>
/// Returns copies of all menu shortcut items in the main form.
/// </summary>
/// <returns>A list containing copies of all of the menu items with a keyboard shortcut.</returns>
public static List<ToolStripMenuItem> GetMenuShortcutClones()
{
List<ToolStripMenuItem> shortcutItems = new List<ToolStripMenuItem>();
Stack<ToolStripMenuItem> itemsToBeParsed = new Stack<ToolStripMenuItem>();
foreach (ToolStripItem menuItem in mainForm.menuStrip.Items)
{
if (menuItem is ToolStripMenuItem)
{
itemsToBeParsed.Push((ToolStripMenuItem)menuItem);
}
}
while (itemsToBeParsed.Count > 0)
{
ToolStripMenuItem menuItem = itemsToBeParsed.Pop();
foreach (ToolStripItem childItem in menuItem.DropDownItems)
{
if (childItem is ToolStripMenuItem)
{
itemsToBeParsed.Push((ToolStripMenuItem)childItem);
}
}
if (menuItem.ShortcutKeys != Keys.None)
{
shortcutItems.Add(CloneMenuItem(menuItem));
}
}
return shortcutItems;
}
/// <summary>
/// Returns an effective shortcut clone of a ToolStripMenuItem. It does not copy the name
/// or text, but it does copy the shortcut and the events associated with the menu item.
/// </summary>
/// <param name="menuItem">The MenuItem to be cloned</param>
/// <returns>The newly generated clone.</returns>
private static ToolStripMenuItem CloneMenuItem(ToolStripMenuItem menuItem)
{
ToolStripMenuItem copy = new ToolStripMenuItem();
copy.ShortcutKeys = menuItem.ShortcutKeys;
copy.Tag = menuItem.Tag;
var eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);
var eventHandlerList = eventsField.GetValue(menuItem);
eventsField.SetValue(copy, eventHandlerList);
return copy;
}
Child Form:
private void OnRefresh(object sender, EventArgs e)
{
// Refresh the hiddenShortcutMenu.
List<ToolStripMenuItem> shortcutList = MainForm.GetMenuShortcutClones();
hiddenShortcutMenu.Items.Clear();
hiddenShortcutMenu.Items.AddRange(shortcutList.ToArray());
}
Inside the child form's constructor, I instantiated the hiddenShortcutMenu, set Visible to false, assigned it to my child form's control, and set the event. The last was a bit fiddly in that I had to have it periodically refresh since the menus sometimes changed according to context. Currently, I have it set to the Paint event for maximum paranoia, but I think I'm going to try to find a way for the main form to signal that it's changed the menu structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23227685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to concatenate a patchValue number with a string in angular forms? This is my TS
ngOnInit() {
this.editProfileForm = new FormGroup({
firstNumber: new FormControl(null, {
validators: [Validators.required],
})
}
}
fetchNumber() {
this.nameService.fetchName().subscribe(
() => {
this.editProfileForm.patchValue({
firstNumber: this.profileData.firstnumber,
});
},
);
}
my HTML
<ion-col>
<ion-input
*ngIf="nameData"
type="number"
inputmode="numeric"
formControlName="firstNumber"
placeholder="First number" >
<ion-button clear icon-only fill="clear">
<ion-icon [src]="icons.info"></ion-icon>
</ion-button>
</ion-input>
</ion-col>
What I want to achieve is when I have my input in HTML that gets filled with the value of firstNumber to add also the string "%". I've tried with "+"
firstNumber: this.profileData.firstNumber + "%";
, putting "%" in a variable and still doesn't work. If you guys have any if this can be done I would really appreciate it.
A: Add the % in the input field using pipe
first create the formcontrolname and bind the value in the input text
<input type="text" formControlName="amount" [value]="myform.get('controlname')|pipe">
i attached the stackbliz,kindly refer it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64772383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Interprocess Communication in C, one character at a time First off, this IS homework, I am not asking for an answer, however I am confused about something.
I have a homework assignment for a programming class, and I am a little confused about how to write the code the specific way that the instructor is asking.
The program first creates a child process, and then proceeds to send command line arguments from the parent process, through a pipe, ONE CHARACTER at a time to the child process, and then read them into the child process ONE CHARACTER at a time, incrementing the character count in the child process each time a character is read in.
I think I accomplished sending the data through the pipe one character at a time, but I have no idea how to "go" to the child process every time a character is sent, read it, increment the number of characters, and then go back to the parent process and repeat.
Here is my code, It works and gives accurate answers, but any tips on how to accomplish what my instructor is asking would be appreciated, thank you!!
// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
//
// Child process counts number of characters sent through pipe.
//
// Child process returns number of characters counted to parent process.
//
// Parent process prints number of characters counted by child process.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
// set up pipe
int pA[2];
char buff[50];
pipe(pA);
// call fork()
pid_t childId = fork();
if (childId == 0) {
// -- running in child process --
int nChars = 0;
// close the output side of pipe
close(pA[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.
nChars = read(pA[0], buff, sizeof(buff)); //this line of code is what i need to change to be reading characters in one at a time
// Return number of characters counted to parent process.
return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
int size = 0;
printf("CS201 - Assignment 3 - Timothy Jensen\n");
// close the input side of the pipe
close(pA[0]);
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
for (int i = 1; i < argc; i++)
{
size = strlen(argv[i]);
for (int z = 0; z < size; z++)
{
write(pA[1], &argv[i][z], 1);
}
}
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
wait(&nChars);
printf("child counted %d chars\n", nChars/256);
return 0;
}
}
A: You need to make the following changes:
*
*Make the last argument 1 in the call to read.
read(pA[0], buff, 1);
*Put the above call in a while loop and increment nChar for every successful attempt at read.
while ( read(pA[0], buff, 1) == 1 )
{
++nChars;
}
*Close the file descriptor from the parent process once you are done writing to it.
Here's a working version of main.
int main(int argc, char **argv)
{
// set up pipe
int pA[2];
char buff[50];
pipe(pA);
// call fork()
pid_t childId = fork();
if (childId == 0) {
// -- running in child process --
int nChars = 0;
// close the output side of pipe
close(pA[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.
while ( read(pA[0], buff, 1) == 1 )
{
++nChars;
}
return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
int size = 0;
printf("CS201 - Assignment 3 - Timothy Jensen\n");
// close the input side of the pipe
close(pA[0]);
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
for (int i = 1; i < argc; i++)
{
size = strlen(argv[i]);
for (int z = 0; z < size; z++)
{
write(pA[1], &argv[i][z], 1);
}
}
close(pA[1]);
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
wait(&nChars);
printf("child counted %d chars\n", nChars/256);
return 0;
}
}
A: It seems a little silly, but you could change:
nChars = read(pA[0], buff, sizeof(buff));
to:
char ch;
nChars = read(pA[0], &ch, 1);
Of course, you would put the above into a loop to assemble a string 'one character at a time' back into buff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23977368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scrapy merging chained requests into one I have scenario where I am browsing a shop, going through 10s of pages. Then when I find the item that I want, I will add it to basket.
Finally I want to checkout the basket. The problem is that, with scrapy chaining, it wants to checkout the basket as many times as I have items in basket.
How can I merge the chained requests into one, so after adding 10 items to basket, the checkout is called only once?
def start_requests(self):
params = getShopList()
for param in params:
yield scrapy.FormRequest('https://foo.bar/shop', callback=self.addToBasket,
method='POST', formdata=param)
def addToBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/addToBasket', callback=self.checkoutBasket,
method='POST',
formdata=param)
def checkoutBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/checkout', callback=self.final, method='POST',
formdata=param)
def final(self):
print("Success, you have purchased 59 items")
EDIT:
I tried to make the request in closed event, but it is not running into the request nor callback..
def closed(self, reason):
if reason == "finished":
print("spider finished")
return scrapy.Request('https://www.google.com', callback=self.finalmethod)
print("Spider closed but not finished.")
def finalmethod(self, response):
print("finalized")
A: I think you can manually checkout when spider finished:
def closed(self, reason):
if reason == "finished":
return requests.post(checkout_url, data=param)
print("Spider closed but not finished.")
See closed.
update
class MySpider(scrapy.Spider):
name = 'whatever'
def start_requests(self):
params = getShopList()
for param in params:
yield scrapy.FormRequest('https://foo.bar/shop', callback=self.addToBasket,
method='POST', formdata=param)
def addToBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/addToBasket',
method='POST', formdata=param)
def closed(self, reason):
if reason == "finished":
return requests.post(checkout_url, data=param)
print("Spider closed but not finished.")
A: I solved it by using Scrapy signals and spider_idle call.
Sent when a spider has gone idle, which means the spider has no
further:
*
*requests waiting to be downloaded
*requests scheduled items being
*processed in the item pipeline
https://doc.scrapy.org/en/latest/topics/signals.html
from scrapy import signals, Spider
class MySpider(scrapy.Spider):
name = 'whatever'
def start_requests(self):
self.crawler.signals.connect(self.spider_idle, signals.spider_idle) ## notice this
params = getShopList()
for param in params:
yield scrapy.FormRequest('https://foo.bar/shop', callback=self.addToBasket,
method='POST', formdata=param)
def addToBasket(self, response):
yield scrapy.FormRequest('https://foo.bar/addToBasket',
method='POST', formdata=param)
def spider_idle(self, spider): ## when all requests are finished, this is called
req = scrapy.Request('https://foo.bar/checkout', callback=self.checkoutFinished)
self.crawler.engine.crawl(req, spider)
def checkoutFinished(self, response):
print("Checkout finished")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50791031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.