text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: PHP contact form issue (Method Not Allowed) PHP CODE
$name_error = $email_error = "";
$name = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
$to = "ayoub.kermout@gmail.com"
$about = "GA:TC CONTACT RECIVED!!"
$body = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message"
mail($to, $about, body, "From: $name <$email>")
$success = "Message sent, thank you for contacting us!";
$name = $email = $message = '';
}
}
?>
JAVASCRIPT CODE
(function($) {
"use strict"; // Start of use strict
// Smooth scrolling using jQuery easing
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - 48)
}, 1000, "easeInOutExpo");
return false;
}
}
});
// Closes responsive menu when a scroll trigger link is clicked
$('.js-scroll-trigger').click(function() {
$('.navbar-collapse').collapse('hide');
});
// Activate scrollspy to add active class to navbar items on scroll
$('body').scrollspy({
target: '#mainNav',
offset: 48
});
// Collapse the navbar when page is scrolled
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
// Scroll reveal calls
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Magnific popup calls
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1]
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
}
});
})(jQuery);
HTML CODE
<div class="container">
<div class="row">
<div class="col-lg-8 mx-auto text-center">
<h2 class="section-heading text-white">CONTACT FORM</h2>
<hr class="light">
<p class="text-faded">Fill the form table down below to contact us.</p>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 text-center">
<h2>Contact</h2>
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<form id="contact-form" class="form" action="mail/contact.php" method="post" role="form">
<div class="form-group">
<label class="form-label" for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your name" tabindex="1" required>
</div>
<div class="form-group">
<label class="form-label" for="email">Your Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" tabindex="2" required>
</div>
<div class="form-group">
<label class="form-label" for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" tabindex="3">
</div>
<div class="form-group">
<label class="form-label" for="message">Message</label>
<textarea rows="5" cols="50" name="message" class="form-control" id="message" placeholder="Message..." tabindex="4" required></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-start-order">Send Message</button>
</div>
</form>
</div>
</div>
</div>
PROBLEM:
As you can see that my PHP, JS, HTML code for the contact form, But for some reason it doesn't work!!??
Every time I try to use it I keep getting (method not allowed)!!!??
I most tried everything (new PHP code different html code)
and note (I'm using it on a site hosted on glitch) it doesn't officially support PHP but it does.
A: I tried you code. It should work except it should be $body instead of body in mail($to, $about, body, "From: $name <$email>");.
So the problem should be from the host provider.
BTW: Gmail seems having more strict security policy. I failed on Gmail and tried another mail service and succeed to receive the email.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48069121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Unhandled Promise rejection: Cannot call method 'push' of null I have an issue I just cannot seem to understand. If anyone could offer some advise I would appreciate it.
I am using Ionic2 with Meteor/Mongo to build a Chat App.
I have the following code:
private findChats(): Promise<Mongo.Collection<Chat>> {
let promise: Promise<Mongo.Collection<Chat>> = new Promise<Mongo.Collection<Chat>>(resolve => {
let registeredIds: String[] = [this.senderId];
for (let i = 0; i < this.jobModelsForSender.length; i++) {
console.log('findChats: registeredIds.push this.jobModelsForSender[i].id: ' + registeredIds + ' - ' + this.jobModelsForSender[i].id);
registeredIds.push('J' + this.jobModelsForSender[i].id);
console.log('findChats: pushed: ' + registeredIds);
}
this.subscribe('chats', this.senderId, registeredIds, () => {
console.log('findChats: in subscribe: ' + this.senderId+' '+registeredIds);
let chats: Mongo.Cursor<Chat> = Chats.find(
{ memberIds: { $in: registeredIds } },
{
sort: { lastMessageCreatedAt: -1 },
transform: this.transformChat.bind(this),
fields: { memberIds: 1, lastMessageCreatedAt: 1 }
}
);
console.log('findChats: chats: ' + chats);
this.chats = chats;
let localChatCollection: Mongo.Collection<Chat> = new Mongo.Collection<Chat>(null);
chats.forEach((chat: Chat) => {
localChatCollection.insert(chat);
});
console.log('findChats: resolve(localChatCollection): ' + localChatCollection);
resolve(localChatCollection);
});
});
return promise;
}
But I get the following output:
findChats: registeredIds.push this.jobModelsForSender[i].id: P8 - 72 app.bundle.js:118232
findChats: pushed: P8,J72 app.bundle.js:118234
findChats: registeredIds.push this.jobModelsForSender[i].id: P8 - 72 app.bundle.js:118232
findChats: pushed: P8,J72 app.bundle.js:118234
findChats: registeredIds.push this.jobModelsForSender[i].id: P8 - 72 app.bundle.js:118232
findChats: pushed: P8,J72 app.bundle.js:118234
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
zone.js:463
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
zone.js:463
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
zone.js:463
findChats: in subscribe: P8 P8,J72 app.bundle.js:118243
findChats: chats: [object Object] app.bundle.js:118249
findChats: resolve(localChatCollection): [object Object]
As you can see, I am getting an error in zone.js. As far as I can see, when I debug this, and as the logs show, it does the push successfully to registeredIds. It then exits the function, returning the promise. After that it goes into zone.js where the error is logged.
A: The answer will probably not be relevant to many people, but as Anton pointed out, that it is an issue to do with the promise loading asynchronously.
I had an event that was calling the same promise at the same time. As soon as I remove the trigger to that event, I don't get any errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39890210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why is my posted data null in the Controller target of this AJAX call? I have modeled (no pun intended) my AJAX call on the answer here from logan filley, which seems sensible and likely to work. This is the jquery I have in the View:
$("#btnSaveConfig").click(function () {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').checked,
scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').checked,
scheduleFillRate: $('#ckbx_fillratebycustomer_location').checked,
schedulePriceCompliance: $('#ckbx_pricecompliance').checked,
// TODO: Finish this by storing add'l emails in an array along with the three on the page;
recipients: $('#email1').val(),
generationDayOfMonth: $('#dayofmonthselect').val(),
generationOrdinal: $('#ordinalselect').val(),
generationDayOfWeek: $('#dayofweekselect').val(),
generationWeekOrMonth: $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: $('#delperffrom').val(),
daterangeToDeliveryPerformance: $('#delperfto').val(),
daterangeFromFillRate: $('#fillratefrom').val(),
daterangeToFillRate: $('#fillrateto').val(),
daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
daterangeToPriceCompliance: $('#pricecomplianceto').val()
}
$.ajax({
type:"POST",
url:'@Url.Action("PostUnitConfig", "SaveConfig")',
async:true,
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(saveConfigModel)
});
}); // $("#btnSaveConfig").click()
...and this is my Model:
public class SaveConfigModel
{
public UnitConfigVals unitConfigVals { get; set; }
public class UnitConfigVals
{
public string unit { get; set; }
public bool scheduleProduceUsage { get; set; }
public bool scheduleDeliveryPerformance { get; set; }
public bool scheduleFillRate { get; set; }
public bool schedulePriceCompliance { get; set; }
public List<string> recipients { get; set; }
public int generationDayOfMonth { get; set; }
public string generationOrdinal { get; set; }
public string generationDayOfWeek { get; set; }
public string generationWeekOrMonth { get; set; }
public int daterangeFromProduceUsage { get; set; }
public int daterangeToProduceUsage { get; set; }
public int daterangeFromDeliveryPerformance { get; set; }
public int daterangeToDeliveryPerformance { get; set; }
public int daterangeFromFillRate { get; set; }
public int daterangeToFillRate { get; set; }
public int daterangeFromPriceCompliance { get; set; }
public int daterangeToPriceCompliance { get; set; }
}
}
...and Controller (obviously ultra-spartan at the moment):
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
{
try
{
string s = model.unitConfigVals.unit;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(new { success = true });
}
}
I am reaching the breakpoint in my Controller (on the "string s = model.unitConfigVals.unit;" line), but it throws an exception because the value of "model" is null. Why? Have I got something in my AJAX call wrong, or...?!?
UPDATE
I changed my jquery to this (changed boolean assignments and appended a semicolon):
$("#btnSaveConfig").click(function() {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').attr('checked'),
scheduleDeliveryPerformance:
. . .
};
$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
//contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ data: saveConfigModel })
});
});
...but the Controller is still passed a null model.
UPDATE 2
Now I changed "attr('checked')" to "is('checked')" but no difference...
UPDATE 3
"model" is null here in the Controller:
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
...when the AJAX call is like this:
$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
dataType: "json",
data: saveConfigModel
});
...and also when the AJAX call is like this:
$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
data: saveConfigModel
});
...and this:
$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
Do I need the "async: true"? I don't use that in my (working) GET AJAX calls. Similarly, do I need "cache: false"? I do use that in those working GET AJAX calls...
UPDATE 4
Even when I provide just some bogus vals:
var saveConfigModel = {
unit: 'Buford', //$('#unitsselect').val(),
scheduleProduceUsage: true, //$('#ckbx_produceusage').is(':checked'),
scheduleDeliveryPerformance: false, // $('#ckbx_deliveryperformance').is(':checked'),
scheduleFillRate: false, //$('#ckbx_fillratebycustomer_location').is('checked'),
schedulePriceCompliance: false, //$('#ckbx_pricecompliance').is('checked'),
// TODO: Finish this by storing add'l emails in an array along with the three on the page; might be as easy as declaring an array like this one, and adding to it as necessary
recipients: 'platypus@whatever.com', // $('#email1').val(),
generationDayOfMonth: '2nd', //$('#dayofmonthselect').val(),
generationOrdinal: 'First', //$('#ordinalselect').val(),
generationDayOfWeek: 'Thursday', // $('#dayofweekselect').val(),
generationWeekOrMonth: 'month', // $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: '1', // $('#delperffrom').val(),
daterangeToDeliveryPerformance: '1', //$('#delperfto').val(),
daterangeFromFillRate: '1', //$('#fillratefrom').val(),
daterangeToFillRate: '1', //$('#fillrateto').val(),
daterangeFromPriceCompliance: '1', //$('#pricecompliancefrom').val(),
daterangeToPriceCompliance: '1' //$('#pricecomplianceto').val()
};
...it still winds up at the Controller null like forevermore before.
And then, grasping at straws, I even encased the boolean values in single quotes ('true' and 'false'), but that also (probably predictably) made no difference either.
UPDATE 5
For future generations, this is the AJAX that works:
$.ajax({
type: "POST",
url: '@Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
A: Since the values you posting back are for your nested UnitConfigVals class (not SaveConfigModel, then you controller method should be
public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model)
and the ajax data option needs to be
data: JSON.stringify({ model: saveConfigModel })
Alternatively you could keep the current controller method and use
data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }})
although it seems a little odd that you using a nested class here.
A few other issues with your initial code
*
*$('#ckbx_produceusage').checked will return undefined, and it
needs to be $('#ckbx_produceusage').is(':checked') which will
return true or false
*Since recipients is List<string>, it will need to be
recipients: [ 'someValue', 'anotherValue', etc ]
However all this code to build you json data not really necessary, and if your view is generated correctly using the strongly typed HtmlHelper methods, then your ajax call can be as simple as
$.ajax({
type:"POST",
url:'@Url.Action("PostUnitConfig", "SaveConfig")',
dataType: "json",
data: $('form').serialize(),
success: function(data) {
// do something
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36948092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: qDebug output in qtCreator while running unit tests with catch2 I have a project with unittests which are implemented with catch2 and using the catch2-integration in qtcreator. The unittests contain qDebug()<<"message" calls. The project uses CMAKE as build system. Everything compiles and I can both run the tests as standalone application and with the interface (i.e. "run selected tests") in qtcreator. Currently it is compiled in debug-mode.
However, when running in a terminal, I get all qDebug messages.
If I'm running the main application (not the unit tests), I can observe qDebug messages in the "Application output" tab.
However, if I'm running the unit tests, no matter if I use qtCreator interface or start debugging or run the compiled tests, the "Application output" stays empty.
As stated above, I'm able to see them in a terminal, but then I only can run the full test suite, while I would hope to be able only to run selected tests and get their output.
What needs to be in place that the qDebug messages which originate from catch2 unittests in qtcreator are displayed in the "Application Output" tab during test execution?
QtCreator 7.0.0, Windows, MSVC2019, 64Bit.
Amongst others I already tried (without luck): QtCreator: qDebug Messages Not Shown
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73418504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c/c++ clang linking error on Mac OSX - webkitgtk I am trying to use GTK3 and WebKitGTK. I am successful at running the following code :
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>
#include <JavaScriptCore/JavaScript.h>
using namespace std;
static void destroyWindowCb(GtkWidget* widget, GtkWidget* window);
static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window);
int main(int argc, char* argv[])
{
// Initialize GTK+
gtk_init(&argc, &argv);
// Create an 800x600 window that will contain the browser instance
GtkWidget *main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(main_window), 800, 600);
// Create a browser instance
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
// Put the browser area into the main window
gtk_container_add(GTK_CONTAINER(main_window), GTK_WIDGET(webView));
// Set up callbacks so that if either the main window or the browser instance is
// closed, the program will exit
g_signal_connect(main_window, "destroy", G_CALLBACK(destroyWindowCb), NULL);
g_signal_connect(webView, "close", G_CALLBACK(closeWebViewCb), main_window);
// Load a web page into the browser instance
webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/");
// Make sure that when the browser area becomes visible, it will get mouse
// and keyboard events
gtk_widget_grab_focus(GTK_WIDGET(webView));
// Make sure the main window and all its contents are visible
gtk_widget_show_all(main_window);
// Run the main GTK+ event loop
gtk_main();
return 0;
}
static void
destroyWindowCb(GtkWidget* widget, GtkWidget* window)
{
gtk_main_quit();
}
static gboolean
closeWebViewCb(WebKitWebView* webView, GtkWidget* window)
{
gtk_widget_destroy(window);
return TRUE;
}
And the following cmake list :
cmake_minimum_required(VERSION 3.3)
project(HttpsMock)
# Use the package PkgConfig to detect GTK+ headers/library files
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
pkg_check_modules(WEBKIT REQUIRED webkitgtk-3.0)
# Setup CMake to use GTK+, tell the compiler where to look for headers
include_directories(${GTK3_INCLUDE_DIRS})
include_directories(${WEBKIT_INCLUDE_DIRS})
# and to the linker where to look for libraries
link_directories(${GTK3_LIBRARY_DIRS})
link_directories(${WEBKIT_LIBRARY_DIRS})
# Add other flags to the compiler
add_definitions(${GTK3_CFLAGS_OTHER})
add_definitions(${WEBKIT_CFLAGS_OTHER})
# Flags and source
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -v")
set(SOURCE_FILES main.cpp)
add_executable(HttpsMock ${SOURCE_FILES})
# Linking
target_link_libraries(HttpsMock ${GTK3_LIBRARIES})
target_link_libraries(HttpsMock ${WEBKIT_LIBRARIES})
But as soon as I try to use another method like :
WebKitURIRequest *request = webkit_uri_request_new("http://www.webkitgtk.org/");
The program doesn't want to link anymore. It's really weird. Here's a sample of the error :
[100%] Linking CXX executable HttpsMock
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.10.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -o HttpsMock -L/opt/local/lib -search_paths_first -headerpad_max_install_names CMakeFiles/HttpsMock.dir/main.cpp.o -lwebkitgtk-3.0 -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpangoft2-1.0 -lpango-1.0 -lm -lfontconfig -lfreetype -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lsoup-2.4 -lgio-2.0 -lgobject-2.0 -ljavascriptcoregtk-3.0 -lglib-2.0 -lintl -rpath /opt/local/lib -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.0/lib/darwin/libclang_rt.osx.a
Undefined symbols for architecture x86_64:
"_webkit_uri_request_new", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
I really have no clue of what is going on. Could someone please enlighten me?
Thanks
A: The problem is that I was using
pkg_check_modules(WEBKIT REQUIRED webkitgtk-3.0)
instead of
pkg_check_modules(WEBKIT REQUIRED webkit2gtk-3.0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32875266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Batch CompositeItemWriter How to properly set writer delegates Hi I am trying to add two writers to a spring batch compositeitemwriter. I am getting an error saying:
The method setDelegates(List<ItemWriter<? super MyObject>>) in the type CompositeItemWriter<MyObject> is not applicable for the arguments (List<ItemWriter<MyObject>>)
My code below
public ItemWriter<MyObject> myWriter(){
ItemWriter<MyObject> myWriter = new myWriter();
return myWriter;
}
public ItemWriter<MyObject> myOtherWriter(){
ItemWriter<MyObject> myOtherWriter = new MyOtherWriter();
return myOtherWriter;
}
public CompositeItemWriter<MyObject> compositeItemWriter(){
CompositeItemWriter<MyObject> writer = new CompositeItemWriter<MyObject>();
List<ItemWriter<MyObject>> writerList = new ArrayList<ItemWriter<MyObject>>();
writerList.add(myWriter());
writerList.add(myOtherWriter());
writer.setDelegates(writerList); //<-- ERROR HERE
return writer;
}
I could not find any strong code examples of compositeitemwriters that did not use xml. I know my error has something to do with generic type parameters, which I have little knowledge of. Could anyone explain why the above code would not work and possibly how to remedy it? Multiple itemwriters in Spring batch This is the closest I could find, but it uses generic types which also give me an error.
Thank you for any help! I am new to spring batch.
A: Try modifying...
List<ItemWriter<MyObject>> writerList = new ArrayList<ItemWriter<MyObject>>();
...with :
List<ItemWriter<? super MyObject>> writerList = new ArrayList<ItemWriter<? super MyObject>>();
CompositeItemWriter#setDelegates takes a list in the form List<ItemWriter<? super T>>.
See spring documentation.
A: Just in case you did not find a proper solution.
I would do it like this:
public ItemWriter<MyObject> myWriter() {
ItemWriter<MyObject> myWriter = new JdbcBatchItemWriter<MyObject>(); // <-- Example item writer 1
return myWriter;
}
public ItemWriter<MyObject> myOtherWriter() {
ItemWriter<MyObject> myOtherWriter = new JdbcBatchItemWriter<MyObject>(); // <-- Example item writer 2
return myOtherWriter;
}
public CompositeItemWriter<MyObject> compositeItemWriter() {
CompositeItemWriter<MyObject> writer = new CompositeItemWriter<MyObject>();
writer.setDelegates(Arrays.asList(myWriter(),myOtherWriter())); //<-- NO ERROR HERE :)
return writer;
}
I hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45358029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I implement a decay for a matrix transformation with react-native-gesture-handler and reanimated? I'm trying to learn react-native-gesture-handler and react-native-reanimate. I like the idéa of using matrices for transformation, but I have a hard time understanding where to fit in physics functions, such as withDecay.
I want to use the new Gestures API (https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/gesture) instead of the old gestureHandler API (https://docs.swmansion.com/react-native-gesture-handler/docs/gesture-handlers/api/common-gh)
Here is a nice example of using matrices for transformation and simply multiplying the change-matrice with the current matrice.
https://github.com/wcandillon/can-it-be-done-in-react-native/blob/master/bonuses/sticker-app/src/GestureHandler.tsx
This concept works great, but I also want to have a decay effect after ending a pan, i.e. the translation should continue to glide a bit.
Here is my first attempt. It does not work, and might be a bit naive. But I think that the code shows what I want to do. I just don't know how to do it correctly. My attempt was to add the .onEnd event, compared to Williams Candillon's original code.
const pan = Gesture.Pan()
.onChange(e => {
matrix.value = multiply4(
Matrix4.translate(e.changeX, e.changeY, 0),
matrix.value,
);
})
.onEnd(({velocityX, velocityY}) => {
matrix.value = multiply4(
Matrix4.translate(
withDecay({velocity: velocityX}),
withDecay({velocity: velocityY}),
0,
),
matrix.value,
);
});
A: the problem here is the withDecay returns an animation value (it auto update). So the idea would be to do trX.value = withDecay(), same of y and then use useDerivedValue to get the total Matrix4. I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73978353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot Remove Underline From Vue router-link I think I tried almost everything trying to remove underline from router-link.
This is my code:
<router-link :to="{name: 'Plan'}">
<div>Plan Your Trip</div>
<div class='expander'>
<router-link :to="{name: 'Plan'}">COVID-19</router-link>
<router-link :to="{name: 'Plan'}">Visa</router-link>
<router-link :to="{name: 'Plan'}">Essentials</router-link>
</div>
</router-link>
I'm trying to remove underline from sub-links only.
Things I've tried:
In-line style
<router-link style="text-decoration: none !important;" :to="{name: 'Plan'}">COVID-19</router-link>
Assign class
<router-link class="sub-link" :to="{name: 'Plan'}">COVID-19</router-link>
<style scoped>
.sub-link{text-decoration: none !important;}
</style>
Declare tag
<router-link tag="div" :to="{name: 'Plan'}">COVID-19</router-link>
<style scoped>
div{text-decoration: none !important;}
</style>
Assign seperate tag + Declare class for that tag
<router-link :to="{name: 'Plan'}">
<div class="sub-link">COVID-19</div>
</router-link>
These are just few lists, I literally tried every possible methods I can think of... Am I missing something about customizing Vue router-link?
A: Uses display: inline-block;text-decoration:none;, the trick is display: inline-block;.
Css spec states
For block containers that establish an inline formatting context, the
decorations are propagated to an anonymous inline element that wraps
all the in-flow inline-level children of the block container. For all
other elements it is propagated to any in-flow children. Note that
text decorations are not propagated to floating and absolutely
positioned descendants, nor to the contents of atomic inline-level
descendants such as inline blocks and inline tables.
Example: The link COVID-19 in your codes will remove the underline.
<router-link :to="{name: 'Plan'}">
<div>Plan Your Trip</div>
<div class='expander'>
<router-link :to="{name: 'Plan'}" style="display: inline-block;text-decoration:none;">COVID-19</router-link>
<router-link :to="{name: 'Plan'}">Visa</router-link>
<router-link :to="{name: 'Plan'}">Essentials</router-link>
</div>
</router-link>
Below is one demo:
let Layout = {
template: `<div>
<h4>Layout Page </h4>
<router-link to="/contact">
<div>
<p>Links<p>
<router-link to="/contact/add" style="display: inline-block;text-decoration:none;">Add1</router-link>
<router-link to="/addcontact">Add2</router-link>
</div>
</router-link>
<router-view></router-view>
</div>`
};
let Home = {
template: '<div>this is the home page. Go to <router-link to="/contact">contact</router-link> </div>'
};
let ContactList = {
// add <router-view> in order to load children route of path='/contact'
template: '<div>this is contact list, click <router-link to="/contact/add">Add Contact In sub Router-View</router-link> here to add contact<p><router-view></router-view></p> Or Click <router-link to="/addcontact">Add Contact In Current Router-View</router-link></div>'
};
let ContactAdd = {
template: '<div>Contact Add</div>'
}
let router = new VueRouter({
routes: [{
path: '/',
redirect: 'home',
component: Layout,
children: [{
path: 'home',
component: Home
},
{
path: 'contact',
component: ContactList,
children: [{
path: 'add',
component: ContactAdd
}]
},
{
path: 'addcontact', // or move ContactAdd as direct child route of path=`/`
component: ContactAdd,
}
]
}]
});
new Vue({
el: '#app',
components: {
'App': {
template: '<div><router-view></router-view></div>'
},
},
router
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.0.1/dist/vue-router.js"></script>
<section id="app">
<app></app>
</section>
A: When you inspect the DOM for a router-link, you see that it's an a tag. Bear in mind, that even when the initial underline is removed, there is an underline that happens when you hover over the router link text.
Using this snippet
<router-link :to="{name: 'Plan'}">
<div>Plan Your Trip</div>
<div class='expander'>
<router-link :to="{name: 'Plan'}">COVID-19</router-link>
<router-link :to="{name: 'Plan'}">Visa</router-link>
<router-link :to="{name: 'Plan'}">Essentials</router-link>
</div>
</router-link>
.expander a {
text-decoration: none;
}
.expander a:hover {
text-decoration: none;
}
A: The outer router-link is applying text-decoration: underline to its inner-text and the inner router-links are also applying text-decoration: underline to their inner-text.
You essentially have double underlines applied to your inner router-links at the moment.
You need to remove it from both. If you need another element to have text-decoration: underline then set it for that element separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63526678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery ui Slider for Background and Font Colors I have a problem regarding my new site design prospect, and it involves using some jQuery and jQueryUI (mainly SliderUi) and some css manipulation.
Everytime I slide the #slider, the width of .left will then update depend on (ui.value from 1-100 + '%'), from here slide + background transition is happening already,
My question is is there any possible way to manipulate the color of texts depending on slider's treshold or value? if yes, can you suggest how can I come up into something like this?
Snippet below.
Thanks in advance!
$(document).ready(function() {
$( "#slider" ).slider({
max: 101,
min:1,
value: 51,
slide: function(event,ui) {
var percentage = (ui.value)-1;
$('.left').css("width",percentage +'%');
}
});
});
#slider {z-index: 5;background: #666; }
.left, .right {positioackgrn:absolute; top: 0; left: 0; height: 100vh;}
.left {background: #000; width: 50%; z-index: 1;}
.right {background: #fff; z-index: -1; width: 100%;}
.main-content {z-index: 3; position: absolute; top: 0; left: 0; width: 100%;}
h3 {color: blue; text-align: center; margin-top: 30px;}
<link href="https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<div id="slider"></div>
<div class="left"></div>
<div class="right"></div>
<div class="main-content">
<h3>A part of my font must change color depending on slider-ui threshold</h3>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
A: Update!
http://jsfiddle.net/lsubirana/7od3sfrr/1/
HTML:
<div id="slider"></div>
<div class="left"><h3>My font color must change depending on slider-ui threshold</h3></div>
<div class="right"><h3>My font color must change depending on slider-ui threshold</h3></div>
CSS:
.left, .right {position:absolute; top: 0; left: 0; height: 100vh;overflow:hidden;}
.left h3 {color: white; text-align: center; margin-top: 30px;width:100vw;}
.right h3 {color: black; text-align: center; margin-top: 30px;width:100vw;}
Original Answer:
One method to obtain what you are looking for is to pass the slider percentage to a function that can return you an rgb color value. The following page shows how to create rainbows in javascript and I believe can be applied in this case:
http://krazydad.com/tutorials/makecolors.php
$(document).ready(function() {
$( "#slider" ).slider({
max: 101,
min:1,
value: 51,
slide: function(event,ui) {
var percentage = (ui.value)-1;
$('.left').css("width",percentage +'%');
$('h3').css('color', rgb(percentage));
}
});
});
function rgb(p){
var frequency = .08;
r = Math.sin(frequency*p + 0) * 127 + 128;
g = Math.sin(frequency*p + 2) * 127 + 128;
b = Math.sin(frequency*p + 4) * 127 + 128;
return 'rgb(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ')';
}
http://jsfiddle.net/lsubirana/376ow969/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26851439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Extract fields from Json using Kusto in Application Insights I have the following json contained in a particular field in the traces.customDimensions:
When I parse this Json to extract a particular value I always get an empty column, for example:
traces | order by timestamp desc
| project CurrentContext = parse_json(customDimensions.CurrentPluginContext)
| extend Source = CurrentContext.source
| project Source
The query returns the following:
I've also tried:
traces | order by timestamp desc
| project timestamp, CurrentContext = customDimensions.CurrentPluginContext, CurrentParentContext = customDimensions.CurrentParentluginContext,
Source = parse_json(tostring(customDimensions.CurrentPluginContext)).source,
DepthCurrentContext = parse_json(tostring(customDimensions.CurrentPluginContext)).depth,
DepthCurrentParentContext = parse_json(tostring(customDimensions.CurrentParentluginContext)).depth
| mv-expand CurrentContext
| extend Source = CurrentContext.source
But here I get also an empty "Source" column. And the Columns "DepthCurrentContext" and "DepthCurrentParentContext" do not even appear.
The Json is valid.
Do I miss something here?
Any help is very appreciated!
UPDATE 27.02.2023
When I do the following:
let json = '{"source": "GetUserData","correlationId": "00000000-0000-0000-0000-000000000000","depth": "1","initiatingUserId": "00000000-0000-0000-0000-000000000000","isInTransaction": "False","isolationMode": "2","message": "Update","mode": "Asynchronus","operationId": "00000000-0000-0000-0000-000000000000","orgId": "00000000-0000-0000-0000-000000000000","orgName": "unqXXXXXXXXXXXXXXXXXXXX","requestId": "00000000-0000-0000-0000-000000000000","userId": "00000000-0000-0000-0000-000000000000","entityId": "00000000-0000-0000-0000-000000000000","entityName": "systemuser","type": "Plugin","stage": "Post-operation"}';
traces
| extend properties = parse_json(json)
| project Source = properties.source, CorrelationID = properties.correlationId
I get the properties out of the Json. The Json is the exact same as the ohne from the log.
Any idea?
A: as mentioned in the documentation: you will need to use tostring on the internal property bag.
i.e. parse_json(tostring(parse_json(customDimensions).CurrentPluginContext))
A: traces | order by timestamp desc
| project CurrentContext = parse_json(customDimensions.CurrentPluginContext)
| extend Source = parse_json(tostring(CurrentContext)).source
| project Source
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75577446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: getting sql error unknown column in where clause when trying to filter data In the SQL query where city clause when I put string 'delhi' I get results but when I put a variable like below I get error unknown column delhi in where clause. how to solve the issue?
router.get('/filter/:city', (req, res) => {
const location = req.params.city;
const singleQuoteLocation = location.replace(/"/g, "'");
connection.query(
`select * from weather_data where city=${singleQuoteLocation}`,
(err, results, field) => {
if (err) {
console.log(err);
} else {
res.status(200).send(results);
console.log(results);
}
}
);
});
A: You should be using a prepared statement with a ? placeholder for the city value. Then, bind a JS variable to the ?.
router.get('/filter/:city', (req, res) => {
const location = req.params.city;
connection.query(
"SELECT * FROM weather_data WHERE city = ?", [location],
(err, results, field) => {
if (err) {
console.log(err);
}
else {
res.status(200).send(results);
console.log(results);
}
}
);
});
Note that when using a prepared statement there is no need to massage the location variable by doing things like wrapping in single quotes. Instead, let your MySQL driver worry about how to handle this, via the prepared statement.
A: `select * from weather_data where city = \'${singleQuoteLocation}\' `
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70470296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to stretch table within a cell (nested table) in html? Nested table does not 100% height of parent td
I have used height="100%" but did not help
HTML:
<table width="50%" border="1" align="center">
<tbody>
<tr>
<td valign="top">
<table border="1" align="center" width="100%">
<tbody>
<tr>
<td align='center'>
<p>Text</p>
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top">
<table border="1" align="center" width="100%">
<tbody>
<tr>
<td align='center'>
<p>Text</p>
<p>Text</p>
<p>Text</p>
<p>Text</p>
<p>Text</p>
<p>Text</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Actual result: https://jsfiddle.net/fela93/8ysfawve/17/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58569565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the most efficient way to find rows of a CSV not containing duplicate entries across the fields of that row (excluding blank entires)? I'm looking to find all of the rows of a CSV file that contain the duplicate data in two or more of the fields of that row (i.e. find all of the rows without unique data in each field.)
For example, I have the following CSV file:
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21
I would want the following rows to be printed:
John,Smith,Smith,21
John,42,42,42
These rows are printed because a the data in one field of these rows occurs in another field. Note that "Mary,,,21" was not printed even though it has duplicate empty fields.
I could write a Python script and keep a count of the times each entry occurs in each row, but it seems like there must be a better way to do this.
A: Using perl:
perl -F, -lane 'my %s; print if grep { $s{$_}++ } @F'
Uses:
*
*-F, to set field separator to ,
*-l to automatically handle linefeeds
*-a to autosplit
*-n to wrap it in a while ( <> ) { loop.
*-e to specify code to exec.
Incoming data is autosplit on , into @F and we use a %s hash to spot if there's a dupe.
If — based on your comment — you need to skip empty fields (which this would count as dupes):
perl -F, -lane 'my %s; print if grep { /./ ? $s{$_}++ : () } @F'
This includes a ternary operator to test if a field is empty.
Testing with Windows (which isn't quite the same, because of quotes):
C:\Users\me>perl -F, -lane "my %s; print qq{line matches:$_} if grep { /./ ? $s{$_}++ : () } @F"
line matches:John,Smith,Smith,21
line matches:John,42,42,42
If written longhand, it looks more like this:
#!/usr/bin/env perl
use strict;
use warnings;
while ( my $line = <DATA> ) {
my %seen;
chomp($line);
my @fields = split /,/, $line;
if ( grep { /./ and $seen{$_}++ } @fields ) {
print $line,"\n";
}
}
__DATA__
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21
You could use the Text::CSV module to parse it, but I would suggest not doing so, unless you're specifically dealing with quoting/embedded linefeeds etc.
E.g.:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Text::CSV;
my $csv = Text::CSV -> new ( {sep_char => ',', eol => "\n", binary => 1} );
while ( my $row = $csv -> getline ( \*DATA ) ) {
my %seen;
if ( grep { /./ and $seen{$_}++ } @$row ) {
print join ",", @$row, "\n";
}
}
__DATA__
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21
A: Using awk you can do:
awk -F, '{delete a; for (i=1;i<=NF;i++) if ($i!="") if ($i in a) {print; next} else a[$i]}' file
John,Smith,Smith,21
John,42,42,42
A: $ awk -F, '{delete seen; for (i=1;i<=NF;i++) if ( ($i!="") && seen[$i]++ ) { print; next } }' file
John,Smith,Smith,21
John,42,42,42
A: If you'd like a Perl solution that you can integrate into a larger script (and doesn't quite so closely resemble line noise), and that correctly handles CSV data where a field contains a comma, I'd use the Text::CSV module:
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $file = shift or die "Usage: $0 <file>\n";
open my $fh, '<', $file or die "Cannot open $file: $!\n";
my $csv = Text::CSV->new();
while (my $row = $csv->getline($fh)) {
my %h;
$h{$_}++ for @{$row};
for my $dup_field (grep { $h{$_} > 1 } keys %h) {
if (length $dup_field) {
print $csv->string();
next;
}
}
}
A: If you like perl and regex, then this looks good :
perl -ne 'print if /(?:^|,)([^,]+),(?:.*,)?\1(?:,|$)/'
If you need explanations :
([^,]+) matches a "word" (in that context, I use "word" to mean "the data of a row"), and \1 will see if it is repeated. (?:.*,)? allows other words to be between the repetitions of your data. And finally (?:^|,) and (?:,|$) ensure that the 2 repeated words are the same, and no one is a substring of the other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37054597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to implement level order print for MaxHeap I'm currently making a MaxHeap program and I need to print my heap in level order. How can this be done? Do I create a method to print the heap in level order inside of my heap class or would I do it in my main class? I know for like my binary search tree project i used iterative methods and called them from my main class but I'm not sure if I can do that here. Below is my implementation of the MaxHeap class from my textbook:
public final class MaxHeap<T extends Comparable<? super T>> implements MaxHeapInterface<T>
{
private T[] heap;
private int lastIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
int swaps=0;
public MaxHeap() {
this(DEFAULT_CAPACITY);
}
public MaxHeap(int initialCapacity) {
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else
checkCapacity(initialCapacity);
@SuppressWarnings("unchecked")
T[] tempHeap = (T[]) new Comparable[initialCapacity + 1];
heap = tempHeap;
lastIndex = 0;
initialized = true;
}
public T getMax() {
checkInitialization();
T root = null;
if (!isEmpty())
root = heap[1];
return root;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55802947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Unescape a JavaScript string in Ruby What is the simplest way to unescape the following string in Ruby.
Sample Input
str = "\\u003Cul id=\\\"list_example\\\"\\u003E\\n\\t\\u003Cli class=\\\"item_example\\\"\\u003EHello\\u003C/li\\u003E\\n\\u003C/ul\\u003E\\n\\n"
puts str # => \u003Cul id=\"list_example\"\u003E\n\t\u003Cli class=\"item_example\"\u003EHello\u003C/li\u003E\n\u003C/ul\u003E\n\n
str.encoding # => #<Encoding:UTF-8>
Desired Output
puts str #=>
<ul id="list_example">
<li class="item_example">Hello</li>
</ul>
A: The simplest approach is just to read the string as a JSON string.
unescaped_str = JSON.load("\"#{str}\"")
A: That string is escaped twice. There are a few ways to unescape it. The easiest is eval, though it is not safe if you don't trust the input. However if you're sure this is a string encoded by ruby:
print eval(str)
Safer:
print YAML.load(%Q(---\n"#{str}"\n))
If it was a string escaped by javascript:
print JSON.load(%Q("#{str}"))
See also Best way to escape and unescape strings in Ruby?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22772241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 'future_to_publish' hook not working in wordpress I'm trying to save data to a file when a scheduled post is published. I tried to do this using the hooks 'future_to_publish', 'publish_future_post', 'transition_post_status' - none of them worked for me. I experimented with changing the priority of the hooks - didn't work either.
This is my code:
<?php
function savePostData( $ID ) {
$wpRootPath = get_home_path();
$postsDataPath = $wpRootPath . 'test.txt';
$handle = fopen( $postsDataPath, "w" );
fwrite( $handle, $ID );
fclose( $handle );
}
add_action( 'future_to_publish', 'savePostData', 10, 1 );
?>
When attaching the same function to the following hooks everything works:
add_action( 'publish_post', 'savePostData', 10, 1 );
add_action( 'pending_to_publish', 'savePostData', 10, 1 );
add_action( 'draft_to_publish', 'savePostData' );
I read there is some problem with the is_admin() function interfering with the wordpress cron job, but, still, I cannot get this to work.
A: It turned out when a post is published with cron, 'publish_post' hook is also executed and I didn't need to use it together with the 'future_to_publish' hook.
The problem with both hooks, however, was that for some reason get_home_path(); does not work in the same way as when the post is published immediately from admin panel, so using the exact path to my file solved the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37520367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Downloading a Nested DT table in Shiny I've got a nested DT table in my Shiny app. The child table is a list that gets passed and rendered into the table. When I go to add a download button via DT's built in method, the output contains the parent table data and then a list of [Object][Object].. instead of the actual child data.
Do I have to write my own downloadable button method instead of using DT's method or is there a original DT method that helps with this? Haven't found a solution yet.
Data
Parent
structure(list(Market = c("ABILENE, TX", "AKRON, OH"), `SQAD CPP ($)` = c(10,
49), `SQAD CPM ($)` = c(22, 30), `Override CPP ($)` = c(0, 0),
`Override CPM ($)` = c(0, 0)), .Names = c("Market", "SQAD CPP ($)",
"SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)"), row.names = c(NA,
-2L), class = "data.frame")
Child
structure(list(Market = c("ABILENE, TX", "ABILENE, TX", "ABILENE, TX",
"ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX",
"ABILENE, TX", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH",
"AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH"
), Daypart = c(" Podcast", " Streaming/Digital Audio", "Afternoon Drive",
"Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive",
"Weekend", " Podcast", " Streaming/Digital Audio", "Afternoon Drive",
"Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive",
"Weekend"), `Mix (%)` = c(10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L, 10L), `Spot:60 (%)` = c(4,
4, 4, 4, 4, 4, 2, 6, 4, 4, 4, 4, 4, 4, 4, 2, 6, 4), `Spot:30 (%)` = c(6,
6, 6, 6, 6, 6, 3, 9, 6, 6, 6, 6, 6, 6, 6, 3, 9, 6), `SQAD CPP ($)` = c(10,
6, 27, 31, 44, 32, 31, 26, 26, 34, 21, 170, 156, 112, 151, 136,
177, 95), `SQAD CPM ($)` = c(21, 13, 57.6, 64.8, 93.6, 68.4,
64.8, 54, 54, 21, 13, 104.5, 96.1, 69, 93, 83.6, 108.7, 58.5),
`Override CPP ($)` = c(10, 6, 27, 31, 44, 32, 31, 26, 26,
34, 21, 170, 156, 112, 151, 136, 177, 95), `Override CPM ($)` = c(21,
13, 57.63, 64.83, 93.64, 68.43, 64.83, 54.03, 54.03, 21,
13, 104.49, 96.13, 68.96, 92.99, 83.59, 108.67, 58.51), population = c(47200L,
47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L,
162700L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L,
162700L, 162700L), slider_60s = c(0.4, 0.4, 0.4, 0.4, 0.4,
0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4,
0.4), slider_30s = c(0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6,
0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6)), .Names = c("Market",
"Daypart", "Mix (%)", "Spot:60 (%)", "Spot:30 (%)", "SQAD CPP ($)",
"SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)", "population",
"slider_60s", "slider_30s"), class = "data.frame", row.names = c(NA,
-18L))
Code
# Bind the market level and mix breakout data together for the final table
market_mix_table <- reactive({
# Take a dependency on input$goButton
input$goButton
isolate({
markets <- market_costings_gross_net()
mix_breakout <- mix_breakout_digital_elements()
# Make the dataframe
# This must be met length(children) == nrow(dat)
Dat <- NestedData(
dat = markets,
children = split(mix_breakout, mix_breakout$Market)
)
return(Dat)
})
})
# Render the table
output$daypartTable <- DT::renderDataTable({
Server = FALSE
# Whether to show row names (set TRUE or FALSE)
rowNames <- FALSE
colIdx <- as.integer(rowNames)
# The data
Dat <- market_mix_table()
parentRows <- which(Dat[,1] != "")
callback_js = JS(
"var ok = true;",
"function onUpdate(updatedCell, updatedRow, oldValue) {",
" var column = updatedCell.index().column;",
" if(column === 8){",
" ok = false;",
" }else if(column === 7){",
" ok = true;",
" }",
"}",
sprintf("var parentRows = [%s];", toString(parentRows-1)),
sprintf("var j0 = %d;", colIdx),
"var nrows = table.rows().count();",
"for(var i=0; i < nrows; ++i){",
" if(parentRows.indexOf(i) > -1){",
" table.cell(i,j0).nodes().to$().css({cursor: 'pointer'});",
" }else{",
" table.cell(i,j0).nodes().to$().removeClass('details-control');",
" }",
"}",
"",
"// make the table header of the nested table",
"var format = function(d, childId){",
" if(d != null){",
" var html = ",
" '<table class=\"display compact hover\" ' + ",
" 'style=\"padding-left: 30px;\" id=\"' + childId + '\"><thead><tr>';",
" for(var key in d[d.length-1][0]){",
" html += '<th>' + key + '</th>';",
" }",
" html += '</tr></thead><tfoot><tr>'",
" for(var key in d[d.length-1][0]){",
" html += '<th></th>';",
" }",
" return html + '</tr></tfoot></table>';",
" } else {",
" return '';",
" }",
"};",
"",
"// row callback to style the rows of the child tables",
"var rowCallback = function(row, dat, displayNum, index){",
" if($(row).hasClass('odd')){",
" $(row).css('background-color', 'white');",
" $(row).hover(function(){",
" $(this).css('background-color', 'lightgreen');",
" }, function() {",
" $(this).css('background-color', 'white');",
" });",
" } else {",
" $(row).css('background-color', 'white');",
" $(row).hover(function(){",
" $(this).css('background-color', 'lightblue');",
" }, function() {",
" $(this).css('background-color', 'white');",
" });",
" }",
"};",
"",
"// header callback to style the header of the child tables",
"var headerCallback = function(thead, data, start, end, display){",
" $('th', thead).css({",
" 'color': 'black',",
" 'background-color': 'white'",
" });",
"};",
"",
"// make the datatable",
"var format_datatable = function(d, childId, rowIdx){",
" // footer callback to display the totals",
" // and update the parent row",
" var footerCallback = function(tfoot, data, start, end, display){",
" $('th', tfoot).css('background-color', '#F5F2F2');",
" var api = this.api();",
"// update the Override CPM when the Override CPP is changed",
" var col_override_cpp = api.column(7).data();",
" var col_population = api.column(9).data();",
" if(ok){",
" for(var i = 0; i < col_override_cpp.length; i++){",
" api.cell(i,8).data(((parseInt(col_override_cpp[i])*100)/(parseInt(col_population[i])/1000)).toFixed(0));",
" }",
" }",
"// update the Override CPP when the Override CPM is changed",
" var col_override_cpm = api.column(8).data();",
" for(var i = 0; i < col_override_cpm.length; i++){",
" api.cell(i,7).data(((parseInt(col_override_cpm[i])*parseInt(col_population[i])/1000)/(100)).toFixed(0));",
" }",
"// Update the spot mixes",
" var col_mix_percentage = api.column(2).data();",
" var col_mix60_mix30 = api.column(10).data();",
" var col_mix30_mix15 = api.column(11).data();",
" for(var i = 0; i < col_mix_percentage.length; i++){",
" api.cell(i,3).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix60_mix30[i])).toFixed(1));",
" api.cell(i,4).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix30_mix15[i])).toFixed(1));",
" }",
"// Make the footer sums",
" api.columns().eq(0).each(function(index){",
" if(index == 0) return $(api.column(index).footer()).html('Mix Total');",
" var coldata = api.column(index).data();",
" var total = coldata",
" .reduce(function(a, b){return parseInt(a) + parseInt(b)}, 0);",
" if(index == 3 || index == 4 ||index == 5 || index == 6 || index==7 || index==8) {",
" $(api.column(index).footer()).html('');",
" } else {",
" $(api.column(index).footer()).html(total);",
" }",
" if(total == 100) {",
" $(api.column(index).footer()).css({'color': 'green'});",
" } else {",
" $(api.column(index).footer()).css({'color': 'red'});",
" }",
" })",
" // update the parent row",
" var col_share = api.column(2).data();",
" var col_CPP = api.column(5).data();",
" var col_CPM = api.column(6).data();",
" var col_Historical_CPP = api.column(7).data();",
" var col_Historical_CPM = api.column(8).data();",
" var CPP = 0, CPM = 0, Historical_CPP = 0, Historical_CPM = 0;",
" for(var i = 0; i < col_share.length; i++){",
" CPP += (parseInt(col_share[i])*parseInt(col_CPP[i]).toFixed(0));",
" CPM += (parseInt(col_share[i])*parseInt(col_CPM[i]).toFixed(0));",
" Historical_CPP += (parseInt(col_share[i])*parseInt(col_Historical_CPP[i]).toFixed(0));",
" Historical_CPM += (parseInt(col_share[i])*parseInt(col_Historical_CPM[i]).toFixed(0));",
" }",
" table.cell(rowIdx, j0+2).data((CPP/100).toFixed(2));",
" table.cell(rowIdx, j0+3).data((CPM/100).toFixed(2));",
" table.cell(rowIdx, j0+4).data((Historical_CPP/100).toFixed(2));",
" table.cell(rowIdx, j0+5).data((Historical_CPM/100).toFixed(2));",
" }",
" var dataset = [];",
" var n = d.length - 1;",
" for(var i = 0; i < d[n].length; i++){",
" var datarow = $.map(d[n][i], function (value, index) {",
" return [value];",
" });",
" dataset.push(datarow);",
" }",
" var id = 'table#' + childId;",
" if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" });",
" } else {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: -1, visible: false},",
" {targets: 0, orderable: false, className: 'details-control'},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" }).column(0).nodes().to$().css({cursor: 'pointer'});",
" }",
" subtable.MakeCellsEditable({",
" onUpdate: onUpdate,",
" inputCss: 'my-input-class',",
" columns: [2, 7, 8],",
" confirmationButton: {",
" confirmCss: 'my-confirm-class',",
" cancelCss: 'my-cancel-class'",
" }",
" });",
"};",
"",
"// display the child table on click",
"var children = [];", # array to store the id's of the already created child tables
"table.on('click', 'td.details-control', function(){",
" var tbl = $(this).closest('table'),",
" tblId = tbl.attr('id'),",
" td = $(this),",
" row = $(tbl).DataTable().row(td.closest('tr')),",
" rowIdx = row.index();",
" if(row.child.isShown()){",
" row.child.hide();",
" td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>');",
" } else {",
" var childId = tblId + '-child-' + rowIdx;",
" if(children.indexOf(childId) === -1){", # this child table has not been created yet
" children.push(childId);",
" row.child(format(row.data(), childId)).show();",
" td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');",
" format_datatable(row.data(), childId, rowIdx);",
" }else{",
" row.child(true);",
" td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');",
" }",
" }",
"});"
)
# Table
table <- DT::datatable(
Dat,
callback = callback_js,
rownames = rowNames,
escape = -colIdx-1,
style = "bootstrap4",
extensions = 'Buttons',
options = list(
dom = "Blfrtip",
buttons = list("copy",
list(
extend = "collection",
buttons = "csv",
text = "Download"
)
),
lengthMenu = list(c(-1, 10, 20),
c("All", 10, 20)),
columnDefs = list(
list(width = '30px', targets = 0),
list(width = '545px', targets = 1),
list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
list(orderable = FALSE, className = 'details-control', targets = colIdx),
list(className = "dt-center", targets = "_all")
)
)
)
# Call the html tools deps (js & css files in this directory)
cell_edit_dep <- htmltools::htmlDependency(
"CellEdit", "1.0.19",
src = 'www/',
script = "dataTables.cellEdit.js",
stylesheet = "dataTables.cellEdit.css"
)
table$dependencies <- c(table$dependencies, list(cell_edit_dep))
table %>% formatStyle(
c('Market', 'SQAD CPP ($)', 'SQAD CPM ($)', 'Override CPP ($)', 'Override CPM ($)'),
target = 'row',
backgroundColor = "#F5F2F2"
)
})
A: Try this:
js <- c(
"function(xlsx) {",
" var table = $('#daypartTable').find('table').DataTable();",
" // Letters for Excel columns.",
" var LETTERS = [",
" 'A','B','C','D','E','F','G','H','I','J','K','L','M',",
" 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'",
" ];",
" // Get sheet.",
" var sheet = xlsx.xl.worksheets['sheet1.xml'];",
" // Get a clone of the sheet data. ",
" var sheetData = $('sheetData', sheet).clone();",
" // Clear the current sheet data for appending rows.",
" $('sheetData', sheet).empty();",
" // Row count in Excel sheet.",
" var rowCount = 1;",
" // Iterate each row in the sheet data.",
" $(sheetData).children().each(function (index) {",
" // Used for DT row() API to get child data.",
" var rowIndex = index - 2;", #
" // Don't process row if its the header row.",
sprintf(" if (index > 1 && index < %d) {", nrow(Dat)+2), #
" // Get row",
" var row = $(this.outerHTML);",
" // Set the Excel row attr to the current Excel row count.",
" row.attr('r', rowCount);",
" // Iterate each cell in the row to change the row number.",
" row.children().each(function (index) {",
" var cell = $(this);",
" // Set each cell's row value.",
" var rc = cell.attr('r');",
" rc = rc.replace(/\\d+$/, \"\") + rowCount;",
" cell.attr('r', rc);",
" });",
" // Get the row HTML and append to sheetData.",
" row = row[0].outerHTML;",
" $('sheetData', sheet).append(row);",
" rowCount++;",
" // Get the child data - could be any data attached to the row.",
sprintf(" var childData = table.row(':eq(' + rowIndex + ')').data()[%d];", ncol(Dat)-1), #
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
" headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(var i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excelt row counter.",
" }",
" // The child data is an array of rows",
" for (c = 0; c < childData.length; c++) {",
" // Get row data.",
" child = childData[c];",
" // Prepare Excel formatted row",
" var colNames = Object.keys(child);",
" childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(var i = 0; i < colNames.length; i++){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
" '\" s=\"5\"><is><t>' + child[colNames[i]] +",
" '</t></is></c>';",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // Just append the header row and increment the excel row counter.",
" } else {",
" $('sheetData', sheet).append(this.outerHTML);",
" rowCount++;",
" }",
" });",
"}"
)
datatable(
Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
extensions = "Buttons",
options = list(
dom = "Bfrtip",
columnDefs = list(
list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
list(orderable = FALSE, className = 'details-control', targets = colIdx),
list(className = "dt-center", targets = "_all")
),
buttons = list(
list(
extend = "excel",
exportOptions = list(
orthogonal = "export",
columns = 0:(ncol(Dat)-2)
),
orientation = "landscape",
customize = JS(js)
)
)
)
)
Here is an example of the generated Excel file:
EDIT
Better:
excelTitle <- NULL # set to NULL if you don't want a title
js <- c(
"function(xlsx) {",
" var table = $('#daypartTable').find('table').DataTable();",
" // Number of columns.",
" var ncols = table.columns().count();",
" // Is there a title?",
sprintf(" var title = %s;", ifelse(is.null(excelTitle), "false", "true")),
" // Integer to Excel column: 0 -> A, 1 -> B, ..., 25 -> Z, 26 -> AA, ...",
" var XLcolumn = function(j){", # https://codegolf.stackexchange.com/a/163919
" return j < 0 ? '' : XLcolumn(j/26-1) + String.fromCharCode(j % 26 + 65);",
" };",
" // Get sheet.",
" var sheet = xlsx.xl.worksheets['sheet1.xml'];",
" // Get a clone of the sheet data. ",
" var sheetData = $('sheetData', sheet).clone();",
" // Clear the current sheet data for appending rows.",
" $('sheetData', sheet).empty();",
" // Row count in Excel sheet.",
" var rowCount = 1;",
" // Iterate each row in the sheet data.",
" $(sheetData).children().each(function (index) {",
" // Used for DT row() API to get child data.",
" var rowIndex = title ? index - 2 : index - 1;",
" // Don't process row if it's the title row or the header row.",
" var i0 = title ? 1 : 0;",
" if (index > i0) {",
" // Get row",
" var row = $(this.outerHTML);",
" // Set the Excel row attr to the current Excel row count.",
" row.attr('r', rowCount);",
" // Iterate each cell in the row to change the row number.",
" row.children().each(function (index) {",
" var cell = $(this);",
" // Set each cell's row value.",
" var rc = cell.attr('r');",
" rc = rc.replace(/\\d+$/, \"\") + rowCount;",
" cell.attr('r', rc);",
" });",
" // Get the row HTML and append to sheetData.",
" row = row[0].outerHTML;",
" $('sheetData', sheet).append(row);",
" rowCount++;",
" // Get the child data - could be any data attached to the row.",
" var childData = table.row(':eq(' + rowIndex + ')').data()[ncols-1];",
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
" var headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // The child data is an array of rows",
" for(let c = 0; c < childData.length; c++){",
" // Get row data.",
" var child = childData[c];",
" // Prepare Excel formatted row",
" var childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" var i = 0;",
" for(let colname in child){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"5\"><is><t>' + child[colname] +",
" '</t></is></c>';",
" i++;",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // Just append the header row and increment the excel row counter.",
" } else {",
" $('sheetData', sheet).append(this.outerHTML);",
" rowCount++;",
" }",
" });",
"}"
)
datatable(
Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
extensions = "Buttons",
options = list(
dom = "Bfrtip",
columnDefs = list(
list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
list(orderable = FALSE, className = 'details-control', targets = colIdx),
list(className = "dt-center", targets = "_all")
),
buttons = list(
list(
extend = "excel",
exportOptions = list(
orthogonal = "export",
columns = 0:(ncol(Dat)-2)
),
title = excelTitle,
orientation = "landscape",
customize = JS(js)
)
)
)
)
EDIT 2
In callback_js, replace
" var dataset = [];",
" var n = d.length - 1;",
" for(var i = 0; i < d[n].length; i++){",
" var datarow = $.map(d[n][i], function (value, index) {",
" return [value];",
" });",
" dataset.push(datarow);",
" }",
" var id = 'table#' + childId;",
" if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" });",
" } else {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: -1, visible: false},",
" {targets: 0, orderable: false, className: 'details-control'},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" }).column(0).nodes().to$().css({cursor: 'pointer'});",
" }",
with
" var n = d.length - 1;",
" var id = 'table#' + childId;",
" var columns = Object.keys(d[n][0]).map(function(x){",
" return {data: x, title: x};",
" });",
" if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
" var subtable = $(id).DataTable({",
" 'data': d[n],",
" 'columns': columns,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" });",
" } else {",
" var subtable = $(id).DataTable({",
" 'data': d[n],",
" 'columns': columns,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: -1, visible: false},",
" {targets: 0, orderable: false, className: 'details-control'},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" }).column(0).nodes().to$().css({cursor: 'pointer'});",
" }",
Moreover, you probably don't want the hidden columns in the Excel file. So replace this code:
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
......
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
with
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]).slice(1,9);",
" // Prepare Excel formatted row",
" var headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // The child data is an array of rows",
" for(let c = 0; c < childData.length; c++){",
" // Get row data.",
" var child = childData[c];",
" // Prepare Excel formatted row",
" var childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"5\"><is><t>' + child[colNames[i]] +",
" '</t></is></c>';",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
EDIT 3
This doesn't work if there are some periods in the column names of a child table. Here is the fix:
" var columns = Object.keys(d[n][0]).map(function(x){",
" return {data: x.replace('.', '\\\\\\.'), title: x};",
" });",
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61549420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: conditional drop-down list on row cluster values I have the following table:
Is there a way to have dynamic drop-down list including all values from only same cluster (example of possible values in Link list column)? Cluster column is big so I am looking for dynamic solution.
A: So you can do this with formulas, but it's a bit involved. Bottom line is that here is the result I came up with:
The drop-down was created dynamically using dynamic named ranges and formulas
We need to start out with some definitions. This is my test worksheet and data:
The formulas will work out using the named ranges, so you can put your "working area" (the boxed area in green) almost anywhere, including on a different (possibly hidden) worksheet.
You must define four, dynamic named ranges as follows, which match the color-shaded areas in the image above:
Many of these formulas are array formulas, so you must be careful to enter them with CTRL+SHIFT+ENTER.
Once your data areas and names are defined, the first area to populate is the UniqueClusterList (the range on the sheet is F2:M2). We're building a list of unique items, based on the data in your column of cluster values. So you need an array formula that identifies all the unique values in the range. In each cell in the range, enter the array formula CTRL+SHIFT+ENTER for each:
Cell F2 =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:E2,ClusterList)=0),ClusterList),"")
Cell G2 =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:F2,ClusterList)=0),ClusterList),"")
Cell H2 =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:G2,ClusterList)=0),ClusterList),"")
Cell I2 =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:H2,ClusterList)=0),ClusterList),"")
... and so on. Notice that only the cell address in the middle is changing.
Next, we need to build up the list of IDs for each unique Cluster value. This is also an array formula. Starting in cell F3 with CTRL+SHIFT+ENTER:
=IFERROR(INDEX(IDList, SMALL(IF(F$2=ClusterList, ROW(IDList)-2,""), ROW()-2)),"")
Then use your cursor to grab the auto-fill icon in the selection box of that cell and drag it down to cell F16. Since cells F3:F16 are now selected, re-grab the auto-fill icon and drag to the right to fill the whole range F2:M16. All of the values should pop-in as calculated by the formulas.
Your final step is to create the lookup formula for the drop-down list. So select cell C3, then on the ribbon click Data --> Data Tools --> Data Validation to get the dialog window. Now select Allow: List, and in the Source: field enter the following formula:
=OFFSET($F$2,1,MATCH(A3,UniqueClusterList,0)-1,SUMPRODUCT(COUNTIF(IDList,OFFSET($F$2,0,MATCH(A3,UniqueClusterList,0)-1,MAXUNIQUE,1))),1)
You'll now have a drop-down in cell C3 that matches the very first image above. Drag the auto-fill selection icon all the way down to cell C20 and all of those cells will correctly calculate the drop-down list based on the available Clusters and IDs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61126683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: QTabWidget inside a QSplitter switching very slow I'm new to Qt, and wanted to implement some dialogs for a program.
The GUI of the dialog is simple: there's a tree on the left, and some tabs on the right (the number of tabs may change), and there are some widgets for input in each tab.
But when I implemented this dialog with Qt5.0.2, I found it is very slow when I switch tabs. (usually more than 0.1s to switch a tab, sometimes it stopped to response for several seconds if I randomly click on the tabs for many times)
I'm wondering if I was using Qt in a wrong way, or if there is something I can do to improve the performance
Here is an example for my scenario:
TestQT::TestQT(QWidget *parent)
: QMainWindow(parent)
{
QSplitter* pSplitter = new QSplitter();
QTreeWidget* pTree = new QTreeWidget();
pSplitter->addWidget(pTree);
QTabWidget* pTabs = new QTabWidget();
for (int i = 0; i < 10; i++)
{
QWidget* pPage = new QWidget();
QVBoxLayout* pLayout = new QVBoxLayout();
for (int j = 0; j < 20; j++)
{
QHBoxLayout* pLineLayout = new QHBoxLayout();
pLineLayout->addWidget(new QCheckBox());
pLineLayout->addWidget(new QLineEdit());
pLayout->addLayout(pLineLayout);
}
pPage->setLayout(pLayout);
pTabs->addTab(pPage, tr("Page%1").arg(i));
}
pSplitter->addWidget(pTabs);
this->setCentralWidget(pSplitter);
}
A: I agree with Kuba. Mostly GUI malfunctions are occurred when another action is blocking the thread it is running on, so your solution in these cases is to either move the GUI or that action to another thread.
Since I only see the code for GUI here, let's try moving the GUI to another thread first. With the header QThread, add these codes to your function and see if it helps:
QThread * t1 = new QThread();
this->moveToThread(t1);
t1->start();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17940242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Express app - Change base url I'm building a Q&A app following this tutorial and everything goes well, but I need to change the chance to change the base root where the app is being served via config files.
Now the app is served in localhost:8080 and I need to be served over localhost:8080/qae (for example).
I think the answer is near this piece of code:
// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
serveClient: config.env !== 'production',
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
app.angularFullstack = server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode '+config.ip, config.port, app.get('env'));
});
}
setImmediate(startServer);
(from /server/app.js)
But I can't figure it. Is it possible doing this in a simple way?
////////EDIT////////
I tried all the proposed solutions, but I'm doing something wrong and got errors. This is my routes.js in case it helps:
/**
* Main application routes
*/
'use strict';
import errors from './components/errors';
import path from 'path';
export default function(app) {
// Insert routes below
app.use('/api/cpd', require('./api/cpd'));
app.use('/api/categories', require('./api/category'));
app.use('/api/terms', require('./api/term'));
app.use('/api/qae', require('./api/qae'));
app.use('/api/stats', require('./api/stat'));
app.use('/api/tags', require('./api/tag'));
app.use('/api/questions', require('./api/question'));
app.use('/api/things', require('./api/thing'));
app.use('/api/users', require('./api/user'));
app.use('/auth', require('./auth'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
A: You can do the following:
var app = express();
var routes = require('./routes/index');
app.set('base', '/qae');
then you need to add route
app.use('/qae', routes);
Hope this helps :)
A: You should change your rooting to this:
app.use('/qae',require('./routes'))
and in routes/index.js you can have all declarations of your routes.
In routes.js
export default function(app) {
// Insert routes below
app.use('/qae', require('./api'));
app.use('/auth', require('./auth'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
create file index.js in api
const express = require('express')
const router = express.Router()
router.use('/api/cpd', require('./cpd'));
router.use('/api/categories', require('./category'));
router.use('/api/terms', require('./term'));
router.use('/api/qae', require('./qae'));
router.use('/api/stats', require('./stat'));
router.use('/api/tags', require('./tag'));
router.use('/api/questions', require('./question'));
router.use('/api/things', require('./thing'));
router.use('/api/users', require('./user'));
module.exports = router
That way all your api routes will look like /qae/api/*. If you need auth also after this prefix you need to do it same way.
Best solution is to have i app.use('/',...) including routers from subfolders.
A: If your ./routes module returned a router instead of taking an app object, then you could do this to make it available in / route:
app.use(require('./routes'));
or this to use /qae prefix:
app.use('/qae', require('./routes'));
but since you pass the app object to the function exported by ./routes then it is the ./routes module that actually registers the routes and since you didn't include its code it's hard to give you a specific example. I can only say that you will need to change the routes definitions in ./routes for a different prefix, and you'd need to return a router instead of taking app argument for the above examples to work.
Tthen you ./routes would have to look like this:
let express = require('express');
let router = express.Router();
router.get('/xxx', (req, res) => {
// ...
});
router.get('/yyy', (req, res) => {
// ...
});
module.exports = router;
and only then you'll be able to use:
app.use('/qae', require('./routes'));
in the main code.
A: Folder Structure
bin/
www
server/
routes/
index.js
book.js
views/
index.ejs
app.js
router.js
error.js
public/
package.json
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
require('./router')(app);
require('./errors')(app);
module.exports = app;
route.js
var index = require('./routes/index');
var books = require('./routes/books');
var base = '/api';
module.exports = function (app) {
app.use(base+'/', index);
app.use(base+'/books', books);
};
error.js
module.exports = function (app) {
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
};
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42902739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to get the tool id for eclipse headless build Eclipse has a headless build option and in the documentation they say we can add or replace tool options
Replace a tool option value: -T {toolid} {optionid=value}
Append to a tool option value: -Ta {toolid} {optionid=value}
Prepend to a tool option value: -Tp {toolid} {optionid=value}
Remove a tool option: -Tr {toolid} {optionid=value}
How would someone find the {toolid} value for a build option?
I would like to change the command line arguments for this command
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf" "KTV_Rear.hex"
to
arm-none-eabi-objcopy -O binary "KTV_Rear.elf" "KTV_Rear.bin"
I have not been able to find any documentation on how to get the tool id to pass to the -T command. Any help would be appreciated.
==================== UPDATE ========================
I tried to figure out what the tool ids were in the way that HighCommander4 suggested. Searching for "tool id" in the project gives
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.1172133377" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.707543027" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1908892168" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.1903643389" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.270131667" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.1091026714" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1404415533" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.292770688" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
The output of the build window for the command I need to modify is
Invoking: GNU ARM Cross Create Flash Image
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf" "KTV_Rear.hex"
It does not seem obvious which one of the tool ids might relate to arm-none-eabi-objcopy. I tried using the string for the tool id for the archiver with no luck.
I found this link that seems related
A: At the .cproject file you can find the tool id (use the superClass field, without the number) and for each tool you can find a list of options ids. At the invocation line you need to specify the tool id, the option id and the value for the option, like in the following example (adding my_lib_location to the libraries search path):
-Tp cdt.managedbuild.tool.gnu.c.linker.exe.release gnu.c.link.option.paths=my_lib_location
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56229725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Better way to manage Database class for common operations Our company work on multiple Windows Services and EXEs (more than 30). Each of the service/exe have one database class which have connection details and respective SQL queries.
Now, whenever some change come, our team need to maintain all the projects, which takes a lot of programmer's time and efforts. Also seems inappropriate.
I was wondering if there was a better architecture to manage such kind of structure. So that it can save programmer's time and repetitive effort.
What I have think is that to maintain a common DLL, which will have
all the connection detail and SQL queries. Maintaining this structure
using inheritance will save a lot of repetitive effort.
Is there any better way to manage this? What are your opinions?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55004392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adjust the image as per screen resolution of window I have add a JLabel in a JFrame
and one image of size 1024x768 is added in JLabel.
When I set the resolution of window screen in 1024x768 the and run the application the image is shown in full window. But when I set the resolution of window screen in 1280x768 - the image is shown in only one third portion of window.
How can I adjust or add the image of size 1024x768 so that in any screen resolution the image will show covering the full window? In other words the image is adjusted as per the screen resolution of window.
A:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;
class ImagePanel extends JPanel {
Image image;
ImagePanel(Image image) {
this.image = image;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,0,0,getWidth(),getHeight(),this);
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://pscode.org/media/stromlo2.jpg");
final Image image = ImageIO.read(url);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Image");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
ImagePanel imagePanel = new ImagePanel(image);
imagePanel.setLayout(new GridLayout(5,10,10,10));
imagePanel.setBorder(new EmptyBorder(20,20,20,20));
for (int ii=1; ii<51; ii++) {
imagePanel.add(new JButton("" + ii));
}
f.setContentPane(imagePanel);
f.pack();
f.setVisible(true);
}
});
}
}
Raw image used
A: I have faced this problem several times while i was adding image to the JFrame. Either the image size would be small or the JFrame size was small.
Here is a great site wherein you can resize your images according to the JFrame without distorting the image.
You can visit this website Go to the site
I have explained and showed how to make use of photo editor that the website provides to resize the image.
Go to my video tutorial Go to the Video Session
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7980272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Status of statement (void)f() in C++14, is it ill-formed? if not, is the f() part discard-value? Is the following program ill-formed according to the C++14 standard?
int f() { return 42; }
int main() {
(void)f();
}
If not, is the sole function call expression contained within a discard-value expression? (note that is the subexpression, not the whole expression statement)
A:
Is the following program ill-formed according to the C++14 standard?
No. If you have some specific reason for thinking this might be invalid, you might be able to get a more detailed answer, but quoting each and every sentence of the standard in an attempt to point out that that sentence doesn't render the program invalid is not productive.
If not, is the sole function call expression contained within a discard-value expression?
The sole function call expression is the discarded-value expression.
5.2.9 Static cast [expr.static.cast]
6 Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5). [...]
I am assuming you are already aware that a C-style cast performs a static_cast if possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33323932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# value type with dynamic number of fields The best way to explain my problem is with a code snippet:
enum Resource { ..., Size }
class ResourceVector
{
int[] values = new int[(int)Resource.Size];
public static ResourceVector operator + (ResourceVector a, ResourceVector b)
{...}
...
}
We are using this type everywhere as though it were a value type. I.e. we are making the assumption that:
ResourceVector b = a;
b += c;
will not affect a, because that is how we are used to talking about vectors (and that is how a vector with a fixed number of fields does behave, if implemented as a struct).
However since that assumption is wrong, it has led to some extremely subtle bugs.
I am wondering if there is a way to make this behave as a value type, other than just expanding the members of Resource each into their own members in a struct ResourceVector (which requires touching every member of ResourceVector if we wish to add another Resource).
Oh, just in case, we are working with C# 2.0. So no fancy-pants features :-)
Thanks.
A: I think you are confusing “value type” with “immutable type”. You actually want your ResourceVector to be an immutable type.
An immutable type is one that has no way to change its contents. Once constructed, an instance retains its value until it is garbage-collected. All operations such as addition return a new instance containing the result instead of modifying an existing instance.
string is the most well-known immutable class. All operations like Substring and Replace return a new string and don’t modify the existing strings.
Once your type is properly immutable, semantically it doesn’t matter so much anymore whether it is a value type or a reference type — but it matters to the performance. If you pass values around a lot, you should probably make it a reference type in order to avoid a lot of unnecessary copying.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3485201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Migration wont recognize hstore extension created on schema_search_path I´m trying to add a column using postgresql HStore.
Since I´m running a multi tenant app (using apartment gem), I´ve created the hstore extension on a dedicated schema, called "shared_extensions", as seen here: [https://github.com/influitive/apartment#installing-extensions-into-persistent-schemas][1]
I also added the shared_extensions schema to database.yml as:
default: &default
adapter: postgresql
encoding: unicode
pool: 5
schema_search_path: "public,shared_extensions"
However, when I try to run rake db:migrate to add hstore column, I´m still receiving the error:
ActiveRecord::StatementInvalid: PG::UndefinedObject: ERROR: type "hstore" does not exist
This is the hstore migration code:
class AddAdditionalInformationsToParties < ActiveRecord::Migration
def change
add_column :parties, :additional_informations, :hstore
end
end
I´m not sure, but it looks like migrations are not recognizing the schema_search_path on database.yml file.
A: You need to enable the hstore extension in postgres.
Try running rails g migration add_hstore_extension, then edit it like below:
class AddHstoreExtension < ActiveRecord::Migration
def self.up
enable_extension "hstore"
end
def self.down
disable_extension "hstore"
end
end
Note that you'll need that to run before the migration which uses it.
A: I ended up adding the extension to pg_catalog, which is always implicitly on search_path, as described by Craig Ringer in this post:
Create HSTORE with multiple schemas
CREATE EXTENSION hstore WITH SCHEMA pg_catalog;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32292444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Prometheus query filter not working for OR filter Is there any issue with the below query?
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace="test1|test2"}
It works if I pass just one namespace.
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace="test1"}
Sum also works without passing anything.
sum(kube_resourcequota{resource="count/deployments.apps",type="hard"})
A: The instant vector selector can be expressed as
*
*namespace="test1" to match label namespace exactly equal to "test1"
*<no selector on namestapce> to match all values of namespace
*namespace=~"test1|test2" to match label namespace with given regex
You made a mistake: you used a regex "test1[test2" with an exact match (=) instead of regex match (=~).
Correct expression would be:
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace=~"test1|test2"}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60064572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rainbow lines in openGL es I writing an application that draws in openGL es 1.0 in the Android NDK and renders it on an android phone. So far, I can draw two lines. The problem is that those two lines are rainbow. I was trying to debug where coordinates are on screen (where 0,0 and 1,1 are) so I added color to the two lines I am drawing. One should be drawn in red, the other in green. The code I use to draw them is as follows:
void appInit()
{
glEnable(GL_CULL_FACE);
}
void appRender(jint width, jint height)
{
prepareFrame(width, height);
drawLines();
}
void drawLines()
{
glLoadIdentity();
glPushMatrix();
GLfloat color1[] = {0.0f,1.0f,0.0f,1.0f};
drawLine( 1.0f,1.0f,2.0f,2.0f,color1);
glPopMatrix();
glPushMatrix();
GLfloat color2[] = {1.0f,0.0f,0.0f,1.0f};
drawLine(0.0f,0.0f,1.0f,1.0f, color2);
glPopMatrix();
}
void drawLine(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat * color)
{
GLfloat vVertices[] =
{x1, y1,
x2, y2};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
//glColor4f(color[0],color[1],color[2],color[3]);
glColorPointer(4,GL_FLOAT,0,color);
glVertexPointer(2, GL_FLOAT, 0, vVertices);
glDrawArrays(GL_LINES, 0, 4);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
void prepareFrame(int width, int height)
{
glViewport(0, 0, width, height);
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glLoadIdentity();
}
appInit is called, then appRender is called over and over again with the screen dimensions. The result is this:
http://i.stack.imgur.com/G91oX.png
If anyone knows why they are drawing rainbows instead of the colors I specified, that would be wonderful. Bonus points if you can tell me what the coordinate system is like by default on android (no gluperspective or lookat is used).
A: Try creating a color array that has a color for each vertex. Right now I think you're reading off the end of the array into uninitialized memory when you try to render two vertexes, since you don't specify the color for the second vertex.
Also, I think the third argument for your glDrawArrays() call should be 2, not 4, since you're only rendering two vertexes.
I'm somewhat surprised it didn't crash with an access violation of some sort, honestly :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4976291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is learning a framework such as Zend or CakePHP while just starting to learn OOP a good or bad idea? I've been studying php for about 6 months now and want to start learning OOP and a framework. When I was learning javascript and jQuery, I learned the best when I was learning and applying both of them at the same time, so now I"m wondering if diving right into learning a framework while learning OOP (up until now I've only done procedural php coding) is a good idea.
A: Learning OOP and learning about MVC is a good idea, before getting into PHP frameworks. Straight away you will have to make design decisions about where you should put different code. If you make the mistakes early, then to improve your design you will have to go back and fix up poor mistakes.
I read a nice answer recently: How to increase my "advanced" knowledge of PHP further? (quickly)
A: In general I'd say Yes it is a good idea. The reason being that many OO concepts get applied in frameworks so you will get lots of practical exposure to various patterns an constructs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4989734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Signal R ASP.Net (Starts pending when server access the application) We published an application in a laptop that act as a server, then access the application by other pc through wlan, Signal R works when the client's pc (Multiple Clients) access the application. But when the server's pc starts to access the application, Signal R starts pending.
Code on startup (Receives Update):
$.connection.hub.start().done(function () {
$.connection.hub.stop();
$.connection.hub.start();
}); // fixed for mobile browsers
$.connection.myHub.client.getUpdate = function (message) {
console.log(message);
getInventoryInformation();
}
Code on sending updates (Triggered by click event)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Restaurant/SalePackageIng",
data: JSON.stringify(parameters),
beforeSend: function () {
$(".overlay").show();
},
success: function () {
$.connection.myHub.server.getUpdate("Current Inventory Updated!");
},
error: function () {
console.log("Oops! Something went wrong. 562");
}
});
We conclude that every time the server's pc access the application signal r starts pending.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50595216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dart : A non-null String must be provided to a Text widget So I am going to create a quiz app but while I run it, I get the following error
'pakage:flutter/src/wigets/text.dart': Field assertion : line 298 pos
10 :'data !=null': A non-null String must be provided to a Text widget
it is a flutter based code, what are the possible thing i missed ? Can you help me please ! i shall be obliged for this :)
Here Is image of Error
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:crazyquiz/resultpage.dart';
class getjson extends StatelessWidget {
String langname;
getjson(this.langname);
String assettoload;
setasset() {
if (langname == "Funny") {
assettoload = "assets/funny.json";
} else if (langname == "General Knowledge") {
assettoload = "assets/gk.json";
} else if (langname == "Javascript") {
assettoload = "assets/js.json";
} else if (langname == "C++") {
assettoload = "assets/cpp.json";
} else {
assettoload = "assets/linux.json";
}
}
@override
Widget build(BuildContext context) {
setasset();
return FutureBuilder(
future:
DefaultAssetBundle.of(context).loadString(assettoload, cache: true),
builder: (context, snapshot) {
List mydata = json.decode(snapshot.data.toString());
if (mydata == null) {
return Scaffold(
body: Center(
child: Text(
"Loading",
),
),
);
} else {
return quizpage(mydata: mydata);
}
},
);
}
}
class quizpage extends StatefulWidget {
var mydata;
quizpage({Key key, this.mydata = ""}) : super(key: key);
@override
_quizpageState createState() => _quizpageState(mydata);
}
class _quizpageState extends State<quizpage> {
var mydata;
_quizpageState(this.mydata);
Color colortoshow = Colors.indigoAccent;
Color right = Colors.green;
Color wrong = Colors.red;
int marks = 0;
int i = 1;
int j = 1;
int timer = 30;
String showtimer = "30";
var random_array;
Map<String, Color> btncolor = {
"a": Colors.purple,
"b": Colors.lightBlueAccent,
"c": Colors.blueGrey,
"d": Colors.blueAccent,
};
bool canceltimer = false;
genrandomarray() {
var distinctIds = [];
var rand = new Random();
for (int i = 0;;) {
distinctIds.add(rand.nextInt(10));
random_array = distinctIds.toSet().toList();
if (random_array.length < 10) {
continue;
} else {
break;
}
}
print(random_array);
}
@override
void initState() {
starttimer();
genrandomarray();
super.initState();
}
@override
void setState(fn) {
if (mounted) {
super.setState(fn);
}
}
void starttimer() async {
const onesec = Duration(seconds: 1);
Timer.periodic(onesec, (Timer t) {
setState(() {
if (timer < 1) {
t.cancel();
nextquestion();
} else if (canceltimer == true) {
t.cancel();
} else {
timer = timer - 1;
}
showtimer = timer.toString();
});
});
}
void nextquestion() {
timer = 30;
setState(() {
if (j < 10) {
i = random_array[j];
j++;
} else {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => resultpage(marks: marks),
));
}
btncolor["a"] = Colors.purple;
btncolor["b"] = Colors.lightBlueAccent;
btncolor["c"] = Colors.blueGrey;
btncolor["d"] = Colors.blueAccent;
});
starttimer();
}
void checkanswer(String k) {
if (mydata[2][i.toString()] == mydata[1][i.toString()][k]) {
[i.toString()][k]);
marks = marks + 5;
colortoshow = right;
} else {
}
setState(() {
btncolor[k] = colortoshow;
canceltimer = true;
});
Timer(Duration(seconds: 1), nextquestion);
}
Widget choicebutton(String k) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 20.0,
),
child: MaterialButton(
onPressed: () => checkanswer(k),
child: Text(
mydata[1][i.toString()][k],
style: TextStyle(
color: Colors.white,
fontFamily: "Alike",
fontSize: 16.0,
),
maxLines: 1,
),
color: btncolor[k],
splashColor: Colors.indigo[700],
highlightColor: Colors.indigo[700],
minWidth: 200.0,
height: 45.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
),
);
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Quizstar",
),
content: Text("You Can't Go Back At This Stage."),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Scaffold(
body: Column(
children: <Widget>[
Expanded(
flex: 3,
child: Container(
padding: EdgeInsets.all(15.0),
alignment: Alignment.bottomLeft,
child: Text(
mydata[0][i.toString()],
style: TextStyle(
fontSize: 16.0,
fontFamily: "Quando",
),
),
),
),
Expanded(
flex: 6,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
choicebutton('a'),
choicebutton('b'),
choicebutton('c'),
choicebutton('d'),
],
),
),
),
Expanded(
flex: 1,
child: Container(
alignment: Alignment.topCenter,
child: Center(
child: Text(
showtimer.toString(),
style: TextStyle(
fontSize: 35.0,
fontWeight: FontWeight.w700,
fontFamily: 'Times New Roman',
),
),
),
),
),
],
),
),
);
}
}`
A: Not a flutter guy. But I'll try to help you.
If you look into flutter source and search your error message you'll get a clue what to do.
So at text.dart we can find that dart check that you fill data field with a String when you call a constructor.
So my bet is that you misplace toString here mydata[0][i.toString()]
A: Text widget needs a string to be initialized. As vsenik mentioned, you are probably giving a null instead of string to a text widget. The problem is in one of the below lines.
mydata[1][i.toString()][k]
mydata[0][i.toString()]
You could use debug or insert a print statement before these lines.
A: I think Yalin is perfectly right, but I would add:
Dart has some very useful operators to prevent that kind of errors, which can be catastrofic on real world usage. You can check them here. In particular you could use
mydata[0][i.toString()] ?? "Default text"
to prevent this kind of problem when an object is null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62468250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add multiple objects to local storage with the same key I have this piece of code that reads data from an excel sheet, turns them into objects and then display their details in a neat product card
let allHoodies = [
['Hoodie', 'Purple', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(1).jpg'],
['Hoodie', 'Blue', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(2).jpg'],
['Hoodie', 'Green', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(3).jpg']
]
allHoodies.forEach((element, index) => {
let obj = {}
obj.id = index
obj.type = element[0]
obj.color = element[1]
obj.material = element[2]
obj.price = element[3]
obj.imagesrc = element[4]
allHoodies[index] = obj
})
//Evaluating each hoodie and displaying its information in HTML
allHoodies.forEach(function(hoodie) {
let card = `
<div class="card">
<img class="product-image" src="${hoodie.imagesrc}">
<h1 class="product-type">${hoodie.type}</h1>
<p>Color: ${hoodie.color}</p>
<p>${hoodie.material} <a href="#" onclick="addToStorage(${hoodie.id})">Read more</a> </p>
<p class="price">${hoodie.price}</p>
<p><button>Buy</button></p>
</div>
`;
// Add the card to the page
document.getElementById('product-container').innerHTML += card;
});
What I'm trying to do is, upon clicking "Buy", it adds multiple items to the local storage although I'm struggling to do it and add multiple ones, it keeps on adding only 1 of them and overwriting the previous one (I'm assuming due to the fact that they have the same key)
Here's what I've tried (which works, but its not my goal):
function addToCart(id){
let hoodie = hoodies[id];
localStorage.setItem('item', JSON.stringify(hoodie));
}
and then I simply add the addToCart() function to the button, would someone guide me and help me figure out how I could actually add multiple ones to the local storage and not just keep overwriting?
Expected result:
Runnable JSFiddle snippet
A: You can use localStorage#getItem to get the current list, and JSON#parse to convert it to an array of objects. Then, use Array#push to add the current item, and finally, use localStorage#set and JSON#stringify to save the updated list:
function addToCart(id) {
try {
const hoodie = allHoodies[id];
if(hoodie) {
const items = JSON.parse(localStorage.getItem('items') || "[]");
items.push(hoodie);
localStorage.setItem('items', JSON.stringify(items));
}
} catch(e) {
console.log('error adding item');
}
}
Function to show the saved list:
function displayProductsinCart() {
const products = JSON.parse(localStorage.getItem("item") || "[]");
document.getElementById("item-container").innerHTML = products.reduce((cards, product) =>
cards + `<div class="card">
<img class="item-image" src="${product.image}">
<h1 class="product-type">${product.type}</h1>
<p>Color: ${product.color}</p>
<p>${product.description}</p>
<p class="price">${product.price} </p>
<p><button>Buy</button></p>
</div>
`, '');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70326666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Graphql gql with variables and Query component (deprecated) I am trying to get use graphql with query component .
const LOAD_PRODUCTS = gql`
query {
category(input :{title : "${category}"}){
name
products {
id
name
brand
inStock
gallery
prices{
currency {
label
symbol
}
amount
}
attributes{
id
name
type
items {
id
displayValue
value
}
}
}
}
}
`
and later i am using the query compnent to fetch the data
<Query query={LOAD_PRODUCTS} variables={{category : "all" }}></Query>
but react is give error that category is not defined in the gql
what to do ....
I tried all the solutions on the internet and failed.
I did not want to use the hooks.
A: You need to specify the mapping of your query variables. Also your syntax is assuming string substitution rather than query variables.
Try:
const LOAD_PRODUCTS = gql`
query myQuery ( $category: String! ) {
category(input: { title: $category }){
name
products {
…
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74585984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need help adding WHERE clause in pre-written SQL statement Preface: my SQL is rudimentary. I received a SQL query from a vendor, it selects and exports every single employee comment and other data from a few different DBs as CSV meant for import, it was written by them but they're not helping with this request. The query is pulling so much data it makes a large time consuming file for import. So I want to add to / modify the query to have a "WHERE date > whateverdate" to narrow my results to recent data. For example, I want to pull only comments entered in the past 2 days.
The column I'm looking to add the clause for is the column "A.CMS502", defined as datetime. I believe this is the only relevant column in this query. An example date in this column is "2003-10-06 17:05:21.000". I am using SQL Server 2008 if it helps. Is it possible here? Thank you.
SELECT
'ID,Acct/LnNbr,NoteCreatedDate,CollectorId,ApplytoAll,Note'
UNION ALL
SELECT
ID + ',' + ID + ',' + NoteCreatedDate + ',' + CollectorId + ',' + 'No' + ',' + Note
FROM
(SELECT
CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S'
THEN SUBSTRING(A.CMS301,1,LEN(A.CMS301) - 1)
ELSE A.CMS301
END + '-' +
CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S'
THEN 'S' ELSE 'L'
END AS [ID],
REPLACE(CONVERT(VARCHAR, A.CMS501, 10), '-', '') AS [NoteCreatedDate],
CASE WHEN U.CMS1201 IS NOT NULL
THEN U.CMS1205 + ' ' + U.CMS1204
ELSE (SELECT CMS1205 + ' ' + CMS1204 FROM sysUSER WHERE CMS1201 = 'PSUSER')
END AS CollectorId,
CAST(A.CMS512 AS NVARCHAR(MAX)) AS [Note]
FROM
ACTIVITY AS A
LEFT JOIN
sysUSER AS U ON A.CMS503 = U.CMS1201
WHERE
A.CMS504 NOT IN (411,500,511,711,804,900,901,903,907,2000,999777)
AND A.CMS504 NOT BETWEEN 1102 AND 1199) AS S
A: Try this, this will output last 2 days.
SELECT 'ID,Acct/LnNbr,NoteCreatedDate,CollectorId,ApplytoAll,Note'
UNION ALL
SELECT ID + ',' + ID + ',' + NoteCreatedDate + ',' + CollectorId + ',' + 'No' + ',' + Note
FROM
(
SELECT CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN SUBSTRING(A.CMS301,1,LEN(A.CMS301) - 1) ELSE A.CMS301 END
+ '-' + CASE WHEN SUBSTRING(A.CMS301,LEN(A.CMS301),1) = 'S' THEN 'S' ELSE 'L'
END AS [ID]
,REPLACE(CONVERT(varchar,A.CMS501,10),'-','') AS [NoteCreatedDate]
,CASE WHEN U.CMS1201 IS NOT NULL THEN U.CMS1205 + ' ' + U.CMS1204 ELSE
(SELECT CMS1205 + ' ' + CMS1204 FROM sysUSER WHERE CMS1201 = 'PSUSER')
END AS CollectorId
,CAST(A.CMS512 AS nvarchar(max)) AS [Note]
FROM ACTIVITY AS A
LEFT JOIN sysUSER AS U
ON A.CMS503 = U.CMS1201
WHERE A.CMS504 NOT IN (411,500,511,711,804,900,901,903,907,2000,999777)
AND A.CMS504 NOT BETWEEN 1102 AND 1199
AND A.CMS502 >= DATEADD(D, -2, GETDATE())
) AS S
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52956124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: incorrect password and receive an alert from program django please im new to django and i want to add source code to my project, when the user try to connect, if the password equal to "test" i want that the template be showed again to the user with an alert javascript that says that the the password is incorrect
here is my code:
views.py
#Authentification
def home(request):
if request.method=='POST':
admin1=AdministrateurForm(request.POST)
if admin1.is_valid():
nom=admin1.cleaned_data['login']
pwd=admin1.cleaned_data['passe']
for admin1 in Administrateur.objects.all():
if admin1.login==nom and admin1.passe==pwd:
return redirect(menuPrincipal)
else:
return redirect(home)
else:
admin1=AdministrateurForm()
return render(request,'GPI/index.html',locals())
template:
index.html:
above of the code i put this one :
<body id="page-top" class="index">
{% if pwd == "test" %}
<script type="text/javascript">alert("Mot de passe ou login incorrect !")</script>
{% else %}
{% endif %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27019247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular Karma Mock Error response Test always fail because login.subscribe error don't have error.status
error.status -> 'undefined'
Test:
it('form submit fail', () => {
expect(element.querySelector('#login-email')).toBeDefined();
expect(element.querySelector('#login-password')).toBeDefined();
updateForm('test@gmail.com', '123456');
component.login(component.loginForm);
httpMock
.expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
.error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
httpMock.verify();
expect(component.hasError).toBeTruthy();
expect(component.error).toEqual('unregisteredPair');
});
component.login:
login(form: FormGroup): void {
if (this.lockForm) {
return;
}
if (!form.valid) {
Object.keys(form.controls).forEach(key => {
form.get(key).markAsTouched();
});
this.lockForm = false;
return;
}
this.lockForm = true;
this.hasError = false;
this.error = '';
this.loading = true;
this.service.login(form.value.email, form.value.password).subscribe(() => {
this.router.navigate([this.service.redirectUrl || '/dashboard']);
this.loading = false;
}, (error: any) => {
this.hasError = true;
this.lockForm = false;
this.error = error.status === 400 ? 'unregisteredPair' : error.error.localizationKey;
this.loading = false;
});
}
at the end of this test got error:
TypeError: Cannot read property 'localizationKey' of undefined
this happen then status != 400
A: Solved this problem by using spyOn
spyOn works similar to the httpMock (but for calling some functions), here's an example:
it('form submit fail', () => {
email.value = 'test@test.test';
email.dispatchEvent(new Event('input'));
password.value = '123456';
password.dispatchEvent(new Event('input'));
spyOn(service, 'login').and
.returnValue(
Observable.throw(
new HttpErrorResponse({
error: {
message: 'Here some message...',
localizedKey: 'someKey'
},
status: 500
})
)
);
button.click();
expect(component.hasError).toBeTruthy();
expect(component.lockForm).toBeFalsy();
expect(component.error).toEqual('someKey');
});
In this example spyOn emulate response from AuthService.login() (when in call) and return expected response for unit testing
For success response use Observable.of() and new HttpResponse()
A: Manually call the fixture.detectChanges()
it('form submit fail', () => {
fixture.detectChanges();
expect(element.querySelector('#login-email')).toBeDefined();
expect(element.querySelector('#login-password')).toBeDefined();
updateForm('test@gmail.com', '123456');
component.login(component.loginForm);
httpMock
.expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
.error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
httpMock.verify();
expect(component.hasError).toBeTruthy();
expect(component.error).toEqual('unregisteredPair');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47936620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Image interpolation - nearest neighbor (Processing) I've been having trouble with an image interpolation method in Processing. This is the code I've come up with and I'm aware that it will throw an out of bounds exception since the outer loop goes further than the original image but how can I fix that?
PImage nearestneighbor (PImage o, float sf)
{
PImage out = createImage((int)(sf*o.width),(int)(sf*o.height),RGB);
o.loadPixels();
out.loadPixels();
for (int i = 0; i < sf*o.height; i++)
{
for (int j = 0; j < sf*o.width; j++)
{
int y = round((o.width*i)/sf);
int x = round(j / sf);
out.pixels[(int)((sf*o.width*i)+j)] = o.pixels[(y+x)];
}
}
out.updatePixels();
return out;
}
My idea was to divide both components that represent the point in the scaled image by the scale factor and round it in order to obtain the nearest neighbor.
A: For getting rid of the IndexOutOfBoundsException try caching the result of (int)(sf*o.width) and (int)(sf*o.height).
Additionally you might want to make sure that x and y don't leave the bounds, e.g. by using Math.min(...) and Math.max(...).
Finally, it should be int y = round((i / sf) * o.width; since you want to get the pixel in the original scale and then muliply with the original width. Example: Assume a 100x100 image and a scaling factor of 1.2. The scaled height would be 120 and thus the highest value for i would be 119. Now, round((119 * 100) / 1.2) yields round(9916.66) = 9917. On the other hand round(119 / 1.2) * 100 yields round(99.16) * 100 = 9900 - you have a 17 pixel difference here.
Btw, the variable name y might be misleading here, since its not the y coordinate but the index of the pixel at the coordinates (0,y), i.e. the first pixel at height y.
Thus your code might look like this:
int scaledWidth = (int)(sf*o.width);
int scaledHeight = (int)(sf*o.height);
PImage out = createImage(scaledWidth, scaledHeight, RGB);
o.loadPixels();
out.loadPixels();
for (int i = 0; i < scaledHeight; i++) {
for (int j = 0; j < scaledWidth; j++) {
int y = Math.min( round(i / sf), o.height ) * o.width;
int x = Math.min( round(j / sf), o.width );
out.pixels[(int)((scaledWidth * i) + j)] = o.pixels[(y + x)];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10119037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery Unexpected Token ILLEGAL For some reason, a space appears before one of the variables in my jQuery output. I get a JS error saying unexpected token ILLEGAL. I assume this means that there is a character somewhere that is not allowed. The problem is that I can't figure out where it's coming from.
This is my jQuery:
$(document).ready(function(){
$('select').each(function(){
var selectName = $(this).prop("name");
var selectOpts = $(this).find("option");
var selectPar = $(this).parent();
var hiddenInput = '<input type="hidden" name="'+selectName+'" value="">';
var menu = '<dv class="jqSelect">' +
'<div class="selected" id="'+selectName+'-selected"><div id="'+selectName+'-text">'+$(this).find(":selected").text()+'</div>' +
'<div class="caret" onclick="$(\'ul#'+selectName+'-menu\').toggle();"></div>' +
'<ul id="'+selectName+'-menu">';
selectOpts.each(function(){
var optVal = $(this).prop("value");
var optStr = $(this).text();
if($(this).is(":selected")){
$('#'+selectName+'-selected').text(optStr);
}
menu += '<li onclick="$(\'#'+selectName+'-text\').text(\''+optStr+'\');$(\'#'+selectName+'-menu\').hide();$(\'input[name="'+selectName+'"]\').prop(\'value\', \''+optVal+'\');">'+optStr+'</li>';
});
menu += '</ul></div>';
selectPar.html(menu + hiddenInput);
$('ul#'+selectName+'-menu').hide();
});
});
This is where the space is happening in Chrome dev console:
<li onclick="$('#category_id-text').text('Tutorials');$('#category_id-menu').hide();$('input[name=" category_id"]').prop('value',="" '7');"="">Tutorials</li>
A: You have quote issues as mentioned, but the main issue is you have inline event handlers in the generated html. That is not a good idea.
If you need to add actions to generated elements, use the
data-nameinlowercase="value"
on the elements, then assign the event handlers using
$("#container").on("event name","element selector",function() {
someFunction($(this).data("nameinlowercase"));
});
which will handle future elements too
In your case
'<div class="caret" data-togglename="ul#'+selectName+'-menu"></div>'
and
$("#caretParentContainerId").on("click",".caret",function() {
$($(this).data("togglename")).toggle();
});
where caretParentContainerId is the ID of the container that wraps the .caret elements
A: The problem is in the double quotes inside others double quotes, like this
<li onclick="something="something more" something else"></li>
If you want keep your code structure try this:
menu += '<li onclick="$(\'#' + selectName + '-text\').text(\'' + optStr + '\');$(\'#' + selectName + '-menu\').hide();$(\'input[name=' + selectName + ']\').prop(\'value\', \'' + optVal + '\');">' + optStr + '</li>';
but I think it's better you do something like this:
menu += '<li onclick="myFunction(' + selectName + ", " + optStr + ", " + optVal + ')">' + optStr + '</li>';
and create a function like this:
function myFunction(selectName, optStr, optVal) {
$("#" + selectName + "-text").text(optStr);
$("#" + selectName + "-menu").hide();
$("input[name='" + selectName + "']").prop("value", optVal);
}
With this is easier to debug and simplifly your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24548373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: PHP Form coding with no response I have used php code inside my page but its not working in localhost showing the undefined variable in the textboxes and selectboxes which I have given like this:
$propertyid = ereg_replace("[^A-Za-z0-9-]", "", $_POST['propertyid']);
$propertyname = ereg_replace("[^A-Za-z0-9]", "", $_POST['propertyname']);
$propertytype = ereg_replace("[^A-Z a-z0-9]", "", $_POST['propertytype']);
$propertydealtype = ereg_replace("[^A-Z a-z0-9]", "", $_POST['propertydealtype']);
$propertystreet = ereg_replace("[^A-Z a-z0-9]", "", $_POST['propertystreet']);
<td width="249" align="left" valign="middle">PropertyID:</td>
<td width="739"><input name="propertyid" type="text" value="<?php echo "$propertyid"; ?>" /></td>
</tr>
<tr>
<td width="249" align="left" valign="middle">PropertyName:</td>
<td width="739"><input name="propertyname" type="text" value="<?php echo "$propertyname"; ?>" /></td>
</tr>
<tr>
<td align="left" valign="middle">Property Type:</td>
<td><select name="propertytype">
<option value="<?php echo "$propertytype"; ?>"><?php echo "$propertytype"; ?></option>
<option value="Appartment/Fla">Appartment/Flat</option>
<option value="Farm House">Farm House</option>
<option value="Guest House">Guest House</option>
<option value="Lord">Lord</option>
<option value="Hostel">Hostel</option>
</select></td>
</tr>
<tr>
<td align="left" valign="middle">Deal Type:</td>
<td><select name="propertydealtype">
<option value="<?php echo "$propertydealtype"; ?>"><?php echo "$propertydealtype"; ?></option>
<option value="For Sale">For Sale</option>
<option value="For Rent">For Rent</option>
<option value="For Lease">For Lease</option>
<option value="Ejara">Ejara</option>
<option value="Sar Qulfi">Sar Qulfi</option>
</select></td>
<tr>
<td align="left" valign="middle">Property Streeet:</td>
<td><input name="propertystreet" type="text" value="<?php echo "$propertystreet"; ?>" /></td>
</tr>
inside of each box whenever i am executing in localhost receiving errors inside boxes.
A: I'm not sure how really ereg_replace works, but first of all it's deprecated, and second - I think you cannot have spaces between the expressions => "[^A-Z a-z0-9]" should be "[^A-Za-z0-9]"
A: Your input tags should be inside a form tag... where is your form tag?
$_POST retrieve your input data from a form
A: during echo, variables don't need to be in quotes. so it's better like this:
<?php echo $propertytype; ?>.
undefined variable error means that probably the $_POST are not defined. But in this case you should get errors there as well.
From php page about function ereg_replace : This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15835852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to iterate over an dictionary without knowing the keys, while getting key and object? I have an NSDictionary and want to iterate over the objects. But at the same time, I need to know the key of the dictionary.
I remember there was a special, fancy form of fast enumeration, but have forgotten the exact syntax.
Anyone?
A: I think what you want is something like this:
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
Taken from here.
A: This is also a good choice if you like blocks.
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
}]
A: for (id key in mydictionary) {
id mything = [mydictionary objectForKey:key];
}
A: keyEnumerator returns an object that lets you iterate through each of the keys in the dictionary. From here
A: To my knowledge, at the time when you asked the question, there was only one way of traversing keys and values at the same time: CFDictionaryApplyFunction.
Using this Core Foundation function involves an ugly C function pointer for the body of the loop and a lot of not-less-ugly, yet toll-free-bridged casting.
@zekel has the modern way of iterating a dictionary. Vote him up!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3064933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: adding objects to array in localStorage Ok, I've tried to follow examples here, I know there might be a few different ways of adding objects to an array in localstorage and not overwriting it but I'm failing to find at least one of them.
Got this code to store objects in array but it's overwriting itself. May anyone show me what am I missing? (And I'm afraid I could be missing a lot).
function addEntry() {
var entryTitle = document.getElementById("entryTitle").value;
var entryText = document.getElementById("entryText").value;
var entry = {
"title": entryTitle,
"text": entryText
};
localStorage.setItem("entry", JSON.stringify(entry));
var allEntries = [];
allEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(allEntries));
};
A: When you use setItem it overwrites the item which was there before it. You need to use getItem to retrieve the old list, append to it, then save it back to localStorage:
function addEntry() {
// Parse any JSON previously stored in allEntries
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var entryTitle = document.getElementById("entryTitle").value;
var entryText = document.getElementById("entryText").value;
var entry = {
"title": entryTitle,
"text": entryText
};
localStorage.setItem("entry", JSON.stringify(entry));
// Save allEntries back to local storage
existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
};
Here is a fiddle which demonstrates the above.
A: adding objects to array in localStorage (Ionic):
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var testObject ={username:this.username,
mobile:this.mobile,
email:this.email,
type:this.type,
password:this.password};
localStorage.setItem('testObject', JSON.stringify(testObject));
existingEntries.push(testObject);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
A: Maybe you just need to fetch the entries before pushing the new one:
var allEntries = JSON.parse(localStorage.getItem("allEntries")) || [];
allEntries.push(entry);
//etc...
A:
const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
arr.push(object);
localstorage.setItem(JSON.stringify('key_name', arr);
A: HTML5 localStorage lets you store key/value pairs of data. Both key and value needs to be a string. To store arrays as a key or value you need to encode the array into a JSON string. And while retrieving you need to decode it back to an array.
const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
const data = [arr, ...[object]];
localstorage.setitem(JSON.stringify('key', data);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19635077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Run multiple git commands in a mean stack project using Bash script? We are using multiple branches (development, testing and master). Now the site is done with the most part of the application and bugs are solved. Everytime i have to push the changes on development branch from my local system and login onto server, go to the path and run these commands:
*
*git checkout development
*git pull origin development
*git checkout testing
*git merge origin development
Can we make these 4 commands into one?
EDIT:
I created the bash script but how to add the pasword in the script ?
#!/bin/bash
echo "This is a shell script"
git status
git pull origin development
?
A: If you setup gitcredentials (https://git-scm.com/docs/gitcredentials.html) you should be able to script all of it like that:
#!/bin/bash
echo "This is a shell script"
my_pass="awesomePassword"
server="awesomeServer"
sshpass -p $my_pass ssh $server "git status; git pull origin development; git checkout testing; git merge origin development"
(untested)
You will have to install sshpass and you should note that it is not really a good practice to hardcord passwords like that. Could be avoided by using user input.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44454729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django - ListView with form, How to redirect back to the Form page? So, I have a ListView with exercices list (paginated 1 per page). In each page I have few input the user need to fill up. I managed to find a solution to how to attached the ListView with the Form but i cant find a solution on how to stay on the same page after the submit.
url's:
urlpatterns = [
path('programs/', ProgramListView.as_view(), name='web-programs'),
path('programs/<int:pk>/', ExerciseListView.as_view(), name='program-detail'),
path('data/', views.add_data, name='data-submit'),
views.py (updated with def form_valid):
class ExerciseListView(LoginRequiredMixin,FormMixin, ListView):
model = Exercise
context_object_name = 'exercises'
form_class = DataForm
paginate_by = 1
def get_queryset(self):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
return Exercise.objects.filter(program=program_num)
def form_valid(self, dataform):
program_num = get_object_or_404(Program, pk=self.kwargs.get('pk'))
exercises = Exercise.objects.filter(program=program_num)
for exe in exercises:
dataform.instance.exercise = exe.pk
return super(ExerciseListView, self).form_valid(dataform)
def add_data(request):
if request.method == "POST":
form = DataForm(request.POST)
if form.is_valid():
form.save()
# Data.objects.create(address=form.cleaned_data['form'])
return redirect(?)
template.html:
{% extends "program/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h3> Program Exercises List </h3>
{% for exercise in exercises %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
{% if user.is_superuser %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'exercise-update' exercise.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'exercise-delete' exercise.id %}">Delete</a>
<p class="article-content">{{ exercise.name }}</p>
{% else %}
<p class="article-content">{{ exercise.name }}</p>
{% endif %}
</div>
<div class="article-metadata">
<p class="article-content">{{ exercise.description }}</p>
<p class="article-content">{{ exercise.breath_method}}</p>
<p class="article-content">{{ exercise.recovery_method }}</p>
<p class="article-content">{{ exercise.measure_method }}</p>
<p class="article-content">{{ exercise.load_share }}</p>
<p class="article-content">{{ exercise.notes }}</p>
<p class="article-content">{{ exercise.extra_info }}</p>
<p class="article-content">{{ exercise.reps }}</p>
<p class="article-content">{{ exercise.sets }}</p>
</div>
<form action="{% url 'data-submit' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Exercise Measurements</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Save</button>
</div>
</form>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous Exercise</a>
{% endif %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next Exercise</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{% url 'web-home' %}">Exit</a>
{% endif %}
{% endif %}
{% endblock content %}
forms.py:
class DataForm(forms.ModelForm):
class Meta:
model = Data
fields = ['exercise', 'set_number', 'spo2', 'hr']
In the views.py, i left the "redirect" with "?" because i don't know what to add there.
I can't change the "action" in the template.html because this link is for def add_data(request)
so it will save my inputs.
Once i submit, it saves the new data to my DB but i don't know how to stay on the same page for continue my exercises.
Thanks.
A: *
*You need to use jQuery to achieve this result. Download it, paste to js folder and add it to program/base.html
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
*I'd like to recommend you to add a js block into base.html
somewhere at the bottom of the file
{% block js %}{% endblock js %}
*Then, do this:
<block js>
<script>
$("#submit-btn").submit(function(event) {
// prevent default action, so no page refreshing
event.preventDefault();
var form = $(this);
var posting = $.post( form.attr('action'), form.serialize() );
posting.done(function(data) {
// done
});
posting.fail(function(data) {
// fail
});
});
</script>
<endblock>
...
<form action="{% url 'data-submit' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Exercise Measurements</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" id="submit-btn" type="submit">Save</button>
</div>
</form>
A: You have Program in Exercise so use it get program id looking at your DataForm you have exercise field if am not wrong is foreign-key
from django.shortcuts import redirect, reverse
def add_data(request):
page=request.GET.get('page')
page='?page={}'.format(page) if page else ''
if request.method == "POST":
form = DataForm(request.POST)
if form.is_valid():
data=form.save()
return redirect(reverse('program-detail', kwargs={'pk':data.exercise.program.pk})+ page)
For redirecting to same page you check and pass page parmameter in url in form action like
<form action="{% url 'data-submit' %}{%if request.GET.page%}?page={{request.GET.page}}{%endif%}" method="POST" enctype="multipart/form-data">{% csrf_token %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63828671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do we have only one Store for an Ember App I am confused how Store works in Ember. Do we have one store managing all the models in an ember app? Is it possible to make multiple stores for multiple models? I have right now three models and as it seems they are using the same store. Would it be possible to have different stores for different models?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22982403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I expose a registry hosted in Minikube? I have started a Kubernetes cluster with Minikube. I used a simple deployment file to create a deployment that runs the Registry container:
apiVersion: apps/v1
kind: Deployment
metadata:
name: registry
labels:
app: registry
spec:
replicas: 3
selector:
matchLabels:
app: registry
template:
metadata:
labels:
app: registry
spec:
containers:
- name: registry
image: registry:latest
ports:
- containerPort: 80
After this, I expose the deployment using a service:
$ kubectl expose deployment/registry --type="LoadBalancer" --port 5000
$ minikube service registry
This exposes my registry to the host machine. I can navigate to http://172.17.174.88:31826/v2/_catalog in my browser and see there's no repositories yet. I have an image running an ASP.Net WebApi project called WeatherApp on my host machine's docker. I run these commands:
$ docker tag 0a259f7ce186 172.17.174.88:31412/weatherapp
$ docker push 172.17.174.88:31412/weatherapp
This causes the following error:
The push refers to repository [172.17.174.88:31412/weatherapp] Get
https://172.17.174.88:31412/v2/: dial tcp 172.17.174.88:31412:
connect: no route to host
I think the problem is that my docker client is trying to connect to the registry over HTTPS, which will not work. How can I force my docker client to use HTTP to push the image to my registry?
A: I‘m afraid that you will have no chance to fall back to just http. You are forced to use https. You need to configure insecure registries in your docker client.
This might help: https://docs.docker.com/registry/insecure/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61367940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error in SQL statement with inserting I am trying to insert user inputted data into database, but am getting the error "Syntax error: Encountered "[" at line 1, column 160." Here is my code, what am I doing wrong?`
if (action.getSource() == Submit_button)
{
try
{
sql = "INSERT INTO Customer (FNAME, LNAME, AGE, LICNUM, STATE, CAR_TYPE, RENTDATE, RETURNDATE, TOTAL, PAYTYPE, RETURNED) VALUES(";
sql = sql + "'" + f_name.getText() + "'" + "," + "'" + l_name.getText() + "'" + "," + Age + "," + "'" + liscense_num.getText() + "'" + "," + "'"
+ issuing.getText() + "'" + "," + "'" + car_select.getToolkit() + "'" + "," + "'" + rental.getText() + "'" + "," + "'" + return_d.getText() + "'"
+ "," + total.getText() + "," + "'" + button_val.getText() + "'" + "," + "'true'" + ")";
myStatement.execute(sql);
System.out.print("Record has Been added to database");
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
A: can you change query into this?
sql = "INSERT INTO Customer (FNAME, LNAME, AGE, LICNUM, STATE, CAR_TYPE, RENTDATE, RETURNDATE, TOTAL, PAYTYPE, RETURNED) VALUES('"+f_name.getText()+"','"+l_name.getText()+"','"+Age+"','"+liscense_num.getText()+"','"+issuing.getText()+"','"+car_select.getToolkit()+"','"+rental.getText()+"','"+return_d.getText()+"','"+total.getText()+"','"+button_val.getText()+"','true') ";
A: --Not an answer:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "[" at line 1, column 160.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at Auto.actionPerformed(Auto.java:381)
at java.awt.Button.processActionEvent(Unknown Source)
at java.awt.Button.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: ERROR 42X01: Syntax error: Encountered "[" at line 1, column 160.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatementOrSearchCondition(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 25 more
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36831166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is Task.Delay breaking the STA state of the thread? Introduction
This is a lengthy question! You will find some background on the problem at the beginning, then code samples, which have been simplified for representation and the Question after that. Please read in any order that you find good for you!
Background information
I am writing a Proof-of-Concept part for an application for communicating with an STA COM. This part of the application has the requirement of running in a Single-Threaded Apartment (STA) context in order to communicate with said STA COM. The rest of the application runs in a MTA context.
Current state
What I have come up with so far is creating a Communication class that contains a while loop, running in a STA. The work that needs to be relayed to the COM object is queued from the outside to the Communication class via ConcurrentQueue. The work items are then dequeued in the while loop and the work is performed.
Code context
Communication class
This is a static class, containing a loop that is intended to run in STA state and check if some work needs to be done by the COM and dispatch the work to the handler.
static class Communication
{
#region Public Events
/// This event is raised when the COM object has been initialized
public static event EventHandler OnCOMInitialized;
#endregion Public Events
#region Private Members
/// Stores a reference to the COM object
private static COMType s_comObject;
/// Used to queue work that needs to be done by the COM object
private static ConcurrentQueue<WorkUnit> s_workQueue;
#endregion Private Members
#region Private Methods
/// Initializes the COM object
private static void InternalInitializeCOM()
{
s_comObject = new COMType();
if (s_comObject.Init())
{
OnCOMInitialized?.Invoke(null, EventArgs.Empty);
}
}
/// Dispatches the work unit to the correct handler
private static void HandleWork(WorkUnit work)
{
switch (work.Command)
{
case WorkCommand.Initialize:
InternalInitializeCOM();
break;
default:
break;
}
}
#endregion Private Methods
#region Public Methods
/// Starts the processing loop
public static void StartCommunication()
{
s_workQueue = new ConcurrentQueue<WorkUnit>();
while (true)
{
if (s_workQueue.TryDequeue(out var workUnit))
{
HandleWork(workUnit);
}
// [Place for a delaying logic]
}
}
/// Wraps the work unit creation for the task of Initializing the COM
public static void InitializeCOM()
{
var workUnit = new WorkUnit(
command: WorkCommand.Initialize,
arguments: null
);
s_workQueue.Enqueue(workUnit);
}
#endregion Public Methods
}
Work command
This class describes the work that needs to be done and any arguments that might be provided.
enum WorkCommand
{
Initialize
}
Work unit
This enumeration defines the various tasks that can be performed by the COM.
class WorkUnit
{
#region Public Properties
public WorkCommand Command { get; private set; }
public object[] Arguments { get; private set; }
#endregion Public Properties
#region Constructor
public WorkUnit(WorkCommand command, object[] arguments)
{
Command = command;
Arguments = arguments == null
? new object[0]
: arguments;
}
#endregion Constructor
}
Owner
This is a sample of the class that owns or spawns the Communication with the COM and is an abstraction over the Communication for use in the rest of the application.
class COMController
{
#region Public Events
/// This event is raised when the COM object has been initialized
public event EventHandler OnInitialize;
#endregion Public Events
#region Constructor
/// Creates a new COMController instance and starts the communication
public COMController()
{
var communicationThread = new Thread(() =>
{
Communication.StartCommunication();
});
communicationThread.SetApartmentState(ApartmentState.STA);
communicationThread.Start();
Communication.OnCOMInitialized += HandleCOMInitialized;
}
#endregion Constructor
#region Private Methods
/// Handles the initialized event raised from the Communication
private void HandleCOMInitialized()
{
OnInitialize?.Invoke(this, EventArgs.Emtpy);
}
#endregion Private Methods
#region Public Methods
/// Requests that the COM object be initialized
public void Initialize()
{
Communication.InitializeCOM();
}
#endregion Public Methods
}
The problem
Now, take a look at the Communication.StartCommunication() method, more specifically this part:
...
// [Place for a delaying logic]
...
If this line is substituted with the following:
await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);
// OR
await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(true);
during inspection the final stop - Communication.InternalInitializeCOM() the apartment of the thread seems to be MTA.
However, if the delaying logic is changed to
Thread.Sleep(100);
the CommunicationInternalInitializeCOM() method seems to be executed in a STA state.
The inspection was done by Thread.CurrentThread.GetApartmentState().
The Question
Can anyone explain to me why does Task.Delay break the STA state? Or am I doing something else that is wrong here?
Thank you!
Thank you for taking all this time to read the question! Have a great day!
A: Hans has nailed it. Technically, your code is breaking because there's no SynchronizationContext captured by the await. But even if you write one, it won't be enough.
The one big problem with this approach is that your STA thread isn't pumping. STA threads must pump a Win32 message queue, or else they're not STA threads. SetApartmentState(ApartmentState.STA) is just telling the runtime that this is an STA thread; it doesn't make it an STA thread. You have to pump messages for it to be an STA thread.
You can write that message pump yourself, though I don't know of anyone brave enough to have done this. Most people install a message pump from WinForms (a la Hans' answer) or WPF. It may also be possible to do this with a UWP message pump.
One nice side effect of using the provided message pumps is that they also provide a SynchronizationContext (e.g., WinFormsSynchronizationContext / DispatcherSynchronizationContext), so await works naturally. Also, since every .NET UI framework defines a "run this delegate" Win32 message, the underlying Win32 message queue can also contain all the work you want to queue to your thread, so the explicit queue and its "runner" code is no longer necessary.
A: Because after await Task.Delay() statement , your code runs inside one of the ThreadPool thread, and since the ThreadPool threads are MTA by design.
var th = new Thread(async () =>
{
var beforAwait = Thread.CurrentThread.GetApartmentState(); // ==> STA
await Task.Delay(1000);
var afterAwait = Thread.CurrentThread.GetApartmentState(); // ==> MTA
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55761773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to detect C symbol conflicts in R The curl R package was giving misterious segfaults on Solaris (both GCC and Solaris Studio build of R). Through trial and error I found that the solution was to rename an internal C function called fetch to something different and now everything works fine.
I suppose there must have been some kind of naming conflict, but I don't understand why the compiler did not warn me. Where can I find if a function has been defined elsewhere? How can I detect/prevent/debug such problems in the future?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30339566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compress image of any format(jpeg,png etc) in Asp.net with c# without effecting height & width? I have gone through many websites but those code are not working as expected. Some reduced the dimensions & some increases the image size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35202046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Complex SQL Query with Business Logic I'm stuck with a complex query where I need to implement some business logic. Below are the tables that I'm having (I have omitted extra columns for readabality)
Team - TeamID, TeamName
TeamMember - MemberID, TeamID, MemberName
Question - QuestionID, CategoryID, DifficultyLevelID, Question
Category - CategoryID, CategoryName
DifficultyLevel - DifficultyLevelID, DifficultyLevelName
QuestionOffered - QuestionOfferedID, QuestionID, OfferedTo
Now, The business logic is, I have 10 categories (like Science, History, Geography etc.) and 3 Difficulty level (i.e. Easy, Medium, Hard). Each category and difficulty level have 5 questions.
So 3 x 5 = 15 questions for each category (5 Easy, 5 Medium, 5 Hard). Total 15 x 10 (categories) = 150 questions.
Now I want that everytime a user comes in, I'll check whether I have already offered (can be tracked from QuestionsOffered table) all the 5 questions under that category and difficulty level, if so, then I won't show that category and difficulty level again.
So, say I come in first time I'll get all the category and then selecting a category I'll get all the difficulty level. Now I select Easy and proceed. So under each category I can select a particular difficulty level 5 times after that I'll get the category and other difficulty levels (i.e. Medium and Hard) after I have done with all 5 easy.
So, in this way, if I'm done with all 5 easy, 5 medium and 5 hard questions under a same category, the category itself won't show up.
Ofcourse I can implement this logic in programming for populating the category but that would end up with numerous lines of code.
So is there any way to check this business logic in SQL? So that I will get the data to populate?
A: inner join your questions, categories, and levels together, then left join to the questions already offered. Filter where any field in the questions offered table is null, and you will have a list of unanswered questions? perhaps?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27299611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to place UIView Over Cell Border Hi I want to place a UIView at top of cell but when I show this cell a border of cell is over a UIView. How can I resolve it?
This is my result
screen of my result
A: for all those who have had this problem here is the solution:
override func awakeFromNib() {
super.awakeFromNib()
draw(self.frame)
}
override func draw(_ rect: CGRect) {
UIColor.gray.set()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 20)
path.lineWidth = 2
path.stroke()
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68729549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to return sequelize sum as json? How do I return value in json?
exports.get = id => Model.sum('price',
{
where: {
id,
}
}
);
result
23
desired
{ sum: 23 }
A: You can do that in 2 ways :
1. Simple change the response :
exports.get = id => Model.sum('price',
{
where: {
id,
}
}
).then(sum => {sum}); //<----- Little hack
2. Use sequelize.fn , Below one will return array , so you need to return the first element of array , for your expected result
exports.get = id => Model.findAll({
attributes: [[sequelize.fn('SUM', sequelize.col('price')), 'sum']] ,
where : { id }
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52023459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assumed role in AWS Lambda, access denied on SSM call I'm getting an error in my Lambda function, which calls SSM:
AccessDeniedException: User: arn:aws:sts::redacted:assumed-role/LambdaBackend_master_lambda/SpikeLambda is not authorized to perform: ssm:GetParameter on resource: arn:aws:ssm:eu-west-1:redacted:parameter/default/key/api
However, I'm pretty sure I configured this correctly:
Role, with AssumeRole for Lambda (although we know that works from the error message).
λ aws iam get-role --role-name LambdaBackend_master_lambda
{
"Role": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
]
},
"RoleId": "redacted",
"CreateDate": "2017-06-23T20:49:37Z",
"RoleName": "LambdaBackend_master_lambda",
"Path": "/",
"Arn": "arn:aws:iam::redacted:role/LambdaBackend_master_lambda"
}
}
And my policy:
λ aws iam list-role-policies --role-name LambdaBackend_master_lambda
{
"PolicyNames": [
"ssm_read"
]
}
λ aws iam get-role-policy --role-name LambdaBackend_master_lambda --policy-name ssm_read
{
"RoleName": "LambdaBackend_master_lambda",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ssm:DescribeParameters"
],
"Resource": "*",
"Effect": "Allow"
},
{
"Action": [
"ssm:GetParameters"
],
"Resource": "arn:aws:ssm:eu-west-1:redacted:parameter/*",
"Effect": "Allow"
}
]
},
"PolicyName": "ssm_read"
}
I've run it through the policy simulator and it seems to be fine!
A: In my case (I used AWS SDK for Go V2), I needed both ssm:GetParametersByPath and
ssm:GetParameter to make it work.
A: Played around with this today and got the following, dropping the s from ssm:GetParameters and using ssm:GetParameter seems to work when using the GetParameter action. ie AWS_PROFILE=pstore aws ssm get-parameter --name param_name. This weirded me out a bit because I cannot find this at all in the iam action docs here. However it does seem to work, and ssm is still a bit under documented.
Amazon has updated and moved it's docs. The new docs incude both ssm:GetParameters and ssm:GetParameter.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ssm:DescribeParameters"
],
"Resource": "*",
"Effect": "Allow"
},
{
"Action": [
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:eu-west-1:redacted:parameter/*",
"Effect": "Allow"
}
]
}
A: Ran into the same error today. The following Java code caused it when encrypted = false and paramName referred to an unencrypted parameter
GetParameterRequest request = new GetParameterRequest()
.withName(paramName)
.withWithDecryption(encrypted);
GetParameterResult resultPacket = ssmClient.getParameter(request);
The fix was to create the unencrypted parameter request without setting the WithDecryption flag - GetParameterRequest request = new GetParameterRequest().withName(paramName);
A: It really depends on the command you use in your Lambda.
If you use boto3.client('ssm').get_parameters(Names=[param1, param2]), then you need "Action": ["ssm:GetParameters"],
or alternatively when you use boto3.client('ssm').get_parameter(Name=param), you would need "Action": ["ssm:GetParameter"]
A: regarding the confusion ssm:GetParameter and ssm:GetParameters. I attached the policy AmazonEC2RoleforSSM to some user and ran into the same problem, "not authorized to perform: ssm:GetParameter" because this Policy only has ssm:GetParameters. AWS had a deprecation warning attached to that policy and recommended to use
AmazonSSMManagedInstanceCore instead, which has both Actions ssm:GetParameters and ssm:GetParameter. Which then worked fine.
A: In my case, I was using s3:GetObject and s3:ListBucket. To fix the error I had to add the bucket twice in resources and append to one of them a *. For example:
{
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"s3:GetObject",
"s3:ListBucket",
],
"Resource" : [
"arn:aws:s3:::mybucket/*",
"arn:aws:s3:::mybucket",
]
},
]
}
A: For me I had the path wrong (I was missing the leading / on the path name when making the request - it seems obvious but it's easy to miss and worth double checking if you're experiencing this issue.
❌ Wrong
var getParameterResponse = await _ssm.GetParameterAsync(new GetParameterRequest
{
Name = "my-component-namespace/my-parameter",
WithDecryption = true
});
✅ Correct
var getParameterResponse = await _ssm.GetParameterAsync(new GetParameterRequest
{
Name = "/my-component-namespace/my-parameter",
WithDecryption = true
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44734572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Minimise / maximise a div I ve created a chat appliction in one DIV.
Now i need it to be placed in the bottom of page, which should be minimised & maximized
Can any one help me
<div style="height:40px; width:300px; background-color:#CC66FF; position:absolute;bottom:15px;" >
<div id="vithu" style="height:40px; width:200px;"></div>
<span id="error_msg"></span>
<table>
<form method="post">
<tr>
<td><input type="text" name="txt_msg_box" id="txt_msg_box" ></td>
<td><input type="button" value="Chat" onClick="save_chat();" /></td>
</tr>
<input type="hidden" id="hdn_username" name="hdn_username" value="<?php echo rand_str();?>" />
</form>
</table>
</div>
A: I assume you are looking for something like this... modal windows using prototype
A: Use the jQuery to set the display property of the div to none. Add "divNotDisplayed" class when you hide the div. If this class is present then alter the size of other divs. Add "divDisplayed" class when you display the div and once again alter other divs.
Udachi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3465975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is an easy but reliable way to parse parameters in C? I have some input parameters like:
param1=param1Value¶m2=param2Value¶m3=param3Value...
These parameters are linked with the character '&', the parameter and its value is linked with '='. I want to parse them into a key-value-map like this:
[param1, param1Value], [param2, param2Value], [param3, param3Value],...
But because the parameter's value contains the tow key-characters, this would break the parameter-parsing procedure.
I was informed the parameter passer, who created these parameter format to easy customize, such as changing the parameter value for different application using sprintf. So its hard to persuade them to separator these parameters in a map-array.
I was originally going to use yacc/lex, but is to complicated to such a little-feature. sscanf can also parse text something like regexp, but it does not seem so easy to build a regexp-like string for my parameter-list.
Is there any simple but reliable way to parse them without key-character?
A: You can use strtok to tokenize the string at the '&' character, then split the "tokens" at '=' to get the parameter names and values.
The splitting at '=' can either be done with strtok as well (or rather strtok_r) or using strchr and strncpy/strcpy or strndup/strdup.
A: If you are guaranteed that pattern you could use a simple parse function.
If you are guaranteed a max length of key/value then fixed buffer + copy would be the simplest. Else you could first find location of separator, then malloc that size, etc.
As a simple example/concept with fixed size of max 100 i.e.:
#include <stdio.h>
int get_pair(char **p, char *key, char *val)
{
int esc = 0; /* escape level */
char *cp = key; /* current target */
*key = '\0'; /* if either is blank */
*val = '\0';
if (!*p || !**p)
return 0;
/* this could be done more elegant */
while (**p) {
if (**p == '=' && (esc & 1) == 0) {
*cp = '\0'; /* terminate */
cp = val; /* change target */
++(*p);
continue;
} else if (**p == '&' && (esc & 1) == 0) {
++(*p); /* skip & and break */
break;
}
if (**p == '\\') {
if((++esc & 1) == 0) /* if 2, 4, 6 ... \'s */
*cp++ = **p;
} else {
esc = 0;
*cp++ = **p;
}
++(*p);
}
*cp = '\0';
return 1;
}
int main(void)
{
char *data = "ab=123&a\\=42&m\\\\ed\\=\\&do\\\\\\\\=mix";
char key[100];
char val[100];
printf("Parse: %s\n", data);
while (get_pair(&data, key, val))
printf("key: %s\nval: %s\n\n", key, val);
return 0;
}
Output:
Parse: ab=123&a\=42&m\\ed\=\&do\\\\=mix
key: ab
val: 123
key: a=42
val:
key: m\ed=&do\\
val: mix
A: Yes, I have fixed them: while passer give me the parameters, they should use \ to escape the = and &, but the \ itself do not need to escape. While I extracted these parameters, I just replace the \& with &, and \= with '='. If the real value is \\=, just encoded it with \\\=. I do not need to analyse the \ character, just leave them where they are.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10136623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Debugging a group_by/summarise/do code in R I am often working with the dplyr package and group_by/summarise/do functions. I often have big datasets and it takes 2 or 3 hours to compute my functions (maybe it can be optimized but this is not the subject).
It happens that after 1.5 hour of calculation, my do function gives an error, because I forgot to take into account one specific case in my code. The only problem is that I do not know which iteration gives this error and generally, I have to create loops to replace my group_by / summarise / do code in order to know what is the data giving a problem.
A really simple example to explain my problem... Cause generally I work with some complicated own-created functions with lots of groups.
require(dplyr)
FUN <- function(x) {
for (i in 1:which(!is.na(x$value))[1])
{
print("TEST")
}
}
df <- data.frame(ID = c(rep("ID1",10), rep("ID2", 20), rep("ID3", 5)),
value= c(sample(1:100, 10), rep(NA, 20), sample(0:50, 5)))
Result <- group_by(df, ID) %>%
do(Res=FUN(.))
Here I will have an error for the second group (group by ID2) because all values are NA and the loop in FUN can't work. To know that my problem comes from ID2, I would do something like this :
for (j in 1:length(unique(df$ID)))
{
Interm <- df[df$ID==unique(df$ID)[j],]
Res <- FUN(Interm)
print(j)
}
Thanks to this I know that my problem comes from j=2 so from ID2.
This is okay for simple calculation like this but it really takes a long time for my functions. For example, right know my code with group_by/do is giving an error after 45 minutes, I did a two-loop code to know what is the data giving the error and after 1.5 hour, it is still running... When I will find the error, I will just add one line to my function (FUN) to take into account this specific case, re-run the do code and maybe have another error 1h later...
Simple question : Is there a way to know from what data the code is giving an error with the group_by/do code ?
Thanks
A: Frank's answer is by far the simplest, but here's a swatch of code I've worked on for mid-pipe debugging and such.
Caveat emptor:
*
*this code is under-tested;
*even if well-tested, there is no intention for this to be used in production or unattended use;
*it has not been blessed or even reviewed by any authors or contributors to dplyr and related packages;
*it currently works in R-3.4 and dplyr-0.7.4, but it is not taking advantage of many "goodnesses" that should be used, such as rlang and/or lazyeval;
*it works for my uses, not tested for yours.
Bug reports welcome, if/when you find something amyss.
Mid-pipe message
This can include just about anything you want:
mtcars %>%
group_by(cyl) %>%
pipe_message(whichcyl = cyl[1], bestmpg = max(mpg)) %>%
summarize(mpg=mean(mpg))
# Mid-pipe message (2018-05-01 09:39:26):
# $ :List of 2
# ..$ whichcyl: num 4
# ..$ bestmpg : num 33.9
# $ :List of 2
# ..$ whichcyl: num 6
# ..$ bestmpg : num 21.4
# $ :List of 2
# ..$ whichcyl: num 8
# ..$ bestmpg : num 19.2
# # A tibble: 3 x 2
# cyl mpg
# <dbl> <dbl>
# 1 4. 26.7
# 2 6. 19.7
# 3 8. 15.1
Mid-pipe assert
You can optionally just realize what's going on and look at the data quickly, allowing you to see the moment and then exit out of the pipe:
mtcars %>%
group_by(cyl) %>%
pipe_assert(all(mpg > 12), .debug=TRUE) %>%
summarize(mpg = mean(mpg))
# #
# # all(mpg > 12) is not TRUE ... in Group: cyl:8
# # 'x' is the current data that failed the assertion.
# #
# Called from: pipe_assert(., all(mpg > 12), .debug = TRUE)
# Browse[1]>
# debug at c:/Users/r2/Projects/StackOverflow/pipe_funcs.R#81: if (identical(x, .x[.indices[[.ind]], ])) {
# stop(.msg, call. = FALSE)
# } else {
# .x[.indices[[.ind]], ] <- x
# return(.x)
# }
# Browse[2]>
x
# # A tibble: 14 x 11
# # Groups: cyl [1]
# mpg cyl disp hp drat wt qsec vs am gear carb
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 18.7 8. 360. 175. 3.15 3.44 17.0 0. 0. 3. 2.
# 2 14.3 8. 360. 245. 3.21 3.57 15.8 0. 0. 3. 4.
# 3 16.4 8. 276. 180. 3.07 4.07 17.4 0. 0. 3. 3.
# 4 17.3 8. 276. 180. 3.07 3.73 17.6 0. 0. 3. 3.
# 5 15.2 8. 276. 180. 3.07 3.78 18.0 0. 0. 3. 3.
# 6 10.4 8. 472. 205. 2.93 5.25 18.0 0. 0. 3. 4.
# 7 10.4 8. 460. 215. 3.00 5.42 17.8 0. 0. 3. 4.
# 8 14.7 8. 440. 230. 3.23 5.34 17.4 0. 0. 3. 4.
# 9 15.5 8. 318. 150. 2.76 3.52 16.9 0. 0. 3. 2.
# 10 15.2 8. 304. 150. 3.15 3.44 17.3 0. 0. 3. 2.
# 11 13.3 8. 350. 245. 3.73 3.84 15.4 0. 0. 3. 4.
# 12 19.2 8. 400. 175. 3.08 3.84 17.0 0. 0. 3. 2.
# 13 15.8 8. 351. 264. 4.22 3.17 14.5 0. 1. 5. 4.
# 14 15.0 8. 301. 335. 3.54 3.57 14.6 0. 1. 5. 8.
# Browse[2]>
c
# Error: all(mpg > 12) is not TRUE ... in Group: cyl:8
or you can optionally update/change the data; realize that this modifies the data in the pipe, not the source, so is really only good in dev and/or one-off fixes:
mtcars %>%
group_by(cyl) %>%
pipe_assert(all(mpg > 12), .debug=TRUE) %>%
summarize(mpg = mean(mpg))
# #
# # all(mpg > 12) is not TRUE ... in Group: cyl:8
# # 'x' is the current data that failed the assertion.
# #
# Called from: pipe_assert(., all(mpg > 12), .debug = TRUE)
# Browse[1]>
# debug at c:/Users/r2/Projects/StackOverflow/pipe_funcs.R#81: if (identical(x, .x[.indices[[.ind]], ])) {
# stop(.msg, call. = FALSE)
# } else {
# .x[.indices[[.ind]], ] <- x
# return(.x)
# }
(Ignore the current line of debugged code, if ..., that's my stuff and not beautiful.) I'm in the debugger now, I can look at and alter/fix the data:
# Browse[2]>
x
# ...as before...
x$mpg <- x$mpg + 1000
If the data is changed, the pipe continues, otherwise it'll stop.
# Browse[2]>
c
# # A tibble: 3 x 2
# cyl mpg
# <dbl> <dbl>
# 1 4. 26.7
# 2 6. 19.7
# 3 8. 1015.
(The data can be changed but the labels cannot ... so if we had done x$cyl <- 99, it still would have shown 8 in rest of the pipe. This is a consequence of dplyr not allowing you to change grouping variables ... which is a good thing, IMO.)
There's also pipe_debug which always debugs, but it is less impressive. It also does not (currently) pass on changed data, so use pipe_assert for that (e.g., pipe_assert(FALSE,.debug=TRUE)).
Source, also available in my gist:
#' Mid-pipe assertions
#'
#' Test assertions mid-pipe. Each assertion is executed individually
#' on each group (if present) of the piped data. Any failures indicate
#' the group that caused the fail, terminating on the first failure.
#'
#' If `.debug`, then the interpreter enters the `browser()`, allowing
#' you to look at the specific data, stored as `x` (just the grouped
#' data if `is.grouped_df(.x)`, all data otherwise). If the data is
#' changed, then the altered data will be sent forward in the pipeline
#' (assuming you fixed the failed assertion), otherwise the assertion
#' will fail (as an assertion should).
#'
#' @param .x data.frame, potentially grouped
#' @param ... unnamed expression(s), each must evaluate to a single
#' 'logical'; similar to [assertthat::assert_that()], rather than
#' combining expressions with `&&`, separate them by commas so that
#' better error messages can be generated.
#' @param .msg a custom error message to be printed if one of the
#' conditions is false.
#' @param .debug logical, whether to invoke [browser()] if the
#' assertion fails; if `TRUE`, then when the debugger begins on a
#' fail, the grouped data will be in the variable `x`
#' @return data.frame (unchanged)
#' @export
#' @import assertthat
#' @md
#' @examples
#' \dontrun{
#'
#' library(dplyr)
#' library(assertthat)
#'
#' mtcars %>%
#' group_by(cyl) %>%
#' pipe_assert(
#' all(cyl < 9),
#' all(mpg > 10)
#' ) %>%
#' count()
#' # # A tibble: 3 x 2
#' # cyl n
#' # <dbl> <int>
#' # 1 4 11
#' # 2 6 7
#' # 3 8 14
#'
#' # note here that the "4" group is processed first and does not fail
#' mtcars %>%
#' group_by(cyl, vs) %>%
#' pipe_assert( all(cyl < 6) ) %>%
#' count()
#' # Error: all(cyl < 6) is not TRUE ... in Group: cyl:6, vs:0
#'
#' }
pipe_assert <- function(.x, ..., .msg = NULL, .debug = FALSE) {
if (is.grouped_df(.x)) {
.indices <- lapply(attr(.x, "indices"), `+`, 1L)
.labels <- attr(.x, "labels")
} else {
.indices <- list(seq_len(nrow(.x)))
}
for (assertion in eval(substitute(alist(...)))) {
for (.ind in seq_along(.indices)) {
.out <- assertthat::see_if(eval(assertion, .x[.indices[[.ind]],]))
if (! .out) {
x <- .x[.indices[[.ind]],]
if (is.null(.msg)) .msg <- paste(deparse(assertion), "is not TRUE")
if (is.grouped_df(.x)) {
.msg <- paste(.msg,
paste("in Group:",
paste(sprintf("%s:%s", names(.labels),
sapply(.labels, function(z) as.character(z[.ind]))),
collapse = ", ")),
sep = " ... ")
}
if (.debug) {
message("#\n", paste("#", .msg), "\n# 'x' is the current data that failed the assertion.\n#\n")
browser()
}
if (identical(x, .x[.indices[[.ind]],])) {
stop(.msg, call. = FALSE)
} else {
.x[.indices[[.ind]],] <- x
return(.x)
}
}
}
}
.x # "unmodified"
}
#' Mid-pipe debugging
#'
#' Mid-pipe peek at the data, named `x` within [browser()], but
#' *changes are not preserved*.
#'
#' @param .x data.frame, potentially grouped
#' @return data.frame (unchanged)
#' @export
#' @md
#' @examples
#' \dontrun{
#'
#' library(dplyr)
#'
#' mtcars %>%
#' group_by(cyl, vs) %>%
#' pipe_debug() %>%
#' count()
#'
#' }
pipe_debug <- function(.x) {
if (is.grouped_df(.x)) {
.indices <- lapply(attr(.x, "indices"), `+`, 1L)
.labels <- attr(.x, "labels")
} else {
.indices <- list(seq_len(nrow(.x)))
}
# I used 'lapply' here instead of a 'for' loop because
# browser-stepping after 'browser()' in a 'for' loop could continue
# through all of *this* code, not really meaningful; in pipe_assert
# above, since the next call after 'browser()' is 'stop()', there's
# little risk of stepping in or out of this not-meaningful code
.ign <- lapply(seq_along(.indices), function(.ind, .x) {
x <- .x[.indices[[.ind]],]
message("#",
if (is.grouped_df(.x)) {
paste("\n# in Group:",
paste(sprintf("%s:%s", names(.labels),
sapply(.labels, function(z) as.character(z[.ind]))),
collapse = ", "),
"\n")
},
"# 'x' is the current data (grouped, if appropriate).\n#\n")
browser()
NULL
}, .x = .x)
.x # "unmodified"
}
#' Mid-pipe status messaging.
#'
#' @param .x data.frame, potentially grouped
#' @param ... unnamed or named expression(s) whose outputs will be
#' captured, aggregated with [utils::str()], and displayed as a
#' [base::message()]; if present, a '.' literal is replace with a
#' reference to the `data.frame` (in its entirety, not grouped)
#' @param .FUN function, typically [message()] or [warning()] (for
#' when messages are suppressed); note: if set to `warning`, the
#' argument `call.=FALSE` is appended to the arguments
#' @param .timestamp logical, if 'TRUE' then a POSIXct timestamp is
#' appended to the header of the `str`-like output (default 'TRUE')
#' @param .stropts optional list of options to pass to [utils::str()],
#' for example `list(max.level=1)`
#' @return data.frame (unchanged)
#' @export
#' @md
#' @examples
#' \dontrun{
#'
#' library(dplyr)
#'
#' mtcars %>%
#' pipe_message( # unnamed
#' "starting",
#' group_size(.)
#' ) %>%
#' group_by(cyl) %>%
#' pipe_message( # named
#' msg = "grouped",
#' grps = group_size(.)
#' ) %>%
#' count() %>%
#' ungroup() %>%
#' pipe_message( # alternate function, for emphasis!
#' msg = "done",
#' .FUN = warning
#' )
#'
#' head(mtcars) %>%
#' pipe_message(
#' list(a = list(aa=1, bb=2, cc=3))
#' )
#' head(mtcars) %>%
#' pipe_message(
#' list(a = list(aa=1, bb=2, cc=3)),
#' .stropts = list(max.level = 2)
#' )
#'
#' }
pipe_message <- function(.x, ..., .FUN = message, .timestamp = TRUE, .stropts = NULL) {
.expressions <- eval(substitute(alist(...)))
if (is.grouped_df(.x)) {
.indices <- lapply(attr(.x, "indices"), `+`, 1L)
.labels <- attr(.x, "labels")
} else {
.indices <- list(seq_len(nrow(.x)))
.labels <- ""
}
lst <- mapply(function(.ind, .lbl) {
.x <- .x[.ind,,drop=FALSE]
lapply(.expressions, function(.expr) {
if (is.call(.expr)) .expr <- as.call(lapply(.expr, function(a) if (a == ".") as.symbol(".x") else a))
eval(.expr, .x)
})
}, .indices, .labels, SIMPLIFY=FALSE)
.out <- capture.output(
do.call("str", c(list(lst), .stropts))
)
.out[1] <- sprintf("Mid-pipe message%s:",
if (.timestamp) paste(" (", Sys.time(), ")", sep = ""))
do.call(.FUN, c(list(paste(.out, collapse = "\n")),
if (identical(.FUN, warning)) list(call. = FALSE)))
.x # "unmodified"
}
A: You can still do the printing thing here:
df %>% group_by(ID) %>% do({
the_id = unique(.$ID)
cat("Working on...", the_id, "which is...", match(the_id, unique(df$ID)), "/", n_distinct(df$ID), "\n")
FUN(.)
})
which prints
Working on... 1 which is... 1 / 3
[1] "TEST"
Working on... 2 which is... 2 / 3
Error in 1:which(!is.na(x$value))[1] : NA/NaN argument
I routinely do this (using data.table not dplyr, but the same idea). I realize there are more sophisticated ways to debug, but it's worked well enough for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50119618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I want to understand the probability results that we get from the logistic regression I got results from a logistic regression model as 0 or 1. I want to use their probabilities as propensity score for my marketing work. When I see the results, I noticed there are two probabilities, I want to know which probability is the probability for predicting 1 and which is for 0. Below is a rough sample of results that I see, which confused me.
#actual | prediction | probability
#0 | 1 | [89, 11]
#1 | 1 | [76, 34]
#0 | 0 | [80, 20]
#0 | 1 | [99, 1]
Here first probability number is higher than second, but I don't know which is the one for predicting 1 vs predicting 0. How to make sure I am taking probability of 1 and then rank ordering the observations to take highest propensity customers?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58457979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery - .append() not working I'm in the process of creating a small currency conversion script using the money.js library and have run into a problem with the .append(); part. Here is what I have so far:
<script type="text/javascript">
$(document).ready(function () {
function pfxCurrencyConverter() {
//get the users options from the form and store in variables
var pfxFromCurrency = $('#pfx-from-currency').val();
var pfxToCurrency = $('#pfx-to-currency').val();
//set base options
fx.base = pfxFromCurrency
fx.settings = {
from: pfxFromCurrency
};
// get the amount input by the user
var inputAmount = $('#pfx-input-amount').val();
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON('http://openexchangerates.org/latest.json', function (data) {
// Check money.js has finished loading
if (typeof fx !== "undefined" && fx.rates) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates: data.rates,
base: data.base
}
}
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency});
$("#currencies").append("<li>New Value" + convertedValue + "</li>");
});
} //end pfxCurrencyConverter
$(document).ready(function () {
pfxCurrencyConverter();
});
</script>
</head>
<!-- output form for user to populate -->
<!-- Output the front end form, include external stylesheet and define customisable css -->
</head>
<!-- output form for user to populate -->
<body>
<form method="get" onsubmit="return pfxCurrencyConverter();">
Amount: <input type='text' id='pfx-input-amount' /><br />
From: <select id='pfx-from-currency'>
<option>Please Choose</option>
<option>GBP</option>
</select><br />
To: <select id='pfx-to-currency'>
<option>Please Choose</option>
<option>USD</option>
</select><br />
<input type='submit' value='Convert' />
</form>
<ul id="currencies"></ul>
</body>
</html>
I have also this in the html right after the submit button, it works fine with just a string but stops working once I add + convertedValue
<script>document.write("New Value" + convertedValue);</script>
Any help is greatly apprecited
A: The problem was that the .append() was being called before the value was returned from getJson(). Placing the .append() inside the .getJson() solved the problem. This works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://josscrowcroft.github.com/money.js/money.js"></script>
<script type="text/javascript">
function ConvertMoney(to, from, amt) {
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON('http://openexchangerates.org/latest.json',
function (data) {
// Check money.js has finished loading:
if (typeof fx !== "undefined" && fx.rates) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates: data.rates,
base: data.base
};
}
var result = "<li>" + fx.convert(amt, { from: from, to: to }) + "</li>";
$("#result").append(result);
});
}
$("#convert").live("click", function () {
var from = $("#pfx-from-currency").val();
var to = $("#pfx-to-currency").val();
var amt = $("#pfx-input-amount").val();
ConvertMoney(to, from, amt);
});
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var from = $("#pfx-from-currency").val();
var to = $("#pfx-to-currency").val();
var amt = $("#pfx-input-amount").val();
ConvertMoney(to, from, amt);
}
});
</script>
</head>
<body>
Amount:
<input type='text' id='pfx-input-amount' /><br />
From:
<select id='pfx-from-currency'>
<option>Please Choose</option>
<option>GBP</option>
</select><br />
To:
<select id='pfx-to-currency'>
<option>Please Choose</option>
<option>USD</option>
</select><br />
<input type='button' id="convert" value='Convert' />
<ul id="result">
</ul>
</body>
</html>
A: Looks like you have an object terminated by a semicolon
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency; });
that is not valid, try changing it to
var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency });
Also I would expect
var pfxToCurrency = document.getElementById('pfx-to-currency').value
and not just
var pfxToCurrency = document.getElementById('pfx-to-currency')
A: Looks like you have an extra <script> tag:
<script type="text/javascript">
$(document).ready(function(){
<script type="text/javascript">
A: please make sure that properly Closing your Document ready function ( ** closing )
$(document).ready(function () {
........
..........
});
} //end pfxCurrencyConverter
**});**
$(document).ready(function(){
pfxCurrencyConverter();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8955636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to separate key-values per row from a JSON formatted list? I've been trying to get a more readable output from a JSON list. I have not yet been successful. I hard-coded some data to see if I can get it as I want. This is what I did:
import json
jsonData = {
"person": {"FirstName": "Kwin", "LastName": "Harley", "Age": 25},
"DoB": {"DateOfBirth": "19/12/1996", "Birthplace": "Belgium"},
"insurer":{"id":"12345","contractNumber":"98765432",
"valid_from":"2020-10-01T00:00:00.000Z","valid_until":"2021-01-30T00:00:00.000Z",
"representativeID":"135792468",
"representativeEmail":"sample@test.com"}
}
jsonString = json.dumps(jsonData, sort_keys=False, indent=4)
print(jsonString)
Output 1
As you can see, the data is structured nicely.
Now, when I use my main code, the output looks like this:
Output 2
It just returns the data in 1 row :(
Is there a way to fix that? This is the code I have for that:
qrType = qr.type
qrData = json.dumps(qr.data.decode('utf-8'),sort_keys=True)
# print the QR type and data to the terminal
print("[INFORMATION] Found {} barcode:\n{}".format(qrType, qrData))
A: I don't think you're passing a dict to json.dumps() at all. qr.data is clearly a string, as you .decode() it. Presumably it's a json string, so you want to do something like this:
formatted_data = json.dumps(json.load(qr.data.decode()), indent=2)
print(formatted_data)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69741497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Delay won't work I'm making an event calender as a task for school and I'm new to this.
The problem is that when I do a delay in the receive part of my loop, my table vanishes.
I'm looking on the internet and in my code for errors for 2 days now.
Event is a tuple => {{Time (tuple like now(), make_ref()}, NotifyPid, Load}
getTime gives back an integer normally
-module(calender).
-export([start/0, start_new/0, post/1, postincr/1, gettime/0]).
-export ([kalender/0, getTime/1, increment/1, makeTime/1]). % internal use only
%% @doc Starts the program
start() ->
case whereis('event manager') =:= undefined of
true ->
register('event manager', spawn(calender, kalender, [])),
{ok, 'event manager'};
false ->
{event_not_made}
end.
%% @doc Starts a new program even program already exist but kills it first
start_new() ->
case whereis('event manager') =:= undefined orelse unregister('event manager') of
true ->
ets:delete(calend),
register('event manager', spawn(calender, kalender, [])),
{ok, 'event manager'};
false ->
{ok, event_not_made}
end.
% Puts Events into sorted table
% Time is an integer value in milliseconds
post(Event) ->
'event manager'!{post, Event},
{ok, gettime()}.
%% @doc Puts Events into sorted table
%% Increment is an integer value which will be added to the present time
%% The increment value of time is in milliseconds
%% @end
postincr(Event) ->
'event manager'!{postincr, Event},
{ok, gettime()}.
%% @doc Gives the difference in time between present and time at start
gettime() ->
'event manager'!{gettime, self()},
receive
T -> T
end.
%% @private Calculates the difference of time between the present time and Event time
getTime(Time) ->
NowTime = now(),
timer:now_diff(Time, NowTime)div 1000.
%% @private Adds the incremental time of postincr to the present time
increment(Incr) ->
{X, Y, Z} = now(),
X1 = X * 1000000000000,
Y1 = Y * 1000000,
Incr1 = X1 + Y1 + Z + (Incr * 1000),
makeTime(Incr1).
%% @private Changes integer to tuple of 3 values
makeTime(Time) ->
X = Time div 1000000000000,
Y = (Time rem 1000000000000) div 1000000,
Z = Time rem 1000000,
{X, Y, Z}.
%% @private Makes the sorted table, starts the loop
kalender() ->
Cal = {ets:new(calend, [ordered_set, named_table, {keypos, 1}, public]), now()},
loop(Cal).
%% @private Loops through the table and checks for received messages
loop(Cal) ->
io:format("Loop start ~n"),
{Calen, TimeAtStart} = Cal,
io:format("Before case ~n"),
case ets:first(Calen) of
'$end_of_table' ->
io:format("end of table ~n"),
{end_of_table};
{Time, Ref} ->
io:format("Before calculation event ~n"),
Ms = getTime(Time),
io:format("After getTime ~n"),
if
Ms =< 0 ->
io:format("Ms =< 0 ~n"),
[Event | _Rest] = ets:lookup(Calen, {Time, Ref}),
io:format("~p~n", [Event]),
{{_Time1, _Ref1}, NotifyPid, _Load} = Event,
io:format("~p~n", [NotifyPid]),
NotifyPid!Event,
io:format("After event send ~n"),
ets:delete(Calen, {Time, Ref}),
io:format("After Ms =< 0 ~n");
Ms > 0 ->
io:format("Event not done ~n"),
{event_not_yet_done}
end,
io:format("After calculation event ~n")
end,
I think that it goes wrong from here somewhere:
io:format("Before Delay ~n"),
% Gets the delay time
Delay = case ets:first(Calen) of
'$end_of_table' ->
io:format("Delay infinity ~n"),
infinity;
{DelayTime, _DelayRef} ->
io:format("~p~n", [DelayTime]), => the DelayTime has for example a value of {9283,823031,155000}
Dl = getTime(DelayTime),
case Dl > 0 of
true ->
Dl,
io:format("~p~n", [Dl]); => this io:format gives me on the screen a calculated value example: 7899995274337
false ->
0,
io:format("0 ~n")
end,
io:format("Delay time~n")
end,
io:format("Before receive ~n"),
receive
{post, PostEvent} ->
io:format("In post ~n"),
{PostTimeI, Np, Ld} = PostEvent,
PostRef = make_ref(),
PostTimeT = makeTime((PostTimeI * 1000)),
io:format("After making the tuples ~n"),
io:format("~p ~p ~p ~p ~p~n", [PostTimeI, PostRef, PostTimeT, Np, Ld]),
ets:insert(Calen, {{PostTimeT, PostRef}, Np, Ld}),
io:format("After insert post ~p~n", [whereis('event manager')]);
{postincr, PostIncrEvent} ->
{Incr, Np, Ld} = PostIncrEvent,
PostIncrRef = make_ref(),
PostIncrTime = increment(Incr),
ets:insert(Calen, {{PostIncrTime, PostIncrRef}, Np, Ld});
{gettime, From} ->
From!getTime(TimeAtStart)
after
Delay ->
io:format("Delaying ~n"),
{ok}
end,
io:format("After receive ~n"),
loop(Cal).
A: The problem is probably that your process spawned with your start/0 function crashes. When a process crashes, any ETS tables it owns are reaped. Try using spawn_monitor and then use the shell's flush() command to get hold of messages that comes in. It probably dies. Another way is to use the tooling in the proc_lib module and then use erl -boot start_sasl to get some rudimentary crash error reporting up and running for your process.
A "naked" spawn(...) is usually dangerous since if the spawned process crashes, you won't learn anything. At least use spawn_link or spawn_monitor.
A: I found my problem:
I was testing my code but I didn't had a Pid to test with, so I used whereis('event manager'). Instead I had to use self().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19836518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to use Google "Application Licensing"? When should we use Google Play's service Application Licensing?
Is this a new mechanism against cracked apps on Android?
When should I recommend my clients to use this service? I have read the tutorial, but it did not answer to my queries.
I first thought that this is a mechanism for multimedia-selling apps only, but now I see I was wrong.
If anyone used this service, please tell me why you used it.
A:
When should we use Google Play's service Application Licensing?
When you have an application that you fear will be pirated, and sold/modified without your permission.
Is this a new mechanism against cracked apps on Android?
This system itself has been cracked. Application Licensing uses the LVL library. AntiLVL can crack it.
It's best to implement this in addition to your own authentication methods(Cntrl+F for "Guidelines for custom policies".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12428934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change Item Position in Firebase Recycler Adapter I am using Firebase Recycler Adapter in my app to display items from my database, but I want a situation whereby newer items will be at the top of the fragment so i tried to use orderByChild() like this:
Query conversationQuery = mConvDatabase.orderByChild("timestamp");
but that didn't solve the problem.
What i really want to do is to update chat fragment anytime a user receives a new message to move the new conversation to the top just like every other messenger app.
this is my ChatFragment
@Override
public void onStart() {
super.onStart();
Query conversationQuery = mConvDatabase.orderByChild("timestamp");
FirebaseRecyclerAdapter<Conv, ConvViewHolder> firebaseConvAdapter = new FirebaseRecyclerAdapter<Conv, ConvViewHolder>(
Conv.class,
R.layout.users_layout,
ConvViewHolder.class,
conversationQuery
) {
@Override
protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, int i) {
final String list_user_id = getRef(i).getKey();
// Query MessageQuery = mMessageDatabase.child(list_user_id);
Query lastMessageQuery = mMessageDatabase.child(list_user_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("message").getValue().toString();
String type_image = dataSnapshot.child("type").getValue().toString();
boolean seen = Boolean.parseBoolean(dataSnapshot.getKey());
if (type_image.equals("image")){
convViewHolder.setMessage("image",conv.isSeen());
}else {
convViewHolder.setMessage(data, conv.isSeen());
}}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
convViewHolder.setUserOnline(userOnline, getActivity());
}
mConvList.scrollToPosition(0);
convViewHolder.setName(userName);
convViewHolder.setUserImage(userThumb, getContext());
convViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mConvList.setAdapter(firebaseConvAdapter);
firebaseConvAdapter.notifyDataSetChanged();
}
Is there a way i can manipulate the time stamp sent to database so it can be later retrieved in an appropriate manner? or can i just change the arrangement locally in my code as data is been loaded?
A: You can do something like this.
//Display
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
firebaseRecyclerAdapter.notifyDataSetChanged();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55879882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: USE_FINGERPRINT is deprecated in API level 28 Constant USE_FINGERPRINT was deprecated in API level 28 and we should use more generic USE_BIOMETRIC which has been added in same API level.
I swap these constants in my Manifest and I'm getting error when calling FingerprintManagerCompat.from(context).isHardwareDetected().
Error is:
Missing required permission - USE_FINGERPRINT
This happens because of @RequiresPermission("android.permission.USE_FINGERPRINT") annotation in FingerprintManagerCompat in 28.0.0-rc3 support v4 lib.
Is this something I can ignore and continue using new permission?
A: biometrics API provides BiometricConstants for error handling
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
//The device does not have a biometric sensor.
if (errorCode == BiometricPrompt.ERROR_HW_NOT_PRESENT){
//Do something
}
}
A: I've faced the same problem, imho the short answer is to ignore the deprecation, as long as you only want to support fingerprint authentication in your app.
As stated in the google dev blog, since API 28 google comes up with the new biometrics API, which simplifies the whole process of biometrics authentication. They provide a simple builder for the auth-dialog. Additionally, they support face and iris detection, too - imho it is just a matter of time if you want to support it and probably might be worth upgrading it.
The only disadvantage I've discovered so far is that if you want to check if e.g. fingerprint hardware is available, you'll have to start the authentication process to check this out and wait for the error callback. The deprecated fingerprint API instead provides methods like isHardwareDetected() or hasEnrolledFingerprints() for this purpose. In this case, you would probably have to re-design your application, if you rely on this information. The reason for the deprecation of those methods is probably, that it only supports fingerprints, therefore it is not a bad idea to upgrade it.
Google has also provided the compat 'androidx.biometric:biometric:1.0.0-alpha02' version for the devices below API 28, it seems that by importing this dependency, you could simply switch to USE_BIOMETRIC permission without modifying anything else in your app - you won't be bothered by the warning anymore. Since it is only in alpha stage, I would use it with care. Therefore, as long as you don't use anything from the biometrics API, you could also simply ignore the problem and face it again when you want to support additional biometric authentication methods.
EDIT: Now, the beta version of compat library is released, 'androidx.biometric:biometric:1.0.0-beta01'. For more info on this, check here.
Now, the stable version of compat library is released on December 18, 2019, 'androidx.biometric:biometric:1.0.1'. For more info on this Click here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51375606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: Error occured while adding security to a module in openerp I have created a new module in openerp now I want to give security for the module for that I have created a folder named "security" inside my module folder and created a xml file and ir.model.access.csv file in it.My aim is I want to create two roles for my module one is manager and other is user.
for that I have added the below code in the xml file
<record id="group_mat_mgmt_user" model="res.groups">
<field name="name">User</field>
<field name="category_id" ref="base.module_category_mat_mgmt"/>
<field name="implied_ids" eval="[(4, ref('base.group_user'))]"/>
</record>
<record id="group_mat_mgmt_manager" model="res.groups">
<field name="name">Manager</field>
<field name="category_id" ref="base.module_category_mat_mgmt"/>
<field name="implied_ids" eval="[(4, ref('group_mat_mgmt_user'))]"/>
<field name="users" eval="[(4, ref('base.user_root'))]"/>
</record>
At the view part I have added like this
<menuitem name="Materials Management" id="menu_mat_mgmt_root"
groups="group_mat_mgmt_manager,group_mat_mgmt_user"
sequence="80"/>
then the permission given at the csv but i got an error like this
File
"C:\OpenErp\openerp\openobject-server\openerp\addons\base\ir\ir_model.py",
line 850, in _get_id raise ValueError('No such external ID
currently defined in the system: %s.%s' % (module, xml_id)) alueError:
No such external ID currently defined in the system:
mat_mgmt.group_mat_mgmt_manager
A: It looks like you did not add files in openerp.py in well sequence. Are you getting this error from CSV file or from View.xml file ?
You need to check openerp.py file. You may be assign first ir.model.access.csv/module_view.xml and after that, module_security.xml in 'data' attribute. So It will go first checking ir.model.access.csv/module_view.xml and it will not find that group, that you created in security.xml and that will be load after loading ir.model.access.csv/module_view.xml files. You can check it and you need to pass first security.xml and after that, ir.model.access.csv/module_view.xml files in openerp.py.
You can also check by assigning group like this : module_name.GROUP_XML_ID wherever you did assign/use those groups.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16601836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: inconsistent midi naming when using multiple devices of the same type I am facing an obscure behaviour of device naming when trying to use multiple USB midi devices of the same type of hardware. As this might be hardware/system/driver related, here is my general setup:
*
*host: Windows 8.1 x64 (tested on multiple machines)
*usb devices: 2x Livid Brain V2 (a general purpose usb-midi interface)
The two devices (same hardware, let's call them device X and Y) are flashed with two different firmware flavours so that they appear with different names in the midi enumeration. If I only connect device X it shows itself as "Brain2" / if I only connect device Y it's "Brain2B". Those are the names I get from the MIDIINCAPS / MIDIOUTCAPS (winmm.dll). So far so good.
The problem arises as soon I connect both devices at the same time, than both get the same name (of the latter connected) - so the enumeration changes:
*
*first X, then Y => both get the name "Brain2B"
*first Y, then X => both get the name "Brain2"
However, I can access and use the devices but I am not able to distinguish between them anymore (which is basically the same starting position as having the identical firmware on both devices).
I'd be happy if anyone could point me in the right direction. Has anyone encountered anything similiar? Could this be a system related issue? (Or is it a bad driver, maybe?) Thanks in advance!
EDIT:
I had a closer look at the usb properties with a tool callled USB Device Tree Viewer (similar to USBView) and it turned out the identifiers are correct there. So, how does winmm.dll get the midi enumeration - could it be a bug in there? (unlikely)
Moritz
(btw: here is the related topic/post in the manufacturer's forum: link)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33960352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Bigquery - Return array of structs with specific fields of the struct I have an array of structs in bigquery.
I would like to return an array of structs, but the struct of the array with less fields that the original struct.
Example:
I would like to have the same results but without Skills.Id.
I tried to do something like this but
SELECT [(select struct(dd.Level as Level, dd.TypeId as typeid)
from unnest(dd.Skills) as dd )] as skills
FROM tablee dd
But get an exception:
Scalar subquery produced more than one element
A: Try ARRAY instead of []:
SELECT ARRAY(select struct(dd.Level as Level, dd.TypeId as typeid)
from unnest(tablee.Skills) as dd) as skills
FROM tablee
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69796174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I go about creating an engine for Flash that I can import and use in a game? I have been making sprites for an animation, however, I want to make a simple platformer almost like a Mario clone, but don't know how to code one. Should I use DreamWeaver or FlashBuilder? Any other tips or advice is appreciated.
A: You can start pretty easily using Flash Develop from: http://www.flashdevelop.org/
With Flash Develop, you can also start with an 'engine' or framework to make coding the game easier like FlashPunk (http://useflashpunk.net/) or Flixel (http://flixel.org/)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19572035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Leaflet - Add Layer on LayerAdd event so i want to add a Layer if a other Layer is added ....
i did make a small Example
var mymap = L.map('mymap').setView([51.505, -0.09], 13);
var baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
}).addTo(mymap);
var layer1 = L.marker([51.505,-0.10]);
var layer2 = L.marker([51.505,-0.09]);
var layer3 = L.marker([51.505,-0.8]);
var basemaps = {
"OSM": baseLayer
};
var overlays = {
"Layer1": layer1,
"Layer2": layer2,
"Layer3": layer3
}
L.control.layers(basemaps,overlays,{collapsed:false}).addTo(mymap);
layer1.on("add",function(){
layer2.addTo(mymap);
});
and on
JSFiddle (Updated Version)
Like you (may) can see the second Marker is shortly added but instantly removed after the add-Event is finished ...
Iam not sure how i can prefent it from doing that or more specific how i realy can add the second marker (since in the Layer Control the checkbox isnt even activated in that short moment) ....
A: you can either use map.on('layeradd') and or try the layeradd
event on your layer1 object.
leaflet's documentation link: http://leafletjs.com/reference-1.0.3.html#layerevent
EDIT... add the following code to js-fiddle code.
layer1.on('add',(e)=>{
layer2.addTo(mymap);
});
layer1.addTo(mymap);
if that doesn't remove the addTo line from above and paste the following
setTimeout(()=>{
layer1.addTo(mymap);
},500);
EDIT 2 :
var controlObj = L.control.layers(basemaps,overlays,{collapsed:false}).addTo(mymap);
layer1.on("add",function(){
console.log(controlObj._form[2].click())
});
this code works... but its not how it should be dont... will have to figureout a better way to do this, but this will work temporarily.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42729822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Asp.Net Core Route Default Action I have a Asp.net Core application and i use a route like this.
routes.MapRoute(
name: "Address",
template: "adress-info/{action}/{id?}",
defaults: new { controller = "Address", action = "Index" }
);
My url helper generate wrong url addres if i don't use default parameter.
For example
//This is generate right url. http://localhost/address-info
@Url.RouteUrl("Address",new {action="Index"})
//i expect generate same url as up but it's generate http://localhost/address-info/anotherAction
@Url.RouteUrl("Address")
Why doesn't apply MapRoute's default action? What is the problem?
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56953849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Executing for loop with two inputs I am using for-loop to execute my command in linux. I have 20 files in one input and 20 files in another input
for f1 in zero-mam-2050-2074*.nc;
do;
f2={avm-mam-1976-2000-tasmax-*.nc};
command $f1 $f2 output;
done
It is not reading the second input.
A: The semicolons:
for f1 in zero-mam-2050-2074*.nc;
do;
f2={avm-mam-1976-2000-tasmax-*.nc};
command $f1 $f2 output;
done
are useless.
for f1 in zero-mam-2050-2074*.nc
do
f2={avm-mam-1976-2000-tasmax-*.nc}
command $f1 $f2 output
done
Line 3 is fishy. What do you want to do? Create an array?
for f1 in zero-mam-2050-2074*.nc
do
f2=(avm-mam-1976-2000-tasmax-*.nc)
command "$f1" "${f2[@]}" output
done
To loop over, let's say 20 files, matching pattern f1, and call each with let's say 20 files matching f2:
for f1 in zero-mam-2050-2074*.nc
do
f2=avm-mam-1976-2000-tasmax-*.nc
command "$f1" $f2 output
done
This would lead to 20 command invocations, rolling through f1 but each called with all the files matching f2.
For 20x20 matches, you would use a second loop.
Fitted to file patterns on my harddrive:
for f1 in file1*; do f2=sample.*; echo command "$f1" $f2* output; done
command file1 sample.conf sample.go sample.log sample.xml output
command file1.txt sample.conf sample.go sample.log sample.xml output
command file1nums sample.conf sample.go sample.log sample.xml output
You would of course use your patterns and, after testing, remove the echo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49666517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Bubble sort is not sorting I've written a code to input the name, day and time of a few shows, with the option to have it sorted (bubble sort) by day and name. I'm using 1.4.2 (because I have to) and an ArrayList along with a simple class.
I've been staring at this for hours, left and came back to it a bunch of times, but unfortunately, it isn't working! Any idea why?! Here's my code:
//method to sort and display info
public static void sortDay(){
for(int i = 0; i < show.size() - 1; i++) {
for(int j = 0; j < show.size() - 1; j++){
showInfo current = (showInfo)show.get(j);
showInfo next = (showInfo)show.get(j+1);
if (current.day.compareTo(next.day) < 0) {
showInfo temp = new showInfo();
temp.name = ((showInfo)show.get(j)).name;
temp.day = ((showInfo)show.get(j)).day;
temp.time = ((showInfo)show.get(j)).time;
((showInfo)show.get(j)).time = ((showInfo)show.get(i)).time;
((showInfo)show.get(j)).day = ((showInfo)show.get(i)).day;
((showInfo)show.get(j)).name = ((showInfo)show.get(i)).name;
((showInfo)show.get(i)).time = temp.time;
((showInfo)show.get(i)).day = temp.day;
((showInfo)show.get(i)).name = temp.name;
}
}
}
System.out.println("Show Information");
for (int i = 0; i < show.size(); i++){
System.out.println("Name: " + ((showInfo)show.get(i)).name);
System.out.println("Day: " + ((showInfo)show.get(i)).day);
System.out.println("Time: " + ((showInfo)show.get(i)).time);
}
}
Any help would be great! Thanks in advance!
A: First, I'll assume you're using some kind of List - likely an ArrayList.
That said, the main operations for Bubble Sort are described as follows:
*
*Compare for ordering
*Create temporary variable
*Place left value into temporary variable
*Place right value into left value
*Place old left value into right value from temporary value
You're shuffling about the fields, which will lead to confusion and bugs. Use the above approach instead.
Here it is illustrated with generics (so you don't have to cast anymore), and a capital class name, as is the convention. I don't have a temporary variable in this example, as I already have a reference to current.
List<ShowInfo> show = new ArrayList<>(); // assume populated
public static void sortDay(){
for(int i = 0; i < show.size(); i++) {
for(int j = 0; j < show.size() && j != i; j++) {
ShowInfo current = show.get(i);
ShowInfo next = show.get(j);
// If the current day is greater than the next day, we need to swap.
// Adjust to suit your business logic (if current is less than next).
if (current.day.compareTo(next.day) > 0) {
show.set(i, next);
show.set(j, current);
}
}
}
}
A: For a generic way of doing this, perhaps you could try something like:
public static <T extends Comparable> void sort(final List<T> list){
boolean remaining;
do{
remaining = false;
for(int i = 0; i < list.size()-1; i++){
final T current = list.get(i);
final T next = list.get(i+1);
if(current.compareTo(next) < 0){
list.set(i, next);
list.set(i+1, current);
remaining = true;
}
}
}while(remaining);
}
A: How do you fix it?
I'm just answering your question: how to fix the code you posted. For "how to improve it?" all other answers are way better than whatever I can come up with.
There are two points:
*
*swap on the same index, in the inner for (index j)
*correct swapping: where you have j write j+1 and where you have i write j
*the other for is just so it will iterate enough times to get it sorted in the worst case (suggestions in other answers go for a while, much better)
That being said, the swapping pseudocode is:
if (show[j] < show[j+1]) {
temp = j+1
j+1 = j
j = temp
}
And here is the swapping code with the fixes:
if (current.day.compareTo(next.day) < 0) {
showInfo temp = new showInfo();
temp.name = ((showInfo)show.get(j+1)).name;
temp.day = ((showInfo)show.get(j+1)).day;
temp.time = ((showInfo)show.get(j+1)).time;
((showInfo)show.get(j+1)).time = ((showInfo)show.get(j)).time;
((showInfo)show.get(j+1)).day = ((showInfo)show.get(j)).day;
((showInfo)show.get(j+1)).name = ((showInfo)show.get(j)).name;
((showInfo)show.get(j)).time = temp.time;
((showInfo)show.get(j)).day = temp.day;
((showInfo)show.get(j)).name = temp.name;
}
And here is the printed result (assuming day - time - name for each show, so we are sorting on the first int):
Show Information before sort
610 - -72 - 1402
838 - -184 - 1096
-478 - 248 - 934
709 - 832 - -590
2007 - 954 - -315
Show Information after sort
2007 - 954 - -315
838 - -184 - 1096
709 - 832 - -590
610 - -72 - 1402
-478 - 248 - 934
A: public class myBubbleSort
{
private static int[] a;
public static void main(String[] args)
{
getArray(10);
System.out.println("Array before sorting");
printArray();
ascendingBubble();
System.out.println("Array after ascending sort");
printArray();
descendingBubble();
System.out.println("Array after descending sort");
printArray();
System.out.println();
System.out.println("Random sort");
getArray(10);
bubbleSort(true);
System.out.println("Array after Random sort");
printArray();
}
// print the number in random array
public static void printArray()
{
for (int i : a)
{
System.out.print(i + " ");
}
System.out.println();
}
// generate a random array to be sorted in ascending and descending order
public static void getArray(int size)
{
a = new int[size];
int item = 0;
for (int i = 0; i < size; i++)
{
item = (int) (Math.random() * 100);
a[i] = item;
}
}
// sort getArray in ascending order and bubblesort it
public static void ascendingBubble()
{
int temp;
System.out.println();
System.out.println("Ascending sort");
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - 1; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
bubbleSort(true);
}
// sort getArray in descending order and bubblesort it
public static void descendingBubble()
{
int temp;
System.out.println();
System.out.println("Descending sort");
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - 1; j++)
{
if (a[j] < a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
bubbleSort(true);
}
// bubble sort algorithm
public static void bubbleSort(boolean printTime)
{
boolean sorted = false;
int pass = 1;
int temp;
long startTime;
long endTime;
long duration;
startTime = System.nanoTime();
while (pass < a.length - 1 && (!sorted))
{
sorted = true;
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
sorted = false;
}
}
pass = pass + 1;
}
endTime = System.nanoTime();
duration = (endTime - startTime);
if(printTime)
{
System.out.println(duration + " "+ " nano seconds");
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19760980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When drawing on a canvas, should calculations be done relative to cartesian plane coordinates? I've been seeing a lot of canvas-graphics-related javascript projects and libraries lately and was wondering how they handle the coordinate system. When drawing shapes and vectors on the canvas, are the points calculated based on a cartesian plane and converted for the canvas, or is everything calculated directly for the canvas?
I tried playing around with drawing a circle by graphing all its tangent lines until the line intersections start to resemble a curve and found the difference between the cartesian planes I'm familiar with and the coordinate system used by web browsers very confusing. The function for a circle, for example, "y^2 + x^2 = r^2" would need to be translated to "(y-1)^2 + (x-1)^2 = r^2" to be seen on the canvas. And then negative slopes were positive slopes on the canvas and everything would be upside down :/ .
The easiest way for me to think about it was to pretend the origin of a cartesian plane was in the center of the canvas and adjust my coordinates accordingly. On a 500 x 500 canvas, the center would be 250,250, so if I ended up with a point at 50,50, it would be drawn at (250 + 50, 250 - 50) = (300, 200).
I get the feeling I'm over-complicating this, but I can't wrap my mind around the clean way to work with a canvas.
A: Current practice can perhaps be exemplified by a quote from David Flanagan's book "JavaScript : The Definitive Guide", which says that
Certain canvas operations and attributes (such as extracting raw
pixel values and setting shadow offsets) always use this default
coordinate system
(the default coordinate system is that of the canvas). And it continues with
In most canvas operations, when you specify the coordinates
of a point, it is taken to be a point in the current coordinate system
[that's for example the cartesian plane you mentioned, @Walkerneo],
not in the default coordinate system.
Why is using a "current coordinate system" more useful than using directly the canvas c.s. ?
First and foremost, I believe, because it is independent of the canvas itself, which is tied to the screen (more specifically, the default coordinate system dimensions are expressed in pixels). Using for instance a Cartesian (orthogonal) coordinate system makes it easy for you (well, for me too, obviously :-D ) to specify your drawing in terms of what you want to draw, leaving the task of how to draw it to the transformations offered by the Canvas API. In particular, you can express dimensions in the natural units of your drawing, and perform a scale and a translation to fit (or not, as the case may be...) your drawing to the canvas.
Furthermore, using transformations is often a clearer way to build your drawing since it allows you to get "farther" from the underlying coord system and specify your drawing in terms of higher level operations ('scale', 'rotate', 'translate' and the more general 'transform'). The abovementioned book gives a very nice exemple of the power of this approach, drawing a Koch (fractal) snowflake in many fewer lines that would be possible (if at all) using canvas coordinates.
A: The HTML5 canvas, like most graphics systems, uses a coordinate system where (0,0) is in the top left and the x-axis and y-axis go from left to right and top down respectively. This makes sense if you think about how you would create a graphics system with nothing but a block of memory: the simplest way to map coordinates (x,y) to a memory slot is to take x+w*y, where w is the width of a line.
This means that the canvas coordinate system differs from what you use in mathematics in two ways: (0,0) is not the center like it usually is, and y grows down rather than up. The last part is what makes your figures upside down.
You can set transformations on the canvas that make the coordinate system more like what you are used to:
var ctx = document.getElementById('canvas').getContext('2d');
ctx.translate(250,250); // Move (0,0) to (250, 250)
ctx.scale(1,-1); // Make y grow up rather than down
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15378430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unexpected end of stream when using Postman I tried to make a http request using postman. But I am having a response of
"Unable to determine boundary: unexpected end of stream".
When I checked from the server side, Looks like the request body is incomplete.
Any idea would greatly help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74651445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Displaying an Html file as IframeElement and getting variables from it I am displaying a html file that is kind of a quiz player(html + js).
Displaying works fine but at the player when user presses finish button and with the js script tags inside the html file score is calculated and they are getting their score.
I want to access that score variable inside my flutter app.
So I need to make my html file and flutter talk. Please help.
html.IFrameElement _iframeElement = html.IFrameElement();
_iframeElement.src = _url;
_iframeElement.style.border = 'none';
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iframeElement,
);
Widget _iframeWidget;
_iframeWidget = HtmlElementView(
key: UniqueKey(),
viewType: 'iframeElement',
);
A: You can send message from one window to another with postMessage, and access it via addEventListener and remember that the iframe is the child of your flutter page (and flutter is the parent), so:
To send data from flutter to the iframe, you can use _iFrameElement.contentWindow?.postMessage (after the iframe loaded), and to get that data in iframe, you can use window.addEventListener.
To send data from iframe, you can use window.parent.postMessage, and
to get that data in flutter, you can use window.addEventListener.
A sample code would be:
Flutter:
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class IFramePage extends StatefulWidget {
const IFramePage({Key? key}) : super(key: key);
@override
State<IFramePage> createState() => _IFramePageState();
}
class _IFramePageState extends State<IFramePage> {
int i = 0;
IFrameElement _iFrameElement = IFrameElement();
@override
void initState() {
_iFrameElement.src = 'http://localhost/iframe/iframe.html';
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iFrameElement,
);
_iFrameElement.onLoad.listen((event) {
// Send message to iframe when loaded
_iFrameElement.contentWindow
?.postMessage('Hello! Clicked: $i times', "*");
});
// Get message from iframe
window.addEventListener("message", (event) {
var data = (event as MessageEvent).data ?? '-';
if (data == 'clicked') {
setState(() {
i++;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text('clicked $i time(s)'),
SizedBox(
width: 300,
height: 300,
child: HtmlElementView(
key: UniqueKey(),
viewType: 'iframeElement',
),
),
],
),
);
}
}
and IFrame:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div>This is my iframe</div>
<button type="button" onclick="sendData()">Click Me!</button>
</body>
<script>
// Send data to parent window
const sendData = () => window.parent.postMessage('clicked', "*");
// Get data from parent window
window.addEventListener("message", (event) => console.log(event.data));
</script>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73436755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to slice each individual element of a python list or array I have a python list which is derived from a pandas series as follows:
dsa = pd.Series(crew_data['Work Type'])
disc = [dsa]
print(disc)
The output is as follows:
[0 Disc - Standard Removal & Herbicide
1 Disc - Standard Removal & Herbicide
2 Standard Trim
3 Disc - Hazard Tree
4 Disc - Hazard Tree
...
134 Disc - Hazard Tree
135 Disc - Hazard Tree
136 Disc - Hazard Tree
137 Disc - Hazard Tree
138 Disc - Hazard Tree
Name: Work Type, Length: 139, dtype: object]
Now the next step is to slice the first 4 characters of each element so that the value returned is Disc
This appears to be simple when performed on a single string, however when attempting to do this with a list for some reason appears to be almost impossible. This can be done simply in Excel using the formula =LEFT(A1,4), so surely it can be done as simple in python?
If anyone has a solution that would be great.
A: With a sample dataframe
In [138]: df
Out[138]:
col1 col2 col3 newcol
0 a 1 x Wow
1 b 2 y Dud
2 c 1 z Wow
In [139]: df['newcol']
Out[139]:
0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object
In [140]: type(_)
Out[140]: pandas.core.series.Series
Selecting a column gives me a Series; no need for another Series wrapper
In [141]: pd.Series(df['newcol'])
Out[141]:
0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object
We can put it in a list, but that doesn't do any good:
In [142]: [pd.Series(df['newcol'])]
Out[142]:
[0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object]
In [143]: len(_)
Out[143]: 1
We can extract the values as a numpy array:
In [144]: pd.Series(df['newcol']).values
Out[144]: array(['Wow', 'Dud', 'Wow'], dtype=object)
We can apply a string slicing to each element of either the array or series - with a list comprehension:
In [145]: [astr[:2] for astr in _144]
Out[145]: ['Wo', 'Du', 'Wo']
In [146]: [astr[:2] for astr in _141]
Out[146]: ['Wo', 'Du', 'Wo']
The list comprehension isn't necessarily the most 'advanced' way, but it's a good start. Actually it is close to the best, since slicing a string has to use string methods; no one else implements string slicing.
pandas has a str method for applying string methods to a series:
In [147]: ds = df['newcol']
In [151]: ds.str.slice(0,2) # or ds.str[:2]
Out[151]:
0 Wo
1 Du
2 Wo
Name: newcol, dtype: object
This is cleaner and prettier than the list comprehensions, but actually slower.
A: I might be missing the gist of the question, but here's a regular expression implementation.
import re
# Sample data
disc = [' Disc - Standard Removal & Herbicide ',
' Disc - Standard Removal & Herbicide ',
' Standard Trim ',
' Disc - Hazard Tree',
' Disc - Hazard Tree ',]
# Regular Expression pattern
# We have Disc in parenthesis because that's what we want to capture.
# Using re.search(<pattern>, <string>).group(1) returns the first matching group. Using just
# re.search(<pattern>, <string>).group() would return the entire row.
disc_pattern = r"\s+?(Disc)\s+?"
# List comprehension that skips rows without 'Disc'
[re.search(disc_pattern, i).group(1) for i in disc if re.match(disc_pattern, i)]
Output:
['Disc', 'Disc', 'Disc', 'Disc']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59959149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Composite images in gnuplot I am trying to plot a 2D composite image in gnuplot. I have three different channels, and I would like each to be displayed in a different color. I would like to be able to pick the color, rather than using e.g. RGB. I want the output to look like this. Right now, I have my image data saved in a text file with columns X, Y, Channel 1, Channel 2, Channel 3
I can plot an RGB composite image using
file = "data.txt"
plot file using 1:2:3:4:5 with rgbimage
I can make a composite image "by hand" in the following way
# define channel colors by RGB values (normalized to 1)
array c1 = [0, 1, 1] # cyan
array c2 = [1, 0, 1] # magenta
array c3 = [1, 1, 0] # yellow
# define output colors for three channels
r(x, y, z) = c1[1] * x + c2[1] * y + c3[1] * z
g(x, y, z) = c1[2] * x + c2[2] * y + c3[2] * z
b(x, y, z) = c1[3] * x + c2[3] * y + c3[3] * z
plot data using 1:2:(r($3,$4,$5)):(g($3,$4,$5)):(b($3,$4,$5)) with rgbimage
Is there a built in gnuplot way to do this?
A: There is a builtin CMY color model for the palette, but I don't think that helps for this purpose. I can propose an alternative method that is slightly simpler than what you show. It works specifically for CMY, whereas the scheme you show could be adapted for other sets of colors. So honestly I think you may be better off with what you have.
# Assume input CMY values are in the range [0:1]
# We will convert to RGB values also in the range [0:1]
# Since color component values by default run from 0-255 we must
# first reset that range.
#
set rgbmax 1.0 # this command introduced in version 5.2.1
plot data using 1:2:(1.-$3):(1.-$4):(1.-$5) with rgbimage
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62974941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: merging json in jquery-ui What function does jquery ui use to override the default options passed to a plugin on init?
My plugin has an option that defaults to "false" and if you specify "true" it does something else. And if you specify an object (a json with more jsons nested) you open a whole bunch of possibilities. i want to set defaults for these options i know that ui is doing the same thing for standard "defaults" set, so where can i find that function?
A: This question was answered on the jQuery forum
It's jQuery.extend
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2328598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to prevent gcc from generating PT_GNU_STACK program header? My gcc 4.8 always generates a PT_GNU_STACK program header in the ELF executable on Linux.
When I use gcc -S, in the .s file (assembly file), gcc generates a line .section .note.GNU-stack,"",@progbits. Without this line the PT_GNU_STACK program header disappears from the ELF executable.
Is it possible to specify a command-line flag for gcc so that it won't generate the PT_GNU_STACK program header?
(I don't care if the stack is executable or not, either solution is fine for me.)
It looks like it's not possible to prevent gcc 4.8 from emitting .section .note.GNU-stack,"",@progbits, because this is hardcoded in file_end_indicate_exec_stack defined in gcc/varasm.c. But maybe there is another solution such a command-line flag to ld.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41901847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to proxy a websocket properly? I'm having trouble proxies websocket using http-proxy-middleware. The error I got was Websocket connection to https://api.dsm-staging.test.site failed.
Here's the code I'm using in express :
const { createProxyMiddleware } = require("http-proxy-middleware");
const options = {
target: "https://api.dsm-staging.test.site",
changeOrigin: true,
ws: true,
};
const proxy = createProxyMiddleware(options);
app.use("/v1/*", proxy);
This is my code in front end :
this.socket = io("https://api.dsm-staging.app.test.site", {
reconnectionAttempts: 5,
reconnectionDelayMax: 10000,
extraHeaders: {
Authorization: `Bearer ${token}`,
},
transports: ["websocket"],
});
this.socket.on("connect", () => {
console.log(this.socket.connected);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70468731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Will OSX devices register to a Raspberry Pi running avahi-daemon I have a Mac Mini on my local network running Plex Media Server on port 32400. The device is going to sleep mode after 1 hour of inactivity. I want the device to wake if a package is sent to it on port 32400.
If I understood it correctly I have to have a Bonjour Sleep Proxy in the same network, i.e. an AppleTV. I wonder if I can use a Raspberry Pi instead running the avahi-daemon? Will the Mac Mini register itself to Avahi running on the Raspberry Pi before sleeping and is it going to get woken up if I send a package on port 32400 to the Mac Mini?
As far as I can see, avahi-daemon is a Linux version of Apple's mDNSResponder which the Bonjour Sleep Proxies from Apple are running.
A: Avahi does not currently support sleep proxy, as either a client or server. So this will not work.
Currently you require some Apple device for a sleep proxy such as Airport, Time Capsule, Apple TV, etc.
I hope to add support for Sleep Proxy into Avahi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31045999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DownloadURL return null in below code When I change the file its successfully updated in firebase storage but I when I try to get downloadURL its show null.
fileChange(event: any) {
const imageFolder: string = this.employee.id;
const fileList: FileList = event.target.files;
const file: File = fileList[0];
const storageRef = firebase.storage().ref().child(`${imageFolder}/profile.jpg`).put(file);
console.log(storageRef.snapshot.downloadURL);
}
A: The put() is asynchronous. If you want to get the url after the file is uploaded you have to do it like this:
firebase.storage().ref().child(`${imageFolder}/profile.jpg`).put(file).then((snapshot) => {
storageRef = snapshot.downloadURL:
console.log(snapshot.downloadURL);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45758036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: figure - figcaption - responsive website Sorry, this looks easy but I can't seem to make it work.
I just want a website exactly like this:
I want it to be responsive, to work/look good on tablets and smartphones too.
I've tried everything but nothing seems to work.
So far I came up with this:
<div id="container">
<h1>title</h1>
<div id="grid">
<figure id="r">
<img src="http://placehold.it/300x200" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="p">
<img src="http://placehold.it/300x200" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="c">
<img src="http://placehold.it/300x200" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="s">
<img src="http://placehold.it/300x200" alt="">
<figcaption>caption</figcaption>
</figure>
</div>
</div>
I'm inexperienced in html/css but need it for tomorrow. Maybe you can help me, or post an example, maybe a website that is similar to what I want. Thank you very much.
A: You can do it with the Flexbox and @media queries:
* {box-sizing: border-box}
body {margin: 0}
#container {
width: 1200px; /* adjust */
max-width: 100%; /* responsiveness */
margin: 0 auto; /* horizontally centered on the page */
padding: 0 5px; /* adjust */
}
h1 {text-align: center}
#flex {
display: flex; /* displays flex-items (children) inline */
flex-wrap: wrap; /* enables their wrapping */
margin: 0;
}
figure {
display: flex; /* flex behavior also for figure elements */
flex-direction: column; /* stacks flex-items vertically */
justify-content: center; /* centers them vertically */
align-items: center; /* and horizontally */
flex: 0 1 calc(50% - 10px); /* initial width set to 50% - 10px (2 x 5px left & right padding) of the flex-container's (#flex) width */
margin: 5px; /* adjust */
}
img {
display: block; /* removes bottom margin/whitespace */
max-width: 100%; /* responsiveness */
}
@media (max-width: 568px) { /* adjust */
#flex {flex-direction: column}
}
<div id="container">
<h1>title</h1>
<div id="flex">
<figure id="r">
<img src="http://placehold.it/400x300" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="p">
<img src="http://placehold.it/400x300" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="c">
<img src="http://placehold.it/400x300" alt="">
<figcaption>caption</figcaption>
</figure>
<figure id="s">
<img src="http://placehold.it/400x300" alt="">
<figcaption>caption</figcaption>
</figure>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48488088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Better way of grouping rows by the latest entry within a group using LINQ Say I have a table with 3 cols: ActionId, uid & created.
I want to group actions by the uid, but every time a new action is inserted into a group (by uid), it will push the group upto the top, and individual rows within that group ordered.
This is what I came up with in SQL:
select * from actions as a
inner join
(
select aa.[uid], MAX(aa.[created]) as maxcreated
from actions as aa
group by aa.[uid]
) as a2 on a2.uid = a.uid
order by a2.maxcreated desc, a.created desc
Is there a better way to achieve this in SQL, and also then how to do this in LINQ?
A: So you want each group ordered internally, and the groups order by the latest value, right? Okay, I think we can do that...
var query = from action in actions
group action by action.Uid into g
orderby g.Max(action => action.Created) descending
select new { Uid = g.Key,
Actions = g.OrderByDescending(action => action.Created) };
foreach (var group in query)
{
Console.WriteLine("Uid: {0}", group.Uid);
foreach (var action in group.Actions)
{
Console.WriteLine(" {0}: {1}", action.Created, action.ActionId);
}
}
A: For the SQL, get the sort column in the SELECT statement
SELECT *, (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) AS MaxCreated
FROM actions a
ORDER BY MaxCreated desc, a.created desc
or
SELECT *
FROM actions a
ORDER BY (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) desc, a.created desc
(just fixed an error in the first query)
Here's my linq:
var actions = (from a in actions
orderby ((from a2 in actions
where a2.UserID == a.UserID
select a2.created).Max ()) descending, a.created descending
select a);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6597382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Consume a web service by a web service via Mule ESB I have a web service that sends a name to a web service called sayHello(), and receives a String "Hello, name".
I want to change the point-to-point connection to something like this:
web service ---> Mule ESB ---> web service
I wonder how can I do that? I've searched for a long time but I didn't find useful document on this topic. Which endpoints should I use?
Thanks.
A: It depends on the type of webservice you need to expose and consume:
For exposing SOAP based webservices, you can use some strategies,
1) Proxying webservices with Protocol Bridging or WSProxyService
https://docs.mulesoft.com/mule-user-guide/v/3.7/proxying-web-services
2) Proxying webservices with CXF
https://docs.mulesoft.com/mule-user-guide/v/3.7/proxying-web-services-with-cxf
3) Building a webservice with CXF
https://docs.mulesoft.com/mule-user-guide/v/3.7/building-web-services-with-cxf
For exposing RESTful webservices, you should design a RAML and then use the APIKit component
http://raml.org/
https://docs.mulesoft.com/anypoint-platform-for-apis/apikit-tutorial
For consuming SOAP based webservices, you should use the Webservice Consumer component
https://docs.mulesoft.com/mule-user-guide/v/3.7/web-service-consumer
For consuming REST webservices, you should use the HTTP Request Connector :
https://docs.mulesoft.com/mule-user-guide/v/3.7/http-request-connector
So, if you want to expose a SOAP webservice (not a proxy service), that internally consumes a SOAP webservice, you can use:
HTTPListener->CXF->WebserviceConsumer
If you want to expose a webservice proxy you can use the ProtocolBridging or CXF strategy.
If you want to expose a REST webservice, that internally consumes a REST webservice, you can use:
HTTPListener->APIKit->HTTPRequest
And so on..
A: This describes a scenario that you are trying to fulfill https://docs.mulesoft.com/anypoint-platform-for-apis/proxying-your-api
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34002118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: JS: Extract number from string, that is before a specific word I want to extract the number that is exactly before the text kcal. How may I do this?
foo = "1119 kJ / 266 kcal";
// want to return: 266
http://regex101.com/r/tZ3fH8/1
A: You can use a capturing group to match and capture the digits preceding that word. The below regex will match/capture any character of: digits, . "one or more" times preceded by optional whitespace followed by the word "kcal".
var r = '1119 kJ / 266 kcal'.match(/([\d.]+) *kcal/)[1];
if (r)
console.log(r); //=> "266"
A: Regex is simpler and cleaner but if it's not for you then here's another route. You can split your string by the "/" then split it again by the resulting pairs:
foo = "1119 kJ / 266 kcal";
pairs = foo.split("/");
res = pairs[1]; //get second pair
var res = foo.split(" "); //spit pair by space.
if (isNumber(res[0]) {
alert("It's a number!");
}
function isNumber(n) {
//must test for both conditions
return !isNaN(parseFloat(n)) && isFinite(n);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27052436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where are Apache Giraph logs (with log4j) located? I am currently experimenting with Apache Giraph using the configuration described in the QuickStart Tutorial :
*
*Ubuntu 12
*Hadoop 0.20
*Giraph Release 1.2
I am running all computation on a single-node local cluster, as described in the QuickStart.
While running the example computations and other custom codes work fine, I am unable to retrieve/locate the logs expected whith log4j logger.
Could you indicate me where these logs are located, either in local system or HDFS ?
Command used to launch Giraph computation :
$HADOOP_HOME/bin/hadoop path/to/giraph/jar org.apache.giraph.GiraphRunner community.RevertedGraphComputation community.JsonLongLongDoubleVertexInputFormat /user/hduser/input/test_graph.txt community.VertexWithLongValueDoubleEdgeTextOutput /user/hduser/output/reverted
Thank you !
Abreviated version of the java code for logging :
//In RevertedGraphComputation class
private static Logger LOG = Logger.getLogger(RevertedGraphComputation.class);
//In compute() method
LOG.info("Vertex "+vertex.getId());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65043003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pandas - How to assign different classes to a recurring series without using a loop? I have a series with recurring values in pandas dataframe. The first 20 values are given below:
# input
[-1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1]
Note that -1 indicates the start of a new class while 1 indicates continuation of previous class.
I can change "-1" and "1" to any value for the encoding.
What I want for the output is to be class labels like given below:
# output
[0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5]
For now I have done this using a for loop.
I could not find a better way with in-built pandas / python functions.
How do I achieve this without using for loop?
A: Compare values by -1 and use cumulative sum by Series.cumsum and if first value of Series is 0 subtract 1:
s = pd.Series([-1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1,
1, 1, 1, 1, -1, 1, 1, 1])
s1 = s.eq(-1).cumsum()
out = s1.sub(1) if s[0] == -1 else s1
If always first value is -1 subtract 1:
out = s.eq(-1).cumsum().sub(1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67412412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: for in loop not working as expected javascript I have an object, Object { 2014-01-30=[1], 2014-02-01=[1]}
and an array called fechasPeriodo,
so why is the following code:
fechasPeriodo = [];
for(var property in SelectedDates) {
fechasPeriodo.push(new Date(property));
}
producing this result [Date {Wed Jan 29 2014 18:00:00 GMT-0600}, Date {Fri Jan 31 2014 18:00:00 GMT-0600}]
Edit: I'd expect the result to be Thu Jan 30 2014 etc. , Sun 02 Feb 2014.
Actually it's a problem only because I'm trying to define a range of dates in datepicker using a Google Calendar feed. So the following code:
if(fechasPeriodo.length > 1) {
r[1] = fechasPeriodo[0] <= date && date <= fechasPeriodo[1] ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
}
I'd expect to highlight a range from the 30th Jan to the 02nd of February. But if you can guide me as to why it isn't working, I'd be very grateful, I'm following this fiddle:
http://jsfiddle.net/qaEuj/
At the risk of being downvoted again I have to say that I still don't understand why my last bit of code above isn't working like the fiddle I mention, so here's my complete code:
$(document).ready(function() {
var fechaDefecto = new Date('2014/01/01');
var fechaFin = new Date('2014/08/31');
SelectedDates = null;
/*SelectedDates[new Date('12/25/2014')] = new Date('12/25/2014');
SelectedDates[new Date('12/12/2014')] = new Date('12/12/2014');
SelectedDates[new Date('06/06/2014')] = new Date('06/06/2014');*/
$('#tiposFechas').change(function() {
$.getJSON("https://www.google.com/calendar/feeds/cide.edu_sm151i2pdhu2371vq8hamcver4@group.calendar.google.com/public/full?q="+encodeURI($(this).val()), {"alt" : "json"}, function(data) {
SelectedDates = {};
$.each(data.feed.entry, function(i, entry) {
var key = entry.gd$when[0].startTime.substr(0, 10)
var clave = entry.gd$when[0].endTime.substr(0, 10);
if(key in SelectedDates === false || clave in SelectedDates === false) {
SelectedDates[key] = [];
SelectedDates[clave] = [];
}
SelectedDates[key].push(entry.title.$t);
SelectedDates[clave].push(entry.title.$t);
});
$('#cal').datepicker("refresh");
});
});
$('#cal').datepicker(
{
beforeShowDay: function (date) {
var r = [true, ""];
if (SelectedDates === null) {
r[1] = "Highlighted-unknown";
}
else {
fechasPeriodo = [];
for(var property in SelectedDates) {
fechasPeriodo.push(new Date(property));
//alert(property);
}
var key = $.datepicker.formatDate("yy-mm-dd", date);
if(key in SelectedDates) {
if(fechasPeriodo.length > 1) {
r[1] = fechasPeriodo[0] <= date && date <= fechasPeriodo[1] ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
}
else {
r[1] = "Highlighted"+SelectedDates[key][0].replace(/\s/g, "_");
}
r[2] = SelectedDates[key].join(", ");
}
}
return r;
},
minDate : fechaDefecto,
maxDate : fechaFin,
numberOfMonths: [3,3]
});
});
I'm hoping someone points out a cause, even if it's a criticism, because it's getting late.
I must say I tried this:
r[1] = new Date(fechasPeriodo[0].getYear(), fechasPeriodo[0].getMonth(), fechasPeriodo[0].getDate()) <= date && date <= new Date(fechasPeriodo[1].getYear(),fechasPeriodo[1].getMonth(),fechasPeriodo[1].getDate()) ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
But didn't work either. May there be a problem in the way I'm representing the dates when I call new Date in the line fechasPeriodo.push(new Date(property)); and the way I'm comparing them?
A: It's just the difference between the UTC and non-UTC representation.
new Date('2014-01-30').toString(); //Wed Jan 29 2014 19:00:00
new Date('2014-01-30').toUTCString(); //Thu, 30 Jan 2014 00:00:00
Try fechasPeriodo[0].toUTCString(); and I'm pretty sure it will return what you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26900421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: RedisConnectionException: Unable to init enough connections amount Today I start the spring boot project in MacBook Pro with M1 pro(with 8 performance core and 2 efficient core), shows error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redissonClient' defined in class path resource [misc/redisson/RedissonConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.redisson.api.RedissonClient]: Factory method 'redissonClient' threw exception; nested exception is org.redisson.client.RedisConnectionException: Unable to init enough connections amount! Only 10 of 24 were initialized. Redis server: cruise-redis-master.reddwarf-cache.svc.cluster.local/10.108.202.100:6379
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.19.jar:5.3.19]
the remote redis was a single redis master server with 2 slaves. my redission config look like this:
package misc.redisson;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author dolphin
* @version 1.0
* @date: 2020/9/5 9:50
*/
@Configuration
public class RedissonConfig {
@Value(value = "${spring.redis.host}")
private String redisHost;
@Value(value = "${spring.redis.port:6379}")
private Integer redisPort;
@Value(value = "${spring.redis.timeout:2000}")
private Integer redisTimeOut;
@Value(value = "${spring.redis.password}")
private String redisPwd;
@Bean(name = "redissonClient")
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + redisHost + ":" + redisPort)
.setPassword(redisPwd)
.setTimeout(redisTimeOut)
.setDatabase(1);
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
}
and the redis server(2Core and 8GB memory in the cloud) max client config:
connected_clients
120
cluster_connections
0
maxclients
10000
the remote server was a single kubernetes node, and connected local machine and remote server by telepresence. why did this happen? what should I do to fixed this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72484061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a shared static field in c# The question that I have is in regards to creating a shared field that is Static within an instance class. The code that I am going to display works perfectly fine. What I am really wanting to grasp is the understanding behind the logic. Here is a code snippet which is of a very basic class and a method which creates objects from this class and displays to the screen how many objects have been created.
public class Counter
{
private int value;
private static int ValueCounter = 0;
public Counter()
{
value = ValueCounter;
ValueCounter++;
}
public static int objectCount()
{
return ValueCounter;
}
}
Above is a very basic but working class. I am trying to keep it as simple and as basic as possible so that I get the understanding of it.
Below is now the code snippet that creates instances of the class and displays to the screen how many instances have been created.
private static void showObjectCounter()
{
Counter val1 = new Counter();
Counter val2 = new Counter();
Counter val3 = new Counter();
Counter val4 = new Counter();
int totalValue = Counter.objectCount();
Console.WriteLine("Total objects created = {0}", totalValue);
}
Now this is my question regarding this matter. When a new object is created the value field is independent of each instance hence each object gets there own copy. However the static field is a shared field and incremented with each new creation of an object. I was wondering if this increment value is saved after each creation of the new object i.e one object is created value is incremented to 1, then another object is created and the last value of the increment was at 1 so now it is incremented to 2 and so on for each new object creation.
Or does each new object that is created get incremented to 1 and then are all added together to find the total value of the objects created ?
It is a very basic and simple question but Iam fighting with myself over which is ryt or wrong prob because of the time of nyt that it is. Anyhow if anyone has a simple answer to a very simple question then please feel free to share it.
Thanks.
A: It's really a shared value, so every time a constructor runs, the value is incremented by 1 regardless of when the variable is accessed thereafter. You could verify this yourself:
private static void showObjectCounter()
{
Counter val1 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val2 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val3 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
Counter val4 = new Counter();
Console.WriteLine("Total objects created = {0}", Counter.objectCount());
}
You'll see that value changes every time.
A: You might be helped by using some conventional naming and coding style.
*
*Use this for instance variables
*Use C# Property instead of getter/setter method
*Don't use this for static variables
*Slightly more descriptive naming
Sample:
public class Counter
{
public int Count { get; }
private static int instanceCounter = 0;
public static int InstanceCount
{
get
{
return instanceCounter;
}
}
public Counter()
{
this.Count = instanceCounter;
instanceCounter++;
}
}
A: In your example, there is only one physical location in memory that corresponds to the ValueCounter variable.
By contrast, the non-static value field is stored in each instance's object data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22798434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to authenticate ansible managed node using cyberark password I'm having 1000 + RHEL 6/7 servers integrated with cyberark, the local user's (sudo user - remote user as per Ansible control node) is fetching password from my cyberark and it gets refreshed every 8 hours. Can you please suggest procedure to authenticate and execute my playbooks on the managed nodes using cyberark password.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64841200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Checkbox choice changed when listview expanded
I checked the first three checkbox on expandableListView. Why when I expand listview is the last CheckBox checked?
private ArrayList<Group_Items> setAllData() {
String group_titles[] = {
"Payment of Employer and employees contribution",
"Monthly Return Filing in Form 5 and Declaration in form 2",
"Monthly Return Filing in Form 10",
"Monthly Return Filing in Form 12",
"Statement of Recovery from contractor",
"Annual Return in Form 6A",
"Renewal of contribution card of an employee by filing Form 3 & 3A",
"Submission of contribution card of employees leaving services" };
String child_info[] = {
"We have deployed secured web services framework in accordance with OASIS standards. Please refer the user manual (Secured Web service user manual) under the help section and do the necessary changes at your end to start consuming the same. Existing web services shall be discontinued w.e.f 1-Dec-2015.",
"Return of employees qualifying for membership",
"Return of members leaving the services during the month",
"Statement of contribution",
"Self Explnatory",
"Consolidated annual contribution statement",
"Self Explnatory",
"Self Explnatory" };
String dates[] = {
"15th of Next Month + 5 Days Grace period",
"15th of Next Month",
"15th of Next Month",
"25th of Next Month",
"7th of Next Month",
"30th April",
"Within one month on the expiry of contribution card currancy to the commissioner",
"20th of Next Month" };
ArrayList<Group_Items> list = new ArrayList<Group_Items>();
ArrayList<Child_Items> ch_list= new ArrayList<Child_Items>();
ch = new Child_Items();
int i=0;
int size=1;
for (String group_title : group_titles) {
Group_Items gru = new Group_Items();
gru.setName(group_title);
ch_list = new ArrayList<Child_Items>();
for (; i < size; i++) {
Child_Items ch = new Child_Items();
ch.setChild_title(child_info[i]);
ch.setDd("Due Date:");
ch.setDate(dates[i]);
ch_list.add(ch);
}
gru.setItems(ch_list);
list.add(gru);
size=size+1;
}
return list;
}
I have created ExpandableListView with CheckBox beside each title and when I checked first three or four CheckBox from eight titles and first groupItem is expanded then automatically the last (8th) CheckBox is checked.
This is my custom adapter code
public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter{
Context context;
ArrayList<Group_Items> group_al;
public MyBaseExpandableListAdapter(Context context,ArrayList<Group_Items> group_al) {
this.context=context;
this.group_al=group_al;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Child_Items> chList = group_al.get(groupPosition).getItems();
return chList.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
Child_Items ch = (Child_Items) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandable_child_items, null);
}
TextView child = (TextView) convertView.findViewById(R.id.child);
TextView dd = (TextView) convertView.findViewById(R.id.dd);
TextView date= (TextView) convertView.findViewById(R.id.date);
child.setText(ch.getChild_title().toString());
dd.setText(ch.getDd().toString());
date.setText(ch.getDate().toString());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
ArrayList<Child_Items> chList = group_al.get(groupPosition).getItems();
return chList.size();
}
@Override
public Object getGroup(int groupPosition) {
return group_al.get(groupPosition);
}
@Override
public int getGroupCount() {
return group_al.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Group_Items gr = (Group_Items) getGroup(groupPosition);
long group_id = getGroupId(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.expandable_group_items, null);
}
TextView title = (TextView) convertView.findViewById(R.id.title);
title.setText(gr.getName());
CheckBox chk=(CheckBox) convertView.findViewById(R.id.chk);
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return false;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35263866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to Create a filter function for Scheme So i have
(define (countNumber lats)
(let loop ((lats2 lats)
(count 0))(cond ((null? lats2) count)
((number? (car lats2))
(loop (cdr lats2) (+ count 1)))
(else (loop (cdr lats2) count)))))
and i want to make a filter function that goes something like
(define (filter func lst)
(countNumber (filter lst)))
So essentially you pass in something like (filter even? '(1 2 3 4)) and it returns 2 and 4. filter: arity mismatch is the error given.
A: You forgot to pass the func predicate along, and don't name your function filter, that clashes with a built-in procedure. Try this:
(define (my-filter func lst)
(countNumber (filter func lst))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28330718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing of interface methods Actually the code below is Simple example of interface.But it showing an error 'PublicDemo.DemoPublic' does not implement interface member 'PublicDemo.demo1.two()'. 'PublicDemo.DemoPublic.two()' cannot implement an interface member because it is not public.
namespace PublicDemo
{
public interface demo
{
void Demo();
}
public interface demo1:demo
{
void one();
void two();
}
class DemoPublic :demo1
{
protected internal string variable;
public void Demo()
{
Console.WriteLine("{0}", variable);
}
public void one()
{
Console.WriteLine("this is one method");
}
protected void two()
{
Console.WriteLine("this is two method");
}
}
class Excute : DemoPublic
{
static void Main(string[] args)
{
Excute Dp = new Excute();
Dp.variable = Console.ReadLine();
Dp.Demo();
Dp.one();
Dp.two();
Console.ReadKey();
}
}
}
i need why it is not working
A: Change
protected void two()
{
Console.WriteLine("this is two method");
}
into
public void two()
{
Console.WriteLine("this is two method");
}
A: You yourself answered the question:
'PublicDemo.DemoPublic.two()' cannot implement an interface member because it is not public.
Answer is Interface members have to be public.
A: Change Protected to Public.You have defined an public Interface.Once you define Public Interface,the Contracts in the Interface also will be public by Default.
public void two()
{
Console.WriteLine("this is two method");
}
A: It means what is says. Your two method is protected. It needs to be public if implemented from an interface.
protected void two(){
Console.WriteLine("this is two method");
}
change it to public
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24691508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to print out autoincrement ID in Activerecord model I have a before_save in my model
before saving the record to the database...I'd like to print out the autoincremented ID that will be inserted. My table has a column id in it.
I tried
before_save :printId
def printId
puts "ID that will be inserted is: " + self.id
end
this does not work...
A: Try after_save.
A: The autoincrement ID does not exist for an ActiveRecord object until it has been saved. It's possible to get the next autoincrement ID for a table, but this doesn't guarantee that the ID will be given to your object when saved since another record may have been added in the meantime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2233721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Connect to Access database protected with database password using UCanAccess I can connect to an Access database with UCanAccess from NetBeans 8, but now I need to specify database password in the connection properties. How can I do that?
A: use following way,
DriverManager.getConnection("jdbc:ucanaccess://path_to_your_db_file", your_user, your_password);
or
DriverManager.getConnection("jdbc:ucanaccess://path_to_your_db_file;password=your_password");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25201483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Finding previous page Url i am trying to find the url of previous page.Such as if a user navigates from Page A to Page B using Server.Redirect("B.aspx"), page B can display the url referring to it.
I have tried using
Response.Write(Page.PreviousPage.ToString());
Response.Write(Request.UrlReferrer.ToString());
Response.Write(Context.Request.UrlReferrer.ToString());
Response.Write(Request.ServerVariables["HTTP_REFERER"].ToString);
but all in vain it gives me null exception error
A: You can save you current page in the Session and then retrieve it from there:
string previousPage = Session["PreviousPage"] as string;
Session["PreviousPage"] = System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.FilePath);
This way the previousPage string will always contain the previous page's filename, and the Session variable will contain the current page, ready to be used on the next page.
This way you can also detect if the referrer is an outside link because then the previousPage string will be null.
A: If it's only for this scenario (where you programatically redirect to B.aspx) then why not put something on the querystring to say where the redirect came from. This would be more likely to work across muliple browser types and devices.
One advantage to this approach is that you'll be able to tell the difference between a redirect to B.aspx and a direct link (either via a link on one of your pages, or from the user entering the URL into the address base) to page B.aspx.
The referrer is something the the client provides as part of the HTTP request. As such, you can't rely on it.
By the way, this question is related:
Request.UrlReferrer null?
Update
Given your comments it's not clear that's an easy solution other than "edit all your files". I suspect that global search/replace might be your best bet.
Some more background: If you use Fiddler (or any other http debugging tool) you should be able to see that the Referrer header isn't being populated when you perform a redirect. For example, this is the result of a redirect (i.e. an HTTP 302 response causing IE to redirect to another page):
GET /webapplication1/WebForm3.aspx HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: en-GB
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MS-RTC LM 8; Zune 3.0)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: (removed)
Here is the HTTP request that is generated by clicking the "Questions" link on StackOverflow.com:
GET /questions HTTP/1.1
Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Referer: https://stackoverflow.com/questions/772780/finding-previous-page-url
Accept-Language: en-GB
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MS-RTC LM 8; Zune 3.0)
Accept-Encoding: gzip, deflate
Host: stackoverflow.com
Connection: Keep-Alive
You can see that the later, generated by a link on a page, generates the Referer header.
A: You can also use Server.Tansfer("B.aspx") instead of Response.Redirect("B.aspx")
Edit: Searock, if you don't want to change your existing code, Request.ServerVariables["HTTP_REFERER"].ToString() should work fine in that case.
A: Just to note that HTTP_REFERER is not reliable. You can't rely on that because so many clients doesn't send for various reasons (paranoid settings, security software etc.).
Also some new windows opened by JS might not have REFERER
SSL > NONE SSL pages won't have REFERER either, so be careful about relying something like that.
Better idea would be sending previous page in Querystring.
If it's ASPX you might do it in more clever way like adding a new hidden parameter to all forms or processing link just before writing out the buffer.
A: Could you just confirm what methods you are actually using here (ideally by editing the original question)?
HttpServerUtility (i.e. Server.) doesn't have a "Redirect" method, it has Transfer and Execute.
HttpResponse (i.e. Response.) does.
HttpResponse.Redirect will send a 302 response to the client, telling it to issue a new request for the value of the Location field. I'm then able to query Request.UrlReferrer to see the value of the page that performed the Redirect.
If you are using HttpServerUtility.Transfer or HttpServerUtility.Execute then these actions happen entirely at the server within ASP.NET, and so the "referrer" may well be null. The client browser will also think it is still on the originally requested page.
See also How to detect if an aspx page was called from Server.Execute
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/772780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Linking to a static library that requires a frameworks I have a main project and a few smaller sub-projects. The smaller projects contain both a self contained Cocos2d app and a static library containing only the classes that are relevant to the main project (the sub-projects all use the Cocos2D framework). The main project is dependant on the static libraries. I think this approach is theoretically sound, but in practice it is not working.
The symptom I am seeing is as follows: When the code is executed as part of the main project the pre-processor values work. When I run the app of a subproject it runs as expected.
I have set the -all_load linker option in the main target. This is because the classes in the sub-projects are only mentioned in nib files. Without -all_load the classes are 'optimized' out of the main target as the compiler incorrectly determines the code to be superfluous.
I have linked all of the sub-projects to the .frameworks that they require.
Is this fixable or is this approach doomed to fail? How else can I manage these projects without static libraries? Other developers work on the sub-projects and the static library approach prevents us from getting in each others way.
Update
Reading that question back makes me think I should have taken a break a lot earlier! The question doesn't explain the problem very well (or make much sense!). The problem relates to how to use sub-projects to organise code. I've now almost solved the issue. I'll probably write a blog post when I've fully solved it.
A: Since the static libraries end up "baked in" to your executable, you don't need to concern yourself with their linking anymore than you need your executable.
Just set up the project dependencies so that the dependent framework builds first (so the .framework/Headers folder gets populated properly), then the libraries, then your app. I have done this in multiple apps with great success.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6573833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to convert date and time to different timezones in momentjs In my angular app I have a selectbox, where the user can select to which timezone he/she wants to convert a specific time. Currently I'm using momentjs for date-time manipulations, the problem is I don't know, how to change the date-times's timezone dynamically, as momentjs has only .utc() method.
Till now I used only one timezone, so I've hard-coded the utc() method.
My service:
public convertDate(): void {
this.date = moment(this.date).utc().format("DD/MM/YYYY - HH:mm");
}
Should be (pseudo code):
public convertDate(selectedTimezone: string): void {
this.date = moment(this.date).selectedTimezone().format("DD/MM/YYYY - HH:mm");
}
A: You can use moment-timezone.
*
*Install the moment-timezone:
npm install --save moment-timezone
*Install types: npm install -D @types/moment-tipes
*Import to your service: import "moment-tipes"
In your angular service:
public convertDate(selectedTimezone: string): void {
this.date = moment(this.date).tz(selectedTimezone).format("DD/MM/YYYY - HH:mm");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49552974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Use the WCF Service developed in .Net 4.0 in the Application developed in 2.0 or lower version? I came across with this situation. I have one already developed Application in 2.0, Now in this application i want to use one WCF Service that is developed in 4.0. How can i do this?
I tried the following
1. Regular Method Add the Service Reference and then use that. It didn't work for me.
2. I googled it and i got one more method, using svcutil.exe, but i dont have svcutil.exe with 2.0.
Waiting for the response.
Thanks in advance.
A: Windows Communication Foundation (WCF) was first introduced to the .NET Framework as part of .NET 3.0. It's not available with .NET 2.0.
If the WCF service exposes a SOAP endpoint then you may be able to use it through the Web Service Extensions (WSE) that were published for old versions of Visual Studio. See here: http://www.microsoft.com/download/en/details.aspx?id=10854 for details.
A: If you want to use a service written in .Net 4 with a .Net 2.0 project, you should be able to use basic http binding. That should allow it to interop with a client that knows nothing about WCF. It's similar to using an old school .asmx web service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8092963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.