text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: SpringBoot issues with SessionScope I run a SpringBoot application with MyBatis.
And i have a MyBatis's mapper like this:
@Component
@Mapper
public interface AccountMapper {
@Insert("insert into dc_account(identification,nickname,username,password) values (#{identification},#{nickname},#{username},#{password})")
public int insert(Account account);
@Update("update dc_account set identification=#{identification},nickname=#{nickname},username=#{username},password=#{password}")
public int update(Account account);
@Select("select * from dc_account where username=#{username} and password=#{password}")
@Results(
id = "account",
value = {
@Result(property = "identification", column = "identification"),
@Result(property = "nickname", column = "nickname"),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password")
}
)
Account select(Account account);
}
Account class is:
@Component
@SessionScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Account{
@Value("1")
int identification;
@Value("1")
String nickname;
@Value("1")
String username;
@Value("1")
String password;
//getter and setter
}
Controller:
@Autowired
AccountMapper accountMapper;
@Autowired
Account account;
//.......
@RequestMapping("/login")
Account login(
@RequestParam("username")String username,
@RequestParam("password")String password){
account.setUsername(username);
account.setPassword(password);
accountMapper.select(account);
return account;
}
And when i enter url localhost:8080/login?username=1&password=1
It report
and if i remove the @SessionScope annotation of class Account everything works fine.
I don't know where went wrong...can anybody give some advice?
A: After a whole afternoon's searching.
Here is what i think:
When I change the controller into this code below,everything still works fine.
So there is nothing wrong with mybatis
@RequestMapping("/login")
Account login(
@RequestParam("username")String username,
@RequestParam("password")String password){
account.setUsername(username);
account.setPassword(password);
return accountMapper.select(account);
//return account;
}
But it i change the code slightly into
@RequestMapping("/login")
Account login(
@RequestParam("username")String username,
@RequestParam("password")String password){
account.setUsername(username);
account.setPassword(password);
//return accountMapper.select(account);
return account;
}
It then report the same error message that i mention in the question.
I think the @SessionScope's bean(which is Account class) is already managed by SpringBoot's ioc container,
and if i return the same session scope bean from that controller method,
these two bean point to the same thing,that causing some kind of self-reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61284552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQLite 'BETWEEN' doesn't behave as expected I'm trying to select all rows that fall between two column values. The values are UNIX Timestamps but the query isn't returning any rows at all. Why would that be?
Here's my code:
public static ArrayList<Appointment> getAppointments(long start, long end) {
ArrayList<Appointment> appointments = new ArrayList<>();
try {
Statement stat = db.createStatement();
System.out.println("\n" + start + " -> " + end);
// debugging only
try (ResultSet rs = stat.executeQuery("SELECT * FROM appointments;")) {
while (rs.next()) {
long time = rs.getLong("date");
if (time >= start && time <= end) {
System.out.println("Should be adding to list");
}
}
} //
try (ResultSet rs = stat.executeQuery("SELECT * FROM appointments WHERE date BETWEEN " + start + " AND " + end + ";")) {
while (rs.next()) {
System.out.println("ADDING");
appointments.add(new Appointment(rs.getLong("date"), rs.getInt("duration")));
}
}
} catch (SQLException ex) {
}
System.out.println(appointments);
return appointments;
}
Where the table has three rows with these values:
1347390000000 15
1347461100000 30
1347469200000 45
And the output is:
date = 1347390000000 duration = 15
date = 1347461100000 duration = 30
date = 1347469200000 duration = 45
1350141222283 -> 1350746022283
[]
1349536422283 -> 1350141222283
[]
1348931622283 -> 1349536422283
[]
1348330422283 -> 1348931622283
[]
1347725622283 -> 1348330422283
[]
1347120822283 -> 1347725622283
Should be adding to list
Should be adding to list
Should be adding to list
[]
1346516022283 -> 1347120822283
[]
A: You have to declare the data types of the columns.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13033357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding column to dataframe based on another dataframe using pandas I need to create a new column in dataframe based on intervals from another dataframe.
For example, I have a dataframe where in the time column I have values and I want to create column in another dataframe based on the intervals in that time column.
I think a practical example is simpler to understand:
Dataframe with intervals
df1
time value var2
0 1.0 34.0 35.0
1 4.0 754.0 755.0
2 9.0 768.0 769.0
3 12.0 65.0 66.0
Dataframe that I need to filter
df2
time value var2
0 1.0 23.0 23.0
1 2.0 43.0 43.0
2 3.0 76.0 12.0
3 4.0 88.0 22.0
4 5.0 64.0 45.0
5 6.0 98.0 33.0
6 7.0 76.0 11.0
7 8.0 56.0 44.0
8 9.0 23.0 22.0
9 10.0 54.0 44.0
10 11.0 65.0 22.0
11 12.0 25.0 25.0
should result
df3
time value var2 interval
0 1.0 23.0 23.0 1
1 2.0 43.0 43.0 1
2 3.0 76.0 12.0 1
3 4.0 88.0 22.0 1
4 5.0 64.0 45.0 2
5 6.0 98.0 33.0 2
6 7.0 76.0 11.0 2
7 8.0 56.0 44.0 2
8 9.0 23.0 22.0 2
9 10.0 54.0 44.0 3
10 11.0 65.0 22.0 3
11 12.0 25.0 25.0 3
EDIT: As Shubham Sharma said, it's not a filter, I want to add a new column based on intervals in other dataframe.
A: You can use pd.cut to categorize the time in df2 into discrete intervals based on the time in df1 then use Series.factorize to obtain a numeric array identifying distinct ordered values.
df2['interval'] = pd.cut(df2['time'], df1['time'], include_lowest=True)\
.factorize(sort=True)[0] + 1
Result:
time value var2 interval
0 1.0 23.0 23.0 1
1 2.0 43.0 43.0 1
2 3.0 76.0 12.0 1
3 4.0 88.0 22.0 1
4 5.0 64.0 45.0 2
5 6.0 98.0 33.0 2
6 7.0 76.0 11.0 2
7 8.0 56.0 44.0 2
8 9.0 23.0 22.0 2
9 10.0 54.0 44.0 3
10 11.0 65.0 22.0 3
11 12.0 25.0 25.0 3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63763944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create Table using PostgreSQL I'm trying to create a table using PostgreSQL. The code above is correctly authenticating. The problem I'm facing now is how to correctly create the table 'devices' and write data to it.
const Sequelize = require('sequelize');
const env = require('./config');
sequelize = new Sequelize({
database: '******',
dialect: 'postgres',
username: '********',
password: '******',
host: '********',
port: 3211
});
sequelize.authenticate().then(() => {
console.log("Connected to DB");
})
.catch((err) => {
console.log(err);
})
function insertIntoPostgres(filename, data) {
var fileToCreate =
`/${env.azurePG.data_store_pg.folder}/${filename}.json`;
var options = {
streamContents: new Buffer(JSON.stringify(data))
}
filesystemClient.fileSystem.create(env.azurePG.data_store_pg.account_name_pg, fileToCreate, options)
.then(res => {})
.catch(err => {
console.log("error inserting into postgres: ", err);
});
};
// Export the above methods
module.exports = {
insertIntoPostgres
}
Here is the part of my code that I think is wrong from the above code:
filesystemClient.fileSystem.create(env.azurePG.data_store_pg.account_name_pg, fileToCreate, options)
.then(res => {})
.catch(err => {
console.log("error inserting into postgres: ", err);
});
};
my config.js
module.exports = {
PGDATABASE : "******",
PGPORT : 3211,
azurePG : {
PGUSER : "*******",
PGHOST : "********",
PGPASSWORD : "*******",
data_store_pg : {
account_name_pg : "********",
folder : "devices"
}
}
};
Any ideas on where is the problem?
A: You need to actually create the table first, then run your code to populate the table. I would take a look at the data set you're working with to get an idea of the field names and data types and then run something like this:
CREATE TABLE devices(
id serial PRIMARY KEY,
name TEXT NOT NULL,
otherfield TEXT NOT NULL
);
I'm not sure if you're trying to build a full automated cycle of creating a table and populating it, but you could just hop on over to postgres and run the create table code in the terminal or whatever database management tool you're using. After the table is created, you should be table to run the below code to verify it's been created correctly:
SELECT * FROM devices
It should come back with an empty table with all the columns you specified. If all that is good to go, run your code that populates the table. Should work fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52650504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rust failed to downcast_ref from trait object extended from Any Here is the Rust Playground of the example code.
use std::any::Any;
pub trait MemorizedOutput: Any {
fn as_any(&self) -> &dyn Any;
}
impl<T: Any> MemorizedOutput for T {
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let a = Box::new(1i32) as Box<dyn MemorizedOutput>;
println!("{}", a.as_any().downcast_ref::<i32>().unwrap());
}
Why is the above code panic at unwrap().
A: Box<dyn MemorizedOutput> implements Any, so it is covered by the blanket implementation of MemorizedOutput. As per https://doc.rust-lang.org/reference/expressions/method-call-expr.html, Rust will prefer methods implemented on Box<dyn MemorizedOutput> before it the dereferenced type dyn MemorizedOutput. So a.as_any() is actually <Box<dyn MemorizedOutput> as MemorizedOutput>::as_any(&a), which obviously cannot be downcasted into i32.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67206692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Minimizing calls to database in rails i am familiar with memcached and eager loading, but neither seems to solve the problem i am facing.
My main performance lag comes from hundreds of data retrieval calls from the database. The tricky thing is that I do not know which set of users i need to retrieve until i have several steps of computation.
I can refactor my code, but i was wondering how you experts handle this situation? I think it should be a fairly common situation
def newsfeed
- find out which users i need
- retrieve those users via DB
- find out which events happened for these users
- for each of those events
- retrieve new set of users
- find out which groups are relevant
- for each of those groups
- retrieve new set of users
- etc, etc
end
A: Denormalization is the magic password for your situation.
There are several ways to do this:
For example, store the ids of the last 10 users in the event and group.
Or create a new model NewsFeedItem (belongs_to :parent, :polymorphic => true). When a user attends an event, create a NewsFeedItem with denormalized informations like this users name, his profile pic etc. Saves you from second queries to user_events and users.
A: You should be able to do this with only one query per Event / Group loop. What you'll want to do is: inside your for loop add user ids to a Set, then after the for loop, retrieve all the User records with those ids. Rinse and Repeat. Here is an example:
def newsfeed
user_ids = Set.new
# find out which users i need
... add ids to user_ids
# retrieve those users via DB
users = User.find(user_ids.to_a)
# find out which events happened for these users
# you might want to add a condition
# that limits then events returned to only recent ones
events = Event.find_by_user_id(user_ids.to_a)
user_ids = Set.new
events.each do |event|
user_ids << discover_user_ids_for_event(event)
# retrieve new set of users
users = User.find(user_ids.to_a)
# ... and so on
end
I'm not sure what your method is supposed to return, but you can likely figure out how to use the idea of grouping finds together by working with collections of IDs to minimize DB queries.
A: Do you want to show all the details at once (I mean when the page is loading do you really want to load all of those information) , If not what you can do is, load them on demand
as follows
def newsfeed
*
*find out which users i need
*retrieve those users via DB
*find out which events happened for these users
once you show the events give them a button or something to drill down to other details (on -demand) then load them using AJAX (so that page will not refresh)
use this technique repeatedly when users want to go deep details
By doing this , you will save lots of processing power and will get only the details user needs
I dont know if this is applicable to your situation
If not then you have to find a more optimized way of loading details
cheers,
sameera
A: I understand that you are trying to perform some kind of algorithm on the basis of your data to do some kind of recommendation or similar sort of thing.
I have two suggestions:
1) You reevaluate your algorithm / design on the basis of what you actually want to achieve. For instance, in cases where an application has users who can potentially have lots of posts and the app wants to perform some algorithm on the basis of the number of posts then it will be quite expensive to count their posts every time. To optimise this, a post_count column can be added on the user model and increase that count whenever a user successfully does a post. Similarly, if you can establish some kind of relation like this between your user, events, groups etc, then think of something on those lines.
2) If first solution is not feasible, then for anything like this you must avoid doing multiple queries and then using ruby for crunching data which would obviously be very expensive and is never advisable if you have large data set. So what you need here is to make one sql query using join and get all data in just one go. Also pick only those field names from the database that you need. It really helps in case of large data sets. For instance, if you need user id and event_id from user and events table and nothing else then do something like so
User.find(:all,
:select => 'users.id, users.event_id',
:joins => 'join events on users.id = events.user_id',
:conditions => ['users.id in (your user ids)'])
I hope this will point you in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2888966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Match only letters and special characters with RegExp How can I allow only letters and special characters with a regular expression?
A: I suggest you use GSkinner's REGEX builder and experiment with a lot of the examples on the right hand side. There are are many variations to get this job done. If you want to be explicit you can use:
/[a-zA-Z!@#$%¨&*()-=+/*.{}]/
Tony's answer will also work, but includes more extra characters than the ones you've defined in your comment.
A: This
$str = $_REQUEST["htmlstringinput"];
preg_match("([\w\-]+[@#%.])", $str);
for letters, numbers and special characters in this special character range [@#%.] are allowed
and this
$str = $_REQUEST["htmlstringinput"];
preg_match("([-a-zA-Z]+[@#%.])", $str);
for only letters and special characters in the same special character range as above
Worked for me. For further reading and research you can go to : http://gskinner.com/RegExr/
A: /[\p{L}\p{P}]+/u
matches letters and punctuation characters. Or what did you mean by "special characters"?
A: all characters not a number? how bout this:
/[^\d]*/
A: Use following code in .htaccess to block all URLs with number (as per OP's comments)
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_URI} ![0-9]
RewriteRule ^user/ /index.php?goto=missed [NC,L]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5886910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error by solving sudoku using backtracking I'm trying to implement a code of (SolveSudoku) by using backtracking.
But I always get an error.
I looked at many solutions in the internet ,but they are different which confuses me. that's why I'm asking here.
I think the mistake can be in the function is_safe somewhere ,because other people solved it by using reference/dereference (pointers/adresses).
this is my code :
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 9
int ** create_puzzle()
{
int i , j;
int **my_puzzle;
my_puzzle =(int**)malloc(sizeof(int*)*9);
int my_array [N][N]={ 0,1,9, 0,0,2, 0,0,0,
4,7,0, 6,9,0, 0,0,1,
0,0,0, 4,0,0, 0,9,0,
8,9,4, 5,0,7, 0,0,0,
0,0,0, 0,0,0, 0,0,0,
0,0,0, 2,0,1, 9,5,8,
0,5,0, 0,0,6, 0,0,0,
4,7,0, 0,2,8, 0,7,9,
0,0,0, 1,0,0, 8,6,0};
for (i =0;i<N;i++)
{
my_puzzle[i]=(int **)malloc(sizeof(int *)*9);
for(j=0;j<N;j++)
{
my_puzzle [i][j]=my_array[i][j];
}
}
return my_puzzle;
}
void print_puzzle(int **puzzle)
{
int r,c;
for(r=0;r<N;r++)
{
if(r%3==0){
printf("-------------------------------\n");
}
for(c=0;c<N;c++)
{
if(c%3==0)
printf("|");
printf("%d ",puzzle[r][c]);
}
printf("| \n");
}
printf("-------------------------------\n");
}
//function to check if all cells are assigned or not
bool is_zero(int **puzzle,int row ,int column)
{
if(puzzle[row][column]==0)
{
return true;
}
return false;
}
//checking in row
bool check_Row(int **puzzle,int number,int column)
{
for(int row=0;row<9;row++)
{
if(puzzle[row][column]==number)
{
return true;
}
}
return false;
}
//checking column
bool check_Column(int ** puzzle,int number,int row)
{
for(int column=0;column<9;column++)
{
if(puzzle[row][column]==number)
{
return true;
}
}
return false;
}
//checking sub matrix
bool check_box(int **puzzle,int number,int row,int column)
{
int row_start=(row/3)*3;
int start_column=(column/3)*3;
for(int i=row_start;i<row_start+3;i++)
{
for(int j=start_column;j<start_column+3;j++)
{
if(puzzle[i][j]==number)
{
return true;
}
}
}
return false;
}
//function to check if we can put a
//value in a paticular cell or not
bool is_safe(int ** puzzle,int number,int row,int column)
{
if(is_zero(puzzle,row ,column))
{
return !check_Row(puzzle,number,column)&&
!check_Column(puzzle,number,row)&&
!check_box(puzzle,number, row,column);
}
return false;
}
//function to solve sudoku
//using backtracking
bool sudoko_solver(int **puzzle)
{
int row,column;
int number=0;
for(row=0;row<9;row++)
{
for(column=0;column<9;column++)
{
if(is_safe(puzzle[row][column],number,row,column))
{
puzzle[row][column]=number;
if(sudoko_solver(puzzle))
{
return true;
}
else
{
puzzle[row][column]=0;
}
}
}
}
return false;
}
int main ()
{
int **puzzle= create_puzzle();
print_puzzle(puzzle);
if(sudoko_solver(puzzle))
{
print_puzzle(puzzle);
}
else
{
printf("No solution");
}
return 0;
}
I always get -1073741819 as output .
A: You have included one header twice:
#include <stdlib.h>
#include <stdlib.h>
and omitted
#include <stdio.h>
Even when corrected, there are several compiler warnings, four like
warning C4715: 'check_Column': not all control paths return a value
and one is
warning C4024: 'is_safe': different types for formal and actual
parameter 1
and also two similar to
warning C4047: '=': 'int *' differs in levels of indirection from 'int
**'
My compilation when run does not give a wrong answer: it crashes. So fix all the warnings.
A: The function
bool check_Row(int **puzzle,int number,int column)
{
for(int row=0;row<9;row++)
{
if(puzzle[row][column]==number)
{
return true;
}
else{return false;}
}
}
only tests the 0th row. No matter what number is there it returns immediately. Ditto for other checks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54640519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Gulp + Sass + Combine Media Queries + Sourcemaps + Minify I'm trying to get the above combination working but am unable to. I have tried the following combinations:
1)
var sass = require('gulp-ruby-sass');
gulp.task('sass',function () {
gulp.src('_scss/main.scss')
.pipe(sass({
loadPath: ['_scss'],
style: "compressed",
trace: true,
sourcemap: true,
sourcemapPath: "../../../_scss",
noCache: true,
require: ['sass-media_query_combiner']
}))
2)
var sass = require('gulp-ruby-sass');
var cmq = require('gulp-combine-media-queries');
var cssmin = require('gulp-cssmin');
gulp.task('sass',function () {
gulp.src('_scss/main.scss')
.pipe(sass({
loadPath: ['_scss'],
style: "nested",
trace: true,
sourcemap: true,
sourcemapPath: "../../../_scss",
noCache: true
}))
.pipe(cmq())
.pipe(cssmin())
3) I also tried using gulp-sass + gulp-combine-media-queries + gulp-minify-css + gulp-sourcemaps
Before moving to Gulp, I was using this build command in ST2:
"cmd": ["sass", "--update", "${project_path}/web/_scss/main.scss:${project_path}/web/resources/css/main.css", "--stop-on-error", "--no-cache", "--style", "compressed","-r","sass-media_query_combiner"],
link to question on reddit, also sass-media_query_combiner and gulp-ruby-sass
A: ".pipe(cmq())" should be before ".pipe(gulp.dest())"
gulp.task('sass', function() {
return gulp.src("./*.scss")
.pipe(sass())
.pipe(cmq())
.pipe(gulp.dest(".css/"))
.pipe(reload({stream: true}))
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25264397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to connect our Jira using nodejs I'm beginner in this territory!
My question is how to connect to our Jira ( https://mycompany.atlassian.net (cloud)) for get all data from our jira projects (ex. user stories, tasks, issues ...).
- I have access to admin jira !
- I saw this: https://docs.atlassian.com/jira/REST/cloud/
- Should I have to buy an another licence for access to get data from api?
What are the first steps?
A: I believe the license you purchased to use Jira gives you access to the api without further cost.
First steps?
The second link you gave in your post relating to the api (docs.atlassian.com/jira/REST/cloud/) gives you everything you need to know if you understand its content.
Googling nodejs jira api gave a number of package results that would make interacting with the api very easy. At the time node-jira was top of the list and looked like it suited your needs. There are other packages too so worth looking around.
General pointers:
*
*Start on a list of nodejs packages you will need to build your app from what you know and package searches. Initialize your node project and start adding those packages to package.json.
*Identify the Jira authentication method you are going to use.
*
*The api supports basic over https or oauth and cookie once authenticated.
*Find examples of how the package you are using handles authentication. It should be easy in the package readme or with google.
*Identify the API calls that will give you the data you need.
*
*The options are easy to find in node-jira readme if using it or use the api docs.
*The jira api documentation will give you the expected json response schema that you will need to access the json you get back.
*An example would be the Projects api definition. It gives you an example response and the full response schema.
*The api options are described as 'expandable' which means you only get what you ask for, if you want more you have to ask for it. (see expand option for each api call)
*Consider what you need to process the data you get back and display it in whatever format you require.
*
*Again more package options, json processing, templating.
*If it is a web page you might need something like express.
*Use that information to start coding (not in any specific order).
*
*Code for getting requests (say a web page).
*Code for authentication and api calls.
*Code for templating each data view of api response data.
*Code the overall app structure.
*Give yourself some debug messages that can be turned on and off so you can see process sequence which can help a lot in troubleshooting.
*Write test scripts! Change code.... run the test/s, got a new feature... write a test then code to the test. Retest before release.
There are lots of package options, information, and examples. Use Google lots, search npmjs.com for packages, use the api docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40544844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to erase an element that is nested within a list which is nested within a vector I'm building a hashtable using separate chaining using vector of a list of pairs as the data structure. I'm having some issues where I'm trying to erase a pair from the list structure nested within the vector. Here is a simple of the code http://cpp.sh/8cz4h
and here is the code:
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <utility>
using namespace std;
int myhash(const string & k) ;
int main()
{
vector < list < pair <string, string> > > v;
v.resize(15);
string k = "foo";
//I believe this will take me to the list element I want to iterate over
for (auto &itr : v[myhash(k)])
{
if (itr.first == k)
{
//then delete the pair
v[myhash(k)].erase(itr);
break;
}
}
}
int myhash(const string & k) {
return k.size() % 15;
}
with an error at the erase function saying it cannot match a list of pairs with pairs which makes sense to me, I know that v[myhash(k)].erase(itr); doesn't make a whole lot of sense, not sure how to fix it though.
something I think would do the trick is something like v[myhash(k).at(itr)].erase(itr); but I'm not sure how one can navigate to a certain spot in a list
thanks for anyhelp.
as a disclaimer I was chatting with a user on here yesterday with this problem and he came up with a solution here: http://cpp.sh/96na5 however this seemed a bit overwhelming to me and I have a feeling there is a simpler solution out there
A: This can be done the following way
v[myhash( k )].remove( { k, k } );
A: When you use a range-for loop, you get the items of the list. std::list does not have a version of erase that accepts an item to be removed from a list.
Instead of using a range-for loop, use an iterator and a normal for loop.
auto& list = v[myhash(k)];
auto iter = list.begin();
auto end = list.end();
for (; iter != end; ++iter )
{
if (iter->first == k)
{
//then delete the pair
list.erase(iter);
break;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33976622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R equal values in different data frames I have two different data frames. For example Lets say dataframe 1:
| A |
| -------- |
| 11 |
| 24 |
| 3|
| 14|
| 17|
and dataframe 2:
|b | c |
| -------- | -------------- |
| 23 | Cat |
| 24 | Dog |
| 11 | Cow |
| 3 | Snake |
I want to get c values to dataframe 1. So my desired outcome would be something like that:
and dataframe2:
|a | new value|
| -------- | -------------- |
|11 | Cow |
| 24 | Dog |
| 3 | Snake |
| 14 | NA |
| 17 | NA |
I tried this:
library(dplyr)
dataframe1<-dataframe1 %>% mutate(newvalue=ifelse(a%in% dataframe2$b, dataframe2$c,NA))
But this doesnt work properly. What could I do?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73052898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Microsoft.OData.Client with Microsoft.OData.Core 7.0 I would need to use Microsoft.OData.Client in my project, wich already reference Microsoft.OData.Core 7.0.0 and Microsoft.AspNet.OData 6.0.
Actually i don't find version of client that's compatible with Microsoft.OData.Core 7.0.0 and later.
Last version supported by client is 6.15.
Microsoft.OData.Client (6.15.0) requires Microsoft.OData.Core (= 6.15.0).
Do we have a new version of OData.Client in the horizon that will use Core>=7 and match the one used by the AspNet package?
Any other solutions in the meantime?
A: Finally i keep the client part based on 6.15 Odata version and Simple.OData.Client 4.20,
Server part will be upgraded to odata 7.0
It works well provided you use the timestamp type on client in remplacement of system.DateTime or Microsoft.OData.Edm.Library.Date Types
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42071996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get single field from different collection in mongodb I am having two collections 'MotorDetails' and 'PersonDetails'.Person Id is present is my both collections. I required all items from PersonDetails and only Manufacturer Name from MotorDetails for each person Id. how to join collections in mongodb?
I am very new to mongodb so Please help me with this scenario
A: db.PersonDetails.aggregate([
{$lookup:{
from: "MotorDetails",
localField:"personId",
foreignField:"personIdEquivalentOnMotorDetails",
as:"PersonToManufacturer"
}}
])
Search on stackoverflow(check existing questions) and Google if you want to learn something new. Do not post direct questions where answers are already present on stackoverflow. https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
You should read , try out yourself and post here only if you stuck at some point.
A: MongoDB being a NoSQL database does not support concept of relationships
Alternatively it facilitates defining relationship using embedded documents.
Also MongoDB has added $lookup operator which is used to perform left outer join operations into MongoDB Database as a part of aggregation pipeline.
For more detailed description regarding $lookup operator please refer documentation as mentioned into following URL
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49569981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ansible : ssh keys not getting copied to all nodes in inventory - debug:
msg: "Setting up passwordless ssh"
- name: Create SSH key
command: ssh-keygen -b 2048 -t rsa -f /root/.ssh/id_rsa -q -N ""
args:
creates: /root/.ssh/id_rsa
- name: Fetch the keyfile from the node to master
fetch:
src: "/root/.ssh/id_rsa.pub"
dest: "buffer/{{inventory_hostname}}-id_rsa.pub"
flat: yes
- name: Copy the key add to authorized_keys using Ansible module
authorized_key:
user: root
state: present
key: "{{ lookup('file','buffer/{{item}}-id_rsa.pub')}}"
when: "{{ item != inventory_hostname }}"
with_items:
- "{{ groups[group_names[0]] }}"
register: ssh_setup_result
- name: Add host to known hosts list
shell: ssh-keyscan -H "{{ inventory_hostname }}" >> ~/.ssh/known_hosts
- name: Add host to known hosts list
shell: ssh-keyscan -H "{{ hostname_domain }}" >> ~/.ssh/known_hosts
- name: get key
command: ssh-keyscan {{ inventory_hostname }}
register: keys
- name: add key to known_hosts
lineinfile:
path: /root/.ssh/known_hosts
line: " {{ keys.stdout }}"
insertbefore: BOF
when: "{{ item != inventory_hostname }}"
with_items:
- "{{ groups[group_names[0]] }}"
ssh-keys is not getting copied to cross hosts , say keys from node1 is not getting copied to known hosts of node2. Similarly vice versa. How to resolve this ?
Ansible version used:
ansible [core 2.11.11]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73881911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xtext, implementing Long, Double and Float types the question is very simple.
How do I implement long, double and float types correctly in my Xtext grammar so I can use them later in my interpreter?
the interpreter is an extend class.
EDIT 1
In my code i have something like
IDValue: value=ID;
StringValue: value=STRING;
IntValue : value=INT;
SimpleValue:
IntValue | StringValue
;
And i would like to have something like
DoubleValue : value=DOUBLE;
In my interpreter I can do
if (p.var0 instanceof StringValue) :
I expect to do also
if (p.var0 instanceof DoubleValue) :
EDIT 2
This is the grammar:
Set:
'SET' '(' attribute=ID ',' value=(AttributeValue ) ')'
;
StringValue: value=STRING;
IntValue : value=INT;
LongValue : value = LONG;
DoubleValue : value=DOUBLE;
SimpleValue:
IntValue | StringValue | LongValue | DoubleValue
;
Structure: {Structure}
'{' ID ':' var0=AttributeValue (',' ID ':' var1+=AttributeValue)* '}'
;
Array: {Array}
'[' var0=AttributeValue(',' var1+=AttributeValue)* ']'
;
AttributeValue :
SimpleValue |
Structure |
Array
;
LONG returns ecore::ELong: INT ("L"|"l");
DOUBLE returns ecore::EDouble : INT'.'INT;
And this is the class in my interpreter where I execute the Set function and must recongnize the type of the variable (it's in Xtend):
def dispatch void exec(Set s) {
val setAttribute = LocalMapAttribute.get(s.attribute.toString)
val cosem = LocalMapCosem.get(setAttribute.object)
val setValue = s.value.getType
if (setValue instanceof Array) {Jtest.SetFunction(cosem,setAttribute.attribute_name,ArrayToList(setValue),"Array")}
else if (setValue instanceof String) {Jtest.SetFunction(cosem,setAttribute.attribute_name,setValue)}
else if (setValue instanceof Structure) {Jtest.SetFunction(cosem,setAttribute.attribute_name,StructToList(setValue),"Struct")}
else if (setValue instanceof Long) {println("LONG DETECTED" + setValue)}
else if (setValue instanceof Double) {println("DOUBLE DETECTED" + setValue)}
else if (setValue instanceof Integer) {Jtest.SetFunction(cosem,setAttribute.attribute_name,setValue )}
}
To recongnize the type I use these methods:
def dispatch Array getType (Array array){
//println("SET with Array")
return array
}
def dispatch getType (SimpleValue simple){
//println("SET with Simple Value")
return getTypeSimple(simple)
}
def dispatch Structure getType (Structure structure){
//println("SET with Strcutre")
return structure
}
def dispatch String getTypeSimple (StringValue str){
//println("SET with Sting")
return (str.value as String)
}
def dispatch int getTypeSimple (IntValue Int){
//println("SET with int")
return (Int.value )
}
def dispatch double getTypeSimple (DoubleValue Int){
println("SET with DoubleValue")
return (Int.value )
}
def dispatch long getTypeSimple (LongValue Int){
println("SET with LongValue")
return (Int.value )
}
The Value Converter:
public class MyDslValueConverters extends DefaultTerminalConverters {
IValueConverter<Long> longValueConverter = new IValueConverter<Long>() {
@Override
public Long toValue(String string, INode node) throws ValueConverterException {
// TODO make this more robust
return Long.parseLong(string.substring(0, string.length()-1));
}
@Override
public String toString(Long value) throws ValueConverterException {
// TODO make this more robust
return Long.toString(value)+"L";
}
};
IValueConverter<Double> DoubleValueConverter = new IValueConverter<Double>() {
@Override
public Double toValue(String string, INode node) throws ValueConverterException {
// TODO make this more robust
return Double.parseDouble(string);
}
@Override
public String toString(Double value) throws ValueConverterException {
// TODO make this more robust
return Double.toString(value);
}
};
}
A: you can import the ecore metamodel and thus its datatypes using import "http://www.eclipse.org/emf/2002/Ecore" as ecore. Then you can use them as return value in a terminal or datatype rule LONG returns ecore::ELong: INT ("L"|"l");. Finally you have to implement a ValueConverter that does the Convertion from String to Long and Vice Versa
public class MyDslValueConverters extends DefaultTerminalConverters {
IValueConverter<Long> longValueConverter = new IValueConverter<Long>() {
@Override
public Long toValue(String string, INode node) throws ValueConverterException {
// TODO make this more robust
return Long.parseLong(string.substring(0, string.length()-1));
}
@Override
public String toString(Long value) throws ValueConverterException {
// TODO make this more robust
return Long.toString(value)+"L";
}
};
@ValueConverter(rule = "LONG")
public IValueConverter<Long> LONG() {
return longValueConverter;
}
}
And dont forget the binding
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {
override bindIValueConverterService() {
return MyDslValueConverters
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41022942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When does C decide if char[] is a character array or a string? char[i] stands for declaration of a variable both a char array and a string. I know that C adds a null character to the end of the array if it is a string. However, how does C know when to add the null character, in other words, in what stage?
A: it doesn't, C "strings" are just an assumption about arrays ( that they have a 0 somewhere indicating the end of the string)
There is no type "string" in C, just libraries which deal with char arrays with the above assumption. It is completely up to the library functions to manage the arrays and work out when to terminate them if needed. Quite often these functions don't respect what memory was actually allocated for the array, it will assume there's enough allocated space for whatever it's doing
It would be entirely possible to use pascal type strings in C and write a string library using that convention if one wished.
A: C doesn't know the difference between a char[] or char* which is a string and a char[] or char* which isn't a string.
The only place where C will add a nul terminator is when you use a string literal.
const char x[] = "Hello, world!";
// ^ plus terminator, sizeof=14
const char *y = "Hello, world!";
// ^ plus terminator
You can just as easily create an array without a terminator:
const char x[] = {'H', 'e', 'l', 'l', 'o', ',',
' ', 'w', 'o', 'r', 'l', 'd', '!'};
// ^ NO terminator
// sizeof=13
Okay, maybe not "just as easily", it's a fair bit of extra typing. But you can see the point: it's the fact that you used double quotes "..." that added the nul terminator.
Certain library functions will also give you nul terminators, like strcpy or snprintf.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41709488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Batch file to move a file from a folder to another folder & create a text file in its place having the name of the moved file I needed a batch file to which we could provide input (any file) from Windows 7 context menu option "Send to".
This batch file must then move that file to another folder, & create a text file in it's place with the same name as the moved file.
I needed this to move mp3 files from their album folder to a common folder, while keeping a track of which file belonged to what folder.
A: At first create a Batchfile with the following content:
@echo off
set newpath=H:/testing
set filename=%*
move %filename% %newpath%
set txtfilename=%filename:~0,-3%txt
echo.content of textfile >%txtfilename%
where insteadof the H:/testing you put the new path of your files,
and instead of the "content of textfile" you write what shall be in the textfiles created at the old location of the files.
it does not matter where you create the batch file, because in the next step you go to the search bar and type in shell:sendto and open the folder,
where you create a shortcut to your batchfile.
You can now send files to your batchfile over the "send to" menue,
and the batch file copies the file to the specified path and leaves a text file with the desired content where the moved file once was.
Edit: if you want to use it on files with varying number of characters in the ending, the code has to be modified to
@echo off
setlocal enabledelayedexpansion
set newpath=H:/testing
set filename=%*
move %filename% %newpath%
set ending=%filename:*.=%
set txtfilename=!filename:%ending%=!.txt
echo.content of textfile >%txtfilename%
but in this case you can't have dots or file-endings in the names of your folders or leaving the textfile wont work properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31686068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone-CTMessageCenter API I have an application to schedule and send an SMS to an individual or bulk in iPhone. So, I am planning to use a Private API called CTMessageCenter. But, I am getting to know that Apple might reject the app during their acceptance, if we use the above third party API.
Also, I am getting to know that if I use the API provided by Apple, then that would be accepeted for sure.
Can you help me answering this question?
A: Yes you are correct. If you use any private Apple API in your app, it will be rejected.
Note that a third party code library is not the same thing as a private API (such as libraries you download from github, sourceForge, etc.) As long as the library(s) you use follow the rules, that is fine.
I'm not familiar with CTMessageCenter, so I don't know which it is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11045093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mocking ObjectContext, dealing with ObjectQuery.Include(string) method? I have been investigating how to decouple my DomainServices from their datasource so I can test them in unit tests. I'm starting to think fully decoupling them is not possible.
There is a decent amount of info out there, such as this question and this blog post. The blog post in particular gets you really far into mocking ObjectContext.
But my DomainServices have methods like this:
public IQueryable<Client> GetClients()
{
return ObjectContext.Clients
.Include("Foo")
.Include("Bar")
.Where(c => c.IsBaz);
}
It doesn't seem possible to fully mock the Include method, as it returns an ObjectQuery<T>, and the Include method is not captured in an interface anywhere (There is no IObjectQuery interface). ObjectQuery implements IQueryable<T>, and so I thought making my own Include method that returns IQueryable would work, but only if I plan to call Include at most once per query.
I am using EF4, .NET 4, Silverlight 4 and RIA Services RTW.
As a bit of a rant, I'm disappointed at how test unfriendly LINQ to Entities and by extension RIA Services is :(
A: I don't think you should be unit testing at that level. I'm all in for unit tests, but there is a certain point where you need to stop.
Lets say that code is part of a ClientsLinqRepository, which in turns implements IClientsLinqRepository. You mock IClientsLinqRepository, when you implement code that depends on it.
While the above is perfectly valid, ClientsLinqRepository is an integration implementation. Pretty much like if you had IMessageSender and you implemented MailSender. Here you have code that its main responsibility is integrating with a separate system, for you that's the database.
Based on the above scenario, I suggest you do some focused integration tests on that class. So in that case you do want to hit the external system (database), and make sure that integration code is working appropriately with the external system. It'll allow you to quickly identify if anything in the code vs. the database is broken without dealing with the complexity of the rest of the system (which a pain when trying to do integration tests at other levels).
Keep the focused integration tests separate from the unit tests, so you can run the amazingly fast unit tests as much as you want, and run integration test when changes are made to any of the integration pieces and every now and then.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2976563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: grouping some fields and selecting some of them in oracle I have a table like below. I obtained this table with grouping some fields.
739033 007607000176 23.01.2014 13:10:53 007607000176 ELTN 007607000176 ELTN 43494 24 82860 580360
753281 007607000176 23.01.2014 13:13:38 007607000176 ELTN 007607000176 ELTN 43494 24 82860 580360
738084 007607000390 23.01.2014 13:10:53 007607000390 PRTG 007607000390 BASC 18368 14 70865 191623
752332 007607000390 23.01.2014 13:13:38 007607000390 PRTG 007607000390 BASC 18368 14 70865 191623
738238 007607000574 23.01.2014 13:10:53 007607000574 PRTG 007607000574 PRTG 18368 14 67456 297456
752486 007607000574 23.01.2014 13:13:38 007607000574 PRTG 007607000574 PRTG 18368 14 67456 297456
738508 007607000655 23.01.2014 13:10:53 007607000655 BASC 007607000655 PRTG 805 1 10520 283020
752756 007607000655 23.01.2014 13:13:38 007607000655 BASC 007607000655 PRTG 805 1 10520 283020
432213 007607000670 14.05.2011 00:12:31 007607000670 ELTN 007607000670 ELTN 40506 25 163933 903433
432460 007607000670 15.05.2011 00:12:35 007607000670 ELTN 007607000670 ELTN 40506 25 163933 903433
432660 007607000670 16.05.2011 00:12:37 007607000670 ELTN 007607000670 ELTN 40506 25 163933 903433
738083 007607000670 23.01.2014 13:10:53 007607000670 ELTN 007607000670 ELTN 78370 46 109520 1199020
752331 007607000670 23.01.2014 13:13:38 007607000670 ELTN 007607000670 ELTN 78370 46 109520 1199020
433177 007607000670 18.05.2011 00:12:40 007607000670 ELTN 007607000670 ELTN 41506 26 95183 904683
433428 007607000670 19.05.2011 00:12:42 007607000670 ELTN 007607000670 ELTN 41506 26 95183 904683
433928 007607000670 21.05.2011 00:12:49 007607000670 ELTN 007607000670 ELTN 44324 28 101706 911206
434420 007607000670 23.05.2011 00:12:55 007607000670 ELTN 007607000670 ELTN 44324 28 101706 911206
434156 007607000670 22.05.2011 00:12:50 007607000670 ELTN 007607000670 ELTN 44324 28 101706 911206
I want to select one of them that has the same id.(second column).How can I do ?
EDIT
This is what I want :
739033 007607000176 23.01.2014 13:10:53 007607000176 ELTN 007607000176 ELTN 43494 24 82860 580360
738084 007607000390 23.01.2014 13:10:53 007607000390 PRTG 007607000390 BASC 18368 14 70865 191623
738083 007607000670 23.01.2014 13:10:53 007607000670 ELTN 007607000670 ELTN 78370 46 109520 1199020
A: You can use row_number(). For instance, if the third column where datetime, then the following gets the most recent row:
select t.*
from (select t.*,
row_number() over (partition by id order by datetime desc) as seqnum
from table t
) t
where seqnum = 1;
A: Try to include in your query count(1) and group by all other columns. Also add having count1) > 1 in your query. Please take a look at the sample:
with src as (
select '1' as id,'s1' as descr from dual
union all
select '1','s1' from dual
union all
select '2','s2' from dual
)
select id,descr,count(*) from src group by id,descr
having count(*) > 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31650797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Dynamically add a list to the sign up page of users I am new to RoR and I am trying to implement a kind of content management system. Let's say there is an admin user which creates other users.
I have tried the Devise gem. My first question is how can I use this gem so that the admin user creates other users (entering their info, name, email, password)? Is is programatically correct to let the admin user to go to the sign up page and create new users?
My second question is that, in my application the admin should be able to dynamically add a list of organization names in runtime. Therefore, when creating new user, an organization should be chosen from the organization list for that user. I was thinking about creating an empty database for the organization name, and admin user adds to that database in the runtime. Is it a good way?
Thank you so much,
Amir
A: I'm not sure if this is the best way to go but, I could manage to make it work like follow.
In your user model, make sure you have added :confirmable in devise.
devise :database_authenticatable, :registerable, :confirmable, ...,
Also you need your user table to have the following fields.
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
Then in your user controller add the following method.
def create_new_account
@new_user = User.new(user_params)
if @new_user.valid?
@new_user.skip_confirmation!
@new_user.confirmed_at = nil
if @user.save
render action: "some_action"
else
render action: "some_other_action"
end
end
end
When and a user creates a new account through that method and email will be send to the new account's email address with a confirmation token. That will forward the new user to a page asking them for there password.
The email template that is being send can be fond at app/views/devise/mailer/confirmation_instructions.html.erb
And in your routes make sure you have a post request to the controller's action.
post "create_new_account" => "users#create_new_account"
I'm not an expert on this but the way I understand this, is that you need the confirmation option in Devise to let your new user accounts enter there own password. But since the current admin user is already logged in. You need to skip the confirmation step.
Again I'm not 100% sure this is the right way.
I would be happy to hear what other people has to say about this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37911889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems using post request in axios I'm having problems trying to use a POST request in axios.
I need to send an object to my backend, but it receives predefined values inside my function, so I can't send all my data.
I tried in different ways and got different messages but I still couldn't find my error.
export function createUsers(user: userApi) {
user.pin = '001'
user.customFields = []
//@ts-ignore
user.admission_at = selectedDate.value
return axios.post('/users',{
...user,
admission_at: dateBr(user.admission_at)
})
}
In this first attempt when I send data, it ends up sending only the pre-defined values:
On the second try I only modified my return, but this time I send my object and it ignored my predefined values, like the "pin" for example. That way I didn't know how to format my date either, using "dateBr". I believe that the best way to send is the first one, but I need all the data
export function createUsers(user: userApi) {
user.pin = '001'
user.customFields = []
//@ts-ignore
user.admission_at = selectedDate.value
return axios.post('/users', user)
}
export interface userApi extends Record<string, unknown>{
customFields?: string[];
company?: number|string;
email: string;
password: string;
name: string;
admission_at: string;
cpf: string;
profession: string;
phone: string;
pin?: string;
enrollment: string;
department_id: string;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72000906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to animate a page on unload, after new page has preloaded (jQuery) I am trying to animate a page out while a new page is loading in. The effect I am going for is similar to the process used on this site http://www.whitefrontier.ch/. I am more of a designer than a developer so I have had no luck with this. Below are the two solutions that I have tried that I think are closest to correct. I realize on that site, they are using fancybox as a preloader. Do i need fancybox to get the desired result?
$(window).load(function() {
$('a').animate({right: '250px'},"slow");
});
$(window).on('beforeunload', function(){
$('a').animate({right: '250px'},"slow");
});
A: Instead of using $.unload() why not use a page pre-loader? This is a common design pattern for web pages that have to load large static assets(like videos or large images). You can setup your page pre-loader like this:
//example js
//Show your web page once all the assets are fully loaded
$(window).load(function()
{
$('#preLoader').hide(); //Or whatever animation you want to remove the preloader
$('#pageWrapper').show(); //Or whatever animation you want to show the page
});
<!-- Example HTML -->
<div id="preLoader">
<h1>Loading.....</h1>
</div>
<div id="pageWrapper" style="display:none;">
[page content goes here]
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29839180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why references to Strings don't behave like other Objects references?
In the following code
public class Test {
public static void main(String[] args){
int [] arr = new int[]{1,2};
String b=new String("abc");
f(b,arr);
System.out.println(b);
System.out.println(arr[0]);
}
public static void f(String b, int[] arr){
b+="de";
b=null;
arr[0] = 5;
}
}
Why the reference variable of the string doesn't behave like the reference variable of the array?.
I know string are immutable so operations on them creates new string but how about references to strings and how the reference b still refer to the old value although it was changed to refer to something else in f() method.
A: Object references in Java are passed by value. Assigning just changes the value, it does not alter the original object reference.
In your example arr[0] is changed, but try arr=null and you will see it has no effect after the method has returned.
A: Method call is called by value in Java, well there is long debate about this , But I think that we should consider in terms of implementation language of Java which is C/C++. Object references just pointers to objects, and primitives are the values.. Whenever a method is called, actual arguments are copied to formal parameters. Therefore, if you change pointer to reference another object , original pointer is not affected by this change, but if you change object itself, calling party can also see the changes, because both party are referring the same object..
Well, in your example, you are changing string reference to null in called method, but you are changing object referred by array reference.. These two operations are not the same, therefore they do have different consequences.. for example, if you change the code as below, they would be semantically same operation..
arr = null;
A: You cnanot change the argument for any method, however you can do the following.
public static void main(String... args) throws IOException {
String[] strings = {"Hello "};
addWorld(strings);
System.out.println("Using an array "+Arrays.toString(strings));
StringBuilder text = new StringBuilder("Hello ");
addWorld(text);
System.out.println("Using a StringBuilder '" + text+"'");
}
private static void addWorld(String[] strings) {
for(int i=0;i<strings.length;i++)
strings[i] += "World!";
strings = null; // doesn't do anything.
}
private static void addWorld(StringBuilder text) {
text.append("World !!");
text = null; // doesn't do anything.
}
prints
Using an array [Hello World!]
Using a StringBuilder 'Hello World !!'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5653034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generic methods T extends I want to do something like that:
public final <T>T getObject(Class <T extends MyObject> myObjectClass){
//...
}
IDE complains about syntax error. How to write this correctly?
A: You declared the generic type bound in the wrong place.
It should be declared within the declaration of the generic type parameter:
public final <T extends MyObject> T getObject(Class<T> myObjectClass)
{
//...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49092960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: os.path.join - how to cope with absolute path Python 3.5.2
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
I want to join them:
STATIC_ROOT = os.path.join(PROJECT_PATH, STATIC_URL)
The result is '/static/'.
This is the documentation:
https://docs.python.org/3/library/os.path.html
We can read that "If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component."
In my case BASE_DIR in the debugger is '/home/michael/PycharmProjects/photoarchive/photoarchive'.
Well, this is an absolute path. Well, it eve was acquired via abspath function.
So, there first component - BASE_DIR - is an absolute path.
Could you tell me why it is thrown away?
And how to get '/home/michael/PycharmProjects/photoarchive/photoarchive/static'?
A: "If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component." applies here: STATIC_URL is an absolute path because it starts with /, so BASE_DIR is dropped.
Drop the leading / else dirname thinks that STATIC_URL is absolute and keeps only that.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = 'static/'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39307631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Whats efficient way to sort a SparseArray by its keys? I'm using SparseArray to replace need of HashMap considering that it is memory efficient. But I can't see any similar sorting method for SparseArray like Collections.sort . How can i sort it without effecting performance?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52620638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CONNECT within Postgres SQL file Is there a command for connecting to a database within an SQL file?
I want to create a database and then immediately begin populating it with tables and data. All contained within a single .sql file. I'm not aware of anything that replaces the \c shell command?
Example SQL file:
CREATE DATABASE mydb;
CREATE USER myusername WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myusername;
CONNECT TO mydb USER myusername; --<-- something like this?
CREATE TABLE administrator (
id integer NOT NULL,
admin_name character varying(150),
password character varying(255),
active boolean,
"timestamp" timestamp without time zone,
email character varying(255)
);
ALTER TABLE administrator OWNER TO myusername;
CONNECT is the closest thing I've found in the documentation, but it's encountering syntax errors. I couldn't find a wrapper that specifies where the tables should go either?
ERROR: syntax error at or near "CONNECT"
A: Add the below statement instead of connect to db
\c mydb;
The reorder statements of execution should be
CREATE DATABASE mydb;
\c mydb;
CREATE USER myusername WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myusername;
CREATE TABLE administrator (
id integer NOT NULL,
admin_name character varying(150),
password character varying(255),
active boolean,
"timestamp" timestamp without time zone,
email character varying(255)
);
ALTER TABLE administrator OWNER TO myusername;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53663974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Changing proportion of agreeing values in numpy arrays I have a problem I've been trying to think through. Say I have a numpy array that looks like this (in the actual implementation, len(array) will be around 4500):
array = np.repeat([0, 1, 2], 2)
array >> [0, 0, 1, 1, 2, 2]
From this, I'm trying to generate a new (shuffled) array where the proportion of values that randomly agree with array is a particular proportion p. So let's say p = .5. Then, an example new array would be something like
array = [0, 0, 1, 1, 2, 2]
new_array = [0, 1, 2, 1, 0, 2]
where you can see that exactly 50% of the values in new_array agree with the values in array. The requirements of the output array are:
np.count_nonzero(array - new_array) / len(array) = p, and
set(np.unique(array)) == set(np.unique(new_array)).
By "agree" I mean array[i] == new_array[i] for agreeing indices i. All values in new_array should be the same as array, just shuffled.
I'm sure there's an elegant way of doing this -- can anybody think of something?
Thanks!
A: You can try something like
import random
p = 0.5
arr = np.array([0, 0, 1, 1, 2, 2])
# number of similar elements required
num_sim_element = round(len(arr)*p)
# creating indeices of similar element
hp = {}
for i,e in enumerate(arr):
if(e in hp):
hp[e].append(i)
else:
hp[e] = [i]
#print(hp)
out_map = []
k = list(hp.keys())
v = list(hp.values())
index = 0
while(len(out_map) != num_sim_element):
if(len(v[index]) > 0):
k_ = k[index]
random.shuffle(v[index])
v_ = v[index].pop()
out_map.append((k_,v_))
index += 1
index %= len(k)
#print(out_map)
out_unique = set([i[0] for i in out_map])
out_indices = [i[-1] for i in out_map]
out_arr = arr.copy()
#for i in out_map:
# out_arr[i[-1]] = i[0]
for i in set(range(len(arr))).difference(out_indices):
out_arr[i] = random.choice(list(out_unique.difference([out_arr[i]])))
print(arr)
print(out_arr)
assert 1 - (np.count_nonzero(arr - out_arr) / len(arr)) == p
assert set(np.unique(arr)) == set(np.unique(out_arr))
[0 0 1 1 2 2]
[1 0 1 0 0 2]
A: Here's a version that might be a little easier to follow:
import math, random
# generate array of random values
a = np.random.rand(4500)
# make a utility list of every position in that array, and shuffle it
indices = [i for i in range(0, len(a))]
random.shuffle(indices)
# set the proportion you want to keep the same
proportion = 0.5
# make two lists of indices, the ones that stay the same and the ones that get shuffled
anchors = indices[0:math.floor(len(a)*proportion)]
not_anchors = indices[math.floor(len(a)*proportion):]
# get values of non-anchor indices, and shuffle them
not_anchor_values = [a[i] for i in not_anchors]
random.shuffle(not_anchor_values)
# loop original array, if an anchor position, keep original value
# if not an anchor, draw value from shuffle non-anchor value list and increment the count
final_list = []
count = 0
for e,i in enumerate(a):
if e in not_anchors:
final_list.append(i)
else:
final_list.append(not_anchor_values[count])
count +=1
# test proportion of matches and non-matches in output
match = []
not_match = []
for e,i in enumerate(a):
if i == final_list[e]:
match.append(True)
else:
not_match.append(True)
len(match)/(len(match)+len(not_match))
Comments in the code explain the approach.
A: (EDITED to include a different and more accurate approach)
One should note that not all values of the shuffled fraction p (number of shuffled elements divided by the total number of elements) is accessible.
The possible value of p depend on the size of the input and on the number of repeated elements.
That said, I can suggest two possible approaches:
*
*split your input into pinned and unpinned indices of the correct size and then shuffle the unpinned indices.
import numpy as np
def partial_shuffle(arr, p=1.0):
n = arr.size
k = round(n * p)
shuffling = np.arange(n)
shuffled = np.random.choice(n, k, replace=False)
shuffling[shuffled] = np.sort(shuffled)
return arr[shuffling]
The main advantage of approach (1) is that it can be easily implemented in a vectorized form using np.random.choice() and advanced indexing.
On the other hand, this works well as long as you are willing to accept that some shuffling may return you some elements unshuffled because of repeating values or simply because the shuffling indexes are accidentally coinciding with the unshuffled ones.
This causes the requested value of p to be typically larger than the actual value observed.
If one needs a relatively more accurate value of p, one could just try performing a search on the p parameter giving the desired value on the output, or go by trial-and-error.
*implement a variation of the Fisher-Yates shuffle where you: (a) reject swappings of positions whose value is identical and (b) pick only random positions to swap that were not already visited.
def partial_shuffle_eff(arr, p=1.0, inplace=False, tries=2.0):
if not inplace:
arr = arr.copy()
n = arr.size
k = round(n * p)
tries = round(n * tries)
seen = set()
i = l = t = 0
while i < n and l < k:
seen.add(i)
j = np.random.randint(i, n)
while j in seen and t < tries:
j = np.random.randint(i, n)
t += 1
if arr[i] != arr[j]:
arr[i], arr[j] = arr[j], arr[i]
l += 2
seen.add(j)
while i in seen:
i += 1
return arr
While this approach gets to a more accurate value of p, it is still limited by the fact that the target number of swaps must be even.
Also, for inputs with lots of uniques the second while (while j in seen ...) is potentially an infinite loop so a cap on the number of tries should be set.
Finally, you would need to go with explicit looping, resulting in a much slower execution speed, unless you can use Numba's JIT compilation, which would speed up your execution significantly.
import numba as nb
partial_shuffle_eff_nb = nb.njit(partial_shuffle_eff)
partial_shuffle_eff_nb.__name__ = 'partial_shuffle_eff_nb'
To test the accuracy of the partial shuffling we may use the (percent) Hamming distance:
def hamming_distance(a, b):
assert(a.shape == b.shape)
return np.count_nonzero(a == b)
def percent_hamming_distance(a, b):
return hamming_distance(a, b) / len(a)
def shuffling_fraction(a, b):
return 1 - percent_hamming_distance(a, b)
And we may observe a behavior similar to this:
funcs = (
partial_shuffle,
partial_shuffle_eff,
partial_shuffle_eff_nb
)
n = 12
m = 3
arrs = (
np.zeros(n, dtype=int),
np.arange(n),
np.repeat(np.arange(m), n // m),
np.repeat(np.arange(3), 2),
np.repeat(np.arange(3), 3),
)
np.random.seed(0)
for arr in arrs:
print(" " * 24, arr)
for func in funcs:
shuffled = func(arr, 0.5)
print(f"{func.__name__:>24s}", shuffled, shuffling_fraction(arr, shuffled))
# [0 0 0 0 0 0 0 0 0 0 0 0]
# partial_shuffle [0 0 0 0 0 0 0 0 0 0 0 0] 0.0
# partial_shuffle_eff [0 0 0 0 0 0 0 0 0 0 0 0] 0.0
# partial_shuffle_eff_nb [0 0 0 0 0 0 0 0 0 0 0 0] 0.0
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
# partial_shuffle [ 0 8 2 3 6 5 7 4 9 1 10 11] 0.5
# partial_shuffle_eff [ 3 8 11 0 4 5 6 7 1 9 10 2] 0.5
# partial_shuffle_eff_nb [ 9 10 11 3 4 5 6 7 8 0 1 2] 0.5
# [0 0 0 0 1 1 1 1 2 2 2 2]
# partial_shuffle [0 0 2 0 1 2 1 1 2 2 1 0] 0.33333333333333337
# partial_shuffle_eff [1 1 1 0 0 1 0 0 2 2 2 2] 0.5
# partial_shuffle_eff_nb [1 2 1 0 1 0 0 1 0 2 2 2] 0.5
# [0 0 1 1 2 2]
# partial_shuffle [0 0 1 1 2 2] 0.0
# partial_shuffle_eff [1 1 0 0 2 2] 0.6666666666666667
# partial_shuffle_eff_nb [1 2 0 1 0 2] 0.6666666666666667
# [0 0 0 1 1 1 2 2 2]
# partial_shuffle [0 0 1 1 0 1 2 2 2] 0.2222222222222222
# partial_shuffle_eff [0 1 2 1 0 1 2 2 0] 0.4444444444444444
# partial_shuffle_eff_nb [0 0 1 0 2 1 2 1 2] 0.4444444444444444
or, for an input closer to your use-case:
n = 4500
m = 3
arr = np.repeat(np.arange(m), n // m)
np.random.seed(0)
for func in funcs:
shuffled = func(arr, 0.5)
print(f"{func.__name__:>24s}", shuffling_fraction(arr, shuffled))
# partial_shuffle 0.33777777777777773
# partial_shuffle_eff 0.5
# partial_shuffle_eff_nb 0.5
Finally some small benchmarking:
n = 4500
m = 3
arr = np.repeat(np.arange(m), n // m)
np.random.seed(0)
for func in funcs:
print(f"{func.__name__:>24s}", end=" ")
%timeit func(arr, 0.5)
# partial_shuffle 213 µs ± 6.36 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# partial_shuffle_eff 10.9 ms ± 194 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# partial_shuffle_eff_nb 172 µs ± 1.79 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66335622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Find substring which comes in middle or right of any string I want to replace any occurrence of a substring which does not come in left . Like,
*
*Input : "ComputerPart"
Find substring ="t"
Replace substring ="success"
Output : CompusuccesserParsuccess
*Input : "topaz"
Find substring ="t"
Replace substring ="success"
Output : topaz //t comes at first place (left) of string 'topaz' so it should not be replaced.
*Input : "questions"
Find substring ="t"
Replace substring ="success"
Output : quessuccessions //this time it should be replaced as 't' found in middle of string 'questions'
Please help me to find a regex pattern in C# for this purpose and any code samples to achieve this.
A: You are looking for not a word boundary on the left:
\Bt
See it here on regexr.
\B is a zero width assertion that matches when on the left side of a position and of the right side is a word character (or a non word character). So here you have a "t" to the right of \B, so it will only match if on the left of the "t" is also a word character.
In other words: It replaces every "t" that is not on the start of a "word".
So I tested it now in c#:
string[] myStrings = { "ComputerPart",
"topaz",
"questions"
};
Regex reg = new Regex(@"\Bt");
foreach (string str in myStrings) {
Console.Out.WriteLine(reg.Replace(str, "success") );
}
and it produces exactly the same output than regexr:
CompusuccesserParsuccess
topaz
quessuccessions
A: how about:
int pos = text.IndexOf("t");
if(pos>0)
text = text.Replace("t", "Success");
Do I get your homework credit :-)
A: I want more homework credit this time!
string readText = File.ReadAllText(path);
string[] lines = readText.Split(Environment.NewLine);
string output;
foreach(string line in lines)
{
int pos = text.IndexOf("t");
if(pos>0)
text = text.Replace("t", "Success");
output += text + Environment.NewLine;
}
File.AppendAllText(newPath, output);
A: I guess this is what you need,
string[] inputstrings = { "ComputerPart", "topaz", "questions" };//An array of input strings to manipulate.
string output = "";
Regex rgx = new Regex("t");//Regex pattern to match occurence of 't'.
foreach (string inputstring in inputstrings)//Iterate through each string in collection.
{
output = rgx.Replace(inputstring, "success", int.MaxValue, 1);//Replace each occurence of 't' excluding those occurring at position [0] in inputstring.
MessageBox.Show(output);//Show output string.
}
What I've done is :
*
*Loop through each string in collection.
*Match each string against the regular expression for any occurrences of 't'.
*The search begins at position 1 in the array of characters derived from each string.So it
automatically leaves any occurrence of 't' at start of string.
Ideone sample.
Hope it helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18895873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Set_Rules Error in Linux : Undefined property: Welcome::$input I am learning codeigniter. I am watching a course videos in udemy.The last video was about the form validation. I wrote the codes in the video. But it is not working in ubuntu. Codes only work on windows. I get an error when I try to use the set rules function. Codeigniter folder permissions are 755. Where is the problem ? CODES ARE WORKING IN WINDOWS BUT NOT WORKING LINUX :)
Welcome class :
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('form');
}
public function save(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Username', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
echo 'başarılı';
}
}
}
Form view :
<form action="<?=base_url("Welcome/save")?>" method="post">
<input type="text" id="fname" name="name"><br>
<button type="submit">Gönder</button>
</form>
Error image :
Sorry, click for error picture.
Error :
A: It seems, Input library is damaged. Replace the following file with an original one.
system/core/Input.php
Or try a fresh install.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61508228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cakephp Route Top Level Request I have a 1.2 app that I'm updating to 1.3. I need to send all top level requests like /foo to a controller action (/sites/view/$1) if they are not a valid controller. So in my 1.2 app I had a route like this (incredibly ugly I know):
Router::connect('(?!admin|billings|carriers|clips|cliptypes|contacts|domains|faqs|leadcomments|leads|leadnotes|sites|teams|users|signupstart|botickets|salestickets|callplaylists|clipcreators|prospectingplaylists|roles|sitethemes|teamannouncements|teamproducts|teamsupportitems|teamthemes|trainingplaylists|trainingfiles|sitetransfers|stats|paymentperiods|search)(.*)', array('controller' => 'sites', 'action' => 'view'));
In cake 1.3 I receive the missing controller message instead of the request getting sent to sites->view().
Thanks for any help,
Jeremy
A: They removed some features in the routing for 1.3:
*
*"First path segments using full regular expressions was removed."
*"Next mid-route greedy star support has been removed."
From migration guide:
http://book.cakephp.org/view/1561/Migrating-from-CakePHP-1-2-to-1-3#Library-Classes-1565
See also 1.3 API:
http://api13.cakephp.org/class/router#method-Routerconnect
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3622327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inserting the elements in grid column wise and creating different controls I am new to Asp.net and C#.I am working in a project where I need to create GridView.Now I wanted to bind this column wise with the data.Like the column1 in the grid is "Category" in the table of database and so on. I also want to create the Hyperlink on the basis of the content in database for example I want to show the text of Hyperlink as "This is Java program" and URL specifies as "http://blogs.article?id=1".Please tell me that how I can do that.Currently I am able to bind the all three columns in the table to the three columns in the grid.
A: Take a look at the HyperLinkField class. This should provide exactly what you're looking for.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7618245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Eclipse Text Editor Behaviour under Linux I use Eclipse Luna 4.4.0 under Ubuntu 14.04.1 LTS. When I edit a file (especially a Java file), then the editor has a vi-like behaviour with a command and edit mode. But I want the same editor behaviour as under Windows which is like Notepad(++), without a command mode.
I couldn't find any key settings under Windows -> Preferences -> General -> Keys. There's a default scheme, a "vim's key bindings" scheme and an emacs scheme, but there seems to be no difference between the default and the vim scheme. And, additionally, I couldn't find any way to export Windows' editor preferences and to import them under Linux.
Is there any way to solve my problem? Or do we have this different behaviour due to platform-dependent implementation?
A: I guess, you have Vrapper or a different plug-in installed that provides these key bindings. If you don't want to have these features, try to uninstall them (select Help -> About from the menu, then click on Installation Details button on the bottom of the About dialog, where you can look for any possible culprits, and uninstall them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26884377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error : null value being entered in table through jsp code My code snippets are as below :
ShopRegister2.jsp :
<%
session = request.getSession();
session.setAttribute("s_id", s_id);
out.println("Your id is : "+s_id);
%>
<br>
Please note it for further use.!<br>
<form name="register" method="post" onsubmit=" return reg_form()" action="ShopRegister3.jsp"><br>
Enter your name : <input type="text" name="s_name" id="s_name"><br>
Enter your Location : <input type="text" name="s_location" id="s_location"><br>
Enter your password : <input type="password" name="s_password" id="s_password"> <br>
Confirm Password : <input type="password" name="c_s_password" id="c_s_password"><br>
<input type="submit" value="Submit"><br>
</form><br>
ShopRegister3.jsp :
String s_name=null, s_password=null, s_location=null;
int s_id = 0;
session.setAttribute("s_name", s_name);
session.setAttribute("s_password", s_password);
session.setAttribute("s_location", s_location);
String s_id_string=(String)request.getParameter("s_id");
s_id = session.getAttribute("s_id") != null ? (Integer) session.getAttribute("s_id") : 0 ;
s_name=(String)session.getAttribute("s_name");
s_password=(String)session.getAttribute("s_password");
s_location=(String)session.getAttribute("s_location");
//entering values into Shop table
PreparedStatement s_insert = con.prepareStatement("insert into ShopSystem.Shop values(?,?,?,?)");
s_insert.setInt(1, s_id);
s_insert.setString(2, s_password);
s_insert.setString(3, s_location);
s_insert.setString(4, s_name);
int c = s_insert.executeUpdate();
//checking whether the value was inserted successfully
if(c>0)
{ %>
S_ID = <%= s_id %> has been registered successfully.<br>
<% response.sendRedirect("ShopMenu3.jsp");
} %>
In the above code the server is directing to ShopMenu3.jsp after running ShopRegister3.jsp
Yet in my database, null values are being entered for the attributes : name, password and location.
I have tried many things..., where exactly seems to be the error?
A: Your session variables are always set to null;
Use:
s_name=(String)request.getParameter("s_name");
s_password=(String)request.getParameter("s_password");
s_location=(String)request.getParameter("s_location");
To get the values before setting them in the session
A: Maybe that is the problem?
String s_name=null, s_password=null, s_location=null;
And then you set session to this null values.
A: You have to first request that parameter before setSession statement;
so in ShopRegister3.jsp, after s_name initialization to `null´.
Request that parameter like:
s_name = request.getParameter("s_name");
Now you can setSession for this variable; it will not return null for s_name variable now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25136860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DFP expandable ads i've supplied an adv creative to a publisher that use Doubleclick for publisher to distribuite the ad unit.
For standard masthead there is no problem, but for expandable masthead i cannot figure out how to do.
My adv creatives ad IAB compliant so for expanding creative i use safeframe standard, but on publisher rendered iframe there is no object $sf, so no safeframe.
What API can i use in DFP iframe for expanding creatives? It is safeframe compliant?
Also the expanding creative loaded have height=1px, i don't know why.
I've tested my safeframe implementation here: http://safeframes.net/examples/creative_test.html
and works like a sharm.
Thanks.
A: Is the publisher actually using async serving or is the creative actually wrapped in a Safe Frame?
The reason I am asking is because if the publisher uses synchronous serving and haven't selected to wrap the creative in SafeFrame, there will be no such.
A: It looks like, you don't display ad from SafeFrame, but from Friendly Iframe, or you call DFP synchronicaly. Try to debug your ad unit on page, if it came from SafeFrame https://support.google.com/dfp_premium/answer/7449957?hl=en&ref_topic=7362877.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40004518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: template argument deduction with strongly-typed enumerations If I have a normal (weak) enumeration, I can use its enumerated values as non-type template parameters, like so:
enum { Cat, Dog, Horse };
template <int Val, typename T> bool magic(T &t)
{
return magical_traits<Val>::invoke(t);
}
and call it as: magic<Cat>(t)
as far as I can see, if I have a strongly-typed enumeration and don't want to hard-code the enumeration type, I end up with:
enum class Animal { Cat, Dog, Horse };
template <typename EnumClass, EnumClass EnumVal, typename T> bool magic(T &t)
{
return magical_traits<EnumVal>::invoke(t);
}
and now I have to write: magic<Animal, Animal::Cat>(t), which seems redundant.
Is there any way to avoid typing out both the enum class and the value, short of
#define MAGIC(E, T) (magic<decltype(E), E>(T));
A: If you're only interested in the enum's value, and not its type, you should be able to use a constexpr function to convert the value to an integer, avoiding repeating the type name.
enum class Animal { Cat, Dog, Horse };
template <typename T> constexpr int val(T t)
{
return static_cast<int>(t);
}
template <int Val, typename T> bool magic(T &t)
{
return magical_traits<Val>::invoke(t);
}
magic<val(Animal::Cat)>(t);
However, as pointed out already by others, if you want to make this depend on the type as well, it will not work.
A: You can do it like this, if you can use C++17
#include <type_traits>
enum class Animal { Cat, Dog, Horse };
template <typename EnumClass, EnumClass EnumVal>
void magic_impl()
{
static_assert(std::is_same_v<EnumClass, Animal>);
static_assert(EnumVal == Animal::Cat);
}
template <auto EnumVal>
void magic()
{
magic_impl<decltype(EnumVal), EnumVal>();
}
int main()
{
magic<Animal::Cat>();
}
demo:
http://coliru.stacked-crooked.com/a/9ac5095e8434c9da
A: This question has an accepted answer (upvoted).
While refactoring my own code, I figured out a more complete solution:
Step 1: using code I was writing:
template<typename V, typename EnumClass, EnumClass Discriminator>
class strong_type final // type-safe wrapper for input parameters
{
V value;
public:
constexpr explicit strong_type(V x): value{x} {}
constexpr auto get() const { return value; }
};
Step 2: client code:
enum class color { red, green, blue, alpha };
// the part OP was asking about:
template<color C>
using color_channel = strong_type<std::uint8_t, color, C>;
using red = color_channel<color::red>; // single argument here
using green = color_channel<color::green>;
using blue = color_channel<color::blue>;
using alpha = color_channel<color::alpha>;
A: I'm sorry, I have to tell you that
It is not possible
Take the macro, put it into a scary named header and protect it from your colleague's cleanup script. Hope for the best.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9400581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Automatically Resume a Suspended Windows Process I'm trying to write a windows batch file in order to resume a windows process that gets Suspended. I'm using pssuspend (from pstools) to resume the process. However, I'm trying to write windows batch file script that will continually get the status of a process (e.g. myExe.exe). If the script is not suspended, I would like for it to keep checking if it is suspended. If it is suspended, I would like it to run the pssuspend code. I'm unsure how to obtain the Suspend status. So far I have this:
if myExe.exe == "Suspend" (
pssuspend -r myExe.exe
suspend_fix.bat
) else (
suspend_fix.bat
)
Thanks for your help!
A: Windows services (that are created with the right attributes) can be suspended, but I am not sure how an executable can be suspended, or what exactly you mean by that.
If you mean that the program has been stopped, and when it does, you want to restart it, then here are a couple of code blocks that I have used to determine if a program is running:
1) by checking to see if the exe name exists, i.e., is running.
By the way, I recommend this one from my interpretation of your post:
BOOL ExeExists(char *exe)
{
HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(pe);
if (Process32First(pss, &pe))
{
do
{
if (strstr(pe.szExeFile,exe))
{
CloseHandle(pss);
return TRUE;
}
}
while(Process32Next(pss, &pe));
}
CloseHandle(pss);
return FALSE;
}
2) by checking to see if the PID exists
BOOL PidExists(int pid)
{
HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(pe);
if (Process32First(pss, &pe))
{
do
{
if (pe.th32ProcessID == pid)
{
CloseHandle(pss);
return TRUE;
}
}
while(Process32Next(pss, &pe));
}
CloseHandle(pss);
return FALSE;
}
By the way this is used to get the process ID (it is defined in winbase.h)
of the application making the call.
int GetProcessIdApp(void)
{
return GetProcessId(GetCurrentProcess());//defined in WinBase.h
}
Inside WinBase.h
WINBASEAPI
DWORD
WINAPI
GetProcessId(
__in HANDLE Process
);
In my scenario, An application broadcasts its PID at start up, such that
my monitoring program (the Windows service) can read it, then use it to make an ongoing determination of the application's status. If the app is discovered to be dead, and if other criteria indicate it should still be running, my service will start it back up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24898328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: trying to download zip file in R 4.0, works in windows, linux but not in MacOS..."HTTP status was '400 Bad Request" I am going bonkers as I switched from a windows tablet to my macbook pro earlier today and cannot seem to run the identical (seemingly trivial) command in R4.02, namely to download a zip file located at the following link:
http://askebsa.dol.gov/FOIA%20Files/2018/Latest/F_5500_SF_2018_Latest.zip
I used the R base syntax of: download.file(url, destfile= "xyz.csv") and it worked as expected in windows, but when I run it in Mac, I get 'HTTP status was '400 Bad Request'. I can manually download it in Mac, I just need to do it in R.
Any ideas if this a cache, cookie or some other issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64473308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Apply a discount to order if user already ordered something else I have a table with users, a table with levels, a table for submitted orders and processed orders.
Here's what the submitted orders looks like:
OrderId UserId Level_Name Discounted_Price Order_Date Price
1 1 OLE Core 0 2020-11-01 00:00:00.000 19.99
2 1 Xandadu 1 2020-11-01 00:00:00.000 0
3 2 Xandadu 0 2020-12-05 00:00:00.000 5
4 1 Eldorado 1 2021-01-31 00:00:00.000 9
5 2 Eldorado 0 2021-02-20 00:00:00.000 10
6 2 Birmingham Blues NULL 2021-07-10 00:00:00.000 NULL
What I am trying to do:
UserId 2 has an order for Birmingham Blues, they have already ordered Eldorado and so qualify for a discount on their Birmingham Blues order. Is there a way to check the entire table for this similarity, and if it exists update the discounted price to a 1 and change the price to lets say 10 for the Birmingham Blues order.
EDIT: I have researched the use of cursors, which I'm sure will do the job but they seem complicated and was hoping a simpler solution would be possible. A lot of threads seem to also avoid using cursors. I also looked at this question: T-SQL: Deleting all duplicate rows but keeping one and was thinking I could potentially use the answer to that in some way.
A: Based on your description and further comments, the following should hopefully meet your requirements - updating the row for the specified User where the values are currently NULL and the user has a qualifying existing order:
update s set
s.Discounted_Price = 1,
Price = 10
from submitted_Orders s
where s.userId=2
and s.Level_Name = 'Birmingham Blues'
and s.discounted_Price is null
and s.Price is null
and exists (
select * from submitted_orders so
where so.userId = s.userId
and so.Level_name = 'Eldorado'
and so.Order_Date < s.OrderDate
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70855549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How to write Timeoutable methods in C# I have methods which take longer time to execute and involve lots of database operations. I want to wrap these methods within timeoutable method so that if it didn't callback within constant time, I will rollback.
Is there any way to do this, also I have to run the method in the main thread only becuase the 3rd party com objects I am using cannot be executed in background thread.
Any kind of suggestion will be highly appreciated.
regards,
Bibek Dawadi
A: I was with you till you said you needed it to run in the main thread. I don't think it's possible the way you describe.
The problem is that you're going to need at least two threads to perform the timing and the actual work, and neither of those can be the main thread because a timer won't use the main thread, and because you'll want the operation to terminate, which if it were the main thread would shut down the whole app. The way you would do this normally is to set up a wrapper class that is run from the main thread and sets up the background thread for the operation as well as the timer.
Why, exactly, does the 3rd party library have to be invoked from the main thread?
A: I knocked together a solution similar to the one linked to, except that I used Thread.Interrupt() instead of Thread.Abort(), thinking that would be a little kinder to the main thread. The problem is that Thread.Interrupt() won't interrupt a call that is blocked, so it is unsatisfactory under many cases. Thread.Abort() is a dangerous call and should be avoided where possible. Pick your poison.
For what it's worth, this is my implementation:
public static class AbortableProc
{
public static void Execute(Action action, Action timeoutAction, int milli)
{
Thread currThread = Thread.CurrentThread;
object stoppedLock = new object();
bool stopped = false;
bool interrupted = false;
Thread timer = new Thread(() =>
{
Thread.Sleep(milli);
lock (stoppedLock)
{
if (!stopped)
{
currThread.Interrupt();
stopped = true;
interrupted = true;
}
}
});
timer.Start();
try
{
action();
lock (stoppedLock)
{
stopped = true;
}
}
catch (ThreadInterruptedException)
{
}
if (interrupted)
{
timeoutAction();
}
}
}
For grins, I put in a timeoutAction so that you could use it in this mode:
AbortableProc.Execute(
() => { Process(kStarting); Process(kWorking); Process(kCleaningUp); },
() => { if (IsWorking()) CleanUp(); }
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4926786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Discord bot mute command by mention I want to add few moderation commands to the bot, but I get stuck with "mute" command:
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(message.member.roles.cache.some(r => r.name === "Siren")){
const role = message.guild.roles.cache.find(r => r.name === "Muted");
const user = message.mentions.members.first().id;
user.roles.add(role);
}
}
}
I keep getting error:
TypeError: Cannot read property 'add' of undefined
I've been reading various guides and going through documentation and I keep failing on finding where I have made a mistake or what even causes this error.
A: At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined.
Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code.
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command')
const role = message.guild.roles.cache.get('21321321312');
if (!role) return message.reply('can`t get a role')
const member = message.mentions.members.first()
if (!member) return message.reply('Pls mention a member')
member.roles.add(role).then(newMember => {
message.channel.send(`successfully muted member ${member.user}`)
})
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63152582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make the table td flexible on small size I need help making the td of a table flexible.
What I got going on is this: http://jsfiddle.net/j8GyV/23/
.card_new {
width: 350px;
border: 1px solid gray;
box-shadow: 1px 1px 3px #888;
border-top: 10px solid green;
min-height: 250px;
padding-: 10px;
margin: 10px;
background-color: #FFF;
}
img {
border-radius: 50%;
width: 70px;
margin: 10px;
}
.name_new {
font-weight: lighter;
margin-left: 100px;
margin-top: -70px;
}
.info_new {
margin: 10px;
font-family: segoe ui;
line-height: 1.4em;
font-size: 1.2em;
}
#mainbox, .split_3 {
box-sizing: border-box;
justify-content: center;
display: flex;
flex-wrap: wrap;
}
What I want to accomplish is exactly what I got going on in the jsfiddle, but when the width of the result window gets small enough for the table td's to be stacked on-top of eachother, I want the table td to start resizing(being flexible) itself to still fit in the result window, and not have the right side disappear behind the edge.
A: You could add a media query like this:
@media (max-width: 768px) {
.card_new {
width: 100%;
}
}
See http://jsfiddle.net/j8GyV/25/
A: So I knew what you meant so I decided to add styling to td to make it wrap.
td {
display: -webkit-flex; /* Safari */
-webkit-flex-wrap: wrap; /* Safari 6.1+ */
display: flex;
flex-wrap: wrap;
min-width: 10%;
}
And it worked!
http://jsfiddle.net/j8GyV/30/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45402704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OwinStartup not Starting ... Why? I have the following class on an ASP.NET MVC 5 site:
[assembly: OwinStartup(typeof(MVCSite.Startup))]
namespace MVCSite {
public partial class Startup {
public void Configuration(IAppBuilder application) {
application.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
application.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
}
And on Web.Config I have the following:
<add key="owin:AutomaticAppStartup" value="false"/>
I have a breakpoint inside Startup.Configuration but this does not fire ...
Any idea why?
A: It's usually happend because SystemWeb package is not installed on your project.
Use this command at your Package Manager Console:
Install-Package Microsoft.Owin.Host.SystemWeb
In the other hand you may use this configuration on your app.config or web.config if the above solution is not work:
<appSettings>
<add key="owin:AutomaticAppStartup" value="true"/>
</appSettings>
A: Using
<add key="owin:AutomaticAppStartup" value="true"/>
Is the answer.
A: Try removing [assembly: OwinStartup(typeof(MVCSite.Startup))] and give a shot
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19760545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How to make a Messagebox wait in C#? Example: when i click on the Button i want that the Programm will wait for 4 Secons before the MessageBox pops up :)
Whats the code for that? thanks :)
i tried it with a timer but the MessageBox pops up Automaticly when i Press the Button
A: As JDro04 pointed out, you can use Thread.Sleep to do delay. But your app will hang if you do it from main thread. So you can do delay in separate thread and invoke MessageBox.Show in the main one, here's the snippet:
private void Button1_Click(object sender, RoutedEventArgs e)
{
Task.Factory
.StartNew(() => Thread.Sleep(4000))
.ContinueWith(
continuationAction: _ => { MessageBox.Show("My message!"); /* put rest of your code here */ },
cancellationToken: CancellationToken.None,
continuationOptions: TaskContinuationOptions.None,
scheduler: TaskScheduler.FromCurrentSynchronizationContext());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41902109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get the number of undelivered messages (metric api) present in Pubsub using python client library? I am using Pubsub as a queuing mechanism tool and want to know the count of the messages residing inside the topic of Pubsub. For the same purpose, I have decided to use the Google API metric pubsub.googleapis.com/subscription/num_undelivered_messages but I am unable to figure out how can this be achieved using python client library monitoring_v3.
from google.cloud import monitoring_v3
import time,os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/key.json"
client = monitoring_v3.MetricServiceClient()
project = 'project_name'
project_name = client.project_path(project)
metric_type = "pubsub.googleapis.com/subscription/num_undelivered_messages"
Can you please guide me on how to proceed further and query this google api metric named as num_undelivered_messages?
A: This works for me but I am not sure if it's the creator's intention.
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "..."
client = monitoring_v3.MetricServiceClient()
result = query.Query(
client,
project,
'pubsub.googleapis.com/subscription/num_undelivered_messages',
minutes=1).as_dataframe()
A: You might need to run your code this way for a specific subscription:
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "my-project"
client = monitoring_v3.MetricServiceClient()
result = query.Query(client,project,'pubsub.googleapis.com/subscription/num_undelivered_messages', minutes=60).as_dataframe()
print(result['pubsub_subscription'][project]['subscription_name'][0])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55613144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: find nearest key match with input value greater or equal to key and records unsorted I'm having the below input file and trying to find out the nearest key match with input value greater or equal to key. It works when the input file is sorted.
Input file:
10,Line1
20,Line2
30,Line3
40,Line4
50,Line5
55,Line6
70,Line7
75,Line8
90,Line9
95,Line10
99,Line11
Code that I tried:
$ awk -F, -v inp=85 ' NR==1 { dp=0 } { dt=($1-inp); d=sqrt(dt*dt); if(d<=dp && inp >= $1 ) { rec=$0 } dp=d } END { print rec } ' source.txt
75,Line8
$ awk -F, -v inp=55 ' NR==1 { dp=0 } { dt=($1-inp); d=sqrt(dt*dt); if(d<=dp && inp >= $1 ) { rec=$0 } dp=d } END { print rec } ' source.txt
55,Line6
It works fine when the source.txt is sorted on the key column i.e first. But it gives incorrect results when the file is not sorted
$ shuf source.txt | awk -F, -v inp=85 ' NR==1 { dp=0 } { dt=($1-inp); d=sqrt(dt*dt); if(d<=dp && inp >= $1 ) { rec=$0 } dp=d } END { print rec } '
50,Line5 # Wrong
Can this be fixed for the unsorted file?.
Solutions using any unix tools are welcome!
A: You may use this awk:
awk -F, -v n=85 'n>=$1 && (max=="" || $1>max){max=$1; rec=$0} END{print rec}' file
75,Line8
Run this again with a different value:
awk -F, -v n=55 'n>=$1 && (max=="" || $1>max){max=$1; rec=$0} END{print rec}' file
55,Line6
A: With Perl
perl -0777 -wnE' $in = shift // 85;
%h = split /(?:\s*,\s*|\s*\n\s*)/;
END { --$in while not exists $h{$in}; say "$in, $h{$in}" }
' data.txt 57
Notes
*
*read the whole file into a string ("slurp"), by -0777
*populate a hash with file data; I strip surrounding spaces in the process
*count down from input-value and check for such a key, until we get to one that exists
*input is presumed integer and being in range
The nearest key is the first one that exists as input "clicks" down toward it an integer at a time.
The invocation above (for 57) prints the line: 55, Line6.
A version that does check the range of input and allows non-integer input
perl -MList::Util=min -0777 -wnE' $in = int shift // 85;
%h = split /(?:\s*,\s*|\s*\n\s*)/;
die "Input $in out of range\n" if $in < min keys %h;
END { --$in while not exists $h{$in}; say "$in, $h{$in}" }
' data.txt 57
A: Following code comply with your requirement
use strict;
use warnings;
my $target = shift
or die "Please enter a value";
my $line;
while( <DATA> ) {
my @data = split ',';
last if $data[0] > $target;
$line = $_;
}
print $line;
__DATA__
10,Line1
20,Line2
30,Line3
40,Line4
50,Line5
55,Line6
70,Line7
75,Line8
90,Line9
95,Line10
99,Line11
A: Code for unsorted lines
use strict;
use warnings;
my $target = shift
or die "Please enter a value";
my @lines = <DATA>;
my $line;
my %data;
map { my @array = split ',', $_; $data{$array[0]} = $_ } @lines;
foreach my $key ( sort keys %data ) {
last if $key > $target;
$line = $data{$key};
}
print $line;
__DATA__
10,Line1
20,Line2
30,Line3
40,Line4
50,Line5
55,Line6
70,Line7
75,Line8
90,Line9
95,Line10
99,Line11
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58942695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: check if google recaptcha is checked or has been filled im using google recaptcha
<label for="template-contactform-botcheck">Botcheck</label>
<div id="recaptcha_sme"></div>
and I want to verify if its checked or not, has been filled or not and the way im doing it is through this code (refer below)
if ($("#recaptcha_sme #recaptcha-anchor").hasClass("recaptcha-checkbox-checked")) {
alert("the captcha has been filled");
} else {
alert("Please fill the captcha!");
}
and I don't intend to go trough server side validation (google recaptcha API checking), I just want to be notified (using alert prompt) if the google recaptcha is checked or filled. Any ideas, clues, suggestions, recommendations to make it?
below is my complete form submit script code (submit function in jquery).
$("#sme_application_dialog form").submit(function(e){
if ($(this).find("#recaptcha_sme #recaptcha-anchor").hasClass("recaptcha-checkbox-checked")) {
alert("the captcha has been filled");
} else {
alert("Please fill the captcha!");
}
e.preventDefault();
});
as you can see from above reference, I'm just trying to check if the element that has an id of "recaptcha-anchor" has a class of "recaptcha-checkbox-checked" (as i can see from DOM structure using chrome dom explorer, that class has added unto the element that has an id of "recaptcha-anchor everytime the google recaptcha is checked or has been filled) so I thought that might work but sadly and unfortunately it doesn't work.
PS: assume that I have div that has an id of "sme_application_dialog_form" and inside it there is a from and inside that form, there is the google recaptcha and I have "$(document).ready". Assume that everything set and working (except for the validation where I'm checking the google recaptcha is checked or has been filled)
A: Add data-callback to your ReCapthca div:
<div class="g-recaptcha" data-sitekey="***" data-callback="recaptchaCallback"></div>
Add this function to your code.
var recaptchachecked;
function recaptchaCallback() {
//If we managed to get into this function it means that the user checked the checkbox.
recaptchachecked = true;
}
You may now can use the recaptchachecked on your OnSubmit() function.
A: You can validate it on callback function by getting response value is null or not.
callback function
function submit(){
var response = grecaptcha`.`getResponse();
if(response != '0'){
//captcha validated and got response code
alert("the captcha has been filled");
}else{
//not validated or not clicked
alert("Please fill the captcha!");
}
}
It will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32218183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Constraints set up to many containers I have this VC:
My goal is:
*
*2 big containers up should change size for 3.5 inch display
*4 little ones should have pin size
*bottom one should be always in bottom.
What i do here:
*
*2 big containers have Heights equally properties.
*4 little ones have pin height
*bottom one have bottom space to superview
Everything is on UIImageView (i don't know if its matter)
Should I create constraints for container to container? How?
When i change to 3.5 inch display view i'm getting:
A: Remove the blue line from the top of the view to the small container on top left.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16980819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Editing a jsonb value in postgresql? I have a jsonb column that stores values like this:
{"v":"0","c":"ACC",...}
I'd like to update some of the v values to 1
Is there any built-in function to do that in postgresql?
E: I'm using v9.6
A: With Postgresql 9.5
UPDATE test SET data = data - 'v' || '{"v":1}' WHERE data->>'c' = 'ACC';
OR
UPDATE test SET data = jsonb_set(data, '{v}', '1'::jsonb);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46295537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Working with Git branches I have a Rails app deployed on Heroku and I have a git repo that I'm currently working on with uncommitted code changes. In the meantime, I need to make changes to the source on Heroku independently of the local repo. Can I do the following:
*
*Clone the Heroku git repo on the same development machine with a different app name though with the same account
*Make changes to the new local repo
*Commit those changes to the new local repo
*Push those changes to the Heroku repo
*Resume working on my original local repo
Will this approach work?
A: Yep, that workflow would work, or stash them - and don't forget if you do make a clone of the heroku repo you'll have made changes to a different clone of the repo and you'll need to make those changes in your original local repo.
In future I'd suggest that you assume that your 'master' branch is what's live on Heroku and branch of that to work in - you can even push this branch into a new app for testing purposes. This way bug fixes can be performed on your local master branch (or another branch and merged into master) and pushed to heroku and then when you've finished your new work you merge the branch back into master and deploy that to your live environment. I wrote a blog article on the subject a while back, here
A: I haven't used heroku but if I wanted to make changes to a deployed application while I had unsaved changes in my sandbox, I would do one of the following.
*
*stash my local changes, cut a branch from the point where I want to make a fix, make it, deploy it, switch back to my original branch and pop from the stash.
*Commit my unsaved changes (into the current branch - say work), cut a branch from the point where I want to make a fix, make my fix, deploy it, switch back to work, reset my HEAD to before my "temporary" commit and resume work.
Unless you're using git in an unconventional fashion, there's no need to make another clone.
A: If you clone the heroku repository to a separate directory, made changes and push it from there, then there is a possibility of conflicts later down the road.
If its only the issue with the uncommitted changes then certainly you can stash them using "git stash" and later retrieve it using "git stash pop".
A: My work-cycle: I always keep a master branch with the #1 rule "always push to Heroku after committing something to master". If I code on something that I do not want to deploy immediately, I have to branch.
I know this works not for all use cases, but having always a branch that is identical to the app that is productive on Heroku makes me sleep better ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5115091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't build APK in Unity after trying to integrate AdMob (IronSource) Integrating the IronSource plugin (v7.0.4.1) doesn't cause any issues. I know this because I am still able to build an APK successfully after installing it. Integrating some of the adapters such as AdColony and UnityAds also do not result in any problems.
However, once I try to integrate the AdMob adapter, I can no longer build an APK. I just get a prompt that says "Android resource linking failed. See the Console for details". Clicking OK results in these error logs:
A: In my case, the old audience network plugin caused the problem. Build failed when both Audience network and AdMob were present. After removing the audience network plugin (as I am not using it), the build was successful.
Update SDK, and other plugins. Resolve, and then try again.
A: Solution
The AdMob SDK requires use of the <queries> tag which for Unity 2018 and higher needs a newer Gradle feature which doesn't come with the Gradle version Unity packages.
Here is another post with the same issue.
A: Tested : Unity 2020.3.11f1 and GoogleMobileAds-v6.1.2
Step 01 : Install GoogleMobileAds plugin and setup and Asset > External Dependency Manager > Android Resolver > resolve.
Step 02 : Set Target API Level 30 in Player Setting.
enter image description here
Step 03 : Tick in Custom Main Gradle Template and Custom Launcher Gradle Template.
enter image description here
Step 04: How mainTemplate and launcherTemplate files generating. [If not view then first build ignore the errors]
enter image description here
Step 05 : Added below code into mainTemplate.gradle file with your favorite editor.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
// Must be Android Gradle Plugin 3.6.0 or later. For a list of
// compatible Gradle versions refer to:
// https://developer.android.com/studio/releases/gradle-plugin
classpath 'com.android.tools.build:gradle:3.6.0'
}
}
allprojects {
repositories {
google()
mavenCentral()
flatDir {
dirs 'libs'
}
}
}
//Look like that
enter image description here
Step 06 : Download Gradle gradle-5.6.4-all.zip from grdale.org. Download from https://services.gradle.org/distributions/
After download extract the file and set gradle path into Edit > Preference > External Tools > Gradle Install with Unity(recommended) UnChecked
enter image description here
Step 07 : Build
Helpful Link : https://developers.google.com/ar/develop/unity-arf/android-11-build
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65286688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flip the fill variable with geom_bar(position="fill, stat = "identity) in ggplot I have the following code :
newdf %>%
ggplot() +
aes(x = smoke_status, y = Count, fill = Birth_status) +
xlab("Smoking Activity") +
ylab("Proportion") +
labs(fill = "Birthweight") +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = scales::percent)
How can I change the plot so that the percentage in red corresponding to "low birth weight" is at the bottom of the bar chart?
Thank you in advance!
If you want to test with my dataframe I used the opt dataset from the medicaldata package:
install.packages("medicaldata")
library(medicaldata)
newdf = opt %>%
filter(BL.Cig.Day != "NA", Birthweight != "NA") %>%
select(c(cig = BL.Cig.Day, Birthweight)) %>%
mutate(cig = as.double(cig), Birthweight = as.double(Birthweight)) %>%
mutate(smoke_status = case_when(cig >= 9 ~ "High", cig <9 ~ "Normal"),
Birth_status = case_when(Birthweight < 2500 ~ "Low", Birthweight >=2500~ "Normal")
) %>%
group_by(smoke_status, Birth_status) %>%
summarize(Count = n())
A: You could reverse the stack order via position = position_fill(reverse = TRUE):
library(ggplot2)
ggplot(newdf) +
aes(x = smoke_status, y = Count, fill = Birth_status) +
xlab("Smoking Activity") +
ylab("Proportion") +
labs(fill = "Birthweight") +
geom_bar(position = position_fill(reverse = TRUE), stat = "identity") +
scale_y_continuous(labels = scales::percent)
DATA
newdf <- structure(list(smoke_status = c("High", "High", "Normal", "Normal"), Birth_status = c("Low", "Normal", "Low", "Normal"), Count = c(
10L,
34L, 4L, 44L
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(smoke_status = c(
"High",
"Normal"
), .rows = structure(list(1:2, 3:4), ptype = integer(0), class = c(
"vctrs_list_of",
"vctrs_vctr", "list"
))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), .drop = TRUE))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71715132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCL: Blur image with Gaussian filter, Gaussian blur I have gaussian filter mask nxn computed for n = 5. That looks like this:
int gauss5[] = {
1, 4, 7, 4, 1,
4, 20, 33, 20, 4,
7, 33, 55, 33, 7,
4, 20, 33, 20, 4,
1, 4, 7, 4, 1
};
int gauss5_summ = 331;
After computation in opencl image become darker. What is the reason?
size_t global_wblur[2];
size_t local_wblur[2];
global_wblur[0] = h;
global_wblur[1] = w;
local_wblur[0] = local_wblur[1] = 32;
err = clEnqueueNDRangeKernel(queue, cl_img_gaussian_blur, 2, NULL, global_wblur, local_wblur, 0, NULL, NULL);
if (err != CL_SUCCESS) {
fprintf(stderr, "error: clEnqueueNDRangeKernel() blur %d %s\n", err, cl_strerror(err));
exit(EXIT_FAILURE);
}
kernel source:
__kernel void cl_img_gaussian_blur(__global const uchar *gray, __global uchar *out, __global const uchar *gbox, uint n, uint sum, uint w, uint h)
{
int i, j, offset;
uint x, y, summ;
y = get_global_id(0);
x = get_global_id(1);
offset = n/2;
/* ignore border pixels
*/
if (y - offset < 0 || y + offset > h || x - offset < 0 || x + offset > w) {
out[y*w + x] = gray[y*w + x];
return;
}
summ = 0;
for (j = -offset; j <= offset; j++) {
for (i = -offset; i <= offset; i++) {
summ += gray[(y + j)*w + x + i]*gbox[(j + offset)*n + i + offset];
}
}
out[y*w + x] = summ/sum;
}
Blured images:
dark(opencl) -- https://github.com/apetrunev/imgalg-opencl/blob/master/dark.png
normal -- https://github.com/apetrunev/imgalg-opencl/blob/master/test-blur/out.png
A: You said that the gbox data is initialized like:
clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5, gauss5, 0, NULL, NULL);
That is wrong, since you are copying 1/4th of the real amount of memory. The proper way is:
clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5*sizeof(cl_int), gauss5, 0, NULL, NULL);
Otherwise, the rest is 0s, leading to a low value in the output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31975170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i execute a python script using java? I'm trying to integrate a python script in java. I want my java program to be able to execute my python script
I tried to code a class named PythonCaller made to execute a test python script
package pythontest;
import java.io.*;
public class PythonCaller {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
// set up the command and parameter
String pythonScriptPath = "D:\\Programmes\\test.py";
String[] cmd = new String[2];
cmd[0] = "D:\\Programmes\\python.exe"; // check version of installed python: python -V
cmd[1] = pythonScriptPath;
// create runtime to execute external command
Process pr = Runtime.getRuntime().exec("python D:/Documents/Télécom/Programmation/workspace python/test.py");
System.out.println("adhi");
// retrieve output from python script
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
System.out.println(bfr.readLine());
String line = "";
try {
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
System.out.println("daiuh");
}
}
catch(IOException e) {
System.out.println("Exception in reading output" + e.toString());
}
}
}
When i execute it, it appears that bfr.readLine() returns null
Here is the script in test.py :
print("aiujadh")
print("f")
what i dont understand is that i did tests with the exact same code before, and it worked. I changed it because it failed to read the lines that were not "prints". Then i moved back to the working code, and it doesnt work anymore. I looked at similar topics on the internet, and i do not understand why my code doesn't work.
Can somebody try to explain me pls ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71589397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ reliance on argument to const reference not changing Please consider the following code:
void func1(const int &i);
void func2(int i);
void f()
{
int a=12;
func1(a);
func2(a);
}
Compiled with g++ 4.6 with -O3, I can see that the compiled re-reads the value of "a" between the function calls. Changing a's definition to "const int", the compiler doesn't do that, and instead simply loads immediate value "12" into edi. The same is true if a is not const, but I change func1's signature to accept by value.
While not a bug in the code generation, this is still weird behavior. Being as it is that func1 made a commitment not to change a, why should the compiler's code change based on whether a is const or not?
Edit: Some skeptics claim that I might be reading the code wrong. The above code produces the following with -S compilation:
_Z1fv:
.LFB0:
.cfi_startproc
subq $24, %rsp
.cfi_def_cfa_offset 32
leaq 12(%rsp), %rdi
movl $12, 12(%rsp)
call _Z5func1RKi
movl 12(%rsp), %edi <-- Rereading a
call _Z5func2i
addq $24, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
Changing a to const produces:
_Z1fv:
.LFB0:
.cfi_startproc
subq $24, %rsp
.cfi_def_cfa_offset 32
leaq 12(%rsp), %rdi
movl $12, 12(%rsp)
call _Z5func1RKi
movl $12, %edi <-- Use immediate value
call _Z5func2i
addq $24, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
A: In C++, const is really just logical constness and not physical constness. func1 can do a const_cast and modify i. const is like the safety of a gun - you can still shoot yourself in the foot, but not by accident.
As T.C. and juanchopanza have pointed out in the comments, casting away the constness of an object and modifying it is UB. Quoting from "Notes" here :
Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.
A: Summing up the answers, I think this explains it best:
It is legal to take a const reference to a non-const variable, and then cast away the constness. Therefore, the compiler in the first case cannot assume that func1 will not change a.
It is undefined what happens if you cast away the constness to a variable declared const. The compiler in the second case may assume that func1 will not cast away the constness. If func1 does cast away the constness, func2 will receive the "wrong" value, but that's just one consequence of undefined behaviour.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25029516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Sonar plugin postjob measure I have a sonar plugin that post a comment in gitlab when there is new sonar issues in a commit. I would like to add difference of code coverage and code duplication in the comment.
This is made by making a sonar plugin based on PostJob.
The issues are recovered by injection of ProjectIssues in the constructor.
Is there a way to recover the Measures in the post job? I saw that changed in sonar 5.2 but there is no real explanation on how to proceed to read measures.
Thank you for any help.
A: if the ProjectIssues or PostJobContext have no data you are looking for, you can use the web API rest:
WsRequest wsRequest = new GetRequest("api/...");
but beware the last measures will not be computed at the moment of @BatshSide, you have to wait for the Compute Engine to finish his work. So as you cannot wait in 'BatchSide', look for moving your plugin under @ComputeEngineSide
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39883832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: brain-teaser R problem - programming problem solving in R I am trying to write a function to solve a novel problem:
Given the following data:
S = c(19, 10, 12, 10, 24, 25, 22)
k = 4
I am trying to calculate a function. I want to print the maximal subset of S in which any sum of 2 numbers in S' is not evenly divisibly by k
So one answer might be S' = [10, 12, 25] and the other could be S' = [10, 22, 24].
Another example:
if S = {1, 7, 2, 4} and K = 3
Then
1 + 7 = 8
1 + 2 = 3
1 + 4 = 5
7 + 2 = 9
7 + 4 = 11
2 + 4 = 6
That is S' = {1, 7, 4} and will never sum to a multiple of k = 3
A: There is a linear time algorithm for this. This algorithm is well explained by orezvani in this post on Computer Science section of stackexchange.
I translated the orezvani pseudo code in R:
max_subset<-function(S,K){
R <- S %% K
Res <- c()
for(k in 1:(ceiling(K/2)-1)){
index_k = which(R==k)
index_K_k = which(R==(K-k))
if(length(index_k) >= length(index_K_k)){
Res <- c(Res, S[index_k])
}else{
Res <- c(Res, S[index_K_k])
}
}
print(R)
Res <- c(Res, S[which(R==0)][1])
if(K %% 2 == 0){
Res <- c(Res, S[which(R==(K/2))][1])
}
return(Res)
}
I tried with different example:
*
*with S <- c(1, 7, 2, 4) and K = 3 give 1 7 4;
*with S <- c(3, 17, 12, 9, 11, 15) and K = 5 give 11 17 12 15
*with S <- c(3, 7, 2, 9, 1) and K = 3 give 7 1 3
*with S <- c(19, 10, 12, 10, 24, 25, 22) and K = 4 give 25 12 10
In order to be more understandable I tried to be as similar as possible to the pseudocode, probably my solution could be optimized using R language specific features.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57878758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Pinescript issue between local and global scope if (barstate.islast)
myLine = line.new(x1=bar_index[SHI], y1=rsi[SHI],
x2=bar_index[FHI], y2=rsi[FHI], color=color.lime)
line.set_extend(id=myLine, extend=extend.right)
alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")
I'm drawing a line between certain points on RSI I named the line myLine and now I want to add an alert that fires when RSI passes thru that line.
The issue is I can't declare alertcondition inside if statement local scope and also I can't access myLine since it is in the local scope of the if statement, what shall I do in this case?
A: This will solve the myLine access problem.
However, it doesn't solve your crossover() problem, because that function expects 2 series as arguments.
You're providing a series (rsi) and a line object (myLine), which will result in an error.
I've commented out that line.
//@version=4
study("Test", shorttitle="TST")
var line myLine = line.new(na, na, na, na, color=color.lime, extend=extend.right)
var int SHI = 30
var int FHI = 20
rsi = rsi(close, 14)
if (barstate.islast)
line.set_xy1(myLine, bar_index[SHI], rsi[SHI])
line.set_xy2(myLine, bar_index[FHI], rsi[FHI])
plot(rsi)
// alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66295765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google chrome browser is misbehaving I don't know what's going wrong with my chrome browser. Everything was working fine but all of a sudden the width from my css styling for divs, input elements and all other widths are disorganised. I don't know if its the width that increased or the padding or margin but what I know is that everything is disorganised. But I checked firefox and other browsers everything is okay. I cleared my cache and cookie but no solution. Please does anyone knows how I can fix this?
A: I found the silly solution. The browser was zoomed to 120% unknown to me so I adjusted it back to 100%
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37356591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Azure Cloud Service stops saving to table storage when storage is accessed in visual studio server explorer I am working on an azure cloud service that has two different worker roles saving entities to an azure table storage. When I run the solution locally (both in debug and release mode) it works perfectly, however when I deploy the solution (either in debug or release) to the Azure Cloud Production Environment it writes the correct data and works well; but after I open the storage account in the server explorer in visual studio to review what was saved, then the cloud service worker roles stop saving new data to the tables.
Does accessing the azure storage account from the server explorer window in visual studio freeze the storage account when an azure cloud service is running against it?
A: No, that's not possible. Could you please provide more description about how the worker role "stop saving new data to table"? Did it encountered failures? If so, what's the detailed error message? Or did it make no progress while writing table entities?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32103854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reading XML File Through Dataframe I have XML file like below format.
<nt:vars>
<nt:var id="1.3.0" type="TimeStamp"> 89:19:00.01</nt:var>
<nt:var id="1.3.1" type="OBJECT ">1.9.5.67.2</nt:var>
<nt:var id="1.3.9" type="STRING">AB-CD-EF</nt:var>
</nt:vars>
I built a dataframe on it using below code. Though the code is displaying 3 rows and retrieving id and type fields it'snot displaying actual value which is 89:19:00.01, 1.9.5.67.2, AB-CD-EF
spark.read.format("xml").option("rootTag","nt:vars").option("rowTag","nt:var").load("/FileStore/tables/POC_DB.xml").show()
Could you please help me if I have to add any other options to above line to bring the values as well please.
A: You can instead specify rowTag as nt:vars:
df = spark.read.format("xml").option("rowTag","nt:vars").load("file.xml")
df.printSchema()
root
|-- nt:var: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- _VALUE: string (nullable = true)
| | |-- _id: string (nullable = true)
| | |-- _type: string (nullable = true)
df.show(truncate=False)
+-------------------------------------------------------------------------------------------+
|nt:var |
+-------------------------------------------------------------------------------------------+
|[[ 89:19:00.01, 1.3.0, TimeStamp], [1.9.5.67.2, 1.3.1, OBJECT ], [AB-CD-EF, 1.3.9, STRING]]|
+-------------------------------------------------------------------------------------------+
And to get the values as separate rows, you can explode the array of structs:
df.select(F.explode('nt:var')).show(truncate=False)
+--------------------------------+
|col |
+--------------------------------+
|[ 89:19:00.01, 1.3.0, TimeStamp]|
|[1.9.5.67.2, 1.3.1, OBJECT ] |
|[AB-CD-EF, 1.3.9, STRING] |
+--------------------------------+
Or if you just want the values:
df.select(F.explode('nt:var._VALUE')).show()
+------------+
| col|
+------------+
| 89:19:00.01|
| 1.9.5.67.2|
| AB-CD-EF|
+------------+
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66241748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When I do a delete:TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing table http://1.z9ls.com/t6/701/1555244797x1822611239.png
one table is article,the other is category:
article:article_id,article_title,article_category_id...and article_category_id
is the foreign key and references category_id of table category.
When I delete an article:object references an unsaved transient instance - save the transient instance before flushing: com.wjh.blog.domain.Category
Attention:when I DELETE a article,but not insert or update.
//I have already use the @Transactional
//this is the code of ArticleDaoImpl.java
@Override
public void delete(Long article_id) {
Article article = new Article();
article.setArticle_id(article_id);
this.getHibernateTemplate().delete(article);
}
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wjh.blog.domain.Category" table="category">
<id name="category_id" column="category_id">
<generator class="native"/>
</id>
<property name="category_name" column="category_name"/>
<property name="category_parent_id" column="category_parent_id"/>
<set name="category_articles" inverse="true">
<key column="article_category_id"></key>
<one-to-many class="com.wjh.blog.domain.Article"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wjh.blog.domain.Article" table="article" >
<id name="article_id" column="article_id">
<generator class="native"/>
</id>
<property name="article_title" column="article_title"/>
<property name="article_content" column="article_content"/>
<property name="article_time" column="article_time"/>
<property name="article_pic" column="article_pic"/>
<property name="article_desc" column="article_desc"/>
<!--category-->
<many-to-one name="article_category" class="com.wjh.blog.domain.Category"
column="article_category_id" cascade="save-update,persist" ></many-to-one>
</class>
</hibernate-mapping>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55675372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python - cannot set wallpaper with tempfile Code:
import urllib.request
import tempfile
import shutil
import ctypes
SPI_SETDESKWALLPAPER = 20
with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f:
shutil.copyfileobj(response, f)
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, 0)
However, if you use tempfile.NamedTemporaryFile(delete=False) it works.
The docs state:
If delete is true (the default), the file is deleted as soon as it is
closed.
In my original code the file isn't deleted until after having exited the body of the with statement when it is automatically closed. So why isn't SPI_SETDESKWALLPAPER working?
A: You need to read the next couple sentences in the documentation, which read something like this:
Under Unix, the directory entry for the file is either not created at all or
is removed immediately after the file is created. Other platforms do not
support this; your code should not rely on a temporary file created using
this function having or not having a visible name in the file system.
A: I figured out the problem:
To begin with, the value of the fWinIni parameter needs to be changed:
SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
This preserves the wallpaper after logging off.
Second, the temp file needs to be closed in order for SystemParametersInfoW to work. Therefore, delete=False is necessary.
Finally, delete the temp file manually using os.remove(f.name).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38532270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to tell nuget to add package resource files as links, and not copy them into project directory Intro (how to pack resources into a nuget package)
To pack some resource files into a nuget package, what one would normally do, is the following.
Put all the resource files into the content\ directory of a nuget package. This would be specified by the following line in a .nuspec file:
<files>
<file src="Project\bin\Release\script.js" target="content\js\script.js" />
<files>
Now, when this nuget package gets installed into AnotherProject, the following file structure emerges:
Solution.sln
packages\Project.1.0.0\content\js\script.js // the original resource file
AnotherProject\js\script.js // a physical copy
AnotherProject\AnotherProject.csproj // <Content /> tag (see below)
During package installation, AnotherProject.csproj was injected with tag:
<Content Include="js\script.js" />
and this is for the physical copy of the original resource (which is under packages\ directory).
The actual problem (how to pack resources into a nuget package as link)
My aim is not to have the physical copy of a resource file in the AnotherProject directory but rather a "link" to the original resource under packages\ directory. In the csproj, this should look like this:
<Content Include="packages\Project.1.0.0\content\js\script.js">
<Link>js\script.js</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
Brute force solution that I would rather avoid
Now, one "do it the hard way" workaround I can think of is:
*
*not putting resource files under content\ so they do not get added automatically,
*writing Install.ps1 script that would hack the csproj file structure and add the necessary XML piece manually,
This, however, has the following drawbacks:
*
*all my nuget packages need the same script piece in their Install.ps1,
*when installing my packages, there would be a nasty "project reload prompt" in Visual Studio.
A: Since NuGet currently does not support this out of the box your options are either to use PowerShell or to use a custom MSBuild target.
PowerShell
*
*Leave your resources outside of the Content directory in your NuGet package (as you already suggested).
*Add the file link using PowerShell in the install.ps1.
You should be able to avoid the project reload prompt if you use the Visual Studio object model (EnvDTE). I would take a look at Project.ProjectItems.AddFromFile(...) to see if that works for you.
MSBuild target
*
*NuGet supports adding an import statement into a project that points to an MSBuild .props and/or .targets file. So you could put your resources into the tools directory of your NuGet package and reference them from a custom MSBuild .props/.targets file.
Typically the custom .props and .targets are used to customise the build process. However they are just MSBuild project files so you could add items for your resources into these project files.
Note that .props are imported at the start of the project file when a NuGet package is installed, whilst .targets are imported at the end of the project.
Customising NuGet
Another option, which would take more work, would be to modify NuGet to support what you want to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25367541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to write unit test case IHttpClientFactory I have a method in service layer to connect to a service and i am using IHttpClientFactory. My method is working fine. Now i am trying to write unit test cases for the same.
public async Task<MyObject> MyMethodAsync(string arg1, string arg2)
{
var client = _httpClientFactory.CreateClient("XYZ");
var Authkey = "abc";
var AuthToken = "def";
var headers = new Dictionary<string, string>
{
{ Authkey,AuthToken }
};
client.AddTokenToHeader(headers); //This method set the DefaultRequestheader from the dictionary object
var reqData = new
{
prop1 = "X",
prop2 = "Y"
};//req object
var content = new StringContent(JsonConvert.SerializeObject(reqData), Encoding.UTF8, "application/json");
//This is httpClient Post call for posting data
HttpResponseMessage response = await client.PostAsync("postData", content);
if (!response.IsSuccessStatusCode || response.Content == null)
{
return null;
}
MyObject myObject = JsonConvert.DeserializeObject<MyObject>(response.Content.ReadAsStringAsync().Result);//read the result to an object
return myObject;
}
For the above method i am writing test cases. Here i am trying to set the Post methods out put a status code OK and expecting the
MyMethodAsync method to be true as the PostAsync is true. Here i am getting an exception
System.InvalidOperationException : An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.
[Test]
public async Task MyMethodAsync_Gets_True()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("It worked!")
};
//Mock the httpclientfactory
var _httpMessageHandler = new Mock<HttpMessageHandler>();
var mockFactory = new Mock<IHttpClientFactory>();
//Specify here the http method as post
_httpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync",
ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK
});
var httpClient = new HttpClient(_httpMessageHandler.Object);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);
var arg1 = "X";
var arg2 = "D101";
var service = new MyService(_mockAppSettings.Object, mockFactory.Object);
var result = await service.MyMethodAsync(arg1, arg2);
// Assert
Assert.IsNotNull(result);
}
Can someone show what mistake i am doing here?
A: As the exception says you have to
*
*either call the PostAsync with an absolute url
*or set the BaseAddress of the HttpClient
If you choose the second one all you need to do is this:
var httpClient = new HttpClient(_httpMessageHandler.Object);
httpClient.BaseAddress = new Uri("http://nonexisting.domain"); //New code
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);
With this modification the exception will be gone.
But your test will fail because the response.Content will be null and that's why MyMethodAsync will return with null.
To fix this let's change the Setup to this:
public static async Task MyMethodAsync_Gets_True()
{
//Arrange
MyObject resultObject = new MyObject();
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(resultObject))
};
var _httpMessageHandler = new Mock<HttpMessageHandler>();
_httpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync",
ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(response);
...
//Act
var result = await service.MyMethodAsync(arg1, arg2);
//Assert
Assert.NotNull(result);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67421717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a way to create a .net project in eclipse using no template I have eclipse 2021 installed on my laptop which is running Ubuntu 20.04 and I have .net 6 installed with snap when I go to create a .net project it says no template selected it in preferences the .net folder is in the snap folder. I just want to create a blank project , how can I do this. photo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71501269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: bsmultiselect Select one option at a time on div I was trying to use "setSelected" option on my multiselect, but I nnoticed that this does not work with divs (at least I couldn't reach it myself). I am trying to make two synced multiselects, using this example: https://dashboardcode.github.io/BsMultiSelect/snippetJs.html but with the last two inputs only.
var options = [
{ text: 'item1', value: 'item1'},
{ text: 'item2', value: 'item2'},
];
var teste1 = null;
var teste2 = null;
let isTeste2 = true;
var $testes = $('#teste1-id')
if (isTeste2)
$testes = $testes.add('#teste2-id')
var install = function () {
$testes.bsMultiSelect({
options: options
});
if (isTeste2) {
$('#teste1-id').on('dashboardcode.multiselect:change', function () {
$('#teste2-id').bsMultiSelect("UpdateOptionsSelected");
})
}
}
install();
$("#btn").click(
function(){
options[0].selected = true;
var api1 = $testes.BsMultiSelect();
api1.updateOptionSelected(0);
}
)
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@dashboardcode/bsmultiselect@0.6.28/dist/js/BsMultiSelect.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<label class="control-label" for="teste1-id">Teste1</label>
<div id="teste1-id"></div>
<label class="control-label" for="teste2-id">Teste2:</label>
<div id="teste2-id"></div>
<br/>
<button id="btn">Click Me</button>
Could you help me find a solution, please?
A: For only "one select":
var options = [
{ text: 'item1', value: 'item1', selected: true},
{ text: 'item2', value: 'item2', selected: false},
];
function isValidSelection(v){
var l = options.filter(function(item){
return item.selected==true;
}).length;
var r = ( !v ) || (v && l==0);
return r;
}
var teste1 = null;
var $teste1 = $('#teste1-id')
var install = function () {
$teste1.bsMultiSelect({
options: options,
setSelected: function(o,v){
if (isValidSelection(v)){
o.selected = v;
return true;
}
else{
return false;
}
}
});
}
install();
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@dashboardcode/bsmultiselect@0.6.28/dist/js/BsMultiSelect.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<label class="control-label" for="teste1-id">Test it (only one select allowed)</label>
<div id="teste1-id"></div>
<br/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65816625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to set headers in SQLPLUS? I have set following SQLPLUS commands:
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING ON
SET LINESIZE 100
SET PAGESIZE 1000
SET SPACE 0
SET TERMOUT OFF
SET TRIMOUT OFF
SET TRIMSPOOL ON
SET VERIFY OFF
But i am getting the result as:
ERROR_CODE
----------
ERROR_DESC
----------------------------------------------------------------------------------------------------
ERROR_COUNT
-----------
EXCP098
EXCEPTION: Processing not allowed
2
EXCP014
EXCEPTION: UNKNOWN STATUS
11
i.e. all the column headings and column values are in a new line instead of all column header should be in the same row and then record 1 should be in the first row and then record 2 should be in the second row.
I want it should be displayed as:
ERROR_CODE ERROR_DESC ERROR_COUNT
-----------------------------------------------------------------------
EXCP098 EXCEPTION: Processing not allowed 2
EXCP014 EXCEPTION: UNKNOWN STATUS 11
A: If "ERROR_DESC" is too long to fit on a line (together with "ERROR_CODE" and "ERROR_COUNT"), you have a few options to try:
*
*return just a substring,
*TRIM the value, or
*change the data type for "ERROR_DESC".
What's working and appropriate, depends on your overall context. After all, the display in SQLPlus is usually not the most important aspect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27639716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Parallel Solution search I have written some code in python using multiprocessing package. It sort of searches for a solution for an equation in 6 different ways.So I have 6 different processes running the same function with different parameters. I would like to stop all the sub-processes once the solution has been found by one of the sub-process.Right now after using the join function, the result is that even if the solution is found , the other processes continue , till they find one . I'm using join() .
for i in range(N):
p=multiprocessing.Process(target=mysolver,args=(g,h,q,B[i],i,dic,))
jobs.append(p)
p.start()
for p in jobs:
p.join()
This how I call the function for solving. Usually N is 6 -10 .
A: You need to have a list containing a reference to all threads and accessible by all threads. This list of threads should be ready before you start the threads. The thread that finds a solution first can kill the others using the list, taking care of not commiting suicide.
You might face a racing condition in case one of the threads dies before you call join. As such you might be calling join on a already dead thread. A quick and dirty workaround is to let each thread wait few milliseconds fot the main thread to call join for all threads.
An other cleaner solution is to use a flag that is checked by all threads while they look for a solution. If they find it to be true, they should immediately terminate by returning. The thread that finds a solution can set the flag to true and return. Now all threads will nicely join the main thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29640011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Diffing between two entire directories/projects in hg or git? I inherited a project originally stored in CVS with all the revisions. I made quite a few edits, and I'm trying to compare all the changes I made in the original directory, in regards to new files added versus the old ones.
Is there some sort of utility for hg/git where I can do a tree diff, or something of that nature? So that say, there's a mark between newly added files, deleted files, am I asking for too much?
A: I don't really understand what you want, but isn't diff -ur enough for you? It will work even on directories without any kind of version control.
A: git diff does exactly that. but it only works for git projects.
hg diff, svn diff pretty every version control system can diff directory trees
A: From git diff manpage:
git diff [--options] [--] [<path>...]
[...]
If exactly two paths are given, and at least one is untracked, compare the two files / directories. This behavior can be forced by --no-index.
If you want to compare two versions (e.g. two tagged releases, or two branches) in two different repositories, you can use trick described in GitTips page on Git Wiki, under "How to compare two local repositories".
Assuming that you are inside one repository, and second repository is in /path/to/repo, so its GIT_DIR is /path/to/repo/.git if it is non-bare repository, you can something like the following:
$ GIT_ALTERNATE_OBJECT_DIRECTORIES=/path/to/repo/.git/objects \
git diff $(git --git-dir=/path/to/repo/.git rev-parse --verify A) B
where A and B are revisions you want to compare. Of course you can also specify path limiter in above expression.
Explanation: GIT_ALTERNATE_OBJECT_REPOSITORIES variable can be used to make git commands concatenate object database of the two repositories. git --git-dir=... rev-parse ... is used to turn name (extended SHA-1 expression) in repository given as parameter to git-dir option into unique SHA-1 identifier. The $( ... ) construct puts result of calling given command in command line. git diff is used to compare two revisions (where one is from alternate object repository).
Alternate solution would be to simply import other repository into given repository, using git remote add (and git fetch). Then you would have everything locally, and would be able to do comparision inside single repository.
A:
Is there some sort of utility for hg/git where I can do a tree diff... [s]o that say, there's a mark between newly added files, deleted files... [emphasis added]
Yes. We can git diff the current directory against another directory and...
...mark the added, deleted, and modified files:
git diff --name-status --no-index ./ path/to/other/dir
...show only added files:
git diff --diff-filter=A --name-status --no-index ./ path/to/other/dir
... show only deleted files:
git diff --diff-filter=D --name-status --no-index ./ path/to/other/dir
...show only modified files:
git diff --diff-filter=M --name-status --no-index ./ path/to/other/dir
See also: https://git-scm.com/docs/git-diff
A: To simply create a diff patch in git's diff format from two arbitrary files or directories, without any fancy repository stuff or version control:
git diff --no-index some/path other/path > some_filename
Jakub Narębski's comment on knittl's answer hinted at the answer... For simplicity's sake, that's the full command.
The > part creates a file and redirects the output to it. If you don't want a file and just want the output printed in your console so you can copy it, just remove the > some_filename part.
For convenient copying and pasting, if you've already cded to a directory containing the original directory/file named a and the modified directory b, it'll be:
git diff --no-index a b > patch
A: It's not git-specific, but as a general diff utility for Windows, I really like WinMerge.
A: There Are Following Another Ways For Diffing between two entire directories/projects.
*
*In Git There is Syntax:
Syntax: git-diff [] [--] […]
This form is to view the changes you made relative to the index (staging area for the next commit). In other words, the differences are what you could tell Git to further add to the index but you still haven’t.
Here is the.
URL: https://git-scm.com/docs/git-diff
git diff --no-index directory 1 project /path directory 2 project/path >> File name
*Using Linux Command diff --brief --recursive dir1path/ dir2Path/
*If you are using windows there is an application WinMerge.
A: Creating the patch from dir1 to dir2 (--binary only needed for binaries):
git diff --no-prefix --no-index --binary dir1 dir2 > dir.diff
Applying the patch to contents of working directory, which has the same contents as dir1:
cd dir1_copy
git apply ../dir.diff
git apply has default -p1 which strips the leading directories in diff commands.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1791854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: MetPy Wet Bulb Temperature function returns error when output of Most Unstable Parcel function is used as input When attempting to use the find the wet-bulb temperature for a parcel returned by MetPy's most_unstable_parcel function, I am getting an error that seems to be related to the Pint attributes of the most unstable parcel pressure. It is necessary to strip away those attributes by coercing the pressure to be of type int or float.
See discussion, below.
I would greatly appreciate some help in understanding how to use the most unstable parcel pressure without resorting to the artifice of coercing it to a type that requires re-assigning units. Thank you!
Example Calculation (data from OUN 20220328 00Z sounding):
from metpy.units import units
import metpy.calc as mpcalc
# Construct a sample sounding:
p = [972.0, 942.8, 925.0, 910.1, 878.2, 850.0, 847.3, 826.0, 817.0, 787.5]*units('hPa')
T = [25.4, 22.4, 20.6, 19.3, 16.4, 13.8, 13.6, 11.6, 11.1, 9.4]*units('degC')
Td = [6.4, 5.3, 4.6, 4.1, 2.9, 1.8, 1.7, 0.6, -0.2, -2.9]*units('degC')
h = [345, 610, 776, 914, 1219, 1497, 1524, 1737, 1829, 2134]*units('m')
# Find the Most Unstable Parcel
MUp = mpcalc.most_unstable_parcel(p,T,Td,h)
# MUp
# (972.0 <Unit('hectopascal')>,
# 25.4 <Unit('degree_Celsius')>,
# 6.4 <Unit('degree_Celsius')>,
# 0)
# Next compute the wet-bulb-temperature for this parcel:
Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])
When this is executed, we get the following error traceback:
IndexError Traceback (most recent call last)
Input In [4], in <module>
----> 1 Twb = mpcalc.wet_bulb_temperature(MUp[0],MUp[1],MUp[2])
File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/xarray.py:1230, in preprocess_and_wrap.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
1227 _mutate_arguments(bound_args, units.Quantity, lambda arg, _: arg.m)
1229 # Evaluate inner calculation
-> 1230 result = func(*bound_args.args, **bound_args.kwargs)
1232 # Wrap output based on match and match_unit
1233 if match is None:
File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/units.py:288, in check_units.<locals>.dec.<locals>.wrapper(*args, **kwargs)
285 @functools.wraps(func)
286 def wrapper(*args, **kwargs):
287 _check_units_inner_helper(func, sig, defaults, dims, *args, **kwargs)
--> 288 return func(*args, **kwargs)
File ~/miniconda3/envs/MetPy/lib/python3.8/site-packages/metpy/calc/thermo.py:3073, in wet_bulb_temperature(pressure, temperature, dewpoint)
3071 ret = it.operands[3]
3072 if ret.size == 1:
-> 3073 ret = ret[0]
3074 return units.Quantity(ret, temperature.units)
IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed
After running a few permutations of inputs, I discovered that it is possible to use the output pressure value if one first coerces it to, say, type float or int.
# Reformat the pressure value as input to
# wet_bulb_temperature()
d = float(MUp[0].magnitude)*units('hPa')
Twb1 = mpcalc.wet_bulb_temperature(d,MUp[1],MUp[2])
print(Twb1)
# output is 14.209821596989343 degree_Celsius
# As far as Python is concerned, the two instances of pressure are
# identical:
print(MUp[0]==d)
# Output: True
It's just not clear to me why the pressure output from most_unstable_parcel (e.g. MUp[0]) cannot be used directly as an input to the wet-bulb temperature calculation.
A: This is a bug with MetPy's wet_bulb_temperature function in handling NumPy scalars, so thank you for identifying the issue! A pull request fixing this has been submitted, which should make it into the upcoming MetPy v1.3.0 release.
For now, you will need to somehow override the array shape recognition that exists in wet_bulb_temperature. Converting from a NumPy scalar to a Python scalar as you discovered is one such way to do so. Another is converting to 1D NumPy arrays, like the following:
Twb = mpcalc.wet_bulb_temperature(
*(np.atleast_1d(arg) for arg in (MUp[0], MUp[1], MUp[2]))
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71655087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boost.flyweight and Boost.MPL I have a question regarding flyweight options, given the definition below, based on http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp
typedef boost::flyweights::flyweight<
std::string,
boost::flyweights::tag<int>,
boost::flyweights::static_holder_class<boost::mpl::_1>,
boost::flyweights::hashed_factory_class<
boost::mpl::_1,
boost::mpl::_2,
boost::hash<boost::mpl::_2>,
std::equal_to<boost::mpl::_2>,
std::allocator<boost::mpl::_1>
>,
boost::flyweights::simple_locking,
boost::flyweights::refcounted
> StringFlyweight;
StringFlyweight test1("Hello World");
what value has boost::mpl::_1 and boost::mpl::_2 ? When are asigned ?
boost::mpl::_1 is most probably std::string. boost::mpl::_2 should be size_t ? If true, how is deducted ?
I don't understand how is key_type chosen.
I have read http://www.boost.org/doc/libs/1_41_0/libs/flyweight/doc/tutorial/lambda_expressions.html but I it is my first contact with Boost.MPL and is not enough :)
A: boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafunction on-the-fly where it is needed), etc.
An expression containing at least a placeholder is a placeholder expression, which can be invoked like any other metafunction, with some arguments that will replace the placeholders.
In your example, assuming the following typedef
typedef boost::flyweights::hashed_factory_class<
boost::mpl::_1,
boost::mpl::_2,
boost::hash<boost::mpl::_2>,
std::equal_to<boost::mpl::_2>,
std::allocator<boost::mpl::_1>
> hashed_factory;
we can assume that at some other point in the code, the hashed_factory will be invoked with some parameter:
typedef typename
boost::mpl::apply<
hashed_factory,
X,
Y
>::type result; // invoke hashed_factory with X and Y
// _1 is "replaced" by X, _2 by Y
I did not look in Flyweight code, but we can suppose that _1 will be bound to the value type of the flyweight, and _2 to the key type (since it is used for hashing and testing equality). In this case, I think both will be std::string since no key type is specified.
I'm not sure my explanation about MPL's placeholders is quite clear, feel free to read the excellent MPL tutorial that explains very well metafunctions, lambda expressions and other template metaprogramming features.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7832412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I create an array of ascending and then descending numbers? For example:
I have min and max values and a number of increments which may be odd or even;
if I have min = 3 and max = 10 and increments = 15 then I want:
3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3
However, if increments = 16 I want (notice the two 10's in the middle):
3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3
I have to create these arrays add-hoc using just min, max, and number of increments.
UPDATE:
To make this clearer the number of increments is equal to the number of items that must be in the array and the items are decimals.
so if min = 5.0 and max = 15.0 and increments = 6 then the array would contain:
5.0, 10.0, 15.0, 15.0, 10.0, 5.0
A: Linq way:
int min = 3;
int max = 10;
int increments = 15;
Enumerable
.Range(min, max - min + 1)
.Concat(Enumerable
.Range(min, max - min + 1)
.Reverse()
.Skip(increments % 2))
.ToArray();
A: This should work:
public static IEnumerable<decimal> NewMethod(decimal min, decimal max, int count)
{
var increment = (max - min) / (int)((count - 1) / 2);
for (var i = min; i < max; i += increment)
yield return i;
if (count % 2 == 0)
yield return max;
for (var i = max; i >= min ; i -= increment)
yield return i;
}
Sample test:
var min = 3.0m;
var max = 10.0m;
var count = 16;
MessageBox.Show(string.Join(", ", NewMethod(min, max, count)));
Edit: You have to cope with floating point types losing precision, otherwise you will be missing an element in the final result set. Tinker a bit with Math.Round over the i += and i -= part, that's up to you. I have updated code to replace double with more reliable decimal type. But there is no guarantee this should not fail every time. Easier is to avoid cases where you will need decimal types in the result like { 1, 2.2, 3.4 } etc.
A: Here's a one-way ramp that handles floating point values correctly. You should be able to modify it to make a triangle waveform. When implementing a ramp, care must be taken to make sure not to accumulate either round-off errors, or off-by-one errors for various inputs.
void Packet::SetRamp( const SampleType start /*= Signal::One*/,
const SampleType finish /*= -Signal::One */ )
{
SampleType slope, current;
SampleOffsetType len;
len = GetLength();
if ( len < 2 )
throw std::range_error( "packet is not large enough to set ramp into" );
slope = ( finish - start ) / ( len - 1 );
for ( SampleOffsetType row = 0; row < len; row++ )
{
current = slope * row + start;
SetSample( row, current );
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16570347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Do we have a way to include full source into APK? I'm developing samples for different Android technologies and want to include the full source code (Eclipse project) archived into the APK. That should allow anyone with Google Market access to easily reuse the code.
Is there a proper way to automatically pack the code/resources and put it into assets?
I'm using Eclipse under Win//Linux.
Currently I have to manually 7z-compress the src&res and put it into assets before signing.
A: Sure, just compress it and include it in a directory under your APK (e.g. raw). But be aware that your APK will at least x2 its size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14254373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display calendar to pick a date in java In other languages like VB, C#, in occasions where you want the user to enter a date, say in a text box,we can make a calendar to appear once you click on it. So the user can click on the corresponding date and that date will be put to the text box.
By that way we can get rid of problems that can be caused due to dates in an incorrect format. I need to know how we can achieve this in java?
Actually, I need to combine this with a JTable. there is a column where the date need to be entered. But users may enter dates in various formats. So I thought of going to something like this. Hope there is a way to do this, easily.
Will anyone please show me how to do this. Any help is greatly appreciated..
Thank you.
A: Another easy method in Netbeans is also avaiable here,
There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette. Lots of goodies here! Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)
A: I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;
public class DatePickerExample extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("JXPicker Example");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400, 400, 250, 100);
JXDatePicker picker = new JXDatePicker();
picker.setDate(Calendar.getInstance().getTime());
picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));
panel.add(picker);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
A: I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
String s = "";
if (dayNo >= 1 && dayNo <= maxDayNo) {
s = String.valueOf(dayNo);
}
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
A: The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components.
I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .
A: *
*Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
*Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
*Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
*Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11736878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: C# UI automated testing - Does anyone succeeded to capture the command prompt window object? I have an UI automated test developed with White. One of the cases needs to open cmd and write some commands. The problem is when I input the first command. I tried something like:
Process.Start("CMD.EXE");
///Thread.Sleep(2000);
SendKeys.SendWait(command);
The problem is that sendkeys starts to input before the windows is opened, and trims the command, skipping first characters (depending on window appearance moment). It works with a sleep, but I'm trying to avoid such practices.
In order to avoid this I would insert a timer to wait for the window to be visible. So my questions:
*
*Can this window be captured, so I can wait for it?
OR
*
*Any other way to send the command?
A: for this special case ,you could execute the cmd to run your commands as args, i mean, avoid sendKeys and execute the cmd like this : Process.Start("CMD.EXE", "/c echo hello world");
note that /c will execute the cmd and exit while /k execute the cmd and return to the CMD prompt.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41759029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Data.Aeson encoding optional keys I have the following problem, I have a JSON format with optional keys that I need to generate from my haskell code.
Lets make an example
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
import Data.Aeson
data Person = {
name :: String,
shoeSize :: Maybe Int,
favoriteColor :: Maybe String,
favoriteFood :: Maybe StringC
} deriving (show, eq, generic)
instance ToJSON Person -- Generic instance
now, if I try encoding a Person without a shoesize I still get a key "shoeSize" set to null, what is the Aeson way of making keys optional in encoding
edit, example of an encode
encode $ Person "windwarrior" Nothing "green" Nothing
should result in
{"name":"windwarrior", "favoriteColor":"green"}
A: Use TemplateHaskell to derive the ToJSON instance instead of Generic. The TH functions optionally take an Options which has the omitNothingFields option.
A: There is the Options datatype with an omitNothingFields field for Generics as well so you don't have to use TemplateHaskell, however there's currently (v0.11.2.0) a bug that makes it generate invalid JSON under certain circumstances, e.g. several record fields. It has been fixed but is in master.
You can also handwrite instances if you prefer, for your example:
instance ToJSON Person where
toJSON (Person name shoeSize favoriteColor favoriteFood) = object fields
where
consMay attr = maybe id ((:) . (attr .=))
conss = consMay "shoeSize" shoeSize
. consMay "favoriteColor" favoriteColor
. consMay "favoriteFood" favoriteFood
fields = conss ["name" .= name]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19665099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why is the order of haystack and needle inconsistent in PHP functions in_array and strpos? The order of parameters haystack and needle in these 2 very core PHP functions is not consistent:
*
*http://php.net/manual/en/function.in-array.php (needle, haystack)
*http://php.net/manual/en/function.strpos.php (haystack, needle)
Why is this the case?
A: Needle/Haystack in PHP
They are actually not inconsistent like many think. You have partly discovered the consistency:
*
*All string functions are (haystack, needle)
*All array functions are (needle, haystack)
Rasmus Lerdorf (the creator of PHP) states this in a talk in 2019 around 25 minutes in:
25 Years of PHP - phpday 2019
https://youtu.be/iGOAQli7tGc?t=1485
Inconsistencies in PHP
At 16:45, he has a slide titled "What was he thinking?" and he addresses "naming inconsistencies". (needle/haystack issue is just one of them)
https://youtu.be/iGOAQli7tGc?t=1005
In this talk he also explains that his design decisions for PHP are almost all based on the idea that PHP is a "wrapper for underlying C libraries", and has kept the parameters in the same order as the underlying code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52985459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cut off string at not allowed tags in regex I got this fine working regex to use with php's preg_match_all to match a string containing 0 to x lines before and 0 to y lines after a specific word in a sentence/string:
'(?:[^\.?!<]*[\.?!]+){0,x}(?:[^\.?!]*)'.$word.'(?:[^\.?!]*)(?:[\.?!]+[^\.?!]*){0,y}'.'(?:[\.?!]+)'
Now, I want the string to be cut off when specific tags occur. So I was thinking about implementing this part in this string above:
(?:(<\/?(?!'.$allowed_tags.')))
in which $allowed_tags is a php variable that could look like this for example: '(frame|head|span|script)'
Despite trying to get this to work with lookahead, lookbehind and other conditions I can't get it working properly and I unfortunately have to admit this is way beyond my programming skills.
Hopefully someone can help me with this? I am sure someone among you geniuses can :)
Thanks a lot in advance!
Example input-output:
For example I would like to grab this part:
<p>Tradition, Expansion, Exile.<br/>Individual paths in Chinese contemporary art </p><p>The contemporary <i>art world</i> craves for novelty: the best reason for Chinese art to be so trendy is also the <strong>worst one</strong>.</p>
from this complete string:
<div readability="120"><p>Tradition, Expansion, Exile.<br/>Individual paths in Chinese contemporary art </p><p>The contemporary <i>art world</i> craves for novelty: the best reason for Chinese art to be so trendy is also the <strong>worst one</strong>.</p><div>
That means in this example <p></p><i></i><strong></strong> <br/> are allowed tags and <div > and </div> aren't.
A: Assuming you define div and span tags as “illegal” as per your comment, the following regex will match x sentences before and y sentences after the sentence conatining $word, as long as those sentences do not contain the “illegal” tags:
'(?:(?<=[.!?]|^)(?:(?<!<div|<\/div|<span|<\/span)>|[^>.!?])+[.!?]+){0,x}[^.!?]*'.$word.'[^.!?]*[.!?]+(?:(?:<(?!\/?div|\/?span)|[^<.!?])*[.!?]+){0,y}'
Split up and explained (quotes and string concatenation operator removed, comments and line breaks added for better reading):
// 0 TO X LEADING SENTENCES
(?: ---------------------------------// do not create a capture group
(?<=[.!?]|^) ----------------------// match only after sentence end or start of string
(?: -------------------------------// do not create a capture group
(?<!<div|<\/div|<span|<\/span)> -// match “>” only if not preceded by span or div tags
|[^>.!?] ------------------------// or any any other, non punctuation character
)+ --------------------------------// one or more times
[.!?]+ ----------------------------// followed by one or more punctuation characters
){0,x} ------------------------------// the whole sentence repeated 0 to x times
// MIDDLE SENTENCE WITH KEYWORD
[^.!?]* -----------------------------// match 0 or more non-punctuation characters
$word -------------------------------// match string value of $word
[^.!?]* -----------------------------// match 0 or more non-punctuation characters
[.!?]+ ------------------------------// followed by one or more punctuation characters
// 0 TO Y TRAILING SENTENCES
(?: ---------------------------------// do not create a capture group
<(?!<\/?div|\/?span) --------------// match “<” not followed by a “div” or “span” tag
|[^<.!?] --------------------------// or any non-punctuation character that is not “<”
)* --------------------------------// zero or more times
[.!?]+ ----------------------------// followed by one or more punctuation characters
){0,y} ------------------------------// the whole sentence repeated 0 to y times
Note the lookbehind assertion used for matching sentences before $word will only match opening and closing tags without attributes, and has to match both the opening and closing tag variants literally, as lookbehind assertions cannot be of variable length. There are other limitations and gotchas:
*
*notably that the regex will return an “illegal” tag if it is located inside the sentence containing $word
*and that “inside” a sentence literally means “following the closing punctuation of the preceding sentence”, which, although formally correct, might not be what is expected.
All of this goes to highlight the limitations of a regex based approach to the problem. In this light, you might think that switching to a more programatic approach (like parsing all sentences into an array irrespective of tags, then scanning for “illegal” tags and trimming or rejecting the array accordingly, which would allow for a more flexible tag matching regex) would work better, and you would be right, were it not for the underlying difficulty of matching a natural language construct like a sentence with a regex with any degree of accuracy. I’ll leave you to ponder what the “sentence splitting” regex used in this question and answer would do to the following:
“T.J. Hooker was plaid (sic.) by W. Shatner of Starship Enterprise (!) fame”
It’s not pretty. And neither is the result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11064322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Read a column file in julia I would not like to pickaxe a lot in the language just to read a file with numerical data arranged by columns. Is there an easy way to do this now in julia 1.1? Surprisingly this simple task is not on the manual. In python one would do something like this:
def read2col(filename, length):
data = []
for line in open(filename,'r'):
for word in line.split():
data.append(word)
data = np.reshape(data,(length,2))
data = np.asarray(data, dtype=np.float64)
return data
A: There is already an inbuilt function in Julia that does exactly that:
using DelimitedFiles
reshape(readdlm("myfilename.txt"),:,2)
Let's give it a spin:
shell> more file.txt
1 2 3
4 5 6
7 8 9
10 11 12
julia> reshape(readdlm("file.txt"),:,2)
6×2 Array{Float64,2}:
1.0 8.0
4.0 11.0
7.0 3.0
10.0 6.0
2.0 9.0
5.0 12.0
or if you want a different ordering just transpose with '
julia> reshape(readdlm("file.txt")',:,2)
6×2 reshape(::LinearAlgebra.Adjoint{Float64,Array{Float64,2}}, 6, 2) with eltype Float64:
1.0 7.0
2.0 8.0
3.0 9.0
4.0 10.0
5.0 11.0
6.0 12.0
A: (untested)
function read2col(filename, len)
asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
data = []
for word in split(read(filename, String), r"\s+")
push!(data, word)
end
data = reshape(data,(len, 2))
data = asfloat64.(data)
return data
end
or even
asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
read2col(fname, len) = asfloat64.(reshape(split(read(fname, String), r"\s+"), (len, 2)))
A: The laziest way to do it is to use CSV.jl
using CSV
for row in CSV.File("file.txt",delim=' ',ignorerepeated=true)
println("a=$(row.a), b=$(row.b), c=$(row.c)")
end
delim=',': a Char or String that indicates how columns are delimited in a file; if no argument is provided, parsing will try to detect the most consistent delimiter on the first 10 rows of the file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59399168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I make a modulino in Perl6? I want to make a modulino (a file that can run as either a module or a script) in Perl6.
The following code "processes" file names from the command line:
sub MAIN ( *@filenames )
{
for @filenames -> $filename
{
say "Processing $filename";
}
}
Saving this as main.pm6 I can run it and it works:
perl6 main.pm6 hello.txt world.txt
Processing 'hello.txt'
Processing 'world.txt'
So, I want this to be a module so that I can add functions and make testing it easier. However, when I add a module declaration to it, it no longer outputs anything:
module main;
sub MAIN ( *@filenames )
{
for @filenames -> $filename
{
say "Processing '$filename'";
}
}
Which results in nothing output:
perl6 main.pm6 hello.txt world.txt
So, how can I build a modulino in Perl6?
I'm using Perl6 running on MoarVM from the January 2015 release of Rakudo Star.
UPDATE:
When I try wrapping the module in braces:
module main
{
sub process (@filenames) is export
{
for @filenames -> $filename
{
say "Processing '$filename'";
}
}
};
sub MAIN ( *@filenames )
{
process(@filenames)
}
I also get errors:
===SORRY!=== Error while compiling main.pm6
Undeclared routine:
process used at line 14. Did you mean 'proceed'?
A: The MAIN sub needs to be declared outside the module, but it still must be able to see process.
There are multiple ways to achieve this, eg by not declaring a module at all
sub process(@filenames) {
for @filenames -> $filename {
say "Processing '$filename'";
}
}
sub MAIN(*@filenames) {
process(@filenames);
}
by making process our-scoped and calling it by its longname
module main {
our sub process(@filenames) {
for @filenames -> $filename {
say "Processing '$filename'";
}
}
}
sub MAIN(*@filenames) {
main::process(@filenames);
}
or by exporting process and importing it in the body of MAIN
module main {
sub process(@filenames) is export {
for @filenames -> $filename {
say "Processing '$filename'";
}
}
}
sub MAIN(*@filenames) {
import main;
process(@filenames);
}
In my opinion the most appropriate option is to add MAIN to the module and import it into the script's mainline. This way, everything declared within the module is visible within MAIN without having to explicitly export everything:
module main {
sub process(@filenames) {
for @filenames -> $filename {
say "Processing '$filename'";
}
}
sub MAIN(*@filenames) is export(:MAIN) {
process(@filenames);
}
}
import main :MAIN;
Note that this does not export MAIN by default, ie users of your module will only get it if they provide the :MAIN tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29281305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Can a bot click a link that makes a modal window in javascript? I have a form that launches in a modal window (fancybox to be exact) that loads a page that triggers an event in Google Analytics. I'm trying to keep bots from clicking it.
Since the fancybox uses jQuery to load the html page, can a bot reach the page and trigger the event? I'm trying to determine if the events are real.
I'm getting a difference between unique events and total events and trying to explain why there would be a discrepancy. Is the only way to explain it as genuine people clicking or could it be bots?
A: Yes, a bot can do that. There's many ways of creating bots, and different methods will make most bots undetectable unless you have some really complex checks in place. I believe reCaptcha has a tonne of checks for example, ranging from the movement of the mouse, the react time of the user, user agents and so on and so forth.
Bots can come in all shapes and forms, including some that might use Selenium to imitate a user using an actual browser, or they could even be written in a lower level and move the mouse and cause key presses on a system level.
What it comes down to is how much energy/time you're willing to expend to make it harder for bots to do their thing. I doubt you'll ever get 100% accuracy on stopping bots.
But yes, a bot can trigger a button press event, or even press the button directly like a normal user would
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35752557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Limit number of results for Songkick API I'm trying to limit the number of results that this pulls:
http://api.songkick.com/api/3.0/search/venues.json?query={venue term}&apikey={API KEY}
I've tried adding on maxResults, limit, results.. none of them seem to work.
I can't find anything in the documentation. Anyone know?
Thanks!
A: The documentation for venue search mentions the per_page argument, that limits how many items are returned for each request.
You can try using:
http://api.songkick.com/api/3.0/search/venues.json?query={venue term}&per_page=10&apikey={API KEY}
It accepts any value between 1 and 50.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39030058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FileHelpers Library: AfterReadRecord Compilation Error I'm hoping there's an expert in using the FileHelpers library here.
I'm using the 2.9.9 stable version from Nuget and trying to use the AfterReadRecord event handler to test if fields are empty.
The code I have is shown in simplified form below:
public class Test
{
public class MyClass
{
public string Name;
}
public static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<MyClass> e)
{
if (String.IsNullOrWhiteSpace(e.Record.Name))
{
throw new InvalidDataException("Name is required");
}
}
public void ReadCSV()
{
FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
engine.Options.IgnoreFirstLines = 1;
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
}
}
There's a compilation error on that last line in the ReadCSV file. The error is:
Cannot implicitly convert type 'FileHelpers.Events.AfterReadHandler<MyClass>' to
'FileHelpers.Events.AfterReadHandler<object>'
I'm stuck. Any helpers?
Jake
A: The problem is that u are using a version of the engines that don't use generics but using generics in the handler
Try with this:
var engine = new FileHelperEngine<MyClass>();
engine.Options.IgnoreFirstLines = 1;
engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17971250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to 'translate' a string of words using a map? Search through a maps keys and displaying the value I have a map that contains Spanish words as keys and the same word in English as the values for each key. I want to translate a string of words from Spanish to English. I'm assuming I'll need to parse the string to separate the words. I don't know how to search through the map keys and then to display the value.
map<string, string> trans;
tran["rearrancar"] = "reboot";
tran["pantalla"] = "screen";
tran["texto"] = "text";
tran["virus"] = "virus";
tran["tinta"] = "ink";
tran["mitad"] = "half";
tran["interno"] = "internal";
tran["memoria"] = "memory";
tran["papel"] = "paper";
tran["energia"] = "power";
tran["fallo"] = "bug";
tran["pelo"] = "hair";
tran["el"] = "the";
tran["dos"] = "two";
tran["todas"] = "all";
tran["en"] = "in";
tran["de"] = "of";
tran["los"] = "the";
tran["comprar"] = "buy";
tran["tarde"] = "afternoon";
tran["quieres"] = "want";
tran["muchachos"] = "boys";
tran["tienen"] = "have";
tran["ordenador"] = "computer";
tran["con"] = "with";
tran["antes"] = "before";
tran["vacio"] = "empty";
tran["tu"] = "you";
tran["hambre"] = "hunger";
tran["contaminado"] = "corrupt";
tran["a"] = "to";
tran["una"] = "a";
tran["la"] = "the";
tran["cafe"] = "brown";
tran["su"] = "your";
tran["es"] = "is";
tran["quiero"] = "want";
tran["vamos"] = "go";
tran["mi"] = "my";
tran["barco"] = "ship";
tran["nosotros"] = "we";
tran["casa"] = "house";
tran["yo"] = "I";
tran["borrar"] = "delete";
tran["necesita"] = "necessary";
tran["despues"] = "after";
string paragraph ("yo quiero una ordenador virus
todas de los muchachos tienen interno memoria
mi pelo es cafe
tu quieres tinta con su papel
rearrancar el ordenador a vacio el pantalla");
Would it be better to store each word into an array of strings?
Edit: I can now search the map for the word to translate but it crashes after the 4th translated word. I'm sure it has something to do with the parameters in my for loop but I don't know what to put in it.
stringstream ss(paragraph);
string word = "";
for (int i = 0; i < paragraph.length(); i++) {
getline(ss, word, ' ');
cout << tran.find(word)->second << " ";
}
Paragraph is the string containing the paragraph to be translated. Tran is the name of my map containing the Spanish keys and English values.
A: Your loop loops paragraph.length() times (the number of characters in paragraph), but each time you extract a word. See the problem?
Use while (getline(ss, word, ' ')) instead. getline will return the stream it was given, and converting it to bool is equivalent to !ss.fail(). This basically loops until an extraction fails (reached the end of the stream and did not extract anything).
You also never checked if the search for the word in the map fails and therefore have the possibility of trying to dereference tran.end().
Some other minor problems with your code includes using namespace std which can be considered bad practice, and some typos involving the difference between tran and trans.
The fixed code:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main()
{
std::map<std::string, std::string> tran;
tran["rearrancar"] = "reboot";
tran["pantalla"] = "screen";
tran["texto"] = "text";
tran["virus"] = "virus";
tran["tinta"] = "ink";
tran["mitad"] = "half";
tran["interno"] = "internal";
tran["memoria"] = "memory";
tran["papel"] = "paper";
tran["energia"] = "power";
tran["fallo"] = "bug";
tran["pelo"] = "hair";
tran["el"] = "the";
tran["dos"] = "two";
tran["todas"] = "all";
tran["en"] = "in";
tran["de"] = "of";
tran["los"] = "the";
tran["comprar"] = "buy";
tran["tarde"] = "afternoon";
tran["quieres"] = "want";
tran["muchachos"] = "boys";
tran["tienen"] = "have";
tran["ordenador"] = "computer";
tran["con"] = "with";
tran["antes"] = "before";
tran["vacio"] = "empty";
tran["tu"] = "you";
tran["hambre"] = "hunger";
tran["contaminado"] = "corrupt";
tran["a"] = "to";
tran["una"] = "a";
tran["la"] = "the";
tran["cafe"] = "brown";
tran["su"] = "your";
tran["es"] = "is";
tran["quiero"] = "want";
tran["vamos"] = "go";
tran["mi"] = "my";
tran["barco"] = "ship";
tran["nosotros"] = "we";
tran["casa"] = "house";
tran["yo"] = "I";
tran["borrar"] = "delete";
tran["necesita"] = "necessary";
tran["despues"] = "after";
std::string paragraph(
"yo quiero una ordenador virusu todas de los muchachos tienen");
std::stringstream ss(paragraph);
std::string word;
while (std::getline(ss, word, ' '))
{
auto findResult = (tran.find(word));
std::cout
<< (findResult != tran.end() ?
findResult->second : "[translation not found]") << " ";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50123936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS Cognito: Add custom claim/attribute to JWT access token My app creates a custom attribute "userType" for each new signed-up user. Now I would like this "userType" claim/attribute to be added to the JWT access token whenever the user signs in or the token gets refreshed.
Is there an option to tell cognito to add my custom claim/attribute to the JWT access token? (Without a pre token generation Lambda)
A: Custom attributes are not available in Cognito access token. Currently it is not possible to inject additional claims in Access Token using Pre Token Generation Lambda Trigger as well. PreToken Generation Lambda Trigger allows you to customize identity token(Id Token) claims only.
A: You can use ID token to get the token with custom attributes.
Access tokens are not intended to carry information about the user. They simply allow access to certain defined server resources.
You can pass an ID Token around different components of your client, and these components can use the ID Token to confirm that the user is authenticated and also to retrieve information about them.
How to retrieve Id token using amazon cognito identity js
cognitoUser.authenticateUser(authenticationDetails,{
onSuccess: function(result) {
var accessToken = result.getIdToken().getJwtToken();
console.log('accessToken is: ' + accessToken);
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
},
});
A: I have the same problem when I want to create several microservice. There isn't a way I can customize an access token, but only an identity token. However, I use client credentials in the machine-to-machine which needs access token. So, in no way I can customize my token. At last, I decide to add such info(like user type) in the event header. It's not a very secure way compared to customize a token, but there isn't any other easy way to do it right now. Otherwise, I have to rewrite the authorizer in Cognito. Like rewriting a customize authorizer and it's very painful.
A: I have the same issue with Cognito; exist other tools like "PingFederate"Auth-server of Ping identity and Auth0 Auth-server; I know that the requirement isn't part of the standard, but these applications were my alternatives to fix this issue
A: The responses suggesting to use the ID Token for authorization in your backend systems are bad security practice. ID Tokens are for determining that the user is in fact logged in and the identity of that user. This is something that should be performed in your frontend. Access Tokens on the other hand are for determining that a request (to your backend) is authorized. ID Tokens do not have the same security controls against spoofing that Access Tokens have (see this blog from Auth0: https://auth0.com/blog/id-token-access-token-what-is-the-difference/).
Instead, I recommend that your backend accept an Access Token as a Bearer token via the Authorization HTTP header. Your backend then calls the corresponding /userinfo endpoint (see: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) on the authorization server that issued the Access Token, passing such said Access Token to that endpoint. This endpoint will return all of the ID Token information and claims, which you can then use to make authorization decisions in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56970499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: TADOQuery.Open executes a statement but only once I use this code to copy row from Table1 to Table2, but it gives me
Command Text does not return a result set
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('insert into Table1');
ADOQuery1.SQL.Add('select Field1 ,Field2 from Table2');
ADOQuery1.SQL.Add('where ArtNo= 1');
ADOQuery1.Open;
ADOQuery1.Refresh ;
If I don't use
ADOQuery1.Open;
it gives me
ADOQuery1: Cannot perform this operation on a closed dataset.
It copies what I want but only once. How to copy many times? Thank you.
A: For scripts that do not open a cursor (like insert, update or exec ones) use the ExecSQL Method of TADOQuery.
It returns a Integer representing the number of affected rows by your query.
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('insert into Table1');
ADOQuery1.SQL.Add('select Field1 ,Field2 from Table2');
ADOQuery1.SQL.Add('where ArtNo= 1');
NumRows := ADOQuery1.ExecSQL;
ShowMessageFmt('Affected rows on Table2: %d', [NumRows]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4139633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to bind drowpdown list with one static value and rest from database I am working with asp.net mvc I want to add a dropdown list that holds one static value and other values coming from database
@Html.DropDownListFor(Function(model) model.nDepartmentID,
New SelectList(ViewBag.txt, "Value", "Text"), New With
{Key .[class] = "select1",Key .style = "width: 150px;"})
A: Use below code
@Html.DropDownListFor(m => m.nDepartmentID, (SelectList)ViewBag.DepartmentList, "Select Any Department", new {@class="select1",@style="width: 150px;" })
Your controller Action will be
public ActionResult ShowPage()
{
var deptmnts=db.Departments.ToList();
ViewBag.DepartmentList=new SelectList(deptmnts,"ID","DepartmentName");
retun View();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28472178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what does it mean to delete a file on android Naturally I thought to delete a file means to remove it from existence. So when I do
File file = new File(absPath);
....//add content
file.delete();
I expect that no further operation can be executed on file or it would throw an exception. But how come I can still add content to the file such as shown here Android saving Bitmap to SD card. So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there? I am not in a position to test this now, so I was hoping for authoritative reference.
A:
how come I can still add content to the file such as shown here Android saving Bitmap to SD card.
That code creates a new file after deleting the old one.
So how do I delete a file so that it is completely gone? So that when someone go look through file manager, the file is no longer there?
Call delete() on a File object that points to the file. Then, do not use that same File object to write to the file again, thereby creating a new file, as the code that you link to does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34667600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to package a simple Python project and have it perform installation over the internet I would like to know if there's a way to package a simple Python project and have it perform installation over the internet, just like when you install a module with pip.
A: Sure there is. This is how all the 3rd party packages we are all using did.
The formal pypa explain how to do it here.
Basically you need to package your project to a wheel file and upload it to the pypi repository. To do this you need to declare (mainly in setup.py), what is your package name, version, which sub-packages you want to pack to the wheel etc..
A: If your packages are required for a particular project, it is straightforward to contain them in the Git repository. You can put them in the directory named wheelhouse, which comes from the name of the previous default directory created by pip wheel.
If you put the private package foo in the wheelhouse, you can install as follows:
pip install foo -f wheelhouse
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58658820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: MySQL query works through workbench but not mysqli I am attempting to call my PHP class and run the function get_group_count which counts the number of groups for a certain user ID. The mysqli query uses a stored procedure that works in MySQL Workbench but not with PHP's mysqli.
Public function:
public function get_group_count($userID) {
if($this->status()) {
$db = Database::getInstance();
$con = $db->getConnection();
$pull = $con->prepare("CALL get_group_count(?)");
$pull->bind_param('i', $userID); // line 19
if(!$pull->execute()) {
$pull->close();
return false;
};
$pull->store_result();
$pull->bind_result($count);
$pull->fetch();
$pull->close();
return $count;
};
return false;
}
Error:
Call to a member function bind_param() on a non-object in ... on line 19
Stored procedure:
DELIMITER //
CREATE PROCEDURE get_group_count(IN userID int)
BEGIN
SELECT (SELECT count(*) FROM groups WHERE adminID = userID) + (SELECT count(*) FROM members WHERE userID = userID) AS count;
END //
DELIMITER ;
When calling the procedure through MySQL Workbench it returns a total number of rows from the groups table and members table.
Note: I also get the same error when attempting to run the query through mysqli rather than the stored procedure.
How can I fix this?
EDIT:
$con var_dump:
object(mysqli)#4 (19) {
["affected_rows"]=>
int(1)
["client_info"]=>
string(6) "5.5.45"
["client_version"]=>
int(50545)
["connect_errno"]=>
int(0)
["connect_error"]=>
NULL
["errno"]=>
int(2014)
["error"]=>
string(52) "Commands out of sync; you can't run this command now"
["error_list"]=>
array(1) {
[0]=>
array(3) {
["errno"]=>
int(2014)
["sqlstate"]=>
string(5) "HY000"
["error"]=>
string(52) "Commands out of sync; you can't run this command now"
}
}
["field_count"]=>
int(1)
["host_info"]=>
string(25) "Localhost via UNIX socket"
["info"]=>
NULL
["insert_id"]=>
int(0)
["server_info"]=>
string(14) "5.5.45-cll-lve"
["server_version"]=>
int(50545)
["stat"]=>
string(52) "Commands out of sync; you can't run this command now"
["sqlstate"]=>
string(5) "HY000"
["protocol_version"]=>
int(10)
["thread_id"]=>
int(36623197)
["warning_count"]=>
int(0)
}
$pull var_dump:
bool(false)
NULL
EDIT2: Ended up switching to PDO, everything works now.
A: After looking at the $con dump, it appears that the last query you're executing on this connection is not using its result. mysqli uses unbuffered queries by default, so you need to either fetch the result of the previous query executed into a buffer manually, or free the memory that it's using to make room for your new query, with either store_result() or free_result(), respectively.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36817389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails: ArgumentError in PostsController#create wrong number of arguments (1 for 0) Github Repo
Hi, I'm a noob and need help. Making a yearbook for my bootcamp class and having some hiccups. Current error is:
ArgumentError in PostsController#create
wrong number of arguments (1 for 0)
Extracted source (around line #63):
61
62
63
64
65
66
private
def post_params
params.require(:post).permit(:name, :body)
end
end
screenshot of error message
Wdiers are my users. These wdiers are students and instructors. Currently, I am just trying to add a post onto the wdier show page. I currently have a post on the page for a test wdier that came from my seed file. The error is when I was trying to create a new post. I was able to get to the form page and the error came after I submitted the post. (I had posts called comments originally but changed it to posts and will have comments as a reply to those posts)
Also, want to note that I am using devise, in case that matters.
Here are my pages:
WDIer controller
class WdiersController < ApplicationController
def index
@wdiers = Wdier.all
end
def new
@wdier = Wdier.new
end
def create
@wdier = Wdier.create!(wdier_params)
redirect_to wdiers_path(@wdier)
end
def show
@wdier = Wdier.find(params[:id])
end
def edit
@wdier = Wdier.find(params[:id])
end
def update
@wdier = Wdier.find(params[:id])
@wdier.update(wdier_params)
redirect_to wdiers_path(@wdier)
end
def destroy
@wdier = Wdier.find(params[:id])
@wdier.destroy
redirect_to wdiers_path(@wdier)
end
def wdier_params
params.require(:wdier).permit(:name, :img_url, :squad_name, :squad_id, :quote, :teaching, :memory, :favlang, :wisewords, :tag_list,:github_url, :portfolio_url, :project1_url, :project2_url, :project3_url, :quote, :q1, :q2, :q3, :fb, :linkedin, :email, :role, :student_id, :instructor_id)
end
end
Post controller
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@wdier = Wdier.find(params[:wdier_id])
@post = Post.find(params[:id])
end
def edit
@wdier = Wdier.find(params[:wdier_id])
@post = Post.find(params[:id])
end
def new
@wdier = Wdier.find(params[:wdier_id])
@post = Post.new
end
def create
@wdier = Wdier.find(params[:wdier_id])
@post = @wdier.posts.create!(post_params)
@post = Post.new(params.require(:post).permit(:task))
@post.save
if @post.save
flash[:alert] = "Post created successfully."
redirect_to post_params([:wdier_id])
else
flash[:alert] = "Error creating post."
redirect_to post_params([:wdier_id])
end
end
def update
@wdier = Wdier.find(params[:wdier_id])
@post = Post.find(params[:id])
if @post.user == current_user
@post.update(wdier_params)
else
flash[:alert] = "Only the author of the post can edit it!"
end
redirect_to wdier_params(@wdier)
end
def destroy
@wdier = Wdier.find(params[:wdier_id])
@post = Post.find(params[:id])
if @post.user == current_user
@post.destroy
else
flash[:alert] = "Only the author of the post can delete"
end
redirect_to wdier_path(@wdier)
end
private
def post_params
params.require(:post).permit(:name,:body)
end
end
Post model
class Post < ActiveRecord::Base
belongs_to :instructors
belongs_to :students
belongs_to :users
belongs_to :wdiers
has_many :comments
end
Wdier model
class Wdier < ActiveRecord::Base
belongs_to :squad
belongs_to :instructors
belongs_to :students
has_one :codey
has_many :comments
has_many :posts
has_many :negatives
has_many :photos, through: :negatives
end
Wdier show view:
<section id="wdierShow">
<h1 class="page-header"><%= @wdier.name %></h1>
<div class="index">
<section>
<div class="button"><%= link_to "edit", edit_wdier_path(@wdier)%></h2></div>
</br>
<div class="profileImg">
<%= image_tag @wdier.img_url %>
</div>
<div class="topContainer">
<!-- <h1><%= @wdier.name %></h1> -->
<ul class="grid">
<%= @wdier.squad_id %> </br>
<%= @wdier.codey_id %> </br>
<%= @wdier.quote %> </br>
<%= @wdier.teaching %> </br>
<%= @wdier.memory %> </br>
<%= @wdier.favlang %> </br>
<%= @wdier.wisewords %> </br>
</ul>
</div>
<section id="photo">
<div class="photoGallery">
<h2>Pics Please</h2>
<button> <%= link_to "Add new photo", new_photo_path(@wdier) %></button>
<ul>
<li class="col-lg-3 col-md-4 col-sm-6 col-xs-12"><% @wdier.photos.each do |photo| %>
<%= image_tag photo.img_url %></li>
<% end %>
</ul>
</div>
<section>
</section>
<section id="comment">
<div class="commentGallery">
<div class="overlay">
<h2>keep in touch...</h2>
<%= link_to "Add new comment", new_wdier_post_path(@wdier) %>
<% @wdier.posts.each do |post| %>
<p>
<%= post.body %>
</p>
<% if current_user && current_user == post.user %>
<%= link_to "Edit", edit_wdier_post_path(@wdier) %> |
<%= link_to "Delete", wdier_post_path(@wdier), method: :delete %>
<% end %>
</div>
<% end %>
</div>
</section>
</section>
Post new view:
<%= form_for [@wdier, @post] do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
Schema:
ActiveRecord::Schema.define(version: 20160521153002) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "comments", force: :cascade do |t|
t.string "name"
t.string "body"
t.integer "wdier_id"
end
add_index "comments", ["wdier_id"], name: "index_comments_on_wdier_id", using: :btree
create_table "instructors", force: :cascade do |t|
t.string "name"
t.string "img_url"
t.string "squad_name"
t.string "quote"
t.string "teaching"
t.string "memory"
t.string "favlang"
t.string "wisewords"
t.string "email"
t.string "password"
t.integer "squad_id"
t.integer "user_id"
t.integer "wdier_id"
end
add_index "instructors", ["squad_id"], name: "index_instructors_on_squad_id", using: :btree
add_index "instructors", ["user_id"], name: "index_instructors_on_user_id", using: :btree
add_index "instructors", ["wdier_id"], name: "index_instructors_on_wdier_id", using: :btree
create_table "negatives", force: :cascade do |t|
t.integer "photo_id"
t.integer "instructor_id"
t.integer "student_id"
t.integer "user_id"
t.integer "wdier_id"
end
add_index "negatives", ["instructor_id"], name: "index_negatives_on_instructor_id", using: :btree
add_index "negatives", ["photo_id"], name: "index_negatives_on_photo_id", using: :btree
add_index "negatives", ["student_id"], name: "index_negatives_on_student_id", using: :btree
add_index "negatives", ["user_id"], name: "index_negatives_on_user_id", using: :btree
add_index "negatives", ["wdier_id"], name: "index_negatives_on_wdier_id", using: :btree
create_table "photos", force: :cascade do |t|
t.string "img_url"
t.string "caption"
end
create_table "posts", force: :cascade do |t|
t.string "name"
t.string "body"
t.integer "wdier_id"
end
add_index "posts", ["wdier_id"], name: "index_posts_on_wdier_id", using: :btree
create_table "students", force: :cascade do |t|
t.string "name"
t.string "img_url"
t.string "github_url"
t.string "portfolio_url"
t.string "project1_url"
t.string "project2_url"
t.string "project3_url"
t.string "project4_url"
t.string "quote"
t.string "q1"
t.string "q2"
t.string "q3"
t.string "q4"
t.string "fb"
t.string "linkedin"
t.string "email"
t.string "password"
t.integer "instructor_id"
t.integer "squad_id"
t.integer "user_id"
t.integer "wdier_id"
end
add_index "students", ["instructor_id"], name: "index_students_on_instructor_id", using: :btree
add_index "students", ["squad_id"], name: "index_students_on_squad_id", using: :btree
add_index "students", ["user_id"], name: "index_students_on_user_id", using: :btree
add_index "students", ["wdier_id"], name: "index_students_on_wdier_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "img_url"
t.string "github_url"
t.string "portfolio_url"
t.string "project1_url"
t.string "project2_url"
t.string "project3_url"
t.string "quote"
t.string "squad_name"
t.string "teaching"
t.string "memory"
t.string "favlang"
t.string "wisewords"
t.string "tag_list"
t.string "q1"
t.string "q2"
t.string "q3"
t.string "fb"
t.string "linkedin"
t.integer "squad_id"
t.integer "student_id"
t.integer "instructor_id"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
create_table "wdiers", force: :cascade do |t|
t.string "name"
t.string "img_url"
t.string "github_url"
t.string "portfolio_url"
t.string "project1_url"
t.string "project2_url"
t.string "project3_url"
t.string "quote"
t.string "squad_name"
t.integer "teaching"
t.integer "memory"
t.integer "favlang"
t.integer "wisewords"
t.integer "tag_list"
t.integer "q1"
t.integer "q2"
t.integer "q3"
t.integer "fb"
t.integer "linkedin"
t.integer "email"
t.integer "role"
t.integer "password"
t.integer "squad_id"
t.integer "codey_id"
t.integer "student_id"
t.integer "instructor_id"
end
add_index "wdiers", ["codey_id"], name: "index_wdiers_on_codey_id", using: :btree
add_index "wdiers", ["instructor_id"], name: "index_wdiers_on_instructor_id", using: :btree
add_index "wdiers", ["squad_id"], name: "index_wdiers_on_squad_id", using: :btree
add_index "wdiers", ["student_id"], name: "index_wdiers_on_student_id", using: :btree
add_foreign_key "comments", "wdiers"
end
Any help would be greatly appreciated!!!
I am adding the rake routes to the question.
$ rake routes
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
root GET / yearbook#index
tag GET /tags/:tag(.:format) photo#index
wdier_posts GET /wdiers/:wdier_id/posts(.:format) posts#index
POST /wdiers/:wdier_id/posts(.:format) posts#create
new_wdier_post GET /wdiers/:wdier_id/posts/new(.:format) posts#new
edit_wdier_post GET /wdiers/:wdier_id/posts/:id/edit(.:format) posts#edit
wdier_post GET /wdiers/:wdier_id/posts/:id(.:format) posts#show
PATCH /wdiers/:wdier_id/posts/:id(.:format) posts#update
PUT /wdiers/:wdier_id/posts/:id(.:format) posts#update
DELETE /wdiers/:wdier_id/posts/:id(.:format) posts#destroy
wdiers GET /wdiers(.:format) wdiers#index
POST /wdiers(.:format) wdiers#create
new_wdier GET /wdiers/new(.:format) wdiers#new
edit_wdier GET /wdiers/:id/edit(.:format) wdiers#edit
wdier GET /wdiers/:id(.:format) wdiers#show
PATCH /wdiers/:id(.:format) wdiers#update
PUT /wdiers/:id(.:format) wdiers#update
DELETE /wdiers/:id(.:format) wdiers#destroy
photos GET /photos(.:format) photos#index
POST /photos(.:format) photos#create
new_photo GET /photos/new(.:format) photos#new
edit_photo GET /photos/:id/edit(.:format) photos#edit
photo GET /photos/:id(.:format) photos#show
PATCH /photos/:id(.:format) photos#update
PUT /photos/:id(.:format) photos#update
DELETE /photos/:id(.:format) photos#destroy
codeys GET /codeys(.:format) codeys#index
POST /codeys(.:format) codeys#create
new_codey GET /codeys/new(.:format) codeys#new
edit_codey GET /codeys/:id/edit(.:format) codeys#edit
codey GET /codeys/:id(.:format) codeys#show
PATCH /codeys/:id(.:format) codeys#update
PUT /codeys/:id(.:format) codeys#update
DELETE /codeys/:id(.:format) codeys#destroy
squads GET /squads(.:format) squads#index
POST /squads(.:format) squads#create
new_squad GET /squads/new(.:format) squads#new
edit_squad GET /squads/:id/edit(.:format) squads#edit
squad GET /squads/:id(.:format) squads#show
PATCH /squads/:id(.:format) squads#update
PUT /squads/:id(.:format) squads#update
DELETE /squads/:id(.:format) squads#destroy
A: You are calling post_params with an argument, whereas it is not expecting one.
Since post_params returns a hash, you don't need parenthesis to access the value:
post_params[:wdier_id]
However, you don't permit wdier_id in your strong params, so that would return nil. My guess is that you want this behavior:
redirect_to wdier_path(params[:wdier_id])
A: Look at your error description. In line 32 of posts_controllers.rb in create method you use your function post_params with argument [:wdier_id]. That method doesn't take any arguments, so you have got error.
Instead of redirect_to post_params([:wdier_id]) you should have something like redirect_to photo_path(@post.id) or something like that.
A: The resolution was redirect_to wdier_path(@wdier)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37365616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Web page login with python failure or not? I try to login to the site www.dsbmobile.de. It uses a form (<form name="form1" method="post" action="./Login.aspx" id="form1">), so I do the following:
import requests
url="https://www.dsbmobile.de/Login.aspx"
values={'txtUser':'XXXuserXXX','txtPass':'XXXpasswordXXX'}
r=requests.post(url,data=values)
s=requests.get(url,r.cookies,auth=(values['txtUser'], values['txtPass']))
Both r and s yield a successful response (200), and I get a cookie. However, the resulting page still shows the login page, whereas if I login manually, I get a different page.
Why does the automated login fail?
Most likely this is a duplicate question, but I have tried more than 20 other suggestions from stackoverflow and have failed so far.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46986958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rdgal don't working well to save a shapefile I'm trying to save a shapefile format with detection rates using the "rgdal" packages, but the following error occurs:
Error in showSRID(uprojargs, format = "PROJ", multiline = "NO") :
Can't parse PROJ.4-style parameter string
+proj=longlat +ellps=WGS84+datum=WGS84+no_def
How to fix?
Reproductive example
library(rgdal)
library(sp)
library(camtrapR)
Long<-c(-53.59390711, -53.58148303)
Lat<-c(-4.633924739, -4.6340598)
df1<-data.frame(Long,Lat)
df1$Station<-NA
df1[df1$Long=="-53.59390711",]$Station<-"w"
df1[df1$Long=="-53.58148303",]$Station<-"z"
Station<-c("w","w","w","w","w","w","w","w","w","w","z","z","z","z","z","z","z","z","z","z")
Species<-c("a","a","a","b","b","b","c","c","c","c","a","b","b","b","b","b","c","c","c","c")
df2<-data.frame(Station, Species)
detectionMaps(CTtable=df1,recordTable=df2,Xcol="Long",Ycol="Lat",stationCol="Station",speciesCol="Species",speciesToShow="a",richnessPlot=FALSE,speciesPlots=FALSE,
writeShapefile=TRUE,shapefileDirectory=tempdir(),shapefileName="sp_a", shapefileProjection="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_def")
#The shapefile should be created in this directory: C:\Users\...\AppData\Local\Temp\
A: This is an issue connected to the change from PROJ4 to PROJ6 in rgdal/sp. For you the issue is a bit deeper because the camtrapR package is not yet updated to deal with PROJ6.You can read more about the transition to PROJ6 here.
Without going too deep into it the solution for you would be to downgrade to an older version of sp and rgdal.
For sp (< 1.4-2) and rgdal (< 1.5-8).
EDIT: Since you can define the PROJ String yourself you can also first try: "+init=epsg:4326". This might still work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63334025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Method api target warning Im trying to create a library, but some methods will only work for API > 21.
How can I set the minimum api target for this method and show a warning?
like the TextureView for example:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomTextureView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
A: // Check if we're running on GingerBread or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
// do somthing
// if not
} else {
// do somthing
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35144856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Validating string input value c language #include <stdio.h>
int main()
{
char name[10];
printf("Who are you? \n");
fgets(name,10,stdin);
printf("Good to meet you, %s.\n",name);
if(name=='spyros')
{
printf("Then you are here %s\n",name)
}
return(0);
}
Then i have
warning warning: character constant too long for its type
A: A char can only store 1 character not a set of characters, and by directly comparing the string to a character array won't work because of the null character
This will work , hope it helps
#include <stdio.h>
#include<string.h>
int main()
{
char name[10];
printf("Who are you? \n");
fgets(name,10,stdin);
printf("Good to meet you, %s.\n",name);
if(strcmp(name,"spyro"))
{
printf("Then you are here %s\n",name);
}
return(0);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35971123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: defun with a list as argument I'm trying to pick up Lisp as my new language, and I'm having some issues working out how to have parts of a function work on each element of the list passed to it.
For the purpose of learning how to get around this, I am trying to write a fairly basic form of division does not croak when one of the elements of the list are 0 (but instead just returns 0)
(defun divtest (elements)
(dolist (x elements)
(if (zerop x) 0 () )
(/ elements)))))
I try to run this as:
(divtest '(20 2 5))
Which yields:
*** - /: (20 2 5) is not a number
The point of failure seems to be rooted in the fact that i am not "extracting" the elements in the list before passing them to the function (in this case, neither / nor dolist works as intended, as x never evaluates to 0).
If I'm right, can someone tell me how to perform this "extraction"?
Note: This question is related to one that I've asked earlier, but as I'm unclear about which part of the previous answer actually allowed it to work as intended with this specific problem i decided to go further into the basics
A: / takes as arguments one or more numbers, but in your code you're passing it a list - clearly this will not work. The function apply is your friend here - (apply #'foo a b (list c d e)) is equivalent to (foo a b c d e). Note the the arguments to apply between the function to use and the final list are optional, so (apply #'/ '(20 2 5)) is equivalent to (/ 20 2 5).
Also, your attempt at removing zeros will not work. dolist is evaluating its body for each item in the argument list elements, but you're not actually doing anything to change the content of elements (the result of evaluating dolist s body is not reassigned to the source element as you seem to expect).
The functions remove-if (and its destructive counterpart, delete-if) are what you are looking for. The following shows how to use it (it takes lots of optional arguments, which you don't need to worry about for this purpose).
(defun divtest (elements)
(apply #'/ (remove-if #'zerop elements)))
Also note that this won't behave correctly if the elements list has zero as its first element (assuming I understand what the function's meant to do). So you might instead want something like
(defun divtest (elements)
(apply #'/ (first elements) (remove-if #'zerop (rest elements))))
See the Hyperspec for more details.
A: Try (apply / elements) in place of (/ elements). I think(?) that should work in most dialects of Lisp.
A: Or you can write it like this
(defun divtest (elements)
(if (member 0 elements)
0
(apply #'/ elements)))
A: (block exit
(reduce #'/ '(1 2 3 0 5)
:key (lambda (x)
(if (zerop x)
(return-from exit 0)
x))))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8950323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How are variables passed in laravel mails when using queue? I have set up my system so that users get a mail with their names when they successfully register and it works just fine. But i noticed that it takes a bit longer than i want for the page to display a success message so i decided to use laravel queue for background sending. Unfortunately member detail is added successfully but no mail is sent and the page error says
Undefined property: App\Mail\Received::$name
Basically the following code is failing
$name = $newMember->firstname;
Mail::to($newMember)->queue(new Received($name));
While this one is working perfectly
$name = $newMember->firstname;
Mail::to($newMember)->send(new Received($name));
So the big question is why is the $name property undefined when i use queue but it's defined when i use send?
A: I fixed the issue by adding protected $name property in App\Mail\Received class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46474550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.