text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: I am looking for a way to use Vue props in a function I am looking a way to use props in a function. Yet the console says Cannot read property 'props' of undefined
How should I use props or pass the data to my function?
<template>
</template>
<script>
import {db} from '../plugins/firebase';
export default {
name: "VueComponent",
props: {
for : String
},
data: () => ({
thanks: [],
}),
firestore() {
return {
comments: db.collection('thanks').doc(this.props.for).orderBy('lookingAtMyPost');
}
},
}
</script>
The error:
chat.js?id=217075c507b419bb0145:48071 Uncaught TypeError: Cannot read property 'props' of undefined
at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vuetify-
A: You can access props like you can data properties, you don't have to do this.props.for you can just do this.for and it will work in the same way.
However, It's worth noting, you can't modify props directly in a child component, you'd have to emit an event for that.
From the Vue docs:
All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.
In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console.
Read this article for more info on how to mutate props: https://www.telerik.com/blogs/how-to-emit-data-in-vue-beyond-the-vuejs-documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62499306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to read content from plain text remote file with objective-c I want to read a list (in plain text) from a remote file line by line.
I have found some answers but they're not the ones I'm looking for.
p.s. I've been programing in objective-c and developing in iOS for about 2 months, I'm a rookie i might not understand or recognize some terms. Please answer like you are talking to a beginner.
A: If i am not wrong you just want to read a text from remote file, so here it is.
NSString * result = NULL;
NSError *err = nil;
NSURL * urlToRequest = [NSURL URLWithString:@"YOUR_REMOTE_FILE_URL"];//like "http://www.example.org/abc.txt"
if(urlToRequest)
{
result = [NSString stringWithContentsOfURL: urlToRequest
encoding:NSUTF8StringEncoding error:&err];
}
if(!err){
NSLog(@"Result::%@",result);
}
A: To load the remote txt file, you should take a look at NSURLConnection or AFNetworking (there are other possibilities, these two are probably the most common).
You will then get the content of the file. Depending on what you intend to do with it, you may have to parse it, either with something as simple as -[NSString componentsSeparatedByString:] or with something a bit more powerful like NSScanner.
A: There are three steps involved in loading a file
*
*create the object that specifies the location of the file
*call the appropriate NSString class method to load the file into a
string
*handle the error if the file is not found
In step 1, you need to either create an NSString with the full path to the file in the file system, or you need to create an NSURL with the network location of the file. In the example below, the code creates an NSURL since your file is on the network.
In step 2, use the stringWithContentsOfFile method to load a file from the file system, or the stringWithContentsOfURL method to load a file from the network. In either case, you can specify the file encoding, or ask iOS to auto-detect the file encoding. The code below auto detects while loading from the network.
In step 3, the code below dumps the file to the debug console if successful or dumps the error object to the console on failure.
Missing from this code is multithreading. The code will block until the file is loaded. Running the code on a background thread, and properly notifying the main thread when the download is complete, is left as an exercise for the reader.
NSURL *url = [NSURL URLWithString:@"www.example.com/somefile.txt"];
NSStringEncoding encoding;
NSError *error;
NSString *str = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
if ( str )
NSLog( @"%@", str );
else
NSLog( @"%@", error );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24784912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How To Extract Data From JSON with Rest Template in Java i have to extract the first 5 articles from https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21, having a result like this:
{
"total": 5,
"articles": [
{
"source": "Ilmessaggero.it",
"title": "Title",
"author": "Author",
"url": "URL"
}
]
}
I did this, having all the JSON as String as output for the localhost...
@RequestMapping("/news")
public Article connection() {
return restTemplate.getForObject
("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", Article.class);
The result in the localhost is:
{"source":null,"title":null,"author":null,"url":null}
But the problem now is, how do i put the data into the list of articles?
and how do i save them into mongodb? thanks for the effort
A: I solved it! SImply, the NewsAPI json of Article has a field called Source, which i was trying to parse as a string, but it was NOT! Infact, it is a field described with another object! I simply had to create a class called Source with id and name, and it works! Thanks everyone for the effort!
Here's the codes of the classes:
public class Article {
private Source source;
private String author;
private String title;
private String url;
//getters and setters
News, which has a list of articles:
public class News {
private int totalResults;
private List<Article> articles;
//getters and setters
And source, which is called in Article:
public class Source {
private String id;
private String name;
//getters and setters
Here it is! The parse code is the same of the answer. Just change the return type (Article) as News and the Article.class parameter of getForObject into News.class
A: A simple (i.e. missing exception handling, etc) way is as follows:
First, you need a class to represent the data you are receiving, with fields that match the API response fields, for example:
public class Article {
private String source;
private String title;
... // more fields
// getters and setters
}
The code to fetch the data from the API then looks like this:
RestTemplate template = ... // initialized earlier
ResponseEntity<Article[]> response = template.exchange(
API_URL, // url to the api
HttpMethod.GET, // use the Http verb "GET"
new HttpEntity<>(headers), // optional headers, e.g. for basic auth
Article[].class // the expected response type is Article[]
);
Article[] articles = response.getBody();
List<Article> list = Arrays.asList(articles); // if you need to use collections
Note, a ResponseEntity being non-null does not imply that the request was successful. You can use responseEntity.getStatusCode() to determine the status code of the response.
Be careful, however, since by default, RestTemplate throws an exception when a non-200 error code is recieved (HttpClientErrorException and HttpServerErrorException for 4XX and 5XX codes respectively). If you want your own custom error handling, you should call:
template.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// implement here
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// implement here
}
});
For persistence into MongoDB, you can use JPA, although JPA is not a perfect fit for MongoDB due to its inherently relational nature clashing with Mongo's non-relational structure. Something like Spring Data can more sensibly map this, and is worth looking into: https://spring.io/projects/spring-data-mongodb
EDIT - calling this code
Typically, I will create an class/interface with implementation (called ArticleResource for example) that looks like:
public class ArticleResource {
private final RestTemplate template = new RestTemplate();
public List<Article> getAllArticles() {
ResponseEntity<Article[]> response = template.exchange(API_URL, HttpMethod.GET, new HttpEntity<>(headers), Article[].class);
// some error checking here
return response.getBody() == null ? Collections.emptyList() : Arrays.asList(response.getBody());
}
}
For methods that expect a single value (e.g. findArticleByTitle(String title)) I typically return an Optional<Article> (it is bad practice to return Optional<List<T>>, as an empty list represents "no values" already).
From there in your code you can call:
ArticleResource resource = new ArticeResource();
// if you want to print all the names for example:
resource.getAllArticles().stream().map(Article::getName).forEach(System.out::println);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57604384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: model with relation to other model I am using backbone.js and I have the following unsolved situation:
Assume you have two models:
var Person = Backbone.model.extend({
defaults: {
name: '',
age: 24
}
});
var Car = Backbone.model.extend({
defaults: {
type: '',
driving_person: null
}
});
And I have a service which I can invoke by an ajax call and it return car json in the following format:
{
car: {
type: 'Honda Civic',
driving_person: {
name: 'dan',
age: 13
}
}
}
I add also urlRoot property inside the car model that reference to that service.
Now I want to use fetch in order to load a specific car, but I would like the get the car model with a person MODEL in the driving_person property. How can achieve this?
A: Your car model must contain user_id or user_name or some property like that,
so that you can take that data and do your embedding on the back end.
You also need to make use of parse() method of your model.
You override it to parse your json response from the server,
and when you parse, you automatically create your User model in backbone
(or refer to it, if it is already created).
But I think that also you can do this while creating your car model,
in it's initialize() method.
That may be even better.
However, if what you are asking is how you will select the proper car based on the user, when you request data from the server, then this logic is on the server side.
You need to implement it server side.
If you want to embed a driving_person within a model on a client side just like in your json response, just define your driving_person property, and it will have json object as its value.
If you want a new Backbone.Model embedded within car model, you will need to deal with initialize() of the car model.
Or even maybe parse().
Edited:
If you want to embed a user model into car model after fetch, you need to override constructor method:
var Car = Backbone.Model.extend({
constructor: function(data, options){
this.driving_person = new User(data.driving_person);
delete data.driving_person;
Backbone.Model.prototype.constructor.call(this, data);
}
/// Your other model code like initialize, etc.
Edit 2:
If you want to avoid having a new driver model per each car (because maybe more cars will share same driver), then you should probably have a global variable (or even a collection),
that takes Driver models.
It needs to be a global collection defined earlier in the code.
Then, you add driver to that global collection within this constructor that I gave you.
Let's say that you defined a global DriverCollection earlier in the code
(you do this by:
window.DriverCollection = Backbone.Collection.extend({
model: Driver,
Then, you would make your car model like this:
var Car = Backbone.Model.extend({
constructor: function(data, options){
if (!window.DriverCollection.find(function(driver){return driver.name == data.driving_person.name;}))
{window.DriverCollection.add(driving_person);}
data.driving_person = data.driving_person.name;
Backbone.Model.prototype.constructor.call(this, data);
}
/// Your other Car model code like initialize etc.
This way, your Car constructor takes JSON data and adds to global DriverCollection the driver if it doesnt exist, and it sets your car's driving_person property to name property of the embedded json driver object.
You can of course also use other property to reference & seek your driver, like id or whatever.
This way you avoid duplication.
You need to have Driver model defined for this to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13385903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server - how to "Generate and Publish Scripts" automatically I want to automatically (ideally from the command prompt in a batch file) automate the generation of the schema of my SQL Server 2008 R2 database.
In SSMS, I can right-click the DB, choose "Tasks", "Generate scripts", and then follow the wizard to gen a Schema script. Is there a command-line version of this process that I can use?
A: Microsoft released a new tool a few weeks ago called mssql-scripter that's the command line version of the "Generate Scripts" wizard in SSMS. It's a Python-based, open source command line tool and you can find the official announcement here. Essentially, the scripter allows you to generate a T-SQL script for your database/database object as a .sql file. You can generate the file and then execute it. This might be a nice solution for you to generate the schema of your db (schema is the default option). Here's a quick usage example to get you started:
$ pip install mssql-scripter
# script the database schema and data piped to a file.
$ mssql-scripter -S localhost -d AdventureWorks -U sa > ./adventureworks.sql
More usage examples are on our GitHub page here: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md
A: From this answer, there appear to be tools called SMOScript and ScriptDB that can do that.
If you find a way without third party tools please share :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5068670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Using Integer.parseInt() Properly I imported a string from another activity, which i want to change into an int.
Bundle gotBasket = getIntent().getExtras();
Integer.parseInt(gotBasket.getString("lol"));
From what i've read, the above code is how to do it. However, i don't know what "key", variablename or whatsoever, i will have to use, when using my integer.
For example if i have a TextView, and i want to set it to the value of the integer
I would say
TextView.setText(???????????)
As you can see, i don't know what to write in that field, would love if someone could tell me.
A: This should do it.
try
{
int a = Integer.parseInt(gotBasket.getString("lol"));
textView.setText("" + a);
}
catch (NumberFormatException e)
{
// handle the exception
}
A: You're doing the conversion right, but you're not saving the value anywhere.
int lulz = Integer.parseInt(gotBasket.getString("lol"));
Also, why do you want to convert it to an int to display it in a TextView?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9490506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Launch lync-2013 app from wp 8 app (and pass parameters to it) I am trying to launch a Lync-2013 app from the Windows Phone 8 app that I am developing.
I will be passing the number that lync client will call.
Does anyone know how to do this?
A: You can try the lync: protocol to activate the app:
Windows.System.Launcher.LaunchUriAsync(new Uri("lync:<sip:user1@hotmail.com>"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19610424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Shell script not exiting after a pipe to log file command Please find the below scrip.
When i run it, ./myscript.sh I am getting all echo statements in the terminal as well as in my log file.
But after the execution it is not exiting or coming back to terminal
Please help. I am quiet new to scripting.
#!/bin/sh
process() {
echo "Start..."
echo "Stop..."
exit 10
}
until [ $? -eq 10 ];
do
process | tee -a /home/temp/myLog.log
done
A: The exit code of a pipeline is the exit code of the last process in the pipeline. So here, even if process exits with code 10, the whole pipeline process | tee ... will exit with code 0.
You can change this behaviour using the pipefail option
set -o pipefail
Now the exit code of a pipeline will be the last non-zero exit code of any of the piped processes, or 0 if they all exit successfully.
This blog post explains it nicely, the official reference is the last paragraph from this section of the Bash manual.
A: Try grabbing the result of the first part of the pipe with ${PIPESTATUS[0]}:
#!/bin/sh
process() {
echo "Start..."
echo "Stop..."
exit 10
}
result=0
until [ $result -eq 10 ]
do
process | tee -a myLog.log
result=${PIPESTATUS[0]}
echo $result
done
A: Move the pipe behind the loop; the result is the same but the breaking will work:
#!/bin/sh
process() {
echo "Start..."
echo "Stop..."
exit 10
}
until [ $? -eq 10 ]
do
process
done | tee -a /home/temp/myLog.log
As others pointed out before me, the pipe's exit status is complex, so you cannot just use $? to get it. Best solution seems to be to get rid of the pipe in the context you need the exit status.
Maybe you do not even need the -a anymore this way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21603123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Operator Overloading Post Decrement I have to overload post decrement operator in which I have to Copy all elements of set1 into set2. After copying, decrement all elements of set1 (set2 = set1--;).
plzz tell me how can I implement this????
The simple post decrement operator I overloaded is as follows:
Set & operator --(int)
{
for(int i=0;i<size;i++)
{
arr[i] --;
}
return *this;
}
A: Your postdecrement operator is wrong, it should not return reference to *this. As you can see here: https://en.cppreference.com/w/cpp/language/operator_incdec its declaration is :
T T::operator--(int);
Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61040466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wildcard date form in JavaScript I want to check if string satisfies condition (First, second, fourth, fifth, seventh, eighth, ninth and tenth character can be any number. Third and sixth must be forward slash.) Like date format. I need this:
if (date !== SOMETHING ){
alert("Wrong input!");}
A: You can try to match the date with a regular expression (this one ensures that it matches the format (DD/MM/YYYY or MM/DD/YYYY):
if (date.match( /^\d{2}\/\d{2}\/\d{4}$/ )) {
alert("Valid input!");
} else {
alert("Wrong input!");
}
This regular expression /^\d{2}\/\d{2}\/\d{4}$/ returns true if the string matches the following pattern:
*
*2 digits
*Forward slash
*2 digits
*Forward slash
*4 digits
Here's a JS Fiddle that shows it working.
Here's another (more "Eloquent") solution (return a JavaScript Date through a function):
function findDate(string) {
var dateTime = /(\d{2})\/(\d{2})\/(\d{4})/;
var match = dateTime.exec(string);
return new Date(Number(match[3]),
Number(match[2]) - 1,
Number(match[1]));
}
alert(findDate("30-01-2003"));
Also - I'd recommend reading Regular Expressions - Eloquent JavaScript
A: If you want to validate the format and that it's a valid date, you have to check the values. That can be done with a regular expression but it's much simpler using a Date, e.g.
// Validate dd/mm/yyy date string
function isValidDMY(s) {
var b = s.split('/');
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1];
}
console.log(isValidDMY('4/4/2015')); // true
console.log(isValidDMY('29/2/2015')); // false
There really is no point in insisting on leading zeros for single digit numbers for user input dates, so the above accepts either 4/4/2015 or 04/04/2015.
Edit
If you insist on leading zeros for day and month number, you can check that too by changing the last line to:
return /^(\d\d\/){2}\d{4}$/.test(s) && d && d.getMonth() == b[1];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29462326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ERROR: "._android-support-v4.jar" in project FacebookSDK Help needed!!!! Stuck for 2 weeks on this and help needed.
I've recently imported the facebook sdk for android and its projects into my workspace. It shows up errors and the problems:
Archive for required library: '/home/Documents/facebook-android-sdk-3.0.2.b/facebook/libs/._android-support-v4.jar' in project 'FacebookSDK' cannot be read or is not a valid ZIP file
And the samples get errors along the line of:
The container 'Android Dependencies' references non existing library '/home/Documents/facebook-android-sdk-3.0.2.b/facebook/bin/facebooksdk.jar'
The things I have done following the other discussions without any success are
cleaned project
set the Facebook SDK as library
looked at the build path section and added external jar consisting of facebook/libs
imported fb sdk like 20 times and into different folders.
made sure my java compiler was 1.6
HELP would be very greatly appreciated!!!!
A: Take the lastest version of android-support-v4.jar (in your sdk environement : sdk/extras/android/support/v4/android-support-v4.jar) and replace in your project and library project do not create conflict.
A: The steps to importing a library are:
*
*Download the library
*Place the library in the libs folder of the project.
*Build the project
*Do Not attempt to import the library using some import wizard.
I suspect either your download was corrupted, and you need to do it again, or you put the file into the wrong directly.
A: I think your problem is that the android.support.v4 versions are different, take the one from your project and replace the one in the Facebook sdk lib folder, it should dismiss the clash.
A: As per your question, I think you are not able to compile once you add the SDK to your project. Do you get an error saying unable to run as library?
If so that means you have included this as library and create your project as a library to be used further. It is a common mistake that I have seen many people do when they try to import a library to use and tick mark the checkbox is Library. This actually means you want this project to be treated as a library for future use. Just try to add the SDK and do not tick mark the checkbox and this project will run fine.
Many forums will just tell you to tick that checkbox and you will be stuck on this error for long time.
For any .jar file related issues you have to make the .jars files compatible as there hashing a problem and the two jars are not compatible with each other (a version issue).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13841432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How come the linq syntax work over the IQueryable interface in Rx Framework I've started looking over the reactive framework. Very nice stuff. But while looking at code samples it got me confused. The linq syntax works with the IQueryable. I thought that linq only works with IEnumerable. On what does the C# compiler bases it's linq to extension methods conversions? Does it require a set of methods with a specific interface?
A: Not quite. It's just a syntactic translation. For example, the compiler will translate this:
var query = from item in source
select item.Property;
into
var query = source.Select(item => item.Property);
It does that without knowing anything about the Select method. It just does the translation, then tries to compile the translated code.
All the translations are carefully documented in section 7.16 of the C# 4 spec (and the equivalent for earlier editions, of course).
In the case of Rx, it calls the extensions on IObservable<T> and IQbservable<T>. In the case of Parallel Extensions, it calls the extension methods on ParallelQuery<T>.
You can do some mad stuff with it - I have a blog post which gives a few examples. Here's another odd one:
using System;
using System.Linq;
namespace CornerCases
{
class WeirdQueryExpression
{
static WeirdQueryExpression Where(Func<int, int> projection)
{
return new WeirdQueryExpression { Select = ignored => "result!" };
}
Func<Func<string, bool>, string> Select { get; set; }
static void Main()
{
string query = from x in WeirdQueryExpression
where x * 3
select x.Length > 10;
Console.WriteLine(query);
}
}
}
The query translates to:
WeirdQueryExpression.Where(x => x * 3)
.Select(x => x.Length > 10);
... which is a call to a static method, which returns a WeirdQueryExpression, followed by accessing the Where property which returns a Func<Func<string, bool>, string>. We then call that delegate (passing in another delegate) and assign the result to query.
Funky, huh?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3088019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redact parts of an audio file using python (FFMPEG) I have a use case where I need to dynamically redact parts of an audio file using python. For example sometimes I may have to remove between timestamps 10 to 15 and other times between 5 to 7, 12 to 16 and 21 to 26 . I have tried looking at FFMPEG and think it may be possible with filters or chaining filters, but I am having trouble figuring out which ones to use and the combination. Any help or pointers will be highly appreciated. TIA!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63472388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Uploading and accessing files in Phoenix and storing them locally I want to be able to upload files, and in particular images, and store them locally. I'm aware of plug Plug.Static, but isn't it for static assets? Whereas uploaded files aren't static.
1) Also, I already have this in my application generated automatically:
# lib/my_app/endpoint.ex
plug Plug.Static,
at: "/", from: :my_app, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
Indeed, it's for static assets. How should I go about uploaded files? I want to store them in a different directory. Not necessarily outside of my project, but anywhere where it won't be compiled in the production beam file by default.
2) Given an uploaded file name, I want to be able to get its full url/path from a) controller b) view. How can I do that?
A: Check out the docs for file uploads. Phoenix uses Plug.Upload. Your files will be uploaded to a temporary directory and only exists during the lifecycle of the upload request. You can choose to do whatever you want with that file. If you want to store it somewhere on your server, you might want to keep track of what files you upload and where they are stored on your server in your database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38922635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to return a variable from a function as a global variable on click I would like to return "a=5" variable from the function on click as a global variable and then alert it. Can you please only reply with javascript codes and not jquery. I am trying to understand javascript.
function startBtn() {
var a = 5;
return a;
}
document.getElementsByName("submit-button")[0].addEventListener("click", startBtn);
// var test = startBtn(); //Does not work as I want. I want to pass this as a global variable.
// alert(test); //Does not work as I want
<input class="submit-btn" type="submit" name="submit-button" value="Start">
Thanks.
A: Get the value of the function when the user click on the button and alert inside clickListener.
As per your code snippet you are getting the value of the startBtn function outside of the click listener and alerting it also give 5, but you need to get the value and alert that value only after the user click on the button not when JS is compiled.
function startBtn() {
var a = 5;
return a;
}
document.getElementsByName("submit-button")[0].addEventListener("click", () => {
var test = startBtn();
alert(test);
});
var test = startBtn();
alert(test);
<input class="submit-btn" type="submit" name="submit-button" value="Start">
A: if you want to alert a from js function just insert the alert function on your startBtn function like this
function startBtn() {
var a = 5;
alert(a);
}
document.getElementsByName("submit-button")[0].addEventListener("click", startBtn);
// var test = startBtn(); //Does not work as I want
// alert(test); //Does not work as I want
<input class="submit-btn" type="submit" name="submit-button" value="Start">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66996562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to change User Agent? Im making an app for Mac and the app is basically a WebView inside the viewController which can be accessed from the menu bar.
Its working fine, the webpages load from the menu bar. But the WebView loads the full page as if it was opened from Safari. How do I change this so that it opens the webpage as for example an iPhone?
A: As per the class reference:
WebView has a property named customUserAgent. Just set it to what you want.
var customUserAgent: String!
If you want to manipulate the application name inside that string use the applicationNameForUserAgent property:
var applicationNameForUserAgent: String!
To pretend coming from Mobile Safari on iOS 9.3,
yourWebViewInstance.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13E188a Safari/601.1"
should work.
A: You can use
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Custom-Agent"])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39271245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why can't i use Type variable as a Type parameter to a generic class
class Cage<T>{
Cage();
}
class Chicken{
Chicken();
}
main() {
Type t= Chicken;
var cage = new Cage<t>(); //Does not work
var cage2 = new Cage<Chicken>(); //Works
}
Why cant I use Type variable as a Type parameter to a generic class?
here is a part of my problem, easy to solve by sending the type variable to the constructor but makes it ugly
class Injector{
Map<Symbol, DependencyMapping> _dependencyMappings;
//problem comes here
RegisterDependency(Type type,[Symbol name=#unnamed]){
//...
var mapping = new DependencyMapping<type>(name);
}
}
class DependencyMapping<T>{
//...
}
abstract class DependencyProvider<T> {
//...
}
class ValueProvider<T> implements DependencyProvider {
//...
}
class ClassProvider<T> implements DependencyProvider {
//...
}
class SingletonProvider<T> implements DependencyProvider {
//...
}
A: This is not possible in Dart as it stands today.
Parameterized types (things like List<int>) can take literal types (e.g., List<Chicken>) or type parameters (e.g., List<T> where T is declared as a type parameter in a generic, as it in Cage) as arguments. They cannot take arbitrary expressions, even if those are of type Type.
A variable such as t might hold a Type (as in your example) but in general it is really hard to be sure of that. It could just as easily hold a non-type value such as the number 3, because Dart's type system does not guarantee that something with static type Type really is a Type.
If we let these through, the system would be thoroughly corrupted. We could add runtime checks for that, but that would hit performance.
A: This is not (yet) supported.
There was some explanation somewhere, I'll have to look it up....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28060094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to specify range of port while creating httpserver? I am trying to create an http server using JDK's com.sun.net.httpserver. I am able to run the server with certain endpoints successfully. And it return some random ephemeral port ranging from 0 to 65536.
HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
I was going through the documentation but I couldn't see a way to specify some range instead of specific port.
Is there any way passing range can be achieved?
One hack to the solution is try for all ports in range and see whichever works as specified in the solution - How to find an available port?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75083265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: change - to + in Common Lisp Is there way to change - (minus) function to + (plus) function?
My homework is to implement sin calculation on Macluaurin series
sin(x) = x-(x^3/3!)+(x^5/5!) -(x^7/7!)+(x^9/9!)-...
Each article has different sign. This is my Lisp code
(defun sinMac (x series n plusminus)
(cond ((= series 0) 0)
(t (funcall plusminus
(/ (power x n) (factorial n))
(sinMac x (- series 1) (+ n 2) plusminus)))))
Is it possible to change plusminus to exchange sign? if I get '+ function send '- to next recursive call. From that call (got '-) I call '+ and so on...
A: You could do it with a circular list. Like so:
(defun sin-mac (x series n plus-minus)
(cond ((zerop series) 0)
(t (funcall (car plus-minus)
(/ (power x n) (factorial n))
(sin-mac x (1- series) (+ n 2) (cdr plus-minus))))))
(sin-mac x series 1 '#0=(+ - . #0#))
Or even better, wrap up the initial arguments using labels:
(defun sin-mac (x series)
(labels ((recur (series n plus-minus)
(cond ((zerop series) 0)
(t (funcall (car plus-minus)
(/ (power x n) (factorial n))
(recur (1- series) (+ n 2) (cdr plus-minus)))))))
(recur series 1 '#0=(+ - . #0#))))
A: If the function is a symbol, this is easy:
(defun next-function (function)
(ecase function
(+ '-)
(- '+)))
(defun sinMac (x series n plusminus)
(cond ((= series 0) 0)
(t (funcall plusminus
(/ (power x n) (factorial n))
(sinMac x
(- series 1)
(+ n 2)
(next-function plusminus))))))
A: I would not swap the function but just the sign. Using a loop for this also seems clearer to me (and is most likely more efficient, although there is still plenty of opportunity for optimization):
(defun maclaurin-sinus (x n)
"Calculates the sinus of x by the Maclaurin series of n elements."
(loop :for i :below n
:for sign := 1 :then (- sign)
:sum (let ((f (1+ (* 2 i))))
(* sign
(/ (expt x f)
(factorial f))))))
A few optimizations make this about 10 times faster (tested with n = 5):
(defun maclaurin-sinus-optimized (x n)
"Calculates the sinus of x by the Maclaurin series of n elements."
(declare (integer n))
(loop :repeat n
:for j :from 0 :by 2
:for k :from 1 :by 2
:for sign := 1 :then (- sign)
:for e := x :then (* e x x)
:for f := 1 :then (* f j k)
:sum (/ e f sign)))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26823599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Translate API Key json format I am trying to use the Google translate API from a local machine (not google cloud).
Prior to running the following I have run
export GOOGLE_APPLICATION_CREDENTIALS=API.json
Where the API.json is:
{ "key":"the_key_code" }
After running this code:
import google.auth
from google.cloud import translate
_, PROJECT_ID = google.auth.default()
TRANSLATE = translate.TranslationServiceClient()
I got the following error:
DefaultCredentialsError: The file API_.json does not have a valid type. Type is None, expected one of ('authorized_user', 'service_account', 'external_account')
Then I added type: service_account to the json and got this error:
DefaultCredentialsError: ('Failed to load service account credentials from API.json', ValueError('Service account info was not in the expected format, missing fields client_email, token_uri.'))
I cannot find any documentation as to what the format for the API key json file should be and there is no way to export a json file from google cloud platform, only the ability to copy the key.
Any ideas on how to get translate to work from a local machine?
A: I had to create a credential file for Analytics API too and faced the same lack of informations.
I had no choice and used the new google Cloud Dashboard, you have to create an application, select the API you want, then Google provide you a valid credentials file.
My file looked like this :
{
"type": "service_account",
"project_id": "***",
"private_key_id": "***",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANB***xmw0Fcs=\n-----END PRIVATE KEY-----\n",
"client_email": "***",
"client_id": "***",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "***"
}
That's why i'm pretty sure you have to do the same with translate API, first declaration "type": "service_account", match with the error you get.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69324034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Incompatible row dimensions The task is to encode all the text and categorical features and again combine them to form the data matrix but am getting the error incompatible row dimensions.
My work so far:
Encode categorical feature using Label Encoder
from sklearn.preprocessing import LabelEncoder
enc = LabelEncoder()
enc.fit(x_train[' Round'])
round_train_le = enc.transform(x_train[' Round'])
round_test_le = enc.transform(x_test[' Round'])
Encode Text feature category using TfIdfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer1 = TfidfVectorizer(max_features=500)
vectorizer1.fit(x_train[' Category'])
category_train_enc = vectorizer1.transform(x_train[' Category'])
category_test_enc = vectorizer1.transform(x_test[' Category'])
print(category_train_enc.shape)
print(category_test_enc.shape)
Encode Text feature question using TfIdfVectorizer
vectorizer2 = TfidfVectorizer(max_features=5000)
vectorizer2.fit(x_train[' Question'])
question_train_enc = vectorizer2.transform(x_train[' Question'])
question_test_enc = vectorizer2.transform(x_test[' Question'])
print(question_train_enc.shape)
print(question_test_enc.shape)
Encode Text feature answer using TfIdfVectorizer
vectorizer3 = TfidfVectorizer(max_features=1000)
vectorizer3.fit(x_train[' Answer'])
answer_train_enc = vectorizer3.transform(x_train[' Answer'])
answer_test_enc = vectorizer3.transform(x_test[' Answer'])
print(answer_train_enc.shape)
print(answer_test_enc.shape)
Combining the encoded features:
from scipy.sparse import hstack
x_tr = hstack((round_train_le, category_train_enc, question_train_enc, answer_train_enc))
x_te = hstack((round_test_le, category_test_enc, question_test_enc, answer_test_enc))
print("Final Data matrix")
print(x_tr.shape, y_train.shape)
print(x_te.shape, y_test.shape)
And then am getting the following error:
ValueError Traceback (most recent call last)
<ipython-input-60-12e131ba4df4> in <module>
1 # merge two sparse matrices: https://stackoverflow.com/a/19710648/4084039
2 from scipy.sparse import hstack
----> 3 x_tr = hstack((round_train_le, category_train_enc, question_train_enc, answer_train_enc))
4 x_te = hstack((round_test_le, category_test_enc, question_test_enc, answer_test_enc))
5
~\anaconda3\lib\site-packages\scipy\sparse\construct.py in hstack(blocks, format, dtype)
463
464 """
--> 465 return bmat([blocks], format=format, dtype=dtype)
466
467
~\anaconda3\lib\site-packages\scipy\sparse\construct.py in bmat(blocks, format, dtype)
584 exp=brow_lengths[i],
585 got=A.shape[0]))
--> 586 raise ValueError(msg)
587
588 if bcol_lengths[j] == 0:
ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 145341, expected 1.
Please suggest what change i need to make in the code to resolve the error.
A: When using scipy.sparse.hstack() you have to ensure that all the elements you try to stack have the same 0's dimension, i.e., same number of rows. See the following example:
import numpy as np
from scipy.sparse import hstack
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 2, 3, 5])
c = hstack([a, b])
print(c)
Output:
(0, 0) 1
(0, 1) 2
(0, 2) 3
(0, 3) 4
(0, 4) 5
(0, 5) 1
(0, 6) 2
(0, 7) 3
(0, 8) 5
On the other hand when the number of rows does not match - it results in the error you are getting:
import numpy as np
from scipy.sparse import hstack
a = np.array([1, 2, 3, 4, 5, 6])
b = np.array([[1, 2, 3], [4, 5, 6]])
c = hstack([a, b])
print(c)
Output:
ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 1, expected 2.
So you should check that all your items are of the same number of rows to join them row-wise
Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66625028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I check if a window has WS_VISIBLE to set? (or if is visible) How can I do it? It's an external window, not from my program. Thanks
A: One nuance to be aware of. IsWindowVisible will return the true visibility state of the window, but that includes the visibility of all parent windows as well.
If you need to check the WS_VISIBLE flag for a specific window you can do GetWindowLong(hWnd, GWL_STYLE) and test for WS_VISIBLE.
... It sounds like you don't need to do this for your case, but adding this for future reference in case others run across this question.
A: Do you have an HWND to the window? If not, then you will need to obtain the window handle somehow, for example through FindWindow() (or FindWindowEx()).
Once you have the HWND to the window, call IsWindowVisible().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1061246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: cmd escaped after SoapUI test is finished I am calling SaopUI testrunnet from cmd file.
The problem is that lines after command for testrunner are not executed
I have unchecked "Fail testcase on error" checkbox in soap ui without any help.
Anyway, i have this issue regardless of test was successful or not
this is my command
%SoapUIPath%\testrunner.bat-sTestSuite %projectPath% -I -r -P var2=%var2% -P var1=%var1%
echo ###Test finished###
Echo "Test finished" will not be executed
A: If one batch file directly invokes another one, the execution flow is transfered to the called file, and not returned to the caller.
To retrieve the execution flow after the called file has ended, we need to use the call command
call "%SoapUIPath%\testrunner.bat" ....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41832687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ajax Caching and Correct Format used? I have a JavaScript event that is called like so:
function addEvent(date, resId) {
$("#appPlaceholder").load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId,
function () {
$('#eventModal').modal('show');
});
};
However am I using the correct standards to format/pass my variables?
.load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId) ??
Also I need to make sure the load does not cache, how can I prevent this.
Any Examples much appreciated.
A: If you are not sure about URL encoding, use encodeURIComponent:
var date = encodeURIComponent(date.format());
var id = encodeURIComponent(resId);
To prevent from caching, add to the end some random value. For example:
'&v=' + Math.random()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43304559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to call a function within qx? Here's a bit of Perl code that does what I want:
my $value = get_value();
my $result = qx(some-shell-command $value);
sub get_value {
...
return ...
}
Is it possible to achieve the same effect without using $value? Something like
my $result = qx (some-shell-command . ' '. get_value());
I know why the second approach doesn't work, it's just to demonstrate the idea.
A: my $result = qx(some-shell-command @{[ get_value() ]});
# or dereferencing single scalar value
# (last one from get_value if it returns more than one)
my $result = qx(some-shell-command ${ \get_value() });
but I would rather use your first option.
Explanation: perl arrays interpolate inside "", qx(), etc.
Above is array reference [] holding result of function, being dereferenced by @{}, and interpolated inside qx().
A: Backticks and qx are equivalent to the builtin readpipe function, so you could explicitly use that:
$result = readpipe("some-shell-command " . get_value());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24285646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Application defined or object defined error - Excel VBA the following code gives me an Application defined or object defined error on the bold line. I set the range; however, apparently excel can't read it. I am not sure why that error appears. Any help is much appreciated! Thanks.
Public Sub specialattention()
'Loop to check whether issue needs spcial attention
Dim n As Variant
Dim nend As Range
Dim nrng As Range
Dim nnow As Date
Dim ninterval As Integer
ninterval = Sheets("Ranges").Range("AB3").Value
nnow = Sheets("Issues Database").Range("N5").Value
Set nend = Sheets("Issues Database").Range("M1048576").End(xlUp)
Set nrng = Sheets("Issues Database").Range("M6", nend)
For Each n In nrng
If n.Value = "1" And nnow - n.Offset(0, 1).Value >= ninterval Then
n.Offset(0, 2).Value = "1"
Else
n.Offset(0, 2).Value = "0"
End If
'Color Cells that need special attention
If n.Offset(0, 2).Value = "1" Then
Dim xrng1 As Range
Dim xrng2 As Range
Set xrng1 = n.Offset(0, -11)
Set xrng2 = n.Offset(0, -1)
**Sheets("Issues Database").Range(xrng1, xrng2).Interior.ColorIndex = 19**
Else
Dim xrng3 As Range
Dim xrng4 As Range
Set xrng3 = n.Offset(0, -11)
Set xrng4 = n.Offset(0, -1)
**Sheets("Issues Database").Range(xrng2, xrng3).Interior.ColorIndex = 2**
End If
Next
End Sub
A: As long as the ranges passed to .Range are valid ranges, your code should work.
Based upon your code, the first instance:
Sheets("Issues Database").Range(xrng1, xrng2).Interior.ColorIndex = 19
should be fine.
However, your second instance:
Sheets("Issues Database").Range(xrng2, xrng3).Interior.ColorIndex = 2 is referencing ranges that are not in scope since you are reusing xrng2 which is defined in a different logic path.
Presumable updating your second problem line to this:
Sheets("Issues Database").Range(xrng3, xrng4).Interior.ColorIndex = 2 will give you your expected behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13829094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS Background Images Not Appearing on Mobile (iPhone) I have a header and several divs with background images that are not appearing on my mobile device (iPhone 5). Here is an example:
CSS:
#title_img {
background: url("title.png") no-repeat scroll center top / 100% auto transparent;
height: 125px;
}
The site I am working on is responsive, so at reduced window sizes, I reduce the size of height of the header:
#title_img {
height: 80px;
}
HTML:
<header id="title_img" role="banner"></header>
A blank space where the image should be.
I also have several divs that use the similar CSS for displaying background images that are not appearing on the device. The images are all in the same directory as the CSS file. There is one image that is called through an tag in the HTML and it displays fine on iPhone. Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15421984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is the preprocessor macro "#define TRUE FALSE'" valid? Is the following define statement valid in C?
#define TRUE FALSE
A: Since we should expect TRUE is already defined when FALSE is defined too.
So in this case this would be a redefinition and be invalid.
If you stay intern the #define TRUE FALSE would be valid to the standard, but would be invalid according to all logics I could imagine.
But a way i have already often seen was :
#define FALSE 0
#define TRUE !FALSE
A: You have to remember that preprocessor macros are simply substituted. If you do e.g.
#define TRUE FALSE
then the processor simply replaces all places where it finds TRUE will be replaced by whatever FALSE is defined to.
So indeed it's a good definition. And yes it will most likely change the program workflow, possibly in very unexpected ways that may even cause undefined behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18894206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: discord.js write and read JSON file I have a question. How can I let my DiscordBot write and read a JSON file? I have already programmed something but have only error. Can someone help me out? I would appreciate any help.
const Discord = require("discord.js")
const botconfig = require("../botconfig.json");
const colours = require("../colours.json");
const superagent = require("superagent");
const { report } = require("superagent");
const usedCommand = new Set();
module.exports.run = async(bot, message, args) => {
message.delete();
if (usedCommand.has(message.author.id)) {
message.reply("du kannst diesen Command erst in 15 Sekunden wieder verwenden.").then(msg => msg.delete({ timeout: "10000" }));
} else {
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = args.slice(1).join(" ");
if (!reason) message.reply("Bitte gebe einen Beweis in Form von einem Link (Video: Youtube, Bild: prnt.sc) an!")
var fs = require("fs");
var sampleObject = {
username: member,
proof: reason
};
fs.writeFile('../rpp.json', JSON.stringify(sampleObject, null, 4), (err) => {
if (err) {
console.error(err);
return;
};
console.log("File has been created");
});
usedCommand.add(message.author.id);
setTimeout(() => {
usedCommand.delete(message.author.id);
}, 15000);
}
}
module.exports.config = {
name: "rpp",
description: "Bans a user from the guild!",
usage: "+ban",
accessableby: "Members",
aliases: ["proofwrite"]
}
I want my Discord bot to enter the tagged user and a reason into the JSON file using the "writerrp" command. After that I want the bot to read the data of a user with the "readrrp" command.
A: here is an example of reading from a .json file.
Set up the json file correctly, using the right syntax.
{
"token": "<a token goes here>" //in your local json file - called config.json in this case
}
client.login(config.token) //reads from the config.json file as an obj, which calls the token param
When reading from the json file, you need the fs package
const fs = require('fs');
//assuming your bot has args
let reason = args.slice(1,2) //removes the command and the @
let user = message.mentions.users.first()
//create a new obj
var obj = {
table: []
};
//add some data to it e.g.
obj.table.push({reason: `${reason}`, user:`${user.username}`});
//convert it to json using the json#stringify() method
var json = JSON.stringify(obj);
//write to the json file
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
//if you want to append, do this:
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
credit for the above goes to @kailniris here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65772447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to combine subtotal and sumif with a range of criteria I'm trying to create a formula to combine a SUMIF (using a range of criteria) and a subtotal.
The SUMIF statement:
=SUMPRODUCT(SUMIF(E:E,O2:O21,G:G))
And where I've gotten on making that SUMIF subtotal:
=SUMPRODUCT(SUBTOTAL(9,OFFSET(G2,ROW(G2:G5000)-ROW(G2),0)),(E2:E5000=O2:O21)+0)
That last statement returns an #N/A error. I'd appreciate any input y'all can provide.
Thank you.
Example:
Order | Date | Mach | Rem
-------|-------|-------|-------
A |01/20 | 01 | 1200
B |01/11 | 02 | 400
C |01/21 | 01 | 420
D |01/28 | 04 | 1180
E |01/20 | 01 | 1200
F |01/11 | 04 | 400
G |01/21 | 03 | 420
H |01/28 | 04 | 1180
No t sure I got the table right, so here's an image of what I see.
What I'm trying to do is filter based on the date - say, all orders that occur before 1/21 - and then give the amount remaining in a list of machines.
So, if I wanted the total from Machine 1 and 4, the output from that table (with the date filter on) would be 2800, summing order A, D, E, and F. With the filter off it'd be 5580.
A: Try this formula:
=SUMPRODUCT(NOT(ISERROR(MATCH($C:$C;J:J;0)))*SUBTOTAL(103;OFFSET(C1;ROW(C:C)-MIN(ROW(C:C));0));$D:$D)
Excel structure:
After applying a filter:
You can also include date criteria already in the formula:
=SUMPRODUCT(NOT(ISERROR(MATCH($C:$C;J:J;0)))*($B:$B<$L$1);$D:$D)
Where L1 is date criteria.
But, of course, if you need filter usage, use the first solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41595676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I mimic the redis MONITOR command in a python script using redis-py? Unfortunately, the redis-py library does not seem to have a Monitor routine. I would like to read all of the commands received by the redis server, filter them, and then log the ones I am interested in. Does anybody have an idea of how to do this?
A: Here is some minimal code to implement the monitor code in python.
Note :
*
*I adapted this from the PubSub class in redis-py. See client.py
*This does not parse the response, but that should be simple enough
*Doesn't do any sort of error handling
import redis
class Monitor():
def __init__(self, connection_pool):
self.connection_pool = connection_pool
self.connection = None
def __del__(self):
try:
self.reset()
except:
pass
def reset(self):
if self.connection:
self.connection_pool.release(self.connection)
self.connection = None
def monitor(self):
if self.connection is None:
self.connection = self.connection_pool.get_connection(
'monitor', None)
self.connection.send_command("monitor")
return self.listen()
def parse_response(self):
return self.connection.read_response()
def listen(self):
while True:
yield self.parse_response()
if __name__ == '__main__':
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
monitor = Monitor(pool)
commands = monitor.monitor()
for c in commands :
print(c)
A: Now, the redis library already included the monitor support itself.
https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L3422
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10458146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Spring4 without XML - web.xml - translate to Java I do have couple of JNDI resources in my web.xml
This is for reading a external property file and path depends on environment.
<resource-ref id="resourceRef">
<res-ref-name>config/file</res-ref-name>
<res-type>java.lang.String</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
This is for JNDI JDBC DB definition
<resource-ref id="MyDatabase">
<description></description>
<res-ref-name>jdbc/MyDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
and this for old ejb (EJB2.x)
<ejb-ref id="service">
<description />
<ejb-ref-name>ejb/AgencyService</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>ejb.Home</home>
<remote>ejb.Service</remote>
</ejb-ref>
How can translate these resources to Java (Servlet 3.x)?
An existing application is migrating from servlet 2.5 and EJB 2.x to Servlet3, Rest and EJB3. My new application uses Spring4 (MVC, Security etc) and OpenJPA 2.1.x. Our design goal is not to use "xml" (no web.xml, SpringContext.xml etc).
I created Java class that extends AbstractAnnotationConfigDispatcherServletInitializer
that would be equivalent to Web.xml.
How can I migrate resource-ref and ejb-ref to Java class??
Much appreciated your help!
Note :- edited
A: Basically Spring and JEE stack are "competing" with each other. From what you've stated: EJB3 + JPA clearly belong to JEE stack, on the other hand SpringMVC is obviously from Spring universe + spring boot is obviously in a Spring camp.
Now, web.xml is kind of a bootstrap point for regular spring application (excluding spring boot of course). So, in general you should specify a web listener that will load up the spring. When you've tagged a spring boot in the question everything has mixed up. In two words, spring boot indeed alows to configure everything with annotation but it still "assumes" you're using spring under the hood.
Regarding the resources,
If you are working with DAO layer, you should define beans for those, but bottom line they will be managed by spring then.
But in this case there is no need for EJB. Of course you can still use JPA out of spring DAO (people tend to use Hibernate directly IMO this day if they really need ORM, and Hibernate implements JPA these days) if you wish, but in any case its again will be used by spring.
On the other hand if you need a JEE stack I doubt spring boot can really fit you.
JEE stack is a kind of "all-in-one" bundle which is supported by various application servers, and spring from this point of view is "take parts and combine by yourself" solution. So for spring project you can use tomcat/jetty which are not by any means fully compliant JEE servers. BTW this is exactly what spring boot does.
So I think for the sake of the project you should decide in which camp do you want to be, JEE or Spring. Both technologies look appealing these days, each of them has its benefits/drawbacks, but bottom line it boils down to:
*
*Spring is more flexible and innovative, you get changes faster
*Spring is more complicated to bootstrap (although if there are seasoned developers familiar with spring, it should not be an issue)
*JEE is standardized
A: Use Spring Boot - no need for xml there.
Spring Boot embeds Tomcat (or optionally Jetty), and so does not support EJB.
I'd rewrite the EJB' 's functionality as a "plain old Java" class, using spring features where needed.
For the external config file, Spring has several ways of providing configuration options at runtime / external to the deployment, so no need for JNDI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36299605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testcafe test fails because "Failed to find a DNS-record for the resource" with VPN, but without VPN it works The test fails when I'm connected through the VPN but without it works fine. It performs a click to this URL:
https://www.google.com/search?q=let+me+google+that+for+you
I tried with the --proxy-bypass setting but I suppose I'm not doing it right, any guidance on how it should look like?
A: A VPN should not affect your tests. Judging by the symptoms, it looks like you are using a proxy, not a VPN. If it's true, the proxy server address should be specified using the --proxy option as described here mentioned below.
--proxy <host>
Specifies the proxy server used in your local network to access the Internet.
testcafe chrome my-tests/**/*.js --proxy proxy.corp.mycompany.com
testcafe chrome my-tests/**/*.js --proxy 172.0.10.10:8080
You can also specify authentication credentials with the proxy host.
testcafe chrome my-tests/**/*.js --proxy username:password@proxy.mycorp.com
As for the --proxy-bypass option, it has the opposite meaning. You can use it to specify resources that are not proxied, for example, the ones that are hosted inside of your local network.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58413363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: wso2is in distributed architecture i am a beginner in wso2 and working on a academic project that consists of deploying wso2 in a distributed architecture. I've been looking in wso2 documentation but I couldn't find something that can help me in this project. if u have any clue, that would be very helpful.
A: I do not clearly get what you requirement is. However you can create a distributed deployment of WSO2 APIM as in [1].
There is no specific distributed deployment scenario of wso2 IS. However IS can be used in clustering as in previous answer.
Other than that, WSO2 products can be deployed by clustering. Refer this [2] such clustering patterns.
[1] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager
[2] https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager
A: You can find the clustering documentation for WSO2 IS 5.4.0 in https://docs.wso2.com/display/IS540/Setting+Up+Deployment+Pattern+1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48829384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: submit action doesnt work in Rails 4 when I submitted the form, the new data don't save in database and as a result I can not see them, but when I make a new data like welcome= Welcome.new and welcome.title="your are" by rails console they work and I can only see things that I have made in console not by application. It seems submit bottom doesnt save any data.
new.html.erb
<h1> Submite </h1>
<form action="new" method="post" class="form-horizontal" role ="form">
<div class="form-group">
<label for"kind"> kind </label>
<input type="string" id="kind" name="kind" class="form-control">
</div>
<br>
<div class="form-group">
<label for"title"> title </label>
<input type="string" id="title" name="title" class="form-control">
</div>
<br>
<div class="form-group">
<label for"text">"text </label>
<input type="text" id="text" name="text" class="form-control">
<br>
</div>
<br>
</div>
<input type="submit" value="Submit" class="btn btn-primary">
<a href="/welcomes/index">List </a>
</div>
index.html.erb
<% @welcomes.each do |welcome| %>
<li><%= welcome.title %> </li>
<% end %>
welcomes_controller
def index
@welcomes = Welcome.all
end
def new
@welcome = Welcome.new
end
def create
@welcome = Welcome.new(user_params)
if @welcome.save
flash.keep[:notice]="Successfuly created"
render :index
else
render :new
# format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
private
def user_params
params.require(:welcome).permit(:kind, :title, :text)
end
A: Your form is not submitting to the right route. Use form builder instead:
<%= form_for @welcome do |f| %>
<%= f.label :kind %>
<%= f.text_field :kind %>
<%= f.submit %>
<% end %>
This will put right route for form submission into your HTML
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26027639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to throw an error when an attribute is changed? I want to make sure an error gets thrown when an attribute of an object gets changed outside the class. Here's how I tried to do it:
class Example {
constructor(index) {
this.index = index;
Object.defineProperty(this, 'index', {
set() {
throw new AssertionError("can't set attribute");
}
});
}
}
class AssertionError extends Error {
constructor(message) {
super();
this.name = "AssertionError";
this.message = message;
}
}
let example = new Example(5);
console.log(example.index); //prints undefined instead of 5
example.index = 10; // I want to throw an AssertionError here
The error gets thrown just like I wanted, but the index value is undefined. I still want to be able to change the attribute inside of the class, but I want to prevent the attribute from changing outside of the class.
A: You redefine the property with the call to defineProperty. You should give it a getter:
Object.defineProperty(this, 'index', {
get() { return index; },
set() {
throw new AssertionError("can't set attribute");
}
});
Any given property name can only be used once; a property has to either be a plain property or a property with getter/setter functions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56527816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to convert IntPtr to int A window handle sometimes of type int and other times of type IntPtr
int example:
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
IntPtr example:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
I don't seem to be able to convert/cast from one to the other.
When I try this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0) I get an error cannot implicitly convert from uint to int
A: I think that error cannot implicitly convert from uint to int refers to = statement. The field this.ProcessID is int, but GetWindowThreadProcessId returns uint.
Try this
this.ProcessID = unchecked((int)GetWindowThreadProcessId(windowHandle.ToInt32(),0))
A: The SendMessage signature is
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
or this
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
Don't exchange int and IntPtr. They are nearly equivalent only at 32 bits (equal in size). At 64 bits an IntPtr is nearly equivalent to a long (equal in size)
The GetWindowThreadProcessId signature is
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
or
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
In this case, a ref or a out to "something" are managed references to something, so they are internally converted to IntPtr when passed to Native API. So out uint is, from the point of view of the Native API, equivalent to IntPtr.
Explanation: what is important is that the "length" of the parameters is the correct one. int and uint are equal for the called API. And a 32bit IntPtr is the same too.
Note that some types (like bool and char) have special handling by the marshaler.
You shouldn't EVER convert an int to an IntPtr. Keep it as an IntPtr and live happy. If you have to make some math operations not supported by IntPtr, use long (it's 64 bits, so until we will have Windows 128, there won't be any problem :-) ).
IntPtr p = ...
long l = (long)p;
p = (IntPtr)l;
A: I was getting "Arithmetic operation resulted in an overflow", whenever I was:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler.ToInt32() == 0) //throws Exception
instead of that:
IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler == IntPtr.Zero) //OK
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18173211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Make An Integer Null I have an update function that updates an sql server db table through a dataset. One of the fields in the table is an integer and accepts null values. So when I am populating the update function I need a way to enter a null in when the function wants an integer.
I tried to do it this way but _intDLocation = "" throws an exception
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
'NEED HELP HERE
_intDLocation = ""
End If
A: Try this:
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Nullable(Of Integer)
If Not String.IsNullOrEmpty(_dLocation) Then
_intDLocation = Integer.Parse(_dLocation)
End If
A: Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer. Now _intDLocation is no longer a normal integer. It is an instance of Nullable(Of Integer).
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer?
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
_intDLocation = Nothing
End If
Later on, if you want to check for null you can use this handy, readable syntax:
If _intDLocation.HasValue Then
DoSomething()
End If
In some cases you will need to access the value as an actual integer, not a nullable integer. For those cases, you simply access
_intDLocation.Value
Read all about Nullable here.
A: My application uses a lot of labels that start out blank (Text property), but need to be incremented as integers, so I made this handy function:
Public Shared Function Nullinator(ByVal CheckVal As String) As Integer
' Receives a string and returns an integer (zero if Null or Empty or original value)
If String.IsNullOrEmpty(CheckVal) Then
Return 0
Else
Return CheckVal
End If
End Function
This is typical example of how it would be used:
Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text)
Enjoy!
A: _intDLocation = Nothing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3628757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How to add row in DefaultTableModel under spcific index? I'm building a java application with swing component.
Now I want to create a JTable with 4 fixed row.
In detail I want a JTable(DefaultTableModel) with the last 4 row as fixed with my default value, and throught a Button I want to insert a new row upper this 4 row. There is a metohd to insert a row in a specific point?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42137968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent WebView to open links in other browsers I have a webview and I wish that if target=_blank, then do not open it in the browser, but remains open in webview.
I tried the code below:
private async void webView_LoadCompleted(object sender, NavigationEventArgs e)
{
await webView.InvokeScriptAsync("eval", new[]
{
@"(function()
{
var hyperlinks = document.getElementsByTagName('a');
for(var i = 0; i < hyperlinks.length; i++)
{
if(hyperlinks[i].getAttribute('target') != null)
{
hyperlinks[i].setAttribute('target', '_self');
}
}
})()"
});
}
But there are some websites that can remain open in the webview and there is a website that opens in a browser. How do I fix this so that all links remain open on webview?
A: Your code didn't work because the "Select" button in your image is a HTML <button> element not a <a> element. When user click this button, it calls JavaScript functions to open in new window. So your code won't work for this scenario.
For handling the new window request, I'd suggest using WebView.NewWindowRequested event. This event occurs when a user performs an action in a WebView that causes content to be opened in a new window. We can provide custom handling of the new window request and set the Handled property to true to prevent the default browser from being launched. Following is a simple sample:
private void webView_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
{
webView.Navigate(args.Uri);
args.Handled = true;
}
For more info, please see Remarks and Examples in WebView.NewWindowRequested event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39244638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Entry Point Not Found Exception I'm trying to use a C++ unmanaged dll in a C# project and I'm getting an error when trying to call a function that says that entry point cannot be found.
public class Program
{
static void Main(string[] args)
{
IntPtr testIntPtr = aaeonAPIOpen(0);
Console.WriteLine(testIntPtr.ToString());
}
[DllImport("aonAPI.dll")]
public static extern unsafe IntPtr aaeonAPIOpen(uint reserved);
}
Here is the dumpbin for the function:
5 4 00001020 ?aaeonAPIOpen@@YAPAXK@Z
I changed the dll import to [DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen")] and [DllImport("aonAPI.dll", EntryPoint="_aaeonAPIOpen")] and no luck.
A: It looks like the function you're trying to call is compiled as a C++ function and hence has it's name mangled. PInvoke does not support mangled name. You need to add an extern "C" block around the function definition to prevent name mangling
extern "C" {
void* aaeonAPIOpen(uint reserved);
}
A: Using the undname.exe utility, that symbol demangles to
void * __cdecl aaeonAPIOpen(unsigned long)
Which makes the proper declaration:
[DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen@@YAPAXK@Z",
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr aaeonAPIOpen(uint reserved);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3515270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How to hide dash between the bars in waterfall charts of Highcharts in iOS Basically I want to hide dash between the bars from waterfall chart.I am using highcharts iOS wrapper.I can only change type of dash but there is no option to hide or disable the same
A: You need to set lineWidth property to 0:
let plotOptions = HIPlotOptions()
plotOptions.waterfall = HIWaterfall()
plotOptions.waterfall.lineWidth = 0
options.plotOptions = plotOptions
API Reference: https://api.highcharts.com/ios/highcharts/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57176638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Is there a way to provide environment variables to a VSTS CI npm task? Essentially, I need a way to inject environment variables for my app since I don't want to check a .env file into my repo. I was hoping to run something like API_URL=api.example.com npm run build, but it looks like you can't prepend things before the task command.
Is there a way to do this or is there a better way to create environment variables for a node app hosted in Azure?
A: You can add some build variables to the build definition and then reference those in your build steps somewhere. For example, for your API_URL add a build variable with the same name and value. If you need the variable to be secret for any reason (passwords, etc.) just click the lock icon next to the value field.
Then add a new cmd task to your build and move it to the top to set your environment variables before you start your build. The way you reference the build variables is like this...
set API_URL=$(Build.API_URL)
In the UI it will look like this:
I added two cmd tasks to a test build just to show that it is working. The first one is used to set the environment variable and then I used the second to dump all the environment variables so I could see them. You can see in the build logs that it worked.
If you want to reference the build variables using something other than the command line you can find examples of the different ways to reference build variables here. There are also examples of how to use secret variables on that page.
EDIT:
Since you have some concerns about it not being available in your node app I tested it out in the console real quick to show that it will definitely work.
A: Using yaml config you can switch to script task and then do something like this:
- script: 'npm run'
workingDirectory: 'src'
displayName: 'npm run'
env:
{ API_URL: 'api.example.com' }
A: tehbeardedone's answer is great for the build machine, and the answer is similar for when running your app in an Azure app service, which I'm thinking is what you really need. This is for if you need your access to these .env files just previous to or after your app has started (post build).
*
*To the Azure portal we go.
*Navigate to your app service.
*Click "Configuration" under the "Settings" heading.
For each of the variables you'll need during a production run of your app you'll need to:
*Click "New application setting"
*Paste the name of the variable (exactly as it appears in your .env) into the "Name" field.
*Similarly, paste the value of the variable into the next field.
*Check the "deployment slot setting" checkbox. As nebulous as this field is, it's necessary. When I didn't do this, the app didn't have access to this variable after running the start command.
Restart your app. If you deployment when well, then your app should have access to the variables add in the manner specified above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49578709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Get first text inside a tag using beautiful soup I need to get the salary range from span tag. I tried using find().text but doesn't work as the span tag has other tags in it.
job_list = soup.find_all("div", class_="d-flex flex-column pl-sm css-1buaf54 job-search-key- 1mn3dn8 e1rrn5ka0")
for job in job_list:
salary = job.find("span", class_="job-search-key-1hbqxax e1wijj240")
print(salary)
The output I have:
₹362,870 - ₹955,252 is my desired output
A: What you actually want to do here is get the text inside the div class but not the text in the nested tags within it.
You can use soup.find with option text = True and recursive = False
Creating the data
from bs4 import BeautifulSoup
html_doc = '''<span class="job-search-key-1hbqxax elwijj240" data-test="detailsalary">
₹362,870 - ₹955,252 <span class="job-search-key- elwijj242">(Glassdoor Est.)</span> <span class="SVGInline greyInfoIcon" data-test="salaryIcon"> <svg class="SVGInline-svg greyInforcon-svg" height="16" viewbox="0 @ 16 16" width="16" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd" id="prefix__info-16-px" stroke="none" stroke-width="1">
<path d="M8 14A6 6 @ 118 2a6 6 @ 010 12zme- 1A5 5 @ 108 3a5 5 @ 880 18zm-.6-5.60.6.6 8 111.2 8v11a.6.6 @ 01-1.2 8v7.42MS 5.62.6.6 110-1.2.6.6 @ 810 1.2z" fill="#505863" id="prefix_a"></path>
</svg> </span>
<div class="d-none"></div> </span>'''
soup = BeautifulSoup(html_doc, 'html.parser')
Generating the output
soup.find(class_='job-search-key-1hbqxax elwijj240').find(text=True, recursive=False).strip()
Output
This gives us
'₹362,870 - ₹955,252'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72953840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: nested resources with optional verbs as resources in angular.js I'm having a bit of trouble figuring out how to create my angular resource properly.
.factory('Favorite', function ($resource) {
return $resource('/api/user/:id/favorites/:verb/:favid', {
id: "@_id",
favid: "@favid"
}, {
jobs: {
method: 'GET',
params: {
verb: 'jobs'
}
},
resumes: {
method: 'GET',
params: {
verb: 'resumes'
}
}
});
});
The trick is I want to provide a list function at /api/user/:id/favorites that lists all types of favorites (jobs, etc).
However each favorite type needs to have a CRUD interface for it.
So I also need to support GET/PUT/POST/DELETE for /api/user/:id/favorites/jobs/:jobid
I'm not really sure if I'm doing this right, nor do I know if I can actually do CRUD operations where the jobs and resumes are defined or how I would actually call them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24136176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook ads python sdk get_stats doesn't return "actions" field I can't get AdCampaign's get_stats() method to return the "actions" field. Snippet:
stats = list(ad_campaign.get_stats(fields=[
'impressions',
'spent',
'clicks',
'actions',
]))
print stats[0]
>>> <AdStats> {"clicks": 0, "impressions": 0, "spent": 0}
I have also tried to get the report on AdAccount, AdSet and AdGroup levels, but none of them had the "actions" field.
I'm assuming I have misconfigured my campaign, so here's a basic rundown:
*
*AdCampaign:
*
*status: "PAUSED"
*objective: "WEBSITE_CONVERSIONS"
*AdCampaign has one AdSet:
*
*bid_type: "ABSOLUTE_OCPM"
*bid_info: {'ACTIONS': 1}
*promoted_object: {'pixel_id': <valid pixel id string>}
*start_time: one month in the future
*AdSet has one AdGroup:
*
*objective: "WEBSITE_CONVERSIONS"
I also queried the AdGroup object for conversion_specs, they are set and match defaults described in the doc.
A: You don't actually have to specify any fields for the get_stats method, but the reason you're not seeing any actions is probably because you don't have any. Try it against a campaign that you know people have taken action on. :)
Evan
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28725802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C#: System.IO.DirectoryNotFoundException: 'Could not find a part of the path I am getting an error as shown in the title. I have no idea why im getting this or as to how im supposed to fix this. Visual Studio is giving me the error shown in the title on this line: var f = System.IO.File.OpenRead(fil1);
class Program {
static void Main(string[] args) {
Stopwatch sw = Stopwatch.StartNew();
string fil1 = "C:\Users\mariu\Desktop\Jobboppgave\CaseConsoleApp\Prisfile.txt";
***var f = System.IO.File.OpenRead(fil1);***
int length = (int)(new System.IO.FileInfo(fil1).Length);
A: Your path is incorrect because you didn't escape \ in it. The fastest way to do it is using @:
string fil1 = @"C:\Users\mariu\Desktop\Jobboppgave\CaseConsoleApp\Prisfile.txt";
Rebuild your project and problem will be resolved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52686917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to prevent scrolling to the right in this jsfiddle I have the following jsfiddle http://jsfiddle.net/KfPOQ/
using a web browser it is fine however when on the ebay app on iphone or ipad i have to scroll right to see the full page how do I eliminate this issue?
A: You need to have the content of the page fit within your viewport (or screen) dimensions for the given media type. You can have different stylesheets based on the media type in a link/stylesheet tag. Say, for the iphone, use media="handheld" and try to keep the content within around 600px, or whatever looks good on your mobile device.
Here is another resource from w3c.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12713794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Got parse error with Mail config headers in ZF2 I use Zend\Mail\Transport\Smtp to send an email. Below is my code.
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
public function smtpConfig($message)
{
$transport = new SmtpTransport();
$options = new SmtpOptions(array(
'name' => localhost,
//'host' => 10.92.32.81,
'port' => 25,
));
$transport->setOptions($options);
echo $transport->send($message);
}
public function sendMail($to,$from,$subject,$body)
{
$message = new Message();
$message->addTo($to)
->addFrom($from)
->setSubject($subject)
->setBody($body);
$this->smtpConfig($message);
}
I have configured smtp in local system and I'm able to receive email without any warnings/low priority errors. I delivered this code for project testing. Mail functionality is working fine in their system but in browser console following warning/error is displayed and I dont see this error in my local setup.
Parse error: syntax error, unexpected '[' in D:\applications\www-php\kiosquebo\vendor\zendframework\zend-mail\src\Headers.php on line 39
Any solution given is appreciated.
A: According to the line in the file you're getting the error, PHP is failing to parse this line:
protected $headersKeys = [];
The only issue that is possible here is that your PHP version is too old and does not work with the [] array definer.
You should update your PHP version to at least 5.4.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33562602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: should I add app.js file in gitignore for nodejs/vuejs app? I am new to vuejs. Recently I noticed that when I pull, it says conflict in app.js file. But I can't find the issue as app.js file is big.
Sould I add this file to gitignore file?
what is best practice to work with vue js?
A: I imagine you are building to a folder /dist and the app.js being conflited is the one inside of it.
You should ignore the /dist altogether. This folder is generated on the building process, meaning everyone that runs the project will update and create it.
A: Here is the default vue-cli .gitignore:
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*
Not that not anything here may be useful to put in your own .gitignore. But you should for sure have at least node_modules and /dist.
A: If you are building the Vue project by scratch then I can say the following, when building/compiling your Vue project, best practices say that you should handle your entire production ready project in a dist/ or build/ directory where your main app.js file where the conflicts you are having would occur. This directory is only reserved for deploying the app and is not saved into your code repository, hence on why you should add to the .gitignore file the directory that holds such production files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53819213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't use Twilio with python I used the code from the Twilio website to send a text message using python. I used real values, that I obtained during registration in the actual code. There aren't any XXXXXX in my program.
I removed the {{}} too. the code's still not working.
from twilio.rest import TwilioRestClient
account_sid = "{{ AC3XXXXXXXXXXXXXXXXXXXXXXXXXXXXX }}" # Your Account SID from www.twilio.com/console
auth_token = "{{ 04e4c31XXXXXXXXXXXXXXXXXXXXXXXXXX }}" # Your Auth Token from www.twilio.com/console
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(body="Hello from python. ",
to="+447XXXXXXXXXX", # Replace with your phone number
from_="+4417XXXXXXXXXXX") # Replace with your Twilio number
print(message.sid)
This is the error I'm getting. What does this mean?
Thanks!
Traceback (most recent call last):
File "C:/Users/Pawel/Desktop/Courses/Udacity/Python/send_text.py", line 10, in <module>
from_="+441753254382") # Replace with your Twilio number
File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\messages.py", line 122, in create
return self.create_instance(kwargs)
File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 365, in create_instance
data=transform_params(body))
File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 200, in request
resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
File "C:\Python27\lib\site-packages\twilio-6.3.dev0-py2.7.egg\twilio\rest\resources\base.py", line 164, in make_twilio_request
uri=resp.url, msg=message, code=code)
TwilioRestException:
[31m[49mHTTP Error[0m [37m[49mYour request was:[0m
[36m[49mPOST https://api.twilio.com/2010-04-01/Accounts/{{ AC3ea248ea5628ce024619440468334835 }}/Messages.json[0m
[37m[49mTwilio returned the following information:[0m
[34m[49m[0m
A: account_sid = "{{ account_sid }}" # Your Account SID from www.twilio.com/console
This does not mean place the value in the {{ }}. It means replace that entire string with your value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37751347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: enable button only if older than 90 days Good Day
I have a delete button which deletes entries on my database, problem is I want to disable the button and only enable it if it is older than 90 days.
I used this code and it's working but if it's not older than 90 days it still replies "successfully deleted" although it was not actually deleted and that is why I thought it would be easier to disable the delete button and only enable it if the entry is older than 90 days
please assist
Thanking you
$sql="DELETE FROM client_post WHERE id = '$id' AND date < DATE_SUB(NOW(), INTERVAL 90 DAY)";
$result=mysql_query($sql);
if($result){
echo('Entry '.$id.' successfully deleted <br>');
} else{
echo('<br>Failed to delete');
};
A: Change if statement to:
if($result && mysql_affected_rows() > 0){
Problem with your code is that you are checking if the $result is true, while $result is just an identifier of mysql_query() results. You should check also how much rows where affected by the query.
A: Can you show the rest of the code?
I guess you want to make a check if there are any entries older than 90 days, the button is enabled.
Do you have some kind of list where all entries are shown, and on each entry there is a delete button?
To answer your actual question, you'll need to supply us with more code.
A: As michal said you can use the affected rows to actually check if a row got deleted with:
if($result && mysql_affected_rows() > 0){
If you still want to disable the button tho you can use
SELECT
IF( DATEDIFF( CURRENT_DATE( ), date ) > 90, 1, 0 )
FROM
client_post
WHERE
id = $id
This will return true or false depending on the entry age. Depending on that you can show the button or not.
Also, take a look at PDO much better. MySQL api is deprecated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22603931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to calculate size of directory on FTP? How to calculate size of FTP folder? Do you know any tool or programmatic way in C#?
A: If you have FileZilla, you can use this trick:
*
*click on the folder(s) whose size you want to calculate
*click on Add files to queue
This will scan all folders and files and add them to the queue. Then look at the queue pane and below it (on the status bar) you should see a message indicating the queue size.
A: WinSCP (free GUI on Microsoft Windows):
A: If you just need the work done, then SmartFTP might help you, it also has a PHP and ASP script to get the total folder size by recursively going through all the files.
A: You can use the du command in lftp for this purpose, like this:
echo "du -hs ." | lftp example.com 2>&1
This will print the current directory's disk size incl. all subdirectories, in human-readable format (-h) and omitting output lines for subdirectories (-s). stderr output is rerouted to stdout with 2>&1 so that it is included in the output.
However, lftp is a Linux-only software, so to use it from C# under Windows you would need to install it in the integrated Windows Subsystem for Linux (WSL) or using Cygwin or MSYS2. (Thanks to the commenters for the hints!)
The lftp du command documentation is missing from its manpage, but available within the lftp shell with the help du command. For reference, I copy its output here:
lftp :~> help du
Usage: du [options] <dirs>
Summarize disk usage.
-a, --all write counts for all files, not just directories
--block-size=SIZ use SIZ-byte blocks
-b, --bytes print size in bytes
-c, --total produce a grand total
-d, --max-depth=N print the total for a directory (or file, with --all)
only if it is N or fewer levels below the command
line argument; --max-depth=0 is the same as
--summarize
-F, --files print number of files instead of sizes
-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
-H, --si likewise, but use powers of 1000 not 1024
-k, --kilobytes like --block-size=1024
-m, --megabytes like --block-size=1048576
-S, --separate-dirs do not include size of subdirectories
-s, --summarize display only a total for each argument
--exclude=PAT exclude files that match PAT
A: You could send the LIST command which should give you a list of files in the directory and some info about them (fairly certain the size is included), which you could then parse out and add up.
Depends on how you connect to the server, but if you're useing the WebRequest.Ftp class there's the ListDirectoryDetails method to do this. See here for details and here for some sample code.
Just be aware, if you want to have the total size including all subdirectories, I think you'll have to enter each subdirectory and call it recursively so it could be quite slow. It can be quite slow thought so normally I'd recommended, if possible, to have a script on the server calculate the size and return the result in some way (possibly storing it in a file you could download and read).
Edit: Or if you just mean that you'd be happy with a tool that does it for you, I think FlashFXP does it and probably other advanced FTP clients will as well. Or if it's a unix server I have a vague memory that you could just login and type ls -laR or something to get a recursive directory listing.
A: I use the FTPS library from Alex Pilotti with C# to execute some FTP commands in a few production environments. The library works well, but you have to recursively get a list of files in the directory and add their sizes together to get the result. This can be a bit time consuming on some of our larger servers (sometimes 1-2 min) with complex file structures.
Anyway, this is the method I use with his library:
/// <summary>
/// <para>This will get the size for a directory</para>
/// <para>Can be lengthy to complete on complex folder structures</para>
/// </summary>
/// <param name="pathToDirectory">The path to the remote directory</param>
public ulong GetDirectorySize(string pathToDirectory)
{
try
{
var client = Settings.Variables.FtpClient;
ulong size = 0;
if (!IsConnected)
return 0;
var dirList = client.GetDirectoryList(pathToDirectory);
foreach (var item in dirList)
{
if (item.IsDirectory)
size += GetDirectorySize(string.Format("{0}/{1}", pathToDirectory, item.Name));
else
size += item.Size;
}
return size;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return 0;
}
A: Simplest and Efficient way to Get FTP Directory Size with it's all Contents recursively.
var size = FtpHelper.GetFtpDirectorySize("ftpURL", "userName",
"password");
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
public static class FtpHelper
{
public static long GetFtpDirectorySize(Uri requestUri, NetworkCredential networkCredential, bool recursive = true)
{
//Get files/directories contained in CURRENT directory.
var directoryContents = GetFtpDirectoryContents(requestUri, networkCredential);
long ftpDirectorySize = default(long); //Set initial value of the size to default: 0
var subDirectoriesList = new List<Uri>(); //Create empty list to fill it later with new founded directories.
//Loop on every file/directory founded in CURRENT directory.
foreach (var item in directoryContents)
{
//Combine item path with CURRENT directory path.
var itemUri = new Uri(Path.Combine(requestUri.AbsoluteUri + "\\", item));
var fileSize = GetFtpFileSize(itemUri, networkCredential); //Get item file size.
if (fileSize == default(long)) //This means it has no size so it's a directory and NOT a file.
subDirectoriesList.Add(itemUri); //Add this item Uri to subDirectories to get it's size later.
else //This means it has size so it's a file.
Interlocked.Add(ref ftpDirectorySize, fileSize); //Add file size to overall directory size.
}
if (recursive) //If recursive true: it'll get size of subDirectories files.
//Get size of selected directory and add it to overall directory size.
Parallel.ForEach(subDirectoriesList, (subDirectory) => //Loop on every directory
Interlocked.Add(ref ftpDirectorySize, GetFtpDirectorySize(subDirectory, networkCredential, recursive)));
return ftpDirectorySize; //returns overall directory size.
}
public static long GetFtpDirectorySize(string requestUriString, string userName, string password, bool recursive = true)
{
//Initialize Uri/NetworkCredential objects and call the other method to centralize the code
return GetFtpDirectorySize(new Uri(requestUriString), GetNetworkCredential(userName, password), recursive);
}
public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential)
{
//Create ftpWebRequest object with given options to get the File Size.
var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize);
try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size.
catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later.
}
public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential)
{
var directoryContents = new List<string>(); //Create empty list to fill it later.
//Create ftpWebRequest object with given options to get the Directory Contents.
var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory);
try
{
using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response.
using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream.
{
var line = string.Empty; //Initial default value for line
while (!string.IsNullOrEmpty(line = streamReader.ReadLine())) //Read current line of Stream.
directoryContents.Add(line); //Add current line to Directory Contentss List.
}
}
catch (Exception) { throw; } //Do nothing incase of Exception occurred.
return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories.
}
public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
{
var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.
if (!string.IsNullOrEmpty(method))
ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
return ftpWebRequest; //Return the configured FtpWebRequest.
}
public static NetworkCredential GetNetworkCredential(string userName, string password)
{
//Create and Return NetworkCredential object with given UserName and Password.
return new NetworkCredential(userName, password);
}
}
A: As the answer by @FranckDernoncourt shows, if you want a GUI tool, you can use WinSCP GUI. Particularly its folder properties dialog.
If you need a code, you can use WinSCP too. Particularly with WinSCP .NET assembly and its Session.EnumerateRemoteFiles method it is easy to implement in many languages, including C#.
It is also doable with .NET built-in FtpWebRequest, but that's lot more work.
Both are covered in How to get a directories file size from an FTP protocol in a .NET application.
A: Just use FTP "SIZE" command...
A: You can use The FileZilla client. Download here: https://filezilla-project.org/download.php?type=client
If you want more readable size go to:
Edit -> Settings -> Interface -> filesize format -> size formatting -> select binary prefixes using SI symbols.
When you select a directory you can see its size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3164623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: Theme Choosing on the basis of a certain API value I am working on a front-end project. My task is to receive an API token, then conditionally choose a theme (CSS file) for different API values.
now I have some plans,
1. doing something with package.json
2. using sass/compass
3. using webpack
According to project owner , I am not allowed to use less or sass. Is there any way to do so? I am using Nuxt.js .
N.B: what is have to do within the entry point of project, i.e. before loading the whole project
A: i did this simple task and worked like charm:
data(){
return{
api_value:0
}
},
beforeCreate(){
axios.get('my-api-link)
.then(response=>{
this.api_value = response.data.api_value
})
},
computed:{
inject_theme(){
if(this.api_value ==1)
return '/theme/dark.css'
else if (this.api_value ==2)
return '/theme/dark.1.css'
else if (this.api_value ==3)
return '/theme/dark.2.css'
}
},
head () {
return {
title: this.title,
meta: [
{ hid: 'description', name: this.inject_theme, content: 'My custom description' }
],
link:[
{rel:'stylesheet',href:this.inject_theme}
]
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51439835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: subsetting using a threshold in R and returning a neighboring row using for loops So I have been stumped on this problem for being able to build a table based off a threshold using R. All I want to do is groupby(set_a,set_b) and select a value based on whether rank_of_values is greater than .80 (utilizing some paste a the same time) to build a table. My criteria is, select the max rank_of_values and return the value in a table if true in the table. If that part is false, append in the table the first and second rank_of_values =value in the table. I was able to figure this out previously when there was only one group in set_b but now that there are multiple I am having trouble. I also have tried to figure out the warning but have been stumped tried for length error but no luck so far. Any help and advice would be appreciated.
library(data.table)
#create sample data
set_a <- c("a","a","a","a","b","b","b","b","c","c","c","c","a","a","a","a","b","b","b","b","c","c","c","c","a","a","a","a","b","b","b","b","c","c","c","c")
set_b <- c("red","red","red","red","red","red","red","red","red","red","red","red","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","blue","green","green","green","green","green","green","green","green","green","green","green","green")
#value <- c(sample(1:100,size = 36,replace = T))
value <- c(19,15,3,62,61,17,2,31,16,511,2,64,81,51,58,94,81,79,23,35,9,40,54,78,78,56,11,58,99,74,36,58,5,47,39,98)
a = data.frame(set_a,set_b,value)
a = data.table(a)
#This function calculates the average of the counts
a = a[,rank_of_values:= value/sum(value), by=list(set_a,set_b)]
head(a)
mn <- c() #create matrix to fill
mn0 <- c() #temp matrix
colu = unique(as.character(a$set_a))
colu2 = unique(as.character(a$set_b))
for (i in seq_along(colu))
{
#subset the data table for the set_a:
t = subset(a, set_a == colu[i])
for (i in seq_along(colu2)){
t2 = subset(t, set_b == colu2[i])
#subsetting the data by the set_b
if(t2$rank_of_values > .8){
mn <- cbind(as.character(t2$set_a[i]),paste0(t2$set_b[i],"_a"),t2$value[i])
mn0 <- rbind(mn,mn0)
mn2 <- cbind(as.character(t2$set_a[i]),paste0(t2$set_b[i],"_b"),t2$value[i])
mn0 <- rbind(mn0,mn2)
}
else
{
t2[order(-rank_of_values)][,.SD[1:2]] #create a second data table to select for
#order the data.table and
mn3 <- cbind(as.character(t2$set_a[1]),paste0(t2$set_b[1],"_a"),t2$value[1])
mn0 <- rbind(mn0,mn3)
mn4 <- cbind(as.character(t2$set_a[2]),paste0(t2$set_b[2],"_b"),t2$value[2])
mn0 <- rbind(mn0,mn4)
}
}
}
mn0
Current result:
[,1] [,2] [,3]
[1,] "a" "red_a" "19"
[2,] "a" "red_b" "15"
[3,] "a" "blue_a" "81"
[4,] "a" "blue_b" "51"
[5,] "a" "green_a" "78"
[6,] "a" "green_b" "56"
[7,] "b" "red_a" "61"
[8,] "b" "red_b" "17"
[9,] "b" "blue_a" "81"
[10,] "b" "blue_b" "79"
[11,] "b" "green_a" "99"
[12,] "b" "green_b" "74"
[13,] "c" "red_a" "16"
[14,] "c" "red_b" "511"
[15,] "c" "blue_a" "9"
[16,] "c" "blue_b" "40"
[17,] "c" "green_a" "5"
[18,] "c" "green_b" "47"
Desired Result:
[,1] [,2] [,3]
[1,] "a" "red_a" "62"
[2,] "a" "red_b" "19"
[3,] "a" "blue_a" "94"
[4,] "a" "blue_b" "81"
[5,] "a" "green_a" "78"
[6,] "a" "green_b" "58"
[7,] "b" "red_a" "61"
[8,] "b" "red_b" "31"
[9,] "b" "blue_a" "81"
[10,] "b" "blue_b" "79"
[11,] "b" "green_a" "99"
[12,] "b" "green_b" "74"
[13,] "c" "red_a" "511"
[14,] "c" "red_b" "64"
[15,] "c" "blue_a" "78"
[16,] "c" "blue_b" "54"
[17,] "c" "green_a" "98"
[18,] "c" "green_b" "47"
Warning Message Received:
Warning messages:
1: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
2: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
3: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
4: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
5: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
6: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
7: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
8: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
9: In if (t2$rank_of_values > 0.8) { :
the condition has length > 1 and only the first element will be used
A: I came up with a solution to my question after searching the forums.
mn <- c() #create matrix to fill
mn0 <- c() #temp matrix
colu = unique(as.character(a$set_a))
colu2 = unique(as.character(a$set_b))
for (i in colu){
for (j in colu2){
t = a[a$set_a %in% i & a$set_b %in% j,][order(-rank_of_values)]
for(z in t$rank_of_values[[nrow(t)]]){
if(t$rank_of_values[[z]] > .8){
print(z)
mn <- cbind(as.character(t$set_a[[z]]),paste0(t$set_b[[z]],"_a"),t$value[[z]])
mn0 <- rbind(mn,mn0)
mn2 <- cbind(as.character(t$set_a[[z]]),paste0(t$set_b[[z]],"_b"),t$value[[z]])
mn0 <- rbind(mn0,mn2)
}
else{
#create a second data table to select for
#order the data.table and
mn3 <- cbind(as.character(t$set_a[[1]]),paste0(t$set_b[[1]],"_a"),t$value[[1]])
mn0 <- rbind(mn0,mn3)
mn4 <- cbind(as.character(t$set_a[[2]]),paste0(t$set_b[[2]],"_b"),t$value[[2]])
mn0 <- rbind(mn0,mn4)
}
}
}
}
Result
[,1] [,2] [,3]
[1,] "a" "red_a" "62"
[2,] "a" "red_b" "19"
[3,] "a" "blue_a" "94"
[4,] "a" "blue_b" "81"
[5,] "a" "green_a" "78"
[6,] "a" "green_b" "58"
[7,] "b" "red_a" "61"
[8,] "b" "red_b" "31"
[9,] "b" "blue_a" "81"
[10,] "b" "blue_b" "79"
[11,] "b" "green_a" "99"
[12,] "b" "green_b" "74"
[13,] "c" "red_a" "511"
[14,] "c" "red_b" "64"
[15,] "c" "blue_a" "78"
[16,] "c" "blue_b" "54"
[17,] "c" "green_a" "98"
[18,] "c" "green_b" "47"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40007805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Match function? VBA not working properly I have a following code and i have "name" in cells B11 , B19 and B25 and i was expecting a result of 19 or 25 with the code but it returns Y=1. Could anyone tell me what is the problem?.
Sub mat()
Y = Application.Match("name", ActiveSheet.Range("B19:B30"), 0)
MsgBox Y
End Sub
A: According to the documentation for MATCH:
MATCH returns the position of the matched value within lookup_array, not the value itself.
and with 0as the optional third argument (match_type):
If match_type is 0, MATCH finds the first value that is exactly equal to lookup_value. Lookup_array can be in any order.
So the returned 1refers to the position on B19in the array Range("B19:B30") and the code sample is indeed behaving as expected.
A: Application.Match("name", ActiveSheet.Range("B19:B30"), 0)
The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range
So parsing the parameter ActiveSheet.Range("B19:B30") means that B19 equals relative position =1.
A: add slgn
Sub mat()
Y = Application.Match(slng(range("a4").value), ActiveSheet.Range("B19:B30"), 0)
MsgBox Y
End Sub
ex2:
Application.WorksheetFunction.Match(CLng(TextBox1.Text), sheet110.Range("B6:B" & ls), 0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20028769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# - Powershell AddPSSnapin Causes errors So, I import the System.Management.Automation dll and I'm trying to run a New-Mailbox command with params
so I use:
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException psEx = null;
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out psEx);
That's all fine and dandy... but when I go to run the application I get the following:
Cannot load Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.E2010 because of the following error: The type initializer for 'Microsoft.Exchange.Data.Directory.Globals' threw an exception.
So, I did some research online and found that I need to change from Any CPU to x86 as the platform target.
However, when I do that I get a HTTP Error 503. The service is unavailable. error
I am almost positive that I have to run it as a 32 bit process so that it can use the snapin (which from other reading seems to be what the snapin is running under)
I did change the app pool to Enable 32-bit Applications to True. Which is when I get the error.
I've read other posts... but, I'm not sure how to get past this Service unavailable thing.
I've tried using a x64 build and get Could not load file or assembly 'EmailAdminWeb2' or one of its dependencies. An attempt was made to load a program with an incorrect format.
A: You don't use this at all:
config.AddPSSnapIn("your snapin here", out psEx);
instead.... just use a connection as follows:
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://yourdomainhere/Powershell/Microsoft.Exchange"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", PsCreds);
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
Now run your commands and you're good to go.
Quick notes:
*
*Make sure you're app is targeting x64 not Any CPU or x86
*If you're using .net 4.5 (or 4) make sure you're app pools are set properly (v4.0 not v2.0) and that you have Enable 32bit apps set to false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17200314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: XEN: How to change domU-persistence? I have several running Xen-domUs, now I want to manage them using libvirt / virsh and noticed they all are defined as transient VMs.
Can I somehow change them to be persistent?
A: That's the difference between:
virsh create
and:
virsh define and virsh start.
The first one will create a non-persistent VM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28859947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should the authorities on the token storage be updated when refreshing a token? I'm implementing role-based Jwt which includes authorities attribute inside of Jwt claims. Currently, I use Jwt customizer for extracting authentication object from the context and put it inside of Jwt claims like this. The problem is that, the authorities on the JwtEncodingContext won't be changed as it was stored only for the first time when the token has been issued.
@Bean
fun jwtCustomizer(): OAuth2TokenCustomizer<JwtEncodingContext> {
return OAuth2TokenCustomizer { context: JwtEncodingContext ->
val principal: Authentication = context.getPrincipal() // <-- this won't change
val user: UserDetailsImpl = principal.principal as UserDetailsImpl
context.claims.claim("userId", user.getUserId())
context.claims.claim("authorities", user.getAuthorities())
}
}
However, authorities of a user can be changed regularly, for example the authorities of a user changed from "ADMIN" to "USER" but since the JwtEncodingContext won't be changed so he still got an authority of "ADMIN" whenever he refreshes a token. So I'm not quite sure how to properly handle this, one thing that I can think of is that to force a user to re-login by revoking his token, but this solution probably gives a user really bad experiences due to the authorities can be changed regularly in my system. or maybe a little bit of a dirty solution is that to query the data from user details instead and put it inside of claims like this.
@Bean
fun jwtCustomizer(): OAuth2TokenCustomizer<JwtEncodingContext> {
return OAuth2TokenCustomizer { context: JwtEncodingContext ->
val principal: Authentication = context.getPrincipal() // <-- this won't change
val user: UserDetailsImpl = userDetailsRepository.findById(principal.getUserId())
context.claims.claim("userId", user.getUserId())
context.claims.claim("authorities", user.getAuthorities())
}
}
Any ideas how to handle this?
A: The solution you outlined is one possible option, and it seems to me like a good start. Discussing in comments, I’d disagree that it is a “dirty” solution because you are actually using built-in components, namely the OAuth2TokenCustomizer and UserDetailsService. The built-in components in Spring Security are designed to allow you to integrate your authorization rules and requirements into the framework, which you are attempting to do. If you have a working solution for doing that, I would say that you have something to build on, and you can always improve it later or experiment with other ways if needed.
Another option would be to only include a roles claim (e.g. "roles": ["ROLE_ADMIN"]) in the access token, and perform the authority mapping in the resource server. This has the benefit of always being up to date, but the downside of scalability as it requires many resource servers to query the database where role to authority mappings are stored. If this is of interest, you would use a JwtGrantedAuthoritiesMapper from spring-security-oauth2-resource-server on the resource server side.
I would also recommend opaque tokens instead of JWTs if immediate revocation is needed. Similar support exists if using opaque tokens instead, though it would be better to customize claims on the authz server in this case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75581975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GCP Dataflow - getting data from PubSub to report to the sentry I am wondering if it is possible to get data from pubsub and send it to sentry. I mean:
sentry.init(...., integrations=[BeamIntegrations()])
try:
with Pipeline(optins=options) as pipeline:
(
pipeline
| io.ReadFromPubSub(...) // example message {'f': 'b'}, with attribut id: id1
| some transaformations...
expect:
// and any of above throw an error:
with sentry.push_scope() as scope:
sentry.set_tag('id': id1 from pubsub message) // ?
sentry.capture_expection
A: You can't catch errors in Beam in this way.
You have to use a dead letter queue with Beam and TupleTags.
You will have 2 sinks with this system :
*
*The good sink
*The bad sink
I didn't used sentry but I think it's possible to sink the a PCollection to sentry.
Example of catching errors with a library called Asgarde :
https://github.com/tosun-si/pasgarde
pip install asgarde==0.16.0
with Pipeline(optins=options) as pipeline:
(
input_collection = pipeline
| io.ReadFromPubSub(...) // example message {'f': 'b'}, with attribut id: id1
resut = (CollectionComposer.of(input_collection)
.map(lambda el : .....)
.map(lambda el2 : .....)
)
result_outputs: PCollection[YourObjectOrDict] = result.outputs
# Failure object contains error and input element and it's given by Asgarde library
result_failures: PCollection[Failure] = result.failures
result_failure | 'Send errors to Sentry' >> beam.Map(your_method_to_send_to_sentry)
If it's not possible to send errors to sentry in Beam pipeline, you can think to another solution :
*
*The errors can be written to Bigquery for analytics
*The errors can be loggued to Cloud Logging and then this can fire an email or Slack alerting
You can also catch error and use dead letter queue in native Beam code, I propose you an example from my Github repository :
https://github.com/tosun-si/teams-league-python-dlq-native-beam-summit/blob/main/team_league/domain_ptransform/team_stats_transform.py
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73886829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL, Foreign Key contraint fails in SP, but not when executing manually the task I am executing seems so simple. But this behaviour is very creepy indeed.
I am using MySQL.
I am having a Table for uploaded files - containing ID, FileName, FileHash, UploadDate, UploadUser etc.
Basically, these are XML Files.
And I have also a Table, containing the contents of the uploaded files. XML Files get parsed when uploaded and the contents are written into this Table.
This table has a reference, a foreign key, to the File-Table.
Here is the definition (shortened to the crucial points):
CREATE TABLE `tbl_xmlfiles` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Filename` varchar(1024) NOT NULL,
`FileHash` varchar(45) DEFAULT NULL,
`UploadDate` datetime DEFAULT CURRENT_TIMESTAMP,
`Count` int(11) NOT NULL DEFAULT '0',
`Status` enum('uploaded','closed','error','archived') NOT NULL DEFAULT 'uploaded',
`ScanID` int(11) DEFAULT NULL,
...
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=986 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Stores all uploaded xmlfiles data';
CREATE TABLE `tbl_xmlcontents` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`FileID` int(11) NOT NULL,
...
PRIMARY KEY (`ID`),
KEY `FileID` (`FileID`),
CONSTRAINT `fileID` FOREIGN KEY (`FileID`) REFERENCES `tbl_xmlfiles` (`ID`),
) ENGINE=InnoDB AUTO_INCREMENT=304817 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Stores all xml content data';
For better understanding, a "Scan" bundles multiple XML Files together.
I understand of course, that, if a File from the File Table is to be deleted, we first have to delete the rows from the other table (because this is no CASCADE contraint, which i do not want).
This is what I do in the SP:
CREATE PROCEDURE `sp_DeleteFilesByScanID`(
IN ScanID INT,
IN username VARCHAR(45)
)
BEGIN
...
DELETE c FROM tbl_xmlcontents c LEFT JOIN tbl_xmlfiles f ON c.FileID=f.ID WHERE f.`ScanID`=ScanID;
DELETE FROM tbl_xmlfiles WHERE `ScanID`=ScanID;
...
END
Running this SP, it errors:
Cannot delete or update a parent row: a foreign key constraint fails (`MYGREATTOOL`.`tbl_xmlcontents`, CONSTRAINT `fileID` FOREIGN KEY (`FileID`) REFERENCES `tbl_xmlfiles` (`ID`))
It errors on the second statement "DELETE FROM tbl_xmlfiles ...". The first one is executed as expected.
BUT here comes the clue.
When I execute these two DELETE-lines manually in MySQL Workbench (replacing the ScanID parameter with a valid value) - all works as expected. How can that be, for heaven's sake?
Can you please help me?
Greetings, xola
A: Okay, sticky bit's comment pointed me to the right solution. Thank you very much!
When specifying the ScanID with the table name/alias, then it is not considered as the SP Parameter "ScanID", but as a field name.
Solution:
DELETE FROM tbl_xmlfiles x WHERE x.`ScanID`=ScanID;
Can someone clarify, why the MySQL Parser thinks, that "ScanID" (sorry, here are backticks around the word - Stackoverflow makes this a quote automatically) is the SP Parameter? Aren't Backticks always meant to describe a MySQL field name?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61207264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git Hub Pull request builder plugin I am new to git. I am currently performing a poc using githubpullrequestbuilder plugin.
The GIT configuration looks as follows:
The plugin configuration is as below:
I wish to achieve the below use cases:
*
*Whenever a new Pull request is created a jenkins job should be triggered.(i was able to get this working)
*The job should be triggered incase the PR is updated with new additional commits. E.g: Before a PR is merged, in case there are any new checkins done which are a now a part of the existing PR, this should trigger a jenkins build.(I am not able to get this working.)
*The job should also be triggered if a simple push onto the master branch is made.(I am not able to get this working)
**
What is the correct configuration to achieve the above?
**
Note: I have a git web hook which is set to pull request and push events. Below is a screenshot.
A:
The job should be triggered incase the PR is updated with new additional commits. E.g: Before a PR is merged, in case there are any new checkins done which are a now a part of the existing PR, this should trigger a jenkins build.(I am not able to get this working.)
I'm not sure what you fully want here, do you want to combine both PR to a single PR when a check in is done immediately while a PR is being done ?? I don't think that's possible, why not wait till all check-in's are done and then do a pull request (Pull request are generally done when everything is finalized and you are sure of what needs to go(pushed) in general done in PROD environment)
There is an Trigger Setup option with cancel Build on update. But then you will have to trigger a new PR, you can check other option under Trigger Setup on commit related query
Unless you provide more details on what you require I cant help any further :)
The job should also be triggered if a simple push onto the master branch is made.(I am not able to get this working)
I don't think Git Pull Requests Handles Push. For that you will have to explicitly check the GitHub Branches in the Build Trigger option, and you can add restriction on the branches like 'build only Master'.
P.S. As for your webhook you have given permission to push and pull from Git but the same needs to be applied from Jenkins side :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49628427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Toggle all td's class in column on checkbox checked I'm looking for solution,
I have table with checkboxes at the top of each selected columns.
I want to make click all td's in "checked" column by one checkbox click.
fiddle so far:
$(':checkbox').on('change', function(e) {
var row = $(this).closest('tr');
var hmc = row.find(':checkbox:checked').length;
row.find('td.counter').text(hmc);
});
$("td.zero").on("click", function() {
if ($(this).hasClass("zero2")) {
$(this).removeClass("zero2");
var row3 = $(this).closest('tr');
var wal4 = $(this).text();
var wal5 = $(this).closest('tr').children('td.counter2').text();
wal6 = parseFloat(wal5, 10) - parseFloat(wal4, 10);
row3.find('td.counter2').text(wal6.toFixed(2));
} else {
$(this).addClass("zero2");
var row2 = $(this).closest('tr');
var wal = $(this).text();
var wal2 = $(this).closest('tr').children('td.counter2').text();
wal3 = parseFloat(wal, 10) + parseFloat(wal2, 10);
row2.find('td.counter2').text(wal3.toFixed(2));
}
});
$(':checkbox.taker').on('change', function(e) {
alert("tds in column clicked");
});
td {
text-align: center;
padding: 8px 8px 8px 8px;
cursor: default;
}
input.ptaszek {
transform: scale(2);
}
td.zero2 {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>X</th>
<th>X</th>
<th>X</th>
<th>Count1</th>
<th>Count2</th>
<th>Count3</th>
<th>Val1</th>
<th>Val2</th>
<th>Val3</th>
<th>Val4</th>
<th>Val5</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
</tr>
<tr>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td class='counter'>0</td>
<td class='counter2'>0</td>
<td class='counter3'>0</td>
<td class='zero'>0.5</td>
<td class='zero'>5</td>
<td class='zero'>2.1</td>
<td class='zero'>0.2</td>
<td class='zero'>1.7</td>
</tr>
<tr>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td>
<div><input type='checkbox' name='chkboxarray' class='ptaszek'></div>
</td>
<td class='counter'>0</td>
<td class='counter2'>0</td>
<td class='counter3'>0</td>
<td class='zero'>1.4</td>
<td class='zero'>0.5</td>
<td class='zero'>2</td>
<td class='zero'>1.1</td>
<td class='zero'>1.5</td>
</tr>
</tbody>
</table>
It's working for individual td click now, I need to make "bulk" click all td's by checkbox check ;)
Anyone have ideas?
Thanks for your replies!
A: Update:
Based on comments updating answer.
JSFiddle Demo
Does this help you?
Logic:
Check if the checkbox is checked, if its checked then assign all the respective elements as selected, no matter if they are selected or unselected already and vice versa for unselected, thus the end user will be able to select/unselect all the columns if he uses the checkbox!
$(':checkbox').on('change', function(e) {
var row = $(this).closest('tr');
var hmc = row.find(':checkbox:checked').length;
row.find('td.counter').text(hmc);
});
$("td.zero").on("click", function () {
if ( $( this ).hasClass( "zero2" ) ) {
$(this).removeClass("zero2");
var row3 = $(this).closest('tr');
var wal4 = $(this).text();
var wal5 = $(this).closest('tr').children('td.counter2').text();
wal6 = parseFloat(wal5, 10) - parseFloat(wal4, 10);
row3.find('td.counter2').text(wal6.toFixed(2));
} else {
$(this).addClass("zero2");
var row2 = $(this).closest('tr');
var wal = $(this).text();
var wal2 = $(this).closest('tr').children('td.counter2').text();
wal3 = parseFloat(wal, 10) + parseFloat(wal2, 10);
row2.find('td.counter2').text(wal3.toFixed(2));
}
});
$(':checkbox.taker').on('change', function(e) {
var elem = $(this).parent().index();
$('tr').each(function(index){
var td = $(this).children().eq(elem);
if(index > 1){
if($(':checkbox.taker:checked').length > 0){
td.addClass('zero2');
}else{
td.removeClass('zero2');
}
}
});
});
td
{
text-align: center;
padding: 8px 8px 8px 8px;
cursor: default;
}
input.ptaszek {
transform: scale(2);
}
td.zero2{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>X</th><th>X</th><th>X</th>
<th>Count1</th><th>Count2</th><th>Count3</th>
<th>Val1</th><th>Val2</th><th>Val3</th><th>Val4</th><th>Val5</th>
</tr>
</thead>
<tbody>
<tr><td></td><td></td><td></td><td></td><td></td><td></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
<td><input type='checkbox' class='taker'></td>
</tr>
<tr>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td class='counter'>0</td><td class='counter2'>0</td><td class='counter3'>0</td>
<td class='zero'>0.5</td><td class='zero'>5</td><td class='zero'>2.1</td><td class='zero'>0.2</td><td class='zero'>1.7</td>
</tr>
<tr>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td><div><input type='checkbox' name='chkboxarray' class='ptaszek'></div></td>
<td class='counter'>0</td><td class='counter2'>0</td><td class='counter3'>0</td>
<td class='zero'>1.4</td><td class='zero'>0.5</td><td class='zero'>2</td><td class='zero'>1.1</td><td class='zero'>1.5</td>
</tr>
</tbody>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46098036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Rails generating JSON Object I want to generate a JSON object while fetching data from database.
def duration
return @data[:duration] unless @data[:duration].nil?
@data[:duration] = per_hour.collect do | val |
[val[0], val[1]]
end
end
I get the data I need, but the array isn't correct. My view looks like:
var array = <%= raw @duration_data.to_json %>;
And my array looks like this:
var array = [{"data": [[0,0],[1,60.0]] }];
But what I need is this:
var array = [{"data": {"0":0, "1":60.0} }];
A: You just need to convert your array to a hash:
@data[:duration] = per_hour.collect do |val|
[val[0], val[1]]
end.to_h
For Ruby 1.9:
@data[:duration] = Hash[*per_hour.collect { |val| [val[0], val[1]] }]
A: I would write this as follows:
def duration
@data[:duration] ||= build_duration
end
This is a short way to say: return @data[:duration] if not nil, otherwise, assign build_duration to it.
And then you define build_duration
def build_duration
result = {}
per_hour.each do |val|
result[val[0]] = val[1]
end
result
end
You can write the build_duration more compact, but for me this is very readable: it will build a hash and fill it up as you wish.
A: @data[:duration] ||= per_hour.collect { | val | [val[0], val[1]] }.to_h
Try this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31449578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to put space betwwen Vertically Aligned X-axis label in matplotlib I have aligned my Xticks Vertically but all the labels are collapsed closely shown in the figure below:
This is my code for the above-shown Figure:
plt.plot(x_train.T,"*")
plt.xticks(rotation='vertical')
plt.show()
I want to put space between the x-axis labels. Any Hint?
Thank you in advance!
A: You can resize the font of the xticks:
plt.xticks(fontsize=6, rotation=90)
A: Solution:
plt.plot(x_train.T,"*")
plt.xticks(rotation=90)
plt.gcf().set_size_inches(30, 10)
plt.show()
Result:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57981310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git ssh: conect to host port 22 bad file number; can not pull I just installed a fresh Windows 7 Home Premium on my PC and wanted to reestablish my conection to a Git server. Therefore I copied my old .shh folder from the old installation into C:\users\user.ssh including a id_rsa, id_rsa.pub, known_hosts and a key.ppk. (everything was working with the old system). Afterwards I tryed connecting via Putty and Git Bash both failed. Putty just gave a cryptik "connection timed out" Git Bash returned:
ssh: conncet to host xxx.xx.xx.xx port 22: bad file number
fatal: Could not read from remote repository.
Googeling did not return anything really usefull since the port can not be blocked by the server. I can not change to a https conection and need to use ssh. Turning off the windows firewall did also not help.
I hope someone can help me with this, kind regards,
mhwh
A: The problem solved it self - I do not know why, but now everything is working properly, in the meantime Skype and some Windwos updates have been installed but I am not shure how this might affect the git system...
A: I have also encountered such problems. The solution is to start the Windows Update Service:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28796285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Storing millions of URLs in a database for fast pattern matching I am developing a web analytics kind of system which needs to log referring URL, landing page URL and search keywords for every visitor on the website. What I want to do with this collected data is to allow end-user to query the data such as "Show me all visitors who came from Bing.com searching for phrase that contains 'red shoes'" or "Show me all visitors who landed on URL that contained 'campaign=twitter_ad'", etc.
Because this system will be used on many big websites, the amount of data that needs to log will grow really, really fast. So, my question: a) what would be the best strategy for logging so that scaling the system doesn't become a pain; b) how to use that architecture for rapid querying of arbitrary requests? Is there a special method of storing URLs so that querying them gets faster?
In addition to MySQL database that I use, I am exploring (and open to) other alternatives better suited for this task.
A: For rapid searching the data store, I would suggest creating an index of the urls (or any other string based criteria) that is based on a suffix tree data structure. The search would be done in O(k), where k is the length of the url (which is really fast). A good introduction to such kind of trees you could find here.
When it comes to logging, try not to store them by one. I/O operations are quite resource intensive and are in most cases the bottlenecks of such systems. Try to write the urls into your data store in batch. For example keep the submitted urls in memory and store them only by 1000 chunks at once. Just remember to update on some background or scheduled task the suffix tree to keep the data synchronized.
A: I was faced with this exact issue in SQL Server and the solution for me was a table to store all my unique URLS/TITLES with a unique key on a two computed columns containing a checksum of URL and TITLE. It took up about a tenth of the space as an equivalent key on the string URL/Title.and was 10X faster than a direct index.
I'm using SQL server so the statement was
(checksum([URL],(0)))
and
(checksum([URL],(0)))
I found this for MySql.
Since most of the traffic came from many of the same websites, it allowed me to consolidate urls/titles without having to search the whole table with each insert to enforce the unique constraint. My Procedure just returned an url/title PK if it already existed.
To tie to your users, use a USER_URL table with a FK of the PK of USER and URL.
Good luck.
A: I wish there was a datatype on mysql for URIs. But since oracle has it and mysql is now oracle, this might happen someday...
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements001.htm#i160550
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2981518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Simple WPF combobox filter I have searched Google for a simple solution to this but no luck. I have a standard WPF combo box which I would simply like to be able to filter the list displayed according to the first 2 or 3 letters a users types when the combo box has focus. I tried some coding including some lamba expressions but the error "System.NotSupportedException" keeps getting thrown on the line where "combobox.Items.Filter" is specified. I'm not using MVVM and would just like this simple functionality available for the user. Please help! P.S. IsEditable, IsTextSearchEnabled and StaysOpenOnEdit properties are set to true but the desired functionality is not yet achieved.
A: I have developed a sample application. I have used string as record item, you can do it using your own entity. Backspace also works properly.
public class FilterViewModel
{
public IEnumerable<string> DataSource { get; set; }
public FilterViewModel()
{
DataSource = new[] { "india", "usa", "uk", "indonesia" };
}
}
public partial class WinFilter : Window
{
public WinFilter()
{
InitializeComponent();
FilterViewModel vm = new FilterViewModel();
this.DataContext = vm;
}
private void Cmb_KeyUp(object sender, KeyEventArgs e)
{
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(Cmb.ItemsSource);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(Cmb.Text)) return true;
else
{
if (((string)o).Contains(Cmb.Text)) return true;
else return false;
}
});
itemsViewOriginal.Refresh();
// if datasource is a DataView, then apply RowFilter as below and replace above logic with below one
/*
DataView view = (DataView) Cmb.ItemsSource;
view.RowFilter = ("Name like '*" + Cmb.Text + "*'");
*/
}
}
XAML
<ComboBox x:Name="Cmb"
IsTextSearchEnabled="False"
IsEditable="True"
ItemsSource="{Binding DataSource}"
Width="120"
IsDropDownOpen="True"
StaysOpenOnEdit="True"
KeyUp="Cmb_KeyUp" />
A: I think the CollectionView is what you are looking for.
public ObservableCollection<NdfClassViewModel> Classes
{
get { return _classes; }
}
public ICollectionView ClassesCollectionView
{
get
{
if (_classesCollectionView == null)
{
BuildClassesCollectionView();
}
return _classesCollectionView;
}
}
private void BuildClassesCollectionView()
{
_classesCollectionView = CollectionViewSource.GetDefaultView(Classes);
_classesCollectionView.Filter = FilterClasses;
OnPropertyChanged(() => ClassesCollectionView);
}
public bool FilterClasses(object o)
{
var clas = o as NdfClassViewModel;
// return true if object should be in list with applied filter, return flase if not
}
You wanna use the "ClassesCollectionView" as your ItemsSource for your Combobox
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34382459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Starting Chromium with switches in file? I am running chromium on linux and need to find a way to put all of the startup flags into a file instead of pushing them through the startup command
e.g:
chromium --disable-pinch --disable-sync http://URL
is there a way to have these flags or "Switches" in a config file or something so flags can be added and removed in a central location.
any tips or solutions would be greatly appreciated.
A: The classic way to do this is to create a simple shell script like chromium-custom.sh:
#!/bin/sh
chromium --disable-pinch --disable-sync "$@"
Then
chmod +x chromium-custom.sh
./chromium-custom.sh --extra-parameter http://URL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38642214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to declare "any" module in TypeScript? I need to migrate step by step some large project from js to typeScript.
I rewrite on of the files in ts and i want to specify that other files at this moment can contain any content.
For example something like that:
declare module jsModule:any;
var obj:jsModule.cls = new jsModule.cls()
But it does not work in this moment. I need to specify each exported class/function/variable in module declaration.
Can i declare external module as "any" in some fast way?
A: For an external module with no exposed types and any values:
declare module 'Foo' {
var x: any;
export = x;
}
This won't let you write foo.cls, though.
If you're stubbing out individual classes, you can write:
declare module 'Foo' {
// The type side
export type cls = any;
// The value side
export var cls: any;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31729668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Javascript NaN function This function receive values for another one (the generation parameter). My objective is return onde array in cloneGene variable, although it appears like NaN and I do not know why.
function SampleWithReposition(generation, newGeneration) {
newGeneration = [];
generation = Starting_generation;
var randomGeneration = Math.floor(Math.random() * pop_size) + 0;
for(i=0;i<pop_size;i++){
newGeneration = generation[i] = generation[randomGeneration];
}
return newGeneration;
GenerationStep(newGeneration);
//document.write(newGeneration + ' <br />' + ' <br />');
}
//Mutation and recombination rate
function GenerationStep (mutation_rate, recombination_rate, generation, cloneGene) {
//var generation = [1, 2, 1, 54, 1, 1, 1];
generation = SampleWithReposition();
mutation_rate = recombination_rate = 0.1;
for(var i=0; i<pop_size; i++){
for(var j=0;j<gene_size; j++){
random_number = random();
var max_individual = Math.max.apply(Math, generation);
//mutation_rate
if(random_number < mutation_rate){
var cloneGene = 1;
cloneGene=generation[i][j]=generation[max_individual][j]+1;
document.write(cloneGene);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18854296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change add-to-cart form? Is there a way to change the WooCommerce add-to-cart form through functions.php?
The goal is to add a checkbox for an additional product. When the checkbox is checked this product will also be added to the cart after a click on the add to cart button.
I am looking for a solution which doesn't rely on javascript.
A: A better title would be "WooCommerce up-sells as checkboxes".
A lot of research and several strategies to tackle this problem lead me to a solution which I thought was not even possible in the beginning.
The solution is now exactly what I wanted. A non-JavaScript, no-template-override, but a simple and pure addition to functions.php. It works for simple and variable products (and probably with grouped and external products too).
It misses some nice features still. It won't work yet if an up-sell is a variable product. Quantity selection and limiting up-sells per item or order would be nice additions too. Based on the code below adding those features should not be a big deal anymore.
// create the checkbox form fields and add them before the cart button
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_add_to_cart_form', 10, 0 );
function action_woocommerce_before_add_to_cart_form(){
global $woocommerce, $product;
// get the product up-sells
$upsells = $product->get_upsells();
// store the number of up-sells and pass it on to the add-to-cart hook
?>
<input type="hidden" name="upsells_size" value="<?php echo(sizeof($upsells)); ?>">
<div id="wb-upsell-div">
<?php
// iterate through all upsells and add an input field for each
$i = 1;
foreach( $upsells as $value ){
$product_id = $value;
?>
<input id="wb-upsell-checkboxes" type="checkbox" name="upsell_<?php echo($i) ?>" value="<?php echo($product_id); ?>"><?php echo( '<a href="' . esc_url( get_permalink( $product_id )) . '" target="_blank">' . get_the_title( $product_id ) . "</a>". " ($" . get_post_meta( $product_id, '_regular_price', true) . ")"); ?><br>
<?php
$i++;
}
?>
</div>
<?php
}
// function to add all up-sells, where the checkbox have been checked, to the cart
add_action('woocommerce_add_to_cart', 'custom_add_to_cart', 10, 3);
function custom_add_to_cart() {
global $woocommerce;
// get the number of up-sells to iterate through
$upsell_size = $_POST['upsells_size'];
// iterate through up-sell fields
for ($i=1; $i<=$upsell_size; $i++){
// get the product id of the up-sell
$product_id = $_POST['upsell_' . $i];
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
And here is the CSS for formatting the <div>and the checkboxes. It goes into the style.css file:
#wb-upsell-div {
margin-top: 10px;
margin-bottom: 20px;
}
#wb-upsell-checkboxes{
}
A: So there's an actual answer to this question, you can add whatever you want inside the add to cart <form> using hooks. For example:
add_action( 'woocommerce_before_add_to_cart_button', 'so_34115452_add_input' );
function so_34115452_add_input(){
echo '<input type="checkbox" name="something"/>' . __( 'Some Checkbox', 'text-domain' );
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34115452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to make a radio button in Jquery UI? How can I make the check box a radio button? I want to add a radio button before By buffer and By polygon.
dialog1.empty();
var header = $('<h5></h5>').text('By buffer');
var toggleBtn = $('<button><i id="toggle-icon" class="fa fa-circle"></i></button>').attr('id', 'toggle-buffer-btn').attr('class', 'btn btn-default btn-sm');
var inputRadius = $('<input type="text"/>').attr('id', 'radius').attr('class', 'btn btn-default btn-sm').attr('disabled', 'disabled');
var helpLabel = $('<span id="help-label">Click and drag mouse to create buffer</span>');
var polyBufferChkbx = $('<input type="checkbox">').attr('id', 'polygon-buffer');
var polyBufferLabel = $('<span id="polygon-buffer-label">   By polygon</span>');
var val;
dialog1.append(header);
dialog1.append(toggleBtn);
dialog1.append(inputRadius);
dialog1.append(helpLabel);
dialog1.append('<br/>');
dialog1.append('<br/>');
dialog1.append(polyBufferChkbx);
dialog1.append(polyBufferLabel);
A: If you're going to use jQuery UI, why not let it help you.
Example: https://jsfiddle.net/Twisty/wfqv3orm/
HTML
<div id="dialog1">
</div>
JavaScript
$(function() {
var dialog1 = $("#dialog1");
dialog1.empty();
var header = $("<h5>", {
class: "dialog-header"
}).text("By buffer").appendTo(dialog1);
$("<button>", {
id: "toggle-buffer-btn",
class: "btn btn-default btn-sm"
}).appendTo(dialog1);
dialog1.find("button").append($("<i>", {
id: "toggle-icon",
class: "fa fa-circle"
}));
$("<input>", {
type: "text",
id: "radius",
class: 'btn btn-default btn-sm'
}).prop('disabled', true).appendTo(dialog1);
$("<span>", {
id: "help-label",
style: "margin-bottom: 2em;"
}).html("Click and drag mouse to create buffer").appendTo(dialog1);
$("<input>", {
type: "checkbox",
id: 'polygon-buffer'
}).appendTo(dialog1);
$("<label>", {
id: "polygon-buffer-label",
for: "polygon-buffer"
}).html("By polygon").appendTo(dialog1);
dialog1.controlgroup();
var val;
});
Little bit faster to just build and append elements all at once in my opinion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44233541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FileNotFoundException (The filename, directory name, or volume label syntax is incorrect) I am trying to access a file like this:
public class Main {
private static class RemoteAdapter implements SpellcheckerRemoteAdapter {
private Spellchecker spellchecker;
private String fileName = "deutsch.txt";
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
private RemoteAdapter() {
this.spellchecker = SpellcheckerFactory.createSpellchecker(file);
}
@Override
public boolean check(String word) {
return this.spellchecker.check(word);
}
@Override
public List < String > getProposal(String word) {
return this.spellchecker.getProposal(word);
}
}
public static void main(String[] args) {
System.out.println("Start Server");
try {
Registry registry = LocateRegistry.createRegistry(1088);
SpellcheckerRemoteAdapter adapter = new RemoteAdapter();
UnicastRemoteObject.exportObject(adapter, 0);
registry.rebind(SpellcheckerRemoteAdapter.NAME, adapter);
} catch (RemoteException re) {
System.out.println(re.getMessage());
}
System.out.println("Server is running!");
}
}
When I run my code inside of eclipse it works just fine. But if I export the project as a runnable jar I get the following error:
java.io.FileNotFoundException: file:\C:\Users\Linsane\Desktop\server\SpellcheckerServer.jar!\deutsch.txt (The filename, directory name, or volume label syntax is incorrect)
Although I know that the file is in this location and as I don't build the path myself I don't really get what went wrong.
A: Try removing getClassLoader() call:
File file = new File(getClass().getResource(fileName).getFile());
You can also open the jar file manually and check if the file is actually packaged into the jar file.
A: I solved it with the tip of EJP & What's the difference between a Resource, URI, URL, Path and File in Java?
Instead of passing a File like this:
private String fileName = "deutsch.txt";
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
private RemoteAdapter() {
this.spellchecker = SpellcheckerFactory.createSpellchecker(file);
}
I now pass a URL to the file like this:
private String fileName = "deutsch.txt";
URL url = ClassLoader.getSystemClassLoader().getResource(fileName);
private RemoteAdapter() {
this.spellchecker = SpellcheckerFactory.createSpellchecker(url);
}
Inside of the Spellchecker constructor I then just get an Inputstream of the URL and read from it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50454438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mobile Ads Refresh Rate & Optimization I'm looking to add mobile ads using Mopub.
In thinking where and on which activities to place ads, I'm thinking more screen views = more ad refreshes = more CPM impressions
However Mopub's guide emphasizes click throughs and asks not to refresh the ad often. I think their ad refreshes after a timeout by itself anyways.
http://www.mopub.com/2011/10/12/how-to-optimize-your-mobile-ads-part-2-of-3/
I'm a little confused as that approach would mean less ad impressions. What am I missing?
Obviously I'm trying to optimize ad placement for profitability.
Should I refresh often myself for each activity & fragment load? Or is it best to reload less frequently ?
Thanks.
A: This is a trade off since Higher CTR (Click Through Rate) means higher eCPM (estimated cost per mille (impression)) ads. However, with a faster refresh, you get more ad impressions but the CTR drops ad there is less screen time for an individual ad.
For banners, I'd say about a 20-30s refresh rate is optimal. I know that for MoPub, you can set values lower than 10, but the minimum is around 10 seconds for refresh rate.
You can run a a/b test programmatically on MoPub for two subsets of users, one with an ad unit with 20s and one with an ad unit with 30s and see which one performs better.
For MoPub, you can automatically set refresh rate by editing the ad unit in the UI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30605852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recursive Function in MS SQL I have following two tables:
SELECT [AM_ID]
,[AMI_ID]
,[Parent_AMI_ID]
,[AMI_Code]
FROM [Reporting].[dbo].[DIM_AM]
;
This table contains hierarchy (37 rows)
SELECT [AMI_ID]
,[AMI_Name]
FROM [Reporting].[dbo].[DIM_AMI]
;
This table contains entities (AMI_Name).
And i have to make a table using recursive function in MS SQL that will return following:
SELECT
Level
,AMI_Code
,AMI_Name
FROM...
How can I use the recursive function to generate hierarhy in this format?
How do you write recursive query with recursive function in MS SQL in General?
Give me some Suggestion please.
A: Here is a little example:
DECLARE @DIM_AM TABLE([AM_ID] INT, [AMI_ID] int, [Parent_AMI_ID] INT, [AMI_Code] VARCHAR(20))
DECLARE @DIM_AMI TABLE([AMI_ID] INT, [AMI_Name] VARCHAR(20))
INSERT INTO @DIM_AMI VALUES
(1, 'AMI1'),
(2, 'AMI2'),
(3, 'AMI3'),
(4, 'AMI4')
INSERT INTO @DIM_AM VALUES
(1, 1, NULL, 'CODE_AMI1'),
(2, 2, 1, 'CODE_AMI2'),
(3, 3, 1, 'CODE_AMI3'),
(4, 4, 3, 'CODE_AMI4')
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
SELECT c.Level, c.AMI_Code, d.AMI_Name FROM cte c
JOIN @DIM_AMI d ON d.AMI_ID = c.AMI_ID
Output:
Level AMI_Code AMI_Name
0 CODE_AMI1 AMI1
1 CODE_AMI2 AMI2
1 CODE_AMI3 AMI3
2 CODE_AMI4 AMI4
This is recursive common table expression(cte):
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
First part is starting point where you select top level elements(WHERE Parent_AMI_ID IS NULL):
SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
Then by syntax you need union all.
Then comes recursive part that selects children of previous select:
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33258924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IBM MobileFirst 8.0.0 - WorkLight Logger and Analytics not working I have implemented WL Logger and WL Analytics in my ionic app. But the logs(Client side + Server side) are not publishing on the console.
My steps are:-
1. I have enabled MFPLogger on my console.
2. Initialize WL using
enter code here
WL.Client.init({
onSuccess : function() {
WL.Logger.config({ capture: true });
WL.Analytics.init(this);
enter code here
WL.Analytics.addDeviceEventListener
(WL.Analytics.DeviceEvent.NETWORK);
WL.Analytics.addDeviceEventListener
(WL.Analytics.DeviceEvent.LIFECYCLE);
setInterval(function() {
WL.Logger.send();
WL.Analytics.send();
}, 6000);
console.log("Success WL");
},
onFailure : function(err){
}
});
//Client Side
WL.Logger.info(response)
WL.Analytics.log({type : message},message);
//End
//Server Side
MFP.Logger.info(logging_message);
//End
Please help
A: Please try with this one.
WL.Client.init({
onSuccess : function() {
WL.Logger.config({ maxFileSize : 100000, // allow persistent storage of up to 100k of log data
// level : 'info', // at debug (and above) level
capture : true,
stringify: true // capture data passed to log API calls into persistent storage
});
WL.Analytics.enable().then(function (success) {
console.log(success);
}).fail(function (errObj) {
console.log(errObj);
});
setInterval(function() {
WL.Logger.send();
WL.Analytics.send();
}, 6000);
console.log("Success WL");
},
onFailure : function(err){
console.log("Failed WL");
WL.Logger.error('Caught an exception', err);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47151244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I modify a SELECT query to force specific values to be returned for a column, without updating what's actually stored in the table? I don't know if this is possible, but hopefully this is pretty simply to answer.
Lets say you have read only access to a database (Oracle 11g in this case). You are querying data into an Excel sheet. Part of the data I'm gathering is a panel_name. And I'm only concerned about the data when panel_id=1 OR panel_id=2 OR panel_id=3.
Now, the problem is that for the purposes of this particular query I want to treat panel_id 1 and 3 as if they were the same, not updating the DB, just in the report. So Instead of;
when panel_id=1 then panel_name="Panel 1"
when Panel_id=3 then panel_name="Panel 3"
I'd like override it so that;
when panel_id=1 then panel_name="Panel 1"
when panel_id=3 then panel_name="Panel 1"
I haven't found anything that would allow me to do this though. I'm open to other alternatives as well, but in the end I'd just like to have both of those panels be treated as if they were the same. The code looks something like this;
SELECT
requisitions.received_date AS "Received Date"
,panels.PANEL_NAME AS "Panel Name"
FROM requisitions
inner join panels ON requisitions.PANEL_ID = panels.PANEL_ID
WHERE (panels.PANEL_ID = 1 OR panels.PANEL_ID = 2 OR panels.PANEL_ID = 3)
ORDER BY requisitions.RECEIVED_DATE DESC
A: Do you just want to have a CASE statement in your query?
SELECT
requisitions.received_date AS "Received Date"
,(CASE WHEN panels.panel_id IN (1,3)
THEN 'Panel 1'
ELSE panels.PANEL_NAME
END) AS "Panel Name"
If that is not what you're asking, it would be very helpful to post some sample data and the expected output of your query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21297523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WS-securitypolicy in cxf-bc deploy in servicemix I was wondering if it is possible to build a cxf-bc with WS-SecurityPolicy instead of just the WS-Security. WS-SecurityPolicy seems to be a more elegant solution since everything is in the WSDL. Examples welcome. :)
Well with David's help I got the CXF-BC to install and running on the ESB, but I can't seem to test it. It keeps coming back with:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>These policy alternatives can not be satisfied:
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}UsernameToken</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
My msg:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://nwec.faa.gov/wxrec/UserAccount/types">
<soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/ws-securitypolicy-1.2.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-25" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>bob</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobspassword</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
<wsa:Action>http://nwec.faa.gov/wxrec/UserAccount/UserAccountPortType/ApproveDenyAccountRequest</wsa:Action>
</soapenv:Header>
<soapenv:Body>
...
</soapenv:Body>
Here's the policy in the wsdl:
<wsp:Policy wsu:Id="UserAccountBindingPolicy" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp:ExactlyOne>
<wsp:All>
<wsaw:UsingAddressing xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" wsp:Optional="true" />
<wsp:Policy >
<sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Always">
<wsp:Policy>
<sp:WssUsernameToken10 />
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
A: As of the resolution of https://issues.apache.org/activemq/browse/SMXCOMP-711 and https://issues.apache.org/activemq/browse/SMXCOMP-712 (servicemix-cxf-bc-2010.01) it should be possible and easy to do.
See http://fisheye6.atlassian.com/browse/servicemix/components/bindings/servicemix-cxf-bc/trunk/src/test/java/org/apache/servicemix/cxfbc/ws/security/CxfBcSecurityJAASTest.java?r=HEAD for an example. Specifically the testJAASPolicy method.
As for the error relating to asserting the UsernameToken assertion, you may want to try putting the UsernameToken assertion inside of a SupportingToken or binding assertion depending on what you want to do with the token. It looks like you just want a username and password to be passed in the message without any other security such as a cryptographic binding of the token to the message or encryption so a supporting token will likely fit your needs.
I also urge you to consider the following additional precautions when using a UsernameToken:
*
*Cryptographically bind the token to the message using a signature.
*Use a nonce and created timestamp and cache the token on the server to prevent replay
*Consider encrypting the token (before signing if you also sign) using XML enc
*Using TLS either in lieu of or in addition to the above suggestions
A: With david's and Freeman over at the servicemix-user mailing-list. I was able finally get the correct configuration to implement WS-Security Policy.
Here's my final beans.xml for the my BC
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxfbc="http://servicemix.apache.org/cxfbc/1.0" xmlns:util="http://www.springframework.org/schema/util"
xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:sec="http://cxf.apache.org/configuration/security"
xmlns:person="http://www.mycompany.com/ws-sec-proto"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://servicemix.apache.org/cxfbc/1.0
http://repo2.maven.org/maven2/org/apache/servicemix/servicemix-cxf-bc/2010.01/servicemix-cxf-bc-2010.01.xsd
http://cxf.apache.org/transports/http-jetty/configuration
http://cxf.apache.org/schemas/configuration/http-jetty.xsd
http://cxf.apache.oarg/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
<import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-policy.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-ws-security.xml" />
<bean id="myPasswordCallback" class="com.mycompany.ServerPasswordCallback" />
<cxfbc:consumer wsdl="classpath:wsdl/person.wsdl"
targetService="person:PersonService" targetInterface="person:Person"
properties="#properties" delegateToJaas="false" >
<!-- not important for ws-security
<cxfbc:inInterceptors>
<bean class="com.mycompany.SaveSubjectInterceptor" />
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</cxfbc:inInterceptors>
-->
</cxfbc:consumer>
<util:map id="properties">
<entry>
<key>
<util:constant
static-field="org.apache.cxf.ws.security.SecurityConstants.CALLBACK_HANDLER" />
</key>
<ref bean="myPasswordCallback" />
</entry>
</util:map>
<httpj:engine-factory bus="cxf">
<httpj:engine port="9001">
<httpj:tlsServerParameters>
<sec:keyManagers keyPassword="password">
<sec:keyStore type="JKS" password="password" resource="certs/cherry.jks" />
</sec:keyManagers>
<sec:cipherSuitesFilter>
<sec:include>.*_WITH_3DES_.*</sec:include>
<sec:include>.*_WITH_DES_.*</sec:include>
<sec:exclude>.*_WITH_NULL_.*</sec:exclude>
<sec:exclude>.*_DH_anon_.*</sec:exclude>
</sec:cipherSuitesFilter>
<sec:clientAuthentication want="false"
required="false" />
</httpj:tlsServerParameters>
</httpj:engine>
</httpj:engine-factory>
<bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl" />
<bean class="org.apache.servicemix.common.osgi.EndpointExporter" />
</beans>
Full example can be found here but it may not be there after a while.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2554489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Block multiple UI threads for a dialog in WPF In the moment, I have a problem with multiple UI threads in WPF.
I have a third party component, which I need to use in a project. Unfortunately, every function of the component needs to be executed in the UI thread. The component itself has some long-term operations. For these operations, I want to show a Dialog that shows the progress of the operation. Additionally it should also be possible to cancel this operation. Since the long-term action of the component needs to be executed in the UI thread, the update of the progress bar is not very nice.
To avoid this problem I have put the dialog window in a separated UI thread. Now the progress is displayed as expected and very smoothly. However, now the dialog do not behave as a dialog. Since it is hosted in, a separate UI Thread It only blocks the User Interaction for this UI Thread and not for the main UI thread. Nevertheless, I want the dialog to block the main Window.
It would be possible to use Mousehoocks to achieve something like this. However, I want to know if it is possible to achieve this with WPF, C# functionality.
Therefore, I hope that anyone can help me with this problem.
A: We have found an interesting Article that helped us to solve the problem.
Host Visual
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16914170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Detecting mostly empty images using imagemagick I'd like to use imagemagick or graphicsmagick to detect whether an image has basically no content.
Here is an example:
https://s3-us-west-2.amazonaws.com/idelog/token_page_images/120c6af0-73eb-11e4-9483-4d4827589112_embed.png
I've scoured Fred's imagemagick scripts, but I can't figure out if there is a way to do this:
http://www.fmwconcepts.com/imagemagick/
A: Easiest way would be to use -edge detection followed by histogram: & text:. This will generate a large list of pixel information that can be passed to another process for evaluation.
convert 120c6af0-73eb-11e4-9483-4d4827589112_embed.png \
-edge 1 histogram:text:- | cut -d ' ' -f 4 | sort | uniq -c
The above example will generate a nice report of:
50999 #000000
201 #FFFFFF
As the count of white pixels is less then 1% of black pixels, I can say the image is empty.
This can probably be simplified by passing -fx information to awk utility.
convert 120c6af0-73eb-11e4-9483-4d4827589112_embed.png \
-format '%[mean] %[max]' info:- | awk '{print $1/$2}'
#=> 0.00684814
A: If you are talking about the amount of opaque pixels vs the amount of transparent pixels, then the following will tell you the percentage of opaque pixels.
convert test.png -alpha extract -format "%[fx:100*mean]\n" info:
39.0626
Or if you want the percentage of transparent pixels, use
convert test.png -alpha extract -format "%[fx:100*(1-mean)]\n" info:
60.9374
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27107923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: bar chart with Matplotlib Here is my data structure:
data = {'2013': {1:25,2:81,3:15}, '2014': {1:28, 2:65, 3:75}, '2015': {1:78,2:91,3:86 }}
My x-axis is the number [1,2,3]
My y-axis is the quantity of each number. For example: In 2013, 1 is x axis while its quantity is 25.
Print each individual graph for each year
I would like to graph a bar chart, which uses matplotlib with legend on it.
A: import matplotlib.pyplot as plt
import pandas as pd
data = {'2013': {1:25,2:81,3:15}, '2014': {1:28, 2:65, 3:75}, '2015': {1:78,2:91,3:86 }}
df = pd.DataFrame(data)
df.plot(kind='bar')
plt.show()
I like pandas because it takes your data without having to do any manipulation to it and plot it.
A: You can access the keys of a dictionary via dict.keys() and the values via dict.values()
If you wanted to plot, say, the data for 2013 you can do:
import matplotlib.pyplot as pl
x_13 = data['2013'].keys()
y_13 = data['2013'].values()
pl.bar(x_13, y_13, label = '2013')
pl.legend()
That should do the trick. More elegantly, do can simply do:
year = '2013'
pl.bar(data[year].keys(), data[year].values(), label=year)
which woud allow you to loop it:
for year in ['2013','2014','2015']:
pl.bar(data[year].keys(), data[year].values(), label=year)
A: You can do this a few ways.
The Functional way using bar():
data = {'2013': {1: 25, 2: 81, 3: 15}, '2014': {1: 28, 2: 65, 3: 75}, '2015': {1: 78, 2: 91, 3: 86}}
df = pd.DataFrame(data)
X_axis = np.arange(len(df))
plt.bar(X_axis - 0.1,height=df["2013"], label='2013',width=.1)
plt.bar(X_axis, height=df["2014"], label='2014',width=.1)
plt.bar(X_axis + 0.1, height=df["2015"], label='2015',width=.1)
plt.legend()
plt.show()
More info here.
The Object-Oriented way using figure():
data = {'2013': {1: 25, 2: 81, 3: 15}, '2014': {1: 28, 2: 65, 3: 75}, '2015': {1: 78, 2: 91, 3: 86}}
df = pd.DataFrame(data)
fig= plt.figure()
axes = fig.add_axes([.1,.1,.8,.8])
X_axis = np.arange(len(df))
axes.bar(X_axis -.25,df["2013"], color ='b', width=.25)
axes.bar(X_axis,df["2014"], color ='r', width=.25)
axes.bar(X_axis +.25,df["2015"], color ='g', width=.25)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32956199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Add inner corner curved border to active menu I am trying to create an inner curved border for active/selected menu. Below snippet is so far the best I can do, the square corner shouldn't be visible. Solutions from google doesn't seem to help... Please help me play with it. Thanks guys!
FIDDLE HERE.
body {
background:#eee;width:90%;margin:20px auto
}
ul {
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
list-style: none;
position: relative;
vertical-align:bottom;
}
ul li a {
padding: 10px 15px;
display: block;
line-height: 25px;
margin-bottom:-1px;
}
ul li.active a {
background:#fff;
border:1px solid #aaa;
border-bottom:0;
border-radius:5px 5px 0 0;
}
ul li.active:before,
ul li.active:after {
content:"";
position:absolute;
bottom:-1px;
width:10px;
height:10px;
border:solid #aaa;
}
ul li.active:before {
left:-10px;
border-radius:8px 0;
border-width:0 1px 1px 0
}
ul li.active:after {
right:-10px;
border-radius: 0 8px;
border-width:0 0 1px 1px;
}
.content {
border:1px solid #aaa;background:#fff;height:200px
}
<ul>
<li><a href="#">tab 1</a></li>
<li class="active"><a href="#">tab2</a></li>
<li><a href="#">tab3</a></li>
<li><a href="#">tab4</a></li>
</ul>
<div class="content"></div>
A: This is my solution so far. But I am hoping there is a better solution out there... I use the pseudo element of active a to create a white border to hide the sharp corner.
body {
background:#eee;width:90%;margin:20px auto
}
ul {
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
list-style: none;
position: relative;
vertical-align:bottom;
}
ul li a {
padding: 10px 15px;
display: block;
line-height: 25px;
margin-bottom:-1px;
}
ul li.active a {
background:#fff;
border:1px solid #aaa;
border-bottom:0;
border-radius:5px 5px 0 0;
}
ul li.active:before,
ul li.active:after {
content:"";
position:absolute;
bottom:-1px;
width:10px;
height:10px;
border:solid #aaa;
}
ul li.active:before {
left:-10px;
border-radius:50% 0;
border-width:0 1px 1px 0;
box-shadow: 1px 1px white;
}
ul li.active:after {
right:-10px;
border-radius: 0 50%;
border-width:0 0 1px 1px;
box-shadow: -1px 1px white;
}
.content {
border:1px solid #aaa;background:#fff;height:200px
}
<ul>
<li><a href="#">tab 1</a></li>
<li class="active"><a href="#">tab2</a></li>
<li><a href="#">tab3</a></li>
<li><a href="#">tab4</a></li>
</ul>
<div class="content"></div>
UPDATE: My previous answer requires more css so I edited it. Based on the answer of jbutler, I got the idea about adding box-shadow to hide the corners. Nothing much changed on the original css I presented here, I just added the box-shadow. Updated fiddle HERE.
A: You can try using a white square block :before and :after the li.active a element, and positioning it so it's between the radius and the li:
ul li.active a:before,
ul li.active a:after {
content: "";
position: absolute;
background-color: white;
height: 11px;
width: 10px;
bottom: -1px;
}
ul li.active a:before {
left: -6px;
z-index: 1;
}
ul li.active a:after {
right: -6px;
background-color: white;
z-index: 6;
}
ul li.active:before {
left:-10px;
border-radius:8px 0;
border-width:0 1px 1px 0;
z-index: 5; // <<< This too
}
ul li.active:after {
right:-10px;
border-radius: 0 8px;
border-width:0 0 1px 1px;
z-index: 10; // <<< And here
}
http://jsfiddle.net/be5ceL9z/4/
This essentially just covers the square bottom corners of the li.active and #content elements by manipulating little square elements to cover them, but to be under the border-radius'd li.active:before and :after.
A more thorough explanation (courtesy atomictom's answer):
https://css-tricks.com/tabs-with-round-out-borders/
A: Here is an example of how this could be achieved with a combination of rotation and box shadows:
Initially, you have your rectangular div/element:
+---------+
| ELEMENT |
+---------+
From that, you can position a pseudo element either side of the bottom corners, with a border radius of 50% (to make a circle)
+---------+
| ELEMENT |
O+---------+O
Because I haven't set a background colour, you won't see this.
I've set a border on both, but then set three of the side colours to 'transparent' (so you only see one border).
Rotating this means that you can make the 'curved corner border' for each side:
+---------+
| ELEMENT |
)+---------+(
Using a box shadow then means you can hide the 'elements bottom corner' anyway:
+---------+
| ELEMENT |
) --------- (
Then setting the bottom border color to the active elelemtn itself means it is then 'hidden' anyway:
+---------+
| ELEMENT |
) ( <-- rotated slightly to create your corner
DEMO
/*FOR DEMO ONLY*/
$(document).ready(function() {
$('.menu div').click(function() {
$('.menu div').removeClass("act");
$(this).addClass("act");
});
});
html {
background: lightgray;
}
.menu div {
display: inline-block;
height: 50px;
width: 100px;
background: white;
margin: 10px;
position: relative;
text-align: center;
border-radius: 10px 10px 0 0;
border: 2px solid black;
cursor:pointer;
}
.menu .act {
border-bottom-color: white;
z-index: 40;
}
.act:before,
.act:after {
content: "";
position: absolute;
bottom: -2px;
height: 20px;
width: 20px;
border-radius: 50%;
border: 2px solid transparent;
z-index: 30;
}
.act:before {
left: 100%;
border-left-color: black;
-webkit-transform: rotate(-40deg);
-moz-transform: rotate(-40deg);
transform: rotate(-40deg);
box-shadow: -20px 2px 0 0 white;
}
.act:after {
right: 100%;
border-right-color: black;
-webkit-transform: rotate(40deg);
-moz-transform: rotate(40deg);
transform: rotate(40deg);
box-shadow: 20px 2px 0 0 white;
}
.panel {
width: 80vw;
margin-top: -12px;
background: white;
border-top: 2px solid black;
z-index: 20;
padding-top: 12px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<div>1</div>
<div class="act">2</div>
<div>3</div>
</div>
<div class="panel">Don't you wish Tabs could just be easy?</div>
Note
the jquery included here is for demo only, and shows how you can 'switch tabs'.
A: I'd just comment but I'm not allowed.. Is this the effect you're after?
https://css-tricks.com/tabs-with-round-out-borders/
Looks like you need another psuedo element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29595989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to convert http.get() to http.post() in angular js? I have following url in http.get() request
var ipaddress ="192.160.0.20";
var name = "root";
var pw ="root";
var loginUrl= "http://" + ipaddress + ":8080/managemind/user.cgi?ACTION=login&LOGIN=" + name + "&PASSWORD=" + pw + "&CLIENT_TYPE=mobile&SUBSCRIBER_ID=NotAssigned&MAC_ADDRESS=NotApplicable";
I am doing the following request using get and getting the response.
$http.get(createdUrl)
.then(function(response) {}
Now I want to convert my get request to post request.How to do ?
A: Use $http.post
$http.post(createdUrl)
.then(function(response) {}
A: When sending vulnerable data with post method it's advised to break apart your query string pass it in the request body. Like this:
var myUrlWithoutQueryString = ... // here goes your url
var loginData = {
name: ...
ps: ...
action ...
// and so on
};
$http.post(myUrlWithoutQueryString, loginData);
Notice that the loginData you're passing should match the parsing requirements in the server-side (matching parameteres for instance).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39072015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How can I write output with javascript? I have created a jsfiddle with a code that is intended to replace a string inside a paragraph with a string stored in a button. As far as I can tell, it's right. But I can't get it to work. Can someone point out my mistake?
<p id="arbitraryIdentification">Product information</p>
<button onclick="document.getElementByID('arbitraryIdentification').innerHTML = 'this text just replaced the original text'">text swaperizer</button>
http://jsfiddle.net/q8x9oupn/1/
A: You need to wrap id in quotes and getElementById (not ID)
http://jsfiddle.net/q8x9oupn/3/
A: Take a look at the function document.getElementById.
Returns a reference to the element by its ID; the ID is a string which
can be used to identify the element
So, your correct code would be:
document.getElementById('unique-key-here')
Source
A: *
*'getElementByID' is supposed to be 'getElementById' ('Id' instead of 'ID')
<button onClick="document.getElementById('arbitraryIdentification').innerHTML = 'this text just replaced the original text'">
</button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34231668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Find all instances of "Replace" but not ".Replace" Due to the unfortunate choice of method naming, this is proving nearly impossible to find an answer to this using SO/Google searches...
TL;DR How can I find all instances of the function Replace( in my application, but not the extension method .Replace(?
Long version: I am converting a large VB.Net app to C#. Within the 250,000 lines of code I know there are usages of the Visual Basic Replace function, in addition to the String.Replace method.
Is it possible to search for Replace, without including occurrences of .Replace? I tagged RegEx as I was hoping that is the way, and had a play about at RegExr, but can't figure it out fully.
Thanks.
A:
How can I find all instances of the function Replace( in my application, but not the extension method .Replace(?
You need to use a regex with a negative lookbehind:
(?<!\.)Replace\(
^^^^^^^
The (?<!\.) lookbehind will invalidate all matches of Replace( that are immediately preceded with a ..
If you want to match Replace( that are only preceded with whitespace, use (?<!\S)Replace\(, the (?<!\S) will require either a whitespace or start of string before Replace(.
Since the ( and . are special regex metacharacters, they must be escaped with \.
See the regex demo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40493480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Insert an Image in a MongoDB database and display it on a webpage using PHP? I am writing some code to display Images on Web page. The next code show data in the web but not the Images. what can I change to show the Images in the web.
<?php
$m = new MongoClient();
$db = $m->selectDB("local");
// Get the users collection
//$c_faq = $db->faq;
// GridFS
$grid = $db->getGridFS();
// The file's location in the File System
$path = "C:\Wamp\Apache\htdocs\knowledge\scripts";
$filename = "\imagen1.png";
// Note metadata field & filename field
$storedfile = $grid->storeFile($path . $filename,
array("metadata" => array("filename" => $filename),
"filename" => $filename));
// Return newly stored file's Document ID
echo $storedfile;
// GridFS
$gridFS = $db->getGridFS();
// Find image to stream
$image = $gridFS->findOne("\imagen1.png");
// Stream image to browser
header('Content-type: imagen.png');
echo $image->getBytes();
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38554854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I simplify 2 methods with only Parameter different? I have 2 methods with exactly same body. Only the second parameter (Class or TypeReference) is different. How can I make one method out of this or at least extract the body so it is not duplicated ?
Thanks.
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
A: This might help you take a look at it. One method will have the functionality while the other methods will act as a helper to use. We cannot ignore the variable 'Class and TypeReference' because it is used in the objectMapper.
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass , TypeReference<T> typeReference) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
if(typeClass != null){
result = objectMapper.readValue(e.getResponseBody(), typeClass);
}else{
result = objectMapper.readValue(e.getResponseBody(), typeReference);
}
} catch (IOException ioException) {
System.out.println("Json Mapper Error : " + ioException);
}
return result;
}
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass) {
return mapResponseBody(e, typeClass, null);
}
public static <T> T mapResponseBody(ApiException e, TypeReference<T> typeReference) {
return mapResponseBody(e, null, typeReference);
}
A: You can change your method with TypeReference where you will transform it in Class and call the other method.
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {
Class<T> typeClass = (Class<T>) TypeFactory.defaultInstance().constructType(type).getRawClass();
return mapResponseBody(e, typeClass);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70020212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Post Variable to PHP script I am unable to post a string to a PHP script by sending it as xmlhttp data.
What I am really trying to do is reading that data which I am sending now as a hard-coded string, from another variable.
What I have now is the following code:
xmlhttp.open("POST", "test.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=testname");
This post requests executes well and the PHP script receives the content of the name parameter ($stringData = $_POST["name"]);
I am trying to replace the 'testname' string with dynamic content from a variable. So
VARIABLE= "someContentNotHardCoded";
xmlhttp.send("name="+ VARIABLE);
but this doesn't seem to work. Is it possible what I am trying to do here, to append/replace the 'testname' string with dynamic content loaded from a variable?
A: This is possible, but with these alterations:
Variables should start with a $ sign and concatenation is done with the . sign:
$variable = "someContentNotHardCoded";
xmlhttp.send("name=".$variable);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46035376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Displaying data from a SQLiteDatabase with adapter Code for the DBHelper class:
class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = Environment.getDataDirectory()
+ "/data/test.data/databases/";
private static final String DATABASE_NAME = "test.sqlite3";
private static final int SCHEMA_VERSION = 1;
public static final String TABLE_NAME = "terran_builds";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_OVERVIEW = "overview";
public SQLiteDatabase dbSqlite;
private final Context myContext;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbExist = DBExists();
if (!dbExist) {
this.getReadableDatabase();
copyDBFromResource();
}
}
private boolean DBExists() {
SQLiteDatabase db = null;
try {
String databasePath = DATABASE_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.setVersion(1);
} catch (SQLiteException e) {
Log.e("SqlHelper", "database not found");
}
if (db != null) {
db.close();
}
return db != null ? true : false;
}
private void copyDBFromResource() {
InputStream inputStream = null;
OutputStream outStream = null;
String dbFilePath = DATABASE_PATH + DATABASE_NAME;
try {
inputStream = myContext.getAssets().open(DATABASE_NAME);
outStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
outStream.flush();
outStream.close();
inputStream.close();
} catch (IOException e) {
throw new Error("Problem copying database from resource file.");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
// TODO Auto-generated method stub
if (dbSqlite != null) {
dbSqlite.close();
}
super.close();
}
public Cursor getTerran() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
COLUMN_OVERVIEW };
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, "name");
return mCursor;
}
public String getName(Cursor c) {
return (c.getString(1));
}
}
Code for the Terran activity:
public class Terran extends Activity {
private DBHelper dbHelp = null;
private Cursor ourCursor = null;
private DBAdapter adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.terran_layout);
// this is our listview element, obtained by id from our xml layout
ListView myListView = (ListView) findViewById(R.id.tvterran);
// create our database helper
dbHelp = new DBHelper(this);
// we call the create right afther initializing helper
dbHelp.createDatabase();
// open the database
dbHelp.openDataBase();
// get our cursor
ourCursor = dbHelp.getTerran();
// tell android to start managing cursor
startManagingCursor(ourCursor);
// create our adapter
adapter = new DBAdapter(ourCursor);
// set the adapter
myListView.setAdapter(adapter);
} catch (Exception e) {
// send real error message
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
class DBAdapter extends CursorAdapter {
DBAdapter(Cursor c) {
super(Terran.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
// TODO Auto-generated method stub
terranHolder holder = (terranHolder) row.getTag();
holder.populateFrom(c, dbHelp);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.terran_layout, parent, false);
terranHolder holder = new terranHolder(row);
row.setTag(holder);
return (row);
}
}
static class terranHolder {
private TextView name = null;
terranHolder(View row) {
name = (TextView) row.findViewById(R.id.tvterran);
}
void populateFrom(Cursor c, DBHelper r) {
name.setText(r.getName(c));
}
}
}
Logcat exception:
01-30 20:07:13.765: E/ERROR(7153): ERROR IN CODE: java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): at com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
01-30 20:07:13.775: W/System.err(7153): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 20:07:13.775: W/System.err(7153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-30 20:07:13.775: W/System.err(7153): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1499)
01-30 20:07:13.775: W/System.err(7153): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-30 20:07:13.775: W/System.err(7153): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:731)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost.setCurrentTab(TabHost.java:403)
01-30 20:07:13.775: W/System.err(7153): at android.widget.TabHost.addTab(TabHost.java:242)
I can't get the ListView to generate from the query results. From my debugging I understand that the error is in the Terran class on line 46. I can't figure out what is wrong. Tested with other database, database connection works.
A: com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
put a break point in and run the debugger. Something is null, and I'm guessing it's the list. It's on like 46.
Btw, I'm gold random player. Used to be high diamond Toss. Good luck with the project.
A: Your ListView is null that means that either don't have a ListView with that id in your layout or android didn't generate the proper id for the list and you have an old one that is incorrect.
Try to refresh the project, delete the R class from the folder gen so that the ID are generated again, restart the IDE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9068956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prolog different variable, same value If you query e.g.
?- X = 10, Y = 10, Z = 10.
The output is
X = Y, Y = Z, Z = 10.
But my X is totally different from Y, they just happen to accidentally both be 10, so it doesn't seem clear/logical to display it that way.
Can i make it look like this instead?:
X = 10, Y = 10, Z = 10.
A: I share your preference. Note that different Prolog systems have different top levels...
SWI-Prolog gives me this:
$ swipl
?- X = 10, Y = 10, Z = 10.
X = Y, Y = Z, Z = 10.
Traella Prolog says something quite similar:
$ tpl
?- X = 10, Y = 10, Z = 10.
X = 10, Y = X, Z = X.
GNU-Prolog and Scryer Prolog, however, give me answers that I like better:
$ gprolog
| ?- X = 10, Y = 10, Z = 10.
X = 10
Y = 10
Z = 10
yes
$ scryer-prolog
?- X = 10, Y = 10, Z = 10.
X = 10, Y = 10, Z = 10.
A: change([H,Q,D,N,P]) :-member(H,[0,1,2]), /* Half-dollars /member(Q,[0,1,2,3,4]), / quarters /member(D,[0,1,2,3,4,5,6,7,8,9,10]) , / dimes /member(N,[0,1,2,3,4,5,6,7,8,9,10, / nickels /11,12,13,14,15,16,17,18,19,20]),S is 50H + 25Q +10D + 5*N,S =< 100,P is 100-S.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74508165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compiling ocaml can't find module in opam library, Js.ml in js_from_ocaml Trying to compile ocaml into javascript.
Some OCaml code I have put in https://gist.github.com/larsr/6b3cd6f62d54d56e3f9a uses the menhir parser, and the js_of_ocaml library together. I've installed them with opam.
The code comes from http://toss.sourceforge.net/ocaml.html.
It is a lexer and a parser and a main program that calls them.
The goal is to generate a javascript program from the ocaml code and run it from within a web page.
I am able to compile the first Main program using only menhir with make from the Makefile in the repo, which does
ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer" Main.native
and I can compile a program that only uses js_of_ocaml, with make Formula.js, which does
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
-syntax camlp4o -linkpkg -o Formula.byte Formula.ml
js_of_ocaml Formula.byte
My problem is that now I'm unable to get ocamlfind to build JsClient.js, with
make JsClient.js
so I can't produce javascript code for 'JsClient.ml'. The error I get is that the compiler can't find the module Js which is used by JsClient. The code seems to be in the opam library in my home-dir, but I can't get the right arguments to ocamlfind to use it.
How do I compile the JsClient.ml into JsClient.js?
A: The rule that you use to compile the JsClient.ml file is not good.
JsClient.byte:
ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer"
As you said, this file use the module Js so you need to compile with the same way than the file Formula.ml :
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
-syntax camlp4o -linkpkg -o JsClient.byte JsClient.ml
js_of_ocaml JSClient.byte
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32760603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why are my classes not found even though my imports are correct? The Classes ADSTool and the Class PPM are not found by my compiler. I'm using Eclipse Helios. The docs say that I have to import java.lang.Object for both, and I imported java.lang*; I can't see why this isn't working.
A:
The docs say that I have to import java.lang.Object for both, and I imported java.lang*
Any documentation that tells you that you have to import classes in java.lang is blatantly wrong. The classes in java.lang are implicitly imported.
In fact, I suspect that your problem is that you need to add the JAR files containing those two classes (ADSTool and PPM) to the build path of your Eclipse project. If the classes are not available on the build path, the Eclipse compiler won't find them.
A: check Project->Properties->Java Build Path
did you include JRE System Library in Libraries Tab?
A: Import java.lang.*, not java.lang*. The second dot matters; without it, the compiler can get confused about what you're actually trying to import.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5406658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to access azure web app console or kudu console locally using putty or mac terminal? I have hosted a web app in azure and I am able to use console through kudu console or azure dashboard but for better development workflow, accessing it through mac terminal is essential.
I don't know how to access azure's web console (not azure server management console) through mac terminal.
Its not linux vm. Its default web app using windows.
A: No, it is not possible.
On Mac, if you want to access Kudu Console, you could use a browser open http://<yoursite>.scm.azurewebsites.net. But you could not do it on mac terminal.
On Mac terminal, you could call Kudu API to manage your web app, see this link.
On Mac terminal, you also could use Azure CLI 2.0 to manage your web app.
A: You're trying to do something web apps are not designed to do. You cannot rdp/ssh into a web app. That's what the kudu web console / powershell is for, if you need a command-line for something.
If you need to move specific app or data content to a web app, it's done through the version control provider you wire up to it (e.g. git), or ftp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47815214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why doesn't OpenSSH work but paramiko does when using ansible playbook? I am running ansible-playbook with
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh
This throws error fatal: [default]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ", "unreachable": true}
However, it works fine after adding connection flag -c paramiko.
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c paramiko
Question: what could be the reasons the default connection (OpenSSH) does not work but paramiko does? How can I debug it and make OpenSSH works too?
I would like to understand the reasons. Please let me know if you need more information other than
*
*local: ubuntu 20.04
*remote: CentOS 7
*ansible [core 2.13.6]
When running with verbose mode
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh -vvv
The output is
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
"class": algorithms.Blowfish,
ansible-playbook [core 2.13.6]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/john/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/john/.local/lib/python3.10/site-packages/ansible
ansible collection location = /home/john/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible-playbook
python version = 3.10.6 (main, Nov 2 2022, 18:53:38) [GCC 11.3.0]
jinja version = 3.1.2
libyaml = True
Using /etc/ansible/ansible.cfg as config file
host_list declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
script declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
auto declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
Parsed /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory inventory source with ini plugin
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.
PLAYBOOK: playbook.yml *************************************************************************************************
1 plays in playbook.yml
PLAY [all] *************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************
task path: /home/john/test/playbook.yml:2
<127.0.0.1> ESTABLISH SSH CONNECTION FOR USER: vagrant
<127.0.0.1> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o Port=2222 -o 'IdentityFile="/home/john/test/.vagrant/machines/default/virtualbox/private_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="vagrant"' -o ConnectTimeout=10 -o 'ControlPath="/home/john/.ansible/cp/055b8f4af0"' 127.0.0.1 '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"''
<127.0.0.1> (255, b'/home/vagrant\n', b'')
fatal: [default]: UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ",
"unreachable": true
}
PLAY RECAP *************************************************************************************************************
default : ok=0 changed=0 unreachable=1 failed=0 skipped=0 rescued=0 ignored=0
A: The command that Ansible is running is returning 255 as the return code, for some reason:
<127.0.0.1> (255, b'/home/vagrant\n', b'')
OpenSSH uses this return code for connection errors but does not prevent remote processes from returning it, and Ansible can't tell the difference between a 255 that is a genuine connection error and whatever happened here.
Paramiko is a Python library and raises errors using native Python error handling, so it doesn't have the same issue.
The only way to get Ansible's OpenSSH plugin working is to figure out why '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"' is returning 255 on your target host, and fix that issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74460537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Return content of read-only Here is the HTML:
<div id="ifld1014" class="ax-terminal-field x20" title="" style="top: 272px;
left: 154px;"><input type="text" maxlength="30" size="30"
class="ax-terminal-inputField ax_x20i" readonly="readonly" style="width: 240px;"></div>
Here is some of my casper code:
var x = require('casper').selectXPath;
....//truncated for shortness//....
casper.echo(x('//*[@id="ifldf14"]/input').value);
The result in undefined. I tried .value, .text, .innerHTML, but they all come up undefined when run. How do I get the content of the input field?
A: DOM context
CasperJS a sandboxed DOM context (page context). It is only there where you can access DOM elements directly. The page context is inside of the casper.evaluate() callback. Everything else about a DOM element is only a representation of it, because DOM nodes cannot be passed to the outside context.
Accessing input value
There are a lot of ways to get information out of the DOM, but DOM nodes cannot be printed to the console as-is. Here are two ways to get the input value.
*
*You can use casper.evaluate(). Since you want to use an XPath expression, you can use __utils__.getElementByXPath() helper function that is injected by CasperJS into the page:
var value = casper.evaluate(function(xpathexpr){
return __utils__.getElementByXPath(xpathexpr).value;
}, '//*[@id="ifldf14"]/input');
casper.echo("value: " + value);
*If the input field is inside of a form and if the element has a name attribute, then you can use casper.getFormValues() and get the value using the name of the field.
casper.echo(casper.getFormValues('form').nameHere);
XPath helper utility
var x = require('casper').selectXPath;
Is only a little helper that transforms a string to an object with the properties type and path. It's only used in CasperJS internally to represent XPaths. The distinction is necessary, because CasperJS supports both CSS selectors and XPath expressions. Both of them are simple strings initially, but are executed differently.
A: The problem was I was not using jQuery to get my value out. Thanks for everyone's input!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30971266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tomcat: not appending trailing "/" when finding a directory I deployed a .war archive in Tomcat 7.0.22 (Java 1.6, MacOS Lion). The war is called "myapp.war" and so Tomcat is serving http://localhost/myapp (having expanded the war in /webapps/myapp). This is the usual behavious
When accessing a url that corresponds to a directory, it should append "/" . For having static files (.css, .js..) working correctly, this is needed, but while with the sample sites that ship with Tomcat this works (for example visiting http://127.0.0.1:8080/examples suddenly remaps to http://127.0.0.1:8080/examples/), on my site tomcat doesn't add any "/" making the search for static files broken. When manually calling localhost:8080/myapp/ (<-- I add the slash) everything works fine.
What should be going on? Mind that I haven't touched any Tomcat setting, I'm just experimenting with what comes out directly from Apache's zip file!
Thanks
A: Firstly you should explain more about your situation. As @mico has told here is a solution:
<filter>
<filter-name>Jersey Filter</filter-name>
<filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>your package name(s)</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
<param-value>.*\.jsp|.*\.css|.*\.png|.*\.js|.*\.gif|.*\.jpg</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Jersey Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The idea on solution based on:
defining Jersey ServletContainer as a filter instead of a servlet
Here you can read more: http://jersey.576304.n2.nabble.com/Tomcat-trailing-slashes-and-welcome-files-td4684494.html
Here says that: If you have a '/*' mapping, then Tomcat won't redirect
One more: you should see how tomcat logs your request and decide the main problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7852396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to use npm installed package in laravel application? I want to use select2 package in my laravel 5 application.
I installed it using npm install select2 and also ran npm run dev. It appears in my node_modules folder.
But how do I actually refer to the files - js and scss of select2 package in my app.blade.php ?
A: I suggest an answer to this thread because it isn't marked as resolved and despite the answer given it didn't allow me to resolve the issue as of the time of reading this.
Resources
*
*select2.org
*npm
I have since found a functional solution of which here are the details in relation to the question of the OP. Verified and working with Laravel 8
*
*Install package via npm
npm install select2
*Edit /resources/js/app.js to import javascript from package
require('./bootstrap');
/* ... */
require('select2'); // Add this
/* ... */
Alpine.start();
*Edit /resources/css/app.css to import styles from package
/* ... */
@import 'select2'; // Add this
*Edit /resources/js/bootstrap.js to enable the use of .select2();
window._ = require('lodash');
/* ... */
window.select2 = require('select2'); // Add this
*Run NPM
npm run dev
npm run watch
*NPM result in my case
Laravel Mix v6.0.39
✔ Compiled Successfully in 2982ms
√ Mix: Compiled successfully in 3.05s
webpack compiled successfully
Testing
According to configuration documentation
HTML
<input type="text" class="form-control js-example-basic-single">
JS
<script type="text/javascript">
$(document).ready(function () {
$('.js-example-basic-single').select2({
placeholder: 'Select2 testing purpose'
});
});
</script>
Render
A: Run npm run watch , because keeps track of all changes in .js.
In app.js add
require('select2/dist/js/select2');
In app.blade.php example:
<div>
<select class="js-select2 css-select2-50">
<option>1</option>
</select>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52402858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to fix error with resource routes definition Here https://laravel.com/docs/5.7/controllers#resource-controllers I read that defining a resource
I had post/put methods :
POST /photos store photos.store
...
PUT/PATCH /photos/{photo} update photos.update
but defining in routes/web.php next resource routes:
Route::resource('site-subscriptions', 'Admin\SiteSubscriptionsController', [ 'except' => [] ] )->middleware('WorkTextString');
with form definition :
<form method="POST" action="http://local-votes.com/admin/site-subscriptions/store" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">
<input type="hidden" name="_token" value="X7rzFjRq4o4TeA67FmkQTMI9ApjygM3ovE1C14i2">
I got error for POST :
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
"file": "/mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 255,
Have I error in my web.php definition error ?
Thanks!
A: if you are working with blade, getting a working link this way is bad, you should use laravel helpers like the following:
<form method="POST" action="{{route('site-subscriptions.store')}}" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">
this way you are making sure that the links are correct even if you change your APP_URL in the deployment.
what actually done, is calling route helper function to get the URL for you by the route's name.
from the docs:
route():
The route function generates a URL for the given named route:
$url = route('routeName');
If the route accepts parameters, you may pass them as the second argument to the method:
$url = route('routeName', ['id' => 1]);
By default, the route function generates an absolute URL. If you wish to generate a relative URL, you may pass false as the third argument:
$url = route('routeName', ['id' => 1], false);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54122748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How To Obtain Monthly Data from Quarterly Data Problem:
I have quarterly level data. I need to perform a month over month analysis. Is there a function, or a ggplot feature that will interpolate the quarterly data and fill in monthly data?
Reference Data:
dput(HPF[1:25, ])
structure(list(region = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), path = c(1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
), date = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), index_value = c(1, 1.033852765, 1.041697122,
1.038876363, 1.041043093, 1.060900982, 1.073728928, 1.075879441,
1.080898915, 1.10368893, 1.119240863, 1.122827602, 1.128639801,
1.15275796, 1.169021733, 1.172707492, 1.178666441, 1.203634882,
1.220348482, 1.223890323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), index = c(0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24), counter = 1:25, BaseQoQ = c(0, 0.033852765, 0.00758749917354051,
-0.00270784947028013, 0.00208564760655761, 0.0190749923163842,
0.0120915582298895, 0.00200284535874973, 0.00466546139717505,
0.0210843166587877, 0.0140908661646175, 0.00320461762840418,
0.00517639483536669, 0.0213692260175751, 0.0141085757499344,
0.00315285755256367, 0.00508136004984272, 0.0211836361259394,
0.0138859385432799, 0.00290231933930496, 0.00480410367620832,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
), fdate = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), StressC = c(0.99749, 1.031342765, 1.039187122,
1.036366363, 1.038533093, 1.058390982, 1.071218928, 1.073369441,
1.078388915, 1.10117893, 1.116730863, 1.120317602, 1.126129801,
1.15024796, 1.166511733, 1.170197492, 1.176156441, 1.201124882,
1.217838482, 1.221380323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), StressQoQ = c(0, 0.0339379492526242,
0.00760596502560418, -0.0027143898728953, 0.00209069888540969,
0.0191210941026796, 0.0121202336548254, 0.00200753827606026,
0.00467637125510434, 0.0211333913794913, 0.0141229845362187,
0.00321182042946733, 0.00518799221722843, 0.021416855302633,
0.0141393626118667, 0.00315964160130755, 0.00509225924746737,
0.021228843485116, 0.0139149560969629, 0.00290830110260876, 0.0068690282969297,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
)), .Names = c("region", "path", "date", "index_value", "index",
"counter", "BaseQoQ", "fdate", "StressC", "StressQoQ"), row.names = c(NA,
-25L), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), vars = "region", drop = TRUE, indices = list(
0:24), group_sizes = 25L, biggest_group_size = 25L, labels = structure(list(
region = 1), row.names = c(NA, -1L), class = "data.frame", vars = "region", drop = TRUE, .Names = "region"))
Any insight would be much appreciated! I hope the data I have provided is enough to offer suggestions.
Goal:
I only need to plot/graph the monthly information, I do not need it reference in a data.frame.
A: So this is what you can do:
1) create a vector of dates to interpolate
months <- lapply(X = data$date, FUN = seq.Date, by = "month", length.out = 3)
months <- data.frame(date = do.call(what = c, months))
2) left join you date.frame to the months data.frame to create NAs for extrapolation
library(dplyr)
monthly_data <- left_join(x = months, y = data, by = "date")
3) use one of na.locf() na.appox() na.spline() to interpolate f.ex StressC
library(zoo)
monthly_data$StressC <- na.spline(object = monthly_data$StressC)
Note: the extrapolations above are
*
*na.locf() - most recent point
*na.appox() - linear
*na.spline() - spline (often used in graphics)
Run the following (before interpolation) to see the difference:
plot(x = monthly_data$StressC, ylab = "StressC", xlab="", xaxt = "n")
lines(x = na.locf(monthly_data$StressC), col = "red")
lines(x = na.approx(monthly_data$StressC), col = "green")
lines(x = na.spline(monthly_data$StressC), col = "blue")
Can also do something like this to get gglot:
ggplot(monthly_data, aes(x=date)) +
geom_point(aes(y = StressC), colour="black") +
geom_line(aes(y = na.locf(StressC)), col="red") +
geom_line(aes(y = na.spline(StressC)), col="red")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49161987",
"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.