text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Restrict specific Pages to Load in WKWebview? How can i prevent any web page to load in WEKWebView?
In-order to load whole website i am using this code
self.webview.customUserAgent = userAgent
self.webview.navigationDelegate = self
self.webview.load(URLRequest.init(url: URL.init(string: snapshot.value as! String)!))
but know i want to restrict some specific page to load in this webview by using NavigationDelegate methods?
A: Nice way to do this is to compare URL Host which can be done using the following approach
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let exceptedHosts: [String] = [
"facebook.com",
"m.facebook.com"
]
if let host = navigationAction.request.url?.host {
if exceptedHosts.contains(host) {
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
This will prevent any url with facebook.com or m.facebook.com from being opened, add any hosts to the array to except them from being opened.
Please don't forget to set delegate in viewDidLoad
webview.navigationDelegate = self
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60631926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to import pts file in Matlab I have a pts file with 2d points (x,y) that looks like this:
version: 1
n_points: 5
{
159.128 108.541
230.854 109.176
164.841 179.633
193.404 193.597
192.769 229.143
}
How can I read this file and import this data into variables in Matlab?
Thanks.
A: i would do it like that
FileId=fopen(Filename)
npoints=textscan(FileId,'%s %f',1,'HeaderLines',1)
points=textscan(FileId,'%f %f',npoints{2},'MultipleDelimsAsOne',1,'Headerlines',1)
% now you have the values you want you can put them in a matrix or any variable
Y=cell2mat(C);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19841382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: CoreData+MagicalRecord.h file not found I got stuck into pretty simple looking error but I am not able to solve it.
I am trying to add MagicalRecord into my project with the help of this tutorial, but, after adding #import "CoreData+MagicalRecord.h" in prefix.pch I am getting CoreData+MagicalRecords.h file not found error.
I also tried #import <MagicalRecord/MagicalRecord.h> this but same error.
What can be the issue.
UPDATE:
Adding my prefix file code here.
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Constants.h"
#define MR_SHORTHAND
#import "CoreData+MagicalRecord.h"
#endif
A: This may not be directly related to the original question's problem, but could come in handy.
If you are using Magical Record 2.3 beta 6 or later, it seems from the issues that there was a problem with manual importing that never got sorted out. See https://github.com/magicalpanda/MagicalRecord/issues/1019 (thought the referenced issue claims to have fixed it, I beg to differ)
I was able to get my manual version to build and run by converting my imports from the format #import <MagicalRecord/filename.h> to #import "filename.h".
A: I had the same problem before. This sounds ridiculous but move #import <CoreData+MagicalRecord.h> above #import <UIKit/UIKit.h>. Note the use of <> instead of "" if you are using pods.
Edit
Please take note that this is an old answer. It worked for me before when I posted it. It may not work anymore... I have not used MagicalRecord for quite some time now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31026809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Limitations for Firebase Notification Topics I want to use Firebase notification for my android application and what i want to know is that is there any limitation for number of topics ? or for the number of users that can subscribe a topic ?
For example can i have 10000 topics with 1 million users for each of them ?
A: There is no limitation on the number of topics or subscriptions. There was a limitation of 1 million subscriptions for the first year after topics was initially launched but that restriction was removed at this year's (2016) Google I/O. FCM now supports unlimited topics and subscribers per app. See the docs for confirmation.
A: Topic messaging supports unlimited subscriptions for each topic. However, FCM enforces limits in these areas:
*
*One app instance can be subscribed to no more than 2000 topics.
*If you are using batch import to subscribe app instances, each request is limited to 1000 app instances.
*The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.
Check this
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38829466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: c# LiveCharts WPF how to add 0 value to a date where data does not exist to show in CartesianChart This question is propably more a concept question, but I'm stuck here logically.
I'm using LiveChart for WPF and I try to build a simple CartesianChart dynamically.
I load my Data from a CSV into a List, I'm counting how many times each datapair is in that file and add the amount. The result from this Linq request looks like this:
[0] { Dates = "20191123", Rank = "1st", Amount = 1 } <Anonymous Type>
I go through this result to pick me each date individually for the Lables of my CartesianChart
Now I would like to add my result Data into the CartesianChart for that I need a SeriesCollection mine looks like this:
SeriesCollection = new SeriesCollection
{
new LineSeries
{
Title = "1st",
Values = new ChartValues<int> {}
},
new LineSeries
{
Title = "2nd",
Values = new ChartValues<int> {}
},
new LineSeries
{
Title = "3rd",
Values = new ChartValues<int> {}
}
}
But when I go through my data on some dates I dont have for example first place, so I need a 0 amount value for this day. I'm struggeling to add this to my data.
Here is pretty much the whole code block im experimenting with, that also why it looks a little messy.
var data = File.ReadAllLines(FilePathes.resultPath).ToList();
var rankHistoryList = new List<RankHistory>();
foreach (var line in data)
{
rankHistoryList.Add(RankHistory.parse(line));
};
var result = rankHistoryList.GroupBy(x => new { x.Dates, x.Rank })
.Select(g => new { g.Key.Dates, g.Key.Rank, Amount = g.Count() })
.ToList();
var dates = new List<string>();
foreach (var entry in result)
{
dates.Add(entry.Dates);
}
var singleDates = dates.GroupBy(x => x).Select(grp => grp.First()).ToArray();
foreach (var day in singleDates) {
foreach (var entry in result) {
if (entry.Rank == "1st" && day == entry.Dates)
{
SeriesCollection[0].Values.Add(entry.Amount);
}
else if (entry.Rank != "1st" && day == entry.Dates)
{ SeriesCollection[0].Values.Add(0); }
}
}
A: I think my answer is the most complicated but at least it works:
var allRanks = new List<string>
{
"1st"
,"2nd"
,"3rd"
};
foreach (var entry in result)
{
dates.Add(entry.Dates);
}
var singleDates = dates.GroupBy(x => x).Select(grp => grp.First()).ToArray();
Labels = singleDates;
foreach (var ran in allRanks)
{
foreach (var day in singleDates)
{
if (ran == "1st")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[0].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[0].Values.Add(0);
}
if (ran == "2nd")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[1].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[1].Values.Add(0);
}
if (ran == "3rd")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[2].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[2].Values.Add(0);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59017040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using matlab to read h5 file and display the data in video format I am trying to read the data from h5 file,display it in video format and also store it in video format(.avi,mp4 etc.)
This is the properties of data displayed using: h5disp(filename,datasetname)
> Group '/'
> Dataset 'sequence'
> Size: 1x36x36x193
> MaxSize: InfxInfxInfxInf
> Datatype: H5T_IEEE_F32LE (single)
> ChunkSize: 1x9x9x49
> Filters: fletcher32, deflate(4)
Than I used : data = h5read(filename,datasetname) to read the data and also displayed it on the window.It is showing a proper matrix of data.
Than I used :
load cellsequence
implay(data);
It is showing error: Invalid video format:The 3rd dimension of file should be 1 or 3 Image of error
A: The issue is that the dimensions are incorrect. If you do
data1 = permute(data, [2 3 1 4]); implay(data1)
It should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49561119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating undefined method behavior in Java? I have got a task about a board game to suggest the best move via a method when we get an in-progress game state. I have to do it in Java.
There is a strange instruction in the task: if we get a state which can't occur in normal play then "the behavior of this method is undefined". (You can imagine this state like in chess you get a board with two kings on adjacent fields, which can't be happened in a real chess game.)
The question is: what can this instruction mean? Is there anybody who has already faced with a same problem?
First, I thought that in such a state I should throw, for example, an IllegalStateException. But according to another instruction line I have to throw IllegalStateException when I get a board with a state representing that one of the players has already won the game, or it is draw.
I have already searched for the definition of undefined behavior, but I don't know how can I use it in this case. At all, can I create this kind of behavior in Java which can be connected to this kind of case?
A: I think when the problem states "this behavior is undefined" it's just saying that they aren't going to test that condition because you can't reasonably be expected to do anything. It's not actually a task for you to complete - it's just telling you not to worry about those scenarios.
A: Why not write an "ImpossibleStateException" and throw this if the said case is true?
It's part of Java's design that you can write own exception classes, so why not write one and throw it when an undefined state is happening.
I'm not sure how the said state is ever produced, I could imagine if you talk about a kind of board game, maybe somebody fiddles around with the ram or the vm and tries to cheat / hack the game.
Also, if somebody would make a deep test of EVERY possible state of the program, like every variable with every possible value the game allows, there would be around 98% cases that made no sense at all.
A: From Oracle doc IllegalStateException:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
So I think in your sitiation it is not good solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39798498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Check if the current time is less than a specific time Let's say I got this time 21:07:35 now and this time into a variable 21:02:37 like this
<?php
$current_time = "21:07:35";
$passed_time = "21:02:37";
?>
Now I want check if $current_time is less than 5 minutes then echo You are online
So how can I do this in PHP?
Thanks
:)
A: To compare a given time to the current time:
if (strtotime($given_time) >= time()+300) echo "You are online";
300 is the difference in seconds that you want to check. In this case, 5 minutes times 60 seconds.
If you want to compare two arbitrary times, use:
if (strtotime($timeA) >= strtotime($timeB)+300) echo "You are online";
Be aware: this will fail if the times are on different dates, such as 23:58 Friday and 00:03 Saturday, since you're only passing the time as a variable. You'd be better off storing and comparing the Unix timestamps to begin with.
A: $difference = strtotime( $current_time ) - strtotime( $passed_time );
Now $difference holds the difference in time in seconds, so just divide by 60 to get the difference in minutes.
A: Use Datetime class
//use new DateTime('now') for current
$current_time = new DateTime('2013-10-11 21:07:35');
$passed_time = new DateTime('2013-10-11 21:02:37');
$interval = $current_time->diff($passed_time);
$diff = $interval->format("%i%");
if($diff < 5){
echo "online";
}
A: $my_time = "3:25:00";
$time_diff = strtotime(strftime("%F") . ' ' .$my_time) - time();
if($time_diff < 0)
printf('Time exceeded by %d seconds', -$time_diff);
else
printf('Another %d seconds to go', $time_diff);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18038862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: I/flutter ( 4037): The method '[]' was called on null I am getting an error trying to run this code about the method '[]' being null. Is it maybe the list view? The output doesn't even show up in debug console anymore. Sorry I'm new to this.
The code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class GetStats extends StatefulWidget {
@override
_GetStatsState createState() => _GetStatsState();
}
class _GetStatsState extends State<GetStats> {
Map data;
Future<String> getData() async {
var response = await http.get(
Uri.encodeFull(
'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=D5F4E0DED484F47380C2804A529BAEDC&steamid=76561198406742636'),
headers: {"Accept": "application/json"});
setState(() {
data = json.decode(response.body);
});
print(data["playerstats"]["stats"][0]["value"]);
}
@override
void initState() {
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CSGO STATS'),
centerTitle: true,
),
body: ListView.builder(
itemCount: 20,
itemBuilder: (
BuildContext context,
int index,
) {
return Card(
child: Text(
data["playerstats"],
),
);
}),
);
}
}
Error
I/flutter ( 4037): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 4037): The following NoSuchMethodError was thrown building:
I/flutter ( 4037): The method '[]' was called on null.
I/flutter ( 4037): Receiver: null
I/flutter ( 4037): Tried calling: []("playerstats")
I/flutter ( 4037):
I/flutter ( 4037): When the exception was thrown, this was the stack:
What am I doing wrong? Do I need to initialize something?
A: You are making correct http request and getting data too
However the problem lies in your widget , I checked the API response it is throwing a response of Map<String,dynamic>
While displaying the data you are accessing the data using playerstats key which in turn is giving you a Map which is not a String as required by Text Widget in order to display it !
You can display the data by simply converting it to String by using toString() method like this
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CSGO STATS'),
centerTitle: true,
),
body: ListView.builder(
itemCount: 20,
itemBuilder: (
BuildContext context,
int index,
) {
return Card(
child: Text(
data["playerstats"].toString(),
),
);
}),
);
}
Also, I would like to suggest you some Improvements in your Code
*
*Use type annotation as much as possible, It makes your code more safe and robust , Like you have declared data variable as Map data; , You should declare it like Map<String,dynamic> data;
*I think you forget to call super.initState() in your initState() method , Make sure to call it before all your methods.
*Method getData doesn't return anything, So make it as Future<void> instead of Future<String>
Since you are new contributor to StackOverflow , I welcome you !
Happy Fluttering !
A: data["playerstats"] is a Map while the Text widget needs String.
A: Your method is ok, but the problem is in initiating the text widget.
child: Text(
data["playerstats"],
),
['playerstats'] is not a single text, its a map of list. You need to specify the exact text field name you want to see. Still it will show you full data if you add .toString() with the field name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65102105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Decimal String to hexadecimal String I have a String encoded in this kind of format:
223175087923687075112234402528973166755
The decoded string looks like:
a7e5f55e1dbb48b799268e1a6d8618a3
I need to convert from Decimal to Hexadecimal, but the input number is much bigger than the int or long types can handle, so how can I convert this?
A: You can use BigInteger :
BigInteger big = new BigInteger("223175087923687075112234402528973166755");
System.out.println(big.toString(16));
Output :
a7e5f55e1dbb48b799268e1a6d8618a3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34392957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to give PdfReader a HttpPostedFileBase As I see itextsharp's PdfReader object accepts a filename. But I have HttpPostedFileBase in my controller, how can I give HttpPostedFileBase to PdfReader. Here is the code :
public ActionResult Index(HttpPostedFileBase file)
{
PdfReader myReader = new PdfReader(file); // this gives error.
A: Given a HttpPostedFileBase named file, then you could do this:
byte[] pdfbytes = null;
BinaryReader rdr = new BinaryReader(file.InputStream);
pdfbytes = rdr.ReadBytes((int)file.ContentLength);
PdfReader reader = new PdfReader(pdfbytes);
You could, of course, first save the PDF to a file, and then provide the path to that file, but usually, that's not what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43371107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: uniq returns other result than uniq_by Until now I used uniq_by to count unique projectusers. But this method has been deprecated and the suggestion is to use uniq instead. But uniq_by returns 2 (correct!) and uniq returns 3 (not correct). The projectuser table is filled like this:
id,user_id
1,1
2,1
3,2
And here are the statements:
Projectuser.uniq_by {|p| p.user_id}.count --> 2
Projectuser.uniq {|p| p.user_id}.count --> 3
What do I need to change?
A: The ActiveReord-Version of uniq seem to ignore the given block, and just check that the objects are uniq. If you look at the source you see that is just sets a flag.
See
http://apidock.com/rails/ActiveRecord/QueryMethods/uniq
You can think of it as a modifier for the generated sql-statement.
A: The result is rigth, since uniq is from Array. To match the uniqueness in SQL idiom you need to use distinct.
From the example from the documentation:
person.pets.select(:name).distinct
# => [#<Pet name: "Fancy-Fancy">]
Try:
Projectuser.select(:id, :user_id).distinct
A: I have it solved by using:
Projectuser.uniq.pluck(:user_id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19316183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extended CRUD, function formSubmit don't get all form elements? i have a problem, i cannot get values (added with $form->addField) from form in CRUD. I just get what's in the model, but there just isn't extra values...
MODEL:
class Model_Admin extends Model_Table {
public $table ='admin';
function init(){
parent::init();
$this->addField('name')->mandatory('Name required');
$this->addField('email')->mandatory('Email required');
$this->addField('password')->type('password')->mandatory('Password required');
}
}
On page i create extended CRUD and add two more fields:
$adminCRUD = $this->add('MyCRUD');
$adminCRUD->setModel('Admin');
if($adminCRUD->isEditing('add')){
$adminCRUD->form->addField('line','test2','TEST LINE');
$adminCRUD->form->addField('DropDown', 'appfield','Manages Applications')
->setAttr('multiple')
->setModel('Application');
}
Extended CRUD:
class MyRUD extends CRUD {
function formSubmit($form)
{
//var_dump($form);
var_dump($form->get('test2'));
var_dump($form->get('appfield'));
try {
//$form->update();
$self = $this;
$this->api->addHook('pre-render', function () use ($self) {
$self->formSubmitSuccess()->execute();
});
} catch (Exception_ValidityCheck $e) {
$form->displayError($e->getField(), $e->getMessage());
}
}
}
I get null for $form->get('test2') or $form->get('appfield'). I checked whole $form object and there isn't values from test2.. Somwhere in the process gets lost (or droped), how to get it in extended CRUD?
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21066214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Ffmpeg Join Audio files and video I am trying to use the code bellow to join an audio file in the 6th second of my input video file and export all into one new video file but it doesnt run.
<?php
session_start();
$au = $_SESSION['mysound'];
$ffmpeg = "/usr/local/bin/ffmpeg";
$videofile = "video/sample.mp4";
$outputfile = "upload/outputvideo.mp4"; //This folder has full permissions
if (exec("-i $au -itsoffset 6 -i $videofile -acodec copy -vcodec copy $outputfile")){
echo "SUCCESS";
}else{
echo "FAILURE";
}
?>
Any help please?
A: You can try this which this which sets the order of execution during the merge
ffmpeg -i $videofile -itsoffet 6 -i $au -acodec copy -vcodec copy $outputfile -map 0:0 -map 1:0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13542714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to unify regex capture groups in distinct alternative branches? Suppose I have code like this:
import re
rx = re.compile(r'(?:(\w{2}) (\d{2})|(\w{4}) (\d{4}))')
def get_id(s):
g = rx.match(s).groups()
return (
g[0] if g[0] is not None else g[2],
int(g[1] if g[1] is not None else g[3]),
)
print(get_id('AA 12')) # ('AA', 12)
print(get_id('BBBB 1234')) # ('BBBB', 1234)
This does what I want, but it requires me to inspect every capture group in order to check which one actually captured the substring. This can become unwieldy if the number of alternatives is high, so I would rather avoid this.
I tried using named captures, but (?:(P<s>\w{2}) (?P<id>\d{2})|(?P<s>\w{4}) (?P<id>\d{4})) just raises an error.
The trick in the answer to Unify capture groups for multiple cases in regex doesnβt work, as (\w{2}(?= \d{2})|\w{4}(?= \d{4})) (\d{2}|\d{4}) will capture the wrong amount of digits, and for reasons Iβd rather not get into, I cannot hand-optimise the order of alternatives.
Is there a more idiomatic way to write this?
A: It seems there is! From re documentation:
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
the (optional) no pattern otherwise.
Which makes the example this:
rx = re.compile(r'(?P<prefix>(?P<prefix_two>)\w{2}(?= \d{2})|(?P<prefix_four>)\w{4}(?= \d{4})) (?P<digits>(?(prefix_two))\d{2}|(?(prefix_four))\d{4})')
def get_id(s):
m = rx.match(s)
if not m:
return (None, None,)
return m.group('prefix', 'digits')
print(get_id('AA 12')) # ('AA', 12)
print(get_id('BB 1234')) # ('BB', 12)
print(get_id('BBBB 12')) # (None, None)
print(get_id('BBBB 1234')) # ('BBBB', 1234)
Whether itβs worth the trouble, Iβll leave up to the reader.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66437305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Downloading files from multiple directory in one FTP Connection with FTPWebRequest in .NET Is it possible to change the Path of the FTP session once the Session is Open. The reason I want to do this is to avoid to open the multiple FTP connection. The whole purpose is to download the files located in the FTP site in a single FTP connection. For example, in single FTP connection, I want download the contens from all the directory located in the FTP site. Currently, I have project that is failing everyday because It makes multiple connections to the FTP site to download files from different directory . For example, making more than 80 connections in 1 minutes.
What are restrictions of the FTPWebRequest in .NET
A: As per the documentation for FtpWebRequest:
Multiple FtpWebRequests reuse existing
connections, if possible.
Admittedly that does not really tell you much but if you look at the documentation for the ConnectionGroupName property, it tells you that you can specify the same ConnectionGroupName for multiple requests in order to reuse the connection.
Here is more information on managing connections in .NET.
Alternatively, you should be able to use the WebClient class to issue multiple related FTP requests and although I can't say for sure, I would imagine that it would reuse the connection. Unlike FtpWebRequest which can only be used once, WebClient can be used to make multiple requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2264000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: android studio profile no debug app (ram test) Im QA analyst.
Before me there is a task, to find out how much RAM the application consumes. The application is downloaded from Play Market. In the profiler, I do not see this process (no debuggable processes). Is there a way to profile a third-party application?
screen adnroid studio
What I have tried:
*
*adb shell dumpsys meminfo "com. XXX."
Yes, it shows the RAM consumed by the application, but each time to enter this command is not convenient. I would like to see on the chart. Or to write to the log every second.
*
*Third-party application with Play Market, show only the general memory of the device.
Or can you recommend another method or application? I really hope for help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55184714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to allow selection via icon on dropdown I'm using fuelux with bootstrap to create some nice selections via drop downs.
In the drop down I'm placing icons via font-awesome. I've managed to get the icons to render fine and when selected, the icon is included as selected.
My problem is when I click on an icon in an activated drop down. The selection occurs but is set to nothing. I have to click on either the text or white space around the icon on the dropdown list.
Does anyone know how to fix this?
Here is a JS Fiddle that demonstrates the problem:
http://jsfiddle.net/metalskin/xye7zj3n/
The code in the jsfiddle is as follows:
<div class="row">
<div class="col-md-12">
<form class="form-horizontal">
<div class="form-group">
<label class="col-md-4 control-label" for="title">Title</label>
<div class="col-md-6">
<input
id="title"
name="title"
type="text"
placeholder="Enter the title"
class="form-control input-md"/>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="icon">Icon</label>
<div class="col-md-6 fuelux">
<div
class="btn-group selectlist"
data-initialize="selectlist"
id="iconSelectlist">
<button
class="btn btn-default dropdown-toggle"
data-toggle="dropdown"
type="button">
<span class="selected-label">
<a href="#"><i class="fa fa-users fa-lg"></i></a>
</span>
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li data-value="a">
<a href="#"><i class="fa fa-users fa-lg"></i> Users</a>
</li>
<li data-value="b">
<a href="#"><i class="fa fa-camera fa-lg"></i> Camera</a>
</li>
</ul>
<input
class="hidden hidden-field"
name="mySelectlist"
readonly="readonly"
aria-hidden="true"
type="text"/>
</div>
</div>
</div>
</form>
</div>
</div>
CSS:
.container-fluid {
margin-top: 10px;
}
.row {
margin: auto
}
.row.no-pad {
margin-right:0;
margin-left:0;
}
.row.no-pad >[class*='col-'] {
padding-right:0;
padding-left:0;
}
ul.dropdown-menu-form {
color: black;
}
.selected-label {
color: #555;
}
.dropdown-toggle {
border-color: #ccc;
}
.dropdown-toggle:focus {
border-color: #ccc;
}
.dropdown-toggle:hover {
border-color: #ccc;
}
.caret {
color: #333;
}
External resources:
http://exacttarget.github.io/fuelux/assets/vendor/bootstrap/dist/css/bootstrap.min.css
http://exacttarget.github.io/fuelux/assets/vendor/fuelux/dist/css/fuelux.css
http://exacttarget.github.io/fuelux/assets/vendor/bootstrap/dist/js/bootstrap.js
http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css
http://www.fuelcdn.com/fuelux/3.0.2/js/fuelux.min.js
DTD:
HTML 5
Normalised CSS:
true
Body Tag:
<body class="fuelux">
And jQuery 2.x (edge)
A: It's a bug. Previously only the <a> was allowed as a clickable child element. Icon support was a recent addition. Please see issue and pull request, Selectlist is empty when icon is clicked instead of text label This should be merged into master with release 3.0.3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26038920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asp.Net Mvc - RenderAction - Create in a list view EDIT
I put my solution on a share site. Like that you'll be able to see what I'm talking about. You can download it here : http://www.easy-share.com/1909069597/TestRenderAction.zip
To test it, start the project (let the create form empty) and click the Create button. You'll see what happen.
It's only a example project. I don't care to persist my object to the database for now. I care to make my example work.
I got the following controller :
public class ProductController : Controller
{
public ActionResult List()
{
IList<Product> products = new List<Product>();
products.Add(new Product() { Id = 1, Name = "A", Price = 22.3 });
products.Add(new Product() { Id = 2, Name = "B", Price = 11.4 });
products.Add(new Product() { Id = 3, Name = "C", Price = 26.5 });
products.Add(new Product() { Id = 4, Name = "D", Price = 45.0 });
products.Add(new Product() { Id = 5, Name = "E", Price = 87.79 });
return View(products);
}
public ViewResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product)
{
return View(product);
}
}
The following model :
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
My Product/List.aspx :
<h2>List</h2>
<table>
<tr>
<th></th>
<th>
Id
</th>
<th>
Name
</th>
<th>
Price
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
<%= Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%>
</td>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(String.Format("{0:F}", item.Price)) %>
</td>
</tr>
<% } %>
</table>
<p>
<% Html.RenderAction("Create"); %>
</p>
My Product/Create.ascx :
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm("Create", "Product", FormMethod.Post)) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id") %>
<%= Html.ValidationMessage("Id", "*") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name") %>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="Price">Price:</label>
<%= Html.TextBox("Price") %>
<%= Html.ValidationMessage("Price", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
The problem is that when I hit the create button and I got an error (like empty field), the return view only return my Create.ascx control. It's doesn't return the Product/List.asxp page with in my Create.ascx control with the errors. That's what I would like it's does.
Any idea how I can solve that problem ?
I use Asp.Net Mvc 1 with Asp.Net Futures (which have the Html.RenderAction).
A: [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product)
{
...
return View("List");
}
or
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product)
{
...
return RedirectToAction("List", "Product");
}
A: your controller should work like this:
public class ProductController : Controller
{
IList<Product> products;
public ProductController( )
{
products = new List<Product>();
products.Add(new Product() { Id = 1, Name = "A", Price = 22.3 });
products.Add(new Product() { Id = 2, Name = "B", Price = 11.4 });
products.Add(new Product() { Id = 3, Name = "C", Price = 26.5 });
products.Add(new Product() { Id = 4, Name = "D", Price = 45.0 });
products.Add(new Product() { Id = 5, Name = "E", Price = 87.79 });
}
public ActionResult List( )
{
return View(products);
}
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product)
{
products.Add(product);
return View("List", products);
}
}
Additionally, you need to call RenderPartial instead of RenderAction, because otherwise your POST method will be invoked (due to you did a post-command by submitting the form):
<p>
<% Html.RenderPartial("Create"); %>
</p>
This should work, you only need to persist your products list, as it will reset with every postback.
I hope this helped you :)
A: Are the names of your text fields the same as the properties in your Product object?
Does your product object declare it's properties like this;
public string Name {get;set;}
You must have getters and setters on your objects.
EDIT
Wait, are you wanting fields from your list View to be available in the post to your create action? If yes then you need to place the BeginForm at the View level and not the PartialView level.
Only fields contained within the begin form will be posted to your controller.
EDIT 2
Ah, I think I see it now.
In your controller I think you should do a product.IsValid to check first.
But in your html you should also do this;
<%= Html.TextBox("Id", Model.Id) %>
You need to fill in the value for the text box.
Hope this is what you were after.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2113788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: The direction of stack growth and heap growth In some systems, the stack grows in upward direction whereas the heap grows in downward direction and in some systems, the stack grows in downward direction and the heap grows in upward direction. But, Which is the best design ? Are there any programming advantages for any of those two specific designs ? Which is most commonly used and why has it not been standardized to follow a single approach ? Are they helpful/targeted for certain specific scenarios. If yes, what are they ?
A: Heaps only "grow" in a direction in very naive implementations. As Paul R. mentions, the direction a stack grows is defined by the hardware - on Intel CPUs, it always goes toward smaller addresses "i.e. 'Up'"
A: I have read the works of Miro Samek and various other embedded gurus and It seems that they are not in favor of dynamic allocation on embedded systems. That is probably due to complexity and the potential for memory leaks. If you have a project that absolutely can't fail, you will probably want to avoid using Malloc thus the heap will be small. Other non mission critical systems could be just the opposite. I don't think there would be a standard approach.
A: Maybe it is just dependent on the processor: If it supports the stack going upward or downward?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3374421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript: Handle GET Error (document.createElement) I'm trying to 'include' a JS file to my document. It works fine, but when the file is offline, it should set a variable to FALSE. I googled it, but I didn't get it. So I tried it with the try/catch:
try {
var jq = document.createElement('script');
//jq.onload = put;
jq.type = 'text/javascript';
jq.src = 'http://127.0.0.1:9666/jdcheck.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
catch(e) {
console.log('An error has occurred: '+e.message);
jdownloader = false;
}
It just throws me the error
Failed to load resource http://127.0.0.1:9666/jdcheck.js
How is it possible to set the var to FALSE?
Thank you,
Markus
A: You're sort of doing it wrong. When checking if a script source can be loaded, there are built in onload and onerror events, so you don't need try / catch blocks for that, as those are for errors with script execution, not "404 file not found" errors, and the catch part will not be executed by a 404 :
var jq = document.createElement('script');
jq.onload = function() {
// script loaded successfully
}
jq.onerror = function() {
// script error
}
jq.type = 'text/javascript';
jq.src = 'http://127.0.0.1:9666/jdcheck.js';
document.getElementsByTagName('head')[0].appendChild(jq);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19181890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Iterate through Array generating Xls with Axlsx gem I am generating an Excel sheet using Axlsx gem. However two of the fields are arrays of IDs from others models ;
health.source_of_power and **health.service_offered**
@healths.each do |health|
sheet.add_row [District.find(health.district).name,County.find(health.county).name,SubCounty.find(health.sub_county).name,health.name_of_institution,health.money_received,health.date_received,health.use_of_money,health.grade_of_health_center,health.opening_time.strftime("%I:%M %p"),health.closing_time.strftime("%I:%M %p"),health.service_offered,health.other_service_offered,health.male_patients,health.female_patients,health.brick_and_wattle,health.mad_and_wattle,health.other_structures,health.source_of_power,health.other_source_of_power,health.toilet_facilities,health.alternative_disposal,health.separate_toilets,health.running_water,health.alternative_water,health.state_of_water,health.duration_non_functional,health.placenta_pit,health.placental_disposal,health.waste_pit,health.waste_disposal,health.storage_expired_drugs,health.expired_drugs_storage,health.pregnant_mother,health.number_of_beds,health.delivery_beds,health.ambulance,health.status_of_ambulance,health.keep_records,health.number_of_staff,health.medical_staff,health.resident_medical_staff]
end
How can i generate a list of the names of the fields by iterating through the Arrays.
A: I am guessing you want a list of names in one cell. Assuming you have a Employee model that represents the sources of power (change to whatever yours is), just find and map the ids:
Employee.where(id: health.source_of_power).pluck(:name).join(',')
Or, if you have first and last:
Employee.where(id: health.source_of_power).pluck(:first, :last).map {|t| t.join(' ')}.join(', ')
You could get more efficient if you had an indexed hash of employees ahead of time. Then you aren't running a query per row:
employees_by_id = Employee.all.index_by(&:id)
@healths.each do |health|
sources_of_power = employees_by_id.values_at(health.source_of_power).map(&:name)
sheet.add_row [...,sources_of_power,...]
end
You could use scopes and relations on the health object if they were there. Your info is a bit vague.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26775195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I use docker exec when running cronjobs with Docker? I want to run php-fpm in one container and cron in another container. I have doubts about my method to create the container for cron.
At the moment, I just copied the Dockerfile for php-fpm and slightly modified the end of it - installed cron and added CMD ["cron", "-f"]
This works, but it's not very DRY, because I've repeated a lot of code when I copied php-fpm's Dockerfile. If some of my dependencies changes (e.g. I need a new php extension to be installed), I have to do it in two Dockerfiles, not just one.
Recently I saw some people use "docker exec from another container" approach to solve this. Meaning that their cron container is based on docker image and they use docker exec to run a command in another container. That's DRY, however, I often hear people saying that running docker-in-docker is for some reason not very elegant and typically for workarounds only.
What would be the best practice here? Leave Dockerfiles in a not-DRY state, or use docker-in-docker approach?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58457681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using istio as an reverse proxy for external TLS services Istio allows you to route a http request in a VirtualService to an external host provided a ServiceEntry exists. For example:
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
name: httpbin-ext
spec:
hosts:
- httpbin.org
ports:
- number: 80
name: http
protocol: HTTP
resolution: DNS
location: MESH_EXTERNAL
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: httpbin
spec:
hosts:
- httpbin.domain.co
gateways:
- public-gateway.istio-system.svc.cluster.local
- mesh
http:
- match:
- gateways:
- public-gateway.istio-system.svc.cluster.local
port: 443
host: httpbin.domain.co
route:
- destination:
host: httpbin.org
port:
number: 80
However this only allows for a HTTP endpoint - how do I configure the external endpoint to be TLS/HTTPS?
A: This took me hours to work out - so worth sharing I feel.
In order to terminate this service as a TLS, a Destination Rule is required. My final config:
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
name: httpbin-ext
spec:
hosts:
- httpbin.org
ports:
- number: 443
name: https
protocol: HTTPS
resolution: DNS
location: MESH_EXTERNAL
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: httpbin
spec:
hosts:
- httpbin.domain.co
gateways:
- public-gateway.istio-system.svc.cluster.local
- mesh
http:
- match:
- gateways:
- public-gateway.istio-system.svc.cluster.local
port: 443
host: httpbin.domain.co
- gateways:
- public-gateway.istio-system.svc.cluster.local
port: 80
host: httpbin.domain.co
route:
- destination:
host: httpbin.org
port:
number: 443
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: httpbin-org
spec:
host: httpbin.org
trafficPolicy:
loadBalancer:
simple: ROUND_ROBIN
portLevelSettings:
- port:
number: 443
tls:
mode: SIMPLE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62173813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does JBoss 5.1.0 supports hot deployment ? If yes, how can I do it?
I am a beginner in JBoss. I just want to know how to hot deploy my web applications on JBoss 5.1.0.
1. In eclipse.
2. Without Eclipse.
I am using windows XP.
Thanks
A: 1a) For Eclipse you can either configure the usual WebToolsPlatform (WTP) to do hot deployments.
1b) You can install the JBoss Tools from http://www.jboss.org/tools which might some things smoother. You can think of it as an extension of WTP.
1c) Use a small Ant-Skript to do the same as 2)
2) Simply copy your war file into the subdirectory server/default/deploy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7238827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to delete leading zeros in identifier such as "1.2.03.4" Problem is to write sql script to delete leading zeros i MySQL database table in one column which represents identifires (numbers and dots).
I want to update values in db from example "1.2.03.4" to "1.2.3.4"
A: You may try replace for same. It seems like IP address, so you may check any 0 after . need to be removed i,e: .0 replaces with '.' .
select replace ( @str, '.0','.')
A: MySQL 8+ has regexp_replace() which does exactly what you want:
select regexp_replace('1.2.03.00004', '[.]0+', '.')
EDIT:
If you want to replace only the leading zeros on the third value, then you can use substring_index():
select concat_ws('.',
substring_index(col, '.', 2),
substring_index( substring_index(col, '.', 3), '.', -1 ) + 0, -- convert to number
substring_index(col, '.', -1)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57802542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Browse option is not taking Shared Drive or UNC path I am taking the help of this link Folder Selection
but my shared path or any other UNC path is not appearing.
setlocal
set "psCommand="(new-object -COM 'Shell.Application')^.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
setlocal enabledelayedexpansion
echo FolderPath !folder!
pause
endlocal
REM Ending Folder option
if not exist %folder% mkdir %folder%
set robocopy=robocopy /E
echo FolderPath **%folder%** <-- this 'folder' is not taking UNC/Shared path
%robocopy% "MyLocalDrive" %folder% <-- this 'folder'
Any suggestion
A: This is the Docs from https://msdn.microsoft.com/en-us/library/windows/desktop/gg537710(v=vs.85).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
IShellDispatch.BrowseForFolder( _
ByVal Hwnd As Integer, _
ByVal sTitle As BSTR, _
ByVal iOptions As Integer, _
[ ByVal vRootFolder As Variant ] _
) As FOLDER
and these are the flags see BIF_BROWSEINCLUDEURLS and BIF_SHAREABLE
ulFlags
Type: UINT
Flags that specify the options for the dialog box. This member can be 0 or a combination of the following values. Version numbers refer to the minimum version of Shell32.dll required for SHBrowseForFolder to recognize flags added in later releases. See Shell and Common Controls Versions for more information.
BIF_RETURNONLYFSDIRS (0x00000001)
0x00000001. Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
Note The OK button remains enabled for "\\server" items, as well as "\\server\share" and directory items. However, if the user selects a "\\server" item, passing the PIDL returned by SHBrowseForFolder to SHGetPathFromIDList fails.
BIF_DONTGOBELOWDOMAIN (0x00000002)
0x00000002. Do not include network folders below the domain level in the dialog box's tree view control.
BIF_STATUSTEXT (0x00000004)
0x00000004. Include a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box. This flag is not supported when BIF_NEWDIALOGSTYLE is specified.
BIF_RETURNFSANCESTORS (0x00000008)
0x00000008. Only return file system ancestors. An ancestor is a subfolder that is beneath the root folder in the namespace hierarchy. If the user selects an ancestor of the root folder that is not part of the file system, the OK button is grayed.
BIF_EDITBOX (0x00000010)
0x00000010. Version 4.71. Include an edit control in the browse dialog box that allows the user to type the name of an item.
BIF_VALIDATE (0x00000020)
0x00000020. Version 4.71. If the user types an invalid name into the edit box, the browse dialog box calls the application's BrowseCallbackProc with the BFFM_VALIDATEFAILED message. This flag is ignored if BIF_EDITBOX is not specified.
BIF_NEWDIALOGSTYLE (0x00000040)
0x00000040. Version 5.0. Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized. The dialog box has several new capabilities, including: drag-and-drop capability within the dialog box, reordering, shortcut menus, new folders, delete, and other shortcut menu commands.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_NEWDIALOGSTYLE is passed.
BIF_BROWSEINCLUDEURLS (0x00000080)
0x00000080. Version 5.0. The browse dialog box can display URLs. The BIF_USENEWUI and BIF_BROWSEINCLUDEFILES flags must also be set. If any of these three flags are not set, the browser dialog box rejects URLs. Even when these flags are set, the browse dialog box displays URLs only if the folder that contains the selected item supports URLs. When the folder's IShellFolder::GetAttributesOf method is called to request the selected item's attributes, the folder must set the SFGAO_FOLDER attribute flag. Otherwise, the browse dialog box will not display the URL.
BIF_USENEWUI
Version 5.0. Use the new user interface, including an edit box. This flag is equivalent to BIF_EDITBOX | BIF_NEWDIALOGSTYLE.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_USENEWUI is passed.
BIF_UAHINT (0x00000100)
0x00000100. Version 6.0. When combined with BIF_NEWDIALOGSTYLE, adds a usage hint to the dialog box, in place of the edit box. BIF_EDITBOX overrides this flag.
BIF_NONEWFOLDERBUTTON (0x00000200)
0x00000200. Version 6.0. Do not include the New Folder button in the browse dialog box.
BIF_NOTRANSLATETARGETS (0x00000400)
0x00000400. Version 6.0. When the selected item is a shortcut, return the PIDL of the shortcut itself rather than its target.
BIF_BROWSEFORCOMPUTER (0x00001000)
0x00001000. Only return computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER (0x00002000)
0x00002000. Only allow the selection of printers. If the user selects anything other than a printer, the OK button is grayed.
In Windows XP and later systems, the best practice is to use a Windows XP-style dialog, setting the root of the dialog to the Printers and Faxes folder (CSIDL_PRINTERS).
BIF_BROWSEINCLUDEFILES (0x00004000)
0x00004000. Version 4.71. The browse dialog box displays files as well as folders.
BIF_SHAREABLE (0x00008000)
0x00008000. Version 5.0. The browse dialog box can display sharable resources on remote systems. This is intended for applications that want to expose remote shares on a local system. The BIF_NEWDIALOGSTYLE flag must also be set.
BIF_BROWSEFILEJUNCTIONS (0x00010000)
0x00010000. Windows 7 and later. Allow folder junctions such as a library or a compressed file with a .zip file name extension to be browsed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41884121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# check if directory exists in azure storage I am trying to see if a directory exists within azure data storage. This is how I am initializing the service client:
private void InitializeServiceClient(IndesignExportConfiguration exportConfig, String rootContainer)
{//"UseDevelopmentStorage=true"
serviceClient = new BlobServiceClient(exportConfig.BlobConnectionString);
flyersContainerClient = serviceClient.GetBlobContainerClient(rootContainer.ToLower());
}
And this is where I am trying to see if the directory exists:
var rootContainerName = dealNo + "/";
_flyerId = flyerId;
var blobClient = flyersContainerClient.GetBlobClient(rootContainerName);
if (blobClient.Exists())
{
await ListBlobsForPrefixRecursive(flyersContainerClient, rootContainerName, 1);
}
else
{
InitializeServiceClient(_exportConfig, _exportConfig.SecondaryRootContainer);
await ListBlobsForPrefixRecursive(flyersContainerClient, rootContainerName, 1);
}
So far I have asked another question on stackoverflow and I was told that because the directory is virtual my blobclient.exists if statement wont work. I then looked into using the following:
var blobDirectory = flyersContainerClient.GetBlobDirectoryReference("Path_to_dir");
bool directoryExists = blobDirectory.ListBlobs().Count() > 0
and this:
bool directoryExists = flyersContainerClient.ListBlobsWithPrefix("DirectoryA/DirectoryB/").Count() > 0
Unforutnately the methods GetBlobDirectoryReference and ListBlobsWithPrefix dont seem to exist. I can't seem to figure out what I am doing wrong, or which assembly reference I am missing. Any help would be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72521298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Server Socket won't accept() local application handshake in Java I am trying to connect a client application to my code through port 8000 on my pc offline. I am using the ServerSocket library to connect using the below code. The client's application sends XML messages across the port and I need to connect, interpret and respond. (Please bear in mind that I haven't coded interpret/respond yet when reading the below).
Every time I try to send a message from the client application (when running the debug feature in eclipse), the code gets to the serverSocket.accept() method which should be the 'handshake' between client and server and can't go any further. I am unable to change the client application obviously so need to figure out why it's not accepting the connection.
package connect;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class PortListener2 {
public static void main(String[] args){
System.out.println("> Start");
int portNumber = 8000;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: "+inputLine);
out.println(inputLine);
if (inputLine.equals("exit")){
break;
}
}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("Disconnected");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21995288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: urllib cannot read https (Python 3.4.2)
Would anyone be able to help me fetch https pages with urllib? I've spent hours trying to figure this out.
Here's what I'm trying to do (pretty basic):
import urllib.request
url = "".join((baseurl, other_string, midurl, query))
response = urllib.request.urlopen(url)
html = response.read()
Here's my error output when I run it:
File "./script.py", line 124, in <module>
response = urllib.request.urlopen(url)
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.4/urllib/request.py", line 455, in open
response = self._open(req, data)
File "/usr/lib/python3.4/urllib/request.py", line 478, in _open
'unknown_open', req)
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
result = func(*args)
File "/usr/lib/python3.4/urllib/request.py", line 1244, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: 'https>
I've also tried using data=None to no avail:
response = urllib.request.urlopen(url, data=None)
I've also tried this:
import urllib.request, ssl
https_sslv3_handler = urllib.request.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_SSLv3))
opener = urllib.request.build_opener(https_sslv3_handler)
urllib.request.install_opener(opener)
resp = opener.open(url)
html = resp.read().decode('utf-8')
print(html)
A similar error occurs with this^ script, where the error is found on the "resp = ..." line and complains that 'https' is an unknown url type.
Python was compiled with SSL support on my computer (Arch Linux). I've tried reinstalling python3 and openssl a few times, but that doesn't help. I haven't tried to uninstall python completely and then reinstall because I would also need to uninstall a lot of other programs on my computer.
Anyone know what's going on?
-----EDIT-----
I figured it out, thanks to help from Andrew Stevlov's answer. My url had a ":" in it, and I guess urllib didn't like that. I replaced it with "%3A" and now it's working. Thanks so much guys!!!
A: this may help
Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
A: Double check your compilation options, looks like something is wrong with your box.
At least the following code works for me:
from urllib.request import urlopen
resp = urlopen('https://github.com')
print(resp.read())
A: urllib.error.URLError: <urlopen error unknown url type: 'https>
The 'https and not https in the error message indicates that you did not try a http:// request but instead a 'https:// request which of course does not exist. Check how you construct your URL.
A: I had the same error when I tried to open a url with https, but no errors with http.
>>> from urllib.request import urlopen
>>> urlopen('http://google.com')
<http.client.HTTPResponse object at 0xb770252c>
>>> urlopen('https://google.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python3.7/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/usr/local/lib/python3.7/urllib/request.py", line 548, in _open
'unknown_open', req)
File "/usr/local/lib/python3.7/urllib/request.py", line 503, in _call_chain
result = func(*args)
File "/usr/local/lib/python3.7/urllib/request.py", line 1387, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: https>
This was done on Ubuntu 16.04 using Python 3.7. The native Ubuntu defaults to Python 3.5 in /usr/bin and previously I had source downloaded and upgraded to 3.7 in /usr/local/bin. The fact that there was no error for 3.5 pointed to the executable /usr/bin/openssl not being installed correctly in 3.7 which is also evident below:
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/ssl.py", line 98, in <module>
import _ssl # if we can't import it, let the error propagate
ModuleNotFoundError: No module named '_ssl'
By consulting this link, I changed SSL=/usr/local/ssl to SSL=/usr in 3.7 source dir's Modules/Setup.dist and also cp it into Setup and then rebuilt Python 3.7.
$ ./configure
$ make
$ make install
Now it is fixed:
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2g 1 Mar 2016'
>>> urlopen('https://www.google.com')
<http.client.HTTPResponse object at 0xb74c4ecc>
>>> urlopen('https://www.google.com').read()
b'<!doctype html>...
and 3.7 has been complied with OpenSSL support successfully. Note that the Ubuntu command "openssl version" is not complete until you load it into Python.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27208131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to append attribute for object in Mongodb? Example:
user : {
"user_name" : "chicken_01",
"password" : "123456",
"skills" : {
"PHP" : 7.0,
"NodeJs" : 8.0,
"MongoDB" : 8.0
}
}
I want to add "HTML/CSS" : 8.0 to "skills" inner object. What is the proper way to do it?
Thank you!
A: is it like JS? if yes :
var userObj= JSON.parse(user);
userObj.skills.HTMLCSS = 8.0;
user = JSON.stringify(userObj);
A: db.users.update(
{'user_name' : 'chicken_01'},
{'$set' :
{
"skills.HTML/CSS":8.0
}
})
Except with the name of your collection and not db.users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42208882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: General approach to visualize audio file? What is the general programming approach to visualize audio file like this:
(in the middle is the current player position)
By googling I've found it could have something to do with pitch and in Is there a way to change the pitch of audio being played in a flutter app? I've found it could have something to do with sample rate. I'm not a musitian, but I feel the way to achieve this could be to get internal audio pitch or volume for every second.
So if some of these is correct, what could be the general programming approach to get pitch, sample rate, or internal volume for every second of an audio file?
(if you are unfamiliar with Dart, you can use any language you know, I can translate between programming languages quite well: Python, Java, JavaScript, PHP...)
(is there a way to use ffmpeg for this?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57007770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "java.util.NoSuchElementException: Context is empty" Exception while making downstream request using WebClient I am trying to upgrade to spring boot 2.6.6 from 2.2.0.RELEASE. Upon migrating I found that I was getting the below mentioned exception while making downstream calls using webclient. So I started checking with lower versions of spring boot and I found that my implementation is working fine in Spring Boot 2.6.3. But upgrading to spring boot version 2.6.4 I am getting this error.
JDK version: openjdk 17.0.2
Error:
class org.springframework.web.reactive.function.client.WebClientRequestException | Cause : java.util.NoSuchElementException: Context is empty | Exception message : Context is empty; nested exception is java.util.NoSuchElementException: Context is empty | StackTrace : org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
What changed in spring boot 2.6.4 that I am getting this error? And what changes can i make to my code to fix that.
@PostConstruct
public void init() {
webClient = WebClient.create();
}
public Mono<?> postRequest(final String url, final Object request,
final MultiValueMap headers, final MediaType contentType, final MediaType acceptType) {
Mono<?> response;
try {
URI uri = new URI(url);
long webClientStartTime = System.currentTimeMillis();
response = webClient.post().uri(uri)
.contentType(contentType)
.headers(httpHeaders -> {
if (Objects.nonNull(headers)) {
httpHeaders.addAll(headers);
}
})
.bodyValue(request)
.accept(acceptType)
.exchangeToMono(clientResponse -> {
log.info("clientResponse.statusCode(): {}, path: {}, webClient latency: {}",
clientResponse.statusCode(), uri.getPath(), System.currentTimeMillis() - webClientStartTime);
if (!clientResponse.statusCode().is2xxSuccessful()) {
return Mono.error(new BaseException("Not success response received from downstream. HttpCode: " + clientResponse.statusCode()));
}
return clientResponse.bodyToMono(String.class);
})
.timeout(Duration.ofMillis(500))
.doOnError(throwable -> log.error("clientResponse error: {}, path: {}, webclient latency: {}",
throwable, uri.getPath(), System.currentTimeMillis() - webClientStartTime));
return response;
} catch (Exception ex) {
log.error("Some exception while processing post request. Error: {}", ex.getMessage());
}
return null;
}
A: As suggested by @VioletaGeorgieva, upgrading to Spring boot 2.6.8 has fixed the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72346277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: laravel: how to remove first pagination when click next page of 2nd pagination i have index page with two pagination passing to. first i gave to slide to show featured items and then there is other items after that slider coming through 2nd pagination. but when i click next page. the first pagination items doesn't show but the header of that div remains. my question is what i can do to remove that whole div of slider of featured items on any other page than index page and page after ?page=1 at url. i tried to put if condition but when there is not get value at url it give me error. is there any solution that can hide whole slider div on any other page than 1 and simple index.
class IndexController extends Controller
{
public function Index(){
//Get all Products
$allProducts = DB::table('categories')
->join('products','products.category_id','=', 'categories.id')
->where('categories.status','=','1')->where('products.status','=','1')->paginate(9);
// Get featured products
$featuredProducts = DB::table('categories')
->join('products','products.category_id','=', 'categories.id')
->where('categories.status','=','1')->where('products.status','=','1')->where('feature_item',1)->paginate(25);
//Get all Categories and sub Categories
$categories = Category::with('categories')->where(['parent_id'=>0])->get();
$banners = Banner::where('status','1')->get();
return view('index')->with(compact('featuredProducts','allProducts','categories','banners'));
}
}
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
@include('layouts.frontLayout.front_sidebar')
</div>
<div class="col-sm-9 padding-right">
<div class="features_items">
<h2 class="title text-center">Featured Items</h2>
<div id="recommended-item-carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<?php $count=1; ?>
@foreach($featuredProducts->chunk(3) as $chunk)
<div <?php if($count==1){ ?> class="item active" <?php }else{ ?> class="item" <?php } ?>>
@foreach($chunk as $item)
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img style="width:200px;" src="{{ asset('images/backend_images/products/small/'.$item->image) }}" alt="" />
<h2>$ {{ $item->price }} </h2>
<p> {{ $item->product_name }}</p>
<a href="{{ url('/product/'.$item->id) }}">
<button type="button" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</button>
</a>
</div>
</div>
</div>
</div>
@endforeach
</div>
<?php $count++; ?>
@endforeach
</div>
<a class="left recommended-item-control" href="#recommended-item-carousel" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a class="right recommended-item-control" href="#recommended-item-carousel" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3">
</div>
<div class="col-sm-9 padding-right">
<div class="features_items"><!--features_items-->
<h2 class="title text-center">All Items</h2>
@foreach($allProducts as $product)
<div class="col-sm-4">
<a class="product-image-wrapper" href="{{ url('product/'.$product->id) }}">
<div class="single-products">
<div class="productinfo text-center">
<img src="{{ asset('images/backend_images/products/small/'.$product->image) }}" alt="" />
<h2>C$ {{ $product->price }}</h2>
<p>{{ $product->product_name }}</p>
<a href="{{ url('product/'.$product->id) }}" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>
</a>
</div>
@endforeach
</div><!--features_items-->
<div align="center">{{ $allProducts->links() }}</div>
</div>
</div>
</div>
</section>
A: You can use request()->getQueryString() to check against the query parameters.
@if (!str_contains(request()->getQueryString(), 'page')) || (str_contains(request()->getQueryString(), 'page=1'))
// show pagination only if page is 1 or there is no page param
@endif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59513174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a preferred or built-in way to partition arrays? Given an array and the number of almost equally sized parts that you want it divided into, is there a preferred way of doing so or a built-in that will handle the task? Two example implementations are given below, but someone may know a better method of getting the job done. The code should primarily be designed to array-like objects but could optionally be applicable if given an iterable instead.
Example 1
def partition(array, parts):
"""Takes an array and splits it into roughly equally sized parts."""
array_size = len(array)
part_size = math.ceil(array_size / parts)
for offset in range(0, array_size, part_size):
yield array[offset:offset + part_size]
Example 2
def partition(array, parts):
"""Takes an array and splits it into roughly equally sized parts."""
size = math.ceil(len(array) / parts)
for stop, start in enumerate(range(parts), 1):
yield array[start * size:stop * size]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40896981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vuex-Persistedstate run mutation on reload I'm using Nuxt 2, Vue 2, Vuex 3, Vuetify 2, vuex-persistedstate 4 and nuxt-i18n 6.
I set this plugin to persiste my Vuex state which is containing RTL status and language code:
plugins/persistedState.client.js:
import createPersistedState from 'vuex-persistedstate'
export default ({ store, req, vuetify, $vuetify }) => {
createPersistedState({
paths: [
'app.isRTL',
'app.langCode'
]
})(store)
}
Also, I write some mutaion to save this settings in state and apply theme to vuetify:
store/app/index.js:
export default {
namespaced: true,
state: {
isRTL: false,
langCode: 'en'
},
mutations: {
setRTL: function (state, isRTL) {
this.app.vuetify.framework.rtl = isRTL
state.isRTL = isRTL
},
setLangCode: function (state, langCode) {
this.app.vuetify.framework.lang.current = langCode
state.langCode = langCode
},
}
}
*
*by calling the setLangCode mutation, the language will be set to given language and save that in the sate
*by calling setRTL rtl direction of vuetify will set correctly and save that in the sate
Theproblem is that on page reload vuex-persistedstate will restore the vuex state from local storage but the mutaion that sets the vuetify settings won't get called, so the vuetify will stay on the worng direction.
Also, the nuxt-i18n will detect the language code from the url not from the state and translates the page base on that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67660653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Key-Value pair functionality inside a C# array I am trying to get a 'multidimensional' jagged array working for my major data-transform work. I want the innermost array to have the key-value pair behavior of an object, But I don't know what syntax to use:
object[][][] courseData = new object[][][]
{
new object[][]//chapter 1
{
new object[]
{
{id = 1, question = "question", answer = "answer"},
//this one?
(id = 2, question = "question", answer = "answer"),
//or this one?
}
}
}
Much of this syntax is new to me, so please let me know what other errors I have made.
If key-value pairs in arrays are impossible, I will have to use unnamed index references, right? that would use () on build and [0] as reference, yes? Can this array even hold mixed data types outside the object?
ps: an example of a function that will be doing work on this data:
function mapOrder (array, order, key) {
array.sort( function (a, b) {
var A = a[key], B = b[key];
if (order.indexOf(A) > order.indexOf(B)) {
return 1;
} else {
return -1;
}
});
return array;
};
reordered_array_a = mapOrder(courseData[0][0], orderTemplateSimple[0], id);
Where orderTemplateSample[index] is an array of numbers used to transform the order of the 'extracted' array from courseData.
I want to have the id key reference there, but if I have to replace it with a number that would theoretically work?
A: Let's start from the inmost type, that is
{id = 1, question = "question", answer = "answer"},
it can't be a key value pair since it has three properties: id, question, answer.
However, you can turn it into named tuple
(int id, string question, string answer)
The declaration will be
(int id, string question, string answer)[][][] courseData =
new (int, string, string)[][][]
{
new (int, string, string)[][]//chapter 1
{
new (int, string, string)[]
{
// Long form
(id : 1, question : "question", answer : "answer"),
// Short form: we can skip id, question, answer names
(2, "question", "answer"),
}
}
};
Now you have an array (array of array of array to be exact):
int course = 1;
int chapter = 1;
int question = 2;
// - 1 since arrays are zero based
string mySecondAnswer = courseData[course - 1][chapter - 1][question - 1].answer;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65715754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Docker container failing to start with connection to database from shinyproxy I want to connect an individual app within shiny proxy to a docker network.
I have a few apps on shinyproxy, only one needs to connect to the database.
It is a postgresql DB running on the same machine in a docker set up to receive connections though the network my-docker-network
In application.yml Should I use
container-network: my-docker-network
or
container-network-connections: ["my-docker-network"]
?
Even though I donβt need internal networks in shiny proxy do I still need to set ``internal-networking: trueunderdocker:```
At the moment the container isnβt starting, but as the container runs fine by itself using docker run --net my-docker-network --env-file /mypath/.Renviron my_app_image it seems to be a connection issue. The container also works if I run it with --network="host"
I've tried various options of putting the .Renviron in different places and don't think that is the issue.
Full dockerfile (other apps deleted and pseudonomised):
FROM rocker/r-ver:3.6.3
RUN apt-get update --allow-releaseinfo-change && apt-get install -y \
lbzip2 \
libfftw3-dev \
libgdal-dev \
libgeos-dev \
libgsl0-dev \
libgl1-mesa-dev \
libglu1-mesa-dev \
libhdf4-alt-dev \
libhdf5-dev \
libjq-dev \
liblwgeom-dev \
libpq-dev \
libproj-dev \
libprotobuf-dev \
libnetcdf-dev \
libsqlite3-dev \
libssl-dev \
libudunits2-dev \
netcdf-bin \
postgis \
protobuf-compiler \
sqlite3 \
tk-dev \
unixodbc-dev \
libssh2-1-dev \
r-cran-v8 \
libv8-dev \
net-tools \
libsqlite3-dev \
libxml2-dev
#for whatever reason it wasn't working
#RUN export ADD=shiny && bash /etc/cont-init.d/add
#install packages
RUN R -e "install.packages(c('somepackages'))"
#copy app script and variables into docker
RUN mkdir /home/app
COPY .Renviron /home/app/
COPY global.R /home/app/
COPY ui.R /home/app/
COPY server.R /home/app/
COPY Rprofile.site /usr/lib/R/etc/
#add run script
CMD ["R", "-e", "shiny::runApp('home/app')"]
Useful parts of the application.yml
At the moment I always get "500/container doesn't respond/run" on the shinyproxy side even though it runs on the standalone.
proxy:
title: apps - page
# logo-url: https://link/to/your/logo.png
landing-page: /
favicon-path: favicon.ico
heartbeat-rate: 10000
heartbeat-timeout: 60000
container-wait-time: 40000
port: 8080
authentication: simple
admin-groups: admins
container-log-path: /etc/shinyproxy/logs
# Example: 'simple' authentication configuration
users:
- name: admin
password: password
groups: admins
- name: user
password: password
groups: users
# Docker configuration
docker:
cert-path: /home/none
url: http://localhost:2375
port-range-start: 20000
# internal-networking: true
specs:
- id: 06_rshiny_dashboard_r_ver
display-name: app r_ver container r_app_r_ver
description: using simple rver set up docker and the r_app_r_ver image
container-cmd: ["R", "-e", "shinyrunApp('/home/app')"]
#container-cmd: ["R", "-e", "shiny::runApp('/home/app', shiny.port = 3838, shiny.host = '0.0.0.0')"]
container-image: asela_r_app_r_ver:latest
#container-network: my-docker-network
container-network-connections: [ "my-docker-network" ]
container-env-file: /home/app/.Renviron
access-groups: [admins]
logging:
file:
name: /etc/shinyproxy/shinyproxy.log
Various commented out lines show the current set up but have tried with/without
A: Fixed it by using a shiny server version of the docker - not sure why but this sorted out some connection issue.
Dockerfile:
FROM rocker/r-ver:3.6.3
RUN apt-get update --allow-releaseinfo-change && apt-get install -y \
lbzip2 \
libfftw3-dev \
libgdal-dev \
libgeos-dev \
libgsl0-dev \
libgl1-mesa-dev \
libglu1-mesa-dev \
libhdf4-alt-dev \
libhdf5-dev \
libjq-dev \
liblwgeom-dev \
libpq-dev \
libproj-dev \
libprotobuf-dev \
libnetcdf-dev \
libsqlite3-dev \
libssl-dev \
libudunits2-dev \
netcdf-bin \
postgis \
protobuf-compiler \
sqlite3 \
tk-dev \
unixodbc-dev \
libssh2-1-dev \
r-cran-v8 \
libv8-dev \
net-tools \
libsqlite3-dev \
libxml2-dev \
wget \
gdebi
##No version control
#then install shiny
RUN wget --no-verbose https://download3.rstudio.org/ubuntu-14.04/x86_64/VERSION -O "version.txt" && \
VERSION=$(cat version.txt) && \
wget --no-verbose "https://download3.rstudio.org/ubuntu-14.04/x86_64/shiny-server-$VERSION-amd64.deb" -O ss-latest.deb && \
gdebi -n ss-latest.deb && \
rm -f version.txt ss-latest.deb
#install packages
RUN R -e "install.packages(c('xtable', 'stringr', 'glue', 'data.table', 'pool', 'RPostgres', 'palettetown', 'deckgl', 'sf', 'shinyWidgets', 'shiny', 'stats', 'graphics', 'grDevices', 'datasets', 'utils', 'methods', 'base'))"
##No version control over
##with version control and renv.lock file
##With version control over
#copy shiny server config over
COPY shiny-server.conf /etc/shiny-server/shiny-server.conf
#avoid some errors
#already in there
#RUN echo 'sanitize_errors off;disable_protocols xdr-streaming xhr-streaming iframe-eventsource iframe-htmlfile;' >> /etc/shiny-server/shiny-server.conf
# copy the app to the image
COPY .Renviron /srv/shiny-server/
COPY global.R /srv/shiny-server/
COPY server.R /srv/shiny-server/
COPY ui.R /srv/shiny-server/
# select port
EXPOSE 3838
# Copy further configuration files into the Docker image
COPY shiny-server.sh /usr/bin/shiny-server.sh
RUN ["chmod", "+x", "/usr/bin/shiny-server.sh"]
# run app
CMD ["/usr/bin/shiny-server.sh"]
application.yml:
proxy:
title: apps - page
# logo-url: https://link/to/your/logo.png
landing-page: /
favicon-path: favicon.ico
heartbeat-rate: 10000
heartbeat-timeout: 60000
container-wait-time: 40000
port: 8080
authentication: simple
admin-groups: admins
container-log-path: /etc/shinyproxy/logs
# Example: 'simple' authentication configuration
users:
- name: admin
password: password
groups: admins
- name: user
password: password
groups: users
# Docker configuration
docker:
cert-path: /home/none
url: http://localhost:2375
port-range-start: 20000
# internal-networking: true
- id: 10_asela_rshiny_shinyserv
display-name: ASELA Dash internal shiny server version
description: container has own shinyserver within it functions on docker network only not on host container-network version
container-cmd: ["/usr/bin/shiny-server.sh"]
access-groups: [admins]
container-image: asela_r_app_shinyserv_ver:latest
container-network: asela-docker-net
logging:
file:
name: /etc/shinyproxy/shinyproxy.log
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71586814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configure ODBC drivers in Linux I've followed all the steps from this link:
https://code.google.com/p/pypyodbc/wiki/Linux_ODBC_in_3_steps
But I'm still getting this error:
[unixODBC][Driver Manager] Data source name not found, and no default
driver specified
Then when I started researching more, I found this:
https://askubuntu.com/questions/167491/connecting-ms-sql-using-freetds-and-unixodbc-isql-no-default-driver-specified
Now it says to modify odbc.ini file to include the server and database name.
But if I'm trying to connect to multiple servers at the same time, how should I configure odbc.ini file in this case?
Also - in my database connection string, should I enter the driver name as {SQL Server} or {FreeTDS}?
A: Here's an example set up with FreeTDS, unixODBC, and friends:
freetds.conf:
[server1]
host = one.server.com
port = 1433
tds version = 7.3
[server2]
host = two.server.com
port = 1433
tds version = 7.3
odbc.ini:
[server1]
Driver = FreeTDS
Server = one.server.com
Port = 1433
TDS_Version = 7.3
[server2]
Driver = FreeTDS
Server = two.server.com
Port = 1433
TDS_Version = 7.3
odbcinst.ini:
[FreeTDS]
Description = FreeTDS with Protocol up to 7.3
Driver = /usr/lib64/libtdsodbc.so.0
The Driver = location may differ above, depending on your distro of FreeTDS.
pyodbc connect, DSN free:
DRIVER={FreeTDS};SERVER=one.server.com;PORT=1433;DATABASE=dbname;UID=dbuser;PWD=dbpassword;TDS_Version=7.3;
A few notes:
*
*You'll have to update the TDS version to match the version of SQL Server you are running and the Free TDS version you are running. Version 0.95 supports TDS Version 7.3.
*TDS Version 7.3 will work with MS SQL Server 2008 and above.
*Use TDS Version 7.2 for MS SQL Server 2005.
See here for more:
https://msdn.microsoft.com/en-us/library/dd339982.aspx
Good luck.
A:
if I'm trying to connect to multiple servers at the same time, how should I configure odbc.ini file in this case?
If you want to connect to more than one server you will need to create a separate DSN entry for each one and use more than one pyodbc connection object. Either that, or set up a "Linked Server" on one of the SQL Server instances so you can access both through the same pyodbc connection.
in my database connection string, should I enter the driver name as {SQL Server} or {FreeTDS}?
If you are editing "odbc.ini" then you are creating DSN entries. You would use the DSN name in your connection string, and pyodbc would get the details (server name, database name) from the corresponding entry in "odbc.ini".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33025765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery/JS Select Array Element where element contains n? Got myself all confused here.
I've got a string bellow, which I'm using .split to form an array.
1:new bubble:143:753:3:rgba(65,146,160,0.7)|2:new bubble:370:949:3:rgba(174,76,221,0.7)|3:new bubble:557:940:3:rgba(55,33,11,0.7)|4:new bubble:494:1170:3:rgba(61,68,191,0.7)|5:new bubble:431:736:3:rgba(233,54,149,0.7)|6:new bubble:236:836:3:rgba(14,133,141,0.7)|
the string contains what I've called "bubbles" each bubble is split up by | so you can see there are 6 bubbles (and a blank one)
I then use .split again this time using : as the split. so I effectively have an array which can load into variables;
Array
bubble[0]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[1]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[2]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[3]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[4]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[5]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
bubble[6]{
id = bubbleinfo[0],
name = bubbleinfo[1],
posx = bubbleinfo[2],
posy = bubbleinfo[3],
priority = bubbleinfo[4],
color = bubbleinfo[5]
}
so that's basically how they form. i assuming anyway.
my issue is however i need to be able to update name, posx, posy, priority and colour by selecting the second array dimension's "id"
so psudo code would be something like
foreach bubble[i]
do
if ID = $_post[ID]
get element 3 - replace new value
get element 2 - replace new value
i++
does anybody understand me? if you do then please could you help me with it. as i've no idea how to structure the function to do this.
thanks
Owen
A: jQuery.each could do this for you if I'm understanding your question correctly:-
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
You can find more info here: http://api.jquery.com/jQuery.each/
a clearer example:
var idYouAreLookingFor=2;
$.each(bubble, function(index, value) {
if(value.id==idYouAreLookingFor)
{
value.name='test';
//profit.
}
});
A: Here is my suggestion:
Use JSON as storage format. Now, I don't know which value is which, but here is an example for JSON encoded data:
[{"posx": 143,"posy": 753,"priority": 3, "color": "rgba(65,146,160,0.7)"}, ...]
You can then use JSON.parse [MDN] to create a JavaScript object from this data, which will look like this:
// var obj = JSON.parse(json); is the same as:
var obj = [
{
posx: 143,
posy: 753,
priority: 3,
color: "rgba(65,146,160,0.7)"
},
...
];
It also seems that the IDs of your "bubbles" are continuous, 1-based. If you make them zero-based, you don't have to store them explicitly. The ID would be the index in the array.
Then you can change the values like so:
obj[id].posx = newvalue;
obj[id].posy = another_newvalue;
and afterwards serialize the the whole array with JSON.stringify [MDN]:
var json = JSON.stringify(obj);
and store it in the cookie.
JSON is available for older browser with json2.js.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7882243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Updating document in firestore causes infinite loop So I am trying to update a document in firestore and I do this in a .forEachand when I execute the update it causes an infinite loop. Can someone look at my code and tell me how to stop this? I figure it would just run one time since the snapshot size is only 1.
this.categoriesCollection.ref.where('name', '==',
transaction.category.toLowerCase()).limit(1).onSnapshot((querySnapshot) =>
{
if (querySnapshot.size == 1) {
querySnapshot.forEach((doc) => {
this.categoriesCollection.doc(doc.id)
.update({totalSpent: doc.data().totalSpent + transaction.amount});
});
}
});
A: You're adding a listener to search query that returns one document, then you're making changes to that document. When that document is changed, the results of the query change, and your listener is invoked again with the new results, which means it's going to update yet another document, which means that the query changes. Etc, etc.
If you just want to update a document from a query, don't use onSnapshot() for that. Just use get() to obtain the search results a single time, then update the documents from the results it gives you.
A: I figured it out all I had to do is set the whole thing equal to a variable and then at the end of the closure just call unsubscribe(); and that stopped the loop. So my code is now:
let unsubscribe = this.categoriesCollection.ref.where('name', '==', transaction.category.toLowerCase()).limit(1).onSnapshot((querySnapshot) => {
if (querySnapshot.size == 1) {
querySnapshot.forEach((doc) => {
this.categoriesCollection.doc(doc.id).update({totalSpent: doc.data().totalSpent + transaction.amount});
});
}
});
unsubscribe();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50979333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Laravel Eloquent sql statement after exist check is limited to 1 I've found a really weird behaviour in the current laravel 4.2 patch. Until now whenever I want to get some datas from my eloquent model I check if results are available before i get them via the following code example:
$foo = $model->hasManyRelationFunction();
if($foo->exists())
foreach($foo->get() as $elem)
....
this results in the following sql statement:
select count(*) as aggregate from "vendor_tabs" where "vendor_tabs"."vendor_id" = '80' limit 1 <-- exist() ?
following by the real select sql statement without Limit 1, for example:
select * from "vendor_tabs" where "vendor_tabs"."vendor_id" = '80' order by "id" asc
Since i've updated laravel 4.2 to the current patch, it also limits the real sql statement to 1
`select * from "vendor_tabs" where "vendor_tabs"."vendor_id" = '80' order by "id" asc` limit 1
but ONLY when I make the if($foo->exists()) check. As soon i comment out the exist condition everything works fine. Are their any informations about this behaviour or am I just stupid? :D
Edit: It seems like they made the eloquent builder "more fluent" in patch 4.2.13. I still dont know if this is a bug or a feature, imo this shouldnt be the normal behaviour.
/**
* Determine if any rows exist for the current query.
*
* @return bool
*/
public function exists()
{
$limit = $this->limit;
$result = $this->limit(1)->count() > 0;
$this->limit($limit);
return $result;
}
A: In fact you don't need to check existence. You should only do:
foreach ($model->hasManyRelationFunction as $elem) {
// do whathever you want
}
and it's just enough to get the data. You don't need to check existence here or if you think you do, you should show a real example of a code what you are trying to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28629685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ANT Ivy generating a vulnerability report for dependent libraries Using ANT Ivy library to manage dependencies for a java application...
Is there any ANT task, or any code suggestions for generating a vulnerability audit / report for our dependent libraries during our autobuilds?
Here is an example (most dependencies removed for brevity) out our dependencies.xml
<ivy-module version="2.0">
<info organisation="com.yamaha" module="YDS" />
<configurations defaultconfmapping="compile->default;sources;javadoc">
<conf name="compile" description="Required to compile application"/>
<conf name="sources" description="Source jars"/>
<conf name="javadoc" description="Javadoc jars"/>
<conf name="runtime" description="Additional run-time dependencies" extends="compile"/>
<conf name="test" description="Required for test only" extends="runtime"/>
</configurations>
<dependencies>
<dependency org="commons-collections" name="commons-collections" rev="[3.2,3.2.+]"/>
<dependency org="commons-beanutils" name="commons-beanutils" rev="1.9.+"/>
</dependencies>
Here is our ant code for retreiving dependencies:
<ivy:retrieve file="dependencyFile.xml" type="bundle, jar" sync="true"/>
We would simply like to add some ANT code that will list any vulnerabilities in the dependency.xml file?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75388198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why is "hibernate.ejb.event.flush" required in spring persistence.xml In my persistence.xml, I have
<property name="hibernate.ejb.event.flush" value="xxx.persistence.hibernate.PatchedDefaultFlushEventListener"/>
What is the role of that property in persistence.xml? What does it mean?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28910044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update a item from a list width Backbone.js I've started using Backbone.js and i have an issue with the updating of html elements.
This is my code:
Router:
App.Routers.Test = Backbone.Router.extend({
routes: {
"/start" : "start",
"/modify" : "modify"
},
start: function() {
this.List = new App.Collections.Test;
this.ViewList = new App.Views.Test({model: this.List});
this.List.fetch();
},
modify: function() {
var model = this.List.get(1);
model.set({name: 'Item modified'});
alert('Modified!');
}
});
Views:
App.Views.Item = Backbone.View.extend({
inizialize: function() {
this.model.bind('change:name',this.render);
},
render: function() {
$('#tmpl').tmpl(this.model.attributes).appendTo(this.el); // jQuery Template
return this;
}
});
App.Views.Test = Backbone.View.extend({
el: '#list',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('reset', this.render);
},
render: function() {
$(this.el).empty();
this.model.each(function(model) {
var viewItem = new App.Views.Item({model: model});
$('#list').append((viewItem.render().el));
});
}
});
When I go to "#/modify" the Model has changed, but this not updated on the html view, although I have added in the item views this code:
this.model.bind('change:name',this.render);
Maybe I didn't understand the correct functioning of backbone, how to behave?
PS: Since I'm new on backbone, is accept any advice.
A: In your modify method, call the appropriate view. I usually pass an instance of the model and el. So, for example:
this.modifyPage = new App.Views.Test({
el: $('#list'),
model: model
});
Though, if you don't need the el as context from the router, it's best to limit the use of jQuery to only the views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7025895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transactional annotation slows down the performance than HibernateDAOSupport I am exporting a report in my code, I am using HibernateDAOSupport and the method is not annotated with @Transactional. So when the request comes from the UI then automatically Transaction is created and the report is exported in 2 mins.
But when I try to use thread, so I had to put annotation @Transactional, otherwise I get an error of LazyInitialization as no Transcaction is present.
So when I put @Transactional then the same report takes time 2.4 mins. This time keeps increasing and sometimes it take double of the time without @Transactional
I am not sure why it takes time when I put annotation @Transactional
The main class:
CommonDAO
public class CommonDAO extends HibernateDaoSupport
private HibernateTransactionManager txnManager;
public void setTxnManager(HibernateTransactionManager txnManager) {
this.txnManager = txnManager;
}
public List executeSQLQueryPaging(final String hql,
final Object[] params, final Integer[] pagingParam) throws ServiceException {
List results = null;
results = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult(pagingParam[0]);
query.setMaxResults(pagingParam[1]);
return query.list();
}
});
return results;
}
ModuleDAO extends CommonDAO
public List getReportData{
executeSQLQueryPaging();
...
return list}
Service
public List getReportData(){
.....
return ModuleDAO.getReportData();
}
If I put @Transactional at service layer then the performance detriorates, or else it is faster if executed from web.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59026628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sql database versus document database? Small introduction:
*
*I've tried to develop my project with sql database, entity framework, linq.
I have table 'Users' and for example i have list of user educations. I ask myself: 'How much educations user can have? 1, 2, 10...' ? And seems at 99% of cases not more than 10. So for such example in sql i need to create referenced table 'Educations'. Right? If i need to display user educations and user i need to join above mentioned tables... But what if user have 10 or even more collections with not more than 10 items in each? I need to create 10 referenced tables in sql? And than join all of them when i need to display? For better performance i've created denormized tables with shape of data that i need to show on ui. And every time when user was updated, i need to update denormilized structure.
*Now i redeveloped my project to use document database(MongoDB). And i've created one document for User with all 10 collections inside.
May be i've lost something? But seems document database win here. It's very fast and very easy to support. +1 to document database.
So, what is your opinion about what better to use document database or sql database?
When I should use document database and when sql?
A: This article has suggestions on when to use NoSQL DB's. Also this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4482972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to find out the out the lowest date for each integration_id group where the name column is approved? id | integration_id | date | name
(1, 1, 2021-04-14 18:04:18.167+05:30, approved)
(2, 1, 2021-04-15 18:04:18.167+05:30, approved)
(3, 2, 2021-04-16 18:04:18.167+05:30, not approved)
(4, 2, 2021-04-17 18:04:18.167+05:30, approved)
If there are multiple integration_ids like these and we need to choose only the approved rows, how do I write a query to fetch the minimum date rows from each integration id group in postgresql.
id | integration_id | date | name
(1, 1, 2021-04-14 18:04:18.167+05:30, approved)
(4, 2, 2021-04-17 18:04:18.167+05:30, approved)
This should be my final answer.
A: On Postgres, DISTINCT ON comes in handy here:
SELECT DISTINCT ON (integration_id) *
FROM yourTable
WHERE name = 'approved'
ORDER BY integration_id, date;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69161038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel Formula: Count Matches Where 2 IDs have a Common Tag I'm trying to figure out the most efficient way to do this in one cell's formula and would appreciate some assistance.
SHEET1
ID TAG
123 Flowers
123 Sports
135 Sports
456 Flowers
456 Cars
123 Clouds
456 Sports
SHEET2
ID1 ID2 RESULT
123 456 2 [WANT TO CALCULATE THIS]
135 246 0 [WANT TO CALCULATE THIS]
The way the formula should work is look in SHEET1 where both ID1 and ID2 have a tag in common and count them.
A: Here's one approach which should work for you.
Setup assumed:
Sheet1 data is in range A1:B8
Sheet2 data is in range A1:B3
Then formula that you should insert in Sheet2!C2 shall be:
=SUM((FREQUENCY(IFERROR(MATCH(IF(Sheet1!$A$1:$A$8=Sheet2!A2,Sheet1!$B$1:$B$8,"z"),IF(Sheet1!$A$1:$A$8=Sheet2!B2,Sheet1!$B$1:$B$8,"a"),0),"a"),IFERROR(MATCH(IF(Sheet1!$A$1:$A$8=Sheet2!A2,Sheet1!$B$1:$B$8,"z"),IF(Sheet1!$A$1:$A$8=Sheet2!B2,Sheet1!$B$1:$B$8,"a"),0),"b"))>0)+0)
NOTE: This is an array formula and shall be inserted by committing CTRL+SHIFT+ENTER and not just ENTER. If entered correctly, Excel put {} braces around it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48001096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Geolocation Total Distance using Array I've been trying to do this for a few days but have yet to get anywhere.
This is for a hybrid app i'm building using Phonegap Build.
I am trying to get my geolocation app to work out distance travelled. So far I have it so it returns a value between A and B, but I need it to work it out when the current location updates (watch location) so it iterates instead, so if I went in a circle 10 times it wouldn't just be the radius of the circle.
This is what I have so far...
Please excuse the code, i'm relatively new to Javascript and struggle with understanding parameters and returns fully.
Starting Latitude: <span id="starting_lat">0</span><br>
Starting Longitude: <span id="starting_long">0</span><br>
Current Latitude: <span id="current_lat">0</span><br>
Current Longitude: <span id="current_long">0</span><br>
Speed: <span id="speed">0</span><br>
My Distance: <span id="myDistance">0</span><br>
<script>
var startingLat;
var startingLong;
var currentLat;
var currentLong;
startApp(); //Start the Application
function startApp() {
getStartingPosition(); //Get my starting position
startTracking(); // Start watching the location
}
function getStartingPosition(){
var getStartingLocation = function(position) {
startingLat=position.coords.latitude;
startingLong=position.coords.longitude;
document.getElementById('starting_lat').innerHTML=(startingLat);
document.getElementById('starting_long').innerHTML=(startingLong);
};
// onError Callback receives a PositionError object
//
function displayError(frror) {
alert('code: ' + frror.code + '\n' +
'message: ' + frror.message + '\n');
}
navigator.geolocation.getCurrentPosition(getStartingLocation, displayError);
}
function startTracking(){
function onSuccess(position) {
currentLat=position.coords.latitude;
currentLong=position.coords.longitude;
document.getElementById('current_lat').innerHTML=(currentLat);
document.getElementById('current_long').innerHTML=(currentLong);
getDistance()
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
}
// Take the starting longitude and latitude, along with current latitude and longitude to work out the distance and output it to the myDistance div.
function getDistance(){
var lat1 = startingLat;
var lon1 = startingLong;
var lat2 = currentLat;
var lon2 = currentLong;
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
d=d.toFixed(2);
document.getElementById('myDistance').innerHTML=(d);
function deg2rad(deg) {
return deg * (Math.PI/180)
}
}
</script>
I have tried using another example on here to add in distance with an array but the structure was slightly different to what i've done so i found it confusing. Can anyone recommend a simple method to applying an array that iterates distance?
Just to mention again, this is for a mobile app using Phonegap Build.
Thank you.
A: This page by Movable Type contains formulae for geospatial calculations and, even better, most of the formulae are already written in Javascript.
So using their library and your example, I would do something like this:
Starting Latitude: <span id="starting_lat">0</span><br>
Starting Longitude: <span id="starting_long">0</span><br>
Current Latitude: <span id="current_lat">0</span><br>
Current Longitude: <span id="current_long">0</span><br>
Speed: <span id="speed">0</span><br>
Direct Distance (km): <span id="directDistance">0</span><br>
Cumulative Distance (km): <span id="cumulativeDistance">0</span><br>
<script>
var startPos;
var prevPos;
var currentPos;
var watchID;
var cumulativeDist = 0;
document.addEventListener("deviceready", startApp, false); //Start the Application
function startApp() {
// Start watching the location
watchID = navigator.geolocation.watchPosition(onSuccess, onError, {timeout: 30000, maxAge:0, enableHighAccuracy: false }); // enableHighAccuracy=false => No GPS
}
function onSuccess(position) {
if(currentPos){
prevPos = currentPos;
)
currentPos = new LatLon(position.coords.latitude, position.coords.longitude);
document.getElementById('current_lat').innerHTML=(currentPos.lat());
document.getElementById('current_long').innerHTML=(currentPos.lon());
if(!startPos){
startPos = currentPos;
document.getElementById('starting_lat').innerHTML=(startPos.lat());
document.getElementById('starting_long').innerHTML=(startPos.lon())
}
if(prevPos){
getDistance();
}
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function getDistance(){
cumulativeDist += currentPos.distanceTo(prevPos);
document.getElementById('cumulativeDistance').innerHTML=(cumulativeDist);
var directDist = currentPos.distanceTo(startPos);
document.getElementById('directDistance').innerHTML=(directDist);
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29211116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does my loop stop after the first round? I'm trying to loop through a large string that is in the format of field:characters. I need to check if all fields are present. First I split up the string into each individual pair:
import re
passport_string = '''iyr:2013 hcl:#ceb3a1
hgt:151cm eyr:2030
byr:1943 ecl:grn
eyr:1988
iyr:2015 ecl:gry
hgt:153in pid:173cm
hcl:0c6261 byr:1966'''
pass_list = re.split('\n| ', passport_string)
pass_list comes out as:
['iyr:2013', 'hcl:#ceb3a1', 'hgt:151cm', 'eyr:2030', 'byr:1943', 'ecl:grn', '', 'eyr:1988', 'iyr:2015', 'ecl:gry', 'hgt:153in', 'pid:173cm', 'hcl:0c6261', 'byr:1966']
I then iterate through each pair. I want to split each at : then append to a new list. Once I reach '' in pass_list I want to append all that was before it to a final list. This is what I came up with:
fields = []
holder = []
for pair in pass_list:
field = pair[:pair.find(':')]
holder.append(field)
if len(pair) == 0:
fields.append(holder)
holder = []
This results in:
[['iyr', 'hcl', 'hgt', 'eyr', 'byr', 'ecl', '']]
Why did my loop not check the second half?
Thanks in advance.
edit: I got the answer for anyone wondering:
passport_string = '''iyr:2013 hcl:#ceb3a1
hgt:151cm eyr:2030
byr:1943 ecl:grn
eyr:1988
iyr:2015 ecl:gry
hgt:153in pid:173cm
hcl:0c6261 byr:1966
'''
Had to change where the closing ''' was.
A: passport_string = '''iyr:2013 hcl:#ceb3a1
hgt:151cm eyr:2030
byr:1943 ecl:grn
eyr:1988
iyr:2015 ecl:gry
hgt:153in pid:173cm
hcl:0c6261 byr:1966
'''
Change the location of the bottom '''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65151449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Displaying highchart columnrange charting xAxis, yAxis and series I have columnrange charting . I am trying to display xaxsis ,yAxsis and series data on the chart . But somehow i can't display all the categories on yAxis and xAxsis on the chart from the data and i can't display series ,too . This code was working for linechart and updated couple of thing in the code to modify it to columnrange charting but no luck .
I am pushing the data in an array var series = []; and call it in series but doesn't display anything
I saved it in jfiddle since the script is long
Here is the link
Thanks http://jsfiddle.net/a7rmx/
A: You have two errors:
*
*trying to attach series to data, shoule be: series: series
*wrong format for points, should be: { low: from, high: to, x: x }
See fixed demo: http://jsfiddle.net/a7rmx/45/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24076667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Salesforce update() method error when using a BigDecimal Is there a different between the upsert and update operations in Salesforce when it comes to data types?
I use upsert to sync up my Contacts and update to sync up my Accounts.
When setting a custom field for a contact I pass it a BigDecimal value, and it happily syncs with Salesforce, do the same for my Account when I call update and I get:
Unable to find xml type for :java.math.BigDecimal
Seems that the update method doesn't like BigDecimals?
Thanks,
Chris
A: I can't say why exactly you'd be getting that problem with Account and not Contact, but my first inclination would be not to try to pass in a BigDecimal at all and instead convert it to a double first using BigDecimal.doubleValue(). The downside is that you may lose some precision there, but the upside is that it should work without incident :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15928781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Filter wordpress query by checkboxes I have a situation where I have a query with two different post types and I have to checkboxes on top with the names of post type. I wont by default those checkboxes to be checked and if one of theme is unchecked to remove that post type and the post affiliated to that post type from the query.
A: This part is circumstancial, but you get the idea. Give the values to the ones that are/aren't checked.
if($checkboxone == '1') {
$types = array( 'typeone' )
}
if($checkboxtwo == '1') {
$types = array( 'typetwo' )
}
if($checkboxtwo == '1' && $checkboxone == '1'){
$types = array( 'typeone', 'typetwo' )
}
then plug that value into your WP_Query by some means like this. the documentation for it is here
// The Query
$the_query = new WP_Query( array( 'post_type' => $types );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
//DO STUFF
endwhile;
// Reset Post Data
wp_reset_postdata();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12433253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CNN train with weird result: VAL LOSS increases while VAL ACCURACY / PRECISION / RECALL also increase I am fine tuning a 5 classes with model Resnet50 w/ 10 millions trainable parameters. Data has around 140,000 samples and 20% are used for validation. Batchsize 256 I may add and lr is warming linearly from 1e-5 up to 3e-4 for first 10 epochs then cosine annealing twice from there for another 20 epochs (10 - 30), we than flat the lr at 5e-6 from epochs 30th to 40th. Each classes have a lot in common but easily are differentiated.
The picture attached said it all: after epoch 10, everything are increasing, both val loss, val accuracy, val precision and val recall (not to mention also F1, top-1 etc... also increase steadily). In practice, the prediction give a lot of false positive than expected with very high probability of 99%.
What really happened here may I ask ?
...
base_model = ResNet50(include_top=False, weights='imagenet', input_tensor=Input(shape=(224, 224, 3)))
x = base_model.output
x = GlobalMaxPooling2D(name='feature_extract')(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(len(classIDs), activation="softmax", name='all_classes_hatto')(x)
classifier = Model(inputs=base_model.input, outputs=[x])
...
Thanks for your helps. Steve
A: Fixed. Four (4) things have to be done:
1) Data is a concern, hence clean data a bit more
2) Put more noice into the model
3) Batchnorm after activation at almost last layer
4) Switch to DenseNet201 which learns much deeper
x = base_model.output
x = GlobalMaxPooling2D(name='feature_extract')(x)
# Add Gaussian noices
x = GaussianNoise(0.5)(x)
# Add batchnorm AFTER activation
x = Activation('relu')(x)
x = BatchNormalization()(x)
x = Dense(512, activation='linear')(x)
# Add batchnorm AFTER activation w/o DropOut
x = Activation('relu')(x)
x = BatchNormalization()(x)
x = Dense(len(classIDs), activation="softmax", name='all_classes_hatto')(x)
classifier = Model(inputs=base_model.input, outputs=[x])
This works and I finally got an oustanding model now (the blue line).
Steve
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60679330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Java and C# communication via message queue I have an application in C#, which is extracting some data from files. I want to send this extracted data to Java application via message queue. I have no experience with message queue. I don't want to use web services.
*
*Which message broker will be the best one?
*I have domain models in C# which I need to send to Java app. How to do it? These are just plain POCO classes. Should I serialize them to XML, then to string, the send as a byte array, and in the Java side do the reverse order?
A: You can use RabbitMQ .It's easy to use and also support huge number of developer platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24342919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React How to fix Failed prop type - Invalid prop of type string expected object I'm building a small react-app where among other things users can register, login and so on. For the Login, I have created a loginform with additional error validation, coming from the backend. Now when I try to login, and by purpose enter wrong credentials, nothing happens (which in some reason is right) but instead of my error messages, the console tells me about an error:
Failed prop type: Invalid prop `errors` of type `string` supplied to `Login`, expected `object`
Here is the code:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import classnames from "classnames";
import { loginUser } from "../../actions/authActions";
class Login extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
errors: {}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.auth.isAuthenticated) {
this.props.history.push("/mysite");
}
if (nextProps.errors) {
this.setState({ errors: nextProps.errors });
}
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
};
this.props.loginUser(userData);
}
render() {
const { errors } = this.state;
return (
<div className="login">
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<h1 className="display-4 text-center">Log In</h1>
<p className="lead text-center">Sign in to your account</p>
<form noValidate onSubmit={this.onSubmit}>
<div className="form-group">
<input
type="email"
className={classnames("form-control form-control-lg", {
"is-invalid": errors.email
})}
placeholder="Email Address"
name="email"
value={this.state.email}
onChange={this.onChange}
/>
{errors.email && (
<div className="invalid-feedback">{errors.email}</div>
)}
</div>
<div className="form-group">
<input
type="password"
className={classnames("form-control form-control-lg", {
"is-invalid": errors.password
})}
placeholder="Password"
name="password"
value={this.state.password}
onChange={this.onChange}
/>
{errors.password && (
<div className="invalid-feedback">{errors.password}</div>
)}
</div>
<input type="submit" className="btn btn-info btn-block mt-4" />
</form>
</div>
</div>
</div>
</div>
);
}
}
Login.propTypes = {
loginUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ loginUser }
)(Login);
I have no clue why that error appears!? Can someone help me out?
A: You are passing string as an error instead of object in the props for the Login component. Try console.log of "errors" in the component where Login component is rendered to see what value is getting set.
A: PropTypes expecting an object because of your propTypes definition
erros: PropTypes.object.isRequired,
Use:
Login.propTypes = {
loginUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.string.isRequired
};
If it's no required your also have to define a defaultProp:
Login.propTypes ={
errors: PropTypes.string,
}
Login.defaultProps = {
errors: '',
}
A: Make sure your link is not misspelled,
export const loginUser=(userData)=>dispatch=>{
axios.post('/api/users/login',userData)
not
export const loginUser=(userData)=>dispatch=>{
axios.post('/api/user/login',userData)
users not user
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54590504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I pass some values from one view to another view in codeigniter? I have an application done on Code-igniter.
I wanted to pass title and URL to another page when I click on a link to the next page.
For e.g.
Page one - properties/home/details/titleofthecontent - in this page i have a link report it .
When i click on report it i will get next page /report_abuse .Here I need to get the page title and the URL from the previous page.
I have the variable to pass but how could I pass it? This is same as passing values from one view to another view.
A: Inside your controller, have
$data['nestedView']['otherData'] = 'testing';
before your view includes.
When you call
$this->load->view('view_destinations',$data);
the view_destinations file is going to have
$nestedView['otherData'];
Which you can at that point, pass into the nested view file.
A: From what you explain, I understand that you want to pass some data from a controller to another (since your URL's are different).
To do this, you can:
*
*Pass the data through query strings (GET) as explained above or
*Set a flash data variable in the first controller, and use it in the second. I would advise to use this solution, as that's why flash data exists.
A: You can use $this->uri->segment() of Codeigniter like below.
$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment
You can pass the variables values via url and get on the controller. and so on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39844594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to clear insufficient space on disk where the following directory resides in teamcity I am getting the following message :-
Warning: insufficient space on disk where the following directory resides: Z:\TeamCity\.BuildServer\system. Disk space available: 915.53Mb. Please contact your system administrator.
I already have executed the build history cleanup command. but this has not done much. Can you please guide what directory under the following path I clear up to make space on disk.
This Z:\TeamCity.BuildServer\system path has artifacts, caches, changes, messages directories. Which directory to delete to make space.
Many Thanks
A: Take a look to the Clean-up process settings: http://blogs.lessthandot.com/index.php/ITProfessionals/ITProcesses/don-t-forget-to-clean
Wayback Machine Archive Link
By default TeamCity kepts everything forever, you must configure clean-up rules for each project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16830731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Run shell command from JavaScript in node-webkit? Is there any way to run shell command from JavaScript in node-webkit?
There is a lot of similar questions, but it didn't help me.
I'm trying to build simple desktop app for listing installed tools.
I've created node module 'tools-v' which is installed globally and works when I run it in command line.
This module run several commands: npm -v, node -v, git -v etc.
I'm on Windows 7.
//var sys = require('sys');
var exec = require('child_process').exec;
//var toolsv = (process.platform === "win32" ? "tools-v.cmd" : "tools-v");
$(document).ready(function() {
//myCmd = "C:\\Users\\win7\\AppData\\Roaming\\npm\\tools-v.cmd";
//myCmd = toolsv;
myCmd = 'tools-v';
//gui.Shell.openItem('firefox',function(error, stdout, stderr) { });
//opening Firefox works.
exec(myCmd, function (error, stdout, stderr) {
//detached: true;
console.log('stdout: ' + stdout);
$('#output').append('stdout: ' + stdout)
if (error !== null) {
console.log('exec error: ' + error);
}
});
});
I'm always getting error:
""exec error: Error: spawn ENOENT""
I tried spawn instead of exec. I also tried several other commands, beside node module.
Thanks.
A: Actually, this code works. I just didn't built full app, I tested it trough sublime build for node-webkit. Preforming full build with grunt solved every spawn issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26920834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: throw new InvalidArgumentException("Route [{$name}] not defined."); routing error in laravell 5.6 I want to update my database and trying to redirect it to a defined url in Laravel 5.6
public function update(Request $request, Apply1 $Apply1)
{
$Apply1 ->Given_Name=$request->Given_Name;
$Apply1 ->Surname=$request->Surname;
$Apply1 ->Date_Birth=$request->Date_Birth;
$Apply1 ->Place_Birth=$request->Place_Birth;
$Apply1 ->Mother_Name=$request->Mother_Name;
$Apply1 ->Father_Name=$request->Father_Name;
$Apply1 ->Passport_Number=$request->Passport_Number;
$Apply1 ->Passport_Issue_Date=$request->Passport_Issue_Date;
$Apply1 ->Passport_Expiry_Date=$request->Passport_Expiry_Date;
$Apply1 ->Type_Supporting_Doc=$request->Supporting_Doc;
$Apply1 ->Supporting_Doc_Form=$request->city;
$Apply1 ->Supp_Doc_Expiry_Date=$request->Supp_Expiry_Date;
$Apply1 ->E_mail_address=$request->mail_address;
$Apply1 ->Phone_Number=$request->Phone_Number;
$Apply1 ->Address=$request->Address;
$Apply1 ->City=$request->Permanent_City;
$Apply1 ->State=$request->Address;
$Apply1 ->Postal_Code=$request->Permanent_City;
$Apply1 ->save();
return redirect(Route('Apply1.show1', $Apply1->id));
}
and my defined route is in web.php file is
Route::get('Apply1/show1/{id}', function ($id) {
return 'User '.$id;
});
but still getting error in the end that ("Route [{$name}] not defined.");
i have defined the correct route but i don,t know why i am getting this error again
A: I guess you are not following the named route documentation properly.
Your route:
Route::get('Apply1/show1/{id}', function ($id) {
return 'User '.$id;
});
According to the documentation, you need to add name at the end of the route. That means, you should add it like this..
Route::get('Apply1/show1/{id}', function ($id) {
return 'User '.$id;
})->name('Apply1.show1'); // you had not written this
In this way, you will get your desired result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52774383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP curl request for weird parameters I'm trying to automate signing up for classes (cause im allways forgetting to do it)
When i manually sign up it uses this url for classes on a specific day:
https://URL.com/public/tickets.php?PRESET%5BTickets%5D%5Bname%5D%5B%5D=&PRESET%5BTickets%5D%5Bday%5D%5B%5D=2018-03-04
which decodes into
https://URL.com/public/tickets.php?PRESET[Tickets][name][]=&PRESET[Tickets][day][]=2018-03-04
But im having the hardest time translating this into a curl request. I've (amongst other things) tried
$data = array("PRESET" => array("Tickets" => array("name"=>array(""), "day"=> array("2018-03-02"))));
and
$data = array('PRESET[Tickets][naam][]=', 'PRESET[Tickets][naam][]=');
But i allways get a page where no day has been selected. Sometimes there is a php error on the page about a parameter that is expected to be an array.
this is my curl request
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, $targetSite);
curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie);
curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookie);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
Can someone tell me how to properly send the parameters with the curl request? Thanks!
A: when you put it into CURLOPT_POSTFIELDS, you're putting it into the request body, not the request URL. furthermore, when you give CURLOPT_POSTFIELDS an array, curl will encode it in multipart/form-data-format, but you need it urlencoded (which is different from multipart/form-data). remove all the POST code, and use http_build_query to build the url,
curl_setopt ( $ch, CURLOPT_URL, "https://URL.com/public/tickets.php?" . http_build_query ( array (
'PRESET' => array (
'Tickets' => array (
'name' => array (
0 => ''
),
'day' => array (
0 => '2018-03-04'
)
)
)
) ) );
and protip, you can use parse_str() to decode urls into php arrays, and furthermore, you can use var_export to get valid php code to create that array at runtime, and finally, as shown above, you can use http_build_query to convert that array back to an url, that's what i did here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49094177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Discord.py delete messages and allow specific message How can I allow users send only the specific message and delete every other message!
A: @client.event
async def on_message(msg):
if not msg.content == 'specific_msg':
await client.delete_message(msg)
You have to give Manage Messages permission to your bot.
A: You can use this method and add the messages you want to allow in the msgs variable.
msgs=['hi there','hello there']
@bot.event
async def on_message(msg):
if msg.content.lower() not in msgs:
await bot.delete_message(msg)
await bot.process_commands(msg)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54973956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: React Redux router saga material-ui and tabs corresponding to current route I'm pretty new to react and I'm using react-boilerplate + material-ui
I have tabs like so:
And I want to be able to change the current tab so it would change the current route and vice-versa.
Also when refreshing the page with a route it should go to the right tab.
So I have my tabpagechooser container component like so:
index.js:
/*
*
* TabsPageChooser
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { changeTab } from './actions';
import makeSelectTab from './selectors';
import messages from './messages';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
export class TabsPageChooser extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props)
this.handleHome = this.props.onChangeTab.bind(null, 0);
this.handleSettings = this.props.onChangeTab.bind(null, 1);
this.handleAbout = this.props.onChangeTab.bind(null, 2);
}
render() {
console.log(this.props);
return (
<Tabs initialSelectedIndex={this.props.tab.tabIdx} >
<Tab
icon={<FontIcon className="material-icons">home</FontIcon>}
label={<FormattedMessage {...messages.home} />}
onActive={this.handleHome} />
<Tab
icon={<FontIcon className="material-icons">settings</FontIcon>}
label={<FormattedMessage {...messages.settings} />}
onActive={this.handleSettings} />
<Tab
icon={<FontIcon className="material-icons">favorite</FontIcon>}
label={<FormattedMessage {...messages.about} />}
onActive={this.handleAbout} />
</Tabs>
);
}
}
TabsPageChooser.propTypes = {
onChangeTab: React.PropTypes.func,
};
const mapStateToProps = createStructuredSelector({
tab: makeSelectTab(),
});
function mapDispatchToProps(dispatch) {
return {
onChangeTab: (tabId) => {
dispatch(changeTab(tabId));
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TabsPageChooser);
actions.js:
/*
*
* TabsPageChooser actions
*
*/
import {
ROUTES_ID,
CHANGE_TAB,
} from './constants';
export function changeTab(tabId) {
return {
type: CHANGE_TAB,
tab: tabId,
};
}
export function urlFromId(tabId) {
if (!(tabId > 0 && tabId < ROUTES_ID)) {
return '/';
}
return ROUTES_ID[tabId];
}
export function changeTabFromUrl(url) {
console.log(url);
return changeTab(ROUTES_ID.indexOf(url));
}
constants.js:
/*
*
* TabsPageChooser constants
*
*/
export const CHANGE_TAB = 'app/TabsPageChooser/CHANGE_TAB';
export const ROUTES_ID = [
'/',
'/settings',
'/about',
];
reducer.js:
/*
*
* TabsPageChooser reducer
*
*/
import { fromJS } from 'immutable';
import {
CHANGE_TAB,
} from './constants';
const initialState = fromJS({
tabIdx: 0,
});
function tabsPageChooserReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_TAB:
return state.set('tabIdx', action.tab);
default:
return state;
}
}
export default tabsPageChooserReducer;
sagas.js:
import { take, call, put, select, takeLatest, takeEvery } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { changeTabFromUrl, urlFromId } from 'containers/TabsPageChooser/actions';
import { makeSelectTab } from 'containers/TabsPageChooser/selectors';
import { CHANGE_TAB } from 'containers/TabsPageChooser/constants';
import { LOCATION_CHANGE } from 'react-router-redux';
function* doChangeTab(action) {
//Act as dispatch()
yield put(changeTabFromUrl(action.payload.pathname));
}
function* doChangeUrl(action) {
//Act as dispatch()
yield put(push(urlFromId(action.tab.tabId)));
}
// Individual exports for testing
export function* defaultSagas() {
yield takeEvery(LOCATION_CHANGE, doChangeTab);
yield takeEvery(CHANGE_TAB, doChangeUrl);
}
// All sagas to be loaded
export default [
defaultSagas,
];
My problem is especially that last file, the LOCATION_CHANGE event, trigger the changeTab action which in turn trigger the CHANGE_TAB event, which trigger a location change etc...,
What am I doing wrong, how should I do ?
A: I finally succeeded,
What I have changed:
/*
*
* TabsChooser
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { changeTab } from 'containers/App/actions';
import { makeSelectLocationState, makeSelectTabsChooser } from 'containers/App/selectors';
import messages from './messages';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
const locationId = [
'/',
'/settings',
'/about',
];
export class TabsChooser extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
this.contentsTab = [
{ route: this.props.onChangeTab.bind(null, locationId[0]), icon: <FontIcon className='material-icons'>home</FontIcon>, label: <FormattedMessage {...messages.home} />, },
{ route: this.props.onChangeTab.bind(null, locationId[1]), icon: <FontIcon className='material-icons'>settings</FontIcon>, label: <FormattedMessage {...messages.settings} />, },
{ route: this.props.onChangeTab.bind(null, locationId[2]), icon: <FontIcon className='material-icons'>favorite</FontIcon>, label: <FormattedMessage {...messages.about} />, },
];
let tabId = locationId.indexOf(this.props.tabLocation);
return (
<div>
<Tabs value={tabId} >
{this.contentsTab.map((tab, i) =>
<Tab key={i} value={i} icon={tab.icon} label={tab.label} onActive={tab.route} />
)}
</Tabs>
</div>
);
}
}
TabsChooser.propTypes = {
onChangeTab: React.PropTypes.func,
tabLocation: React.PropTypes.string,
};
function mapDispatchToProps(dispatch) {
return {
onChangeTab: (location) => dispatch(changeTab(location)),
};
}
const mapStateToProps = createStructuredSelector({
tabLocation: makeSelectTabsChooser(),
});
export default connect(mapStateToProps, mapDispatchToProps)(TabsChooser);
I now send the location instead of the the tab id in changeTab(),
I move action.js, reducer.js, selector.js and sagas.js into containers/App
action.js:
/*
* App Actions
*
*/
import { CHANGE_TAB, TABCHANGE_LOCATION } from './constants'
export function changeTab(tabLocation) {
return {
type: CHANGE_TAB,
tabLocation,
};
}
export function changeLocation(tabLocation) {
return {
type: TABCHANGE_LOCATION,
tabLocation,
};
}
constants.js:
/*
* AppConstants
*/
export const CHANGE_TAB = 'app/App/CHANGE_TAB';
export const TABCHANGE_LOCATION = 'app/App/TABCHANGE_LOCATION';
reducer.js:
/*
* AppReducer
*
*/
import { fromJS } from 'immutable';
import {
CHANGE_TAB,
TABCHANGE_LOCATION,
} from './constants';
// The initial state of the App
const initialState = fromJS({
tabLocation: window.location.pathname // Initial location from uri
});
function appReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_TAB:
return state.set('tabLocation', action.tabLocation);
case TABCHANGE_LOCATION:
return state.set('tabLocation', action.tabLocation);
default:
return state;
}
}
export default appReducer;
The initialState tabLocation is set with the window.location.pathname, so the right tab is selected at app bootup.
selector.js:
/**
* The global state selectors
*/
import { createSelector } from 'reselect';
const selectGlobal = (state) => state.get('global');
const makeSelectLocationState = () => {
let prevRoutingState;
let prevRoutingStateJS;
return (state) => {
const routingState = state.get('route'); // or state.route
if (!routingState.equals(prevRoutingState)) {
prevRoutingState = routingState;
prevRoutingStateJS = routingState.toJS();
}
return prevRoutingStateJS;
};
};
const makeSelectTabsChooser = () => createSelector(
selectGlobal,
(globalState) => globalState.getIn(['tabLocation'])
);
export {
selectGlobal,
makeSelectLocationState,
makeSelectTabsChooser,
};
sagas.js:
import { take, call, put, select, takeLatest, takeEvery, cancel } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { changeLocation } from './actions';
import { makeSelectTabsChooser } from './selectors';
import { CHANGE_TAB } from './constants';
import { LOCATION_CHANGE } from 'react-router-redux';
function* updateLocation(action) {
//put() act as dispatch()
const url = yield put(push(action.tabLocation));
}
function* updateTab(action) {
const loc = yield put(changeLocation(action.payload.pathname));
}
// Individual exports for testing
export function* defaultSagas() {
const watcher = yield takeLatest(CHANGE_TAB, updateLocation);
const watcher2 = yield takeLatest(LOCATION_CHANGE, updateTab);
}
// All sagas to be loaded
export default [
defaultSagas,
];
So finally the sagas wrap it up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41870582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could not find active fragment with index -1 Activity fragment manager problem When change orientation:
Caused by: java.lang.IllegalStateException: Could not find active fragment with index -1
at
android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:3026)
at
android.support.v4.app.Fragment.restoreChildFragmentState(Fragment.java:1446)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1380)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at
com.motors.mobile.core.v2.DaggerIncludeBaseActivity.onCreate(DaggerIncludeBaseActivity.java:26)
Follow my code :
@Override
protected void tabletPortraitInit(Bundle savedInstanceState) {
super.tabletPortraitInit(savedInstanceState);
openSubFragment();
}
@Override
protected void tableLandscapeInit(Bundle savedInstanceState) {
super.tableLandscapeInit(savedInstanceState);
openSubFragment();
}
protected void openSubFragment() {
Bundle bundle = getIntent().getBundleExtra(CAR_DETAIL_KEY);
fragment = new BuyDetailFragment();
if (getSupportFragmentManager().findFragmentByTag(BuyDetailFragment.TAG) != null)
fragment = (BuyDetailFragment) getSupportFragmentManager().findFragmentByTag(BuyDetailFragment.TAG);
fragment.setArguments(bundle);
menuClickListener = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.flMain, fragment, BuyDetailFragment.TAG)
.commit();
// init toolbar items
View tbView = getLayoutInflater().inflate(R.layout.items_detail_menu_layout, toolbar.findViewById(R.id.container), true);
phone = tbView.findViewById(R.id.phone);
message = tbView.findViewById(R.id.message);
link = tbView.findViewById(R.id.notifications);
site = tbView.findViewById(R.id.site);
shortlistView = tbView.findViewById(R.id.wishListMenu);
phone.setOnClickListener((e) -> menuClickListener.clickPhone());
message.setOnClickListener((e) -> menuClickListener.clickMessage());
link.setOnClickListener((e) -> menuClickListener.clickNotifications());
site.setOnClickListener((e) -> menuClickListener.clickSite());
shortlistView.setOnClickListener((e) -> menuClickListener.clickShortlist());
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.vector_heart);
drawable.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.SRC_IN);
shortlistView.changeIcon(drawable);
}
There is no my baseActivity
A: Does your fragment have setRetainInstance(true)? If so, that may be causing you an issue here, especially if you are using a fragment apart of FragmentStatePagerAdapter.
A: This can happen with a combination of dismissAllowingStateLoss after onSaveInstanceState and retainInstanceState.
See this helpful example with steps to reproduce (that site does not allow commenting, but it helped me diagnose the issue)
Steps to reproduce:
*
*Open page and show dialog fragment with retainInstance = true
*Background app, onSaveInstanceState is called
*dismiss dialog in an async task via dismissAllowingStateLoss
*perform configuration change, for example by changing language or orientation
*open app
*crash "Unable to start activity... java.lang.IllegalStateException: Could not find active fragment with index -1"
Under the scenes what's going on is that FragmentManagerImpl.restoreAllState now has an active fragment with an index of -1 because dismissAllowingStateLoss removes the fragment from the backstack, BUT, it is still part of nonConfigFragments because the commit part of dismissAllowingStateLoss was ignored as it was called after onSaveInstanceState.
To fix this will require one of:
*
*not using retainInstanceState on Dialogs that can be dismissed via dismissAllowStateLoss, or
*not calling dismiss after state loss
and implementing the desired behavior in a different way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48931474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Save numpy ndarray to file with index to file I have a large NumPy array, say 1000*1000.
I want to save it to a file with each line format like the following.
row col matrix[row,col]
I can't seem to find a method that does it efficiently.
I could do a nested for loop but it's too slow.
Constructing a larger matrix which contains the indices would be too expensive on memory.
I was thinking of list comprehension, but are there other ways of doing it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72492585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a git patch between repository and non-repository I have a situation where a folder needs to be patched to be the same state as a repository. Consider this short tale:
Ten years age Goofus and Gallant are somewhat alike and at a fork in the road Gallant moves onward and becomes a better person. Goofus hangs out and does nothing. The almighty pointy hair decrees Goofus must become more like Gallant again. How can Gallant patch Goofus without making him a clone ?
*
*Goofus and Gallant similar but not identical
*Gallant enters the repository
*Gallant milestone reached
*Goofus needs to be patched to Gallant
What's the best way to get the patch ?
Should I make a branch and mutate Gallant back to Goofus and then make an inverse patch ?
A: If you want to simply import Goofus back into Gallant (which will be the same as a patch), simply download an archive (zip or tarball) of Goofus, and uncompress it somewhere, then use it as working tree for a one-time import:
cd /path/to/Gallant
git --work-tree=/path/to/Unzipped/Goofus add .
git commit -m "Goofus import"
git push
The git add part will detect any modified, added or removed files from Goofus, and add them in the Gallant repo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43820960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: With Meteor's iron-router, how do you re-render the template from a template event? My template shows different content based on a non-reactive value (in localStorage). I would like to do the following:
Template.foo.events
'click #link': ->
localStorage.setItem 'key', 'different'
// re-render template foo
this.render() is undefined. Router.render('foo') does nothing.
A: The easiest way is to use a dependency tied to your value.
keyDep = new Deps.Dependency()
Template.foo.events
'click #link': ->
localStorage.setItem 'key', 'different'
keyDep.changed()
Template.foo.key = ->
keyDep.depend()
return localStorage.getItem 'key'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23586360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VBA Access Write to PS1 file I am trying to use Access 2016 as a front end for a database that when a user clicks a button it generates a Powershell script and runs it.
I am currently using this:
Dim Script As String
Script = ("test" & vbCrLf & "2nd line?")
Set f = fileSysObject.OpenTextFile("C:\Users\%Username%\Documents\Access.ps1", True, True)
f.Write Script
f.Close
Then to run the script I am using:
Dim run
run = Shell("powershell ""C:\Users\%Username%\Documents\Powershell\Access.ps1""", 1)
I realise that this is probably a really bad way of doing this! So any help is greatly appreciated!
Thanks!
EDIT:
Sorry there is no question!
The problem is that it highlights an error at 'f.write Script'
Compile Error: Method or data member not found.
A: The format %VAR% doesn't work in VBA, you need to Environ("VAR")
That said username doesn't return a value with that method, but you can use VBA.Environ("Username") in this case:
Dim strScript, strUserName, strFile As String
Dim objFSO, objFile as Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
strScript = ("test" & vbCrLf & "2nd line?")
strUserName = VBA.Environ("Username")
strFile = "C:\Users\" & strUserName & "\Documents\Access.ps1"
Set objFile = objFSO.CreateTextFile(strFile)
objFile.WriteLine strScript
objFile.Close
Set objFSO = Nothing
Set objFile = Nothing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42436477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can you have multiple HttpSessionStrategy? I would like to have a header based HttpSessionStrategy as listed below however Spring Social seems to want to store the social token on the session.
When it is redirected back to the application no x-auth-header is specified so a new session is created and the token is lost.
Can we have still have the HeaderSessionStrategy with the CookieSessionStrategy as a fallback?
What is the best way to handle this?
@Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
A: Here is what you want.
SmartHttpSessionStrategy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33162158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LOGIN SYSTEM FORM [ how to validate the data in the database in order to access the next html file] This is a log-in form where the user can sign-up. No problems in the sign-up form, however when logging the if condition is somehow false then will go to the else condition where it tells that the saved data is wrong even though the data is saved into the database.
Here's the code
if(isset($_POST['submit'])){
$username = $_POST["lg-username"];
$password = $_POST["lg-password"];
$sql = "SELECT * from login_table where user='$username' and pass='$password'";
if ($conn->query($sql) === TRUE) {
echo "<script>alert('WELCOME' + $user)</script>";
include_once('../scanning/index.html');
} else {
echo "<script>alert('ERROR! USERNAME OR PASSWORD IS INCORRECT')</script>";
include_once('login-signup.html');}}
can you help to validate the username and password in order to access the other html file? THANK YOU!
A: I just added a variable $result to query the SQL
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo "<script>alert('WELCOME'+ $username)</script>";
include_once('../scanning/index.html');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65807219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: htaccess rewriting between subdomains I have got following folder structure for my domain (domain.com):
/data/images (itΒ΄s subdomain name, so itΒ΄s accessable via http:// images.domain.com)
/data/www (itΒ΄s subdomain name, so itΒ΄s accessable via http:// www.domain.com)
/data/.htaccess
And IΒ΄m trying to do:
If some image in images.domain.com doesnΒ΄t exist, rewrite URL with has request to www.domain.com/somescript.php, so for example
http://images.domain.com/non-existing-image.jpg
should be rewritten to
http://www.domain.com/somescript.php?id=non-existing-image.jpg.
Here is my htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(jpg|gif|png|bmp)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /data/www/somescript.php?id=$1 [L,QSA]
But itΒ΄s not working. Browser said: "not found". If I tried to change path to "somescript.php" the results were "bad-request" or "not-found".
Via access log I saw that in most cases the path to "somescript.php" is starting from "/data/www/images/" (so final path is non-existing "/data/www/images/www/somescript.php") so I guess I need to get one level higher in my folder structure, but I donΒ΄t know how (I guess IΒ΄ve already tried almost all combinations).
Could someone please help me how to properly set the combination of RewriteBase and absolute/relative path for the "somescript.php" file?
I also want to note, that if I change the path to "http://www.domain.com/somescript.php" on the last line in my htaccess file, it works well - but due to "http://" itΒ΄s redirected and I would like to made as rewrite.
Thank you very much.
A: Try replacing the / at the beginning of your rewrite rule. In order for it to actually go to another domain, you must specify http:// before the domain, so your last line would need to be like this:
RewriteRule ^(.*)$ http://www.domain.com/somescript.php?id=$1 [L,QSA]
If you don't specify the http:// it's seen as a relative path and will go off of the domain currently in use, just appending it as a regular relative path.
Or: (This only works on some setups)
Apache (or whatever you're using) doesn't go off of your user's home directory. It uses the root directory for the website. So by specifying the / at the beginning of the domain, you're actually saying /www/images.domain.com/<rest of absolute path>. However, if both these directories are owned by the same user, you can use a relative path to go up to the parent directory and then into the alternative directory, like so:
RewriteRule ^(.*)$ ../www.domain.com/somescript.php?id=$1 [L,QSA]
I wouldn't recommend this much though, as relative paths can easily become broken.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9143828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - hover function with two classes for an element, a hover for each class I'm not sure if this is a different problem embedded somewhere in my code, or an issue with the hover function i'm not aware of -
in short, i have an element with two classes
<input type="image" class="classA classB" ... />
and i have jQuery code like so:
$('classA').hover(){
function1,
function2
}
$('classB').hover(){
function3,
function4
}
what i'm wanting is that when you hover over the input, BOTH hover functions (function1, function3) get fired. And when you move off it, BOTH functions (function2, function4) are also fired.
What appears to be happening is that the classB hover completely overrides or shadows or what have you the classA hover function.
Is this intended behaviour (or is this an indication that something is wrong with my much-larger code base?), and if so, what is the general consensus work around?
A: The classB's hover overwrites the classA's hover in the case of a tag that has both classes, because of the order they are written in (classB's hover after classA's hover).
A solution could be:
$('.classA, .classB').hover(
// mouseover
function() {
var $this = $(this);
if($this.hasClass('classA')) {
function1();
}
if($this.hasClass('classB')) {
function3();
}
},
// mouseout
function() {
var $this = $(this);
if($this.hasClass('classA')) {
function2();
}
if($this.hasClass('classB')) {
function4();
}
});
A: AH-HA!
Ok, so sp00m's answer here were good and right - but it wasn't quite for my purpose. Because i have a fair bit of code running around, I was hoping to keep things "clean" (cleanish?). I probably should have been clearer in the original question...
See, I already had elements that needed the first hover, and elements that needed the second, so when i had elements that needed both the aim was to not have a third hover for that scenario. Code non-reuse and complexity! Boo!
What I didn't realise was that the hover that comes last will overwrite the first hover. This is probably something to do with the fact that it was targeting one class, and the first was targeting another.
The solution was this:
$('.classB, .classA').hover(){
function3,
function4
}
Happily, when i target classA using the multi selector it doesn't override the original hover.
That is, I removed classB from the class attribute for my input, and added classA to the hover selector!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12726697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Consuming RSS feed with AWS Lambda and API Gateway I'm a newbie rails programmer, and I have even less experience with all the AWS products. I'm trying to use lambda to subscribe to and consume an rss feed from youtube. I am able to send the subscription request just fine with HTTParty from my locally hosted rails app:
query = {'hub.mode':'subscribe', 'hub.verify':'sync', 'hub.topic': 'https://www.youtube.com/feeds/videos.xml?channel_id=CHANNELID', 'hub.callback':'API Endpoint for Lambda'}
subscribe = 'HTTParty.post(https://pubsubhubbub.appspot.com/subscribe, :query=>query)
and it will ping the lambda function with a get request. I know that I need to echo back a hub.challenge string, but I don't know how. The lambda event is empty, I didn't see anything useful in the context. I tried formatting the response in the API gateway but that didn't work either. So right now when I try to subscribe I get back a 'Challenge Mismatch' error.
I know this: https://pubsubhubbub.googlecode.come/git/pubsubhubbub-core-0.3.html#subscribing explains what I'm trying to do better than what I just did, and section 6.2.1 is where the breakdown is. How do I set up either the AWS Lambda function and/or the API Gateway to reflect back the 'hub.challenge' verification token string?
A: You need to use the parameter mapping functionality of API Gateway to map the parameters from the incoming query string to a parameter passed to your Lambda function. From the documentation link you provided, it looks like you'll at least need to map the hub.challenge query string parameter, but you may also need the other parameters (hub.mode, hub.topic, and hub.verify_token) depending on what validation logic (if any) that you're implementing.
The first step is to declare your query string parameters in the method request page. Once you have declared the parameters open the integration request page (where you specify which Lambda function API Gateway should call) and use the "+" icon to add a new template. In the template you will have to specify a content type (application/json), and then the body you want to send to Lambda. You can read both query string and header parameters using the params() function. In that input mapping field you are creating the event body that is posted to AWS Lambda. For example: { "challenge": "$input.params('hub.challenge')" }
Documentation for mapping query string parameters
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36825042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Display bigger image on click I am trying to make gallery page and when I click on image, it will go bigger and then arrows shows on both sides and you can click them and display next and previous pictures. Can you please help me how to do it? I don't know JavaScript language also I would like to ask if I should change anything in my code?
<div class="main-outer">
<div class="content">
<div class="novinky full">
<h1 class="title" id="title">Gallery</h1>
<div class="article-full">
<div id="pages-viewer" class="viewer" style="visibility: visible;">
<div class="toastui-editor-contents" style="overflow-wrap: break-word;">
<div class="">
<form action="" method="get">
<p>Category: </p>
<select id="category" name="category" onchange="this.form.submit()">
<option value="all" <?= $sort_by == 'all' ? ' selected' : '' ?>>VΕ‘etky</option>
<?php foreach ($categories as $c) : ?>
<option value="<?= $c['title'] ?>" <?= $category == $c['title'] ? ' selected' : '' ?>><?= $c['title'] ?></option>
<?php endforeach; ?>
</select>
<p>Sort by: </p>
<select id="sort_by" name="sort_by" onchange="this.form.submit()">
<option value="z_to_a" <?= $sort_by == 'z_to_a' ? ' selected' : '' ?>>A-Z</option>
<option value="a_to_z" <?= $sort_by == 'a_to_z' ? ' selected' : '' ?>>Z-A</option>
</select>
</form>
</div>
<div class="media-list">
<?php foreach ($media as $m) : ?>
<?php if (file_exists($m['thumbnailpath'])) : ?>
<div style="width:<?= $imgwidth ?>px;height:<?= $imgheight ?>px; margin-bottom: 100px; margin-left: 11px; margin-right: 11px;">
<a href="#"><img src="<?= $m['thumbnailpath'] ?>" alt="<?= $m['title'] ?>" data-id="<?= $m['id'] ?>" data-title="<?= $m['title'] ?>" max-width="<?= $imgwidth ?>" height="<?= $imgheight ?>" style="align: center; max-height: <?= $imgheight ?>"></a>
<div style="text-align:center; font-size:25px; font-weight: bold;">
<p><?= substr($m['title'], 0, 23); ?>
</div>
<div style="text-align:center;"><?= substr($m['rok'], 0, 15); ?></p>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
A: I think you may want to look at http://chocolat.insipi.de.
It's a free cross browser JavaScript library that handles switching images.
A: This is my favorite gallery and it's easy to use.
https://sachinchoolur.github.io/lightgallery.js/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71952959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Divs don't display in the same line on Firefox I'm using Bootstrap and custom CSS to develop my personal website and I have the following HTML code to generate the content part with two columns.
<div class="row-fluid">
<div id="content" class="span9">
content
</div>
<div id="ads" class="span3">
ads
</div>
</div>
This works in all browser, but with the following CSS, the ads div goes under the content div when viewed in Firefox. In all other browsers, the ads div keeps in the right side of content div (this is the correct display).
#content{
margin-top:2em;
padding: 1em;
box-sizing: border-box;
border-radius: 20px 20px 0 0;
border: 2px solid #EEF;
}
#ads{
margin-top:2em;
padding: 1em;
box-sizing: border-box;
border-radius:15px;
border: 2px solid #EEF;
}
I think this happens because the padding + border, but all other browsers displays correctly. So, there is a way to fix this in Firefox?
If needed, this error can be viewed in http://www.dinhani.com.br (sorry, content is in portuguese because development started these days).
A: Firefox doesn't implement box-sizing without a -moz- prefix. See bugzilla
Also, your question missed the most important CSS rules: i.e. the width of each div. The page you link to shows rules for .row-fluid > .span3 and another for .span9
A: You change your html like this (just small changes in div start tag.
and I hope you get our output like image below
<div class="row-fluid">
<div id="content" class="span9">
content
</div>
<div id="ads" class="span3">
ads
</div>
</div>
ok you want to like this image2
#content{
margin-top:2em;
padding: 1em;
box-sizing: border-box;
border-radius: 20px ;
border: 2px solid #EEF;
float:left;
}
#ads{
margin-top:2em;
padding: 1em;
box-sizing: border-box;
border-radius:15px;
border: 2px solid #EEF;
float: left;
}
A: I hope this fiddle can help you http://jsfiddle.net/9Zf8U/1/ I just added firefox css hack here and nothing eals.
A: Adding css hacks for (moz browser) only.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10172948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mysql, Load Data Infile, only particular lines I'm struggling to add data from a text file into a mysql database. In my text file I have dozens of lines from which I want to extract just specific ones (which are the ones with a similar structure as the table structure).
Table structure:
Name
Surname
Email
City
ZIP
Text File:
_field1 >>> blah
otherfield >>> blah
Name >>> John
anotherfield >>> blah
Email >>> [email protected]
City >>> Portland
ZIP >>> 90210
yetanotherfield >>> foo
A: It's probably best to parse the file in some other language and then invoke INSERT from there, but since the order of fields within the file is predictable, you could go via user variables with something like:
LOAD DATA INFILE '/path/to/file.txt' INTO TABLE my_table
FIELDS TERMINATED BY '\n' LINES TERMINATED BY 0x1e
(@dummy, @dummy, @name, @dummy, @email, @city, @zip, @dummy)
SET Name = SUBSTRING(@name, LOCATE(' >>> ', @name ) + 5),
Email = SUBSTRING(@email, LOCATE(' >>> ', @email) + 5),
City = SUBSTRING(@city, LOCATE(' >>> ', @city ) + 5),
ZIP = SUBSTRING(@zip, LOCATE(' >>> ', @zip ) + 5);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12882732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Future Value of yearly investments Suppose you have an investment plan where you invest a certain fixed amount at the beginning of every year. Compute the total value of the investment at the end of the last year. The inputs will be the amount to invest each year, the interest rate, and the number of years of the investment.
This program calculates the future value
of a constant yearly investment.
Enter the yearly investment: 200
Enter the annual interest rate: .06
Enter the number of years: 12
The value in 12 years is: 3576.427533818945
I've tried a few different things, like below, but it doesn't give me that 3576.42, it gives me only $400. Any ideas?
principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print("The value in 12 years is: ", principal)
A: If it's a yearly investment, you should add it every year:
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
total = 0
for i in range(years):
total += yearly
total *= 1 + apr
print("The value in 12 years is: ", total)
With your inputs, this outputs
('The value in 12 years is: ', 3576.427533818945)
Update: Responding to your questions from the comments, to clarify what's going on:
1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example.
2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this
for i in range(years): # For each year
total += yearly # Grow the total by adding the yearly investment to it
total *= 1 + apr # Grow the total by multiplying it by (1 + apr)
The longer form just isn't as clear:
for i in range(years): # For each year
total = total + yearly # Add total and yearly and assign that to total
total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total
A: It can be done analytically:
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)
Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do:
pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1)
pmt(1000000, 0.09, 20, 0)
A: As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below.
Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back.
principal = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16076072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getimagesize function is not working properly I created a function, i am using this function to resize image to make it fit as div background image, i send div size and image path to function.. It works well when height is bigger than width but it does not work when width is bigger than height.. How can this be possible?
function imgw($divsize, $imgw){
$imgurl=$_SERVER["DOCUMENT_ROOT"]."/".$imgw;
list($width, $height) = getimagesize($imgw);
if($width > $height){$nwidth="auto";}
if($width < $height){$nwidth=$divsize."px";}
if($width==$height){$nwidth=$divsize."px";}
return $nwidth;
}
function imgh($divsize, $imgh){
$imgurl=$_SERVER["DOCUMENT_ROOT"]."/".$imgh;
list($width, $height) = getimagesize($imgurl);
if($width > $height){$nheight=$divsize."px";}
if($width < $height){$nheight="auto";}
if($width==$height){$nheight=$divsize."px";}
return $nheight;
}
Edit: This functions are used for the following code below.
<? $anwidth=imgw(70, $solsutunpic); $anheight=imgh(70, $solsutunpic);?>
<div style='background: url(<?php echo $solsutunpic ?>) no-repeat; background-size: <?php echo $anwidth ?> <?php echo $anheight ?>; width: 70px; height: 70px; display:inline-block; border-radius: 3px; margin-right:5px;'></div>
A: You have a typo in function imgw($divsize, $imgw)
list($width, $height) = getimagesize($imgw);
right code
list($width, $height) = getimagesize($imgurl);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24227548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display the name of the day 2 days ahead of current day currently I'm doing a calender/scheduler. How do i display the name of the day that is 2 days ahead of the current day.(eg. today is wednesday so i'm suppose to display friday) Currently what i did was this.
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[d.getDay()];
A: Demo FIDDLE
Jquery
var d=new Date();
d.setDate(d.getDate()+2);
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
alert(weekday[d.getDay()]);
A: Simply add +2 because getDay() returns the day.
var n = weekday[d.getDay()+2];
Here is the example Fiddle
A: In the following sample +d gives the same result as d.getTime() :
// 3600000ms (=1h) x 48 = 2 days
var n = weekday[new Date(+d + 3600000 * 48).getDay()]
I also really like ling.s's approach, but it needs a little fix :
// friday.getDay() -> 5
// weekday[5 + 2] -> undefined
// weekday[(5 + 2) % 7] -> "Sunday"
var n = weekday[(d.getDay() + 2) % 7];
Here is one way to display it :
<span id="twoDaysLater"></span>
var weekday = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
var now = new Date();
var twoDaysLater = new Date(+now + 3600000 * 48);
var dayName = weekday[twoDaysLater.getDay()];
jQuery(function ($) {
// DOM is now ready
$('#twoDaysLater').text(dayName);
});
Here is a demo : http://jsfiddle.net/wared/346L8/.
Based on ling.s's solution : http://jsfiddle.net/wared/346L8/2/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21423687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to send messages from web-service to Android clients? I have a PHP web-service, and Android client. I need to make ability to send messages from service for my Android client. How can I make this mechanism?
A: Unless you have implemented a push mechanism, or using an external one, such as Google C2DM, which is available for Android (I have not tested it myself, last time I checked it, it was in a beta state), the only way left is use a polling mechanism (ask every so often the web service).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8592005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .htaccess Redirect Rewrite Rule I'm struggling with some redirects on the redesign of a website.
The old one got several urls like this:
http://www.example.com/sitegroup/pages/GA/GA_Be.shtml
And I want to redirect this to:
http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenforum-ideengarten
I tried it with the following rewriterule:
RewriteRule ^/?pagesGA/GA_Be.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenforum-ideengarten$1 [R=301,L,NE]
But I just can't get it working.. I'm really new to .htaccess rewriterules.
Also some of the old pages got links like this:
http://www.example.com/sitegroup/pages/GA/GA_Be.shtml?navid=15
But the ?navid=15 isn't doing something(just highlighting the menulink) so I thought just redirecting the GA_BE.shtml should be enough. Am I correct?
Here is the complete .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitegroup/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sitegroup/index.php [L]
</IfModule>
# END WordPress
RewriteRule ^/?pagesGA/GA_Be.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenforum-ideengarten$1 [R=301,L,NE]
Thanks in advance!
A: You should put your RewriteRule before Wordpress Dispatcher:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitegroup/
RewriteRule ^pages/GA/GA_Be\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenforum-ideengarten [R=301,L,NE]
RewriteRule ^pages/GA/GA_Bg\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenplanung-landscββhaftsplanung [R=301,L,NE]
RewriteRule ^pages/GA/GA_En\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#erdsondenbohrung-erdββwaerme [R=301,L,NE]
</IfModule>
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitegroup/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sitegroup/index.php [L]
</IfModule>
# END WordPress
Otherwise the request will first be handled by the Dispatcher and never reach your rule.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35623903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP casting float to int returns different value When I'm executing the following code in PHP (v5.5.9) something unexpected happens:
$valueAsCents = 54780 / 100 * 100;
var_dump($valueAsCents);
var_dump((int) $valueAsCents);
This returns
float 54780
int 54779
So apparently the float value with no decimals, is not equal to the int value. Any ideas of what's going on here?
A: When you divide $valueAsCents = 54780 / 100 then it becomes a float which is not always accurate in digital form because of the way they are stored. In my tests I got
547.7999999999999545252649113535881042480468750000
When multiplied by 100 this is would be
54779.9999999999927240423858165740966796870000
When PHP casts to int, it always rounds down.
When converting from float to integer, the number will be rounded towards zero.
This is why the int value is 54779
Additionally, the PHP manual for float type also includes a hint that floating point numbers may not do what you expect.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32589643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to open a file in iWork in the iPad From what I understand, UIApplication -openFile can open files externally, the application depending on the URL scheme. Say I have a pages (or word maybe?) document, and I want to open it in pages from my app. Does anyone know the URL scheme for me to do that? Is there a list anywhere? (Keynote, and Numbers would also be useful).
A: It doesn't work that way because you cannot transmit the file via a URL and Pages cannot access a file that is stored in your app's sandbox.
If you want to give the user the option to open a file in Pages in your UI, UIDocumentInteractionController is the way to do that. It presents a UI where the user can preview the file and select to open it in any application that supports the file type.
AFAIK it is not possible with the SDK to do this completely programmatically, i.e. without user interaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3153068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Member access call does not compile but static call does So today I faced interesting problem while trying to build our company solution and I wanted to ask you guys do you know why is this happening. I've been told that it might be from my machine/visual studio because other people did not have same problem.
So we have a method in project A:
private static string RpcRoutingKeyNamingConvention(Type messageType, ITypeNameSerializer typeNameSerializer)
{
string queueName = typeNameSerializer.Serialize(messageType);
return messageType.GetAttribute<GlobalRPCRequest>() != null || AvailabilityZone == null
? queueName
: queueName + "_" + AvailabilityZone;
}
where GetAttribute<GlobalRPCRequest>() is defined in public static class ReflectionHelpers
public static TAttribute GetAttribute<TAttribute>(this Type type) where TAttribute : Attribute;
then we have project B which have method:
public static string GetAttribute(this XElement node, string name)
{
var xa = node.Attribute(name);
return xa != null ? xa.Value : "";
}
I have to point out that we have reference to project B in project A.
Now what happens is that when I try to build I get compile error:
Error 966 The type 'System.Xml.Linq.XElement' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. D:\Repositories\website\website\submodules\core\src\A\Extensions\Extensions.cs 37 13 A
Whats happening is that compiler thinks that I am actually using GetAttribute method from project B(in my opinion!). Why this is happening? Since when I try to navigate to GetAttribute VS leads me to the right method (the one that is in ReflectionHelpers).
Could it be because of the reflection? NOTE: I fixed this issue by calling the method statically or adding reference to System.Xml.Linq in my project A, but I am curious of the strange behavior of VS/syntax-checking feature.
A: It's a guess, but I think your function:
private static string RpcRoutingKeyNamingConvention(Type messageType, ITypeNameSerializer typeNameSerializer) does not match your helper method signature because you try returning a string:
public static TAttribute GetAttribute<TAttribute>(this Type type) where TAttribute : Attribute; which expects a TAttribute return type.
Maybe, you can try modifiying your function RpcRoutingKeyNamingConvention to return GlobalRPCRequest and check if the compiler continues to go crazy.
A: Visual Studio gets confused all the times! I tried to reproduce the scenario in my VS 2015 (.NET 4.6) and it compiles just fine. I didn't have to add reference to System.Xml.Linq in my Project A.
My guess is that it might be a cache issue. You might want to try this:
*
*Remove reference to Project B
*Clean then rebuild both solutions
*Add the reference back
*Rebuild and voila!! Well.. hopefully
Hope it helps, let me know :)
A: I guess that's going on:
- B has reference to System.Xml.Linq
- B is built without a problem.
- You are referencing B in A
- A hasn't got a reference to System.Xml.Linq
- A seem to consume the function defined in B
- When you try to build project A, it produces that error
Am I right?
If that's the case, it is totally normal. Because a project which consumes a reference (A) must have a reference to what is referenced (System.Xml.Linq) by what it references (B).
Think like this: When you try to add a nuget package to your project if it has a dependency, nuget will install it too. Why? Because of this situation.
This is completely normal if I understand your answer correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36576898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Are there any native (Microsoft) API for Windows Explorer FTP (under Windows XP) for access login credentials? REWORK FOR REOPEN:
How can I have access to Windows Explorer FTP programmatically via command line or PowerShell or VBScript? THNX
ORIGINAL QUESTION:
I have been using Windows Explorer as an FTP.
I accidently clicked Save Password when logging in meaning that it automatically logins me into that account when I connect to that specific server.
How can I remove those saved credentials?
Cheers
A: Open User Accounts by clicking the Start button , clicking Control Panel, clicking User Accounts and Family Safety (or clicking User Accounts, if you are connected to a network domain), and then click User Accounts.
In the left pane, click References.
Click the password that you want to remove, and then click Remove.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11133307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to rename the files of different format from the same folder but different subfolder using python I have one scenario where i have to rename the files in the folder. Please find the scenario,
Example :
Elements(Main Folder)<br/>
2(subfolder-1) <br/>
sample_2_description.txt(filename1)<br/>
sample_2_video.avi(filename2)<br/>
3(subfolder2)
sample_3_tag.jpg(filename1)<br/>
sample_3_analysis.GIF(filename2)<br/>
sample_3_word.docx(filename3)<br/>
I want to modify the names of the files as,
Elements(Main Folder)<br/>
2(subfolder1)<br/>
description.txt(filename1)<br/>
video.avi(filename2)<br/>
3(subfolder2)
tag.jpg(filename1)<br/>
analysis.GIF(filename2)<br/>
word.docx(filename3)<br/>
Could anyone guide on how to write the code?
A: Recursive directory traversal to rename a file can be based on this answer. All we are required to do is to replace the file name instead of the extension in the accepted answer.
Here is one way - split the file name by _ and use the last index of the split list as the new name
import os
import sys
directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
os.rename(filePath, newFilePath) #rename your file
Hope this helps.
A: check below code example for the first filename1, replace path with the actual path of the file:
import os
os.rename(r'path\\sample_2_description.txt',r'path\\description.txt')
print("File Renamed!")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60202594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jenkins not excluding certain folders in excluded regions I have setup a CI Workflow in Jenkins to build project from bitbucket server.
I followed this Excluded Regions in Jenkins with Git
I made configuration such that ,when ever any changes are pushed into the repository, Jenkins will trigger a build.
I felt Repository is having too many checkins and each project is having separate workflows in Jenkins. So I used the "Polling ignores commits in certain places" option
But it seems not working.
I think this may be a bug as well.
Please see screenshot attached.
Scenario
I have 3 projects named Project1,Project2 and Project3
I want to look only changes in Project1 and then build.
For that i gave "Project1/.*" in the Included Regions. But even when changes are done to Project2 / Project 3, Jenkins triggers a build.
Doubt:
The Repository structure is as below
Project : TestForJenkins
Repository : JenkinsRepo
Project1,Project2,Project3,Packages,.gitignore
Since Project1 is at toplevel in repository, please let me know if i am giving wrong lookup path by providing "Project1/.*" in included region section.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41670545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SOAP v_2 is not working getting 500 internal server error When trying to login using soap v2 it giving 500 internal server error in magento.i checked the server error log file it is givving Access Denied here are my codes.
this is the error on log file
PHP Fatal error: Uncaught SoapFault exception: [2] Access denied. in /home/admin/web/example.com/public_html/apitest.php:4\nStack trace:\n#0 /home/admin/web/example.com/public_html/apitest.php(4): SoapClient->__call('login', Array)\n#1 /home/admin/web/example.com/public_html/apitest.php(4): SoapClient->login('skulabs', 'api12345')\n#2 {main}\n thrown in /home/admin/web/example.com/public_html/apitest.php on line 4
These are my codes
$proxy = new SoapClient('http://example.com/api/v2_soap/?wsdl'); // TODO : change url
print_r($proxy);
$sessionId = $proxy->login('skulabs', 'api12345'); // TODO : change login and pwd if necessary
$result = $proxy->catalogCategoryTree($sessionId);
var_dump($result);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43044369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Partial View not showing updated model values. Always shows existing values Actually i tried to update the partial view content whenever i do search. So i use ajax call to achieve this. So, the values from the controller to partial view model is correct(new data), but its not binding to the view (shows existing data).
Main View
<div class="tab-pane active" id="partialviewpage">
@{
Html.RenderPartial("_Details", Model);
}
</div>
Partial View (_Details)
foreach (var item in Model.AllAds)
{
//div contents
}
Ajax Call
var text = 'test';
$.ajax({
url: '@Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Category Controller
public ActionResult Subcategory(string item)
{
//Logic calling Api content goes here
var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JssSearch = new JavaScriptSerializer();
List<Result> Jsonresult = (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
var Model= new ModelName();
{
Model.AllAds = new List<Result>();
Model.AllAds = Jsonresult;
}
return PartialView("_Details", Model);
}
So, What's wrong with my code and how can i modify the code to get the new model values. Any help appreciated. Thanks in advance.
A: I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
var text = 'test';
$.ajax({
url: '@Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48515830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to read the cursor more than once I am working on Oracle stored procedure and need inputs on the below use case.
*
*Stored procedure will fetch the data in the cursor after some calculations.
*The cursor data will be returned to front end.
Now I have a requirement to add cursor data in another table and send to front end.
As per my understanding, once we open and read cursor to store in another table, we can't send the same cursor to front end. We will have to fetch data from source table again and send to front end.
This impacts the performance.
Any ideas on achieving this without fetching twice?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25751905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: on hover one div, assign animation class on another div stack!
I have an animation that is assigned to the class .slide
I have on hover on a div, when I hover over the div I want the animation class be assigned to another div. Using CSS animations.
I'd appreciate the help and thanks!
Code:
http://codepen.io/iheartkode/pen/wWMQmG?editors=0110
share-container {
position: relative;
width: 150px;
height: 75px;
background: #FF5722;
border-radius: 10px;
cursor: pointer;
&:hover {
// assign animation class to the share-icons class
}
p {
text-align: center;
color: white;
}
}
.share-icons {
position: absolute;
z-index: -2;
top: 15px;
left: 4px;
margin: 0 auto;
width: 120px;
height: auto;
padding: 10px;
background: coral;
text-align: center;
color: white;
font-size: 2em;
cursor: pointer;
}
.slide {
animation: slide 2s linear;
@keyframes slide {
from {
transform: translateY(0px);
}
to {
transform: translateY(100px);
}
}
}
A: Edited after your clarification:
Change this in your HTML:
<div class="share-icons slide">
And this in your SCSS:
&:hover .slide {
// assign animation class to the share-icons class
animation: slide 2s linear;
@keyframes slide {
from {
transform: translateY(0px);
}
to {
transform: translateY(100px);
}
}
}
And then adjust the animation as needed.
And here's a fork in action:
http://codepen.io/denmch/pen/WxrLQZ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37758174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to get SSL certificate info with CURL in PHP? I would like to be able to read the SSL certificate information with CURL.
From the Linux console I get this response header:
GET https://www.google.com/ -ed
Cache-Control: private, max-age=0
Connection: close
Date: Sun, 20 Jun 2010 21:34:12 GMT
Server: gws
Content-Type: text/html; charset=ISO-8859-1
Expires: -1
Client-Date: Sun, 20 Jun 2010 21:34:18 GMT
Client-Peer: 66.102.13.106:443
Client-Response-Num: 1
Client-SSL-Cert-Issuer: /C=ZA/O=Thawte Consulting (Pty) Ltd./CN=Thawte SGC CA
Client-SSL-Cert-Subject: /C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
Client-SSL-Cipher: RC4-SHA
Client-SSL-Warning: Peer certificate not verified
Set-Cookie: PREF=ID=4d56960f6e3ad831:TM=1277069652:LM=1277069652:S=GF-w8Yc-_61NBzzJ; expires=Tue, 19-Jun-2012 21:34:12 GMT; path=/; domain=.google.com
Title: Google
X-XSS-Protection: 1; mode=block
But with CURL the header is much shorter:
HTTP/1.1 200 OK
Date: Sun, 20 Jun 2010 21:39:07 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=2d4fb1c933eebd09:TM=1277069947:LM=1277069947:S=6_TgGKzD0rM4IWms; expires=Tue, 19-Jun-2012 21:39:07 GMT; path=/; domain=.google.com
Server: gws
X-XSS-Protection: 1; mode=block
Transfer-Encoding: chunked
Is there any possibility to get these information, the full header with CURL or with some other PHP function?
A: This code snippet isn't using curl specifically, but it retrieves and prints the remote certificate text (can be manipulated to return whatever detail you want using the various openssl_ functions)
$g = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));
$r = fopen("https://somesite/my/path/", "rb", false, $g);
$cont = stream_context_get_params($r);
openssl_x509_export($cont["options"]["ssl"]["peer_certificate"],$cert);
print $cert;
outputs:
-----BEGIN CERTIFICATE-----
...certificate content...
-----END CERTIFICATE-----
A: You will get the certificate as a resource using stream_context_get_params. Plug that resource into $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); to get more certificate information.
$url = "http://www.google.com";
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
print_r($certinfo);
Example result
Array
(
[name] => /C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
[subject] => Array
(
[C] => US
[ST] => California
[L] => Mountain View
[O] => Google Inc
[CN] => www.google.com
)
[hash] => dcdd9741
[issuer] => Array
(
[C] => US
[O] => Google Inc
[CN] => Google Internet Authority G2
)
[version] => 2
[serialNumber] => 3007864570594926146
[validFrom] => 150408141631Z
[validTo] => 150707000000Z
[validFrom_time_t] => 1428498991
[validTo_time_t] => 1436223600
[purposes] => Array
(
[1] => Array
(
[0] => 1
[1] =>
[2] => sslclient
)
[2] => Array
(
[0] => 1
[1] =>
[2] => sslserver
)
[3] => Array
(
[0] => 1
[1] =>
[2] => nssslserver
)
[4] => Array
(
[0] =>
[1] =>
[2] => smimesign
)
[5] => Array
(
[0] =>
[1] =>
[2] => smimeencrypt
)
[6] => Array
(
[0] => 1
[1] =>
[2] => crlsign
)
[7] => Array
(
[0] => 1
[1] => 1
[2] => any
)
[8] => Array
(
[0] => 1
[1] =>
[2] => ocsphelper
)
)
[extensions] => Array
(
[extendedKeyUsage] => TLS Web Server Authentication, TLS Web Client Authentication
[subjectAltName] => DNS:www.google.com
[authorityInfoAccess] => CA Issuers - URI:http://pki.google.com/GIAG2.crt
OCSP - URI:http://clients1.google.com/ocsp
[subjectKeyIdentifier] => FD:1B:28:50:FD:58:F2:8C:12:26:D7:80:E4:94:E7:CD:BA:A2:6A:45
[basicConstraints] => CA:FALSE
[authorityKeyIdentifier] => keyid:4A:DD:06:16:1B:BC:F6:68:B5:76:F5:81:B6:BB:62:1A:BA:5A:81:2F
[certificatePolicies] => Policy: 1.3.6.1.4.1.11129.2.5.1
[crlDistributionPoints] => URI:http://pki.google.com/GIAG2.crl
)
)
A: No. EDIT: A CURLINFO_CERTINFO option has been added to PHP 5.3.2. See http://bugs.php.net/49253
Apparently, that information is being given to you by your proxy in the response headers. If you want to rely on that, you can use curl's CURLOPT_HEADER option to trueto include the headers in the output.
However, to retrieve the certificate without relying on some proxy, you must do
<?php
$g = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));
$r = fopen("https://www.google.com/", "rb", false, $g);
$cont = stream_context_get_params($r);
var_dump($cont["options"]["ssl"]["peer_certificate"]);
You can manipulate the value of $cont["options"]["ssl"]["peer_certificate"] with the OpenSSL extension.
EDIT: This option is better since it doesn't actually make the HTTP request and does not require allow_url_fopen:
<?php
$g = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));
$r = stream_socket_client("ssl://www.google.com:443", $errno, $errstr, 30,
STREAM_CLIENT_CONNECT, $g);
$cont = stream_context_get_params($r);
var_dump($cont["options"]["ssl"]["peer_certificate"]);
A: To do this in php and curl:
<?php
if($fp = tmpfile())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.digicert.com/");
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_CERTINFO, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($ch);
curl_errno($ch)==0 or die("Error:".curl_errno($ch)." ".curl_error($ch));
fseek($fp, 0);//rewind
$str='';
while(strlen($str.=fread($fp,8192))==8192);
echo $str;
fclose($fp);
}
?>
A: This could done the trick
[mulhasan@sshgateway-01 ~]$ curl --insecure -v https://yourdomain.com 2>&1 | awk 'BEGIN { cert=0 } /^\* SSL connection/ { cert=1 } /^\*/ { if (cert) print }'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3081042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Floating Point Precision using REST I'm pulling timeseries data in from a MS-SQL database using REST. I've found that the floating point precision goes down from a value like 0.00166667 to 0.002 when I'm using REST to retrieve data, but using the DB designer's own tools, the precision is maintained.
Is this a limitation of the REST method, or is it something specific to the implementation?
Just to clarify -- my work is using a proprietary database that uses MS-SQL as its backbone. It's not open-source so I can't poke around and see how requests are being handled.
A SOAP method is offered, which I'm going to try to implement to compare, but I'm more concerned whether or not this is a REST problem or not.
A: Representational State Transfer is just a general style of client-server architecture. It doesn't specify anything nearly so detailed such the appropriate handling of floating point values. The only constraints it imposes are things like the communication should be "stateless". So the concepts of REST exist on a higher level of abstraction and the issue you are seeing must be something specific to the implementation of the service that is providing the floating point values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15574960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xamarin.Forms: deployment issue after Visual Studio upgrade After upgrading Visual Studio Professional 2019 to version 16.9.2, when I try to deploy on Android Emulator
api 28 (9.0), I get following error:
Error XA0130: Sorry. Fast deployment is only supported on devices running Android 5.0 (API level 21) or higher. Please disable fast deployment in the Visual Studio project property pages or edit the project file in a text editor and set the 'EmbedAssembliesIntoApk' MSBuild property to 'true'.
Before the upgrade, everything worked fine. This is really frustating!
A: To correct this problem I had to
*
*uninstall app on Android phone (important step)
*Unload Android Project from solution explorer
*This brings up the project file code now search code for
<EmbedAssembliesIntoApk>false</EmbedAssembliesIntoApk>
*Change false to true save
*reload project problem solved.
Note leave fast deploy checked.
A: Go to >> Solution Properties>> Android Options>> Uncheck "Use Fast Deployment(debug mode only)"
A: I had the same issue recently after adding images to my project found out that I had upper case letters as a name SomePicture.png renaming all images to lower case solved it.
A: @AlwinBrabu, I think you meant "Project Properties" -> Android Options -> Uncheck Fast Deployment(debug mode only).
This worked for me, although this is a workaround. I do not consider it a solution.
A: To solve this, I had to right-click on the Android project in the Solution Explorer, then in Options -> Android Build uncheck the Fast Assembly Deployment option.
Then deploy the project on the Android emulator.
But after deploying it once, I went back to the settings and checked (i.e. ticked) the Fast Assembly Deployment option, and subsequent deploys worked fine.
I'm running Visual Studio for Mac 2022 version 17.0.1 (build 72).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66799236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to destroy two different sessions in the same php script? In my session start script, I choose the session_name and then do a session_start.
$session_name = rand(0,1) ? 'first' : 'second';
session_name($session_name);
session_start();
The above code runs on every page load. After a few page loads, there will probably be sessions for both session_name 'first' and session_name 'second'.
This is my code which is in my logout script to try and destroy both these sessions:
session_start();
session_name("first");
session_unset();
session_destroy();
session_write_close();
session_start();
session_name("second");
session_unset();
session_destroy();
session_write_close();
The script above destroys first but not second. If I run the log out script a second time it then destroys the second session, as the first one is already deleted.
How do I destroy sessions for both session names in the same script?
A: TRY IT
<?php
session_name("first");
session_start();
echo session_status();
session_destroy();
echo session_status();
session_name("second");
session_start();
echo session_status();
session_destroy();
echo session_status();
?>
I've tested it on xampp and it returns values 2121 meaning session is active, none exist, the session is active, none exist.
I've placed session_name() before session_start() because setting the name as you did doesn't take effect after a session has already been started. I've googled it and it has to do something with the php.ini file where session.auto_start is set to "true".
The explanation and a debate on this topic are found here: http://php.net/manual/en/function.session-name.php - check comments.
EDITED:
After reviewing your edit again, you basically don't create two sessions but only one and it starts with a random name "first" or "second". You can destroy a session but the cookie will remain. I've tested your code on xampp and it does exactly that. First, the PHP starts one session and stores a cookie with a time value of "session", after reloading the page it will load one of two options again but this time it will change the existing cookie time to "N/A". You should search for a solution to clear your cookies on your domain after page loads like so:
<?php
$session_name = rand(0,1) ? 'first' : 'second';
session_name($session_name);
session_start();
deleteCookies($session_name);
function deleteCookies($skip_this_one) {
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
if ($name == $skip_this_one) {
//skip
}else{
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
}
//do something inside your session
//when done, stop the session the way you want
session_destroy();
}
?>
This will delete all previous cookies and keep the current session open.
This solution is re-written from here: how to delete all cookies of my website in php
Hope this helps :)
A: Please try below code
<?php unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34294333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How Can I Make Custom Tabs Using Angular Materials Tabs? I want to use Angular Material library and build my own library with some custom designs. But facing some problems while splitting the material components. I think the problem is with shadow DOM. Here is the code that i want to achieve.
Code
custom-tabs-group.html -parent
<div class="custom-tabs">
<mat-tab-group disableRipple>
<ng-content></ng-content>
</mat-tab-group>
</div>
custom-tabs.html -child
<custom-tabs-group [tabContent]="tabContent">
<mat-tab *ngFor="let tab of tabContent" label="{{tab.title}}">{{tab.content}} </mat-tab>
</custom-tabs-group>
is it even possible? Please let me know
A: the code you shared got the ng-content usage backwards... the <custom-tabs-group> will be at the parent level and <ng-content> at the child level.
I tried 2 approaches:
*
*strategy #1: pass the content to the custom child inside the <mat-tab>... this worked
*strategy #2: pass the content to the custom child where <mat-tab> is inside the child... this didn't work
you can check the demo here
A: Actually i figured it out with some hack i don't know if its a good approch or not
custom-tabs.component.html
<div class="custom-tabs">
<mat-tab-group disableRipple>
<mat-tab *ngFor="let tab of tabsContentList" label="{{tab.label}}">
<div [innerHTML]="tab.htmlContent"></div>
</mat-tab>
</mat-tab-group>
</div>
custom-tabs-component.ts
import { DomSanitizer } from '@angular/platform-browser';
import { Component, OnInit, ViewEncapsulation, AfterContentInit, ContentChildren, Input, ViewChild, ElementRef, QueryList } from '@angular/core';
@Component({
selector: 'il-tabs-content',
template: `
<div #content>
<ng-content></ng-content>
</div>
`
,
})
export class TabsContentComponent implements OnInit {
@Input() label: String;
@ViewChild('content') set content(content: ElementRef) {
console.log("block three", content)
this.htmlContent = content;
if (this.htmlContent) {
this.htmlContent = this.htmlContent.nativeElement.innerHTML;
}
}
htmlContent: any;
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'il-tabs-group',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css'],
encapsulation: ViewEncapsulation.None
})
export class TabsGroupComponent implements OnInit, AfterContentInit {
@ContentChildren(TabsContentComponent) tabsContentList: QueryList<TabsContentComponent>;
constructor(public sanitizer: DomSanitizer) { }
ngOnInit() {
}
ngAfterContentInit() {
this.tabsContentList.forEach((tabInstance) => {
var sanEle = this.sanitizer.bypassSecurityTrustHtml(tabInstance.htmlContent)
tabInstance.htmlContent = sanEle;
return tabInstance
})
}
}
usage
<il-tabs-group>
<il-tabs-content label="hello-1">
<h1>hello-1 content</h1>
</il-tabs-content>
<il-tabs-content label="hello-2">
<h1>hello-2 content</h1>
</il-tabs-content>
<il-tabs-content label="hello-3">
<h1>hello-3 content</h1>
<h2>extra content</h2>
</il-tabs-content>
</il-tabs-group>
i defined two components 'il-tabs-content' and 'li-tabs-group'. with this now i can use my own custom tabs build over angular material tabing with dynamic tabs. Anyone with better approch are welcome to share their ideas. thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56069092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: assigning strtof value into 2D array in C I'm trying to parse a CSV file into a 2D array in C. I want to make a matrix wit the structure :
typedef struct {
int row;
int col;
float **arr;
int numElements;
} Matrix;
The function I'm using takes in a dynamically allocated 2D array of floats, and is returned. I'm reading the values in using fgets, tokenizing each value between commas using strtok and then converting the string returned using strtof.
First, I made the 2D arrays dynamically and then pass them to the function to be filled in with values,
RMatrix->arr = make2DArray(RMatrix->row, RMatrix->col);
VMatrix->arr = make2DArray(VMatrix->row, VMatrix->col);
printf("RMatrix->arr : %p \n", RMatrix->arr);
printf("VMatrix->arr : %p \n", VMatrix->arr);
parseCSV(fpRMatrix, RMatrix->arr, RMatrix->row, RMatrix->col, &(RMatrix->numElements), INPUT_LENGTH);
printf("RMatrix parsed\n");
parseCSV(fpVMatrix, VMatrix->arr, VMatrix->row, VMatrix->col, &(VMatrix->numElements), INPUT_LENGTH);
printf("VMatrix parsed\n");
Below are the functions :
void parseCSV(FILE *fp, float **output, int row, int col, int *numElements ,int inputLength)
{
char *buffer;
int rowArr = 0;
printf("Output : %p \n", output);
buffer = (char*) malloc(inputLength * sizeof(char));
while(fgets(buffer, inputLength, fp)) {
char *p =strtok(buffer,",");
int colArr = 0;
float check = 0;
while(p)
{
printf("p now : %s \n", p);
check = strtof(p, (char**) NULL);
printf("check now : %f \n", check);
output[rowArr][colArr] = strtof(p, (char**) NULL);
*numElements += 1;
colArr++;
p = strtok('\0',",");
printf("output[%d][%d] : %f ", rowArr, colArr, output[rowArr][colArr]);
}
printf("\n");
rowArr++;
}
printf("numElements in the end : %d\n", *numElements);
free(buffer);
}
float **make2DArray(int row, int col)
{
float** arr;
float* temp;
arr = (float**)malloc(row * sizeof(float*));
temp = (float*)malloc(row * col * sizeof(float));
for (int i = 0; i < row; i++) {
arr[i] = temp + (i * row);
}
return arr;
}
The output :
Name : RMatrix
NumElements : 0
Rows : 2
Cols : 4
Name : VMatrix
NumElements : 0
Rows : 2
Cols : 4
RMatrix->arr : 0x11684d0
VMatrix->arr : 0x1168520
Output : 0x11684d0
p now : 1
check now : 1.000000
output[0][1] : 0.000000 p now : 2
check now : 2.000000
output[0][2] : 0.000000 p now : 3
check now : 3.000000
output[0][3] : 0.000000 p now : 4
check now : 4.000000
output[0][4] : 0.000000
p now : 5
check now : 5.000000
output[1][1] : 4.000000 p now : 6
check now : 6.000000
output[1][2] : 0.000000 p now : 7
check now : 7.000000
output[1][3] : 0.000000 p now : 8
check now : 8.000000
output[1][4] : 0.000000
numElements in the end : 8
RMatrix parsed
Output : 0x1168520
p now : 1
check now : 1.000000
output[0][1] : 0.000000 p now : 2
check now : 2.000000
output[0][2] : 0.000000 p now : 3
check now : 3.000000
output[0][3] : 0.000000 p now : 4
check now : 4.000000
output[0][4] : 0.000000
p now : 5
check now : 5.000000
output[1][1] : 4.000000 p now : 6
check now : 6.000000
output[1][2] : 0.000000 p now : 7
check now : 7.000000
output[1][3] : 0.000000 p now : 8
check now : 8.000000
output[1][4] : 0.000000
numElements in the end : 8
VMatrix parsed
As you can see, the strtof call succeeded (reflected in p and check variable) but not the assignment into the array.
I've only been using C for a month and I'm fascinated by it. However, it's obvious I need to learn more. I really appreciate your help :)
A: this
arr[i] = temp + (i * row);
should be
arr[i] = temp + (i * col);
since i = [0,row-1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15465016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it good practice to use the xor operator for boolean checks? I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
if (boolean1 ^ boolean2)
{
//do it
}
than
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.
I'm curious as to the best practices regarding the usage of the ^ operator.
A: if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
IMHO this code could be simplified:
if(boolean1 != boolean2)
{
//do it
}
A: With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:
flags = flags ^ MASK;
This article by Vipan Singla explains the usage case more in detail.
If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.
A: You can simply use != instead.
A: I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
A: I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.
A: I think it'd be okay if you commented it, e.g. // ^ == XOR.
A: You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
return A ^ B;
}
But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;
Here's a Stackoverflow question related to XOR swapping.
A: I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
//do it
}
Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
return boolean1 ^ boolean2;
}
Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!
A: != is OK to compare two variables. It doesn't work, though, with multiple comparisons.
A: str.contains("!=") ^ str.startsWith("not(")
looks better for me than
str.contains("!=") != str.startsWith("not(")
A: If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
A: As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.
My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/160697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "159"
} |
Q: JavaFX - GridPane Background Image I've been searching around the internet, and I still haven't found a solution.
All I want to do is: Set an image to my GridPane in a POPUP-window, that I've made, when a button is clicked.
Some programmers refers to:
grid.setStyle("-fx-background-image: url('URL')");
Which were my suggestion as well, but it does not seem to work.
I've also tried to set
Image image = new Image();
and then set an ImageView, but with no luck!
Hope someone in here has a quick fix for this answer.
A: //root.setStyle("-fx-background-image: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxsasGQIwQNwjek3F1nSwlfx60g6XpOggnxw5dyQrtCL_0x8IW')");
This worked out. But not all url's it likes.
A: In case you are using FXML, you have to add stylesheets to your GridPane in the Controller class. For example, gridPane is the reference variable of your GridPane and app.css is a name of your stylesheets:
gridPane.getStylesheets().addAll(getClass().getResource("/css/app.css").toExternalForm())
Then write something like this in your stylesheets:
#gridPane { -fx-background-image:url("file:C:/path/to/your/project/folder/src/main/resources/image.jpg"); }
In addition, you can add stylesheets app.css to GridPane in the SceneBuilder.
The aforementioned procedure worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33973830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.